<!-- Generated from the concise canonical handbook pages by `pnpm docs:pages`. Do not edit this file directly. -->

# The Effect 4 Handbook — Essentials

**Before you write code:** these Effect 3 names do not exist in Effect 4 and are the most common cause of broken generated code ([full list](./troubleshooting/anti-patterns.md#effect-3-names-that-do-not-exist-in-effect-4)).

- `Effect.catchAll` → `Effect.catch`
- `Effect.catchAllCause` → `Effect.catchCause`
- `Effect.catchSome` → `Effect.catchIf` or `Effect.catchTag`
- `Effect.either` → `Effect.result` (returns a `Result`)
- `Effect.tapErrorCause` → `Effect.tapCause`
- `Effect.zipLeft` / `Effect.zipRight` → `Effect.tap` / `Effect.andThen`
- `Context.Tag`, `Effect.Service` → `Context.Service`
- `Layer.scoped` → `Layer.effect` (it already handles a `Scope` requirement)
- `Schema.decodeUnknown` / `Schema.encodeUnknown` → `Schema.decodeUnknownEffect` / `Schema.encodeUnknownEffect` (or the `Sync`, `Result`, `Exit`, `Option`, and `Promise` variants)
- `Schema.decode(schema)` as a decoder → `Schema.decodeEffect(schema)`; in Effect 4 `Schema.decode` builds a transformation from getters
- `@effect/platform`, `@effect/rpc`, `@effect/sql`, `@effect/cli` → modules inside `effect`: `FileSystem` and `Path` from `"effect"`, HTTP from `"effect/http"`, and so on; host Layers from `@effect/platform-node`
- `NodeRuntime` from `"effect"` → `NodeRuntime` from `@effect/platform-node`

The essentials of every concise handbook page for `effect@4.1.4` (audited 2026-11-19), in reading order: what each page and section is for, its stability, and when to reach for it. Every heading links to the full section in that page's Markdown twin; fetch the twin for code, tables, edge cases, and the exact rules. Use [the complete concise handbook](./effect-4-handbook.md) only for an exhaustive review.

# Start Here

## [The Effect 4 Handbook — A Guided Tour of Effect v4](./index.md)

How to use the Effect 4 Handbook, its version contract, conventions, and official companion resources.

### [Orientation](./index.md#orientation)

This edition validates examples against published `effect@4.1.4` — not unreleased `main`. The source audit covered all 144 modules exported from the `effect` root barrel, all 23 public `effect/<area>` families (266 modules), the 35 public packages, their tests and examples, every change from 4.1.0 to 4.1.4, and every canonical Markdown page in this site. Examples are checked with pnpm, Node's native TypeScript execution, TypeScript 7.0.2 in strict mode, and Effect `@effect/tsgo` 0.70.0 diagnostics. Short fragments may declare application-specific boundaries.

Sections: [Version and validation scope](./index.md#version-and-validation-scope) · [Stability and support](./index.md#stability-and-support) · [Official upstream companions](./index.md#official-upstream-companions) · [The through-line: one type](./index.md#the-through-line-one-type) · [The house style (every example in this handbook uses it)](./index.md#the-house-style-every-example-in-this-handbook-uses-it) · [Coding conventions for agents](./index.md#coding-conventions-for-agents) · [The lay of the land](./index.md#the-lay-of-the-land) · [How to use this handbook](./index.md#how-to-use-this-handbook)

## [Getting Started](./foundations/getting-started.md)

Installing the Effect 4 release line, TypeScript and ESM settings, a first program, import forms, and editor tooling.

Everything else in this handbook assumes a project where Effect is installed, TypeScript is strict, and one entrypoint runs an Effect. This page gets you there and names the traps on the way: mismatched package versions, compiler settings that silently weaken the types, and packages that do not exist for Effect 4.

### [Install Effect 4](./foundations/getting-started.md#install-effect-4)

Effect 4 is the `latest` release on npm: a plain `pnpm add effect` installs it. Pin the exact version anyway, so that an upgrade is a deliberate, audited change rather than a side effect of a fresh install.

### [Runtime and compiler requirements](./foundations/getting-started.md#runtime-and-compiler-requirements)

The library's floor and this handbook's validation target are different things. The first column is what the audited release asks of you; the second is what every example here is compiled and run with.

### [A first complete program](./foundations/getting-started.md#a-first-complete-program)

One file, one runtime call. `NodeRuntime.runMain` is the process edge: it forks the program as the root fiber, interrupts it on `SIGINT` or `SIGTERM` so finalizers run, reports an unhandled failure through the logger, and sets the exit code (`0` on success, `130` when the program was only interrupted, non-zero on failure). The runtime itself keeps the process alive while fibers are pending, so `runMain` is about signals, exit codes, and error reporting rather than liveness.

### [Import forms](./foundations/getting-started.md#import-forms)

### [Stable and unstable modules](./foundations/getting-started.md#stable-and-unstable-modules)

Stability is a per-API contract declared with a JSDoc tag, not an import path; since `4.0.2` every module and directly importable export is tagged explicitly. The handbook summarizes it as a badge on every module section.

### [Effect diagnostics in the editor and in CI](./foundations/getting-started.md#effect-diagnostics-in-the-editor-and-in-ci)

The Effect language service ships as `@effect/tsgo`, built on the native TypeScript compiler, and needs `typescript` 7 installed beside it. It adds Effect-aware diagnostics and quick fixes: an Effect that was never yielded or assigned, a bare `yield` without `*`, implementation services leaking through a service method, a second copy of an Effect package, and APIs that do not exist in the installed version. `npx @effect/tsgo setup` adds the dependency and the `@effect/language-service` entry under `compilerOptions.plugins`; `effect-tsgo patch` (run it from a `prepare` script, as the Effect repository does) patches the local TypeScript install so `tsc` emits the same diagnostics; and `npx @effect/tsgo diagnostics --project tsconfig.json --strict` is a standalone CI check in which warnings fail the build. This handbook compiles every example under exactly that pair: strict `tsc` and strict Effect diagnostics, with one rule turned off: `unstableApiUsage` warns on every API tagged `@stability unstable`, including `effect/http`, `effect/sql`, `effect/rpc`, `effect/ai`, and the other unstable area families. A project that uses those modules sets `"diagnosticSeverity": { "unstableApiUsage": "off" }` in the plugin options (or downgrades it to a suggestion) rather than suppressing it line by line; a project that wants to be told when it strays outside the semver-covered surface leaves it on.

### [First-session route: a small approval worker](./foundations/getting-started.md#first-session-route-a-small-approval-worker)

After the first program, follow these five stops in order. Grow one small worker that processes raise proposals through a replaceable approval service; use an in-memory fake and a counted resource rather than a real payroll connection. The recipes are patterns to adapt, not successive files to paste together. These are self-check exercises, not automatically executed or graded lessons.

### [Where next](./foundations/getting-started.md#where-next)

# Runtime Fundamentals

## [Core Runtime & Execution](./foundations/core-runtime-execution.md)

Building and combining Effects: creation, gen and fn, error handling, concurrency, racing, interruption, adapters, and execution planning.

`Effect` is not a running program — it's a description. The runtime spins up **fibers** to execute descriptions, **scopes** bound resource lifetimes, and a finished computation returns an **Exit** carrying a full **Cause**. Build a value of type `Effect<A, E, R>` by composing combinators; nothing runs until you execute it. Running forks a root fiber that may fork children, await deferreds, race siblings, or open scopes. When it finishes it produces an `Exit<A, E>` — either `Success<A>` or `Failure` holding a `Cause<E>` recording everything that went wrong (typed errors, defects, interruptions).

### [Effect](./foundations/core-runtime-execution.md#effect)

`effect/Effect` — stable

`Effect<A, E, R>` is a lazy, immutable description of a computation that yields an `A`, may fail with typed `E`, and requires services `R`. Think of it as program-as-data: you assemble a recipe and the runtime executes it. That indirection enables typed errors, dependency injection, retries, interruption, and tracing as ordinary composition.

Sections: [1. Creating effects](./foundations/core-runtime-execution.md#1-creating-effects) · [2. Sequencing with gen & fn](./foundations/core-runtime-execution.md#2-sequencing-with-gen-fn) · [3. Error handling](./foundations/core-runtime-execution.md#3-error-handling) · [4. Concurrency](./foundations/core-runtime-execution.md#4-concurrency) · [5. Racing & timeouts](./foundations/core-runtime-execution.md#5-racing-timeouts) · [6. Interruption & resource safety](./foundations/core-runtime-execution.md#6-interruption-resource-safety) · [7. Sequential folds and context control](./foundations/core-runtime-execution.md#7-sequential-folds-and-context-control) · [8. Cancellable adapters for promises and callbacks](./foundations/core-runtime-execution.md#8-cancellable-adapters-for-promises-and-callbacks) · [9. Branching and looping](./foundations/core-runtime-execution.md#9-branching-and-looping) · [10. When cleanup can fail](./foundations/core-runtime-execution.md#10-when-cleanup-can-fail) · [11. Running effects at an owned edge](./foundations/core-runtime-execution.md#11-running-effects-at-an-owned-edge)

**Reach for it when** you want typed errors, dependency injection, structured concurrency, and interruption-safe resource handling as the default.

### [ExecutionPlan](./foundations/core-runtime-execution.md#executionplan)

`effect/ExecutionPlan` — unstable

An ordered failover policy for an `Effect` or `Stream`. Each step provides the services needed by the same computation and may add an attempt count, a retry `Schedule`, or a `while` predicate. `Effect.withExecutionPlan` reruns the computation under each step until it succeeds or the plan is exhausted; `Stream.withExecutionPlan` does the same for an entire stream execution.

**Reach for it when** one operation should retry or fail over across interchangeable service implementations — regional endpoints, model providers, replicas, or storage tiers — without putting fallback branching inside the operation itself.

### [Effectable](./foundations/core-runtime-execution.md#effectable)

`effect/Effectable` — stable

The low-level toolkit for making custom values behave like effects — so they can be `yield*`-ed inside `Effect.gen` and evaluated by the runtime. It exposes three entry points: `Effectable.Class<A, E, R>` (abstract base class), `Effectable.Mixin(Base)` (insert the Effect prototype into an *existing* class hierarchy), and `Effectable.Prototype` (class-free builder). With `Class` and `Mixin` you implement one abstract method, `asEffect()`, returning the `Effect` your value stands for. The runtime calls it **on the instance for each execution**, so it sees current receiver state and the services provided at that point. This explains why non-Effect types (e.g. a `Context.Service` key) are still yieldable.

**Reach for it when** building a library primitive or DSL whose values should be first-class citizens of `Effect.gen`.

## [Fibers, Scopes & Runtimes](./foundations/fibers-scopes-runtimes.md)

How Effects run: Exit and Cause, fibers and fiber handles, Scope, scheduler and clock, Deferred, Latch, Runtime, and ManagedRuntime.

What happens after you build an `Effect`: how it finishes (`Exit` and its full `Cause`), the fibers that run it and the handles that supervise them, the `Scope` that bounds every resource, the scheduler and clock underneath, the one-shot and gate primitives fibers coordinate with, and the runtimes that run Effects from non-Effect code. [Core Runtime & Execution](./foundations/core-runtime-execution.md) covers building and combining Effects; this page covers owning them while they run.

### [Exit](./foundations/fibers-scopes-runtimes.md#exit)

`effect/Exit` — stable

`Exit<A, E>` is the result of a finished computation: either `Success<A>` (holding the value) or `Failure<A, E>` (holding a `Cause<E>`). Returned by `runSyncExit`, `runPromiseExit`, `Fiber.await`, and finalizers. An `Exit` is itself an `Effect`, so you can `yield*` it to re-raise its result. Pattern-match with `Exit.match`, or guard with `isSuccess` / `isFailure`.

**Reach for it when** you've crossed out of the Effect world and need to inspect success-or-cause synchronously.

### [Cause](./foundations/fibers-scopes-runtimes.md#cause)

`effect/Cause` — stable

The complete, structured record of why an effect failed. A single failure can be several things simultaneously — a typed error, a finalizer that threw, and an interruption. `Cause` retains all of them. A `Cause` is a flat array of reasons. There are exactly three reason kinds: `Fail` (typed error), `Die` (unexpected defect), and `Interrupt` (fiber cancelled). An empty cause is an empty array.

Sections: [Recovering from a mixed Cause](./foundations/fibers-scopes-runtimes.md#recovering-from-a-mixed-cause)

**Reach for it when** you need to distinguish a typed error from a defect from an interruption, inspect every reason when outcomes combine, or render a full diagnostic with `Cause.pretty`.

### [Fiber](./foundations/fibers-scopes-runtimes.md#fiber)

`effect/Fiber` — stable

`Fiber<A, E>` is a lightweight green thread — a running or finished execution of an effect. You don't construct one directly; you get a handle from `Effect.forkChild` (and friends). A child fiber is bound to its parent's lifetime: when the parent ends, the child is interrupted — no leaks. `Fiber.await` gives you the `Exit` (never fails); `Fiber.join` propagates the result into the current effect (fails if the fiber failed); `Fiber.interrupt` cancels it and waits for cleanup.

Sections: [Choosing a fork by its owner](./foundations/fibers-scopes-runtimes.md#choosing-a-fork-by-its-owner) · [When a forked fiber starts](./foundations/fibers-scopes-runtimes.md#when-a-forked-fiber-starts) · [Requesting cancellation versus awaiting cleanup](./foundations/fibers-scopes-runtimes.md#requesting-cancellation-versus-awaiting-cleanup)

**Reach for it when** you need manual control over a background task — fork work, keep the handle, and await or interrupt on your own schedule. For fixed bundles of work, prefer `Effect.all`/`forEach` with `{ concurrency }`.

### [FiberHandle](./foundations/fibers-scopes-runtimes.md#fiberhandle)

`effect/FiberHandle` — stable

A scoped holder for *at most one* fiber. Setting a new fiber interrupts the previous one (unless `onlyIfMissing` is passed); closing the owning scope interrupts the current fiber automatically, and also waits for replaced fibers that are still running their interruption cleanup. "Latest wins." The structured-concurrency answer to the `let current; current?.cancel(); current = start()` pattern.

**Reach for it when** exactly one instance of a task should be alive at a time and re-triggering should cancel the old one.

### [FiberMap](./foundations/fibers-scopes-runtimes.md#fibermap)

`effect/FiberMap` — stable

A scoped map of fibers keyed by some value. Running work under a key replaces any existing fiber for that key (or skips with `onlyIfMissing`). Completed fibers remove themselves; closing the scope interrupts all remaining fibers, including replaced ones whose interruption cleanup is still running, and waits for them. `FiberHandle` generalized from one slot to many, with the same leak-proof guarantee.

**Reach for it when** you have a dynamic population of keyed background fibers and want them all interrupted cleanly when the parent scope closes.

### [FiberSet](./foundations/fibers-scopes-runtimes.md#fiberset)

`effect/FiberSet` — stable

A scoped, unkeyed bag of fibers. Added fibers remove themselves on completion; closing the scope interrupts whatever remains. `FiberSet.awaitEmpty` blocks until the set drains. The keyless sibling of `FiberMap` — use when spawning an unbounded stream of fire-and-forget tasks that need group supervision.

**Reach for it when** you spawn many independent throwaway fibers and want them tracked as a group — interrupted together on scope close, or awaited together with `awaitEmpty`.

### [Runtime](./foundations/fibers-scopes-runtimes.md#runtime)

`effect/Runtime` — stable

Process-lifecycle helpers: `makeRunMain` (used by platform packages to build `runMain`), `Teardown` / `defaultTeardown` (turn an `Exit` into a process exit code), error markers for custom exit codes, and the `InterruptExitCode` annotation for interruptions that end the program on purpose. Application code almost never imports this directly — use `NodeRuntime.runMain` / `BunRuntime.runMain`, which are built on `makeRunMain`. Touch it only to customize how completion maps to an exit code.

**Reach for it when** writing a platform adapter or needing bespoke exit-code logic for a process entry point. For ordinary apps, use `NodeRuntime.runMain`.

### [Scope](./foundations/fibers-scopes-runtimes.md#scope)

`effect/Scope` — stable

A lifetime boundary. A `Scope` collects finalizers; closing it runs them (sequentially or in parallel) with the `Exit` that ended the work. The machinery underneath `acquireRelease`, `Effect.scoped`, and every `Layer`. Most of the time you never name a scope — `Effect.scoped` opens one, runs your effect, and closes it, discharging the `Scope` requirement. Manipulate scopes directly only when a resource must outlive the expression that created it.

**Reach for it when** a resource must live longer than the expression that creates it, or when implementing a primitive that controls finalization order directly.

### [Scheduler](./foundations/fibers-scopes-runtimes.md#scheduler)

`effect/Scheduler` — stable

Decides *when* queued fiber work runs on the JavaScript thread, and when a long-running fiber should yield. The default is a `MixedScheduler` in `"async"` mode, installed as a `Context.Reference` so it can be swapped: it batches queued tasks by priority (FIFO within a priority) and dispatches each batch with `setImmediate`, or `setTimeout(0)` where `setImmediate` does not exist. It falls back to a Promise microtask when setting that timer throws — Cloudflare Workers forbid timers in global scope — so an effect run at module load can still yield. `new MixedScheduler("sync")` dispatches through microtasks. Effect's fibers are cooperative — they run in bursts and periodically yield to keep the event loop responsive. Two useful knobs: `Scheduler.MaxOpsBeforeYield` (operations before yielding, default 2048) and `PreventSchedulerYield` (disable yielding for controlled workloads).

**Reach for it when** tuning throughput-vs-fairness for a heavy workload, or needing deterministic task ordering in a test. Otherwise the default scheduler is correct.

### [Clock](./foundations/fibers-scopes-runtimes.md#clock)

`effect/Clock` — stable

The service that owns "what time is it" and "sleep." `Clock.currentTimeMillis` and `currentTimeNanos` read the time as effects; `Effect.sleep` goes through the clock too. Installed as a `Context.Reference` — always available and always replaceable. Time is a dependency, not a global: read it through the clock so tests can install a virtual one and fast-forward to any point without real waiting.

**Reach for it when** any logic depends on current time, durations, or delays — so you can drive it with a virtual clock under test.

### [Deferred](./foundations/fibers-scopes-runtimes.md#deferred)

`effect/Deferred` — stable

A one-shot, write-once coordination cell. A `Deferred<A, E>` starts empty, can be completed *exactly once* (with a success, failure, defect, or interruption), and lets any number of fibers `await` the result. Awaiting suspends the fiber without blocking a thread; every waiter sees the same outcome. A `Promise` completed by hand, but Effect-native: typed error channel, interruptible await, runtime-integrated.

**Reach for it when** one fiber must signal a single value or completion to others — bridging callbacks, gating on an approved result, or building single-flight/memoization.

### [Latch](./foundations/fibers-scopes-runtimes.md#latch)

`effect/Latch` — stable

A *reusable* open/closed gate. While a `Latch` is closed, `await` (and `whenOpen`) suspend; `open` releases current and future waiters; `release` frees only current waiters; `close` makes future waiters suspend again. Where `Deferred` is one-shot, a `Latch` resets — open it, close it, open it again.

**Reach for it when** you need a gate that opens and closes repeatedly. For a one-time signal, use `Deferred` instead.

### [ManagedRuntime](./foundations/fibers-scopes-runtimes.md#managedruntime)

`effect/ManagedRuntime` — stable

A reusable runtime built once from a `Layer`. Constructs services lazily on first use, caches them, and exposes plain `runPromise` / `runSync` / `runFork` methods so non-Effect code can execute effects with full dependency injection. Call `dispose()` to release everything the layer acquired. The bridge for embedding Effect inside a world that isn't Effect — Express handlers, React event callbacks, test harnesses, CLI commands. Pay the layer-construction cost once, then call `runtime.runPromise(effect)` repeatedly.

**Reach for it when** embedding Effect into a non-Effect host — framework callbacks, library glue, incremental adoption — and a long-lived, dependency-injected runtime is needed to run effects on demand.

### [Pull](./foundations/fibers-scopes-runtimes.md#pull)

`effect/Pull` — stable

The low-level primitive powering streams and channels. A `Pull<A, E, Done, R>` is an `Effect` that, when evaluated, either: produces a value `A`, fails with an ordinary error `E`, or signals end-of-input via `Cause.Done<Done>` in the error channel. Repeatedly evaluating a `Pull` is how a `Stream` is consumed under the hood. Normal completion is encoded as a special failure (`Cause.Done`) so a single effect expresses "here's a chunk," "I errored," and "I'm finished" — carrying a leftover value at the end if needed. The module provides `catchDone`, `filterDone`, `matchEffect` to distinguish these cases.

**Reach for it when** implementing a custom `Stream` or `Channel` primitive and needing direct control over the element-by-element pull protocol, including the end-of-input signal. For everyday data flow, stay in `Stream`.

### [Version](./foundations/fibers-scopes-runtimes.md#version)

`effect/Version` — unstable

The `effect` package version string reported in OTLP resources, telemetry headers, and span scopes. Added in 4.0.2.

**Reach for it when** you need to read or pin the version that Effect reports in OTLP resources and span attributes.

## [Services, Context & Layers](./foundations/services-context-layers.md)

Typed services, Context, References, Layer construction, memoization, and resource lifecycles.

The `R` in `Effect<A, E, R>` is a typed set of required services. **Context** holds those services, **Layer** is the recipe for constructing them (with dependencies and lifecycles), and the runtime blocks execution until every requirement is satisfied.

### [Context](./foundations/services-context-layers.md#context)

`effect/Context` — stable

A type-safe, immutable map from service tags to implementations. Declare services with `Context.Service` to get the tag, the accessor, and a default layer attachment point; the type system tracks requirements in `R`.

Sections: [Reading a service](./foundations/services-context-layers.md#reading-a-service) · [Designing a service contract](./foundations/services-context-layers.md#designing-a-service-contract) · [Providing one value or building a graph](./foundations/services-context-layers.md#providing-one-value-or-building-a-graph) · [Optional services](./foundations/services-context-layers.md#optional-services) · [Declaring the constructor with `make`](./foundations/services-context-layers.md#declaring-the-constructor-with-make)

### [Layer](./foundations/services-context-layers.md#layer)

`effect/Layer` — stable

A recipe that builds one or more services (possibly from other services) with acquisition and release. Layers are *memoized* and composed into a single dependency graph.

Sections: [Resourceful services](./foundations/services-context-layers.md#resourceful-services) · [What is shared, and what is rebuilt](./foundations/services-context-layers.md#what-is-shared-and-what-is-rebuilt) · [Reading and composing the graph](./foundations/services-context-layers.md#reading-and-composing-the-graph) · [Observing and recovering construction](./foundations/services-context-layers.md#observing-and-recovering-construction) · [Test layers and substitution](./foundations/services-context-layers.md#test-layers-and-substitution)

### [LayerMap](./foundations/services-context-layers.md#layermap)

`effect/LayerMap` — unstable

A service that lazily builds, caches, and tears down layers keyed by a value. Creates resources on first use per key, releases them after an idle timeout.

### [LayerRef](./foundations/services-context-layers.md#layerref)

`effect/LayerRef` — unstable

The unkeyed counterpart to `LayerMap`: a refreshable, reference-counted cache for one layer-built service context. `LayerRef.make(layer)` builds lazily on first scoped borrow, shares the context, optionally keeps it alive while idle, and lets you invalidate or refresh it. Existing borrowers keep their old context until their scopes close; the next borrow receives the rebuilt one.

### [References](./foundations/services-context-layers.md#references)

`effect/References` — stable

The registry of built-in, fiber-scoped runtime settings: log annotations and levels, tracer flags/annotations/links, scheduler-yield controls, active loggers, and unhandled-error reporting. They are implemented as `Context.Reference`s — values with defaults that flow down the fiber tree and can be locally overridden.

Sections: [Default services](./foundations/services-context-layers.md#default-services)

### [Resource](./foundations/services-context-layers.md#resource)

`effect/Resource` — stable

A scoped value that can **refresh itself**. `Resource.auto(acquire, schedule)` acquires a value and re-acquires it on a `Schedule`; `Resource.get` reads the latest successfully stored result. `Resource.manual` provides the same caching with explicit refreshes.

## [Configuration & Secrets](./foundations/configuration-secrets.md)

Configuration providers, validation, secrets, redaction, and application configuration patterns.

`Config` is an `Effect`, validated by `Schema`, read from a swappable provider. Three-part model: **Config** describes what you need and its shape. **ConfigProvider** decides where values come from. **Redacted** masks secret values; **Redactable** customizes rendering for consumers that honor Effect's redaction protocol.

### [Config](./foundations/configuration-secrets.md#config)

`effect/Config` — stable

`Config<T>` extends `Effect<T, ConfigError>` — read config by `yield*`-ing inside `Effect.gen`; missing/invalid values become a typed `ConfigError`. Convenience constructors (`Config.String`, `Config.Number`, `Config.Finite`, `Config.NonEmptyString`, `Config.Boolean`, `Config.Redacted`, `Config.LogLevel`, and the rest of the [built-in table](#built-in-constructors)) read a single key. Combinators (`Config.all`, `Config.nested`, `Config.withDefault`, `Config.map`, `Config.mapEffect`, `Config.flatMap`, `Config.option`) build structured config. `Config.schema(schema, path)` derives loading from the schema's encoded `StringTree`; opaque `Any`, `Unknown`, or JSON-shaped schemas must first be given a concrete string-tree boundary such as `Schema.fromJsonString(Schema.Json)`.

Sections: [Built-in constructors](./foundations/configuration-secrets.md#built-in-constructors) · [Lists and maps from flat values](./foundations/configuration-secrets.md#lists-and-maps-from-flat-values) · [Validating more than syntax](./foundations/configuration-secrets.md#validating-more-than-syntax) · [Absence is not malformed input](./foundations/configuration-secrets.md#absence-is-not-malformed-input)

### [ConfigProvider](./foundations/configuration-secrets.md#configprovider)

`effect/ConfigProvider` — stable

The source a `Config` reads from. Default: process environment. It is a `Context.Reference` you can replace with an in-memory object for tests, a directory of files via `ConfigProvider.fromDir`, or chained providers via `ConfigProvider.orElse`.

Sections: [Resolving one Config against an explicit provider](./foundations/configuration-secrets.md#resolving-one-config-against-an-explicit-provider) · [Precedence and composition](./foundations/configuration-secrets.md#precedence-and-composition)

### [Designing the startup contract](./foundations/configuration-secrets.md#designing-the-startup-contract)

**One `Config` value defines what a valid deployment looks like** — required keys, defaults, numeric bounds, duration syntax, and which values are secrets. A second hand-written parser, or scattered `process.env` reads, creates two definitions of "valid" that drift.

Sections: [Deciding required, optional, and defaulted](./foundations/configuration-secrets.md#deciding-required-optional-and-defaulted) · [Install configuration before anything that depends on it](./foundations/configuration-secrets.md#install-configuration-before-anything-that-depends-on-it) · [Testing the contract](./foundations/configuration-secrets.md#testing-the-contract)

### [Redacted](./foundations/configuration-secrets.md#redacted)

`effect/Redacted` — stable

`Redacted<string>` holds a secret value; stringifying, logging, or inspecting it prints `<redacted>`. The real value is only accessible via `Redacted.value`.

Sections: [Labels, comparison, and wiping](./foundations/configuration-secrets.md#labels-comparison-and-wiping) · [Secrets that arrive through a schema](./foundations/configuration-secrets.md#secrets-that-arrive-through-a-schema)

### [Redactable](./foundations/configuration-secrets.md#redactable)

`effect/Redactable` — stable

The protocol behind `Redacted`. Implement `Redactable` on your own types to customize their representation for consumers that invoke Effect's redaction protocol. The implementing method receives the current fiber's `Context` and returns a replacement value. This symbol alone is not a native `JSON.stringify`, `String`, or console-inspection hook. `Redacted` is the built-in implementer and also supplies safe serialization/inspection hooks.

## [Errors, Option & Result](./foundations/errors-option-result.md)

Typed errors, defects, Cause, Exit, Option, Result, recovery, retry, and failure modeling.

Effect treats failure as a typed value, not an exception. `Option` models absence, `Result` models success-or-failure, `Filter` models keep-or-reject, and `Data` builds structured comparable errors. Together they turn the error channel into ordinary control flow.

### [Designing the error model](./foundations/errors-option-result.md#designing-the-error-model)

Decide what each unpleasant outcome *is* before writing a class for it. The channel it lands in determines who can see it, who may recover from it, and what retry and alerting code will do with it.

### [Effect error handling](./foundations/errors-option-result.md#effect-error-handling)

The `catch*` family handles failures while keeping recovery visible in the effect's type.

Sections: [Selective recovery beyond one tag](./foundations/errors-option-result.md#selective-recovery-beyond-one-tag) · [Transforming the error channel](./foundations/errors-option-result.md#transforming-the-error-channel) · [Folding both channels at a boundary](./foundations/errors-option-result.md#folding-both-channels-at-a-boundary) · [Accumulating errors instead of failing fast](./foundations/errors-option-result.md#accumulating-errors-instead-of-failing-fast) · [Fallback values and ignoring failures](./foundations/errors-option-result.md#fallback-values-and-ignoring-failures) · [Recovery and mixed causes](./foundations/errors-option-result.md#recovery-and-mixed-causes)

### [Classifying an error union](./foundations/errors-option-result.md#classifying-an-error-union)

Before choosing a catch operator, write down which boundary owns each variant: validation failures belong to the API edge, transient transport failures to the retry boundary, impossible invariants to defects rather than `E`. When one boundary must classify the *whole* union — a status code, a retry decision, a user message — **finish the matcher with `Match.exhaustive` or `Match.tagsExhaustive`, never a `switch` with `default`**, so that adding a variant fails compilation exactly where policy must be updated. A default branch silently assigns tomorrow's error to today's fallback.

### [Option](./foundations/errors-option-result.md#option)

`effect/Option` — stable

`Option.some(a)` or `Option.none()`. The typed replacement for `null`/`undefined` — absence is in the type, not an implicit convention.

Sections: [Combining optional values](./foundations/errors-option-result.md#combining-optional-values) · [Fallbacks and boundary exits](./foundations/errors-option-result.md#fallbacks-and-boundary-exits)

### [Result](./foundations/errors-option-result.md#result)

`effect/Result` — stable

`Result.succeed(a)` or `Result.fail(e)`. Synchronous, pure success-or-failure — `Effect`'s error channel without async or requirements.

Sections: [Transforming and combining Results](./foundations/errors-option-result.md#transforming-and-combining-results) · [Moving between Option, Result, and Effect](./foundations/errors-option-result.md#moving-between-option-result-and-effect)

### [Filter](./foundations/errors-option-result.md#filter)

`effect/Filter` — stable

A function `(input) => Result<Pass, Fail>` that decides whether a value passes (optionally refining or transforming it) or is filtered out. A predicate that can narrow the type and explain the rejection.

### [Data](./foundations/errors-option-result.md#data)

`effect/Data` — stable

Helpers for defining value types — classes, tagged classes, tagged enums (discriminated unions), and error classes. Two `Data` values with the same contents are `Equal`, usable as keys in `HashMap`/`HashSet` and comparable via `Equal.equals`.

### [ErrorReporter](./foundations/errors-option-result.md#errorreporter)

`effect/ErrorReporter` — unstable

A pluggable sink for reporting `Cause`s — controls how unhandled failures are surfaced. Register reporters via a `Context.Reference`; annotate error types with severity and attributes for structured rendering.

### [PlatformError](./foundations/errors-option-result.md#platformerror)

`effect/PlatformError` — unstable

The typed error family for platform operations (filesystem, paths, child processes). Two shapes: `BadArgument` (invalid input) and `SystemError` (OS-level failure: `ENOENT`, `EACCES`, etc.), unified under `PlatformError`.

### [The three failure buckets](./foundations/errors-option-result.md#the-three-failure-buckets)

`Exit.findErrorOption` returns `None` for defects and interruptions, so a typed-failure assertion cannot accept a defect by accident. Two gotchas: **retrying or defaulting a defect hides a bug**, and **translating interruption into a user-facing error** creates noise and can block shutdown. Where a boundary must survive a defect (a plugin host, a per-job worker), `Effect.catchDefect` should recover only the defect it recognizes and re-raise the rest with `Effect.die(defect)`. The testing deep dive shows these assertions in context: [Assert typed failures as data](./deep-dives/testing-an-effect-application.md#assert-typed-failures-as-data). For symptoms and fixes, see [Typed failure versus defect and interruption](./troubleshooting/troubleshooting-and-anti-patterns.md#typed-failure-versus-defect-and-interruption).

# Concurrency & Streams

## [Concurrency & Coordination](./concurrency/concurrency-coordination.md)

Structured concurrency and coordination with fibers, queues, deferred values, semaphores, latches, and pools.

Effect's coordination primitives let fibers share permits, queues, broadcasts, pooled resources, and replaceable scoped values without abandoning typed errors or structured concurrency. Start with `Semaphore`, `Queue`, or `PubSub`; use the partitioned, reference-counted, and scoped variants when ownership or lifecycle becomes the harder part.

### [Semaphore](./concurrency/concurrency-coordination.md#semaphore)

`effect/Semaphore` — stable

A counting semaphore with a fixed permit pool. Fibers that need to do work acquire one or more permits; if insufficient permits are free they suspend until permits are released. Waiters are scanned in registration order and the first one whose request fits the free permits goes next; a new request that would fit is queued behind an earlier waiter that also fits rather than overtaking it. A smaller request can still overtake a *larger* earlier request whose permit count is unavailable, so do not assume strict FIFO fairness with mixed permit counts.

### [PartitionedSemaphore](./concurrency/concurrency-coordination.md#partitionedsemaphore)

`effect/PartitionedSemaphore` — unstable

A semaphore with a shared permit pool where waiters are grouped by a partition key. Released permits are distributed to waiting partitions in round-robin order (not global FIFO), preventing any one busy partition from starving others. A waiter that needs several permits is completed before the rotation moves on, so multi-permit waiters in different partitions cannot deadlock by each holding part of what they need.

### [Queue](./concurrency/concurrency-coordination.md#queue)

`effect/Queue` — stable

A fiber-safe FIFO queue for passing values from producers to consumers: each value is delivered to exactly one taker. Supports bounded and unbounded variants, three overflow strategies, explicit end-of-stream signaling via `Queue.end`, and failure/interruption propagation.

Sections: [Consuming: the consumer picks its waiting policy](./concurrency/concurrency-coordination.md#consuming-the-consumer-picks-its-waiting-policy) · [Put queue roles in function signatures](./concurrency/concurrency-coordination.md#put-queue-roles-in-function-signatures) · [Make loss observable](./concurrency/concurrency-coordination.md#make-loss-observable) · [Queue lifecycle: who ends it, and what a failure does](./concurrency/concurrency-coordination.md#queue-lifecycle-who-ends-it-and-what-a-failure-does)

### [PubSub](./concurrency/concurrency-coordination.md#pubsub)

`effect/PubSub` — stable

An in-process publish/subscribe bus. Producers call `PubSub.publish`; every active subscriber receives a copy. Unlike `Queue` (one message to one consumer), `PubSub` fans every message to all subscribers simultaneously. Late subscribers miss messages unless a replay buffer is configured.

Sections: [Delivery semantics: Queue or PubSub](./concurrency/concurrency-coordination.md#delivery-semantics-queue-or-pubsub) · [Overflow strategies and the publish result](./concurrency/concurrency-coordination.md#overflow-strategies-and-the-publish-result) · [Reading a subscription directly](./concurrency/concurrency-coordination.md#reading-a-subscription-directly) · [Proving a subscription did not leak](./concurrency/concurrency-coordination.md#proving-a-subscription-did-not-leak)

### [Pool](./concurrency/concurrency-coordination.md#pool)

`effect/Pool` — stable

A managed pool of scoped resources. A fixed pool preallocates its configured size asynchronously; an elastic pool preallocates `min` and grows toward `max` on demand. It lends items through a fiber's `Scope` and reclaims idle elastic items after a configurable TTL. `Pool.invalidate` removes a broken item so the next borrower gets a fresh one.

Sections: [TTL is not a health check](./concurrency/concurrency-coordination.md#ttl-is-not-a-health-check)

### [RcRef](./concurrency/concurrency-coordination.md#rcref)

`effect/RcRef` — stable

A reference-counted handle for a single scoped resource. The resource is acquired lazily on the first `RcRef.get`, shared among all active borrowers, and finalized when the last borrower's scope closes. An optional `idleTimeToLive` keeps it alive after all borrows end to avoid churn.

### [RcMap](./concurrency/concurrency-coordination.md#rcmap)

`effect/RcMap` — stable

Like `RcRef`, but keyed. An `RcMap<K, A>` runs a `lookup` effect the first time a given key is requested, shares the resource among all active borrows for that key, and releases it when the last borrow closes (with optional idle TTL). Multiple keys are fully independent with separate reference counts. An optional `capacity` caps entries, idle ones included; a new key beyond it fails with `Cause.ExceededCapacityError` — existing entries are never evicted to make room.

### [ScopedRef](./concurrency/concurrency-coordination.md#scopedref)

`effect/ScopedRef` — stable

A `Ref` whose value owns a `Scope`. Setting a new value first acquires the replacement in a fresh scope, then finalizes the old scope, and only then publishes the replacement. Reads are lock-free and synchronous; writes are serialized (one swap at a time).

## [Software Transactional Memory](./concurrency/software-transactional-memory.md)

Composable atomic state and coordination with STM, transactional references, queues, maps, sets, and locks.

### [The mental model](./concurrency/software-transactional-memory.md#the-mental-model)

A transaction is an **optimistic**, **composable**, **all-or-nothing** block of reads and writes over transactional cells (`TxRef` and the collections built on it).

Sections: [The canonical example: draw down a shared merit budget](./concurrency/software-transactional-memory.md#the-canonical-example-draw-down-a-shared-merit-budget) · [Failure rolls back; snapshots need one transaction](./concurrency/software-transactional-memory.md#failure-rolls-back-snapshots-need-one-transaction) · [Inspecting transaction attempts](./concurrency/software-transactional-memory.md#inspecting-transaction-attempts)

### [TxRef](./concurrency/software-transactional-memory.md#txref)

`effect/TxRef` — stable

The atom of STM: a single mutable cell whose reads and writes participate in a transaction. Every other `Tx*` structure is one or more `TxRef`s under the hood.

**Reach for it when** two or more pieces of state must change together and stay mutually consistent under concurrency, or when building custom transactional data structures.

### [TxChunk](./concurrency/software-transactional-memory.md#txchunk)

`effect/TxChunk` — unstable

A transactional growable sequence — a `Chunk` wrapped in a `TxRef` — with `append`, `prepend`, `take`, `drop`, `slice`, `map`, `filter`, `isEmpty`/`isNonEmpty`, all transactional. `TxChunk.isTxChunk` narrows an unknown value.

**Reach for it when** you need a transactional ordered buffer or change-log and queue blocking semantics would be overkill.

### [TxHashMap](./concurrency/software-transactional-memory.md#txhashmap)

`effect/TxHashMap` — stable

Transactional key/value map: `HashMap` behind a `TxRef`, with `get`, `set`, `remove`, `modify`, `modifyAt`, plus `map`, `filter`, `reduce`, `findFirst`, `union`.

**Reach for it when** you have a shared mutable map and updates across several keys must be consistent (reallocations, reconciliation, multi-key invariants).

### [TxHashSet](./concurrency/software-transactional-memory.md#txhashset)

`effect/TxHashSet` — stable

Transactional set of unique values with `add`, `remove`, `has`, `isEmpty`/`isNonEmpty`, and set algebra: `union`, `intersection`, `difference`, `isSubset`.

**Reach for it when** you track a concurrently-mutated set of unique things and want atomic add/remove plus set operations.

### [TxQueue](./concurrency/software-transactional-memory.md#txqueue)

`effect/TxQueue` — stable

Transactional FIFO queue with `bounded`, `unbounded`, `dropping`, and `sliding` strategies. Interface-segregated into `TxEnqueue` (write-only) and `TxDequeue` (read-only). `isEmpty`/`isNonEmpty` check depth without blocking.

**Reach for it when** you need a work queue with backpressure or blocking takes, especially when enqueue/dequeue must coordinate atomically with other transactional state.

### [TxPubSub](./concurrency/software-transactional-memory.md#txpubsub)

`effect/TxPubSub` — stable

Transactional publish/subscribe hub. Publishers call `publish`; each subscriber gets a scoped `TxQueue` receiving messages sent after subscription. Strategies: `bounded`, `unbounded`, `dropping`, `sliding`. Subscriptions are scope-bound — leaving the scope cleans up the subscriber queue. `size`, `isEmpty`/`isNonEmpty`, and `isFull` read the publish buffer without blocking.

**Reach for it when** you need transactional broadcast to many consumers and want publishing to commit atomically alongside other state changes.

### [TxSemaphore](./concurrency/software-transactional-memory.md#txsemaphore)

`effect/TxSemaphore` — stable

Counting semaphore whose permit acquisition is transactional. `acquire`/`acquireN` block (retry) until enough permits are free; `tryAcquire` never blocks; `withPermit`/`withPermits` bracket an effect with auto-release.

**Reach for it when** you need to cap concurrency or model a finite pool of resources, and want acquisition to compose transactionally with other STM state.

### [TxReentrantLock](./concurrency/software-transactional-memory.md#txreentrantlock)

`effect/TxReentrantLock` — stable

Transactional reader-writer lock that is *reentrant*: the same fiber can re-acquire a lock it already holds. Multiple readers may share the read lock; a writer gets exclusive access. Helpers: `withReadLock`, `withWriteLock`, `withLock`, plus scoped `readLock`/`writeLock`.

**Reach for it when** you want explicit reader/writer access control with reentrancy rather than relying purely on optimistic transaction retry.

### [TxDeferred](./concurrency/software-transactional-memory.md#txdeferred)

`effect/TxDeferred` — stable

Write-once transactional cell for a value produced later. `await` retries until completed; `succeed`/`fail`/`done` complete it exactly once (returning `true` on first completion, `false` thereafter); `poll` inspects without blocking.

**Reach for it when** one fiber must wait for a single result or signal produced by another, and that handoff should compose with other transactional state.

### [TxPriorityQueue](./concurrency/software-transactional-memory.md#txpriorityqueue)

`effect/TxPriorityQueue` — stable

Transactional priority queue ordered by an `Order`. `take` returns the smallest element by that order. Constructors (`empty`, `make`, `fromIterable`) take the `Order` up front. `offer`/`offerAll` insert in priority order (`offerAll` merges the batch in rather than re-sorting the whole queue). Also `peek`, `takeUpTo`, `removeIf`, `retainIf`, `isEmpty`/`isNonEmpty`.

**Reach for it when** you need a transactional scheduler or work queue where ordering matters, not just FIFO arrival.

### [TxSubscriptionRef](./concurrency/software-transactional-memory.md#txsubscriptionref)

`effect/TxSubscriptionRef` — stable

Transactional `TxRef` that also publishes its changes. Holds a current value (`get`/`set`/`update`/`modify`) and exposes committed updates as a `Stream` via `changesStream` (or a transactional queue via `changes`), always starting with the current value.

Sections: [Putting it together: a bounded approval pipeline with a freeze signal](./concurrency/software-transactional-memory.md#putting-it-together-a-bounded-approval-pipeline-with-a-freeze-signal)

**Reach for it when** you have transactional shared state that other fibers must observe reactively, and they should only ever see consistent, committed snapshots.

## [State & Mutable References](./concurrency/state-mutable-references.md)

Mutable and synchronized state using Ref, SynchronizedRef, SubscriptionRef, PubSub, and related primitives.

Effect provides fiber-safe shared-state types (`Ref`, `SynchronizedRef`, `SubscriptionRef`) and unsynchronised in-place data structures (`MutableRef`, `MutableList`, `MutableHashMap`, `MutableHashSet`) for hot paths where Effect overhead is undesirable.

### [Ref](./concurrency/state-mutable-references.md#ref)

`effect/Ref` — stable

An atomic mutable cell exposed as Effects. A `Ref<A>` holds one value; reads, writes, and transformations are Effect values — composable with fibers, timeouts, and retries. Internally wraps a `MutableRef` (a plain JS object with a `.current` field). Each pure `update` / `modify` runs synchronously without suspension, so another fiber cannot interleave its own operation inside that transition. The Effect wrapper makes the operation lazy and composable; it is not a lock around a sequence of separate calls.

Sections: [One transition, one call](./concurrency/state-mutable-references.md#one-transition-one-call) · [Sharing one Ref through a service](./concurrency/state-mutable-references.md#sharing-one-ref-through-a-service)

### [SynchronizedRef](./concurrency/state-mutable-references.md#synchronizedref)

`effect/SynchronizedRef` — stable

A separate reference type whose update operations are serialised even when the update is an Effect. It pairs a backing `Ref` with an internal `Semaphore` (single permit) so only one transition is in flight at a time. The API mirrors `Ref` and adds `*Effect` variants: `updateEffect`, `modifyEffect`, `getAndUpdateEffect`, `updateSomeEffect`, `modifySomeEffect`, etc.

### [SubscriptionRef](./concurrency/state-mutable-references.md#subscriptionref)

`effect/SubscriptionRef` — stable

A serialised reference that can also be observed as a `Stream`. It is its own type — not a subtype of `Ref` or `SynchronizedRef` — with the same operation names (`get`, `set`, `update`, `modify`, the `*Effect` and `*Some*` variants). Every state change is published to an internal unbounded `PubSub` with `replay: 1`, and `SubscriptionRef.changes(ref)` returns a `Stream<A>` over it: a subscriber receives the value current at the moment it subscribes, then every later update. Writes hold a single-permit semaphore while they store and publish, so no update is lost between the two.

Sections: [Keep the ref private, expose a Stream](./concurrency/state-mutable-references.md#keep-the-ref-private-expose-a-stream)

### [MutableRef](./concurrency/state-mutable-references.md#mutableref)

`effect/MutableRef` — stable

A tiny synchronous mutable box. Exposes a `.current` field for direct read/write plus a pipeable API: `get`, `set`, `update`, `compareAndSet`, numeric helpers `increment`/`decrement`, and `toggle` for booleans. No Effects, no fiber scheduler involvement. This is the backing store for `Ref` — `Ref` allocates a `MutableRef` internally. Like `Ref`, a `MutableRef` has no identity-based `Equal`: two boxes holding equal values compare equal under `Equal.equals`, and the cached result does not follow later writes, so never use one as a structural key.

### [MutableList](./concurrency/state-mutable-references.md#mutablelist)

`effect/MutableList` — stable

A mutable linked-list-of-buckets optimised for high-throughput append/prepend and front-draining. Uses chunked arrays (buckets) internally: append is amortised O(1), batch takes are nearly free. Tracks `.length`. Supports `append`, `prepend`, `take`, `takeN`, `takeAll`, `appendAll`, `prependAll`, `filter`, `remove`, `clear`. `take` returns the special `MutableList.Empty` symbol (not `null` or `undefined`) when the list is empty. There is no `modify` — `filter(list, predicate)` prunes in place, and `toArray` / `toArrayN` copy without draining. Counts passed to `takeN` / `toArrayN` are normalised: a fractional count is floored, and `NaN` or a non-positive count takes nothing. `appendAll` and `prependAll` copy the values they receive, so later changes to the caller's array do not reach the list. This is the buffer Effect itself uses inside `Queue` and `PubSub`.

### [MutableHashMap](./concurrency/state-mutable-references.md#mutablehashmap)

`effect/MutableHashMap` — stable

An in-place mutable key/value map supporting both JS reference equality and Effect structural equality (for keys implementing `Equal`/`Hash`). Internally layers a native `Map` for ordinary keys with hash-bucket collision chains for structural keys. Is `Iterable<[K, V]>`.

### [MutableHashSet](./concurrency/state-mutable-references.md#mutablehashset)

`effect/MutableHashSet` — stable

A mutable set built on `MutableHashMap` — each element is a map key pointing to `true`. Supports structural equality via `Equal`/`Hash`: elements are deduplicated by value, not reference. Is `Iterable<V>`. Supports `add`, `has`, `remove`, `size`, `clear`, `make`, `fromIterable`, `empty`.

### [Choosing the right state tool](./concurrency/state-mutable-references.md#choosing-the-right-state-tool)

## [Streaming & Channels](./concurrency/streaming-channels.md)

Streams, sinks, channels, codecs, configuration parsers (TOML, YAML, INI, JSON5, JSONC), multipart parsing, and incremental data processing.

`Stream<A, E, R>` is a pull-based source: the consumer requests the next chunk, the stream computes it (possibly failing with `E`, needing services `R`), emits the chunk, and waits. This pull loop provides automatic back-pressure. `Sink<A, In, L, E, R>` folds chunks into a final answer. `Channel` is the bidirectional primitive both are built from. In practice: live in `Stream` 95% of the time; reach for `Channel` only when authoring a new operator.

### [Stream](./concurrency/streaming-channels.md#stream)

`effect/Stream` — stable

`Stream<A, E, R>` is a lazy, pull-based, possibly-infinite sequence of `A`s that can fail with `E` and needs services `R`. Pulling provides automatic back-pressure and supports constant-memory pipelines when each stage keeps bounded state. Collecting, unbounded grouping/buffering, or letting producers outrun consumers can still consume memory proportional to the data. Combinators cover three operations — create, transform, run — and the later subsections cover combining streams, failure handling, resource ownership, and where buffering hides.

Sections: [1. Creating streams](./concurrency/streaming-channels.md#1-creating-streams) · [2. Transforming streams](./concurrency/streaming-channels.md#2-transforming-streams) · [3. Running streams](./concurrency/streaming-channels.md#3-running-streams) · [4. Combining and splitting streams](./concurrency/streaming-channels.md#4-combining-and-splitting-streams) · [5. Handling stream failures](./concurrency/streaming-channels.md#5-handling-stream-failures) · [6. Owning resources inside a stream](./concurrency/streaming-channels.md#6-owning-resources-inside-a-stream) · [7. Where buffering hides](./concurrency/streaming-channels.md#7-where-buffering-hides)

### [Sink](./concurrency/streaming-channels.md#sink)

`effect/Sink` — stable

`Sink<A, In, L, E, R>` consumes elements of type `In`, may fail with `E`, needs `R`, and produces a result `A` plus unconsumed leftover `L`. The leftover slot enables early termination without discarding unused elements — two sinks can be sequenced so the second picks up exactly where the first stopped.

Sections: [Adapting, leftovers, and repeatable batching](./concurrency/streaming-channels.md#adapting-leftovers-and-repeatable-batching)

### [Channel](./concurrency/streaming-channels.md#channel)

`effect/Channel` — stable

The primitive underlying `Stream` and `Sink`. `Channel<OutElem, OutErr, OutDone, InElem, InErr, InDone, Env>` — emits `OutElem`, may fail `OutErr`, finishes with `OutDone`; accepts upstream `InElem` that may fail `InErr` and finish `InDone`; needs `Env`. `Stream` is a channel that only outputs; `Sink` is a channel that consumes and produces a single done value.

### [ChannelSchema](./concurrency/streaming-channels.md#channelschema)

`effect/ChannelSchema` — unstable

Adapter layer that attaches a `Schema` to a channel boundary. `ChannelSchema.encode(schema)()` converts typed values to the schema's encoded form; `ChannelSchema.decode(schema, parseOptions?)()` validates the inverse, and takes optional `SchemaAST.ParseOptions` such as `{ onExcessProperty: "error" }` (as does `decodeUnknown`). `duplex` wraps a bidirectional channel so callers see typed I/O while the inner channel speaks the wire format.

### [Take](./concurrency/streaming-channels.md#take)

`effect/Take` — stable

`Take<A, E, Done>` is a reified single-pull result: either a `NonEmptyReadonlyArray<A>` (a batch), or an `Exit` that is a failure (`E`) or successful completion carrying `Done`. Used to store or transport "what the stream produced in one step" — e.g. bridging a stream through a `Queue` or `PubSub`.

### [Ndjson](./concurrency/streaming-channels.md#ndjson)

`effect/encoding/Ndjson` — unstable

Newline-delimited JSON codecs as channels. `Ndjson.decodeString()` splits on newlines and `JSON.parse`s each line. `Ndjson.decode()` takes `Uint8Array` input: it splits on raw bytes, decodes each line as strict UTF-8, and skips a leading BOM. Both accept `\n`, `\r\n`, and a bare `\r` as line endings. Failures are a tagged `NdjsonError` with `kind: "Pack"` (encoding) or `"Unpack"` (decoding); decoders also set `reason` (`"InvalidJson"`, `"InvalidUtf8"`, or `"LineTooLarge"`) and `unterminated` when the bad line is the final line without a terminator. The lines before a bad line are emitted before the channel fails. `decodeSchemaString(Schema)()` fuses split → parse → validate in one channel.

### [Sse](./concurrency/streaming-channels.md#sse)

`effect/encoding/Sse` — unstable

Server-Sent Events codec. `Sse.decode()` parses SSE text chunks into `Event` values with `id`, `event`, and `data` fields. An SSE `retry:` directive surfaces as a `Retry` failure in the error channel, making reconnect logic straightforward error handling. `Sse.encode()` renders `Event`s as SSE wire text. `Sse.decodeDataSchema(schema)` JSON-decodes the `data` payload while preserving `event` name and `id`. `Sse.decodeSchema(schema, options?, parseOptions?)` validates the whole `{ event, data, id? }` envelope; the third argument passes Schema parse options.

### [Csv](./concurrency/streaming-channels.md#csv)

`effect/encoding/Csv` — unstable

Streaming RFC 4180 CSV over text (`decodeString` / `encodeString`) or UTF-8 bytes (`decode` / `encode`). Cells are strings kept exactly as written; quoted fields may contain delimiters, line breaks, and doubled quotes. Decoders accept LF, CRLF, and CR and strip a leading BOM. With `{ headers: true }` the first record supplies unique field names and every later record becomes an object of the same width; a duplicate header or a row of a different width fails with `CsvError` (`kind: "Header"`, plus one-based `record` and `line`); malformed quoting is `kind: "Syntax"` with a `column`. Records completed before the failing one, including those in the same input chunk, are emitted before the `CsvError`. `delimiter` is one character (default `","`), `maxRecordSize` bounds one record in UTF-16 code units (default 1 MiB, exceeding it is `kind: "RecordSize"`; `Infinity` disables it), and `ignoreEmptyLines` skips blank records instead of reading them as one empty cell. Invalid options throw when the channel is created.

### [JsonArray](./concurrency/streaming-channels.md#jsonarray)

`effect/encoding/JsonArray` — unstable

Streams the elements of **one** JSON array — the root, or the array an RFC 6901 `pointer` selects inside an envelope such as `{"items":[...],"total":n}` — without buffering the whole document. Each element is buffered only until complete, then `JSON.parse`d; the rest of the document is validated and discarded. Use `Ndjson` instead when the producer writes one value per line. (It is unrelated to `Schema.JsonArray`, the type of a JSON array value.) The encoders write a stream of values as one array; an empty stream encodes as `[]`.

### [Xml](./concurrency/streaming-channels.md#xml)

`effect/encoding/Xml` — experimental

Streaming XML 1.0 over text (`decodeString` / `encodeString`) or UTF-8 bytes (`decode` / `encode`). Decoders emit `Xml.Event`s (`Declaration`, `Doctype`, `StartElement`, `EndElement`, `Text`, `Comment`, `ProcessingInstruction`) and check well-formedness. `Xml.elements(path)` collects every element at a root-anchored path (`"*"` matches any name) into a small `{ name, attributes, children }` tree, so a large feed or export is processed one record at a time.

### [SchemaBinary](./concurrency/streaming-channels.md#schemabinary)

`effect/encoding/SchemaBinary` — unstable

A compact binary codec **derived from a Schema** rather than from the runtime shape of a value. It replaced the MessagePack codec (`Msgpack`, `RpcSerialization.layerMsgPack`, and the `msgpackr` dependency have been removed), and it is now what EventLog persistence, EventLog remote messages, and TCP cluster transports put on the wire.

### [Tar](./concurrency/streaming-channels.md#tar)

`effect/encoding/Tar` — unstable

`Tar.decode()` reads v7, USTAR, PAX extended headers (including global headers), GNU long names and links, and base-256 numbers; GNU sparse entries fail with an `Unsupported` `TarError`. `Tar.encode()` writes USTAR, adding a PAX header only for what USTAR cannot hold, and streams bodies without buffering them. Build entries with `Tar.file(path, content)`, `Tar.fileStream(path, size, body)` (note that `size` comes before the body), `Tar.directory`, `Tar.symlink`, and `Tar.hardlink`; unset options default to fixed modes, uid/gid `0`, and an epoch mtime, so archives are reproducible. It does not compress.

### [Zip](./concurrency/streaming-channels.md#zip)

`effect/encoding/Zip` — experimental

Streaming zip with stored and deflated entries and ZIP64 when sizes, offsets, or counts need it. `Zip.decode()` reads entries in archive order from their local headers — so an archive can be decoded as it arrives — and checks every body against its CRC-32 and sizes; it never reads the central directory, so `mode`, comments, and entries only the central directory lists are not reported. `Zip.encode()` writes each entry as it arrives and the central directory at the end. Build entries with `Zip.file(path, content, { method? })` (in memory, default `"Deflate"`; use `"Store"` for already-compressed content), `Zip.fileStream(path, body, options?)`, and `Zip.directory(path)`. Compression uses the runtime's `CompressionStream("deflate-raw")`. Encryption, other methods, and split archives are not supported.

### [Ini](./concurrency/streaming-channels.md#ini)

`effect/encoding/Ini` — unstable

A small, dependency-free INI decoder used by the CLI configuration-file primitive. `Ini.parse(text)` returns a null-prototype record: dotted section names become nested records, `key[]` repetitions become arrays, and `true`, `false`, and `null` become scalars. Other values — including numbers — remain strings.

### [Toml](./concurrency/streaming-channels.md#toml)

`effect/encoding/Toml` — unstable

A focused TOML 1.0 parser covering tables, dotted keys, arrays and inline tables, arrays of tables, multiline strings, numeric formats, and TOML date/time forms. `Toml.parse(text)` does not throw: it returns `Result<Record<string, unknown>, EncodingError>`, failing with an [`EncodingError`](./data/functional-toolkit.md#encodingerror) (`module: "Toml"`, `kind: "Decode"`, and a message carrying the line and column) for invalid input. Tables are null-prototype records. Offset date-times become JavaScript `Date`s; local dates and times remain strings. The parser rejects what TOML 1.0 forbids: duplicate keys and tables, extending an inline table or a statically defined array, out-of-range dates and times such as `1979-02-30` or `24:00:00`, integers outside JavaScript's safe range, raw control characters (including a bare carriage return), and non-scalar Unicode escapes.

### [Yaml](./concurrency/streaming-channels.md#yaml)

`effect/encoding/Yaml` — unstable

A focused YAML 1.2 configuration parser. Unlike `Toml.parse`, `Yaml.parse(text)` returns `unknown` and throws on invalid input. It supports block and flow collections (flow collections may span lines), quoted and block scalars, anchors (including anchors inside flow collections), aliases, and YAML 1.1 merge keys: an unquoted `<<` key merges a mapping, or a sequence of mappings, into the enclosing mapping, with explicit keys winning over merged ones and earlier merge sources over later ones; quote it (`"<<"`) to keep an ordinary key. Invalid indentation, duplicate keys, malformed collections, and unknown aliases throw `SyntaxError`. The parser rejects three inputs that resemble valid YAML but are not: a plain (unquoted) scalar with a colon followed by a space or the end of the value (`description: Use when: deploy`, `description: Deploy:`), a compact nested sequence (`- - value`), and a stream of several documents separated by `---`. Colons without a following space, as in `url: http://x.com` or `time: 12:30`, still parse as plain text.

### [Json5](./concurrency/streaming-channels.md#json5)

`effect/encoding/Json5` — unstable

A dependency-free [JSON5](https://spec.json5.org/) parser for hand-edited configuration. `Json5.parse(text)` returns `Result<unknown, EncodingError>`, failing with an [`EncodingError`](./data/functional-toolkit.md#encodingerror) (`module: "Json5"`, `kind: "Decode"`) whose message gives the line and column but never repeats the input. Beyond JSON it accepts comments, trailing commas, unquoted identifier keys, single-quoted strings, hexadecimal numbers, `Infinity`, and `NaN`. A duplicate key keeps its last value, and a `__proto__` key becomes an ordinary own property instead of replacing the prototype. There is no reviver argument.

### [Jsonc](./concurrency/streaming-channels.md#jsonc)

`effect/encoding/Jsonc` — unstable

JSON with comments, the format of `tsconfig.json` and editor settings files. `Jsonc.parse(text)` returns `Result<unknown, EncodingError>` (`module: "Jsonc"`) and accepts exactly what `JSON.parse` accepts once line and block comments are removed, plus one leading BOM. Unlike JSON5 it rejects trailing commas and every other extension, and duplicate keys and `__proto__` follow `JSON.parse`. Error positions are one-based lines and columns in UTF-16 code units, and the message does not include the input.

## [Scheduling & Time](./concurrency/scheduling-time.md)

Schedules, retries, repetition, Duration, DateTime, Clock, Cron, and time-zone-aware execution.

### [Schedule](./concurrency/scheduling-time.md#schedule)

`effect/Schedule` — stable

**What it is.** A `Schedule<Output, Input, Error, Env>` is a composable recurrence policy. At each step it decides: keep going or stop? If continuing, how long to wait? The policy can inspect the input (error when retrying, success value when repeating) and emit any output. `Effect.retry` and `Effect.repeat` are built on this primitive.

Sections: [Primitive constructors](./concurrency/scheduling-time.md#primitive-constructors) · [Composing schedules](./concurrency/scheduling-time.md#composing-schedules) · [Filtering on the input](./concurrency/scheduling-time.md#filtering-on-the-input) · [Polling with repeat and passthrough](./concurrency/scheduling-time.md#polling-with-repeat-and-passthrough) · [Shorthand options for retry and repeat](./concurrency/scheduling-time.md#shorthand-options-for-retry-and-repeat) · [Retry policy checklist](./concurrency/scheduling-time.md#retry-policy-checklist) · [Scheduled repeat via Schedule.cron](./concurrency/scheduling-time.md#scheduled-repeat-via-schedule-cron) · [Running a side task for as long as the main task runs](./concurrency/scheduling-time.md#running-a-side-task-for-as-long-as-the-main-task-runs) · [Inspecting a schedule](./concurrency/scheduling-time.md#inspecting-a-schedule) · [Testing a policy](./concurrency/scheduling-time.md#testing-a-policy) · [Quick reference](./concurrency/scheduling-time.md#quick-reference)

**Reach for it when** you need to retry failed API calls with backoff, poll a workflow for a terminal state, run background jobs on a cron cadence, or express any policy combining timing, attempt count, and error classification.

### [Duration](./concurrency/scheduling-time.md#duration)

`effect/Duration` — stable

**What it is.** `Duration` is Effect's typed time-span value. Every scheduling API, timeout, and sleep accepts a `Duration.Input` — a raw number (millis), a string like `"5 seconds"`, or a `Duration` object. For arithmetic or comparison, construct a real `Duration` first.

Sections: [Parsing untrusted durations and interop edges](./concurrency/scheduling-time.md#parsing-untrusted-durations-and-interop-edges)

**Reach for it when** you need to express, compare, add, or format typed time spans rather than raw millisecond numbers. It is the currency of every scheduling and timeout API in the library.

### [DateTime](./concurrency/scheduling-time.md#datetime)

`effect/DateTime` — stable

**What it is.** `DateTime` is Effect's Clock-aware, timezone-capable replacement for the native `Date` type. Two flavors: `DateTime.Utc` (a pure millisecond instant) and `DateTime.Zoned` (an instant pinned to an IANA timezone with rendered local time). Covers parsing, current time, arithmetic, and formatting.

Sections: [Computing dates and deadlines](./concurrency/scheduling-time.md#computing-dates-and-deadlines) · [Parsing safely](./concurrency/scheduling-time.md#parsing-safely) · [Time zones (IANA)](./concurrency/scheduling-time.md#time-zones-iana) · [Constructing zoned values from wall-clock input](./concurrency/scheduling-time.md#constructing-zoned-values-from-wall-clock-input) · [Calendar math and truncation](./concurrency/scheduling-time.md#calendar-math-and-truncation) · [Providing the current zone via a Layer](./concurrency/scheduling-time.md#providing-the-current-zone-via-a-layer) · [Formatting](./concurrency/scheduling-time.md#formatting)

**Reach for it when** you need the current time in an Effect, when parsing ISO timestamps safely, when computing dates that must respect DST and timezones, or when formatting a timestamp for display or a database column.

### [Cron](./concurrency/scheduling-time.md#cron)

`effect/Cron` — stable

**What it is.** A pure cron expression parser and evaluator. Parses a standard 5-field (or 6-field with seconds) cron string into a typed `Cron` value queryable for next/previous run times, instant matching, or an infinite sequence of future fire times. Also backs `Schedule.cron`.

Sections: [Repeated local times when clocks fall back](./concurrency/scheduling-time.md#repeated-local-times-when-clocks-fall-back) · [Building a Cron from structured fields](./concurrency/scheduling-time.md#building-a-cron-from-structured-fields) · [Driving a scheduled job with Schedule.cron](./concurrency/scheduling-time.md#driving-a-scheduled-job-with-schedule-cron)

**Reach for it when** you need to parse cron expressions from configuration, check whether a scheduled job should have fired, enumerate upcoming run times for a scheduling preview UI, or drive a background job with `Schedule.cron`.

### [Random](./concurrency/scheduling-time.md#random)

`effect/Random` — stable

**What it is.** Effect-native pseudo-random number generation. Every `Random.*` function returns an `Effect` reading from a `Context.Reference` holding the PRNG service. Because that service can be locally replaced rather than relying on a process-global generator, it is **seedable** and **reproducible** — test suites can pin the seed and get deterministic runs.

Sections: [Deterministic testing](./concurrency/scheduling-time.md#deterministic-testing) · [Jitter without coupling to Math.random](./concurrency/scheduling-time.md#jitter-without-coupling-to-math-random)

**Reach for it when** you need randomness inside an Effect — picking a random item, shuffling data, generating test data, adding jitter to a custom retry delay, or running a reproducible simulation. Never call `Math.random()` directly; you lose testability and fiber-locality.

# Data & Schema

## [Data Structures](./data/data-structures.md)

Effect's immutable collections, equality, hashing, ordering, numeric types, and data-oriented utilities.

Most collections here use immutable transformations, `pipe`-friendly dual APIs, and structural `Equal`/`Hash`. Exceptions are explicit: `HashRing` and low-level helpers such as `Record.assignProperty` mutate their targets. Check each operation's result and ownership contract.

### [Array](./data/data-structures.md#array)

`effect/Array` — stable

Operates on plain JavaScript arrays — no wrapper type. Collection transformations do not mutate the input; results are native arrays, compatible with third-party code without conversion. Observers and branching helpers return their declared result rather than necessarily allocating an array.

### [Chunk](./data/data-structures.md#chunk)

`effect/Chunk` — stable

An immutable ordered sequence with five internal backing shapes: empty, singleton, array, slice (`ISlice`), or concatenation tree (`IConcat`). Two chunks concatenated stay as a tree node — no data is copied at the join. Traversal materializes a non-array backing on demand and caches that readonly array; `Chunk.toArray` then returns a separate mutable copy.

### [HashMap](./data/data-structures.md#hashmap)

`effect/HashMap` — stable

Immutable key-value map backed by a Hash Array Mapped Trie (HAMT). Lookup, insert, and delete are O(log 32 n) — effectively constant for practical sizes. Keys are hashed and compared via Effect's `Equal`/`Hash` protocol — structural equality, not reference equality.

### [HashSet](./data/data-structures.md#hashset)

`effect/HashSet` — stable

Immutable set backed by the same HAMT internals as `HashMap`. Membership tests and set-algebraic ops (`union`, `intersection`, `difference`, `isSubset`) use structural `Equal`/`Hash`. Two structurally equal items (same fields, different references) count as one member.

### [Trie](./data/data-structures.md#trie)

`effect/Trie` — stable

Immutable prefix tree mapping `string` keys to values. Structurally like `HashMap<string, V>` but with first-class prefix operations: enumerate all keys starting with a given prefix, or find the longest stored key that is a prefix of a query string. Iteration yields `[key, value]` pairs in alphabetical order.

### [Graph](./data/data-structures.md#graph)

`effect/Graph` — unstable

Typed graph with directed and undirected support, user-defined node and edge data, and a broad algorithm set: DFS/BFS/topological traversal, shortest paths (Dijkstra, A*, Bellman-Ford, Floyd-Warshall), path enumeration, cycle witnesses, connectivity analysis, minimum spanning forests, transitive reduction, bipartite matching, and maximum flow / minimum cut. Nodes identified by `NodeIndex` (allocated number); edges by `EdgeIndex`.

Sections: [Witnesses, reductions, and matchings](./data/data-structures.md#witnesses-reductions-and-matchings)

### [HashRing](./data/data-structures.md#hashring)

`effect/HashRing` — unstable

Weighted consistent-hashing ring. Register nodes (any value implementing `PrimaryKey`), each with an optional weight. Route string keys to nodes via `HashRing.get(ring, key)` (returns `A | undefined`), or precompute a balanced shard distribution with `HashRing.getShards(ring, shardCount)`.

### [Record](./data/data-structures.md#record)

`effect/Record` — stable

Helpers operating on plain JavaScript objects (`Record<K, V>` / `ReadonlyRecord<K, V>`). Collection transformations return new records; observers, `collect`, and `partition` have their declared result shapes. The low-level `assignProperty` intentionally mutates its target and returns `void`. Provides `map`, `filter`, `filterMap`, `reduce`, `partition`, `collect` (map + collect values into an array), and set operations (`union`, `intersection`, `difference`) over record values.

### [Tuple](./data/data-structures.md#tuple)

`effect/Tuple` — stable

Typed tuple helpers — construct, pick, omit, evolve, map, rename indices, and build structural `Equivalence` and `Order` for fixed-length tuples. All operations preserve the exact tuple type.

### [Struct](./data/data-structures.md#struct)

`effect/Struct` — stable

Helpers for typed plain objects: `pick` / `omit` fields, `evolve` individual values, `assign` additional fields, `renameKeys`, and derive structural `Equivalence` and `Order` from per-field comparators. All return new plain objects — no mutation, no class wrapping.

### [Iterable](./data/data-structures.md#iterable)

`effect/Iterable` — stable

Combinators for any value implementing `[Symbol.iterator]` — arrays, strings, generators, sets, custom sequences. Transformations such as `map`, `filter`, and `take` return lazy iterables with no materialization until traversal. Terminal and aggregating operations such as `reduce`, `size`, `groupBy`, and `forEach` traverse eagerly and may allocate their complete result.

### [NonEmptyIterable](./data/data-structures.md#nonemptyiterable)

`effect/NonEmptyIterable` — stable

Type-level brand: `NonEmptyIterable<A>` extends `Iterable<A>` and carries `readonly [nonEmpty]: A` as a phantom field. Non-emptiness is visible at the type level with zero runtime cost — purely a TypeScript narrowing mechanism.

## [The Functional Toolkit](./data/functional-toolkit.md)

Functional composition with Function, Match, Predicate, Equivalence, Order, Optic, Brand, exact numbers such as BigDecimal and Rational, and utilities.

Effect ships a full standard library — structural equality, comparators, branded types, pattern matching, optics, arbitrary-precision decimals, and more — all composable with each other and the rest of the ecosystem.

### [Match](./data/functional-toolkit.md#match)

`effect/Match` — stable

Exhaustive, composable pattern matching for TypeScript. Type-safe `switch` that narrows unions automatically, enforces case coverage, and composes through `pipe`.

Sections: [Closing a matcher](./data/functional-toolkit.md#closing-a-matcher)

### [Order](./data/functional-toolkit.md#order)

`effect/Order` — stable

A typeclass for total ordering: `Order<A>` returns `-1 | 0 | 1`. All sorting, min/max, and clamp operations in Effect are backed by `Order`.

### [Equal](./data/functional-toolkit.md#equal)

`effect/Equal` — stable

The structural equality protocol. `Equal.equals(a, b)` compares any two values using deep structural comparison for plain objects, arrays, Maps, Sets, and Dates; falls back to `[Equal.symbol]` for custom types.

Sections: [Equality pitfalls and opt-outs](./data/functional-toolkit.md#equality-pitfalls-and-opt-outs)

### [Hash](./data/functional-toolkit.md#hash)

`effect/Hash` — stable

The hashing half of the equality protocol. `Hash.hash(value)` returns a stable integer hash, using structural hashing for plain objects/arrays and delegating to `[Hash.symbol]()` for custom types.

### [Equivalence](./data/functional-toolkit.md#equivalence)

`effect/Equivalence` — stable

A simple function type `(a: A, b: A) => boolean` with combinators for building custom equality predicates outside the `Equal` protocol.

### [Ordering](./data/functional-toolkit.md#ordering)

`effect/Ordering` — stable

The type `Ordering = -1 | 0 | 1` — return value of any `Order<A>` comparator. Provides `Ordering.reverse` to flip a result and `Ordering.match` to branch on it. Mostly consumed by `Order` combinators internally; useful when implementing custom comparators combining multiple sub-comparisons.

### [Combiner](./data/functional-toolkit.md#combiner)

`effect/Combiner` — stable

An associative binary operation: `combine(a, b)` produces another value of the same type. Building block for combining two values into one.

### [Reducer](./data/functional-toolkit.md#reducer)

`effect/Reducer` — stable

`Combiner` + an `initialValue` — enables folding empty collections. The `initialValue` acts as the identity element.

### [Brand](./data/functional-toolkit.md#brand)

`effect/Brand` — stable

Nominal typing for TypeScript. A `Branded<string, "EmployeeId">` is a `string` at runtime but a distinct type at compile time.

### [Optic](./data/functional-toolkit.md#optic)

`effect/Optic` — stable

Composable, typed lenses and prisms for reading and immutably updating nested data. An optic describes a path into a data structure; compose paths then call `.get`, `.replace`, or `.modify`.

### [Predicate](./data/functional-toolkit.md#predicate)

`effect/Predicate` — stable

Type guards, refinements, and Boolean combinators. Both a utility belt of `isString`/`isNumber`/... guards and a combinator library for building complex predicates from simpler ones.

### [BigDecimal](./data/functional-toolkit.md#bigdecimal)

`effect/BigDecimal` — stable

Arbitrary-precision decimal arithmetic based on a `bigint` significand and integer scale. No floating-point rounding errors — `0.1 + 0.2 === 0.3` in BigDecimal.

### [Rational](./data/functional-toolkit.md#rational)

`effect/Rational` — unstable

An exact fraction: a `bigint` `numerator` and a positive `bigint` `denominator`, always reduced to lowest terms (zero is `0/1`). Where [BigDecimal](#bigdecimal) rounds a non-terminating quotient such as one third, `Rational` keeps it exact through any number of `sum`, `multiply`, `divide`, and `pow` steps. Use `BigDecimal` for decimal quantities such as money, and `Rational` for ratios that must stay exact until an explicit conversion: allocation shares, unit-conversion factors, probabilities, compounding rates.

### [ByteSize](./data/functional-toolkit.md#bytesize)

`effect/ByteSize` — unstable

An exact, non-negative, integral byte count: a branded `bigint`, so a 9 EiB object store and a 12-byte header use the same type without precision loss. It replaced the ad-hoc `FileSystem.Size` / `FileSystem.MiB` helpers and is now the size vocabulary across the ecosystem — `FileSystem` `File.Info.size`, HTTP body limits, and `Config.ByteSize`.

### [Differ](./data/functional-toolkit.md#differ)

`effect/Differ` — stable

An interface for patch-based change tracking. A `Differ<T, Patch>` computes the difference between two `T`s as a `Patch`, combines patches, and applies a patch to produce an updated value.

### [TextDiff](./data/functional-toolkit.md#textdiff)

`effect/TextDiff` — experimental

Minimal edit scripts for arrays and text (Myers' algorithm in linear space). `diff(before, after)` compares array items with `Equal.equals` and `diffWith(isEquivalent)` with a custom equivalence; `lines` diffs text line by line, keeping each `\n` so line-ending changes are visible; `codePoints` diffs by Unicode code point, never splitting a surrogate pair. A script is an array of `Equal` / `Delete` / `Insert` runs. `apply` and `applyText` replay a script and return `Result` — `applyText` rejects a script made for different text with a `TextDiffError` — and `invert` reverses it. `unified(edits, { context?, fromFile?, toFile? })` formats a line script as a unified diff.

### [SemVer](./data/functional-toolkit.md#semver)

`effect/SemVer` — unstable

Immutable [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html) values: numeric `major`, `minor`, `patch`, optional `prerelease` identifiers, and optional `build` metadata. Parsing is strict — `SemVer.parse(text)` returns `Result<SemVer, SemVerError>` and rejects partial versions (`"1.2"`) and a `v` prefix; `parseUnsafe` throws, and `make(components)` / `fromInput` build from fields. `format` prints the canonical string.

### [SemVerRange](./data/functional-toolkit.md#semverrange)

`effect/SemVerRange` — unstable

npm-style version ranges over `SemVer`: comparators, `^` caret, `~` tilde, `x`/`*` wildcards, hyphen ranges (`1.2.3 - 2.3.4`), and `||` alternatives. `SemVerRange.parse(text)` returns `Result<SemVerRange, SemVerError>`; constructors (`exact`, `caret`, `tilde`, `greaterThan`, `lessThanOrEqualTo`, `between({ minimum, maximum })`, `any`) build ranges directly. `matches(range, version, options?)`, `maxSatisfying`, and `minSatisfying` accept a `SemVer` or a version string and throw `SemVerError` on an invalid one.

### [Newtype](./data/functional-toolkit.md#newtype)

`effect/Newtype` — unstable

A zero-cost type wrapper — a type-level distinct alias for another type, with helpers to lift its `Equivalence`, `Order`, `Combiner`, and `Reducer` instances. Related to `Brand` but different: a Newtype carries no runtime value of its own; it is the carrier type with a phantom tag.

### [Function](./data/functional-toolkit.md#function)

`effect/Function` — stable

Combinators for functional composition: `pipe`, `flow`, `identity`, `constant`, and indispensable utilities.

### [Number](./data/functional-toolkit.md#number)

`effect/Number` — stable

Pipeable arithmetic, comparisons, and ready-made `Reducer`s for `number`. Exports `Number.Order`, `Number.Equivalence`, `Number.ReducerSum`, `Number.ReducerMultiply`, `Number.ReducerMin`, `Number.ReducerMax`. Arithmetic ops (`sum`, `multiply`, `subtract`, `divide`, `remainder`) are data-last for pipeline use. Also `Number.clamp`, `Number.between`, `Number.sign`, `Number.parse` (safe string parse returning `Option`), `Number.round`, and `Number.nextPow2`.

### [String](./data/functional-toolkit.md#string)

`effect/String` — stable

Comprehensive, pipeable string API. Re-exports the global `String` constructor plus safe wrappers for common string operations. Notable additions over plain JS: `String.indexOf`/`lastIndexOf` return `Option`, `String.stripMargin` cleans multiline template literals, full case-conversion helpers (`camelCase`, `pascalCase`, `snakeToCamel`, `constantCase`, etc.).

### [Boolean](./data/functional-toolkit.md#boolean)

`effect/Boolean` — stable

Boolean logic as pipeable functions. `Boolean.match` branches on a boolean like a mini pattern match. Logical connectives — `and`, `or`, `not`, `xor`, `nand`, `nor`, `implies`, `eqv` — as data-last functions. Includes `Boolean.every`/`some` for iterables and ready-made reducers `Boolean.ReducerAnd`/`ReducerOr`.

### [BigInt](./data/functional-toolkit.md#bigint)

`effect/BigInt` — stable

Arithmetic and comparison for native `bigint`. Mirrors the `Number` API — pipeable `sum`, `multiply`, `subtract`, `divide`, `remainder`, `abs`, `sign`, `clamp`, `between`. Additional math: `BigInt.gcd`, `BigInt.lcm`, `BigInt.sqrt`/`sqrtUnsafe`. Safe conversions: `BigInt.toNumber` → `Option`, `BigInt.fromString` → `Option`, `BigInt.fromNumber` → `Option`. Ready-made reducers: `BigInt.ReducerSum`, `BigInt.ReducerMultiply`; combiners: `BigInt.CombinerMax`, `BigInt.CombinerMin`.

### [Pipeable](./data/functional-toolkit.md#pipeable)

`effect/Pipeable` — stable

The mixin that gives an object a `.pipe(...)` method, enabling `value.pipe(f, g, h)` fluent style. Many object-based Effect types implement this; primitive brands such as `ByteSize` are plain bigints and use module functions or `pipe(value, ...)`. Extend `Pipeable.Class` or mix in `Pipeable.Mixin(Base)` to add `.pipe` to your own types. `Pipeable.pipeArguments` is the internal dispatch used by the `.pipe` implementation.

### [Symbol](./data/functional-toolkit.md#symbol)

`effect/Symbol` — stable

Provides `Symbol.isSymbol` (type guard), consistent with `Predicate.isSymbol`. It does not re-export a constructor alias; use `globalThis.Symbol` to construct symbols when the imported namespace shadows the global name.

### [RegExp](./data/functional-toolkit.md#regexp)

`effect/RegExp` — stable

Re-exports the global `RegExp` constructor, provides `RegExp.isRegExp` (type guard), and adds `RegExp.escape(string)` — escapes all regex metacharacters so a literal string can be safely embedded in a regex pattern.

### [UndefinedOr](./data/functional-toolkit.md#undefinedor)

`effect/UndefinedOr` — stable

Ergonomics for `A | undefined` without `Option` ceremony. Provides `UndefinedOr.map`, `UndefinedOr.match`, `UndefinedOr.getOrThrow`, `UndefinedOr.getOrThrowWith`, and `UndefinedOr.liftThrowable`. Bridges to `Combiner`/`Reducer`: `UndefinedOr.makeReducer(combiner)` and `UndefinedOr.makeReducerFailFast`.

### [Bytes](./data/functional-toolkit.md#bytes)

`effect/Bytes` — unstable

Small helpers for `Uint8Array`: `Bytes.concat(chunks)` joins chunks into one **new** array (it never aliases an input, even for zero or one chunk), `Bytes.Equivalence` compares byte by byte, and `Bytes.Order` sorts lexicographically by unsigned byte with a prefix before any longer sequence. Text and Base64/hex conversions stay in `TextEncoder`/`TextDecoder` and the `effect/encoding` modules below.

### [Base64](./data/functional-toolkit.md#base64)

`effect/encoding/Base64` — stable

Text codecs live under `effect/encoding`, one module per format. The three binary-to-text modules (`Base64`, `Base64Url`, `Hex`) share one shape: `encode` accepts a `Uint8Array` or a string and always succeeds; `decode` returns `Result<Uint8Array, EncodingError>`; `decodeString` decodes and then interprets the bytes as UTF-8, returning `Result<string, EncodingError>`. `decodeString` keeps a leading U+FEFF as part of the text instead of stripping it as a byte-order mark, so decoding then re-encoding returns the original bytes; the same holds for `Schema.StringFromBase64`, `StringFromBase64Url`, and `StringFromHex`. Trim it yourself when the payload is a file that may start with a BOM. There is no catch-all `Encoding` namespace — import the format you need.

### [Base64Url](./data/functional-toolkit.md#base64url)

`effect/encoding/Base64Url` — stable

The URL- and filename-safe alphabet (`-` and `_` instead of `+` and `/`, no padding), with the same `encode` / `decode` / `decodeString` trio. Use it for values that travel in query strings, cookies, or path segments. `Base64Url.encodePadded` keeps the `=` padding for consumers that require it, such as Go's `base64.URLEncoding`; `SchemaGetter.encodeBase64Url` takes the matching `padding` option. Decoding accepts unpadded (`Zg`) and fully padded (`Zg==`) input but rejects partial padding (`Zg=`) with an `EncodingError`.

### [Hex](./data/functional-toolkit.md#hex)

`effect/encoding/Hex` — stable

Hexadecimal with the same trio — `encode` writes lowercase, `decode` accepts either case and fails on an odd length or a non-hex character — plus `Hex.random(length)`, which returns a random lowercase hex string for identifiers such as correlation ids. `random` draws from `Math.random()`, so it is **not cryptographically secure** — never use it for tokens, secrets, or anything an attacker must not guess; for those, draw bytes with `randomBytes` from the [`SecureRandom`](./interfaces/cryptography.md#securerandom) service and pass them to `Hex.encode`. `length` is not validated: it is rounded *down* to a multiple of 8, so `Hex.random(10)` has 8 characters and `Hex.random(3)` is the empty string.

### [EncodingError](./data/functional-toolkit.md#encodingerror)

`effect/encoding/EncodingError` — stable

The single failure type shared by the format modules: a `Data.TaggedError` with `_tag: "EncodingError"`, a `kind` (`"Decode"` or `"Encode"`), the `module` that failed (`"Base64"`, `"Hex"`, and the configuration parsers [`"Toml"`, `"Json5"`, `"Jsonc"`](./concurrency/streaming-channels.md#json5), …), the offending `input`, and a human-readable `message`. `EncodingError.isEncodingError` narrows an `unknown` value. Because every `decode` returns a `Result`, you handle it with the [`Result`](./foundations/errors-option-result.md#result) combinators rather than with `Effect.catch`.

### [Inspectable](./data/functional-toolkit.md#inspectable)

`effect/Inspectable` — stable

Defines the `Inspectable` interface (`toJSON`, `toString`, `[NodeInspectSymbol]`) and a `BaseProto`/`Class` you can extend to make custom types print correctly in the Node.js REPL, logs, and test output. `Inspectable.toJson` first applies redaction, invokes an inspectable `toJSON`, and recursively handles arrays; plain objects otherwise remain unchanged. It is a structured inspection representation, not a promise that `JSON.stringify` can accept every nested value or cycle. String rendering uses `Formatter`.

### [Types](./data/functional-toolkit.md#types)

`effect/Types` — stable

Type-level utilities — no runtime code. Commonly encountered:

### [Utils](./data/functional-toolkit.md#utils)

`effect/Utils` — stable

Advanced plumbing for libraries that implement Effect-style generator syntax; it is not a general application utility bag. `SingleShotGen<T, A>` is the one-yield iterator used to make a custom value work with `yield*`. The type-only `Variance` and `Gen<F>` encode environment, output, and error variance for a `TypeLambda`, which is how `Effect.gen`, `Option.gen`, and `Result.gen` infer the values yielded by their generators.

### [Unify](./data/functional-toolkit.md#unify)

`effect/Unify` — stable

A type-level mechanism that collapses a union of Effect-like types (e.g., `Effect<A> | Effect<B>`) into a single unified `Effect`. Makes `yield*` in `Effect.gen` work correctly across conditional branches returning different Effect types.

### [HKT](./data/functional-toolkit.md#hkt)

`effect/HKT` — stable

Higher-Kinded Types for TypeScript, encoded via the defunctionalisation trick. TypeScript has no native HKT support, so Effect uses a `TypeLambda` interface as a "type function" mapping variance parameters to a concrete type via `Kind<F, In, Out2, Out1, Target>`.

## [Schema](./data/schema.md)

Schema essentials: decoding and encoding, Type versus Encoded, structs, unions, refinements, transformations, brands, defaults, and classes.

Effect v4 rebuilt Schema around a single `Codec` abstraction: a two-way, validating, possibly-effectful bridge between two TypeScript types. `Type` is the decoded, in-memory value; `Encoded` is the wire/storage shape. `decode` goes Encoded → Type (with validation); `encode` goes Type → Encoded. `Schema.String` is the degenerate case (both sides `string`); `Schema.FiniteFromString` (`Encoded = string`, `Type = number`) is the usual numeric boundary. Satellite modules — `SchemaParser`, `SchemaIssue`, `SchemaGetter`, `SchemaTransformation`, `SchemaRepresentation` — are the implementation; `Schema` is the interface.

### [Schema](./data/schema.md#schema-1)

`effect/Schema` — stable

The core module: declare data shape and validation; get back a value that is simultaneously a type-level description (`Type` and `Encoded`), a runtime validator, a two-way codec, and a seed for derived artifacts (JSON Schema, arbitraries, equivalence, formatters).

Sections: [1. Decoding and encoding — pick your result style](./data/schema.md#1-decoding-and-encoding-pick-your-result-style) · [2. Type vs Encoded — the distinction that runs everything](./data/schema.md#2-type-vs-encoded-the-distinction-that-runs-everything) · [3. Structs, the workhorse](./data/schema.md#3-structs-the-workhorse) · [4. Unions, literals, records, tuples](./data/schema.md#4-unions-literals-records-tuples) · [5. Refinements — `check` and `refine`](./data/schema.md#5-refinements-check-and-refine) · [6. Transformations — `decodeTo` + getters](./data/schema.md#6-transformations-decodeto-getters) · [7. Branded schemas](./data/schema.md#7-branded-schemas) · [8. Default values](./data/schema.md#8-default-values) · [9. Classes and tagged errors](./data/schema.md#9-classes-and-tagged-errors)

## [Schema in Depth](./data/schema-in-depth.md)

Schema at real boundaries: annotations, serialization codecs, recursive schemas, construction fallbacks, parse options, optional fields, error messages, and effectful schemas.

This page continues the [Schema](./data/schema.md) guide past the everyday codec work. It covers what you reach for once a schema owns a real boundary: annotations and derived artifacts, serialization codecs, recursive and custom schemas, deliberate construction fallbacks, parse options as boundary policy, optional fields and `null`, Effect data types on the wire, custom error messages, and schemas that need services. Every section builds on the `Type` / `Encoded` model from the main page; the lower-level modules behind it are on [Schema Tooling & Internals](./data/schema-tooling.md).

### [1. Annotations and derivations](./data/schema-in-depth.md#1-annotations-and-derivations)

`annotate` attaches metadata (title, description, examples, custom keys) that flows into JSON Schema, error messages, and docs. Derivations from the same schema object: `Arbitrary.schema` (native property-test generator, from `effect/Arbitrary`), `toEquivalence` (structural equality), `toFormatter` (pretty-printer), `toStandardSchemaV1` (Standard Schema interop), `toJsonSchemaDocument`.

### [2. Serialization codecs](./data/schema-in-depth.md#2-serialization-codecs)

Boundary formats are codecs, not ad-hoc `JSON.stringify` calls. `fromJsonString(schema)` parses JSON text and then validates the parsed value; `fromFormData(schema)` and `fromURLSearchParams(schema)` do the same for browser form and query-string containers. In the other direction, derive a canonical representation with `toCodecJson`, `toCodecStringTree`, or `toCodecIso`.

### [3. Recursive and custom schemas](./data/schema-in-depth.md#3-recursive-and-custom-schemas)

Use `Schema.suspend(() => schema)` to make a recursive edge lazy. Recursive declarations are the main case where an explicit `Schema.Codec<Type, Encoded>` annotation is useful because TypeScript cannot infer a self-reference safely. For an otherwise unsupported runtime type, use `Schema.declare(guard, annotations?)`; use `declareConstructor` when the custom type itself is parameterized by child schemas. Prefer `Schema.instanceOf` for ordinary class-instance checks.

### [4. Construction and deliberate fallbacks](./data/schema-in-depth.md#4-construction-and-deliberate-fallbacks)

**Construction is not decoding.** `make`, `makeOption`, `makeEffect`, and class `new` take the decoded `Type` (after constructor defaults) and run checks; they never turn an encoded string into a transformed value, so `Schema.FiniteFromString.make` wants a number. Decode wire input; construct in already-trusted code.

### [5. Parse options are boundary policy](./data/schema-in-depth.md#5-parse-options-are-boundary-policy)

A schema describes a shape; parse options describe how *this boundary* wants that shape parsed. **Keep them at the call site, not in the schema**, so one schema can back a strict ingress and a tolerant reader without being duplicated.

### [6. Optional fields, null, and Option](./data/schema-in-depth.md#6-optional-fields-null-and-option)

A field specification must answer five input states: key absent, present `undefined`, present `null`, present valid, present invalid (always a failure). The helpers differ in exactly those cells.

### [7. Effect data types at the boundary](./data/schema-in-depth.md#7-effect-data-types-at-the-boundary)

**Two steps, not one.** The constructors for Effect's own data types — `Schema.Option`, `Schema.Result`, `Schema.Exit`, `Schema.ReadonlyMap`, `Schema.ReadonlySet`, `Schema.HashMap`, `Schema.HashSet`, `Schema.Duration`, `Schema.Redacted` — take the *runtime value* on both sides and apply the inner schemas only to the contents. The wire form is a separate, explicit step: `Schema.toCodecJson(schema)`.

### [8. Custom error messages](./data/schema-in-depth.md#8-custom-error-messages)

Messages are plain annotations on the node that fails. The default formatters honor them first and fall back to generated text.

### [9. Effectful schemas and services](./data/schema-in-depth.md#9-effectful-schemas-and-services)

A getter may do asynchronous work or `yield*` a service. The service then appears in the schema's `DecodingServices` (or `EncodingServices`) and flows into the `R` of `decodeUnknownEffect`, where a layer satisfies it. **An effectful schema needs an Effect runner** ([section 1 of Schema](./data/schema.md#1-decoding-and-encoding-pick-your-result-style)).

**Reach for it when** you need to validate, parse, serialize, or describe data crossing any boundary.

## [Schema Tooling & Internals](./data/schema-tooling.md)

Schema internals and tooling: SchemaAST, parsers and compilers, getters, transformations, issues, SchemaError, JSON Schema, Standard Schema, JSON Patch, models, and TestSchema.

The modules behind [Schema](./data/schema.md): the AST every schema compiles to, the parser and its ahead-of-time and JIT compilers, getters and transformations as plain data, schema representations, the issue tree and `SchemaError`, JSON Schema and Standard Schema adapters, JSON Patch and Pointer, data models, and `TestSchema`. Most applications use these indirectly; read a section when you generate artifacts from schemas, write tooling, or need to understand a failure at the issue level.

### [SchemaAST](./data/schema-tooling.md#schemaast)

`effect/SchemaAST` — stable

The introspectable tree behind every schema. Each `Schema` has an `.ast`: a discriminated-union node (`String`, `Number`, `Literal`, `Objects`, `Arrays`, `Union`, `Suspend`, `Declaration`, …) carrying checks, annotations, encoding links, and parse context. This layer makes derivation possible — JSON Schema, arbitraries, equivalence, and the parser all read the AST.

**Reach for it when** building tooling on top of schemas: custom JSON-Schema dialects, schema-driven UI generation, schema linters, or any code that reasons about a schema's structure rather than just runs it.

### [SchemaParser](./data/schema-tooling.md#schemaparser)

`effect/SchemaParser` — stable

The AST-walking interpreter that runs a schema against a value. The `decode*`/`encode*`/`is`/`asserts` functions on the `Schema` module are thin re-exports of `SchemaParser`. `SchemaParser.run` walks the AST once and returns `Effect<A, SchemaIssue.Issue>`; every other function is that result re-clothed in a different type.

**Reach for it when** writing a custom `declare` codec and needing to decode/encode inner schemas, or building a low-level tool that wants the raw `Effect<A, Issue>` traversal. Day to day, call through `Schema`.

### [SchemaCompiler](./data/schema-tooling.md#schemacompiler)

`effect/schema/SchemaCompiler` — unstable

The shared registry that maps an exact `SchemaAST.AST` to a `CompiledDecoder`: a required `decodeEffect` (complete decoding with detailed issues) plus optional `is`, `decode`, `make`, and `makeEffect` operations. The JIT and AOT compilers are both clients of this registry; `SchemaCompiler.set(ast, decoder)` is the manual entry point, and `SchemaCompiler.invalid` / `SchemaCompiler.missing` are the sentinels a fast path returns for "rejected, ask the detailed decoder" and "no value produced".

**Reach for it when** you are writing a compiler or an integration that supplies decoders for specific ASTs. Application code normally goes through `SchemaJITCompiler` or `SchemaAOTCompiler` instead; a hand-written entry that disagrees with its schema silently changes what decodes.

### [SchemaJITCompiler](./data/schema-tooling.md#schemajitcompiler)

`effect/schema/SchemaJITCompiler` — unstable

Generates decoder source for a schema at runtime and installs it through `new Function`. Two entry points: the side-effect import `effect/schema/SchemaJITCompiler/enable` compiles every schema lazily on first use, and `SchemaJITCompiler.enable(schema.ast)` compiles one schema and its parsing dependencies.

**Reach for it when** profiling shows schema decoding on a hot path (high-volume ingestion, large payload arrays) in a runtime that allows `new Function`. Leave it off otherwise; results do not change, only speed.

### [SchemaAOTCompiler](./data/schema-tooling.md#schemaaotcompiler)

`effect/schema/SchemaAOTCompiler` — unstable

The build-time twin of the JIT compiler. `SchemaAOTCompiler.compile(targets)` returns the source of a static JavaScript module whose `install(asts)` export registers the generated decoders, so no code is constructed at runtime. The companion entrypoint `effect/schema/SchemaAOTCompiler/Build` exposes `build(options)`, which loads your schema modules, compiles their **direct** `Schema` exports, and writes a module that installs itself when imported. It needs `FileSystem` and `Path` and fails with `BuildError` or `PlatformError`.

**Reach for it when** you want compiled decoders where `new Function` is unavailable (strict CSP, locked-down runtimes) or you want no code generation at startup. It trades a build step and a regenerate-on-change rule for that.

### [SchemaGetter](./data/schema-tooling.md#schemagetter)

`effect/SchemaGetter` — stable

A `Getter<T, E, R>` is one direction of a conversion: takes an optional encoded value and returns an optional decoded value, possibly failing with an issue or requiring services. Getters are the atoms of the v4 transformation model.

**Reach for it when** defining a transformation and needing the decode or encode leg — especially for optional-field gymnastics (`transformOptional`), async checks (`checkEffect`), or built-in string/binary/JSON conversions.

### [SchemaTransformation](./data/schema-tooling.md#schematransformation)

`effect/SchemaTransformation` — stable

A `Transformation<T, E>` bundles both directions of a conversion — decode (E → T) and encode (T → E) — into one reusable value. Passed as the second argument to `decodeTo` when a clean two-way mapping exists.

**Reach for it when** a transformation has a clean, symmetric decode/encode pair and you want it as a single reusable value, or when a library prebuilt covers the case.

### [SchemaRepresentation](./data/schema-tooling.md#schemarepresentation)

`effect/SchemaRepresentation` — stable

A compiler and persistence pipeline for schema structure. A live `Document` holds a representation root plus shared references; unlike persisted JSON, it may still contain runtime compiler callbacks and non-JSON annotation values. `toJson` is the explicit storage/transport boundary.

**Reach for it when** you need code generation, JSON Schema compilation/import, or a deliberately persisted schema representation with shared references.

### [SchemaIssue](./data/schema-tooling.md#schemaissue)

`effect/SchemaIssue` — stable

The structured error tree produced when parsing fails. Leaf nodes: `InvalidType`, `InvalidValue`, `MissingKey`, `UnexpectedKey`, `Forbidden`, `OneOf`. Composite nodes: `Composite`, `Filter`, `Pointer`, `Encoding`, `AnyOf`. `SchemaError` (thrown/failed by runners) carries this tree in its `.issue` field.

**Reach for it when** you need to act on a validation failure: render field-level errors, build custom messages for rejected rows, localize messages, or pattern-match issue tags to react differently to distinct failure kinds.

### [Schema.SchemaError](./data/schema-tooling.md#schema-schemaerror)

`effect/Schema` — stable

The public error wrapper used by the high-level `Schema.decode*` and `Schema.encode*` adapters. `Schema.SchemaError` is tagged `"SchemaError"` and carries the raw `SchemaIssue.Issue` in `.issue`; its `.message` applies the default formatter. `Schema.isSchemaError` safely recognizes it, including across duplicated package copies. It lives in the `Schema` namespace; there is no standalone `effect/SchemaError` module.

**Reach for it when** you need to detect, transport, or explicitly format high-level schema failures. Reach for raw `SchemaIssue.Issue` via `SchemaParser` when implementing codecs or issue-tree tooling.

### [JsonSchema](./data/schema-tooling.md#jsonschema)

`effect/JsonSchema` — stable

Derive a JSON Schema document from any `Schema` and normalize/convert between JSON Schema dialects (Draft-07, Draft 2020-12, OpenAPI 3.0/3.1). `Schema.toJsonSchemaDocument` produces the document; this module handles dialect plumbing (`$ref` resolution, OpenAPI component keys, cross-dialect conversion). Annotations (`description`, `title`, custom keys via `includeAnnotationKey`) flow into output.

**Reach for it when** you need a machine-readable *value* contract for external consumers: JSON Schema config validation, cross-language codegen of a payload, or structured-output LLM prompting. For an HTTP API description, generate OpenAPI from `HttpApi` instead.

### [StandardSchema](./data/schema-tooling.md#standardschema)

`effect/StandardSchema` — stable

The **type definitions** of the [Standard Schema](https://standardschema.dev) V1 specification — `StandardSchemaV1`, `StandardTypedV1`, and the experimental `StandardJSONSchemaV1` — vendored verbatim so `effect` no longer depends on `@standard-schema/spec`. The module is types only; the conversion lives on `Schema`.

**Reach for it when** a third-party library asks for a Standard Schema and you want your Effect schema to remain the single source of truth.

### [JsonPatch](./data/schema-tooling.md#jsonpatch)

`effect/JsonPatch` — stable

Compute and apply deterministic diffs over JSON values. A `JsonPatch` is an ordered list of `add`/`remove`/`replace` operations addressed by JSON Pointer paths (deterministic subset of RFC 6902). `get(oldValue, newValue)` produces the patch; `apply(patch, value)` replays it without mutating the input. `apply` throws on a malformed JSON Pointer escape (`/a~2`, or a trailing `~`) rather than treating it as a literal key. For line- or character-level diffs of text, see [TextDiff](./data/functional-toolkit.md#textdiff).

**Reach for it when** syncing state across a wire and wanting minimal diffs, or when needing an auditable record of exactly how structured data changed.

### [JsonPointer](./data/schema-tooling.md#jsonpointer)

`effect/JsonPointer` — stable

The RFC 6901 conversions underlying `JsonPatch` paths and JSON Schema `$ref`s. `escapeToken` encodes `~`→`~0` and `/`→`~1`; `unescapeToken` reverses it. `formatUriFragment(path)` and `parseUriFragment(fragment)` convert a whole token path to and from the `#/...` URI-fragment form, adding percent-encoding; parsing returns `undefined` for a malformed fragment.

**Reach for it when** building or parsing JSON Pointer paths by hand, particularly for keys containing slashes or tildes.

### [Model](./data/schema-tooling.md#model)

`effect/schema/Model` — unstable

Define a domain model once and derive operation-specific variants: `select`, `insert`, `update` (database-facing) and `json`, `jsonCreate`, `jsonUpdate` (API-facing). Field declaration helpers encode per-variant behavior: `Model.GeneratedByDb` (omit on insert, present on select), `Model.DateTimeInsertFromDate` (set on insert), `Model.DateTimeUpdateFromDate` (set on update), `Model.Sensitive` (hidden from JSON), `Model.FieldOption` (nullable column ↔ `Option`).

**Reach for it when** persisted shape, write shape, and public API shape diverge — almost any real domain entity. Natural companion to the SQL modules: `Employee.insert` is exactly the schema an insert query wants.

### [VariantSchema](./data/schema-tooling.md#variantschema)

`effect/schema/VariantSchema` — unstable

The general "one definition, many variants" mechanism that `Model` is built on. `VariantSchema.make({ variants, defaultVariant })` produces a toolkit — `Struct`, `Class`, `Union`, `Field`, `FieldOnly`, `FieldExcept`, `fieldEvolve`, `extract` — specialized to your variant names. `Model` is `VariantSchema.make({ variants: ["select","insert","update","json","jsonCreate","jsonUpdate"], defaultVariant: "select" })`.

**Reach for it when** you need `Model`'s "derive many shapes from one" power with a different set of variants than the built-in DB/JSON ones.

### [Testing schemas with TestSchema](./data/schema-tooling.md#testing-schemas-with-testschema)

`effect/testing/TestSchema` — unstable

Assertion helpers for testing schemas. `new TestSchema.Asserts(schema)` groups checks: decoding succeeds/fails as expected, encoding round-trips, `make` behaves, and the derived arbitrary generates valid values. `Decoding` and `Encoding` are also exported standalone.

**Reach for it when** writing tests for schemas — especially custom transformations and refinements. `verifyGeneration(options?)` runs a native `Arbitrary.checkEffect` property (20 runs by default) that generated values satisfy `Schema.is`; `verifyRoundTrip(options?)` (with an Effect-returning `verifyRoundTripEffect` twin) checks decode∘encode round trips. Both take `Arbitrary.CheckOptions` (`{ seed, runs, maxDiscards, maxShrinks, replay }`) directly, bound unsuccessful generation, and report the shrunk input and replay token on failure. `decoding().fail(input, message)` pins down error messages; `decoding().failEffect` / `encoding().succeedEffect` / `encoding().failEffect` are the lazy-`Effect` twins of `fail` / `succeed`.

# Runtime Services

## [Observability](./operations/observability.md)

Instrumentation: designing signals, structured logging, log levels, formatting, spans and tracing, and metrics.

This page covers instrumentation. Getting signals out of the process — OTLP, Prometheus, DevTools, and the OpenTelemetry SDK bridge — is on [Telemetry Export](./operations/telemetry-export.md).

### [Designing signals](./operations/observability.md#designing-signals)

Instrumentation is a design decision before it is an API call: every signal costs storage, exposes data, and needs an owner. Start from the question an operator will ask, pick the signal that answers it, and write its contract down before adding code.

Sections: [Which signal answers which question](./operations/observability.md#which-signal-answers-which-question) · [Cardinality: names and attribute sets are bounded](./operations/observability.md#cardinality-names-and-attribute-sets-are-bounded) · [Privacy: allow-list fields before they are buffered](./operations/observability.md#privacy-allow-list-fields-before-they-are-buffered) · [Telemetry is not readiness, liveness, or an audit log](./operations/observability.md#telemetry-is-not-readiness-liveness-or-an-audit-log)

### [Logger](./operations/observability.md#logger)

`effect/Logger` — stable

A `Logger<Message, Output>` receives a log event (message, level, cause, fiber, timestamp, annotations, log spans) and produces output. The runtime calls every installed logger for every event. Multiple loggers run simultaneously; install with `Logger.layer([...])`.

Sections: [The built-in loggers](./operations/observability.md#the-built-in-loggers) · [Installing and swapping loggers](./operations/observability.md#installing-and-swapping-loggers) · [Logging practice](./operations/observability.md#logging-practice) · [Structured log calls and annotations — merit-cycle run](./operations/observability.md#structured-log-calls-and-annotations-merit-cycle-run) · [Keeping secrets masked in log payloads](./operations/observability.md#keeping-secrets-masked-in-log-payloads) · [Custom loggers — redacting PII](./operations/observability.md#custom-loggers-redacting-pii)

**Reach for it when** swapping log format, adding a file sink, shipping logs to a remote aggregator, or adding a redaction backstop on top of Effect's structured log events.

### [LogLevel](./operations/observability.md#loglevel)

`effect/LogLevel` — stable

`LogLevel` is the union `"All" | "Fatal" | "Error" | "Warn" | "Info" | "Debug" | "Trace" | "None"`, plus helpers `LogLevel.Order`, `isGreaterThan`, `isEnabled`, and ordinal comparison. The runtime compares each event's level against `References.MinimumLogLevel` before dispatching to any logger.

Sections: [Scoping and configuring the minimum level](./operations/observability.md#scoping-and-configuring-the-minimum-level)

**Reach for it when** adjusting log verbosity for a specific scope, comparing levels programmatically, or setting a global minimum via config.

### [Console](./operations/observability.md#console)

`effect/Console` — stable

A service wrapping the browser/Node.js `console` object. Every method (`Console.log`, `Console.error`, `Console.warn`, `Console.group`, `Console.time`, etc.) returns `Effect<void>`. The `Console` reference in context can be swapped for testing.

**Reach for it when** you need testable console output or mix Effect with raw console calls in a CLI tool.

### [Formatter](./operations/observability.md#formatter)

`effect/Formatter` — stable

Value-formatting utility. `format(input)` applies a value's `Redactable` representation before pretty-printing arbitrary values (handles cycles, `BigInt`, typed arrays, class instances). `formatJson(input)` uses JSON semantics with the same redaction precedence, serializes a `bigint` as a quoted string with its `n` suffix, and omits circular object properties; other unsupported JSON values retain the normal `JSON.stringify` behavior. Also provides `formatDate`, `formatPath`, `formatPropertyKey`. Used internally by built-in loggers to render log messages and annotation values. When formatting an `Error`, `format` appends its `cause` — including a defined falsy one such as `0`, `false`, `""`, or `null` (`Error: band lookup failed (cause: 0)`); only a missing or `undefined` cause is omitted.

**Reach for it when** building a custom logger that needs to render Effect values consistently with the default logger, or for cycle-safe pretty-printing outside a logging context.

### [Tracer](./operations/observability.md#tracer)

`effect/Tracer` — stable

Low-level tracing model. A `Tracer` service creates `Span` objects when the runtime forks or executes traced operations. Each `Span` records name, parent, `SpanKind`, attributes, links, events, start/end time (as `bigint` nanoseconds), and whether it was sampled. Drive it through higher-level Effect APIs and swap the backend via layer.

Sections: [Core tracing APIs — wrapping a merit-calculation run](./operations/observability.md#core-tracing-apis-wrapping-a-merit-calculation-run) · [What ends up on a span](./operations/observability.md#what-ends-up-on-a-span) · [Span and correlation rules](./operations/observability.md#span-and-correlation-rules) · [Effect.fn traces automatically](./operations/observability.md#effect-fn-traces-automatically) · [Span links — fan-in across approval steps](./operations/observability.md#span-links-fan-in-across-approval-steps)

**Reach for it when** implementing a custom tracer backend, bridging an external trace context, or tuning sampling. For day-to-day use, `Effect.withSpan` and `Effect.fn` suffice.

### [Metric](./operations/observability.md#metric)

`effect/Metric` — stable

Typed, composable metrics registry. Define counters, gauges, histograms, summaries, and frequency maps as values; update them anywhere; read or export state. Metrics are stored in a registry keyed by name + attributes — the same metric referenced from different modules accumulates to the same series.

Sections: [The five metric types](./operations/observability.md#the-five-metric-types) · [Tracking effects with metrics](./operations/observability.md#tracking-effects-with-metrics) · [Gauges that follow a lifetime](./operations/observability.md#gauges-that-follow-a-lifetime) · [Tagging metrics at call sites — per-department breakdown](./operations/observability.md#tagging-metrics-at-call-sites-per-department-breakdown) · [Runtime metrics](./operations/observability.md#runtime-metrics)

**Reach for it when** tracking throughput, budget drawdown, raise distributions, or any numeric signal. Pair with `OtlpMetrics` or `PrometheusMetrics` to export.

## [Telemetry Export](./operations/telemetry-export.md)

Exporting telemetry: choosing an export path, OTLP exporters, Prometheus, Effect DevTools, and the OpenTelemetry Node and Web SDK bridge.

Getting logs, spans, and metrics out of the process. Instrumentation stays in business code ([Observability](./operations/observability.md)); export is a Layer chosen once per process. This page covers choosing and owning an export path, Effect's native OTLP exporters, the OTLP proxy for browser telemetry, Prometheus, the Effect DevTools, and the bridge to the OpenTelemetry Node and Web SDKs.

### [Choosing and owning an export path](./operations/telemetry-export.md#choosing-and-owning-an-export-path)

Instrumentation lives in business code; export is a Layer decision made once per process. The decisions below are about ownership — which component exports each signal, in what order it starts, who samples, and how long shutdown may wait.

Sections: [One export path per signal](./operations/telemetry-export.md#one-export-path-per-signal) · [Layer order and shutdown](./operations/telemetry-export.md#layer-order-and-shutdown) · [Sampling has one owner per path](./operations/telemetry-export.md#sampling-has-one-owner-per-path) · [Verifying telemetry](./operations/telemetry-export.md#verifying-telemetry)

### [Otlp](./operations/telemetry-export.md#otlp)

`effect/observability/Otlp` — unstable

All-in-one OTLP layer. Wires `OtlpLogger`, `OtlpMetrics`, and `OtlpTracer` from a single config, posting to `/v1/logs`, `/v1/metrics`, and `/v1/traces` under a shared `baseUrl`.

**Reach for it when** you want a single layer for logs + metrics + traces with zero boilerplate. Recommended starting point for new projects.

### [OtlpLogger](./operations/telemetry-export.md#otlplogger)

`effect/observability/OtlpLogger` — unstable

An Effect `Logger` that serializes log records as OTLP log records and ships them via HTTP. Includes log level, message, annotations, cause, fiber id, and current trace/span ids. Batches are flushed on scope finalization to prevent log loss on graceful shutdown.

**Reach for it when** exporting only logs, or assembling a custom observability stack per signal.

### [OtlpMetrics](./operations/telemetry-export.md#otlpmetrics)

`effect/observability/OtlpMetrics` — unstable

Periodically reads the Effect metric registry and posts snapshots to an OTLP metrics endpoint. Supports `"cumulative"` and `"delta"` aggregation temporality.

**Reach for it when** using metrics only, or assembling a custom per-signal stack.

### [OtlpTracer](./operations/telemetry-export.md#otlptracer)

`effect/observability/OtlpTracer` — unstable

Replaces the Effect runtime's `Tracer` with one that batches and exports finished spans over OTLP/HTTP. Spans include trace and span IDs, parent links, attributes, events, timing, kind, and status — `ERROR` for a failure or defect, otherwise `Unset`, including on success (see [What ends up on a span](./operations/observability.md#what-ends-up-on-a-span)).

**Reach for it when** exporting traces only, or composing a custom per-signal observability stack.

### [OtlpExporter](./operations/telemetry-export.md#otlpexporter)

`effect/observability/OtlpExporter` — unstable

Shared batch-export engine used internally by `OtlpLogger`, `OtlpMetrics`, and `OtlpTracer`. Buffers items, posts encoded batches at a configurable interval, retries transient errors, honors HTTP 429 `Retry-After`, temporarily disables export after repeated failures (60 s backoff), and flushes on scope close. Typically not used directly.

**Reach for it when** implementing a custom OTLP signal type that needs the same batching, retry, and graceful-shutdown behaviour as the built-in exporters.

### [OtlpResource](./operations/telemetry-export.md#otlpresource)

`effect/observability/OtlpResource` — unstable

Builds the OTLP `Resource` object (service name, version, arbitrary attributes) attached to every exported signal. `OtlpResource.make({ serviceName, serviceVersion, attributes })` returns a `Resource`; `fromConfig` reads from a config record. Helpers `entriesToAttributes` and `unknownToAttributeValue` convert JS values to OTLP `KeyValue`/`AnyValue`; an integer outside the signed 64-bit range becomes a `doubleValue` (numbers) or `stringValue` (bigints) so collectors do not reject the batch, and `NaN`/`Infinity` are no longer written as `null` by `OtlpSerialization.layerJson`. `fromConfig` trims and percent-decodes `OTEL_RESOURCE_ATTRIBUTES` keys and values, keeps an entry with an empty value as `""`, skips entries without `=` or with an empty key, and lets the last repeated key win; invalid percent-encoding is a defect.

**Reach for it when** building a custom OTLP exporter that needs standard resource metadata, or inspecting how Effect maps JS values to OTLP attribute types.

### [OtlpSerialization](./operations/telemetry-export.md#otlpserialization)

`effect/observability/OtlpSerialization` — unstable

A `Context.Service` class with three methods — `traces(data)`, `metrics(data)`, `logs(data)` — that convert in-memory OTLP data structures to `HttpBody` instances. Two implementations: `OtlpSerialization.layerJson` (JSON, default) and `OtlpSerialization.layerProtobuf` (binary protobuf, `application/x-protobuf`).

**Reach for it when** choosing or swapping serialization format, or writing a custom signal exporter in the same service graph.

### [OtlpProxy](./operations/telemetry-export.md#otlpproxy)

`effect/observability/OtlpProxy` — unstable

Forwards browser OTLP exports through your own HTTP server, so vendor credentials stay on the server and the browser exports to its own origin. `OtlpProxy.layer({ baseUrl, headers?, prefix?, signals?, urls?, maxBodySize?, timeout? })` mounts `POST <prefix>/v1/traces`, `/v1/logs`, and `/v1/metrics` on the `HttpRouter` in context and requires an `HttpClient`; `layerFromConfig` reads each upstream from `OTEL_EXPORTER_OTLP_<SIGNAL>_ENDPOINT` / `OTEL_EXPORTER_OTLP_ENDPOINT` and headers from the matching `*_HEADERS` (a signal without an endpoint gets no route); `make` returns the three handlers for mounting elsewhere, such as an `HttpApi` endpoint.

**Reach for it when** a browser or other untrusted client must export OTLP to a vendor or collector that needs credentials or another origin.

### [PrometheusMetrics](./operations/telemetry-export.md#prometheusmetrics)

`effect/observability/PrometheusMetrics` — unstable

Renders the Effect metric registry in Prometheus exposition format (text/plain version 0.0.4). `PrometheusMetrics.format()` returns `Effect<string>`; `PrometheusMetrics.layerHttp()` registers a `GET /metrics` route on the `HttpRouter` service in context.

**Reach for it when** running a Prometheus-compatible stack (Prometheus + Grafana, Victoria Metrics, etc.) and want metrics scraped via a pull endpoint.

### [DevTools](./operations/telemetry-export.md#devtools)

`effect/devtools/DevTools` — unstable

Application-side entry point for connecting to the Effect DevTools desktop app. `DevTools.layer(url?)` opens a WebSocket to `ws://localhost:34437` (or a custom URL) and mirrors spans and metric snapshots to the DevTools process. Zero configuration required for local development. The client sends a `Ping` as soon as it connects, retries a failed or dropped connection every second (logging failures at `Debug`), so the DevTools app may start after the program, and on shutdown stops pending connections while still flushing telemetry queued on a healthy one. Spans that have already ended send no further events.

**Reach for it when** visually inspecting fiber topology, span trees, and live gauge values during development without setting up a collector.

### [DevToolsClient](./operations/telemetry-export.md#devtoolsclient)

`effect/devtools/DevToolsClient` — unstable

Low-level socket protocol layer underneath `DevTools`. Drives the NDJSON duplex channel, queues `Ping` heartbeats, sends span starts/events/completions, responds to `MetricsRequest` messages by snapshotting the metric registry, and exposes `DevToolsClient.layerTracer` which installs a tracer that wraps the existing tracer and forwards events to the socket.

**Reach for it when** building a custom DevTools integration or embedding the DevTools protocol into a different transport (e.g. TCP socket, Unix pipe).

### [DevToolsServer](./operations/telemetry-export.md#devtoolsserver)

`effect/devtools/DevToolsServer` — unstable

Server-side half of the DevTools protocol. `DevToolsServer.run` accepts a `Client` (a socket connection from a connected Effect application) and drives the conversation: receives span and metric data, sends metric snapshot requests and pong responses. Used by the Effect DevTools desktop app itself; not typically used in application code.

### [DevToolsSchema](./operations/telemetry-export.md#devtoolsschema)

`effect/devtools/DevToolsSchema` — unstable

Schema definitions for the DevTools wire protocol — `Span`, `SpanEvent`, `Ping`/`Pong`, `MetricsRequest`, `MetricsSnapshot`, and the `Request`/`Response` discriminated unions. Both client and server use these schemas to encode/decode NDJSON frames over the WebSocket.

### [OtelNodeSdk](./operations/telemetry-export.md#otelnodesdk)

Bridge between Effect and the official OpenTelemetry Node.js SDK. `NodeSdk.layer(config)` accepts a lazy config factory (or an Effect) returning a `Configuration` object, and installs tracing (`spanProcessor`), metrics (`metricReader`), and logging (`logRecordProcessor`) based on which are present. Always provides `Resource.Resource`, reading from `OTEL_*` environment variables plus any explicit resource metadata.

**Reach for it when** your platform team manages an OTel SDK setup, you need OTel-native auto-instrumentation (HTTP, gRPC, DB drivers), or integrating with a service that uses `@opentelemetry/sdk-node`.

### [OtelWebSdk](./operations/telemetry-export.md#otelwebsdk)

Browser equivalent of `NodeSdk`. Structurally identical API — pass `spanProcessor`, `metricReader`, `logRecordProcessor` — but uses the OTel *web* tracer provider. Use in browser bundler targets where `NodeSdk` would pull in Node-only internals.

**Reach for it when** running Effect in a browser and bridging into an existing OTel web SDK setup.

### [OtelTracer](./operations/telemetry-export.md#oteltracer)

Effect↔OTel tracer bridge. `OtelTracer.layer` installs an Effect `Tracer` that creates `OtelSpan` instances backed by the active OTel `TracerProvider`. Exposes `OtelTracer`, `OtelTracerProvider`, `OtelTraceFlags`, `OtelTraceState` services, and `currentOtelSpan` to retrieve the live OTel span from fiber context. When an Effect span ends, the bridge sets `ERROR` only for a failure or defect; on success or interruption it leaves the status alone, so a status you set on the span from `currentOtelSpan` is what gets exported (otherwise `Unset`).

**Reach for it when** composing Effect's span model with OTel-native span APIs (e.g. setting OTel-specific span status or accessing the raw OTel `Span` for a library that requires it).

### [OtelMetrics](./operations/telemetry-export.md#otelmetrics)

Bridges Effect's metric registry into an OTel `MetricReader`. `OtelMetrics.layer(evaluate, options?)` accepts a lazy factory returning a `MetricReader` or non-empty array of readers and registers a `MetricProducer` that converts Effect metric snapshots to OTel metric data on each collection cycle. Supports cumulative and delta temporality via the `temporality` option.

**Reach for it when** you have an existing OTel metric reader (Prometheus, OTLP push) managed by your platform team and want Effect's built-in metrics to flow into it.

### [OtelLogger](./operations/telemetry-export.md#otellogger)

An Effect `Logger` that forwards log records to an OTel `LoggerProvider`. `OtelLogger.layer({ mergeWithExisting })` installs it alongside or instead of the default logger. `OtelLogger.layerLoggerProvider` builds and scopes the OTel `LoggerProvider` from one or more `LogRecordProcessor`s.

**Reach for it when** Effect logs (including structured annotations) need to flow through an existing OTel logging pipeline, e.g. a `BatchLogRecordProcessor` shipping to a vendor.

### [OtelResource](./operations/telemetry-export.md#otelresource)

Provides the OTel `Resource` service used by all `@effect/opentelemetry` modules. `Resource.layer({ serviceName, serviceVersion, attributes })` builds from explicit config; `Resource.layerFromEnv(additionalAttributes?)` merges additional attributes with `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES` (read with `Config.Record`, so a structured config value works too; keys and values are percent-decoded, and a variable with invalid encoding is discarded with a warning); `Resource.layerEmpty` provides a minimal no-attribute resource. `NodeSdk.layer` and `WebSdk.layer` manage this automatically — only needed directly when composing individual OTel bridge layers.

**Reach for it when** composing individual `@effect/opentelemetry` bridge layers manually rather than using `NodeSdk` / `WebSdk`.

## [Caching & Batching](./operations/caching-batching.md)

Caching, request batching, resolvers, resource-aware memoization, and deduplicated data loading.

Caching avoids repeating the same lookup result; batching combines many logically independent requests into fewer physical calls. `Cache` stores both successful and failed lookup `Exit` values, while `ScopedCache` owns resource lifetimes. `Request` and `RequestResolver` describe data fetching so Effect can deduplicate and batch it safely.

### [Which problem do you have?](./operations/caching-batching.md#which-problem-do-you-have)

Repeated work shows up on a dashboard as "too many HRIS calls", but it has several shapes, and each tool fixes exactly one of them. Measure first — hit ratio, lookup count per request, resolver batch size — then pick the smallest tool.

### [Caching a single Effect](./operations/caching-batching.md#caching-a-single-effect)

`effect/Effect` — stable

`Effect.cached(effect)` has the type `Effect<Effect<A, E, R>>`: running the *outer* effect creates a memo cell and returns a handle; the first evaluation of the *handle* runs the work, and later and concurrent evaluations share that one stored `Exit`.

### [Cache](./operations/caching-batching.md#cache)

`effect/Cache` — stable

Effectful memoization table with bounded capacity and optional TTL. A lookup effect is provided at construction; the cache handles concurrent requests, LRU eviction, and TTL expiry. When several fibers ask for an absent key at once, the lookup runs once and all of them await its result.

Sections: [Keys are logical values](./operations/caching-batching.md#keys-are-logical-values) · [Key API surface](./operations/caching-batching.md#key-api-surface) · [Failure and freshness policy](./operations/caching-batching.md#failure-and-freshness-policy) · [Testing a cache deterministically](./operations/caching-batching.md#testing-a-cache-deterministically)

### [ScopedCache](./operations/caching-batching.md#scopedcache)

`effect/ScopedCache` — stable

`Cache` variant for entries that own resources. Each cached value gets its own `Scope`; on eviction, invalidation, or TTL expiry, that scope closes and all acquired resources are released. The cache itself lives inside an outer scope; closing it tears down every remaining entry.

### [Request](./operations/caching-batching.md#request)

`effect/Request` — stable

Typed, data-only description of one thing to fetch from a data source. A `Request<A, E>` is not an effect — it is a plain object carrying the input fields a resolver needs, plus phantom types for success (`A`) and error (`E`). Used by `RequestResolver` and `Effect.request` for batching and deduplication.

### [RequestResolver](./operations/caching-batching.md#requestresolver)

`effect/RequestResolver` — stable

Executes batches of `Request` values. Core job: receive an array of pending request entries, fetch data (ideally in one batch call), then call `entry.completeUnsafe(Exit.succeed/fail(...))` on each entry. Pairing with `Effect.request` collapses concurrent N+1 queries into a single round-trip.

Sections: [Resolver obligations](./operations/caching-batching.md#resolver-obligations) · [Resolver combinators](./operations/caching-batching.md#resolver-combinators) · [Testing a resolver](./operations/caching-batching.md#testing-a-resolver)

### [PrimaryKey](./operations/caching-batching.md#primarykey)

`effect/PrimaryKey` — stable

Tiny protocol: define `[PrimaryKey.symbol](): string` on a class or object to advertise a stable string identifier. Effect's persistence layer uses this key to store and retrieve serialized exits.

# Web & Integrations

## [HTTP Client](./interfaces/http-client.md)

Typed HTTP clients, requests, responses, middleware, retries, timeouts, scoped responses, cookies, tracing, and platform layers.

Effect 4 ships three stacked layers: a fully typed **HTTP client** (request as value, Schema-decoded response, built-in retries), a **low-level server** (router as Layer, middleware as function), and **HttpApi** — a schema-first API description that derives a server, a typed client, and OpenAPI/Swagger/Scalar docs from one definition, with the contract checked end-to-end at compile time.

### [HttpClient](./interfaces/http-client.md#httpclient)

`effect/http/HttpClient` — unstable

A service (`HttpClient.HttpClient`) representing the ability to execute an HTTP request. Acquire from context, decorate with policy, execute requests. Decorators (`mapRequest`, `filterStatusOk`, `retryTransient`, `followRedirects`, `withRateLimiter`) return a *new* client with that behavior baked in — configure once, every call inherits it.

Sections: [Retries, time budgets, and cancellation](./interfaces/http-client.md#retries-time-budgets-and-cancellation) · [Response lifetimes and `withScope`](./interfaces/http-client.md#response-lifetimes-and-withscope) · [Circuit breaking](./interfaces/http-client.md#circuit-breaking) · [User-controlled destinations](./interfaces/http-client.md#user-controlled-destinations)

**Reach for it when** you call any HTTP service and want retries, decoding, tracing, and a clean domain API instead of raw `fetch`.

### [FetchHttpClient](./interfaces/http-client.md#fetchhttpclient)

`effect/http/FetchHttpClient` — unstable

The `fetch`-backed `HttpClient` implementation. Provide `FetchHttpClient.layer` anywhere a client is needed. Works in browsers, serverless, Node, Bun, and Deno. Swap the underlying `fetch` via `FetchHttpClient.Fetch` (tests or custom agent); set default `RequestInit` options via `FetchHttpClient.RequestInit`.

**Reach for it when** you want the portable, zero-dependency client — which is most of the time. Use `NodeHttpClient`/`BunHttpClient` only when you need native streaming or connection-pool control.

### [HttpClientRequest](./interfaces/http-client.md#httpclientrequest)

`effect/http/HttpClientRequest` — unstable

An immutable request description built with combinators. Start from a verb (`get`, `post`, `put`, `patch`, `delete`, `head`, `options`, `query`) and pipe on URL pieces, query params, headers, auth, and a body. Nothing executes until a client runs it.

Sections: [Request compression and native connections](./interfaces/http-client.md#request-compression-and-native-connections)

**Reach for it when** a request needs more than a URL, or when you want a reusable request transform.

### [HttpClientResponse](./interfaces/http-client.md#httpclientresponse)

`effect/http/HttpClientResponse` — unstable

Typed wrapper around a raw response, plus decoders. `schemaBodyJson(schema)` reads the body, parses JSON, and validates against a Schema in one effectful step. Transport/body-read/JSON failures are `HttpClientError`; a value that parses as JSON but violates the schema is `SchemaError`. `schemaJson` (decode status + headers + body together) has the same union. Also: `filterStatusOk`/`filterStatus`, `matchStatus` (branch on status code), and `stream` for incremental consumption.

**Reach for it when** you need decoded, validated data or status-aware branching from a response.

### [HttpClientError](./interfaces/http-client.md#httpclienterror)

`effect/http/HttpClientError` — unstable

Tagged error family on the client's error channel. Each carries the request (and often the response) for context:

Sections: [Three failure classes](./interfaces/http-client.md#three-failure-classes)

**Reach for it when** you need to distinguish network failures, 404s, and Schema mismatches and handle each differently.

## [HTTP Server](./interfaces/http-server.md)

HTTP servers, routers, incoming messages, multipart handling, static files, and host integrations.

**Mental shift:** a router is a Layer, a handler is an Effect, and middleware is a function from one app-effect to another. Build routes as Layers, merge them, serve with a platform-specific server Layer. Most production apps use the separate [HttpApi topic](./interfaces/http-api.md); this layer is right for webhooks, health checks, file exports, and anything without a schema contract.

### [FindMyWay](./interfaces/http-server.md#findmyway)

`effect/http/FindMyWay` — unstable

The mutable radix-tree engine under `HttpRouter`. `make<A>()` creates a router; `on(methods, path, handler)` and `all(path, handler)` register values; `find(method, url)` returns the handler plus decoded path and search parameters, while `has` only tests a route. Options control trailing/duplicate slash handling, case sensitivity, and maximum parameter length.

### [HttpEffect](./interfaces/http-server.md#httpeffect)

`effect/http/HttpEffect` — unstable

The adapter boundary between an Effect HTTP application and a host. `toWebHandler(app)` produces a Web `(Request) => Promise<Response>` handler; `toWebHandlerLayer(layer)` builds the dependency Layer **immediately** when the handler is created and returns `{ handler, dispose }`. A request that arrives mid-build waits for it; if the build fails, every request rejects with the build error instead of surfacing an unhandled rejection. Eager construction moves cold-start cost to module load and makes a misconfigured deployment fail its first health check rather than its first user. `fromWebHandler` adapts an existing Web handler back into the current Effect request. The lower-level `toHandled` owns request scopes, applies middleware and pre-response hooks, and converts failures into responses — on a handler failure, the request `Scope` still closes with the original cause, so a scope finalizer or middleware can tell a failed request from a successful one even after it's been turned into a response.

### [HttpIncomingMessage](./interfaces/http-server.md#httpincomingmessage)

`effect/http/HttpIncomingMessage` — unstable

The shared body/headers model implemented by server requests and client responses: `headers`, optional `remoteAddress`, and effectful `json`, `text`, `urlParamsBody`, `arrayBuffer`, and byte `stream` accessors. `schemaBodyJson`, `schemaBodyUrlParams`, and `schemaHeaders` decode either side through `Schema`; the underlying body error is unioned with `SchemaError`.

### [HttpPlatform](./interfaces/http-server.md#httpplatform)

`effect/http/HttpPlatform` — unstable

The host service behind local-file/Web-File responses and compression. Node, Bun, Deno, and Web layers implement `platform`, `fileResponse`, `fileWebResponse`, and a compressor supporting `gzip`, `deflate`, `br`, and optionally `zstd`. Most application code calls `HttpServerResponse.file` or `HttpMiddleware.compression` rather than this service directly.

### [HttpStaticServer](./interfaces/http-server.md#httpstaticserver)

`effect/http/HttpStaticServer` — unstable

A safe static-file application built over `FileSystem`, `Path`, and `HttpPlatform`. `make({ root, index?, spa?, cacheControl?, mimeTypes? })` returns an HTTP app; `layer({ ..., prefix? })` mounts GET routes in `HttpRouter`. It confines paths below the configured root, resolves directory indexes, derives MIME types, supports byte ranges and 206/416 responses, and handles conditional requests: `If-Match` / `If-Unmodified-Since` failures answer `412` before cache validation and ranges, ETag/last-modified matches answer `304` (keeping `Content-Location`, `Date`, `Expires`, and `Vary`; `If-None-Match` is parsed as a list of quoted entity tags, so a tag that itself contains a comma still matches), and HTTP dates are read as UTC. A directory URL without a trailing slash is redirected with `301` to the slash form (query and router prefix preserved), so clients that do not follow redirects must request the canonical URL.

### [HttpTraceContext](./interfaces/http-server.md#httptracecontext)

`effect/http/HttpTraceContext` — unstable

HTTP trace propagation interop. `toHeaders(span)` emits W3C `traceparent` and compact B3. `fromHeaders(headers)` safely tries W3C, compact B3, then multi-header B3 and returns `Option<Tracer.ExternalSpan>`; `w3c`, `b3`, and `xb3` are individual decoders.

### [MultipartParser](./interfaces/http-server.md#multipartparser)

`effect/http/MultipartParser` — unstable

The callback-driven incremental `multipart/form-data` parser used by platform adapters. `make(config)` returns `{ write(chunk), end() }`; callbacks receive field values, file chunks (ending with `null`), completion, or structured errors. Limits cover parts, total bytes, per-part bytes, and field bytes. Helpers include `defaultIsFile` and charset-aware `decodeField`.

### [HttpRouter](./interfaces/http-server.md#httprouter)

`effect/http/HttpRouter` — unstable

Request router expressed as Layers. `HttpRouter.add(method, path, handler)` produces a Layer for one route; `HttpRouter.addAll([...])` contributes many. Merge them like any other Layers and pass to `HttpRouter.serve` (real server) or `HttpRouter.toWebHandler` (Fetch-style handler for serverless). Path params, prefixes, CORS, and middleware all compose at this level.

**Reach for it when** you want hand-rolled routes — webhooks, health endpoints, file exports — without a full schema-described API.

### [HttpServer](./interfaces/http-server.md#httpserver)

`effect/http/HttpServer` — unstable

Abstract server service plus the functions that run an HTTP app. `HttpServer.serve(handler)` binds an app-effect to the bound socket; `HttpServer.logAddress`/`withLogAddress` log the listen address; `HttpServer.layerServices` supplies platform-neutral services to a handler. Provide a concrete server Layer — `NodeHttpServer.layer(createServer, { port })` or the Bun equivalent.

Sections: [Request work stays in the request fiber](./interfaces/http-server.md#request-work-stays-in-the-request-fiber) · [Own the listener: acquire late, bind port 0, prove release](./interfaces/http-server.md#own-the-listener-acquire-late-bind-port-0-prove-release)

**Reach for it when** wiring the actual listener, choosing a port, or swapping Node vs Bun by replacing one Layer.

### [HttpServerRequest](./interfaces/http-server.md#httpserverrequest)

`effect/http/HttpServerRequest` — unstable

Incoming request available as a service inside any handler (`yield* HttpServerRequest.HttpServerRequest`). Exposes URL, method, headers, cookies, and body — plus `schema*` helpers that decode parts through a Schema, failing into the error channel on bad input.

**Reach for it when** a handler needs the body, headers, query string, or cookies validated rather than stringly-typed.

### [HttpServerResponse](./interfaces/http-server.md#httpserverresponse)

`effect/http/HttpServerResponse` — unstable

Response builder. Constructors: `text`, `json`, `html`/`htmlStream`, `uint8Array`, `stream`, `file`/`fileWeb`, `redirect`, `empty`, `raw`. Pipeable modifiers: `setStatus`, `setHeader(s)`, cookie family. `schemaJson(schema)` encodes a domain value through a Schema into a JSON response — the symmetric partner of the request decoders.

**Reach for it when** producing any response, especially with a schema-encoded body or cookie/header control.

### [HttpMiddleware](./interfaces/http-server.md#httpmiddleware)

`effect/http/HttpMiddleware` — unstable

Middleware as a plain function: takes the "rest of the app" (an `Effect` producing a response) and returns a new one. Built-ins: `logger` (applied automatically by `HttpRouter.serve` unless disabled), `tracer`, `cors`, `xForwardedHeaders`, `searchParamsParser`. Define custom middleware with `HttpMiddleware.make`.

Sections: [Decompressing incoming bodies](./interfaces/http-server.md#decompressing-incoming-bodies) · [Edge policy checklist](./interfaces/http-server.md#edge-policy-checklist)

**Reach for it when** you need cross-cutting behavior — auth, timing, request IDs, CORS — without repeating it per handler.

### [HttpBody](./interfaces/http-server.md#httpbody)

`effect/http/HttpBody` — unstable

Unified body representation shared by client requests and server responses. The higher-level constructors (e.g. `HttpServerResponse.json`, `HttpClientRequest.bodyText`) usually build these for you, but the module provides explicit control: `HttpBody.text`, `json`/`jsonUnsafe`, `jsonSchema` (encode through a Schema), `uint8Array`, `urlParams`, `formData`/`formDataRecord`, `stream`, `file`. Construction failures surface as `HttpBodyError`, which `HttpBody.isHttpBodyError` guards an unknown error down to.

**Reach for it when** building a body by hand — streaming batches, multipart uploads, or schema-encoded JSON — rather than via a verb helper.

### [Headers](./interfaces/http-server.md#headers)

`effect/http/Headers` — unstable

Immutable, case-insensitive header map with redaction support. `Headers.fromInput` builds one — from a record (array values are joined with `", "`) or from an iterable of pairs, where repeated names are likewise joined rather than the last one winning (do not forward a joined `set-cookie` as one header; read `response.cookies` instead); pure operations: `get`/`set`/`merge`/`remove`. `redact` (and the `CurrentRedactedNames` reference) strips sensitive headers like `authorization` from logs and traces automatically.

**Reach for it when** you manipulate headers directly, or need redaction to keep credentials out of logs.

### [Cookies](./interfaces/http-server.md#cookies)

`effect/http/Cookies` — unstable

Immutable cookie jar plus a `Cookie` type with all attributes (`httpOnly`, `secure`, `sameSite`, `maxAge`, `path`, `domain`). Parse a request's `Cookie` header with `parseHeader`; `fromSetCookie` parses one or more response `Set-Cookie` header values into a jar. Build with `set`/`setUnsafe` and expire with `expireCookie`. The safe constructors validate the cookie name, value, domain, and path and return `CookiesError`; reserve `*Unsafe` forms for already-trusted values. The error's tag is `"CookiesError"`, so recover with `Effect.catchTag("CookiesError", ...)` and branch on `error.reason._tag` (`InvalidCookieName`, `InvalidCookieValue`, `InvalidCookieDomain`, `InvalidCookiePath`, …); `Cookies.isCookiesError` guards an unknown error down to this type. `fromSetCookie` skips any `Set-Cookie` header whose name is not a valid RFC 6265 token instead of storing it. On the server use `HttpServerResponse.setCookie`; on the client, a `Ref<ReadonlyArray<Cookies.Cookie>>` wired via [`HttpClient.withCookiesRef`](./interfaces/http-client.md#httpclient) gives a persistent session.

**Reach for it when** setting auth/session cookies on responses or maintaining a cookie jar across client calls.

### [HttpMethod](./interfaces/http-server.md#httpmethod)

`effect/http/HttpMethod` — unstable

Type-level vocabulary for HTTP verbs: the `HttpMethod` union, the `all` set, `isHttpMethod` guard, and `hasBody` (false for GET, HEAD, OPTIONS, and TRACE, true for POST, PUT, DELETE, PATCH, QUERY, and any other string; given an `HttpMethod` it narrows to `HttpMethod.WithBody`, given a plain `string` it returns a `boolean`). `QUERY` is also in `all`, and `HttpClient`, `HttpRouter`, and `HttpApiEndpoint` each have a `query` constructor or accept the method.

**Reach for it when** branching on request method or validating a method string.

### [Url](./interfaces/http-server.md#url)

`effect/http/Url` — unstable

Safe, immutable helpers over the native `URL`. `Url.fromString` parses (returns a `Result` — bad URL is a value, not a throw); `Url.make(url, params, hash)` constructs a URL while appending `UrlParams` and returns a typed `UrlError`; `mutate` applies a mutation to a copy; pipeable setters (`setHostname`, `setPathname`, `setProtocol`, `setUrlParams`, …) edit without mutation. URL construction lives here — the old `UrlParams.makeUrl` entry point is gone.

**Reach for it when** parsing or transforming URLs with immutability and parse errors as values.

### [UrlParams](./interfaces/http-server.md#urlparams)

`effect/http/UrlParams` — unstable

Immutable, order-preserving query-string model with correct repeated-key handling. Build with `make`/`fromInput`, read with `getAll`/`getFirst`/`getLast`, edit with `set`/`append`/`remove`. Accepts coercible inputs — numbers, booleans, bigints. The schemas for these HTTP data types live in `effect/Schema`: `Schema.UrlParams`, `Schema.RecordFromUrlParams`, and `Schema.JsonFromUrlParamsField(field, { reviver? })`, which round-trips a JSON-encoded query param through a Schema (the former `UrlParams.schemaJsonField`, `schemaRecord`, and `UrlParamsSchema`). `Schema.Headers`, `Schema.Cookie`, `Schema.Cookies`, and `Schema.RecordFromCookies` moved the same way.

Sections: [URL credentials and query redaction](./interfaces/http-server.md#url-credentials-and-query-redaction)

**Reach for it when** building or parsing query strings, especially with repeated keys or typed values.

### [Multipart](./interfaces/http-server.md#multipart)

`effect/http/Multipart` — unstable

Streaming `multipart/form-data` parsing. Distinguishes `Field` (text) from `File` parts; can persist uploads to disk (`PersistedFile`). Exposes Schemas (`FilesSchema`, `SingleFileSchema`, `PersistedFileSchema`) for typed decoding. Safety limits — `MaxParts`, `MaxFileSize`, `MaxFieldSize`, `FieldMimeTypes` — are `Context.Reference`s tunable per route; only `MaxFieldSize` has a finite default (see the [edge policy checklist](#edge-policy-checklist)). Failures: `MultipartError`, which `Multipart.isMultipartError` guards an unknown error down to. `Multipart.isPart` accepts every branded part including `PersistedFile`; `Multipart.isStreamPart` is true only for a text `Field` or a streamed `File`, which is the guard a streaming consumer wants. A request body that fails while a file part is streaming fails that file's stream instead of leaving its consumer waiting, and persisting a file passes a `MultipartError` from the body through unchanged instead of re-wrapping it as an `InternalError` reason. Parts are emitted to the consumer as soon as they're parsed rather than held back until more input arrives, so a slow part behind a fast one doesn't stall the ones already decoded.

**Reach for it when** accepting file uploads or mixed form posts — stream, size-limit, and decode into typed values.

### [HttpServerError](./interfaces/http-server.md#httpservererror)

`effect/http/HttpServerError` — unstable

Server tagged error family: `RequestParseError` (schema decode failed), `RouteNotFound`, `InternalError`, `ResponseError`, `ServeError` (listener couldn't bind). The framework maps these to sensible status codes (parse error → 400, an over-limit body → 413, missing route → 404); `causeResponse` turns a failure cause into a response. Error messages include only the request method and path, never query values or URL credentials, so they are safe in span errors and logs; the full request is still on the error.

**Reach for it when** you want to override how parse or not-found failures are rendered, or react to a bind failure on startup.

### [HttpServerRespondable](./interfaces/http-server.md#httpserverrespondable)

`effect/http/HttpServerRespondable` — unstable

Interface that lets any value describe how it becomes a response. Implement the `HttpServerRespondable` symbol on a class (e.g. a tagged error) and the router converts it to an `HttpServerResponse` automatically — a handler can fail with a domain error and have it rendered without a manual mapping step. `toResponse`/`toResponseOrElse` perform the conversion.

**Reach for it when** you want domain errors or DTOs to render themselves as responses instead of per-error response code.

### [Etag](./interfaces/http-server.md#etag)

`effect/http/Etag` — unstable

ETag generation for caching and conditional requests. `Etag.Generator` service produces strong or weak tags from file info; provide `Etag.layer` (strong) or `Etag.layerWeak` (weak) and the static-file machinery uses it to support `If-None-Match` and 304 responses.

**Reach for it when** serving files or cacheable resources and wanting conditional-request support without hand-rolling hashes.

### [Template](./interfaces/http-server.md#template)

`effect/http/Template` — unstable

Effectful tagged-template literal for building HTML (or any string) where interpolations can themselves be Effects, `Option`s, or Streams. `Template.make` resolves embedded effects (concurrently) and produces `Effect<string>`; `Template.stream` produces `Stream<string>` for progressive rendering. Pair with `HttpServerResponse.html`/`htmlStream` for streaming server-side rendering.

**Reach for it when** rendering HTML server-side with async data and streaming composing naturally inside the markup.

### [HttpStatus](./interfaces/http-server.md#httpstatus)

`effect/http/HttpStatus` — unstable

The single source of truth that maps readable status **names** to numeric codes. `HttpStatus.fromLiteral("Conflict")` returns the literal type `409`, and `HttpStatus.Literal` is the union of known names (`"OK"`, `"Created"`, `"NoContent"`, `"UnprocessableEntity"`, …). `HttpApiSchema.status` consumes it, so an endpoint annotation can say `HttpApiSchema.status("Conflict")` instead of a bare `409`.

**Reach for it when** a status code is part of a contract or a log line and a name reads better than a number.

### [Mime](./interfaces/http-server.md#mime)

`effect/http/Mime` — unstable

MIME lookup backed by a vendored standard registry (the `mime` runtime dependency was removed). Three pure functions, each returning an `Option`: `Mime.getType(pathOrExtension)`, `Mime.getExtension(type)`, and `Mime.getAllExtensions(type)`. Lookups are case-insensitive on the extension, and type parameters and whitespace are normalized, so `"application/json; charset=utf-8"` resolves to `json`. The lookup tables are built lazily on first call rather than at module evaluation, so importing this module without calling a lookup lets bundlers drop the tables and the MIME data they index.

**Reach for it when** choosing a `Content-Type` for a file response or validating an upload's extension against its declared type.

## [HttpApi](./interfaces/http-api.md)

Contract-first HTTP APIs, endpoints, schemas, handlers, middleware, clients, OpenAPI, and security.

Describe the API once as data: groups of endpoints, each with Schema-typed path params, query, payload, success, and errors. Derive a server (implement handlers, get validation free), a fully typed client (method names and argument/return types mirror the definition), and OpenAPI + Swagger + Scalar docs. Rename an endpoint or change a field and every consumer fails to compile.

### [HttpApiEndpoint](./interfaces/http-api.md#httpapiendpoint)

`effect/http-api/HttpApiEndpoint` — unstable

One endpoint described as data. `HttpApiEndpoint.get(identifier, path, spec)` (and `post`, `put`, `patch`, `delete`, …) declares a route whose `params`, `query`, `payload`, `success`, and `error` are all Schemas. The `identifier` becomes the handler key and client method name and is exposed as `.identifier`; do not use `.name`, which is the native function name because endpoints are callable function objects. The path string carries `:params`.

**Reach for it when** describing a single route's typed inputs and outputs — the atom every HttpApi is built from.

### [HttpApiGroup](./interfaces/http-api.md#httpapigroup)

`effect/http-api/HttpApiGroup` — unstable

Named bundle of related endpoints sharing a path prefix, middleware, and OpenAPI metadata. `HttpApiGroup.make("comp").add(...endpoints)` collects endpoints; `.prefix("/comp")` mounts them; `.middleware(Authorization)` applies middleware to the group; `.annotateMerge(OpenApi.annotations(...))` adds docs. Pass `{ topLevel: true }` to flatten a group's endpoints onto the root of the derived client.

**Reach for it when** grouping endpoints that share a prefix or auth, or wanting a clean namespace in the generated client.

### [HttpApi](./interfaces/http-api.md#httpapi-1)

`effect/http-api/HttpApi` — unstable

Root value tying groups into one API. `HttpApi.make("my-api").add(GroupA).add(GroupB)` builds it; `.annotateMerge(OpenApi.annotations(...))` adds top-level docs (title, version, license). This single object is what you serve, generate clients from, and produce OpenAPI specs from.

**Reach for it when** assembling groups into the one definition that drives server, client, and docs.

### [HttpApiSchema](./interfaces/http-api.md#httpapischema)

`effect/http-api/HttpApiSchema` — unstable

Toolkit for describing HTTP-specific facets of a schema: status codes, content types, empty responses, and streaming. `HttpApiSchema.status(code)` pins a status; `NoContent`/`Created`/`Accepted` are ready-made empty responses; `asText({ contentType })` serves a string as text/CSV/etc.; `asNoContent({ decode })` turns an error into a bodyless response; `asMultipart` marks a payload as multipart upload; `StreamUint8Array`/`StreamSse` describe streaming bodies (raw bytes or Server-Sent Events).

Sections: [Streaming request payloads](./interfaces/http-api.md#streaming-request-payloads) · [Upgrades](./interfaces/http-api.md#upgrades)

**Reach for it when** an endpoint needs a specific status, non-JSON content type, empty body, file upload, or streaming response.

### [HttpApiError](./interfaces/http-api.md#httpapierror)

`effect/http-api/HttpApiError` — unstable

Ready-made schema-typed errors for common HTTP failures: `BadRequest`, `Unauthorized`, `Forbidden`, `NotFound`, `Conflict`, `UnprocessableEntity` (422), `RequestTimeout`, `InternalServerError`, and more — each with the correct status code, plus `*NoContent` variants such as `UnprocessableEntityNoContent` for empty-body responses. Add to an endpoint's `error` list and fail with them like any yieldable error.

Sections: [Problem Details (RFC 9457)](./interfaces/http-api.md#problem-details-rfc-9457) · [Status mapping is part of the contract](./interfaces/http-api.md#status-mapping-is-part-of-the-contract)

**Reach for it when** an endpoint needs a standard HTTP error without hand-rolling the status mapping.

### [ProblemDetails](./interfaces/http-api.md#problemdetails)

`effect/http/ProblemDetails` — unstable

The RFC 9457 value layer underneath HttpApi's [problem support](#problem-details-rfc-9457), usable from a plain `HttpRouter` too. `ProblemDetails.contentType` is `application/problem+json`, `blankType` is `about:blank`, `ProblemDetails.Schema` is a lenient codec for a problem object (`type`, `status`, `title`, `detail`, `instance`, plus extension members) that follows RFC 9457 when decoding (a missing `type` becomes `about:blank`, wrong-typed standard members are dropped, unknown members are kept as extensions), and `ProblemDetails.toResponse(problem)` builds the `application/problem+json` response with the problem's `status` (or `500` when absent).

### [HttpApiSecurity](./interfaces/http-api.md#httpapisecurity)

`effect/http-api/HttpApiSecurity` — unstable

Declarative security schemes: `HttpApiSecurity.bearer` (Authorization: Bearer), `apiKey({ key, in })` (header/query/cookie), `basic` (HTTP Basic). Attach to a middleware definition; HttpApi extracts and decodes the credential from each request (handing it to middleware as a `Redacted` value) and emits the matching `securityScheme` into the OpenAPI doc so the "Authorize" button works in Swagger/Scalar.

**Reach for it when** protecting endpoints and wanting both runtime credential extraction and accurate security docs from one declaration.

### [HttpApiMiddleware](./interfaces/http-api.md#httpapimiddleware)

`effect/http-api/HttpApiMiddleware` — unstable

Middleware for the declarative world, defined as a typed service. `HttpApiMiddleware.Service` declares what the middleware `provides` to downstream handlers (e.g. a `CurrentUser` service), what it `requires`, the `error` it can raise, and an optional `security` scheme. The definition lives next to the API (no implementation); the server supplies a `Layer` that implements it; clients supply a `layerClient` to inject credentials.

Sections: [Authentication is not authorization](./interfaces/http-api.md#authentication-is-not-authorization)

**Reach for it when** you need auth (or any cross-cutting concern) that both decodes credentials and provides typed context to handlers, with wiring checked at compile time.

### [HttpApiBuilder](./interfaces/http-api.md#httpapibuilder)

`effect/http-api/HttpApiBuilder` — unstable

The server side — where handlers are implemented. `HttpApiBuilder.group(api, "comp", build)` gives a typed `handlers` object whose `.handle("name", impl)` only accepts endpoints in that group, with inputs (`params`, `query`, `payload`) already decoded and return type constrained to the endpoint's `success`/`error`. `HttpApiBuilder.layer(api, { openapiPath })` turns the implemented API into router routes (and optionally publishes the OpenAPI JSON).

Sections: [Handlers are lazy adapters](./interfaces/http-api.md#handlers-are-lazy-adapters)

**Reach for it when** implementing the server for an `HttpApi` — this is the only place handlers live.

### [HttpApiClient](./interfaces/http-api.md#httpapiclient)

`effect/http-api/HttpApiClient` — unstable

Fully typed client derived from your API definition — no codegen. `HttpApiClient.make(Api, { transformClient })` produces an object mirroring your groups and endpoints: `client.comp.getComp({ params: { id } })` returns `Effect<CompRecord, EmployeeNotFound | ...>` with request encoding, middleware, and response decoding handled. Path params, query, and payload go under named keys: `{ params: { id }, payload: { ... } }`. `transformClient` sets the base URL and adds retries by composing the underlying `HttpClient`.

**Reach for it when** consuming an `HttpApi` from another service or frontend and wanting a typed client that can never silently drift from the server.

### [OpenApi](./interfaces/http-api.md#openapi)

`effect/http-api/OpenApi` — unstable

OpenAPI 3.1 generator and annotation toolkit. `OpenApi.fromApi(api)` returns a complete spec object derived from endpoints, schemas, errors, and security. `OpenApi.annotations({ title, version, description, license, ... })` attaches metadata; services (`OpenApi.Title`, `Version`, `Servers`, `Summary`, `Deprecated`, `Exclude`, `Transform`) override anything down to a single parameter. When several security middlewares are stacked on an endpoint, the document requires all of them (one combined security requirement), matching the server; optional parameters and headers are not marked nullable, and `includeAnnotationKey` copies selected custom schema annotations (such as `x-*` vendor extensions) into the output.

**Reach for it when** you need an OpenAPI document for external consumers, codegen, or API gateways — guaranteed to match what you actually serve.

### [HttpApiSwagger](./interfaces/http-api.md#httpapiswagger)

`effect/http-api/HttpApiSwagger` — unstable

Mounts Swagger UI for your API. `HttpApiSwagger.layer(Api, { path: "/docs" })` serves the interactive Swagger explorer (with a working "Authorize" button if security is declared) at the chosen path, backed by the generated OpenAPI spec. Merge the Layer alongside your API routes.

**Reach for it when** you want the familiar Swagger UI with zero extra wiring.

### [HttpApiScalar](./interfaces/http-api.md#httpapiscalar)

`effect/http-api/HttpApiScalar` — unstable

Same idea as Swagger, rendered with [Scalar's](https://github.com/scalar/scalar) modern API reference UI. `HttpApiScalar.layer(Api, { path: "/docs" })` bundles the Scalar script inline; `HttpApiScalar.layerCdn(Api, { path, version })` loads it from a CDN. Both serve the generated OpenAPI spec.

**Reach for it when** you want a modern docs page instead of Swagger UI — same effort, nicer result.

### [HttpApiTest](./interfaces/http-api.md#httpapitest)

`effect/http-api/HttpApiTest` — unstable

In-memory testing — no socket, no port. `HttpApiTest.groups(Api, ["comp"])` wires selected groups' handlers to a generated client through the *real* request encoding, routing, response encoding, and client decoding pipeline, then returns the typed client. Call endpoints exactly as in production and assert on results. Unselected groups get placeholder handlers that fail if called, keeping tests scoped.

Sections: [What each test ring proves](./interfaces/http-api.md#what-each-test-ring-proves)

**Reach for it when** testing handlers, schema round-trips, error mapping, or middleware — fast, faithful, without standing up a server.

## [GraphQL](./interfaces/graphql.md)

Experimental typed GraphQL operations, clients, middleware, transports, resolvers, partial results, pagination, and code generation.

Typed operations for consuming a GraphQL API, not a GraphQL server framework. All seven `effect/graphql` modules are **experimental**: pin matching packages and re-audit on every upgrade. Prefer [HttpApi](./interfaces/http-api.md) for an Effect-owned HTTP contract, and [RPC](./interfaces/rpc.md) for an Effect-to-Effect procedure protocol.

### [GraphQL](./interfaces/graphql.md#graphql-1)

`effect/graphql/GraphQL` — experimental

`query`, `mutation`, and `subscription` describe a named document, variables, and a result Schema. Variables are encoded before sending; results are decoded before returning, so transformed scalars retain distinct decoded and wire types. The constructors do not validate a handwritten GraphQL document against a server schema: use the generator for that check. `Variables`, `Result`, `Error`, and `Services` project an operation's types. `enumLiterals` and `otherTypename` support generated enum and abstract-type schemas.

**Reach for it when** defining a typed operation by hand or inspecting generated operation types.

### [GraphQLGroup](./interfaces/graphql.md#graphqlgroup)

`effect/graphql/GraphQLGroup` — experimental

`make(...operations)` collects operations; `merge(...groups)` assembles a client surface. Method names come from operation names. Attach `.middleware(Service)` to an operation or a group. Group middleware run outside operation middleware, in attachment order within each level. Keep names unique when combining documents.

**Reach for it when** exposing only the operations an application capability needs.

### [GraphQLClient](./interfaces/graphql.md#graphqlclient)

`effect/graphql/GraphQLClient` — experimental

`make(group)` acquires the protocol and middleware implementations and produces one typed method per operation. Queries and mutations return Effects; subscriptions return Streams. Per-call headers and context let callers supply request-local data without capturing it at client construction.

**Reach for it when** executing operations, paging connections, or replacing a GraphQL dependency in a use-case test.

### [GraphQLClientError](./interfaces/graphql.md#graphqlclienterror)

`effect/graphql/GraphQLClientError` — experimental

Catch the outer `GraphQLClientError`, then inspect `reason._tag`:

**Reach for it when** distinguishing schema defects, transport failures, provider errors, and rate limits.

### [GraphQLMiddleware](./interfaces/graphql.md#graphqlmiddleware)

`effect/graphql/GraphQLMiddleware` — experimental

Define a `Service` and provide its implementation as a Layer. Implementations have `execute` and `subscribe`; `mapRequest` transforms requests for both. Middleware can require request-local services and add its own typed errors to calls. It sees raw execution results from `next`, including GraphQL errors, before client result decoding; transport failures fail `next` instead. This is client middleware: adding a bearer token is not verifying it on the server.

**Reach for it when** attaching credentials, recording rate-limit headers, or applying replay-safe per-operation policy.

### [GraphQLProtocol](./interfaces/graphql.md#graphqlprotocol)

`effect/graphql/GraphQLProtocol` — experimental

`layerHttp({ url })` uses an `HttpClient` for queries/mutations and HTTP SSE subscriptions; `layerWebSocket` supplies the WebSocket transport. Supply a Socket constructor/host layer appropriate to the runtime. The WebSocket protocol is `graphql-transport-ws`, not the older `subscriptions-transport-ws` protocol.

**Reach for it when** choosing HTTP/SSE versus WebSocket or routing calls to request-dependent endpoints.

### [GraphQLResolver](./interfaces/graphql.md#graphqlresolver)

`effect/graphql/GraphQLResolver` — experimental

`ordered` maps a list result to input keys by position; `findById` matches returned objects by a key. `request(resolver)` turns either into a lookup function participating in Effect request batching. `path` selects the result list and `typename` narrows abstract results. Missing/null/wrong-type entries fail their own lookup with `NoSuchElementError`; errors with an entry-specific GraphQL path can fail just that entry, while transport, decoding, or unscoped GraphQL errors fail the batch. Bound batch size to the server's actual list/page limit; a truncated result must not silently become “not found.” Batch limits apply independently per resolved protocol URL and `batchKey`, so interleaved lookups for different tenants do not fragment each other's batches, and each lookup's URL is resolved in its calling fiber.

**Reach for it when** replacing N+1 GraphQL calls with bounded, identity-aware request batches.

### [GraphQL generator](./interfaces/graphql.md#graphql-generator)

`@effect/graphql-generator/Config` — experimental

**pkg @effect/graphql-generator** — provides the `graphqlgen` CLI and public tool modules through subpath exports; there is no package-root entry point. `bin`, `main`, and `internal/*` are not public imports. Pin it with `effect` and its `@effect/platform-node` peer to the same release.

**Reach for it when** consuming an existing schema with many operations, fragments, custom scalars, subscriptions, or aliased batching.

## [RPC](./interfaces/rpc.md)

Typed RPC requests, routers, clients, transports, serialization, streaming, middleware, and OpenRPC documents.

Effect 4's RPC is schema-first and transport-agnostic. One contract — a group of procedures, each with payload/success/error Schema — derives a server, a typed client, and a test harness. Wire format and transport are pluggable layers. The contract never changes.

### [Rpc](./interfaces/rpc.md#rpc-1)

`effect/rpc/Rpc` — unstable

One procedure. `Rpc.make(tag, options)` records a tag plus four Schemas: `payload` (request), `success` (happy result), `error` (typed recoverable failures), and optional `defect` for unexpected deaths.

**Reach for it when** describing exactly one remote call with inputs, outputs, and failures captured as Schema.

### [RpcGroup](./interfaces/rpc.md#rpcgroup)

`effect/rpc/RpcGroup` — unstable

A collection of `Rpc` definitions keyed by tag, forming the service contract. `RpcGroup.make(...rpcs)` builds it; `.add`, `.merge`, `.omit`, `.prefix`, `.middleware`, and `.annotateRpcs` shape it. Hand this single value to both server and client.

Sections: [Evolving a contract](./interfaces/rpc.md#evolving-a-contract)

**Reach for it when** you want a single typed surface the server implements and the client mirrors.

### [RpcServer](./interfaces/rpc.md#rpcserver)

`effect/rpc/RpcServer` — unstable

The runtime that takes a group, its handler layer, a serialization layer, and a transport, and serves requests. Decodes incoming payloads with the procedure's Schema, runs the matching handler (and any middleware), tracks in-flight requests, honours acks and interrupts, encodes the result back to the client.

Sections: [Operational defaults](./interfaces/rpc.md#operational-defaults)

**Reach for it when** you are the callee and need to expose handlers over a real transport.

### [RpcClient](./interfaces/rpc.md#rpcclient)

`effect/rpc/RpcClient` — unstable

The mirror of the server, derived from the same group. `RpcClient.make(group)` returns an object with one method per procedure; calling `client.GetComp({ employeeId })` returns an `Effect` with exactly the success and error types the group declared. No codegen, no duplicated types.

Sections: [Retried mutations need a ledger](./interfaces/rpc.md#retried-mutations-need-a-ledger)

**Reach for it when** you are the caller and want a typed client derived from the group.

### [RpcClientError](./interfaces/rpc.md#rpcclienterror)

`effect/rpc/RpcClientError` — unstable

The error a derived client raises for a transport or protocol failure rather than a declared remote error. Its `reason` is a union of transport failures — HTTP client errors, socket errors, worker errors — plus `RpcClientDefect` for protocol violations and decode failures (e.g. empty or malformed response).

Sections: [Keep six failure categories distinguishable](./interfaces/rpc.md#keep-six-failure-categories-distinguishable)

**Reach for it when** you need to react to transport-level failures distinctly from contract business errors.

### [RpcMiddleware](./interfaces/rpc.md#rpcmiddleware)

`effect/rpc/RpcMiddleware` — unstable

Cross-cutting concerns — auth, logging, rate limiting — modeled as a typed service attached to procedures. `RpcMiddleware.Service<Self, { provides, requires }>()(name, { error })` declares middleware that can fail with a typed `error` and `provides` a service to the handlers behind it.

Sections: [Client middleware attaches; only the server edge enforces](./interfaces/rpc.md#client-middleware-attaches-only-the-server-edge-enforces)

**Reach for it when** a concern spans many procedures and should both gate the call and hand the handler a derived service.

### [RpcSchema](./interfaces/rpc.md#rpcschema)

`effect/rpc/RpcSchema` — unstable

Schema helpers specific to RPC — chiefly `RpcSchema.Stream(success, error)`, the success type that turns a procedure into a streaming response. A handler for a streaming RPC returns a `Stream` (or `Queue.Dequeue`); the client receives a `Stream` of decoded values.

**Reach for it when** a procedure produces a sequence of values rather than a single result.

### [RpcSerialization](./interfaces/rpc.md#rpcserialization)

`effect/rpc/RpcSerialization` — unstable

The pluggable wire format. `RpcSerialization` is a service describing how messages are framed and parsed; provide one of its layers and both client and server use it. Swapping formats is a single layer change with zero impact on contract or handlers.

**Reach for it when** you need to choose or change the on-the-wire encoding — for size, streaming framing, or interop.

### [OpenRpc](./interfaces/rpc.md#openrpc)

`effect/rpc/OpenRpc` — unstable

Publishes an RPC group as an [OpenRPC](https://spec.open-rpc.org/) 1.3.2 document, the JSON-RPC counterpart of [`OpenApi.fromApi`](./interfaces/http-api.md#openapi). `OpenRpc.fromRpcGroup(group, { info, servers? })` reads only the contract: it needs no handlers, no server, and no transport, and it installs no `rpc.discover` method — serve or commit the returned value yourself. It describes the canonical JSON encoding, which is what `RpcSerialization.layerJsonRpc` / `layerNdJsonRpc` put on the wire.

**Reach for it when** non-Effect peers call the group over JSON-RPC and need a machine-readable contract for discovery, client generation, or review.

### [RpcMessage](./interfaces/rpc.md#rpcmessage)

`effect/rpc/RpcMessage` — unstable

The protocol envelope types — messages that flow between client and server once payloads are wrapped for transport. Client-to-server: `Request`, `Ack`, `Interrupt`, `Eof`, `Ping`. Server-to-client: response exits, stream chunks, defects, `Pong`. Also defines branded `RequestId`.

**Reach for it when** implementing a bespoke `Protocol` or reasoning about acks, interrupts, and stream framing at the wire level.

### [RpcWorker](./interfaces/rpc.md#rpcworker)

`effect/rpc/RpcWorker` — unstable

Glue for running an RPC group over a Worker. Pair `RpcClient.layerProtocolWorker` on the main thread with `RpcServer.layerProtocolWorkerRunner` inside the worker to make a typed group drive a typed worker pool — same contract as HTTP, different pipe.

**Reach for it when** you want a typed RPC contract to drive a Worker pool, not a network service.

### [RpcTest](./interfaces/rpc.md#rpctest)

`effect/rpc/RpcTest` — unstable

In-memory harness that wires a derived client straight to handlers — no transport, no serializer, no HTTP server. `RpcTest.makeClient(group)` connects client and server through the no-serialization path; requests, responses, stream chunks, acks, interrupts, headers, and middleware all flow through the real machinery without bytes on a wire.

**Reach for it when** you want fast, deterministic tests of a whole group's behaviour without standing up a server.

### [Utils](./interfaces/rpc.md#utils)

`effect/rpc/Utils` — unstable

Plumbing for transport authors. `withRun` and `withRunClient` build protocol services that expose a stable `send`/`write` handle before the receive loop starts, buffering early messages (with their `Context`) and replaying them once `run` installs the real receiver. The built-in HTTP/socket/worker protocols are built with these.

**Reach for it when** writing a custom `RpcClient.Protocol`/`RpcServer.Protocol` and needing correct buffering during connection setup — otherwise never call it directly.

## [SQL](./interfaces/sql.md)

SQL clients, schemas, resolvers, models, migrations, transactions, streams, and provider adapters.

### [Where SQL belongs in an application](./interfaces/sql.md#where-sql-belongs-in-an-application)

**Dependencies point one way: transport → use case → domain repository → SQL implementation → `SqlClient`.** A route handler that holds the raw `SqlClient` has nowhere to put authorization, invariants, or error meaning, and every driver change reaches the edge.

### [SqlClient](./interfaces/sql.md#sqlclient)

`effect/sql/SqlClient` — unstable

`SqlClient` is the injected service used for every query. It is simultaneously a tagged-template query constructor (`sql` applied to a template literal), an identifier quoter (`sql("employees")`), and an object with helpers (`sql.in`, `sql.insert`, `sql.withTransaction`). `const sql = yield* SqlClient.SqlClient` gives you this callable. Each tagged-template statement is an `Effect` yielding `ReadonlyArray<Row>`.

Sections: [The star: parameterized tagged-template queries](./interfaces/sql.md#the-star-parameterized-tagged-template-queries) · [Helpers you'll use daily](./interfaces/sql.md#helpers-you-ll-use-daily) · [Fragments compose](./interfaces/sql.md#fragments-compose) · [Transactions](./interfaces/sql.md#transactions) · [External effects after commit (outbox)](./interfaces/sql.md#external-effects-after-commit-outbox) · [Statement variants & dialect switches](./interfaces/sql.md#statement-variants-dialect-switches)

**Reach for it when** you talk to a database at all.

### [Statement](./interfaces/sql.md#statement)

`effect/sql/Statement` — unstable

A `Statement<A>` is a list of *segments* (literals, escaped identifiers, bound parameters, insert/update helpers) plus the machinery to compile them to a `[sqlText, params]` pair for the active dialect. It is both an `Effect` and a `Fragment`. The template literal is parsed once into segments; the dialect `Compiler` walks those segments to produce numbered placeholders and the params array.

**Reach for it when** you need a non-default execution mode (stream, raw, values, unprepared), want to `compile()` and assert on generated SQL, or you're authoring a custom dialect/helper.

### [SqlSchema](./interfaces/sql.md#sqlschema)

`effect/sql/SqlSchema` — unstable

`SqlSchema` bridges a query and a `Schema`. It wraps execution so the request is encoded before running and every returned row is decoded through a result Schema. Each helper is a factory: provide a `Request` schema, a `Result` schema, and an `execute` callback; receive `(input) => Effect<decoded, SchemaError | ..., R>`. The difference between helpers is result cardinality.

**Reach for it when** you want queries to return real domain types with validation at the boundary instead of hand-casting `unknown` rows.

### [SqlResolver](./interfaces/sql.md#sqlresolver)

`effect/sql/SqlResolver` — unstable

`SqlResolver` builds schema-aware `RequestResolver`s on top of Effect's Request/Batching machinery: many concurrent lookups collapse into one batched SQL query, with requests deduplicated by payload and results mapped back to callers. Describe one logical lookup (its `Id`/`Request` schema, its `Result` schema, and how to map a result back to the requesting caller). When N callers fire that lookup in one batching window, the resolver encodes all inputs, runs a single `IN (...)`-style query, decodes rows, and completes each request from the shared result set.

**Reach for it when** you'd otherwise fire a query per item in a loop or per field in a GraphQL/RPC resolver.

### [SqlStream](./interfaces/sql.md#sqlstream)

`effect/sql/SqlStream` — unstable

`SqlStream` turns a driver's push-based cursor (event emitter, server-side cursor, callback firehose) into an Effect `Stream` with backpressure. It is plumbing that drivers use to implement `statement.stream` and `connection.executeStream`. `asyncPauseResume` registers an emitter with `single`/`array`/`fail`/`end` callbacks and pause/resume hooks; when the internal bounded queue fills, it calls the driver's `onPause` so the database stops pushing rows faster than they are consumed.

**Reach for it when** writing a driver, or building a custom adapter from a row-emitting source into a `Stream`. For everyday large reads, use `statement.stream`.

### [SqlError](./interfaces/sql.md#sqlerror)

`effect/sql/SqlError` — unstable

The single typed failure for the whole SQL stack. Every query, transaction, and connection acquire fails with `SqlError`. It wraps a structured `reason` — connection, auth, syntax, constraint, deadlock, serialization, timeout, unknown — each preserving the original driver cause and exposing whether a retry could help. The outer error delegates `message`, `cause`, and `isRetryable` to its reason.

Sections: [Normalizing errors at a repository boundary](./interfaces/sql.md#normalizing-errors-at-a-repository-boundary)

**Reach for it when** you handle database failures deliberately — retrying deadlocks, mapping unique violations, or surfacing typed causes upstream.

### [SqlConnection](./interfaces/sql.md#sqlconnection)

`effect/sql/SqlConnection` — unstable

The low-level, driver-facing contract under `SqlClient`. A `Connection` executes already-compiled SQL with positional params and can return transformed rows, raw results, a stream, value arrays, or unprepared results. It also defines the `Acquirer` (a scoped effect that checks a connection out of the pool) and the generic `Row` shape. `SqlClient` is the ergonomic front end; `Connection` is the raw executor a driver implements. Touch it directly only when using `sql.reserve` to pin a connection for an operation outside the statement abstraction.

**Reach for it when** implementing a new driver, or needing a pinned raw connection for operations the statement API does not model.

### [Migrator](./interfaces/sql.md#migrator)

`effect/sql/Migrator` — unstable

Versioned, transactional schema migrations. Records applied migration ids in a table (`effect_sql_migrations` by default), runs only pending ones in order inside a transaction, detects duplicate ids, and treats a concurrent run as locked rather than racing. A migration is a numbered file (`0003_create_equity_grants.ts`) whose default export is an `Effect` using `SqlClient`. A loader discovers them; the migrator diffs recorded vs. existing and applies the gap. Use the driver's `Migrator.layer({ loader })` so migrations run during layer construction, before the service starts.

Sections: [Operating migrations](./interfaces/sql.md#operating-migrations)

**Reach for it when** you need reproducible, ordered schema evolution checked into the repo and applied automatically on deploy.

### [MigratorFileSystem](./interfaces/sql.md#migratorfilesystem)

`effect/sql/MigratorFileSystem` — unstable

The directory loader for [Migrator](#migrator), kept out of `effect/sql/Migrator` and the `effect/sql` barrel because its dynamic `import()` breaks React Native's Metro bundler. `MigratorFileSystem.fromFileSystem(directory)` returns a `Loader<FileSystem | Path>` that imports `<id>_<name>` `.js`/`.ts`/`.mjs`/`.mts` files sorted by id. Import it by its subpath (`effect/sql/MigratorFileSystem`) or through a driver's migrator (`PgMigrator.fromFileSystem`, `SqliteMigrator.fromFileSystem`, …); `@effect/sql-sqlite-react-native` deliberately does not re-export it, so bundle migrations there with `Migrator.fromRecord` or `fromGlob`.

### [SqlModel](./interfaces/sql.md#sqlmodel)

`effect/sql/SqlModel` — unstable

Define a table's shape once as a `Model` schema and derive a typed CRUD repository — `insert`, `insertVoid`, `update`, `updateVoid`, `findById`, `delete` — automatically. A `Model.Class` is a family of *variants* built on VariantSchema: the same definition yields a select schema, an `insert` schema (db-generated columns dropped), an `update` schema, and JSON-API variants (`json`, `jsonCreate`, `jsonUpdate`). `SqlModel.makeRepository` reads those variants to type each operation correctly. Insert/update inputs are encoded with the model's input variants, returned rows decoded with the full model, and dialect quirks (pg `RETURNING` vs. mysql `LAST_INSERT_ID`) are handled automatically.

**Reach for it when** a schema model maps cleanly to a table and you want standard CRUD without re-typing insert/update/select shapes — drop to a raw `sql` tagged template for anything bespoke.

### [Operating SQL in production](./interfaces/sql.md#operating-sql-in-production)

Never log connection strings, full parameter lists, or personal row values. Name operations with low-cardinality, allow-listed span names (`Effect.fn("Employees.findById")`) rather than interpolated text, and remember that `db.query.text` is exported with every statement span.

Sections: [Pools, reservations, and streaming](./interfaces/sql.md#pools-reservations-and-streaming) · [Logging and telemetry safety](./interfaces/sql.md#logging-and-telemetry-safety) · [Verification levels](./interfaces/sql.md#verification-levels)

### [The driver packages](./interfaces/sql.md#the-driver-packages)

Each driver is a thin satellite package contributing a `Layer` producing `SqlClient` wired to a real connection and the correct dialect compiler. All expose `layer(config)` and `layerConfig(Config.Wrap<...>)`, and most ship a matching `*Migrator`. Each layer provides **both** the driver's own service (`PgClient.PgClient`, `MysqlClient.MysqlClient`, …) and the generic `SqlClient.SqlClient`; yielding the driver service gives a value that is also a `SqlClient`, so it can be passed to code written against the generic client.

Sections: [Session settings at connect time](./interfaces/sql.md#session-settings-at-connect-time) · [Native client behavior: codecs, JSON, and LISTEN](./interfaces/sql.md#native-client-behavior-codecs-json-and-listen)

## [Platform & Runtime Hosts](./interfaces/platform-runtime-hosts.md)

Node, Bun, Deno, browser, Cloudflare, filesystem, path, terminal, worker, runtime services, and exit codes.

Effect's platform layer separates service interfaces (in the core `effect` package, runtime-agnostic) from concrete implementations (provided as a Layer from `@effect/platform-node`, `@effect/platform-bun`, `@effect/platform-deno`, or `@effect/platform-browser`; the experimental `@effect/platform-cloudflare` hosts Effect Cluster on Durable Objects). Business logic imports only from `effect/*`; only the entrypoint imports the platform package. Swapping the Layer swaps the runtime.

### [FileSystem](./interfaces/platform-runtime-hosts.md#filesystem)

`effect/FileSystem` — unstable

Service interface for filesystem operations: read, write, stat, copy, move, delete, make directories, create temp paths, stream bytes, watch for changes. Discrete operations return an `Effect` failing with `PlatformError` (`BadArgument` or `SystemError` carrying the OS reason); `stream` and `watch` expose that failure through a `Stream`. `PlatformError.isPlatformError(error)` is a type guard for narrowing an `unknown` caught value — useful at a boundary that re-throws or logs errors from several sources.

Sections: [Testing without a disk](./interfaces/platform-runtime-hosts.md#testing-without-a-disk)

### [Glob](./interfaces/platform-runtime-hosts.md#glob)

`effect/Glob` — experimental

Pure path matching with the same syntax `FileSystem.glob` uses, without touching a disk. `Glob.make(pattern, { dot? })` compiles a reusable value, `Glob.match(glob, path)` (dual) tests a `/`-separated path, and `Glob.escape(text)` makes a literal file name match only itself. Syntax: `*` and `?` within one segment, `[...]` classes (with `!`/`^` negation and POSIX classes such as `[[:digit:]]`), nested `{a,b}` alternatives, `**` as a whole segment for zero or more segments (so `dir/**` matches `dir` too), a trailing `/` for directories only, and `\` escapes. Wildcards never match `.` or `..` and skip dot-names unless `dot` is set. Leading `!` negation and extglobs are not interpreted, malformed syntax such as an unclosed `[` matches literally, and UNC paths never match.

**Reach for it when** filtering paths you already have (an upload's file list, a zip's entries, a watch event) with the same rules as a file-system search.

### [Path](./interfaces/platform-runtime-hosts.md#path)

`effect/Path` — unstable

Service interface wrapping platform path utilities: `join`, `resolve`, `dirname`, `basename`, `extname`, `normalize`, `relative`, `isAbsolute`, `parse`, `format`, plus effectful `fromFileUrl` and `toFileUrl` helpers. The `sep` property gives the platform separator.

### [Terminal](./interfaces/platform-runtime-hosts.md#terminal)

`effect/Terminal` — unstable

Interactive terminal I/O: query dimensions (`columns`, `rows`), follow resizes (`size`), read a line (`readLine`), receive a stream of key events (`readInput`), display text (`display`). Input reading fails with `QuitError` on Ctrl+C or Ctrl+D.

### [Stdio](./interfaces/platform-runtime-hosts.md#stdio)

`effect/Stdio` — unstable

Lower-level counterpart to `Terminal`: `process.argv` via `args`, write `Sink`s for stdout and stderr (accepting `string | Uint8Array`), raw byte `Stream` for stdin, and `stdinIsTerminal` / `stdoutIsTerminal` / `stderrIsTerminal` effects for adapting output to pipes versus TTYs. I/O can fail with `PlatformError`. `Stdio.layerTest` lets you stub any field for unit testing.

### [Socket](./interfaces/platform-runtime-hosts.md#socket)

`effect/socket/Socket` — unstable

Platform-neutral abstraction for a bidirectional socket (TCP, Unix domain, or WebSocket). A `Socket` is **pull-based**: it exposes a scoped `reader` and a scoped `writer`, and nothing is read from the transport until the consumer pulls.

### [SocketServer](./interfaces/platform-runtime-hosts.md#socketserver)

`effect/socket/SocketServer` — unstable

Server-side counterpart to `Socket`. The `SocketServer` service exposes: `address` — the bound `NetAddress.SocketAddress` (an `InetAddressV4 | InetAddressV6` with `address` and `port`, or a `UnixPathAddress` with `path`) — and `run(handler)`, a never-ending Effect that accepts connections and passes each as a `Socket.Socket` to the handler. Errors are `SocketServerError` with reason `SocketServerOpenError | SocketServerUnknownError`.

### [NetAddress](./interfaces/platform-runtime-hosts.md#netaddress)

`effect/net/NetAddress` — unstable

Pure, platform-neutral **values** for network addresses: `Ipv4Address` / `Ipv6Address` (`IpAddress`), `MacAddress`, internet socket addresses `InetAddressV4` / `InetAddressV6` (`InetAddress`, an IP plus a port), and `UnixPathAddress`. `SocketAddress = InetAddress | UnixPathAddress` is what `SocketServer.address` and `HttpServer.address` report. `Ipv4Address` and `Ipv6Address` store their bits as `number`s rather than a `Uint8Array`, so `Equal`/`Hash` and comparisons are cheap; every value implements `Equal` and `Hash`, so addresses work as `HashMap` keys and compare structurally.

### [Host](./interfaces/platform-runtime-hosts.md#host)

`effect/net/Host` — experimental

Pure values for DNS domain names, numeric hosts (including scoped IPv6), and host/port endpoints. Checked `domainNameFromString`, `hostFromString`, and `hostPortFromString` return `Result`s with `NetAddressError`; `*Unsafe` forms are for trusted literals. `*FromInput` constructors accept the corresponding supported value/string/parts inputs without doing DNS. Format endpoints with `formatHostPort` so IPv6 gets brackets; bare numeric-address parsing belongs to [NetAddress](#netaddress).

**Reach for it when** parsing configuration that may contain a name rather than only an IP address.

### [Dns](./interfaces/platform-runtime-hosts.md#dns)

`effect/net/Dns` — experimental

`Dns.Dns` separates `lookup` (OS host resolution, including hosts-file/system sources), `resolve` (DNS records of a selected type), and `reverse` (names for an address). Inputs accept supported strings and typed host/address values. Records include A, AAAA, CAA, CNAME, MX, NAPTR, NS, PTR, SOA, SRV, TXT, and TLSA; record values support structural equality and hashing. A TLSA answer is DNS data, not automatic certificate verification.

**Reach for it when** querying DNS records or resolving host names without embedding a host API in application code.

### [AddressResolver](./interfaces/platform-runtime-hosts.md#addressresolver)

`effect/net/AddressResolver` — experimental

`AddressResolver.AddressResolver.resolve(target, { family? })` converts a socket address or host/port input to a nonempty list of socket addresses. Numeric hosts avoid lookup; names use `Dns.lookup`. Results retain resolver order and are filtered by family; Unix-domain addresses pass through. Invalid endpoints or unsupported numeric families fail with `NetAddressError`, and lookup failures with `DnsError`.

**Reach for it when** turning configured endpoints into typed connection candidates while keeping DNS and interface policy explicit.

### [DatagramSocket](./interfaces/platform-runtime-hosts.md#datagramsocket)

`effect/socket/DatagramSocket` — experimental

Pull-based UDP with scoped native handles. Acquiring `reader` opens and binds the socket; only one reader may be open, and another acquisition waits interruptibly. The scoped writer cannot fail to acquire, but writes wait until a reader is open — even send-only applications must acquire one. `reader.pull` yields a nonempty packet batch; packets retain their bytes safely. `writer.write` takes `{ payload, address? }`, where payload is text or bytes; omit the destination only for a configured/connected peer.

**Reach for it when** implementing datagram protocols or multicast discovery with deliberate loss and lifetime handling.

### [IpNetwork](./interfaces/platform-runtime-hosts.md#ipnetwork)

`effect/net/IpNetwork` — unstable

A CIDR network: a network address plus a prefix length, generic over the address family (`Ipv4Network`, `Ipv6Network`). Construction is strict — `IpNetwork.fromString("10.20.3.7/16")` **fails** because host bits are set; use `IpNetwork.fromAddress` (which masks them) or go through `IpInterface` when you have a host address. Operations: `contains(network, address)`, `containsNetwork`, `overlaps`, `firstAddress` / `lastAddress`, `addressCount` (a `bigint`, since an IPv6 range does not fit a `number`), and `format`. The native `@effect/sql-pg` client decodes PostgreSQL `cidr` columns to their formatted text (for example `"10.20.0.0/16"`), not to an `IpNetwork` value — parse it with `IpNetwork.fromString` where you need the structure.

### [IpInterface](./interfaces/platform-runtime-hosts.md#ipinterface)

`effect/net/IpInterface` — unstable

An address **with** its prefix length — `10.20.3.7/16` — the form a host or network interface is configured with. Unlike `IpNetwork`, host bits are preserved. `IpInterface.fromString` parses it (with `ParseOptions`), `IpInterface.format` renders it, and `IpNetwork.fromInterface(iface)` yields the containing network (`10.20.0.0/16`). `@effect/sql-pg` decodes PostgreSQL `inet` columns to formatted text as well (`"10.20.3.7/16"`, or just the address when the prefix covers the whole address); parse it with `IpInterface.fromString`.

### [Worker](./interfaces/platform-runtime-hosts.md#worker)

`effect/workers/Worker` — unstable

Parent-side API for communicating with a worker thread or IPC child process. A `Worker<O, I>` provides: `send(message: I)` — fire a typed message into the worker; `run(handler)` — a never-completing Effect calling the handler for each emitted `O`. Errors are `WorkerError`.

### [WorkerRunner](./interfaces/platform-runtime-hosts.md#workerrunner)

`effect/workers/WorkerRunner` — unstable

Worker-side counterpart to `Worker`. A `WorkerRunner<O, I>` listens for `I` messages from the parent (tagged by port ID), calls the handler, and sends `O` replies via `send(portId, message)` or `sendUnsafe`. The optional `disconnects` queue notifies when a port closes; the browser and Deno runners provide it (many ports can share one worker there), the Node runner has a single parent and does not. An RPC server running over a worker forwards every disconnect, so a closed port's in-flight requests are interrupted rather than left running.

### [WorkerError](./interfaces/platform-runtime-hosts.md#workererror)

`effect/workers/WorkerError` — unstable

Typed error union for worker communication. `WorkerError` wraps one of four reasons: `WorkerSpawnError` (worker failed to start), `WorkerSendError` (message serialization failed), `WorkerReceiveError` (message decode failed), `WorkerUnknownError` (anything else). Catch with `Effect.catchTag("WorkerError", ...)`.

### [Transferable](./interfaces/platform-runtime-hosts.md#transferable)

`effect/workers/Transferable` — unstable

Transfer-list support for worker message fields. Annotate fields with `Transferable.schema`; a `Transferable.Collector` records backing `ArrayBuffer`s, `MessagePort`s, or `ImageData` buffers for the platform's `postMessage` transfer list. The surrounding message still passes through Schema encoding and structured clone; only the transferred resources avoid copying. Transferring an ArrayBuffer detaches it from the sender, so do not retain a usable-sender-buffer assumption after sending. Without a Collector the annotation does not collect anything.

### [ChildProcess](./interfaces/platform-runtime-hosts.md#childprocess)

`effect/process/ChildProcess` — unstable

Value type describing a command to run — a typed `ProcessBuilder`. Use `ChildProcess.make(cmd, args, options)` to create a `StandardCommand`, or chain two commands with `ChildProcess.pipeTo` to create a `PipedCommand` (shell `|` equivalent). Modifiers: `setEnv`, `setCwd`, `prefix`.

### [CommandLine](./interfaces/platform-runtime-hosts.md#commandline)

`effect/process/CommandLine` — unstable

Builds the single strings that a shell or a Windows program splits back into arguments — for `sh -c`, SSH, or a `shell` command — and argument lists from templates. It is unrelated to `effect/cli`, which parses your own program's arguments. `quote(word, { format? })` quotes one argument, `join(words, { format? })` quotes a whole argument list, and both return a `Result` failing with `CommandLineError` (a NUL character, or an argument the format cannot carry). `display(words)` renders the same text for logs with `Redacted` values replaced by `<redacted>`; `quote` and `join` include the secret, because their output is meant to run. `template` is the parser `ChildProcess.make` uses, returning `Result<Array<Word>, CommandLineError>`. Formats are `"posix"` (default; `sh`, `bash`, `zsh`, and readable by `fish`), `"powershell"` (7.3+), and `"windows"` (C runtime rules). The format follows the *receiving* shell: SSH sends the line to the remote account's login shell, and `cmd.exe` is not supported.

### [ChildProcessSpawner](./interfaces/platform-runtime-hosts.md#childprocessspawner)

`effect/process/ChildProcessSpawner` — unstable

Service that executes `ChildProcess.Command` values.

### [Platform packages](./interfaces/platform-runtime-hosts.md#platform-packages)

The services above are interfaces. Platform packages provide concrete Layer implementations and a `runMain` entry point.

### [Choosing a host](./interfaces/platform-runtime-hosts.md#choosing-a-host)

A platform Layer says *how* a capability is implemented. The host decides something more important: **who owns the runtime, what cancels work, and whether cleanup is actually awaited.** Pick the row first, then the package.

Sections: [Keep platform and unstable imports behind a capability](./interfaces/platform-runtime-hosts.md#keep-platform-and-unstable-imports-behind-a-capability)

### [Browser IndexedDB](./interfaces/platform-runtime-hosts.md#browser-indexeddb)

Five modules form a schema-aware, versioned database rather than a thin `IDBRequest` wrapper:

**Reach for it when** a browser application needs local, typed, queryable state with deliberate migrations and transactions. For simple keys, use `BrowserKeyValueStore`; for generic persistence, `BrowserPersistence.layerIndexedDb` is a separate, simpler store that talks to the raw `indexedDB` API directly rather than building on these typed modules.

### [Other browser capabilities](./interfaces/platform-runtime-hosts.md#other-browser-capabilities)

## [Cryptography](./interfaces/cryptography.md)

Cryptography services: secure randomness, digests, MACs, signatures, AEAD and ciphers, key derivation, agreement, wrapping, key formats, the WebCrypto backend, and JOSE keys, JWS, JWE, JWTs, and JWKS key sets.

The `effect/crypto` modules split cryptography into one service per job: `SecureRandom`, `Digest`, `Mac`, `Aead`, `Cipher`, `Kdf`, `Signature`, `KeyAgreement`, and `KeyWrap`. `KeyFormat` reads and writes keys, `CryptoError` is the only error they fail with, and `WebCrypto` is the reference that the WebCrypto-backed layers run on. Each service is an ordinary `Context.Service`, so a program asks for only the services it uses and a test replaces just those. The [`effect/jose`](#jose-tokens-and-keys) modules build JSON Web Keys, signatures, encryption, and tokens on top of these services.

### [SecureRandom](./interfaces/cryptography.md#securerandom)

`effect/crypto/SecureRandom` — unstable

The `SecureRandom` service generates `randomBytes(size)`, uniform integers with `intBetween(min, max, { halfOpen? })` (exactly uniform, by rejection sampling), Fisher–Yates `shuffle`, `uuidV4()`, `uuidV7()`, and the `ulid` Effect. Every operation has a `never` error channel; a negative size or an empty range dies with a `RangeError`. `uuidV4` and `uuidV7` are functions returning Effects: by default they return the lowercase hyphenated string, and `{ format: "bytes" }` returns the 16 bytes.

### [Digest](./interfaces/cryptography.md#digest)

`effect/crypto/Digest` — unstable

The `Digest` service computes `digest(algorithm, data)` as bytes and `digestHex(algorithm, data)` as lowercase hex. Algorithms are values: `Digest.md5`, `Digest.sha1`, `Digest.sha256`, `Digest.sha384`, and `Digest.sha512`. Output is stable byte for byte, so digests can be persisted. `layerWebCrypto` runs SHA on `crypto.subtle` and MD5 on a vendored pure TypeScript implementation; `NodeCrypto.layerDigest` runs both synchronously on `node:crypto`, which is faster for small inputs.

### [Mac](./interfaces/cryptography.md#mac)

`effect/crypto/Mac` — unstable

HMAC with `Mac.hmacSha1`, `hmacSha256`, `hmacSha384`, or `hmacSha512`. The service has `generateKey(algorithm)`, `sign(key, data)`, and `verify(key, tag, data)`, which returns a `boolean` and compares in constant time. Build keys with `Mac.key(algorithm, bytes)` (any non-empty length; an empty key fails with `InvalidKey`) or `Mac.fromCryptoKey` for a non-extractable WebCrypto key, and export with `Mac.toBytes`. `Mac.timingSafeEqual(a, b)` compares fixed-length secrets you computed elsewhere; arrays of different lengths return `false` immediately.

### [Aead](./interfaces/cryptography.md#aead)

`effect/crypto/Aead` — unstable

Authenticated encryption with `Aead.aes128Gcm`, `aes256Gcm`, `chacha20Poly1305`, or `xchacha20Poly1305`. The service has `generateKey(algorithm)`, `encrypt(key, plaintext, { nonce, aad? })`, and `decrypt(key, ciphertext, { nonce, aad? })`. Ciphertext is `ciphertext‖tag` with a 16-byte tag. Any tampering with the ciphertext, tag, or additional data fails `decrypt` with a detail-free `DecryptionFailed` reason. `Aead.key` validates the key length (a wrong length fails with `InvalidKey`; AES-192 is not supported), and `Aead.fromCryptoKey` accepts AES-GCM `CryptoKey`s only.

### [Cipher](./interfaces/cryptography.md#cipher)

`effect/crypto/Cipher` — unstable

Unauthenticated AES-CTR (`Cipher.aes128Ctr`, `aes256Ctr`) and AES-CBC with PKCS#7 padding (`aes128Cbc`, `aes256Cbc`), with the same `generateKey` / `encrypt` / `decrypt` shape as `Aead` but an `{ iv }` option. Use it only for protocols that pair these modes with their own MAC (SSH, SRTP, JWE, CMS); otherwise use [`Aead`](#aead). An attacker can change the ciphertext undetected, AES-CTR decryption never fails, and AES-CBC reports bad padding and bad length as the same `DecryptionFailed`. Verify a MAC before decrypting (encrypt-then-MAC), and never reuse an IV with one key.

### [Kdf](./interfaces/cryptography.md#kdf)

`effect/crypto/Kdf` — unstable

The `Kdf` service has one method, `derive(algorithm, secret, { salt, length, info? })`, which returns plain bytes. Turn them into a typed key with the target family's constructor, such as `Aead.key` or `Mac.key`. Algorithms are `Kdf.hkdfSha1` … `hkdfSha512` (or `Kdf.hkdf(Digest.sha256)`), `Kdf.pbkdf2Sha256` (600,000 iterations) or `Kdf.pbkdf2({ hash, iterations })`, and `Kdf.argon2id({ memory?, passes?, parallelism? })`, which defaults to 64 MiB, 3 passes, and 4 lanes.

### [Signature](./interfaces/cryptography.md#signature)

`effect/crypto/Signature` — unstable

Digital signatures with `Signature.ed25519`, `ecdsaP256` / `ecdsaP384` / `ecdsaP521` (hashed with SHA-256/384/512, as JOSE ES256/384/512), and RSA-PSS or RSASSA-PKCS1-v1_5 (`rsaPssSha256`, `rsaPkcs1v15Sha256`, … at 3072 bits, or `Signature.rsaPss({ hash, modulusLength })`). The service has `generateKeyPair(algorithm)`, `sign(privateKey, data)`, `verify(publicKey, signature, data)` (a `boolean`), and `publicKeyOf(privateKey)`.

### [KeyAgreement](./interfaces/cryptography.md#keyagreement)

`effect/crypto/KeyAgreement` — unstable

X25519 (`KeyAgreement.x25519`) and ECDH on P-256, P-384, and P-521 (`ecdhP256`, …). The service has `generateKeyPair`, `deriveSharedSecret(privateKey, publicKey)`, and `publicKeyOf`. Both keys must use the same algorithm, which the types enforce. The shared secret is raw bytes: pass it through [`Kdf`](#kdf) (HKDF) before using it as a key. X25519 needs Chrome 133, Firefox 130, or Safari 17 in browsers.

### [KeyWrap](./interfaces/cryptography.md#keywrap)

`effect/crypto/KeyWrap` — unstable

AES-KW (`KeyWrap.aes128Kw`, `aes256Kw`) and RSA-OAEP (`rsaOaepSha256`, `rsaOaepSha1`, or `KeyWrap.rsaOaep({ hash, modulusLength })`). The service has `generateKey` (AES-KW), `generateKeyPair` (RSA-OAEP), `wrap(wrapKey, key)`, and `unwrap(unwrapKey, algorithm, wrapped)`, which returns a typed key of the given algorithm. `wrap` takes an `Aead`, `Cipher`, `Mac`, or `KeyWrap` key, never raw bytes. AES-KW wraps keys whose length is a multiple of 8 and at least 16 bytes; other lengths fail with `InvalidArgument`. A key-encryption key is the key most worth keeping non-extractable, so in browsers build it with `KeyWrap.fromCryptoKey`.

### [KeyFormat](./interfaces/cryptography.md#keyformat)

`effect/crypto/KeyFormat` — unstable

Plain functions, not a service, that run on the [`WebCrypto`](#webcrypto) reference and require nothing: `decodePublic(format, algorithm, data)`, `decodePrivate(...)`, `decodeSecret(...)`, and `encode(format, key)`. Formats are `KeyFormat.spki` (public DER), `pkcs8` (private DER), `jwk` (every role), import-only `pkcs1` (RSA) and `sec1` (EC), and `KeyFormat.pem(format)` for PEM text with 64-column lines. The algorithm decides the family of the result: decoding with `Signature.ecdsaP256` gives a `Signature` key, with `KeyAgreement.ecdhP256` a `KeyAgreement` key. Secret keys are read and written only as JWK.

### [CryptoError](./interfaces/cryptography.md#cryptoerror)

`effect/crypto/CryptoError` — unstable

Every `effect/crypto` failure is one `CryptoError` whose `module` and `method` name the operation (`"Aead"`, `"decrypt"`) and whose `reason` is `InvalidArgument`, `InvalidKey`, `DecryptionFailed`, `Unsupported`, or `NotExtractable`. The message reads `"Aead.decrypt: <reason message>"`. Match reasons with `Effect.catchReason("CryptoError", "DecryptionFailed", ...)`, and narrow unknown values with `CryptoError.isCryptoError` / `isCryptoErrorReason`. `SecureRandom` and `Digest` never fail this way.

### [WebCrypto](./interfaces/cryptography.md#webcrypto)

`effect/crypto/WebCrypto` — unstable

`WebCrypto.WebCrypto` is a `Context.Reference` to the WebCrypto `Crypto` object (typed as `typeof globalThis.crypto`), defaulting to `globalThis.crypto`. Every `layerWebCrypto`, the `KeyFormat` functions, and key functions that touch `crypto.subtle` (such as `Mac.toBytes` on a `CryptoKey`) read it. `WebCrypto.layer(crypto)` swaps it for a polyfill, a worker's object, or a test double. A `CryptoKey` passed to `fromCryptoKey` must come from that same object. In a browser's insecure context, operations that need `crypto.subtle` die with `crypto.subtle is unavailable`, while layers still build and `SecureRandom` and the pure TypeScript algorithms (MD5, ChaCha20) keep working.

### [JOSE: tokens and keys](./interfaces/cryptography.md#jose-tokens-and-keys)

The `effect/jose` modules implement compact JSON Web Keys, Signatures, Encryption, and Tokens on the services above: HMAC runs on [`Mac`](#mac), asymmetric signatures on [`Signature`](#signature), encryption on [`Aead`](#aead) with IVs from `SecureRandom`, thumbprints on [`Digest`](#digest), and key import and export on [`KeyFormat`](#keyformat). Each function's requirements name only the services it uses (verifying with an HMAC key needs `Mac`, with a public key `Signature`), so provide the same crypto layers as for direct use. Import them from the barrel: `import { Jwk, Jwks, Jwt } from "effect/jose"`.

### [Jwk](./interfaces/cryptography.md#jwk)

`effect/jose/Jwk` — unstable

Imports keys and binds each to one algorithm. Imports need no services, because they run on [`KeyFormat`](#keyformat):

### [Jws](./interfaces/cryptography.md#jws)

`effect/jose/Jws` — unstable

Compact JSON Web Signatures over raw bytes. `Jws.sign(payload, key, header?)` returns a `Redacted<string>`. The header may set `typ`, `cty`, a `kid` (defaulting to the key's), and further JSON-valued parameters; `alg` comes from the key, and `crit` and `b64` cannot be set (a runtime attempt fails with `InvalidArgument`). `Jws.verify(token, key)` returns `{ protectedHeader, payload }`. Both require `Jws.KeyRequirements<K>`: `Mac` for an HMAC `SecretKey`, `Signature` for a `PrivateKey` or `PublicKey`.

### [Jwt](./interfaces/cryptography.md#jwt)

`effect/jose/Jwt` — unstable

Signed and encrypted JWTs whose claims are a `Schema`. `Jwt.sign(schema, claims, key, header?)` encodes the claims through the schema and signs them; the encoded value must be a JSON object whose registered claims have the right shapes, or `sign` fails with a `Schema.SchemaError`. `Jwt.verify(schema, token, key, options?)`, `Jwt.verifyWithKeySet(schema, token, { algorithms, ...options })`, and, for encrypted tokens, `Jwt.encrypt` / `Jwt.decrypt` (see [`Jwe`](#jwe)) complete the set. The error type is `Jwt.JwtError`, which is `JoseError | Schema.SchemaError`. A verified result is `{ claims, registeredClaims, protectedHeader }`, plus `key` from `verifyWithKeySet` and `decrypt`.

### [Jwe](./interfaces/cryptography.md#jwe)

`effect/jose/Jwe` — unstable

Compact JSON Web Encryption with a shared key: `dir` key management and `A256GCM` content encryption. `Jwe.encrypt(plaintext, key, header?)` takes a `SecretKey<"dir">` from `Jwk.importSecret(jwk, "dir")`, draws a random 96-bit IV, and requires `Aead | SecureRandom`. `alg` and `enc` are fixed, `kid` defaults to the key's, and `crit` and `zip` are rejected. The protected header is the AEAD's additional data, so a modified header fails decryption.

### [Jwks](./interfaces/cryptography.md#jwks)

`effect/jose/Jwks` — unstable

The `Jwks.Jwks` service resolves a verification key for a `Selection` of `{ algorithm, kid?, protectedHeader? }`. `Jwks.makeLocal(keySet)` and `Jwks.layerLocal(keySet)` serve a fixed set; `Jwks.makeRemote(options)` (requires `HttpClient | Scope`) and `Jwks.layerRemote(options)` (a `Layer<Jwks, JoseError, HttpClient>`) fetch one. The `Jwks.KeySet` schema accepts public JWKs, keeps keys of other families or curves without ever selecting them, and fails on a private or symmetric member anywhere in the set. A custom service built with `Jwks.Jwks.of({ resolve })` can select keys another way, for example from an extra header parameter; the `protectedHeader` it receives is unauthenticated.

### [JoseError](./interfaces/cryptography.md#joseerror)

`effect/jose/JoseError` — unstable

Every `effect/jose` failure is one `JoseError` whose `reason` says what went wrong. Configuration, transport, and import reasons carry a `description` (and a `cause` when there is one); authentication reasons carry nothing about the token, its claims, the plaintext, or the key.

# Application Systems

## [Reactivity & Atom](./systems/reactivity-atom.md)

Effect's reactive Atom graph, registries, hydration, typed clients, and framework bindings.

For a connected, application-oriented treatment of these modules, see [Reactivity — From Atoms to Mastery](./deep-dives/reactivity-from-atoms-to-mastery.md).

### [Atom](./systems/reactivity-atom.md#atom)

`effect/reactivity/Atom` — unstable

An `Atom<A>` is not a value — it's a recipe with a `read` function the registry runs, plus metadata for caching, laziness, and refresh. `Atom.make` is overloaded: pass a plain value for a writable cell, a function of `get` for a derived/computed atom, or an `Effect`/`Stream` for an atom whose value is an `AsyncResult`.

**Reach for it when** you have application state — local, derived, or fetched — that something needs to react to.

### [AtomRegistry](./systems/reactivity-atom.md#atomregistry)

`effect/reactivity/AtomRegistry` — unstable

The store. A `Registry` evaluates atoms, caches their current values in `Node`s, tracks parent/child dependency links, applies writes and refreshes, fans out to subscribers, and disposes unused nodes. Atoms are stateless descriptions; the registry is where state lives. The same atom can hold different values in two different registries. Most apps have exactly one (a framework provider creates it); tests and SSR spin up throwaway registries freely.

**Reach for it when** you need to read or write atoms outside a component — in tests, in an Effect, at the SSR boundary — or to scope a self-contained bundle of reactive state to a subtree.

### [AtomRef](./systems/reactivity-atom.md#atomref)

`effect/reactivity/AtomRef` — unstable

A standalone observable cell — read, set, `map`, `subscribe` — that does *not* go through a registry. `AtomRef.make(value)` gives a mutable ref; `.prop("field")` derives a child ref focused on one property of an object (or index of an array), and writing the child writes back through the parent immutably. `AtomRef.collection(items)` manages a reactive list of item refs with `push`/`insertAt`/`remove`.

**Reach for it when** you want surgical, per-field observable state with minimal machinery and no need for the registry's dependency tracking.

### [AsyncResult](./systems/reactivity-atom.md#asyncresult)

`effect/reactivity/AsyncResult` — unstable

The state of an asynchronous value. An `AsyncResult<A, E>` is one of three tags — `Initial` (no value yet), `Success` (carries `value` + `timestamp`), `Failure` (carries a `Cause<E>` on `.cause`, plus a `previousSuccess`) — and *every* state also carries a `waiting` boolean. The `waiting` flag lets you keep showing the last value while a refresh, retry, or revalidation is in flight instead of flashing back to a spinner.

**Reach for it when** — any atom backed by an Effect or Stream gives you one; render its four states (loading, stale-while-revalidating, error, success) cleanly.

### [AtomHttpApi](./systems/reactivity-atom.md#atomhttpapi)

`effect/reactivity/AtomHttpApi` — unstable

The bridge from a typed `HttpApi` client to ready-made atoms. `AtomHttpApi.Service<Self>()(id, { api, httpClient })` builds a `Context.Service` that wraps the generated client and exposes two atom factories: `.query(group, endpoint, request)` returns a read atom of `AsyncResult<Success, Error>`, and `.mutation(group, endpoint)` returns an `AtomResultFn` you write to fire the call. It owns its own `Atom.runtime`, so the HTTP client layer is provided automatically.

**Reach for it when** you have an `HttpApi` and want its endpoints as cache-aware, hydratable, auto-invalidating query/mutation atoms.

### [AtomRpc](./systems/reactivity-atom.md#atomrpc)

`effect/reactivity/AtomRpc` — unstable

Same as `AtomHttpApi` but for an `RpcGroup`. `AtomRpc.Service<Self>()(id, { group, protocol })` builds a service over a flattened RPC client with the same `.query(tag, payload, options)` and `.mutation(tag)` factories. If an RPC's success is an `RpcSchema.Stream`, its query returns a *pull atom* (`Atom.PullResult`) — write to it to pull the next batch and accumulate streamed results.

**Reach for it when** your backend speaks Effect RPC and you want the frontend to consume it as atoms — including streaming procedures surfaced as incremental pull atoms.

### [Hydration](./systems/reactivity-atom.md#hydration)

`effect/reactivity/Hydration` — unstable

Server-to-client state transfer for atoms. `Hydration.dehydrate(registry)` walks a registry and encodes every atom marked `Atom.serializable`; decoded-only HttpApi queries and non-stream RPC queries become serializable when given a `serializationKey`. Entries are keyed by that serialization key. With the default `encodeInitialAs: "ignore"`, or with `"value-only"`, the array is JSON-compatible; embed it only through a framework-safe escaped serialization channel, never raw string interpolation into a `<script>`. `Hydration.hydrate(registry, state)` preloads encoded values into another registry *before* atoms are first read, so the client renders without an initial refetch.

**Reach for it when** you do SSR or static rendering and want fetched atom state to survive the trip to the browser instead of refetching on mount.

### [Reactivity](./systems/reactivity-atom.md#reactivity)

`effect/reactivity/Reactivity` — unstable

The low-level invalidation engine that reactivity keys ride on. `Reactivity` is a `Context.Service` that maps arbitrary keys to handlers: `invalidate(keys)` runs every handler registered for those keys, `mutation(keys, effect)` wraps an effect so a successful run invalidates them, and `query(keys, effect)` / `stream(keys, effect)` expose an effect as a queue/stream that *reruns* whenever its keys are invalidated. It caches nothing — it is pure pub/sub for "this data changed."

**Reach for it when** you need key-based invalidation outside the atom layer (e.g. a SQL repo), or to understand what `reactivityKeys` are doing.

### [Framework bindings](./systems/reactivity-atom.md#framework-bindings)

The core above is framework-agnostic. Each binding (1) provides an `AtomRegistry` through the framework's context and (2) exposes hooks/primitives that subscribe a component to that registry.

### [@effect/atom-react in practice](./systems/reactivity-atom.md#effect-atom-react-in-practice)

Hooks built on `React.useSyncExternalStore` that read from the nearest `RegistryContext`. Wrap your tree in `RegistryProvider`; it creates one registry, accepts an optional `defaultIdleTTL`, and schedules whole-registry disposal 500 ms after unmount so an immediate remount can reuse it. The provider does not impose an idle TTL unless you pass one. The fallback context uses a standalone registry with a 400 ms default idle TTL, so a lone hook still works without a provider.

Sections: [End-to-end: effectful atom → AsyncResult → React](./systems/reactivity-atom.md#end-to-end-effectful-atom-asyncresult-react)

**Reach for it when** building UI: `useAtom` for local writable state, `useAtomValue` + `matchWithWaiting` (or `useAtomSuspense`) for fetched data, `useAtomSet` for mutations, and `RegistryProvider`/`HydrationBoundary` at the edges.

## [AI & Language Models](./systems/ai-language-models.md)

Language models, tools, toolkits, chat, prompts, embeddings, decisions, telemetry, errors, provider integrations including Amazon Bedrock, workload identity, and AG-UI frontends.

`effect/ai` provides a provider-agnostic AI toolkit. Business logic depends on `LanguageModel.LanguageModel` from context; a concrete provider (OpenAI, Anthropic, Amazon Bedrock, OpenRouter, or any OpenAI-compatible endpoint) is injected as a `Layer`. Schemas validate structured outputs and tool parameters, streaming is a `Stream`, errors are typed, and all calls are traced. Swapping providers requires changing a Layer, not application code. For fixed-answer judgments (a label, a rating on a scale, or a probability) there is a second, narrower service, [`DecisionModel`](#decisionmodel), with its own providers.

### [LanguageModel](./systems/ai-language-models.md#languagemodel)

`effect/ai/LanguageModel` — unstable

A provider-agnostic service for generating text, schema-validated objects, and streaming with first-class tool calling. Write against `LanguageModel.LanguageModel`; supply a provider Layer via `Effect.provide`.

Sections: [Tool-call resolution: concurrency and manual dispatch](./systems/ai-language-models.md#tool-call-resolution-concurrency-and-manual-dispatch) · [Service types are branded](./systems/ai-language-models.md#service-types-are-branded)

**Reach for it when** you need any LLM call — text, validated structured data, streaming, or tool use — without coupling to a vendor SDK. This is the default entry point.

### [Chat](./systems/ai-language-models.md#chat)

`effect/ai/Chat` — unstable

A stateful conversation on top of `LanguageModel`. Owns a mutable history `Ref`; each turn automatically includes prior messages, and an agentic loop automatically appends tool results before the next turn.

**Reach for it when** building a chatbot or agent that needs memory across turns, or needs save/restore of conversation state. For one-shot calls, plain `LanguageModel` is sufficient.

### [Tool](./systems/ai-language-models.md#tool)

`effect/ai/Tool` — unstable

A single typed function the model can call. Bundles a name, a description (shown to the model), a `parameters` `Schema` the model fills in, and a `success` `Schema` for the handler's result. Parameters are validated on the way in; results on the way out. Both cross the boundary through the schema's **JSON codec** (`Schema.toCodecJson`): a `Schema.Date` parameter accepts the ISO string a model or MCP client sends, and a `Schema.Date` or `Schema.BigInt` result reaches the model, MCP clients, and `Chat.exportJson` as JSON. Provider-executed tools keep the provider's own payload.

Sections: [Failure results and their wire format](./systems/ai-language-models.md#failure-results-and-their-wire-format) · [Client-executed tools](./systems/ai-language-models.md#client-executed-tools)

**Reach for it when** the model needs to fetch data or call an API mid-generation. Define the contract here; group and implement with `Toolkit`.

### [Toolkit](./systems/ai-language-models.md#toolkit)

`effect/ai/Toolkit` — unstable

A typed bundle of tools plus their handler implementations. `Toolkit.make(...tools)` groups any number of `Tool`s; `toolkit.toLayer(...)` produces a `Layer` satisfying every handler. The framework decodes parameters, invokes the right handler, validates the result, and feeds it back to the model automatically.

**Reach for it when** exposing one or more tools to a model. Define tools with `Tool`, group here, implement handlers with `toLayer`, and pass the toolkit to `generateText` or `Chat`.

### [Prompt](./systems/ai-language-models.md#prompt)

`effect/ai/Prompt` — unstable

The provider-neutral representation of conversation input: an ordered list of `Message`s (system/user/assistant), each composed of typed `Part`s (text, file, reasoning, tool-call, tool-result).

**Reach for it when** assembling prompts programmatically — injecting a system persona, stitching few-shot examples, or passing multi-part (text + file) input. For trivial calls, pass a string directly.

### [Response](./systems/ai-language-models.md#response)

`effect/ai/Response` — unstable

The typed vocabulary of model output. A non-streaming call returns a `GenerateTextResponse` whose `content` is an array of `Part`s; streaming yields a sequence of `StreamPart`s. Convenience getters avoid manual part parsing.

**Reach for it when** you need more than the final string — token accounting, finish reasons, reasoning traces, or precise streaming part handling.

### [EmbeddingModel](./systems/ai-language-models.md#embeddingmodel)

`effect/ai/EmbeddingModel` — unstable

A provider-agnostic service for turning text into vectors. `embed(input)` returns one embedding; `embedMany(inputs)` returns a batch with usage metadata. The single-input path is backed by a `RequestResolver`, so concurrent `embed` calls are automatically batched into one provider request.

**Reach for it when** building semantic search, role-matching, deduplication, or RAG retrieval — anything requiring text-to-vector conversion with automatic batching.

### [Decision](./systems/ai-language-models.md#decision)

`effect/ai/Decision` — unstable

A decision definition is plain data: one input `Schema` plus named questions whose answers come from a closed set. `Decision.make({ input, decisions })` builds it; nothing calls a model until [`DecisionModel.decide`](#decisionmodel) answers every decision in the definition in **one** provider call.

**Reach for it when** a question has a fixed answer space — routing, triage, policy checks, quality ratings — and you want the answer as a label or number your code can threshold, not as prose.

### [DecisionModel](./systems/ai-language-models.md#decisionmodel)

`effect/ai/DecisionModel` — unstable

The provider-neutral service that answers a `Decision` definition. `DecisionModel.decide(definition, { input })` encodes the input with `Schema.toCodecJson` (an explicit `undefined` field becomes `null`; an absent one stays absent), sends that state and every decision to the provider in one request, validates the reply, and returns `{ answers, usage }`. It requires `DecisionModel.DecisionModel` plus the input schema's encoding services, and fails only with `AiError`.

**Reach for it when** routing, triage, or scoring must be a number your code can threshold and audit. Keep `LanguageModel` for anything that needs words, structure, or tools.

### [Model](./systems/ai-language-models.md#model)

`effect/ai/Model` — unstable

The provider-agnostic handle every provider's `.model(...)` returns. A `Model` is a `Layer` that supplies AI services (`LanguageModel`, `EmbeddingModel`/`Dimensions`, or `DecisionModel`) and records two context values: `Model.ProviderName` and `Model.ModelName`.

**Reach for it when** you need an unsupported provider, or want to read/log which provider+model handled a request.

### [Tokenizer](./systems/ai-language-models.md#tokenizer)

`effect/ai/Tokenizer` — unstable

A service for counting tokens and truncating a `Prompt` to a token budget. `tokenize(input)` returns the token array (use `.length` for a count); `truncate(input, maxTokens)` drops whole messages from the front until the prompt fits.

**Reach for it when** you need to stay under a context window, estimate cost before a call, or trim long histories before sending.

### [IdGenerator](./systems/ai-language-models.md#idgenerator)

`effect/ai/IdGenerator` — unstable

A service that mints identifiers for AI artifacts, primarily tool-call IDs. Uses Effect's `Random` under the hood, so it is deterministic under a seeded test runtime.

**Reach for it when** you need stable, formatted, or deterministic tool-call IDs in tests, or a specific ID shape a provider expects.

### [Telemetry](./systems/ai-language-models.md#telemetry)

`effect/ai/Telemetry` — unstable

Helpers that write standardized GenAI attributes onto OpenTelemetry spans, following the current OTel GenAI semantic conventions (provider name, model, temperature, token usage, etc.). AI calls are already traced; this enriches those spans.

**Reach for it when** running AI in production and needing spans/metrics aligned with GenAI OTel conventions for cost dashboards, latency, and token tracking.

### [AiError](./systems/ai-language-models.md#aierror)

`effect/ai/AiError` — unstable

The typed failure channel for all AI operations. Every provider call, tool invocation, and structured decode fails with an `AiError` carrying a structured `reason`, enabling LLM failures to be handled like any other Effect error.

Sections: [Classifying a failure before retrying](./systems/ai-language-models.md#classifying-a-failure-before-retrying)

**Reach for it when** you need robust error handling — retry on rate limits, surface auth/quota problems, or translate provider failures into domain error types.

### [ResponseIdTracker](./systems/ai-language-models.md#responseidtracker)

`effect/ai/ResponseIdTracker` — unstable

An optimization service for providers that support continuing from a prior response (e.g. OpenAI's Responses API `previousResponseId`). Records which prompt messages were sent with each response; a follow-up call can send only the new messages plus the prior response ID.

**Reach for it when** running long multi-turn sessions against a provider that supports incremental continuation, to cut bandwidth and latency by not re-sending history.

### [AnthropicStructuredOutput](./systems/ai-language-models.md#anthropicstructuredoutput)

`effect/ai/AnthropicStructuredOutput` — unstable

The adapter enabling `generateObject` with Anthropic. `toCodecAnthropic(schema)` converts an Effect `Schema.Codec` into the JSON Schema subset Anthropic accepts and a matching codec to decode the model's reply back into the application type. The Anthropic provider wires this in automatically as its `codecTransformer`.

**Reach for it when** you need Anthropic-compatible JSON Schema by hand. For normal use, call `generateObject` with the Anthropic provider — this runs automatically.

### [OpenAiStructuredOutput](./systems/ai-language-models.md#openaistructuredoutput)

`effect/ai/OpenAiStructuredOutput` — unstable

The OpenAI counterpart. `toCodecOpenAI(schema)` turns an Effect `Schema.Codec` into OpenAI's structured-output JSON Schema subset plus a decoding codec. The OpenAI provider uses it automatically for `generateObject` and for the parameters of strict tools (strict unless the tool sets `Tool.Strict` to `false` or the model config sets `strictJsonSchema: false`); non-strict tools are advertised with their standard JSON Schema, so records and optional properties keep their natural shape.

**Reach for it when** you need OpenAI-compatible JSON Schema directly. Otherwise, `generateObject` with the OpenAI provider already uses it.

### [WorkloadIdentity](./systems/ai-language-models.md#workloadidentity)

`effect/ai/WorkloadIdentity` — unstable

Authenticates provider calls without a long-lived API key: the workload's own identity token (a projected Kubernetes service-account token, a cloud OIDC token) is exchanged at a token endpoint for a short-lived access token. `WorkloadIdentity.make({ tokenUrl, identityToken, exchangeRequest, defaultExpiresIn? })` returns, in an Effect that requires an `HttpClient`, an `HttpClient` transform that sends `Authorization: Bearer <access token>` on every request. Use the core module only for a token endpoint the provider packages do not cover; for the providers below, use their module:

**Reach for it when** a deployment's security policy forbids static provider keys and the platform can issue workload identity tokens.

### [AgUiSchema](./systems/ai-language-models.md#aguischema)

`effect/ai/AgUiSchema` — experimental

Schemas for the [Agent User Interaction (AG-UI)](https://docs.ag-ui.com) protocol, version `AgUiSchema.protocolVersion` (`"1.0"`): the `RunAgentInput` request body a frontend posts (`threadId`, `runId`, `messages`, `tools`, `context`, optional `state`, `forwardedProps`, `resume`), the conversation `Message` union (developer, system, user, assistant, tool, activity, reasoning), and the `Event` union an agent streams back (`RUN_*`, `STEP_*`, `TEXT_MESSAGE_*`, `TOOL_CALL_*`, `REASONING_*`, `STATE_*`, `SUBAGENT_*`, and more).

**Reach for it when** decoding AG-UI input or emitting hand-written AG-UI events; most servers only touch it through `AgUi` and `AgUiServer`.

### [AgUi](./systems/ai-language-models.md#agui)

`effect/ai/AgUi` — experimental

Pure conversions between `effect/ai` values and AG-UI; no I/O.

**Reach for it when** you serve AG-UI over a transport other than `AgUiServer`, or need to post-process the events.

### [AgUiServer](./systems/ai-language-models.md#aguiserver)

`effect/ai/AgUiServer` — experimental

Serves AG-UI runs over HTTP: clients `POST` a JSON `RunAgentInput` and read the run as Server-Sent Events (`Cache-Control: no-cache`, a keepalive comment every 15 seconds). An invalid body is answered with `400` before the stream opens.

**Reach for it when** a browser frontend that speaks AG-UI should drive an Effect agent with streaming text, tool calls, and frontend tools.

### [Production rules for model calls](./systems/ai-language-models.md#production-rules-for-model-calls)

The modules above make a model call typed; they do not make it safe. These rules are the short form of [Building a Production AI Capability](./deep-dives/building-a-production-ai-capability.md), which works through each with code.

### [Provider packages](./systems/ai-language-models.md#provider-packages)

Primitives live in `effect/ai`; concrete providers ship as satellite packages. Each exposes a `Client.layerConfig(...)` that reads its credentials from `Config` (requires an `HttpClient`) and one or more `.model(name)` constructors (each a `Model` Layer). Anthropic, OpenAI, and OpenRouter clients can also authenticate with [workload identity](#workloadidentity) instead of an API key. Every language-model provider produces the same `LanguageModel` service, and every decision provider the same `DecisionModel` service; switching providers is a one-line Layer change.

## [MCP Servers](./systems/mcp.md)

Model Context Protocol: MCP wire schemas, protocol adapters, McpServer over stdio and streamable HTTP, Skills, tracing, McpClient, and in-memory McpTest.

`effect/ai` ships a Model Context Protocol implementation: the wire schemas, the protocol adapters for every supported MCP revision, `McpServer`, which exposes your Effect services as tools, resources, prompts, and Agent Skills over stdio or streamable HTTP, an experimental `McpClient` for calling other MCP servers, and `McpTest` for testing a server in memory. Tools reuse the same `Tool` and `Toolkit` definitions as [AI & Language Models](./systems/ai-language-models.md). For an end-to-end walkthrough, read the [MCP deep dive](./deep-dives/exposing-an-effect-application-over-mcp.md).

### [McpSchema](./systems/mcp.md#mcpschema)

`effect/ai/McpSchema` — unstable

The complete Model Context Protocol (MCP) wire format as Effect `Schema`s and `Rpc` definitions: requests/results, resources and resource templates, prompts, completions, capabilities, and JSON-RPC error codes. The typed contract `McpServer` is built on.

**Reach for it when** building or extending an MCP server and needing the protocol's typed building blocks — especially `param` for resource/prompt templates.

### [McpProtocol](./systems/mcp.md#mcpprotocol)

`effect/ai/McpProtocol` — unstable

The versioned protocol adapter registry used by `McpServer`. It ships five adapters — `McpProtocol.v2024_11_05`, `v2025_03_26`, `v2025_06_18`, `v2025_11_25`, and `v2026_07_28` — each binding the matching client/server RPC groups and transport rules. The `2025-11-25` adapter adds sampling with tools, form- and URL-based elicitation (including identified object schemas), and `McpSchema.Icon` metadata (source URI, MIME type, sizes, light/dark theme) for server info, resources, resource templates, prompts, and tools. Server transports require a non-empty `protocols` list so negotiation is explicit rather than silently assuming whichever MCP revision a client sends.

**Reach for it when** constructing an MCP transport or deciding which protocol revisions a server is willing to negotiate.

### [McpServer](./systems/mcp.md#mcpserver)

`effect/ai/McpServer` — unstable

A batteries-included framework for building MCP servers — the protocol that lets editors and AI clients (Claude Desktop, IDEs) discover tools, resources, and prompts. Handles JSON-RPC plumbing; capabilities are registered as Layers and a transport is chosen.

Sections: [Request-scoped HTTP and typed requirements](./systems/mcp.md#request-scoped-http-and-typed-requirements) · [Request-level dependencies, middleware, and visibility](./systems/mcp.md#request-level-dependencies-middleware-and-visibility) · [Request context, client gating, and human input](./systems/mcp.md#request-context-client-gating-and-human-input) · [Skills](./systems/mcp.md#skills) · [Tracing](./systems/mcp.md#tracing)

**Reach for it when** you want capabilities usable from Claude Desktop, an IDE, or any MCP client — without writing JSON-RPC by hand.

### [McpClient](./systems/mcp.md#mcpclient)

`effect/ai/McpClient` — experimental

A scoped client for **calling another MCP server** over stdio or Streamable HTTP, on the `2025-11-25` or `2026-07-28` protocol revision. The transport fixes the revision: pass one `protocol` adapter; the client does not negotiate. It covers discovery (`listTools`, `listPrompts`, `listResources`), `callTool`, `getPrompt`, `readResource`, the Skills extension, and adapting the remote tools to a `Toolkit`. `client.capabilities` holds the server's advertised `McpSchema.ServerCapabilities`. Resource templates, completion, logging, subscriptions, roots, sampling, elicitation, OAuth, and retries are not implemented: server requests other than `ping` get method-not-found, and a `2026-07-28` `input_required` result fails with reason `UnsupportedError`.

**Reach for it when** your Effect program must consume tools, prompts, or resources that another process publishes over MCP.

### [McpClientError](./systems/mcp.md#mcpclienterror)

`effect/ai/McpClientError` — experimental

Every `McpClient` failure is one `McpClientError` (`_tag: "McpClientError"`) whose `reason` says what happened: `TransportError`, `ProtocolError` (JSON-RPC `code`, `data`), `HttpError` (`status`, `wwwAuthenticate`, `retryAfter`, and any JSON-RPC error in the body), `ClosedError` (`sessionExpired`), `TimeoutError` (`operation`), `LimitError`, `UnsupportedError`, `ValidationError`, `ConfigurationError`, and `ToolError` (the tool's `result`). The error's `message` and `cause` come from its reason. `isMcpClientError` and `isMcpClientErrorReason` are the guards.

**Reach for it when** recovering from specific remote-MCP failures: `Effect.catchReason` / `catchReasons` select reasons, `Effect.catchTag("McpClientError", ...)` handles them all.

### [McpTest](./systems/mcp.md#mcptest)

`effect/ai/McpTest` — unstable

`McpTest.makeClient(registrations, { protocols, protocolVersion?, clientInfo?, clientCapabilities? })` builds `McpServer.layer` over an in-memory `RpcServer.Protocol`, performs the handshake for the selected revision (the first adapter's by default), and returns a typed client in the surrounding `Scope`. Requests travel through the same JSON-RPC encoding, routing, middleware, visibility, and response encoding as stdio and HTTP, so results and errors match what a wire client sees: `ping`, `listTools`, `callTool`, `listResources`, `listResourceTemplates`, `readResource`, `subscribe`/`unsubscribe`, `listPrompts`, `getPrompt`, `complete`, and `setLevel` fail with `McpSchema.McpError`. Server notifications are queued on `client.notifications` in wire form; server-to-client requests (elicitation, sampling, roots) are rejected with method-not-found, so test `elicit` over a real session transport.

**Reach for it when** testing registrations, middleware, visibility, and the wire shape of results without opening a socket; reach for `HttpRouter.toWebHandler` when the HTTP admission rules themselves are under test.

## [Workflows & Durable Execution](./systems/workflows-durable-execution.md)

Durable workflows, activities, retries, interruption, persistence, and operational recovery.

### [Workflow](./systems/workflows-durable-execution.md#workflow)

`effect/workflow` — unstable

`Workflow.make(tag, options)` records a stable tag, a `payload` Schema, optional `success`/`error` Schemas, and an `idempotencyKey` function that turns a payload into a string. The engine derives a deterministic **execution id** from a length-prefixed encoding of the tag and the idempotency key (so a tag/key pair can't be confused with a different pair that happens to concatenate to the same string): starting the same logical work twice yields the same run, not two.

Sections: [Finalizers, compensation, and cancellation](./systems/workflows-durable-execution.md#finalizers-compensation-and-cancellation) · [Detached children and failure-suspended recovery](./systems/workflows-durable-execution.md#detached-children-and-failure-suspended-recovery) · [Abandoned run attempts](./systems/workflows-durable-execution.md#abandoned-run-attempts)

**Reach for it when** you have a multi-step business process that must survive restarts, suppress replay after completed steps are recorded, and be resumable and idempotent by a stable key.

### [Activity](./systems/workflows-durable-execution.md#activity)

`effect/workflow` — unstable

`Activity.make({ name, success, error, execute })` wraps an Effect so the engine runs it, persists its `Exit`, and — on later replay after that persistence succeeds — returns the stored result instead of re-executing. An `Activity` *is* an Effect (use `yield*`), so it composes like any other. Before the `Exit` is durably recorded, an interrupted or redelivered Activity may execute again.

**Reach for it when** a step inside a workflow touches the outside world or is otherwise non-deterministic, and its completed result must be remembered. Design the effect for at-least-once delivery with an idempotency token or transactional boundary.

### [DurableClock](./systems/workflows-durable-execution.md#durableclock)

`effect/workflow` — unstable

`DurableClock.sleep({ name, duration })` pauses a workflow for a duration that may be minutes, hours, or days with no fiber kept alive. A normal `Effect.sleep` holds a fiber; if the process dies, the sleep is gone. A durable sleep schedules a wake-up in the engine and *suspends* the workflow. When the timer fires (even on a different machine after a redeploy), the engine resumes the run. Internally it uses an in-memory activity for short durations (≤ 60-second threshold by default) and a scheduled `DurableDeferred` wake-up for longer ones.

**Reach for it when** a workflow must wait a meaningful amount of time (minutes to months) without pinning a fiber while staying crash-proof.

### [DurableDeferred](./systems/workflows-durable-execution.md#durabledeferred)

`effect/workflow` — unstable

`DurableDeferred.make(name, { success, error })` defines a durable, named wait-point. Inside a workflow, `DurableDeferred.await(deferred)` blocks by suspending the run until a result is recorded. Outside the workflow, complete it with a **token** via `DurableDeferred.succeed`, `fail`, or `done`.

**Reach for it when** a workflow must pause until an out-of-band signal arrives — an external approval, a third-party webhook.

### [DurableQueue](./systems/workflows-durable-execution.md#durablequeue)

`effect/workflow` — unstable

`DurableQueue.make({ name, payload, success, error, idempotencyKey })` defines a durable task queue. A workflow calls `DurableQueue.process(queue, payload)` to enqueue and suspend. A worker built with `DurableQueue.worker(queue, handler)` (a `Layer`) or `makeWorker` drains it.

**Reach for it when** a workflow needs to offload a unit of work to a pool of durable background workers and wait for the typed result.

### [WorkflowEngine](./systems/workflows-durable-execution.md#workflowengine)

`effect/workflow` — unstable

`WorkflowEngine` is the service that registers workflow handlers, runs executions, journals activity results, stores durable-deferred completions, schedules clocks, polls status, and suspends/resumes runs. `WorkflowInstance` is the per-run state threaded through a single execution.

**Reach for it when** wiring the app: `layerMemory` for tests/dev, a persistent engine for production, provided under your workflow layers.

### [WorkflowProxy](./systems/workflows-durable-execution.md#workflowproxy)

`effect/workflow` — unstable

`WorkflowProxy.toRpcGroup(workflows)` produces an `RpcGroup`; `WorkflowProxy.toHttpApiGroup(name, workflows)` produces an `HttpApiGroup` of POST endpoints. For each workflow you get three operations: execute, discard (fire-and-forget), and resume-by-execution-id.

**Reach for it when** something outside the workflow host needs to start or resume runs over RPC or HTTP with full types.

### [WorkflowProxyServer](./systems/workflows-durable-execution.md#workflowproxyserver)

`effect/workflow` — unstable

`WorkflowProxyServer.layerRpcHandlers(workflows)` implements the RPC group produced by `toRpcGroup`; `WorkflowProxyServer.layerHttpApi(api, groupName, workflows)` implements the HTTP group from `toHttpApiGroup`. Each routes execute/discard/resume requests to the matching workflow operation, keeping the engine and handlers on the server side.

**Reach for it when** you've derived a workflow RPC/HTTP surface and need to mount the handlers that actually run the executions.

### [Replay, versioning, and rollout](./systems/workflows-durable-execution.md#replay-versioning-and-rollout)

A journal outlives the code that wrote it. Every name and schema a run has touched is a compatibility contract for as long as that run can still replay.

### [Recovery testing and operations](./systems/workflows-durable-execution.md#recovery-testing-and-operations)

The engine's guarantees are only as good as the backend and the deployment. Test the failure windows on the real storage, and label every claim by its evidence: *proved by the library*, *depends on the adapter*, *depends on the deployment*, or *design guidance*.

## [Cluster & Sharding](./systems/cluster-sharding.md)

Cluster membership, sharding, entities, runners, proxies, messaging, message retention, Cloudflare Durable Objects, and distributed coordination.

Effect Cluster provides *entities*: stateful, addressable actors keyed by id, distributed across machines and reachable through typed RPC clients. A message to `dept-eng` is routed to the owning shard, the entity is spun up on demand, kept warm, and passivated when idle. Pair with durable message storage for at-least-once delivery that survives restarts.

### [Entity](./systems/cluster-sharding.md#entity)

`effect/cluster` — unstable

An `Entity` gives a stable *type name* and an *RPC protocol* to a family of values addressed by id. `Entity.make("Department", [RecordRaise, GetBudget])` declares a kind called Department, keyed by string id, with those RPCs. The cluster picks a shard for each id and routes requests to the owning runner.

**Reach for it when** you have per-key state that you want distributed across machines while keeping each key's logic single-threaded and addressable.

### [Sharding](./systems/cluster-sharding.md#sharding)

`effect/cluster` — unstable

The routing brain of the cluster; every entity client implicitly depends on it. `Sharding` decides which shard owns a given entity id, tracks shards belonging to the local runner, sends each message to a local handler or across the wire to the owning runner. Also registers entities and singletons, mints runner-local snowflake ids, and polls durable storage for persisted work.

Sections: [Transport options](./systems/cluster-sharding.md#transport-options) · [Rebalance and shutdown behavior](./systems/cluster-sharding.md#rebalance-and-shutdown-behavior) · [Running on Cloudflare Durable Objects](./systems/cluster-sharding.md#running-on-cloudflare-durable-objects)

**Reach for it when** building cluster tooling or custom routing. Otherwise, provide its *layer*.

### [Singleton](./systems/cluster-sharding.md#singleton)

`effect/cluster` — unstable

Run an effect on exactly one node in the cluster, regardless of cluster size. `Singleton.make(name, effect)` returns a `Layer` that registers a background effect with Sharding. The runner owning the singleton's shard starts it; if ownership moves (node dies, rebalance) the fiber is interrupted on the old node and restarted on the new owner.

**Reach for it when** you need a cluster-wide daemon that runs exactly once with failover, without standing up external coordination.

### [Runner](./systems/cluster-sharding.md#runner)

`effect/cluster` — unstable

Metadata describing one process that can host shards. A `Runner` is a `Schema.Class` bundling a `RunnerAddress`, the shard `groups` it participates in, and a relative `weight` used when distributing shards.

**Reach for it when** building custom membership or storage backends. Standard deployments get `Runner` values constructed by the transport layer from `ShardingConfig`.

### [Runners](./systems/cluster-sharding.md#runners)

`effect/cluster` — unstable

The node-to-node communication service. Where `Sharding` *decides* where a message goes, `Runners` *delivers* it. Can ping a runner, send a request or control envelope to a remote runner, notify a runner that work is waiting, and mark a runner address unavailable. Persisted notifications recover replies from storage; discarded volatile messages complete after delivery instead of waiting for an entity reply.

**Reach for it when** implementing a new cluster transport. Otherwise, pick a runner layer.

### [MessageStorage](./systems/cluster-sharding.md#messagestorage)

`effect/cluster` — unstable

The durability boundary. `MessageStorage` is the pluggable backend that makes mailboxes *recoverable*. Saves requests, control envelopes, and replies; finds unprocessed messages for shards a runner owns; deduplicates requests by primary key; tracks reply handlers waiting on responses. Upgrades delivery from best-effort to **at-least-once that survives a crash**.

**Reach for it when** you mark RPCs `Persisted`. Pick `SqlMessageStorage` in production, `layerMemory` in tests.

### [MessageRetention](./systems/cluster-sharding.md#messageretention)

`effect/cluster/MessageRetention` — unstable

Bounds the storage of a persisted entity. `MessageStorage` keeps every persisted request and its replies so that duplicates get the stored answer and interrupted work can resume; for a long-lived entity type that table only grows. `MessageRetention.make({ entity, retention, interval?, shardGroup? })` returns a `Layer<never, never, Sharding | MessageStorage>` that registers a [singleton](#singleton) (named `effect/cluster/MessageRetention/<entity type>`) which deletes the entity type's completed requests once their final reply is older than `retention`.

**Reach for it when** a persisted entity type handles an unbounded stream of distinct requests and you can name how long a duplicate must still be recognised.

### [Snowflake](./systems/cluster-sharding.md#snowflake)

`effect/cluster` — unstable

Distributed unique ids. A `Snowflake` is a branded `bigint` packed from a millisecond timestamp, a 10-bit machine id, and a 12-bit per-machine sequence. Globally unique *and* roughly time-sortable without a central coordinator.

**Reach for it when** you need ids that are unique across machines, sortable by time, and cheap to generate — for domain ids where a centralized sequence would be a bottleneck.

### [EntityProxy](./systems/cluster-sharding.md#entityproxy)

`effect/cluster` — unstable

A bridge that exposes a clustered entity to the outside world as a normal RPC service or HTTP API. `EntityProxy.toRpcGroup(entity)` derives an `RpcGroup`; `EntityProxy.toHttpApiGroup(name, entity)` derives an `HttpApiGroup`. Each entity RPC becomes a public operation whose payload gains an `entityId`, plus a fire-and-forget `...Discard` variant.

**Reach for it when** you have entities behind the cluster wall and need to expose them to external callers over HTTP or RPC without hand-writing a forwarding controller per method.

### [ClusterCron](./systems/cluster-sharding.md#clustercron)

`effect/cluster` — unstable

Distributed scheduled jobs. `ClusterCron.make` turns a `Cron.Cron` schedule into a `Layer` that coordinates one recurring job *across the whole cluster* rather than independently on every node.

**Reach for it when** you want durable, deduplicated, failover-safe cron scheduling in a multi-node deployment and can make the scheduled effect safe for at-least-once delivery.

### [ShardingConfig](./systems/cluster-sharding.md#shardingconfig)

`effect/cluster` — unstable

The configuration service for how *this* runner participates: its address, which shard groups it joins, how many shards per group, lock timing, mailbox and passivation limits, poll intervals, and health-check cadence.

Sections: [Capacity limits and their defaults](./systems/cluster-sharding.md#capacity-limits-and-their-defaults)

**Reach for it when** tuning cluster behavior, setting a runner's address/groups, or flipping a node into client-only mode.

### [EntityAddress](./systems/cluster-sharding.md#entityaddress)

`effect/cluster` — unstable

The full routing target for one entity instance: `entityType` + `entityId` + `shardId`, bundled as a `Schema.Class`. Used by messages, persisted envelopes, and entity managers. Read the current one inside a handler via `Entity.CurrentAddress`.

### [EntityId](./systems/cluster-sharding.md#entityid)

`effect/cluster` — unstable

A branded `string` — the routing key sharding hashes to pick a shard. `EntityId.make("dept-eng")` brands a raw string. The "which instance" half of an address.

### [EntityType](./systems/cluster-sharding.md#entitytype)

`effect/cluster` — unstable

A branded `string` naming a *family* of entities (e.g., the "Department" in `Entity.make("Department", ...)`). Distinguishes one kind of actor from another before any id is considered.

### [RunnerAddress](./systems/cluster-sharding.md#runneraddress)

`effect/cluster` — unstable

A `host` + `port` `Schema.Class` identifying how to reach a runner, with structural equality, hashing, and a stable primary key. `RunnerAddress.make("10.0.0.4", 34431)`.

### [ShardId](./systems/cluster-sharding.md#shardid)

`effect/cluster` — unstable

The address of a shard inside a group: a string `group` + numeric `id`, rendered as `group:id` at storage/routing boundaries. Entity ids hash into these; runners own sets of them.

### [SingletonAddress](./systems/cluster-sharding.md#singletonaddress)

`effect/cluster` — unstable

The runtime address of a registered singleton: its `name` paired with the `ShardId` chosen from that name and shard group. Used in registration events and local fiber tracking.

### [MachineId](./systems/cluster-sharding.md#machineid)

`effect/cluster` — unstable

A branded integer marking the machine component of a runner — the middle bits of a Snowflake. Keeps the value distinct from a plain `number` in APIs.

### [RunnerServer](./systems/cluster-sharding.md#runnerserver)

`effect/cluster` — unstable

Server side of the runner protocol: receives ping/notify/request/stream/envelope messages from other runners and forwards them into local `Sharding`. `layer` is the full server; `layerClientOnly` for nodes that send but do not serve.

### [RunnerHealth](./systems/cluster-sharding.md#runnerhealth)

`effect/cluster` — unstable

Decides whether a runner should be treated as alive, so Sharding knows when to move its shards. `layerNoop` (always alive), `layerPing` (heartbeat-based), and `layerK8s` (reads pod readiness).

### [SingleRunner](./systems/cluster-sharding.md#singlerunner)

`effect/cluster` — unstable

A single-process cluster layer: `Sharding` + no-op runner comms + no-op health + SQL message storage + env config, with SQL or in-memory runner storage. For embedded or small single-node deployments that still want durable entities. Requires a `SqlClient` and a `Digest.Digest` service (for example `NodeCrypto.layerDigest` or `Digest.layerWebCrypto`).

### [SocketRunner](./systems/cluster-sharding.md#socketrunner)

`effect/cluster` — unstable

Runs runner RPCs over a raw socket transport on a provided `SocketServer`. `layer` serves and provides clients; `layerClientOnly` dials without hosting shards. The engine under `NodeClusterSocket`.

### [HttpRunner](./systems/cluster-sharding.md#httprunner)

`effect/cluster` — unstable

Connects runner RPCs to HTTP and WebSocket transports — client protocol layers for dialing runner addresses, effects to serve handlers, and route layers for an `HttpRouter`. The engine under `NodeClusterHttp`. Client URLs are built from the runner address plus the configured path, inserting a `/` only when the path lacks one, so a slash-prefixed path such as `/cluster/rpc` is used as written (earlier builds produced a doubled slash).

### [TestRunner](./systems/cluster-sharding.md#testrunner)

`effect/cluster` — unstable

The smallest useful cluster runtime for tests: `Sharding` over in-memory message + runner storage, no-op transport, always-healthy checks. Exercise entity registration, routing, and mailbox persistence with no RPC servers or database — just provide `TestRunner.layer`.

### [K8sHttpClient](./systems/cluster-sharding.md#k8shttpclient)

`effect/cluster` — unstable

A thin HTTP client for the in-cluster Kubernetes API, using the mounted service-account token. Backs the K8s-aware health check and pod helpers (list pods, create pod) for runners that manage their own infrastructure.

### [K8sTypes](./systems/cluster-sharding.md#k8stypes)

`effect/cluster/K8sTypes` — unstable

Type-only Kubernetes declarations used by the cluster helpers: the transitive closure of `Pod` (spec, containers, volumes, affinity, status, metadata), vendored from `kubernetes-types` 1.30 so the `kubernetes-types` dependency could be dropped. `K8sHttpClient.makeCreatePod` takes a `K8sTypes.Pod`. It carries no runtime code and is not a general Kubernetes client model — import it when you construct a pod spec for the cluster helpers, not as a substitute for a full Kubernetes SDK.

### [SqlMessageStorage](./systems/cluster-sharding.md#sqlmessagestorage)

`effect/cluster` — unstable

The production `MessageStorage`: encodes envelopes and reply chunks into SQL tables, redelivers unprocessed messages after restart, deduplicates by primary key, and replays reply chunks until acknowledged. Ships migrations and an optional table prefix (`layerWith({ prefix })`; default `cluster`). Provide via `layer` with any `@effect/sql-*` client; the layer also requires `Digest.Digest` (from `effect/crypto/Digest`), used to hash deduplication keys longer than the 255-character `message_id` column. The platform cluster entrypoints supply it. `makeEncoded({ prefix? })` exposes the SQL `MessageStorage.Encoded` driver by itself for custom storage composition, and `makeEncodedStorage({ prefix? })` builds the same driver without migrations or startup SQL.

### [SqlRunnerStorage](./systems/cluster-sharding.md#sqlrunnerstorage)

`effect/cluster` — unstable

SQL-backed runner registration and shard-ownership: records runners, health flags, machine ids, and shard locks so multiple processes coordinate who owns each shard. Uses advisory locks on Postgres/MySQL when enabled. On PGlite (detected through `SqlClient.driver`), it uses lock-table rows and does not reserve PGlite's only connection.

### [RunnerStorage](./systems/cluster-sharding.md#runnerstorage)

`effect/cluster` — unstable

The typed service contract for runner registration and shard-lock state (which runners exist, their machine ids, which locks they hold). `layerMemory` for single-process/tests; `SqlRunnerStorage` implements it for real clusters.

### [ClusterSchema](./systems/cluster-sharding.md#clusterschema)

`effect/cluster` — unstable

Annotations that add cluster behavior to RPCs and entities without touching payload/result schemas: `Persisted` (durable delivery), `WithTransaction`, `Uninterruptible` (`true`, `"client"`, or `"server"`), `ShardGroup` (route ids to a group), `ClientTracingEnabled`, and `Dynamic` (compute server-side annotations from the decoded request). Attach with `.annotate` / `.annotateRpcs`. A `WithTransaction` value computed through `Dynamic` is kept when the entity re-runs a request, after a handler defect or after an interrupt that a server-uninterruptible persisted request ignores.

### [ClusterError](./systems/cluster-sharding.md#clustererror)

`effect/cluster` — unstable

Structured, schema-backed failures of the cluster runtime: `EntityNotAssignedToRunner`, `MailboxFull`, `AlreadyProcessingMessage`, `PersistenceError`, `MalformedMessage`, `RunnerUnavailable`, `RunnerNotRegistered`. Catch with `Effect.catchTag`.

### [ClusterMetrics](./systems/cluster-sharding.md#clustermetrics)

`effect/cluster` — unstable

Standard metrics the runtime records while running: active `entities`, `singletons`, registered `runners`, `runnersHealthy`, acquired `shards`, `shardsReleasing` (shards this runner is still releasing), the `shardReleaseDuration` timer, and `entityMailboxSizeMax` (largest resident mailbox per entity type). `entities` and the mailbox gauges are read when metrics are snapshotted and are removed when the entity manager shuts down. The opt-in `entityMailboxSize` gauge reports each resident entity's mailbox; enable it with `ShardingConfig.entityMailboxMetrics` or the `mailboxMetrics` option of `Entity.toLayer`, and its series is removed when the entity is released. Wire to a metrics exporter for cluster visibility.

### [ShardingRegistrationEvent](./systems/cluster-sharding.md#shardingregistrationevent)

`effect/cluster` — unstable

Events emitted by `Sharding.getRegistrationEvents` when the local runner registers an entity (`EntityRegistered`) or singleton (`SingletonRegistered`). Await at startup to confirm entities and singletons are live, or assert on them in tests.

### [Envelope](./systems/cluster-sharding.md#envelope)

`effect/cluster` — unstable

The transport envelopes entities exchange: a `Request` wraps a decoded payload with target address, RPC tag, request id, headers, and tracing context; `AckChunk` acknowledges streamed reply chunks; `Interrupt` cancels an in-flight request. Includes JSON codecs and storage primary-key helpers.

### [Message](./systems/cluster-sharding.md#message)

`effect/cluster` — unstable

The message shapes moved through the cluster, in `Incoming` and `Outgoing` variants (request, envelope, interrupt). Carries entity requests and control messages between callers, storage, transports, and handlers, with serialize/deserialize helpers matched to RPC schemas.

### [Reply](./systems/cluster-sharding.md#reply)

`effect/cluster` — unstable

Values produced by clustered RPC execution: a final `WithExit` carrying the RPC `Exit`, or a streaming `Chunk` carrying a non-empty batch of successes. `ReplyWithContext` carries encoding services; serialization helpers move replies through storage or transport.

### [DeliverAt](./systems/cluster-sharding.md#deliverat)

`effect/cluster` — unstable

A protocol for message payloads that carry their own scheduled delivery time. Implement the `DeliverAt.symbol` method to return a target `DateTime`, and durable storage will hold the message until then. The mechanism behind ClusterCron's timed runs.

### [EntityProxyServer](./systems/cluster-sharding.md#entityproxyserver)

`effect/cluster` — unstable

The handler side of EntityProxy: `layerRpcHandlers(entity)` and `layerHttpApi(api, name, entity)` implement the derived RPC/HTTP operations by reading `entityId`, calling the entity client, and forwarding the payload — including the discard variants. Both layers require `Sharding` plus the entity RPCs' server-side **and client-side** schema services (`Rpc.ServicesServer` and `Rpc.ServicesClient`), because the proxy decodes the public request and then re-encodes it as an entity client. If a payload or result schema needs a service to encode or decode, provide it to the proxy layer too.

### [EntityResource](./systems/cluster-sharding.md#entityresource)

`effect/cluster` — unstable

Keeps a long-lived resource alive across routine entity restarts, tied to an entity address. `make({ acquire, idleTimeToLive })` wraps it with a close scope that survives passivation; `makeK8sPod` manages a pod. Pairs with `Entity.keepAlive`.

### [ClusterWorkflowEngine](./systems/cluster-sharding.md#clusterworkflowengine)

`effect/cluster` — unstable

Runs durable `Workflow` executions on top of cluster sharding and message storage. Adapts `WorkflowEngine` so executions, activities, deferred completions, resumes, interrupts, and durable clock wakeups all become persisted cluster entity messages — durable, distributed orchestration for multi-step workflows. Provide its `layer` to back a workflow runtime with the cluster.

## [EventLog & Event Sourcing](./systems/event-log-event-sourcing.md)

Event logs, event sourcing, projections, encryption, identity, and session authorization.

Event sourcing stores immutable facts (decisions that happened) in an append-only log and derives current state by replaying them. The `effect/eventlog` modules provide schema-typed events, a durable journal, handlers that fold events into projections, and a sync protocol (optionally end-to-end encrypted) for multi-device convergence.

### [Event](./systems/event-log-event-sourcing.md#event)

`effect/eventlog` — unstable

`Event.make({ tag, primaryKey, payload, success, error })` defines one kind of fact. `tag` is the stable identifier; `primaryKey` extracts the aggregate/entity id from the decoded payload; `payload`, `success`, and `error` are Schemas. The payload Schema drives the `SchemaBinary` encoding (`event.payloadSchemaBinary`) used for journal entries and replication, so the payload schema is a persisted wire contract: evolve it compatibly.

### [EventGroup](./systems/event-log-event-sourcing.md#eventgroup)

`effect/eventlog` — unstable

A collection of related events forming a contract. Start from `EventGroup.empty` and chain `.add({ tag, primaryKey, payload, ... })` per event. Pure description — no writes, no execution — handed to `EventLog.schema` (to build a writer) and `EventLog.group` (to attach handlers). Tracks every event's tag and payload at the type level, enabling exhaustive handler checking.

### [EventLog](./systems/event-log-event-sourcing.md#eventlog)

`effect/eventlog` — unstable

The runtime service you write events through. Stitches together event groups, handlers, a journal, a local identity, optional remote replicas, and reactivity hooks. `EventLog.schema(...groups)` builds the typed writer contract; `EventLog.group(group, (handlers) => ...)` registers handlers; `EventLog.layer(schema, handlersLayer)` assembles the runtime.

### [EventRow](./systems/event-log-event-sourcing.md#eventrow)

`effect/eventlog/EventRow` — unstable

Mutable rows that converge across replicas, built on one event per row type with `set`, `patch`, and `remove` payloads. `EventRow.make(tag, { key, schema, error? })` returns a value to pass to `EventGroup.add`; its `set(row)`, `patch(key, fields)`, and `remove(key)` return `{ event, payload }`, which spreads into `log.write`, is an item of `writeMany`, and is the argument of a `makeClient` client. `EventRow.handler(row, { set, patch, remove })` resolves newer conflicts per top-level field (last writer wins; nested values are atomic) and calls at most one storage callback; `EventRow.compaction` drops entries that newer ones shadow.

### [EventJournal](./systems/event-log-event-sourcing.md#eventjournal)

`effect/eventlog` — unstable

The storage engine for entries. Records committed entries, exposes them for replay, publishes local changes to subscribers, and tracks per-remote sequence metadata for exchange with other journals. Ships `EventJournal.layerMemory` (in-process, ephemeral) and `EventJournal.layerIndexedDb` (persistent in the browser). The IndexedDB journal upgrades existing databases automatically: version 3 adds an `[event, primaryKey, id]` index so remote writes read only the stored entries that can conflict, and upload progress is checkpointed by insertion order, so entries imported later with older ids are still forwarded. After that upgrade, entries the remote has not confirmed may be uploaded once more.

### [EventLogEncryption](./systems/event-log-event-sourcing.md#eventlogencryption)

`effect/eventlog` — unstable

The crypto service for end-to-end-encrypted replication. Encrypts local journal entries into remote batches, decrypts incoming encrypted changes, hashes byte data, and generates event-log identities. `EventLogEncryption.layer` builds it from the `effect/crypto` `Aead`, `Digest`, and `SecureRandom` services in context (so Node apps can use the `NodeCrypto` layers); `EventLogEncryption.layerSubtle` supplies the Web Crypto layers on the `WebCrypto` reference (browsers, Node, edge).

### [EventLogRemote](./systems/event-log-event-sourcing.md#eventlogremote)

`effect/eventlog` — unstable

The client that connects a local event log to a remote replica. Writes local entries to a server, streams remote changes back from a given sequence number, and waits for local identity authentication. Two constructors: `EventLogRemote.makeEncrypted` / `layerEncrypted` (browser/edge, untrusted network) and `makeUnencrypted` / `layerUnencrypted` (trusted transports or tests).

### [EventLogServer](./systems/event-log-event-sourcing.md#eventlogserver)

`effect/eventlog` — unstable

Server-side handlers for the event-log remote protocol. `EventLogServer.layerRpcHandlers(options)` runs the hello/authenticate challenge flow, attaches the authenticated `EventLog.Identity` to subsequent requests, accepts single or chunked writes, and streams changes back. Also provides `EventLogServer.layerAuthMiddleware` for the auth boundary.

### [EventLogServerEncrypted](./systems/event-log-event-sourcing.md#eventlogserverencrypted)

`effect/eventlog` — unstable

A ready-made server that stores encrypted entries and replication metadata keyed by client public key and store id, streaming ciphertext back for the client to decrypt — plaintext is never visible server-side. `EventLogServerEncrypted.layer` mounts it over an `RpcServer.Protocol`; `layerStorageMemory` provides in-memory `Storage` for dev/tests. Use `SqlEventLogServerEncrypted` for durable storage.

### [EventLogServerUnencrypted](./systems/event-log-event-sourcing.md#eventlogserverunencrypted)

`effect/eventlog` — unstable

A plaintext server: accepts unencrypted batches, runs registered handlers server-side, stores entries, and streams backlog plus live changes. `EventLogServerUnencrypted.layer(schema, handlersLayer)` builds the full RPC server; supply infrastructure services `Storage` (e.g. `layerStorageMemory`), `EventLogServerAuthorization`, and `StoreMapping` (`layerStoreMappingStatic`). For trusted deployments, local dev, and tests.

### [EventLogSessionAuth](./systems/event-log-event-sourcing.md#eventlogsessionauth)

`effect/eventlog` — unstable

Challenge-response auth for sync sessions. A peer proves control of a session signing key (Ed25519): the server issues a short-lived challenge with `makeSessionAuthChallenge`; the client signs a canonical payload (remote id + challenge + event-log public key + signing key) via `signSessionAuthPayload`; the server verifies with `verifySessionAuthenticateRequest`. Domain-separated by the `"eventlog-auth-v1"` context string. `EventLogServer` keeps each pending challenge on the RPC connection that asked for it: overlapping `Hello`s share it until `Authenticate` consumes it, it expires after `SessionAuthChallengeTimeToLiveMillis`, and it is released when the client disconnects, so challenges cannot pile up across connections. `deriveSigningPublicKey(identity)` returns, as an `Effect<Uint8Array>`, the Ed25519 signing public key an identity will present (derived from its private key on the WebCrypto reference) — record it at provisioning time for the authorization policy above.

### [EventLogMessage](./systems/event-log-event-sourcing.md#eventlogmessage)

`effect/eventlog` — unstable

The wire protocol shared by clients and servers. Defines branded `StoreId`s, protocol errors, the hello/authenticate handshake, remote calls for writes and changes (`WriteSingleRpc`, `WriteChunkedRpc`, `ChangesRpc`), and encrypted vs. plaintext entry message formats — bundled into the `EventLogRemoteRpcs` group with an `EventLogAuthentication` middleware. The contract `EventLogRemote` and both server variants implement.

### [SqlEventJournal](./systems/event-log-event-sourcing.md#sqleventjournal)

`effect/eventlog` — unstable

A SQL-backed implementation of `EventJournal` on top of a `SqlClient`. `SqlEventJournal.layer(options?)` stores entries as encoded bytes and keeps per-remote sequence metadata in separate tables, giving a server or Node/SQLite program a durable journal that replays after restart. Drop-in replacement for `EventJournal.layerMemory`.

### [SqlEventLogServerEncrypted](./systems/event-log-event-sourcing.md#sqleventlogserverencrypted)

`effect/eventlog` — unstable

The durable `Storage` for `EventLogServerEncrypted`, persisting ciphertext in SQL. `SqlEventLogServerEncrypted.layerStorage(options?)` requires `SqlClient` and `Digest.Digest` (from `effect/crypto/Digest`; `layerStorageSubtle` supplies the Web Crypto one) and creates tables for the server remote id, session-auth bindings, and encrypted batches, assigns stable sequence numbers, and streams changes — without the database ever seeing plaintext, since clients encrypt/decrypt. Pass `compaction` to enable encrypted remote compaction. The `insertBatchSize` option is gone, and the entry-id tables carry a sequence column, so encrypted servers need fresh storage after the batch-format change. Existing table-name encodings are unchanged.

### [SqlEventLogServerUnencrypted](./systems/event-log-event-sourcing.md#sqleventlogserverunencrypted)

`effect/eventlog` — unstable

The durable `Storage` for `EventLogServerUnencrypted`, storing plaintext entries in SQL and streaming them back by store sequence. `SqlEventLogServerUnencrypted.layerStorage(options?)` creates dialect-specific tables for the server remote id, per-store sequence state, entries, and session-auth bindings. Pair with the unencrypted server layer for a trusted, restart-proof deployment.

# Decisions & Recipes

## [Choosing Effect Primitives](./reference/choosing-effect-primitives.md)

Contrastive decision tables for selecting Effect primitives by errors, services, lifetime, backpressure, durability, and distribution.

Most incorrect Effect code uses a real primitive for the wrong job. Choose first by semantics—absence, failure, coordination, ownership, durability, or distribution—and only then by API convenience.

### [Boundary rules before primitives](./reference/choosing-effect-primitives.md#boundary-rules-before-primitives)

One shape recurs in every table below: **keep a fact explicit inside the program and collapse it only at the edge that owns the decision.** If the collapse happens earlier, no primitive further down can recover the information.

### [Constructor by source convention](./reference/choosing-effect-primitives.md#constructor-by-source-convention)

Choose the constructor by how the wrapped JavaScript reports failure and when it does its work, not by which one makes `E` smallest. `sync` and `promise` are assertions that the code cannot fail; when it fails anyway the result is a defect.

### [Runner by host contract](./reference/choosing-effect-primitives.md#runner-by-host-contract)

Choose the runner by the outcome contract the host needs. Reusable code — services, domain functions, libraries — never calls one.

### [Option vs Result vs Effect](./reference/choosing-effect-primitives.md#option-vs-result-vs-effect)

Do not turn every `None` into a defect, or every pure `Result` into a running Effect. Convert at the boundary where semantics change: `Option` to a typed failure when absence becomes exceptional, and `Result` to `Effect` when the outcome joins effectful control flow. `Effect.result` and `Effect.option` capture typed failures only; `Effect.exit` captures the whole `Cause`.

### [Recovery operator by intent](./reference/choosing-effect-primitives.md#recovery-operator-by-intent)

Typed recovery operators look at the **first `Fail` reason**. A defect beside it takes precedence — the operator does not recover and propagates the error as a defect — while an interruption beside it is dropped when the handler's result replaces the `Cause`. Where an interruption or a second failure matters, use a guarded `catchCause`. Details: [Effect error handling](./foundations/errors-option-result.md#effect-error-handling), [Recovery and mixed causes](./foundations/errors-option-result.md#recovery-and-mixed-causes), [Classifying an error union](./foundations/errors-option-result.md#classifying-an-error-union).

### [Fail fast or accumulate](./reference/choosing-effect-primitives.md#fail-fast-or-accumulate)

A defect in any element still fails the whole call. Accumulate as data rather than as several `Fail` reasons in one `Cause`, because typed handlers inspect only the first one. Details: [Accumulating errors instead of failing fast](./foundations/errors-option-result.md#accumulating-errors-instead-of-failing-fast), [Parse options are boundary policy](./data/schema-in-depth.md#5-parse-options-are-boundary-policy).

### [Providing dependencies by seam](./reference/choosing-effect-primitives.md#providing-dependencies-by-seam)

Provide live implementations only at application or module edges and fakes only at test edges. Details: [Providing one value or building a graph](./foundations/services-context-layers.md#providing-one-value-or-building-a-graph), [What is shared, and what is rebuilt](./foundations/services-context-layers.md#what-is-shared-and-what-is-rebuilt), [Resourceful services](./foundations/services-context-layers.md#resourceful-services), [Optional services](./foundations/services-context-layers.md#optional-services).

### [Fork by owner](./reference/choosing-effect-primitives.md#fork-by-owner)

Name the owner first; the fork function follows.

### [Resource lifetime and bracket](./reference/choosing-effect-primitives.md#resource-lifetime-and-bracket)

Give every handle its own bracket, because a release is registered only after its acquisition succeeds. `Scope` left in `R` means nobody owns the lifetime yet. Details: [Interruption & resource safety](./foundations/core-runtime-execution.md#6-interruption-resource-safety), [When cleanup can fail](./foundations/core-runtime-execution.md#10-when-cleanup-can-fail), [One bracket per resource](./deep-dives/anatomy-of-a-real-effect-application.md#one-bracket-per-resource), [Owning resources inside a stream](./concurrency/streaming-channels.md#6-owning-resources-inside-a-stream).

### [Ref vs SynchronizedRef vs SubscriptionRef vs transactions](./reference/choosing-effect-primitives.md#ref-vs-synchronizedref-vs-subscriptionref-vs-transactions)

Effect 4 exposes software transactional memory through `Effect.tx`, `Effect.txRetry`, and the `Tx*` structures. There is no public `STM` namespace in this release.

### [Deferred vs Latch vs Queue vs PubSub](./reference/choosing-effect-primitives.md#deferred-vs-latch-vs-queue-vs-pubsub)

Classify the communication before naming a primitive. Each of the four classic coordination bugs — a hang, a leaked listener, duplicated work, an event seen by only one observer — comes from answering one of these questions wrongly.

### [Overload semantics at a glance](./reference/choosing-effect-primitives.md#overload-semantics-at-a-glance)

Decide which failure mode you want **before** picking a constructor. `dropping` and `sliding` are stated loss policies, never performance switches.

### [Per-call concurrency vs Semaphore vs Pool](./reference/choosing-effect-primitives.md#per-call-concurrency-vs-semaphore-vs-pool)

Never use `concurrency: "unbounded"` merely to make a batch faster. Use it only when the input is already tightly bounded and every downstream system can accept the resulting load. Several library defaults are unbounded and need an explicit number: `RpcServer` handler concurrency, AI tool-call resolution, and `Stream.callback` buffering. Details: [Write the execution policy first](./deep-dives/structured-concurrency-through-a-bounded-worker.md#write-the-execution-policy-first), [TTL is not a health check](./concurrency/concurrency-coordination.md#ttl-is-not-a-health-check), [Operational defaults](./interfaces/rpc.md#operational-defaults), [Tool-call resolution: concurrency and manual dispatch](./systems/ai-language-models.md#tool-call-resolution-concurrency-and-manual-dispatch).

### [Single-flight, cache, or batching](./reference/choosing-effect-primitives.md#single-flight-cache-or-batching)

Repeated work has three different shapes, and each tool fixes exactly one. Measure first: hit ratio, lookup count per request, resolver batch size.

### [Cache vs ScopedCache vs Resource vs RequestResolver](./reference/choosing-effect-primitives.md#cache-vs-scopedcache-vs-resource-vs-requestresolver)

With `Cache.make`, a cached failure lives exactly as long as a cached success; give failures their own lifetime with `Cache.makeWith`. Details: [Failure and freshness policy](./operations/caching-batching.md#failure-and-freshness-policy), [Keys are logical values](./operations/caching-batching.md#keys-are-logical-values).

### [Array, Chunk, Iterable vs Stream, Sink, Channel](./reference/choosing-effect-primitives.md#array-chunk-iterable-vs-stream-sink-channel)

`Stream.runCollect` is an explicit decision to move the entire remaining stream into memory. Prefer a bounded Sink, incremental `runForEach`, or streaming output when the size is not proven small.

### [Stream buffering and batching operators](./reference/choosing-effect-primitives.md#stream-buffering-and-batching-operators)

Flow-control depth, batch size, and rate are three different knobs. **Buffer capacity is not batch size.**

### [Wire codec: JSON, NDJSON, or SchemaBinary](./reference/choosing-effect-primitives.md#wire-codec-json-ndjson-or-schemabinary)

`SchemaBinary` is the default binary format for cluster runner transports and EventLog journals and remote messages, so switching a link or a journal to or from it changes bytes on the wire and on disk. `maxFrameSize` is unset by default on the raw codec; set it for untrusted peers. Details: [SchemaBinary](./concurrency/streaming-channels.md#schemabinary), [Ndjson](./concurrency/streaming-channels.md#ndjson), [RpcSerialization](./interfaces/rpc.md#rpcserialization), [Serialization codecs](./data/schema-in-depth.md#2-serialization-codecs).

### [HttpClient vs HttpRouter vs HttpApi vs RPC](./reference/choosing-effect-primitives.md#httpclient-vs-httprouter-vs-httpapi-vs-rpc)

These modules are `@stability unstable`; pin all Effect packages to exactly the same release. The adjacent [GraphQL](./interfaces/graphql.md) family is **experimental**, so it can change even in a patch release.

Sections: [When the remote contract is GraphQL](./reference/choosing-effect-primitives.md#when-the-remote-contract-is-graphql)

### [Retry vs repeat vs polling vs Workflow](./reference/choosing-effect-primitives.md#retry-vs-repeat-vs-polling-vs-workflow)

Always bound and classify retry. A retry policy that accepts every error can turn authorization, validation, or schema failures into an outage amplifier. The options form `{ while }` with no `schedule` or `times` is a zero-delay loop. `Effect.timeout` before `retry` bounds each attempt; after it, the whole operation. Details: [Retry policy checklist](./concurrency/scheduling-time.md#retry-policy-checklist), [Shorthand options for retry and repeat](./concurrency/scheduling-time.md#shorthand-options-for-retry-and-repeat), [Where the timeout sits relative to retry](./deep-dives/failure-retry-fallback-and-interruption.md#where-the-timeout-sits-relative-to-retry), [Replay, versioning, and rollout](./systems/workflows-durable-execution.md#replay-versioning-and-rollout).

### [Persistence vs EventLog vs Workflow vs Cluster](./reference/choosing-effect-primitives.md#persistence-vs-eventlog-vs-workflow-vs-cluster)

These systems compose rather than replace one another. A clustered Workflow runner may use Persistence for journals; a Workflow Activity may append to an EventLog; an Entity may use SQL for state. Select the semantic owner first, then add transport and storage deliberately. A write plus an external effect that must both happen is an outbox, not a bigger transaction. Details: [What each primitive guarantees](./tooling/persistence.md#what-each-primitive-guarantees), [Failure windows and honest guarantees](./tooling/persistence.md#failure-windows-and-honest-guarantees), [External effects after commit (outbox)](./interfaces/sql.md#external-effects-after-commit-outbox), [A compact selection guide](./deep-dives/durability-and-distribution-ladder.md#a-compact-selection-guide).

### [Test tool by claim](./reference/choosing-effect-primitives.md#test-tool-by-claim)

Pick the tool by the claim you need to prove; each is evidence for that claim and nothing beyond it.

### [Host and runtime ownership](./reference/choosing-effect-primitives.md#host-and-runtime-ownership)

A platform Layer says how a capability is implemented; the host decides who owns the runtime, what cancels work, and whether cleanup is awaited.

### [More choosers on their owning pages](./reference/choosing-effect-primitives.md#more-choosers-on-their-owning-pages)

### [A compact selection order](./reference/choosing-effect-primitives.md#a-compact-selection-order)

## [Review Checklists](./reference/review-checklists.md)

Design-review and code-review checklists for Effect services, errors, lifetimes, concurrency, boundaries, persistence, observability, and tests.

Use this page three ways: in a **design review**, read a section before code exists and treat every "not decided yet" as an open design question; in a **code review**, answer each question from the diff alone; as a **coding-agent self-check**, run the relevant sections over generated code before proposing it. Every question is phrased so that **yes** is the safe answer — a "no" or "cannot tell from the diff" is a finding, and the link leads to the section that owns the rule and its evidence.

### [Effect construction and running](./reference/review-checklists.md#effect-construction-and-running)

### [Errors and recovery](./reference/review-checklists.md#errors-and-recovery)

### [Services and Layers](./reference/review-checklists.md#services-and-layers)

### [Configuration and secrets](./reference/review-checklists.md#configuration-and-secrets)

### [Resources, scopes, and fibers](./reference/review-checklists.md#resources-scopes-and-fibers)

### [Concurrency, queues, and streams](./reference/review-checklists.md#concurrency-queues-and-streams)

### [Schema boundaries](./reference/review-checklists.md#schema-boundaries)

### [HTTP and RPC boundaries](./reference/review-checklists.md#http-and-rpc-boundaries)

### [SQL and persistence](./reference/review-checklists.md#sql-and-persistence)

### [Caching and batching](./reference/review-checklists.md#caching-and-batching)

### [Observability signals and export](./reference/review-checklists.md#observability-signals-and-export)

### [Tests](./reference/review-checklists.md#tests)

### [Hosts, startup, and shutdown](./reference/review-checklists.md#hosts-startup-and-shutdown)

### [MCP servers](./reference/review-checklists.md#mcp-servers)

### [Upgrading Effect versions](./reference/review-checklists.md#upgrading-effect-versions)

### [Deeper checklists on other pages](./reference/review-checklists.md#deeper-checklists-on-other-pages)

These sections go further than a review question can. Use them when a section above turns up more than one "no".

## [Troubleshooting](./troubleshooting/troubleshooting-and-anti-patterns.md)

Searchable symptoms, causes, and fixes for Effect programs, with focused diagnoses for the most common failures.

Debug Effect code in this order: read `Effect<A, E, R>`, inspect the complete `Cause` or `Exit`, check ownership and termination, and only then change the implementation. Most “Effect bugs” are mismatches between the intended success, failure, requirement, or lifetime and the type that was actually built.

### [Fast symptom map](./troubleshooting/troubleshooting-and-anti-patterns.md#fast-symptom-map)

Find the symptom, apply the first correction, and follow **Details** to the section that owns the explanation. Rows are grouped by where the symptom shows up, not by module. Each owning page carries the evidence; many of these causes were confirmed by running probes against the installed release rather than read off the types.

Sections: [Symptoms: construction, running, and cancellation](./troubleshooting/troubleshooting-and-anti-patterns.md#symptoms-construction-running-and-cancellation) · [Symptoms: errors and recovery](./troubleshooting/troubleshooting-and-anti-patterns.md#symptoms-errors-and-recovery) · [Symptoms: services, Layers, and configuration](./troubleshooting/troubleshooting-and-anti-patterns.md#symptoms-services-layers-and-configuration) · [Symptoms: resources, fibers, and coordination](./troubleshooting/troubleshooting-and-anti-patterns.md#symptoms-resources-fibers-and-coordination) · [Symptoms: streams and buffers](./troubleshooting/troubleshooting-and-anti-patterns.md#symptoms-streams-and-buffers) · [Symptoms: time, retry, and caching](./troubleshooting/troubleshooting-and-anti-patterns.md#symptoms-time-retry-and-caching) · [Symptoms: Schema and boundaries](./troubleshooting/troubleshooting-and-anti-patterns.md#symptoms-schema-and-boundaries) · [Symptoms: HTTP, RPC, and SQL](./troubleshooting/troubleshooting-and-anti-patterns.md#symptoms-http-rpc-and-sql) · [Symptoms: observability](./troubleshooting/troubleshooting-and-anti-patterns.md#symptoms-observability) · [Symptoms: durable systems and AI](./troubleshooting/troubleshooting-and-anti-patterns.md#symptoms-durable-systems-and-ai) · [Symptoms: tests](./troubleshooting/troubleshooting-and-anti-patterns.md#symptoms-tests) · [Symptoms: after an upgrade](./troubleshooting/troubleshooting-and-anti-patterns.md#symptoms-after-an-upgrade)

### [“My Effect never ran”](./troubleshooting/troubleshooting-and-anti-patterns.md#my-effect-never-ran)

An Effect is a lazy description. Calling a function that returns an Effect, placing an Effect inside `Effect.sync`, or constructing one inside an unreturned callback does not execute it.

### [A service is still present in R](./troubleshooting/troubleshooting-and-anti-patterns.md#a-service-is-still-present-in-r)

`R` is a set of unsatisfied service tags. Read a diagnostic such as `Effect<User, DbError, Users | SqlClient>` literally: the program still needs both services.

### [Typed failure versus defect and interruption](./troubleshooting/troubleshooting-and-anti-patterns.md#typed-failure-versus-defect-and-interruption)

`Effect.fail(error)` contributes to `E`. `Effect.die(defect)`, thrown exceptions not captured by an Effect constructor, and impossible-state bugs are defects. Interruption records that a fiber was cancelled. All are represented in `Cause`, but ordinary typed recovery sees only failures.

### [Scope closed or resource leaked](./troubleshooting/troubleshooting-and-anti-patterns.md#scope-closed-or-resource-leaked)

A value acquired with `Effect.acquireRelease`, `Pool.get`, `ScopedCache.get`, `PubSub.subscribe`, server Layers, or platform handles belongs to a Scope. The finalizer runs when that scope closes, regardless of success, typed failure, defect, or interruption.

### [Success-only cleanup](./troubleshooting/troubleshooting-and-anti-patterns.md#success-only-cleanup)

One mistake keeps reappearing under different names: a closing action attached to the happy path only. Code placed after `yield* work` runs on success; `Effect.tap` plus `Effect.tapError` still misses interruption, which is how timeouts, races, and shutdown end work. **Anything opened, incremented, awaited, or promised needs its closing action attached structurally** — `Scope`, `Effect.ensuring`, `Effect.acquireRelease`, `Effect.onExit`, or "iterate the entries" — so success, typed failure, defect, and interruption all pass through it.

### [Fiber, Queue, Deferred, Latch, and TestClock hangs](./troubleshooting/troubleshooting-and-anti-patterns.md#fiber-queue-deferred-latch-and-testclock-hangs)

A hang usually means the program has no event capable of satisfying its wait:

### [Unbounded by default](./troubleshooting/troubleshooting-and-anti-patterns.md#unbounded-by-default)

A buffer without a capacity is a memory leak waiting for load, a capacity without an overflow policy is an undecided design, and a loss nobody counts is invisible. Several defaults are unbounded, so "we never configured it" usually means "it has no limit". Audit these first when memory grows or a dependency is flooded:

### [Retrying the wrong error channel](./troubleshooting/troubleshooting-and-anti-patterns.md#retrying-the-wrong-error-channel)

`Effect.retry` reacts to typed failure, not defects, and reruns the entire wrapped Effect. Place it around the smallest idempotent operation, before `orDie`, and filter by retryability.

### [Schema Type and Encoded mismatch](./troubleshooting/troubleshooting-and-anti-patterns.md#schema-type-and-encoded-mismatch)

For a Schema `S`, `S["Encoded"]` is the boundary representation and `S["Type"]` is the domain value after decoding. A transformation makes the distinction visible—`Schema.NumberFromString` is encoded as a string and decoded as a number.

### [Missing platform Layer](./troubleshooting/troubleshooting-and-anti-patterns.md#missing-platform-layer)

Effect separates capabilities from host implementations. Importing `FileSystem`, `Path`, `HttpClient`, or server interfaces gives types and operations, not a Node/Bun/Deno/browser implementation.

### [Incompatible unstable package versions](./troubleshooting/troubleshooting-and-anti-patterns.md#incompatible-unstable-package-versions)

Keep application `effect` and `@effect/*` integration packages on the same release; compiler tooling such as `@effect/tsgo` has its own version line. Unstable packages share internal symbols, Schema types, Context tags, and peer dependencies; mixing release lines can produce huge structural errors or values that look identical but are not compatible.

### [What to capture in a bug report](./troubleshooting/troubleshooting-and-anti-patterns.md#what-to-capture-in-a-bug-report)

Record the exact package versions and lockfile, the inferred `Effect<A, E, R>`, the complete pretty-printed Cause/Exit, whether the program was interrupted, the owning Scope, and a minimal reproducer using the same platform Layer. For time/concurrency bugs, record the queue capacity/strategy, concurrency bound, fiber ownership, schedule, and whether TestClock or the live clock was installed.

## [Generated-Code Anti-Patterns](./troubleshooting/anti-patterns.md)

Code shapes to search generated or pasted Effect code for, why each is wrong, and the preferred replacement.

This is the list to check generated or pasted code against. Each row names the shape to search for, why it is wrong, the preferred shape, and the section that owns the explanation. For a reviewer's yes/no version of the same material, use the [Review Checklists](./reference/review-checklists.md).

### [Effect 3 names that do not exist in Effect 4](./troubleshooting/anti-patterns.md#effect-3-names-that-do-not-exist-in-effect-4)

Generated code most often breaks on a name carried over from Effect 3. Each of these fails to compile against this edition's audited release; use the Effect 4 spelling instead.

### [Anti-patterns: construction and running](./troubleshooting/anti-patterns.md#anti-patterns-construction-and-running)

### [Anti-patterns: errors and recovery](./troubleshooting/anti-patterns.md#anti-patterns-errors-and-recovery)

### [Anti-patterns: services, Layers, and configuration](./troubleshooting/anti-patterns.md#anti-patterns-services-layers-and-configuration)

### [Anti-patterns: resources, fibers, and state](./troubleshooting/anti-patterns.md#anti-patterns-resources-fibers-and-state)

### [Anti-patterns: concurrency, streams, and caching](./troubleshooting/anti-patterns.md#anti-patterns-concurrency-streams-and-caching)

### [Anti-patterns: Schema and boundaries](./troubleshooting/anti-patterns.md#anti-patterns-schema-and-boundaries)

### [Anti-patterns: HTTP, RPC, and SQL](./troubleshooting/anti-patterns.md#anti-patterns-http-rpc-and-sql)

### [Anti-patterns: observability and tests](./troubleshooting/anti-patterns.md#anti-patterns-observability-and-tests)

### [Anti-patterns: durable systems and AI](./troubleshooting/anti-patterns.md#anti-patterns-durable-systems-and-ai)

## [Recipe: A Service with Live and Test Layers](./recipes/service-and-layers.md)

A runnable service with live and test Layers, explicit requirements, and lifecycle boundaries.

Define the capability once, keep implementations in Layers, and let the program’s `R` show whether wiring is complete.

### [Contract](./recipes/service-and-layers.md#contract)

### [Complete file](./recipes/service-and-layers.md#complete-file)

**Runnable example.**

### [Why this primitive?](./recipes/service-and-layers.md#why-this-primitive)

`Context.Service` gives the capability one stable type-level key; `Layer` describes how an implementation is constructed and, when necessary, released. Business code depends on the capability, not a global singleton or a concrete client. Tests replace the Layer without changing the program.

### [Variations](./recipes/service-and-layers.md#variations)

**Prove that the test Layer is actually wired.** A test Layer that is declared but never provided still type-checks if something else satisfies the requirement, and the test passes against the wrong implementation. Make the assertion depend on state only the fake can produce. The fake below keeps its state in a `Ref` built by the Layer — so every `Effect.provide` starts clean — and exposes it through a small probe service:

### [Common wrong alternative](./recipes/service-and-layers.md#common-wrong-alternative)

Do not call `Effect.runPromise` inside `greet`, hide a client in a module-global variable, or pass dependencies manually through every function. Return Effects that retain `GreetingService` in `R`, compose all Layers once, and run only at the outer application boundary.

## [Recipe: Schema to HttpApi to SQL](./recipes/schema-httpapi-sql-boundary.md)

A complete typed boundary from Schema through HttpApi to SQL persistence.

Use one domain Schema across the HTTP contract and SQL result decoder, while keeping transport decoding and database access at their respective boundaries.

### [Contract](./recipes/schema-httpapi-sql-boundary.md#contract)

### [Complete file](./recipes/schema-httpapi-sql-boundary.md#complete-file)

**Runnable example.**

### [Why these primitives?](./recipes/schema-httpapi-sql-boundary.md#why-these-primitives)

`Employee` is the decoded domain value and the shared contract. HttpApi derives request decoding, response encoding, the typed client, routing, and OpenAPI shape from it. `SqlSchema` encodes requests before execution and decodes unknown driver rows back into `Employee`, preventing unchecked database objects from leaking inward. `SqlClient` remains an injected capability, so PGlite can be replaced by PostgreSQL without changing repository or handler code.

### [Production variation: a repository error and a declared conflict](./recipes/schema-httpapi-sql-boundary.md#production-variation-a-repository-error-and-a-declared-conflict)

The complete file turns every storage failure into a defect, which is right for a demo and too blunt for a service: a duplicate email is an outcome the caller can act on. The middle path keeps three things separate — what the repository owns, what the endpoint publishes, and what stays a defect.

### [Proving the boundary](./recipes/schema-httpapi-sql-boundary.md#proving-the-boundary)

`HttpApiTest` proves codecs, routing, and status mapping, but its typed client cannot send malformed input — encoding fails locally first. To prove that validation lives on the contract, send a raw request through `HttpRouter.toWebHandler` and assert both the `400` and that a counting repository fake was never called; the full test is in [What each test ring proves](./interfaces/http-api.md#what-each-test-ring-proves).

### [Common wrong alternative](./recipes/schema-httpapi-sql-boundary.md#common-wrong-alternative)

Do not cast driver rows to `Employee`, manually parse JSON in handlers, interpolate untrusted SQL text with string concatenation, or define separate request/response/database interfaces that silently drift. Parameterize values with the `sql` tag, decode every untrusted boundary with Schema, and map only intentional database failures into declared endpoint errors; unexpected invariant failures should remain visible.

## [Recipe: A Resource-Safe Bounded Worker](./recipes/resource-safe-bounded-worker.md)

A bounded Queue worker with structured concurrency, backpressure, and deterministic cleanup.

Use a bounded Queue for producer backpressure, a fixed number of supervised consumers for concurrency, and `acquireUseRelease` around each resource-owning job.

### [Contract](./recipes/resource-safe-bounded-worker.md#contract)

### [Complete file](./recipes/resource-safe-bounded-worker.md#complete-file)

**Runnable example.**

### [Why these primitives?](./recipes/resource-safe-bounded-worker.md#why-these-primitives)

The Queue owns buffering and backpressure; the two consumers define actual concurrency. `Effect.acquireUseRelease` owns the per-job resource even though processing can be interrupted. `Queue.end` is an explicit protocol event, so consumers do not remain blocked forever after the producer finishes.

### [Common wrong alternative](./recipes/resource-safe-bounded-worker.md#common-wrong-alternative)

Avoid `Effect.all(jobs.map(processJob), { concurrency: "unbounded" })` over uncontrolled input, a growing module-level array as a mailbox, or manual `acquire`/`release` calls with release only on the success path. Also do not confuse a Queue with PubSub: Queue distributes work among consumers; PubSub copies each event to every subscriber.

## [Recipe: Typed Retry with TestClock](./recipes/retry-with-test-clock.md)

Typed retry policy tested deterministically with TestClock.

Keep transient failures typed, classify them in the Schedule, fork the retrying operation, and advance virtual time instead of waiting in real time.

### [Contract](./recipes/retry-with-test-clock.md#contract)

### [Complete file](./recipes/retry-with-test-clock.md#complete-file)

**Runnable example.**

### [Why these primitives?](./recipes/retry-with-test-clock.md#why-these-primitives)

`Effect.retry` reacts to typed `TransientError`; the Schedule owns classification, delay, and the hard recurrence bound. TestClock replaces time at the service boundary, so the same retry implementation is tested without sleeps or timing races. Forking is essential because `TestClock.adjust` must execute while the retrying fiber is suspended.

### [Assert the shape of the policy](./recipes/retry-with-test-clock.md#assert-the-shape-of-the-policy)

**A retry policy is a specification, and `{"value":"ready","attempts":3}` checks very little of it.** That expectation also passes for a policy with no backoff at all, for one that retries permanent errors, and for one with the wrong multiplier. Test the two paths the policy distinguishes, and record *when* each attempt ran:

### [Common wrong alternative](./recipes/retry-with-test-clock.md#common-wrong-alternative)

Do not call `Effect.orDie` before retry, retry every error indefinitely, use `setTimeout` in tests, or join the sleeping fiber before adjusting time. External writes also need idempotency even with a correct Schedule: retry provides at-least-once attempts, not exactly-once effects.

## [Recipe: Production Observability](./recipes/production-observability.md)

Production logging, metrics, tracing, exporter Layers, and graceful flushing.

Instrument business work once with structured logs, metrics, and spans; select a local JSON logger or the OTLP exporter at the Layer boundary.

### [Contract](./recipes/production-observability.md#contract)

### [Complete file](./recipes/production-observability.md#complete-file)

**Runnable example.**

### [Why these primitives?](./recipes/production-observability.md#why-these-primitives)

Logs, spans, and metrics are fiber-aware Effect operations, so annotations and parent spans propagate without parameter plumbing. The exporter remains a Layer: tests can omit it, local runs can use JSON, and production can install OTLP without changing business logic. `Otlp.layerJson` is the compact default for all three signals and owns batching, HTTP export, retry behavior, and shutdown flush. Reach for the separate `@effect/opentelemetry` package's `NodeSdk` (imported from `@effect/opentelemetry/NodeSdk`; the package root does not re-export it) instead only when an existing OpenTelemetry setup (its SDK config, its exporters, its instrumentation) is already in place; new projects use `effect/observability`'s `Otlp`.

### [Before production](./recipes/production-observability.md#before-production)

### [Common wrong alternative](./recipes/production-observability.md#common-wrong-alternative)

Do not scatter vendor SDK calls, `console.log`, `Date.now`, or exporter construction through service methods. Do not create an OTLP Layer per request. Provide one observability graph at the application root, use `Effect.withSpan`/`Effect.fn`, structured log annotations, and Metric operations inside the program, and let the owning Scope flush and close exporters.

## [Recipe: A Graceful Node Entrypoint](./recipes/graceful-entrypoint-and-shutdown.md)

A Node application entrypoint with scoped resources, signals, and graceful shutdown.

Represent the long-lived application as a Layer, put every background fiber and acquired handle under its Scope, then hand the launched Layer to `NodeRuntime.runMain`.

### [Contract](./recipes/graceful-entrypoint-and-shutdown.md#contract)

### [Complete file](./recipes/graceful-entrypoint-and-shutdown.md#complete-file)

**Runnable example.**

### [Why these primitives?](./recipes/graceful-entrypoint-and-shutdown.md#why-these-primitives)

`Layer.effectDiscard` describes startup and scoped background work without exposing a service. `forkScoped` attaches the heartbeat to the Layer scope; `addFinalizer` declares cleanup beside acquisition. `Layer.launch` keeps that scope alive, and the platform runner translates process signals into Effect interruption before process teardown.

### [Adding readiness and a bounded drain](./recipes/graceful-entrypoint-and-shutdown.md#adding-readiness-and-a-bounded-drain)

The file above stops instantly because a heartbeat has nothing to finish. A worker that holds admitted jobs needs three more things, and none of them is a second shutdown code path — **shutdown order is just Layer order, reversed**, and finalizer order within one Layer, reversed:

### [Common wrong alternative](./recipes/graceful-entrypoint-and-shutdown.md#common-wrong-alternative)

Do not call `process.exit()` from business code, maintain a separate array of ad-hoc cleanup callbacks, use `forkDetach` for ordinary workers, or start a server outside Effect and hope its callbacks shut down in the right order. Abrupt exit can skip finalizers and telemetry flushes. Keep ownership in Scope and let interruption unwind it.

## [Recipe: ManagedRuntime at an Imperative Boundary](./recipes/managed-runtime-integration.md)

Safe integration of Effect services into imperative framework callbacks with ManagedRuntime.

Build the service graph once, call it from Promise-based callbacks many times, and dispose it when the host application stops.

### [Contract](./recipes/managed-runtime-integration.md#contract)

### [Complete file](./recipes/managed-runtime-integration.md#complete-file)

**Runnable example.**

### [A production-shaped bridge](./recipes/managed-runtime-integration.md#a-production-shaped-bridge)

The complete file shows the lifetime. A real host adds four obligations around it, and each is one line: **warm** the runtime at boot, **admit** or refuse before doing work, **forward** the host's `AbortSignal`, and make shutdown **one memoized operation** that stops intake, drains with a bound, and only then disposes.

### [How to test this seam](./recipes/managed-runtime-integration.md#how-to-test-this-seam)

Test the host lifecycle, not just one request. Give the Layer an acquisition counter and a release counter, then assert three things: many requests, including concurrent first requests, leave **acquired = 1**; after `onShutdown()` **released = 1**; after a second `onShutdown()` it is **still 1**. Those reject a runtime per request, a missing dispose, and a non-idempotent hook. For cancellation, abort on an "in flight" latch and await a cleanup gate rather than sleeping after the abort — the [cancellation recipe](./recipes/request-cancellation-through-a-host.md) is that test written as a program.

### [Why this primitive?](./recipes/managed-runtime-integration.md#why-this-primitive)

ManagedRuntime is the deliberate seam from Effect to a host that controls invocation: UI callbacks, existing Promise frameworks, plugin hooks, or gradual migration. It provides the same built Layer context to every run and gives that context one explicit lifetime.

### [Common wrong alternative](./recipes/managed-runtime-integration.md#common-wrong-alternative)

Do not sprinkle `Effect.runPromise(effect.pipe(Effect.provide(layer)))` throughout handlers. That can rebuild expensive Layers on every call and makes cleanup easy to forget.

## [Recipe: Request Cancellation Through a Host](./recipes/request-cancellation-through-a-host.md)

Forwarding a host's cancellation through ManagedRuntime and into a Promise adapter so abandoned requests stop their work.

When a framework that is not Effect owns the request — Express, Hono, a queue SDK, a plugin API — a client disconnect has to travel **two hops** before any work actually stops: from the host's `AbortSignal` into the Effect fiber, and from that fiber into the Promise-based SDK call at the bottom. This recipe wires both hops through one `ManagedRuntime` and proves each one in its output.

### [Contract](./recipes/request-cancellation-through-a-host.md#contract)

**Expected output (exact):**

### [Complete file](./recipes/request-cancellation-through-a-host.md#complete-file)

**Runnable example.**

### [Why it is shaped this way](./recipes/request-cancellation-through-a-host.md#why-it-is-shaped-this-way)

**Cancellation is only as good as its weakest hop.** The host knows the client left; the SDK holds the socket. Effect sits between them and owns the fiber, so it needs an input (the run option) and an output (the adapter's signal). Interruption then does the rest: it aborts the adapter's controller, runs the request scope's finalizers with the interrupt-only `Exit`, and completes the fiber — in that order, which is why the output shows the SDK abort *before* the permit is returned.

Sections: [The two broken versions](./recipes/request-cancellation-through-a-host.md#the-two-broken-versions)

### [Variations](./recipes/request-cancellation-through-a-host.md#variations)

## [Recipe: A Transactional Write with an Outbox](./recipes/transactional-write-with-outbox.md)

An atomic SQL write with a transactional outbox, commit-before-deliver ordering, and honest at-least-once delivery.

Commit a domain change and the event that announces it in one SQL transaction, then deliver the event after commit with honest at-least-once semantics.

### [Contract](./recipes/transactional-write-with-outbox.md#contract)

Sections: [Expected output](./recipes/transactional-write-with-outbox.md#expected-output)

### [Complete file](./recipes/transactional-write-with-outbox.md#complete-file)

**Runnable example.**

### [Why it is shaped this way](./recipes/transactional-write-with-outbox.md#why-it-is-shaped-this-way)

**The intent row is part of the state change.** `Raises.approve` wraps the salary update, the outbox insert, and the budget draw in one `sql.withTransaction`. Commit or rollback is decided solely by the `Exit` of that body, so the body contains no recovery: `MeritBudgetExceeded` leaves it as a failure and takes both writes with it. Publishing from inside the transaction would be wrong in both directions — a rollback cannot recall a delivered event, and a retried transaction would deliver it twice.

### [Variations](./recipes/transactional-write-with-outbox.md#variations)

# Tooling & Reference

## [CLI Framework](./tooling/cli-framework.md)

Typed command-line applications, arguments, flags, prompts, completions, help, documentation specs, and error handling.

The CLI modules define parsers, help, completions, prompts, and command handlers as typed values that compose with ordinary Effects and Layers. Import the barrel with `import { Argument, Command, Flag, Prompt } from "effect/cli"`, or use the module paths shown in each section.

### [CliConfig](./tooling/cli-framework.md#cliconfig)

`effect/cli/CliConfig` — unstable

A fiber-scoped `Context.Reference` controlling runner-wide CLI behavior. Its service contains the ordered list of built-in global flags installed by `Command.run`; the default is `GlobalFlag.BuiltIns`. Earlier action flags have precedence.

**Reach for it when** embedding a CLI, constraining its global surface, or removing a built-in flag that conflicts with your application.

### [Command](./tooling/cli-framework.md#command)

`effect/cli/Command` — unstable

A `Command<Name, Input, ContextInput, E, R>` is both a typed description of how to parse a command's flags and arguments and an Effect that yields its parsed input when run. Subcommands can `yield* parentCommand` inside their handlers to read the parent's typed config without prop-drilling.

Sections: [Key combinators](./tooling/cli-framework.md#key-combinators) · [Validating input across flags](./tooling/cli-framework.md#validating-input-across-flags) · [Testing a command](./tooling/cli-framework.md#testing-a-command)

### [Flag](./tooling/cli-framework.md#flag)

`effect/cli/Flag` — unstable

A `Flag<A>` is a typed parser for named CLI options (`--verbose`, `--shares 1000`). Flags are composable: chain `Flag.withDefault` to make optional, `Flag.optional` to get `Option<A>`, `Flag.withFallbackConfig` to satisfy from an environment variable when absent. Boolean flags: `--dry-run` alone means `true`; `--no-dry-run` negates it — rename that form with `Flag.withNegation("skip-dry-run")` or remove it with `Flag.withoutNegation` (both also change shell completions). An **omitted** boolean flag is not an implicit `false`: like every other flag it fails with `CliError.MissingOption` unless you add `Flag.withDefault(false)`, `Flag.optional`, or a config/prompt fallback. That makes absence uniform across flag types and lets a fallback chain decide it. The built-in global flags add their own `false` default.

Sections: [Flag constructors at a glance](./tooling/cli-framework.md#flag-constructors-at-a-glance) · [Validation, alternatives, and awkward values](./tooling/cli-framework.md#validation-alternatives-and-awkward-values) · [GNU-style optional flag values](./tooling/cli-framework.md#gnu-style-optional-flag-values)

### [Argument](./tooling/cli-framework.md#argument)

`effect/cli/Argument` — unstable

Positional command-line arguments — values without a `--name` prefix. `Argument<A>` is structurally identical to `Flag<A>` with nearly the same constructor surface; the distinction is named vs positional.

### [Param](./tooling/cli-framework.md#param)

`effect/cli/Param` — unstable

The shared machinery powering both `Flag` and `Argument`. A `Param<Kind, A>` carries a `Kind` type tag (`"flag"` or `"argument"`) determining tokenisation. All combinators (`withDefault`, `optional`, `map`, `mapEffect`, `filter`, `withFallbackConfig`, `withFallbackPrompt`, `withSchema`) are implemented once in `Param` and re-exported by both `Flag` and `Argument` (`variadic` is on `Argument` only).

### [Primitive](./tooling/cli-framework.md#primitive)

`effect/cli/Primitive` — unstable

Leaf-level value parsers converting raw CLI strings into typed TypeScript values. Each `Flag.*` and `Argument.*` constructor wraps a `Primitive`. A `Primitive<A>` is essentially `(rawString: string) => Effect<A>` with a display name; the framework derives shell completion types from `_tag`.

### [Prompt](./tooling/cli-framework.md#prompt)

`effect/cli/Prompt` — unstable

Interactive terminal prompts. A `Prompt<A>` is an Effect that runs a TUI render loop and yields a typed value on confirmation. Prompts compose with `Effect.gen`, chain with `Prompt.flatMap`, and collect with `Prompt.all`.

Sections: [Built-in prompt types](./tooling/cli-framework.md#built-in-prompt-types) · [Theming prompts](./tooling/cli-framework.md#theming-prompts)

### [HelpDoc](./tooling/cli-framework.md#helpdoc)

`effect/cli/HelpDoc` — unstable

The intermediate data structure for a command's help page. Captures description, usage line, flag/argument docs, inherited and global flag docs, subcommand listing, and examples — before any string formatting. Shared flags declared on ancestor commands arrive in `inheritedFlags` (rendered as an `INHERITED FLAGS` section), not in `flags`; `commandPath` and `globalFlagsScope` record where the command and its global flags are declared. Rendering is delegated to `CliOutput.Formatter`.

### [Completions](./tooling/cli-framework.md#completions)

`effect/cli/Completions` — unstable

Shell completion script generator. Given a `CommandDescriptor`, `Completions.generate` returns a static completion script string for Bash, Zsh, Fish, or PowerShell (`"powershell"`). The built-in `--completions` flag also accepts `pwsh` as an alias for `powershell`; use the canonical name for programmatic generation.

### [CommandSpec](./tooling/cli-framework.md#commandspec)

`effect/cli/CommandSpec` — unstable

A projection of one command path of a `Command` tree into plain data, for documentation tooling: reference pages, man pages, JSON schemas, or a check that every config fallback is documented. Where [`Completions.fromCommand`](#completions) deliberately drops what a shell should not offer, `CommandSpec` keeps everything: hidden flags and unlisted subcommands are included and marked, primitive types are not collapsed, and each flag says where it is declared.

**Reach for it when** generating documentation or a machine-readable description of a CLI in a build step. For shell scripts use `Completions`, and for rendering `--help` use `HelpDoc`.

### [GlobalFlag](./tooling/cli-framework.md#globalflag)

`effect/cli/GlobalFlag` — unstable

Built-in and user-defined flags that intercept parsing before the normal handler runs. A global flag is either an `Action` (runs a side-effect and exits) or a `Setting` (provides a context service to the handler). Built-ins: `Help`, `Version`, `Wizard`, `Completions`, `LogLevel`.

Sections: [Built-in globals](./tooling/cli-framework.md#built-in-globals)

### [CliError](./tooling/cli-framework.md#clierror)

`effect/cli/CliError` — unstable

The typed error union for the CLI parser. `CliError.CliError` is what `Command.run` may fail with — a discriminated union covering every parser and runner failure mode. `NodeRuntime.runMain` handles these automatically (the runner has already printed them; the exit code comes from the error); match on `_tag` when embedding a CLI in a larger Effect application or writing integration tests.

### [CliOutput](./tooling/cli-framework.md#clioutput)

`effect/cli/CliOutput` — unstable

Two services decide what built-in CLI output looks like and where it goes. `CliOutput.Formatter` is the renderer: it turns help documents, errors, and version strings into text; override it with `CliOutput.layer(myFormatter)`. `CliOutput.Presenter` is the sink: `Command.run` / `runWith` hand it an event (`Help` with reason `"Requested"` or `"Implicit"`, `InvalidInvocation` with the help document and errors, or `Version`) instead of writing to the console itself; override it with `CliOutput.layerPresenter(presenter)`.

### [TerminalCapabilities](./tooling/cli-framework.md#terminalcapabilities)

`effect/cli/TerminalCapabilities` — unstable

A `Context.Reference` of `{ canColor, canAnimate, canPrompt }` for the current process. Built-in `Command` help, version, and error output follows `canColor` (unless you install a `CliOutput.Formatter`), and fallback prompts from `Flag.withFallbackPrompt` / `Argument.withFallbackPrompt` run only when `canPrompt` is `true`. `canAnimate` is for your own output: it says whether stdout is being watched.

**Reach for it when** a CLI must behave correctly in CI, pipes, and dumb terminals, or when your own output should color and animate under the same rules as the built-in help.

## [Persistence](./tooling/persistence.md)

Persistence services, backing stores, serialization, primary keys, and durable application state.

The stack has three levels. `KeyValueStore` supplies raw string/binary storage and swappable backends; `Persistence` stores schema-typed request `Exit` values in named stores; `PersistedCache` and `PersistedQueue` add cache and queue behavior on top. Browser, SQL, Redis, and filesystem modules provide concrete storage layers without changing the typed interface. `RateLimiter` and `CircuitBreaker` keep shared counters and circuit state in the same memory or Redis backends, and `UserDirectories` resolves where a local application should keep its files.

### [What each primitive guarantees](./tooling/persistence.md#what-each-primitive-guarantees)

Pick the primitive from the guarantee you need, and read the right-hand column before relying on it.

### [KeyValueStore](./tooling/persistence.md#keyvaluestore)

`effect/persistence/KeyValueStore` — unstable

Effectful key-value store service for string and binary (`Uint8Array`) values. The lowest layer of the persistence stack — a uniform interface that `Persistence` and `PersistedCache` sit on top of. Swap the backend by swapping the layer.

Sections: [Available layers](./tooling/persistence.md#available-layers)

**Reach for it when** you need lightweight durable string storage without an opinionated client, or when building a custom persistence backend for higher-level modules.

### [UserDirectories](./tooling/persistence.md#userdirectories)

`effect/persistence/UserDirectories` — unstable

A service that resolves where a local application (a CLI, a desktop tool, a dev server) keeps its files: `home`, plus `config(appName)`, `data(appName)`, `cache(appName)`, and `state(appName)`, each an `Effect<string, PlatformError>`. It only computes paths; it creates no directory.

**Reach for it when** a locally installed program needs a conventional place for settings, caches, or history — typically as the directory of `KeyValueStore.layerFileSystem`.

### [Persistence](./tooling/persistence.md#persistence-1)

`effect/persistence/Persistence` — unstable

Service that creates named stores for schema-typed `Exit` values keyed by `Persistable` requests. Where `KeyValueStore` speaks raw strings, `Persistence` speaks typed success/failure results — it serializes an `Exit<A, E>` using the request's success and error schemas, and deserializes it on the next read.

Sections: [Backing layers](./tooling/persistence.md#backing-layers)

**Reach for it when** you want cross-restart memoization for expensive effectful computations and need the full typed `Exit` (success or failure) to survive a process restart.

### [Persistable](./tooling/persistence.md#persistable)

`effect/persistence/Persistable` — unstable

The protocol connecting a request value to its persistence schemas. A `Persistable<A, E>` is a `PrimaryKey` (provides a stable string key) that also carries a success schema `A` and an error schema `E` at the type level. `Persistence` and `PersistedCache` use those schemas to encode and decode the stored `Exit` value.

**Reach for it when** building a `PersistedCache` or using `RequestResolver.persisted` — schemas must be declared upfront so the persistence layer can serialize results.

### [PersistedCache](./tooling/persistence.md#persistedcache)

`effect/persistence/PersistedCache` — unstable

A two-tier cache: in-process `Cache` in front of a durable `Persistence` store. On a miss, it checks the persistence store before running the lookup. A persistence-layer hit restores the result without calling the lookup effect — across process restarts.

**Reach for it when** you want `Cache` semantics with durability — expensive lookups that should survive restarts and be shared across multiple worker processes connected to the same backing store.

### [PersistedQueue](./tooling/persistence.md#persistedqueue)

`effect/persistence/PersistedQueue` — unstable

A durable work queue backed by persistent storage. Items are schema-encoded before enqueueing; workers call `queue.take(handler)` to claim and process one item at a time. If the handler succeeds the item is acknowledged as processed; if it fails the item becomes visible again after a delay chosen by the queue's retry schedule, until `maxAttempts` is exhausted and the item is **dead-lettered** (marked failed and kept). Restarts replay unacknowledged items automatically.

Sections: [Using the SQL store as a transactional outbox](./tooling/persistence.md#using-the-sql-store-as-a-transactional-outbox) · [Failure windows and honest guarantees](./tooling/persistence.md#failure-windows-and-honest-guarantees) · [Recovery testing and operations](./tooling/persistence.md#recovery-testing-and-operations)

**Reach for it when** you need guaranteed-at-least-once delivery of background jobs that must survive process restarts and can be retried on failure.

### [RateLimiter](./tooling/persistence.md#ratelimiter)

`effect/persistence/RateLimiter` — unstable

A persistent token-bucket/fixed-window rate limiter. Stores counters in a shared backing store (memory or Redis), so limits apply across fibers and—with Redis—across multiple processes or pods.

Sections: [Algorithms](./tooling/persistence.md#algorithms)

**Reach for it when** you need rate limits that work across multiple fibers or processes — protecting external APIs or enforcing per-tenant quotas in a multi-worker deployment.

### [CircuitBreaker](./tooling/persistence.md#circuitbreaker)

`effect/persistence/CircuitBreaker` — experimental

Keyed circuit breakers for calls to an unreliable dependency. One breaker holds one circuit per key (a host, a tenant, an endpoint), and the circuit state lives in a `CircuitBreakerStore`: `layerStoreMemory()` keeps it in the process, `layerStoreRedis(options?)` (or `layerStoreRedisConfig`) shares it between processes through [`Redis`](#redis).

**Reach for it when** a dependency that is down should be failed fast and given room to recover, rather than hit by every caller and every retry.

### [Redis](./tooling/persistence.md#redis)

`effect/persistence/Redis` — unstable

A thin service wrapper around a Redis client used internally by the other persistence modules. Provides four primitives: `send` for raw Redis commands on the shared connection, `subscribe(channel)` for a scoped pub/sub subscription delivered as a `Queue.Dequeue<RedisMessage, RedisError>`, `eval` for executing typed Lua scripts via `EVALSHA` (with automatic script loading and SHA caching via `SCRIPT LOAD`), and `reserve` for leasing a dedicated pooled connection.

**Reach for it when** you want Redis backing for any persistence module, or when you need to run Lua scripts with automatic SHA caching and error handling.

## [Testing & Dev Tooling](./tooling/testing-dev-tooling.md)

Effect testing, Vitest integration, generators, doctests, language tooling, and repository tools.

Effect's test services make time, console output, randomness, and dependencies deterministic; `@effect/vitest` integrates those services with a test runner. The repository's documentation tools then compile and validate examples so docs can be treated like code rather than inert prose.

### [TestClock](./tooling/testing-dev-tooling.md#testclock)

`effect/testing/TestClock` — stable

A virtual clock that replaces the real clock inside Effect. `TestClock.adjust("1 hour")` fast-forwards time: every fiber sleeping until that point wakes immediately in scheduled order. Tests that would take minutes in wall time complete in milliseconds.

### [Deterministic crypto in tests](./tooling/testing-dev-tooling.md#deterministic-crypto-in-tests)

`effect/testing` has no crypto test service. Crypto is a set of family services in [`effect/crypto`](./interfaces/cryptography.md) — `SecureRandom`, `Digest`, `Mac`, `Aead`, `Signature`, and the rest — and a test replaces exactly the ones the code under test requires, with an ordinary Layer.

### [TestConsole](./tooling/testing-dev-tooling.md#testconsole)

`effect/testing/TestConsole` — unstable

A test implementation of the Effect `Console` service that captures output instead of printing it. All calls through `Console.log`, `Console.error`, etc. are recorded in memory for deterministic assertion via `TestConsole.logLines` and `TestConsole.errorLines`.

### [Arbitrary](./tooling/testing-dev-tooling.md#arbitrary)

`effect/Arbitrary` — unstable

Effect's native, **Schema-first** property-testing engine. It is not a fast-check bridge: `effect/testing/FastCheck`, `Schema.toArbitrary`, and the `fastCheck` options in `@effect/vitest` do not exist, and the `effect` package does not depend on fast-check.

Sections: [Shrinking, composition, and wire-side samples](./tooling/testing-dev-tooling.md#shrinking-composition-and-wire-side-samples) · [What a derived generator cannot test](./tooling/testing-dev-tooling.md#what-a-derived-generator-cannot-test)

### [TestSchema](./tooling/testing-dev-tooling.md#testschema)

`effect/testing/TestSchema` — unstable

A class-based helper wrapping a `Schema` with ergonomic methods for asserting decoding, encoding, construction (`make`), and property-based round-trip verification.

### [@effect/vitest](./tooling/testing-dev-tooling.md#effect-vitest)

The official Effect test runner adapter for Vitest. It requires Vitest 5 (`>=5.0.0 <6.0.0`), wraps Vitest's `it` with Effect-aware variants that handle fibers, provides the test environment (TestClock + TestConsole), cleans up scopes, and surfaces failures with pretty-printed `Cause` traces. It re-exports everything from `vitest`.

Sections: [Basic test shapes](./tooling/testing-dev-tooling.md#basic-test-shapes) · [Prove laziness and the static contract](./tooling/testing-dev-tooling.md#prove-laziness-and-the-static-contract) · [Sharing a layer across tests](./tooling/testing-dev-tooling.md#sharing-a-layer-across-tests) · [Property-based tests with `it.effect.prop`](./tooling/testing-dev-tooling.md#property-based-tests-with-it-effect-prop) · [In-memory test runtimes shipped with Effect](./tooling/testing-dev-tooling.md#in-memory-test-runtimes-shipped-with-effect)

### [Effect language service (@effect/tsgo)](./tooling/testing-dev-tooling.md#effect-language-service-effect-tsgo)

A build of TypeScript-Go with the Effect language service embedded. It reports Effect-specific mistakes — a floating Effect, an unprovided requirement, error handling on an Effect that cannot fail, two copies of `effect` in one program — as diagnostics, and offers quick fixes and refactors for them. The same rules run in the editor, in `tsc`, and in a dedicated CLI, which is what makes them usable in CI and by coding agents: the feedback arrives before any test runs.

### [@effect/docgen](./tooling/testing-dev-tooling.md#effect-docgen)

An opinionated documentation generator (Node 22.19.0 or later) for Effect-style TypeScript libraries. The `docgen` CLI reads source modules and JSDoc, enforces configurable description/example/`@since` policies, typechecks and runs `@example` blocks, and emits Markdown/site material. It is zero-config by default (`src` → `docs`) or configured with `docgen.json` and its bundled `schema.json`.

### [@effect/doctest](./tooling/testing-dev-tooling.md#effect-doctest)

A Vitest/Vite integration that extracts marked TypeScript examples from JSDoc, Markdown, and MDX and runs every fence as an isolated test module. Mark a fence `ts import.meta.vitest`; an optional `name="..."` labels it. Trailing `// => expectedExpression` assertions use Effect's `Equal.equals` semantics.

## [Cheat Sheet & Index](./reference/cheat-sheet-index.md)

A task-oriented Effect 4 cheat sheet and linked index into the concise handbook.

This page is the short retrieval layer for the handbook: one representative service, then a task-to-module map. Use search or the sidebar for the complete module treatment.

### [The house style, distilled](./reference/cheat-sheet-index.md#the-house-style-distilled)

### [Start here](./reference/cheat-sheet-index.md#start-here)

### [When several primitives look right](./reference/cheat-sheet-index.md#when-several-primitives-look-right)

The companion [Choosing Effect Primitives](./reference/choosing-effect-primitives.md) page is the contrastive layer: it compares error channels, required services, ownership, backpressure, durability, distribution, and the situations where each plausible choice is wrong.

### [What to reach for when…](./reference/cheat-sheet-index.md#what-to-reach-for-when)

Sections: [Build and run](./reference/cheat-sheet-index.md#build-and-run) · [Fail and recover](./reference/cheat-sheet-index.md#fail-and-recover) · [Depend and configure](./reference/cheat-sheet-index.md#depend-and-configure) · [Own lifetimes and fibers](./reference/cheat-sheet-index.md#own-lifetimes-and-fibers) · [Coordinate, share state, and stream](./reference/cheat-sheet-index.md#coordinate-share-state-and-stream) · [Time and scheduling](./reference/cheat-sheet-index.md#time-and-scheduling) · [Data and boundaries](./reference/cheat-sheet-index.md#data-and-boundaries) · [Interfaces](./reference/cheat-sheet-index.md#interfaces) · [Operate](./reference/cheat-sheet-index.md#operate) · [Durable and distributed systems](./reference/cheat-sheet-index.md#durable-and-distributed-systems) · [Test and tool](./reference/cheat-sheet-index.md#test-and-tool)

### [Recipes and deep dives by task](./reference/cheat-sheet-index.md#recipes-and-deep-dives-by-task)

## [Using the Handbook from an Agent](./reference/agent-guide.md)

How a coding agent should read this handbook: which Markdown artifact to fetch for which task, the .md URL rule, catalog and example-inventory fields, citing sections, and a drop-in instructions block.

This page is the reading protocol for coding agents and the tools that drive them. It says which generated artifact to fetch for which task, how to stay in Markdown instead of HTML, what the structured catalogs mean, how to cite a section, and what to do when the handbook does not answer. Humans are welcome too, but every rule below is written so an agent can follow it without judgment calls.

### [The one rule: fetch Markdown, never HTML](./reference/agent-guide.md#the-one-rule-fetch-markdown-never-html)

Every page of this site exists twice at the same path: the rendered HTML route and a Markdown twin with `.md` appended. `/data/schema` is a web page; `/data/schema.md` is the same content as plain Markdown. The landing page `/` is `/index.md`, and a section landing such as `/deep-dives/` is `/deep-dives/index.md`.

### [Match the edition to the installed Effect version](./reference/agent-guide.md#match-the-edition-to-the-installed-effect-version)

The handbook is published as **editions**, one per Effect `major.minor`, each audited against one exact release. The site root always serves the newest edition; every edition, including the newest, is also served under its own path — `/4.0/`, `/4.1/`, `/5.0/` — with the same relative layout, so `/4.0/data/schema.md` and `/5.0/data/schema.md` are the same page for different Effect versions.

### [Which artifact to fetch for which task](./reference/agent-guide.md#which-artifact-to-fetch-for-which-task)

Start at `llms.txt`. It is a few thousand words, lists every page and bundle with its current word count, and maps common intents to the exact section that answers them. From there, pick by task:

### [Reading the capability catalog](./reference/agent-guide.md#reading-the-capability-catalog)

`effect-4-catalog.json` is the structured form of the handbook's selection guidance. Each entry in `capabilities` describes one thing an agent might reach for:

### [Reading the example inventory](./reference/agent-guide.md#reading-the-example-inventory)

`effect-4-examples.json` lists every fenced TypeScript example in the handbook with its `source`, `heading`, line range, `sha256`, `sourceForm`, and `disposition`. Source form answers what you must supply:

### [Citing and quoting](./reference/agent-guide.md#citing-and-quoting)

Cite a section as its Markdown twin URL plus anchor, for example `/foundations/core-runtime-execution.md#effect`. Anchors are derived from the heading text — lower-case, with runs of non-alphanumeric characters replaced by a single hyphen — and a heading that repeats on one page gets a `-1`, `-2` suffix in document order. The module index and the catalog already contain the correct anchors, so copy from them rather than slugifying by hand.

### [When the handbook is not enough](./reference/agent-guide.md#when-the-handbook-is-not-enough)

The handbook covers the public surface of `effect` and the `@effect/*` packages at one audited release, with one representative example per module rather than a complete API reference. When it does not answer:

### [Drop-in instructions for your agent](./reference/agent-guide.md#drop-in-instructions-for-your-agent)

Paste this block into the project's `AGENTS.md`, `CLAUDE.md`, or equivalent and replace the host with the site you are reading. Everything it says is enforceable with a plain HTTP client.

### [What the generated artifacts are](./reference/agent-guide.md#what-the-generated-artifacts-are)

All of these are produced from the Markdown under `docs/` by the repository build and published at the site root. None is edited by hand.

## [Release History](./reference/release-history.md)

What changed between audited Effect releases: behavior, stability, renamed options and telemetry names, new modules, and handbook corrections, one entry per release.

This page records how the handbook has evolved: one entry per audited Effect release, newest first. Each entry names the release the handbook was audited against, the changes in Effect that a reader of the previous entry needs to know about, and what changed in the handbook itself.

### [`effect@4.1.4` — audited 2026-11-19](./reference/release-history.md#effect-4-1-4-audited-2026-11-19)

Edition **4.1** (patch update; full source audit). Tag [`effect@4.1.4`](https://github.com/Effect-TS/effect/tree/effect%404.1.4), commit [`289a53f7`](https://github.com/Effect-TS/effect/commit/289a53f7b1fc40049219c6e69022db2fb859c356), published 2026-11-11. Baseline: `effect@4.1.0`, the previous full source audit. Range reviewed: every package changelog entry and all 253 commits covering published 4.1.1, 4.1.2, 4.1.3, and 4.1.4, which the 4.1.1–4.1.3 entries below recorded only as dependency refreshes. npm omits `gitHead`; the tarball integrity and npm provenance (build commit `289a53f7`) match the release tag.

Sections: [Changes in Effect that matter to readers](./reference/release-history.md#changes-in-effect-that-matter-to-readers) · [Changes in the handbook](./reference/release-history.md#changes-in-the-handbook)

### [`effect@4.1.3` — audited 2026-11-10](./reference/release-history.md#effect-4-1-3-audited-2026-11-10)

Edition **4.1** (patch update). Tag [`effect@4.1.3`](https://github.com/Effect-TS/effect/tree/effect%404.1.3), commit [`7865dbbb`](https://github.com/Effect-TS/effect/commit/7865dbbb7b6a91691921dbb4febedf3ab94a348b), published 2026-11-10. Baseline: `effect@4.1.2`.

Sections: [Changes in Effect that matter to readers](./reference/release-history.md#changes-in-effect-that-matter-to-readers-1) · [Changes in the handbook](./reference/release-history.md#changes-in-the-handbook-1)

### [`effect@4.1.2` — audited 2026-11-02](./reference/release-history.md#effect-4-1-2-audited-2026-11-02)

Edition **4.1** (patch update). Tag [`effect@4.1.2`](https://github.com/Effect-TS/effect/tree/effect%404.1.2), commit [`506eef14`](https://github.com/Effect-TS/effect/commit/506eef143bcc1750ce58920aac1e45da7265d103), published 2026-11-02. Baseline: `effect@4.1.0`.

Sections: [Changes in Effect that matter to readers](./reference/release-history.md#changes-in-effect-that-matter-to-readers-2) · [Changes in the handbook](./reference/release-history.md#changes-in-the-handbook-2)

### [`effect@4.1.0` — audited 2026-10-29](./reference/release-history.md#effect-4-1-0-audited-2026-10-29)

Edition **4.1** (new edition; the 4.0 edition is frozen at `effect@4.0.5`). Tag [`effect@4.1.0`](https://github.com/Effect-TS/effect/tree/effect%404.1.0), commit [`9a91b192`](https://github.com/Effect-TS/effect/commit/9a91b1926a5fbfaffd302a7a41a94d4d53a1154e), published 2026-10-29. Baseline: `effect@4.0.5` (published 2026-10-15). Range reviewed: all package changelogs, changesets, and 579 commits covering published 4.0.6, 4.0.7, and 4.1.0. npm omits `gitHead`; the package integrity, provenance, and published source were checked against the release tag.

Sections: [Changes in Effect that matter to readers](./reference/release-history.md#changes-in-effect-that-matter-to-readers-3) · [Changes in the handbook](./reference/release-history.md#changes-in-the-handbook-3)

### [`effect@4.0.5` — audited 2026-10-22](./reference/release-history.md#effect-4-0-5-audited-2026-10-22)

Edition **4.0** (updated in place). Tag [`effect@4.0.5`](https://github.com/Effect-TS/effect/tree/effect%404.0.5), commit [`7f524e25`](https://github.com/Effect-TS/effect/commit/7f524e25cfb49a71ac39b0f44278d08d40dda5de), published 2026-10-15. Baseline: `effect@4.0.2` (published 2026-10-07). Range reviewed: all package changelogs, changesets, and 191 commits covering published 4.0.3, 4.0.4, and 4.0.5. npm omits `gitHead`; the package integrity, provenance, and published source were checked against the release tag.

Sections: [Changes in Effect that matter to readers](./reference/release-history.md#changes-in-effect-that-matter-to-readers-4) · [Changes in the handbook](./reference/release-history.md#changes-in-the-handbook-4)

### [`effect@4.0.2` — audited 2026-10-09](./reference/release-history.md#effect-4-0-2-audited-2026-10-09)

Edition **4.0** (updated in place). Tag [`effect@4.0.2`](https://github.com/Effect-TS/effect/tree/effect%404.0.2), commit `269a7c86`, published 2026-10-07. Baseline: `effect@4.0.0`. Range reviewed: every 4.0.1 and 4.0.2 changelog entry across all packages.

Sections: [Changes in Effect that matter to readers](./reference/release-history.md#changes-in-effect-that-matter-to-readers-5) · [Changes in the handbook](./reference/release-history.md#changes-in-the-handbook-5)

### [`effect@4.0.0` — audited 2026-10-01](./reference/release-history.md#effect-4-0-0-audited-2026-10-01)

Edition **4.0** (first edition). Tag [`effect@4.0.0`](https://github.com/Effect-TS/effect/tree/effect%404.0.0), commit `67ba4e46`, published 2026-10-01: the first stable release of Effect 4 and the baseline for every later entry.

Sections: [Changes in the handbook](./reference/release-history.md#changes-in-the-handbook-6)
