# Schemas define the boundary

> For agents: start with the [agent guide](https://ratstack.sh/llms.txt). Every page is Markdown by default; add `Accept: text/html` for HTML.

New on /news: [Foldkit 0.171.0 requires result Message schemas](/news).

Schema defines accepted values, runtime checks, and associated TypeScript types.
Decoding checks external input and produces an application value. Encoding produces its external representation.
A codec connects these two representations.

Define the values the application accepts before writing the handler.
Decode unknown input at the boundary. Encode results through the declared output schema.

## Use one model for types and runtime checks

`Schema.Struct` describes a record. `Schema.Literals` describes a fixed set of alternatives.
A schema's `Type` describes its decoded value; `Encoded` describes its external representation.
Those representations can differ when a codec transforms values.

packages/core/src/contracts.ts at b4d6b8f499e57bc76914ad70df3a0c99751ae28c; lines 115-126; highlighted none.

```typescript
const ContentKind = Schema.Literals(["law", "skill", "lore", "prompt"]);

export const SearchMatch = Schema.Struct({
  description: Schema.String,
  digest: Schema.String,
  excerpt: Schema.String,
  id: Schema.String,
  kind: ContentKind,
  routePath: Schema.String,
  score: Schema.Finite,
  title: Schema.String,
});
```

Content kinds have four accepted values. A match must carry the declared fields and a finite score.

Derive the TypeScript type from the schema rather than maintaining a second interface.
Use `Schema.Union` when accepted alternatives have different shapes, including tagged failures.

## Put the schemas in the contract

A contract declares an action's input, output, and failures.
The file-inspection contract names its input, result, and failure.

packages/core/src/contracts.ts at b4d6b8f499e57bc76914ad70df3a0c99751ae28c; lines 255-263; highlighted none.

```typescript
export const inspectFileContract = defineContract("inspectFile", {
  annotations: { idempotent: true, readOnly: true },
  description: "Count bytes, characters, words, and lines in a file",
  failure: FileStatsError,
  input: Schema.Struct({
    path: Schema.String.annotate({ description: "File to inspect" }),
  }),
  output: FileStatsSchema,
});
```

The schemas check values at runtime.

## Decode before dispatch

`Schema.decodeUnknownEffect` accepts unknown input and keeps decoding failures in the Effect error channel.
Our code-mode invoker calls the handler only after decoding succeeds.

packages/capability/src/to-code-mode.ts at b4d6b8f499e57bc76914ad70df3a0c99751ae28c; lines 208-221; highlighted none.

```typescript
      return Schema.decodeUnknownEffect(item.contract.input)(input).pipe(
        Effect.matchEffect({
          onFailure: () =>
            Effect.succeed(
              invokeFailure(
                "InvalidInput",
                "Capability input does not match its schema"
              )
            ),
          onSuccess: (decoded) =>
            run(decoded).pipe(
              Effect.provideContext(context),
              Effect.matchEffect({
                onFailure: (error) =>
```

Rejected input becomes `InvalidInput`. The domain handler receives the decoded value after validation.

The same invoker uses `Schema.encodeUnknownEffect` for declared outputs and failures.
For an already-typed value, `Schema.encodeEffect` supplies the typed encoding API.
JSON serialization alone does not check whether a result satisfies its contract.

## A schema states what a value means

The interest contract separates contact consent from sharing consent. Accepting contact does not authorize sharing.
Its answer fields are bounded strings.

`AbuseVerdictSchema` describes a hold flag, a finite score between zero and one, and signal names.
The `AbuseVerdict` type derives from that schema.
These are domain decisions; Schema does not choose them for us.

A generated input also does not supply a behavior assertion.
[Property tests](/lore/property-based-testing) still need an independent rule that those values must satisfy.

## Common wrong approach

A type assertion changes what TypeScript believes. It does not reject a malformed external value.
Decode at the boundary instead of casting it into a domain type.

Hand-written JSON parsing followed by a copied interface creates two models that can drift.
Use the schema's decoding and encoding APIs. Report malformed input separately from an expected [domain refusal](/lore/error-model).

## Effect idiom and house rule

- Schema defines runtime decoding, encoding, and the associated TypeScript types.
- In rat-stack, one capability contract supplies schemas to every interface projection.
- rat-stack also uses capabilities and a bodyless HTTP 400 response for malformed input.

See also: [one schema, three surfaces](/lore/one-schema-three-surfaces), [OpenAPI refusals](/lore/openapi-describes-the-refusal-too), [services](/lore/services-capture-dependencies), and [testing](/lore/tests-that-earn-their-place).

## Sources

1. [Effect contributors. 2026. Schema. Effect 4.0.0.](https://github.com/Effect-TS/effect/blob/67ba4e46a11ccda0b6761578bfd22c04ae00167d/packages/effect/src/Schema.ts)
   Effect-TS. Struct, Literals, Union, schema-derived types, and effectful decoding and encoding. Accessed 2026-10-06.

2. [Effect contributors. 2026. Schema basics.](https://github.com/Effect-TS/effect/blob/67ba4e46a11ccda0b6761578bfd22c04ae00167d/ai-docs/src/01_effect/02_schema/10_schema-basics.ts)
   Effect-TS. Schema models expose Type and Encoded representations and reusable effectful parsers. Accessed 2026-10-06.

3. [rat-stack contributors. 2026. Shared capability contracts.](https://github.com/joelhooks/rat-stack/blob/65e9465f38092e24486392f22c08f45d61230c20/packages/core/src/contracts.ts)
   rat-stack. Contract schemas model input, output, failures, records, and literal alternatives. Accessed 2026-10-06.

4. [rat-stack contributors. 2026. Code-mode projection.](https://github.com/joelhooks/rat-stack/blob/65e9465f38092e24486392f22c08f45d61230c20/packages/capability/src/to-code-mode.ts)
   rat-stack. The invoker decodes input before dispatch and encodes declared outputs and failures. Accessed 2026-10-06.

5. [rat-stack contributors. 2026. Interest application contract.](https://github.com/joelhooks/rat-stack/blob/65e9465f38092e24486392f22c08f45d61230c20/packages/core/src/join-interest-contract.ts)
   rat-stack. Contact consent and sharing consent remain separate fields. Accessed 2026-10-06.

6. [rat-stack contributors. 2026. Abuse score schemas.](https://github.com/joelhooks/rat-stack/blob/65e9465f38092e24486392f22c08f45d61230c20/packages/core/src/abuse-score.ts)
   rat-stack. The verdict type derives from a schema with a finite bounded score. Accessed 2026-10-06.

7. [Langton, Kit. 2026. Data Modeling. Effect Solutions.](https://github.com/kitlangton/effect-solutions/blob/09f82e6c5c928e7232cd32daf04d7c6a830b63f7/packages/website/docs/05-data-modeling.md)
   Kit Langton. Topic framing for records, alternatives, and schema-backed domain values; no chess example is copied. Accessed 2026-10-06.

## Lore on this page

- [Capabilities](/systems/capabilities)

## Linked from

- A browser send follows one path to the capability → In the Foldkit docs browser, a search is a Message, then an update, then a named Command that calls the search capability over RPC on a cache miss and returns a result Message. → [Read page](https://ratstack.sh/lore/a-browser-send-follows-one-path)

- add-a-feature-flag → Declare a typed feature flag, its scoped evidence ladder, approval roles, removal date, and durable ledger adapter. → [Read page](https://ratstack.sh/skills/add-a-feature-flag)

- Agent guide → An Effect stack so pure (aspirational) Kit Langton will blush. → [Read page](https://ratstack.sh/llms.txt)

- AT Protocol separates identity, data, and application schemas → AT Protocol connects persistent account identifiers, signed public repositories, hosting services, and shared schemas. → [Read page](https://ratstack.sh/lore/at-protocol)

- CAFE all stars → Public profiles of people and channels who build with Cloudflare, Alchemy, Foldkit and Effect, served by five read-only capabilities. → [Read page](https://ratstack.sh/systems/all-stars)

- CAFE names the Cloudflare, Alchemy, Foldkit and Effect stack → CAFE is a named stack: Cloudflare runs the app, Alchemy declares it, Foldkit draws the UI, and Effect does the typed work. → [Read page](https://ratstack.sh/lore/cafe-stack)

- Change log → What changed in the files served here, newest first. → [Read page](https://ratstack.sh/log)

- Code snippets quote a pinned source → Shipped design brief: pinned Git objects, typed diagnostics, and one build-only snippet model for both views. → [Read page](https://ratstack.sh/lore/code-snippets)

- Durability starts with a recovery record → A reading order for storage, replay, worker ownership, overload, and recovery tests. → [Read page](https://ratstack.sh/lore/durability)

- Effect basics → An Effect describes work, expected failures, and required services before a runtime executes it. → [Read page](https://ratstack.sh/lore/effect-basics)

- Effect keeps the surfaces on one contract → Schema owns values, projections build interfaces, and Layers supply implementations. → [Read page](https://ratstack.sh/lore/how-we-do-it-with-effect)

- Errors are part of the interface → An author error needs a location, the rejected input, and a repair. → [Read page](https://ratstack.sh/lore/errors-are-part-of-the-interface)

- Feature flags → Typed feature flags with owners, removal dates, and stable subject rollouts. → [Read page](https://ratstack.sh/systems/flags)

- Flags climb on evidence → A flag ladder connects each rollout step to scoped measurements, approval, and a durable receipt. → [Read page](https://ratstack.sh/lore/flags-climb-on-evidence)

- Full agent guide → An Effect stack so pure (aspirational) Kit Langton will blush. → [Read page](https://ratstack.sh/llms-full.txt)

- Handle expected failures without hiding defects → Declare expected failures, preserve their context, and recover by tag without turning crashes into successful outcomes. → [Read page](https://ratstack.sh/lore/error-model)

- HTTP success needs a status check and a decoder → Supply the client, check the response status, decode accepted data, and name failures at the adapter boundary. → [Read page](https://ratstack.sh/lore/http-responses-need-validation)

- Lifecycles are machines → XState owns finite lifecycle states while declared Effect actors own side effects. → [Read page](https://ratstack.sh/lore/lifecycles-are-machines)

- Old events must still decode → Retained data needs compatibility rules before recovery depends on it. → [Read page](https://ratstack.sh/lore/old-events-must-still-decode)

- onboard-a-list → Analyze or migrate an email list. Measure sanitation rules, preserve stops, choose a cohort, and verify an authorized import or sending cutover. → [Read page](https://ratstack.sh/skills/onboard-a-list)

- One capability, every surface → A schema-typed contract and one handler feed every interface rat-stack keeps. → [Read page](https://ratstack.sh/lore/one-capability-every-surface)

- One schema, three surfaces → A capability contract feeds CLI, HTTP, and MCP; OpenAPI is generated output, not their input. → [Read page](https://ratstack.sh/lore/one-schema-three-surfaces)

- OpenAPI describes the refusal too → The generated HTTP contract declares inputs, outputs, and the bodyless 400 returned when decoding fails. → [Read page](https://ratstack.sh/lore/openapi-describes-the-refusal-too)

- Queues, Pipelines, Workflows and K2 do different jobs → Pick a Cloudflare product for work outside a request by the unit you track: a message, a row, a step, or a record in a log. → [Read page](https://ratstack.sh/lore/queues-pipelines-workflows-and-k2-do-different-jobs)

- Rat Stack lore | rat-stack → Short, source-grounded notes on the ideas and decisions behind rat-stack. → [Read page](https://ratstack.sh/lore)

- RatTube → Curated videos with transcript-based summaries, timestamped notes, and links to wiki concepts, built from one data file. → [Read page](https://ratstack.sh/systems/tube)

- Replay needs stable inputs → Historical processing must not silently depend on today’s clock or external decisions. → [Read page](https://ratstack.sh/lore/replay-needs-stable-inputs)

- Shared schemas need a transition period → Keep old and new representations usable while consumers migrate. → [Read page](https://ratstack.sh/lore/schema-changes-need-a-transition)

- Source change history (log.md) → The generated change log as Markdown. → [Read page](https://ratstack.sh/log.md)

- Structure an Effect codebase by domain → Start with folders for application work, services and Layers in the same file, and startup code that supplies implementations. → [Read page](https://ratstack.sh/lore/structure-effect-by-domain)

- Workshop setup help → An attendee's agent reports where Tokenmaxx setup is stuck, gets known fixes for that step, and later reads the desk's answer. → [Read page](https://ratstack.sh/systems/workshop-help)

## Unlinked mentions

- [A cartridge owns one job and its resources](https://ratstack.sh/lore/cartridges) → ts declares the Postgres schema, Hyperdrive connection, and migration registration.

- [add-a-capability](https://ratstack.sh/skills/add-a-capability) → Schema defines accepted values and their runtime checks.

- [add-a-feature-flag](https://ratstack.sh/skills/add-a-feature-flag) → A child-supplied readScope schema.

- [add-a-lifecycle-machine](https://ratstack.sh/skills/add-a-lifecycle-machine) → Schema defines accepted values and their runtime checks.¶

- [add-a-store](https://ratstack.sh/skills/add-a-store) → Schema defines accepted values and their runtime checks.¶

- [Agent rules for rat-stack (AGENTS.md)](https://ratstack.sh/AGENTS.md) → local directly, run pnpm env:check after schema edits

- [Analytics](https://ratstack.sh/systems/analytics) → Default: persistent in the site schema¶

- [AT Protocol separates identity, data, and application schemas](https://ratstack.sh/lore/at-protocol) → A procedure schema describes an operation.

- [Auth](https://ratstack.sh/systems/auth) → A session whose user id fails the person-id schema check also fails as Unauthenticated.¶

- [Build and run rat-stack (README.md)](https://ratstack.sh/README.md) → The host validates the input schema and runs the same handler used by every other surface.

- [CAFE names the Cloudflare, Alchemy, Foldkit and Effect stack](https://ratstack.sh/lore/cafe-stack) → The dials are an Effect Schema.¶

- [Capabilities](https://ratstack.sh/systems/capabilities) → Schema describes accepted values, their TypeScript types, and the rules for checking and converting them at runtime.¶

- [Capture first, shape later](https://ratstack.sh/lore/capture-first) → Events that do not match a structured stream’s schema “are accepted during ingestion but will be dropped during processing,” the docs say.

- [Code snippets quote a pinned source](https://ratstack.sh/lore/code-snippets) → Collect: Walk Markdown syntax-tree code nodes; scan metadata; Schema-decode requests and source locations.¶

- [Configuration is a supplied, validated dependency](https://ratstack.sh/lore/configuration-is-a-dependency) → Schema defines accepted values and checks data at runtime.¶

- [Database](https://ratstack.sh/systems/database) → Schema describes accepted values and their runtime checks.¶

- [Devtools](https://ratstack.sh/systems/devtools) → A schema defines the accepted values.¶

- [durability](https://ratstack.sh/skills/durability) → “many refactorings require you to run both the original and new versions of the schema in parallel during a transition period that is long enough to allow any applications accessing that portion of the schema time to be redeployed.”¶

- [Effect + Alchemy peer patterns](https://ratstack.sh/resources/same-version-repos) → One schema-derived contract carries payloads and typed failures across the wire.

- [Effect + Alchemy peers](https://ratstack.sh/resources/peers) → Why this tier: Statechart schema conversion on XState 6 is a relevant typed-machine seam; not yet studied.

- [Effect 4 study: September 2026](https://ratstack.sh/resources/effect-4-reference-projects) → Why it matters to us: Schema-first state machines native to Effect.

- [Effect keeps the surfaces on one contract](https://ratstack.sh/lore/how-we-do-it-with-effect) → An Effect Schema defines accepted values and provides types and runtime checks.

- [Effect Meetup SF 2023: Why Effect?](https://ratstack.sh/lore/effect-meetup-sf-2023-why-effect-michael-arnaldi) → A Remix demo contrasts manually added logs, metrics, and traces and nested error handling with Effect context, Schema, spans, metrics, and retry policies.

- [Feature flags](https://ratstack.sh/systems/flags) → A child schema defines it; the default is global.¶

- [HTTP success needs a status check and a decoder](https://ratstack.sh/lore/http-responses-need-validation) → Schema defines accepted values and checks data at runtime.

- [Interest signup](https://ratstack.sh/systems/interest) → Set INTEREST\_OPERATOR\_TOKEN through the local environment schema.

- [Learn mode presents concepts at useful depths](https://ratstack.sh/systems/learn) → Effect Schema describes accepted values and their runtime checks.

- [learn-rat-stack](https://ratstack.sh/skills/learn-rat-stack) → Schema defines accepted values and their runtime checks.¶

- [Lint and type escape ledger (debt.md)](https://ratstack.sh/debt.md) → Reason: Decrypted schema errors contain plaintext contact data and must never reach logs as a cause.

- [MCP is another surface](https://ratstack.sh/lore/mcp-is-another-surface) → Input JSON Schema.¶

- [One capability, every surface](https://ratstack.sh/lore/one-capability-every-surface) → No projection repeats the schema.

- [One schema, three surfaces](https://ratstack.sh/lore/one-schema-three-surfaces) → Effect Schema supplies types and runtime checks for these values.¶

- [OpenAPI describes the refusal too](https://ratstack.sh/lore/openapi-describes-the-refusal-too) → A declared failure defaults to 422 unless its schema names another HTTP status.

- [Production-grade TypeScript](https://ratstack.sh/lore/production-grade-typescript) → He demonstrates Effect context, Schema, spans, metrics, and retry policies in a Remix application.

- [Property-based testing](https://ratstack.sh/lore/property-based-testing) → The same schema defines the capability’s contract and generates its test inputs.

- [Rat King carries signed mail between named agents](https://ratstack.sh/lore/rat-king) → Schema definitions alone do not prove those phases deployed.¶

- [Schema projections: 2026-09-18 history](https://ratstack.sh/resources/schema-projections-and-code-mode) → One Effect Schema definition can feed a CLI, REST API, MCP server, and code mode.

- [security-audit](https://ratstack.sh/skills/security-audit) → Do not scale away the candidate gate, the source/local execution boundary, needs\_validation discipline, schema validation, or independent verification of confirmed records.¶

- [Structure an Effect codebase by domain](https://ratstack.sh/lore/structure-effect-by-domain) → Schema-backed boundaries: Capability contracts and derived interface projections¶

- [Tests prove behavior through supplied services](https://ratstack.sh/lore/tests-that-earn-their-place) → schema derives input generators from Schema.

- [Trace operations where they mean something](https://ratstack.sh/lore/trace-meaningful-operations) → The fixture’s transport decodes outbound JSON through a small Schema.

- [uncomplect](https://ratstack.sh/skills/uncomplect) → Schema: A definition of accepted values that provides TypeScript types and runtime checks.¶

- [write-a-wiki-page](https://ratstack.sh/skills/write-a-wiki-page) → A schema defines accepted values and their runtime checks.
