Skip to content

Concepts ​

Everything in Twinstate is generated from one registry, declared in a file that both the server and the client import. This page defines every term the rest of the docs use.

Kinds ​

A kind is one type of synced thing: a name, its fields — each a zod schema, or a zod schema with Twinstate's modifiers — and its options.

ts
kind('note', { title: z.string(), pinned: z.boolean().default(false) }, {
    id?: true | (() => parentKind),         // how records are addressed (below)
  defaulted?: true,                       // with id: () => parent — exists whenever its parent does
  // how it reaches a client — exactly one of these three (below):
  load?: 'instant' | 'lazy',              //   a root: delivered on its own
  belongsTo?: { kind: () => lazyRoot, by: 'transcriptId', order: 'at asc' }, // a child: with its root
  embedded?: true,                        //   embedded: delivered only inside the records that `ref` it
  validate?: (next, prev) => Rejection | undefined, // return invalid('…') to reject a change (below)
    ops: ('create' | 'update' | 'remove')[], // which operations records allow — required (below)
  memoryOnly?: true,                      // the whole kind is in memory only, never persisted
  query?: { order: ['at desc'], filter?: ['archived'] }, // read through windows (below)
  migrate?: { 2: (v1) => … },             // steps from older stored shapes (see Changing a schema) — built with the lock
  dropped?: ['oldField'],                 // fields removed on purpose — built with the lock
});

const twin = registry({
  name: 'notes',                            // required: names everything Twinstate keeps on the device
  kinds: [settings, note, noteBody, image],
  mutations: { pinNote: mutation(…), … },  // used as twin.mutations.pinNote
  events: { notice: event(NoticeSchema) }, // used as twin.events.notice
});

The registry's name is required, and must be unique among the Twinstate apps that share an origin — picking it is the app's job. Everything Twinstate keeps on the device is per origin (localStorage, IndexedDB, Web Locks, BroadcastChannel), so every name it uses there starts with twinstate:<name>: — the outboxes and their locks, the revision locks, the tabs' channel, the perDevice event ids, the cache's database (its clearCache generation included). Two apps on one origin (say /notes and /tasks) then never adopt each other's outboxes, stop each other's tabs or read each other's cache. The twinstate: prefix is reserved: an app's own keys must not start with it.

Every option is typed from the fields, and an option the kind does not have (a misspelled validator, a query.filters) does not compile. belongsTo.by accepts only a field of the schema typed as an id (idOf(transcript)), and registry(), which sees every kind, checks it is the parent's; belongsTo.order, a query's order and its filter accept only field names, as '<field> asc' | '<field> desc' for orders — so a typo or a renamed field does not compile.

The name makes the kind nominal. Two kinds with identical schemas are still different kinds: Id<'note'> and Id<'draft'> never mix. The registry takes the kinds as a list (written in the call, or kept as const: an array type could hide a duplicate) and keys everything by name (s.note, twin.kinds.note); a duplicate name does not compile. Mutations and events live under their own keys (twin.mutations, twin.events), so no name of yours collides with the registry's.

Values are plain JSON. Records travel as JSON and are kept as JSON in the outbox and the cache, so a kind's fields, and a mutation's arguments, must have both an input type and an output type that are JSON (strings, numbers, booleans, null, arrays and plain objects). z.date(), a Map, a bigint, or a .transform to any of them do not compile. Dates are ISO strings. A stored value is parsed again on every load, so what a field gives must be valid as what it takes: a .transform to another type (z.string().transform(Number)) does not compile, since its stored number would fail the next load — store the value as it is and convert it where it is used. A trimming transform (string to string) is fine. (Past a few levels of nesting, or through recursion such as z.json(), the compiler stops looking; the test kit's checkRegistry() checks every kind's values at any depth.)

"Nothing" is null. A stored value never holds undefined: a kind's field is never .optional() (nor .nullish()), at any depth — it is .nullable(), usually .nullable().default(null), so a create may leave it out. JSON cannot carry undefined, so { a: undefined } and {} would compare unequal on one side and arrive the same on the other, and a patch could never clear such a field. .default() is fine: a defaulted field is optional to give, never undefined once stored. A sparse map is z.record(z.string(), …): z.partialRecord reads to the compiler as optional fields, so it does not compile. (A mutation's arguments and an event's payload may be .optional(): they are not records — nothing compares, patches or replays them — and an absent argument is simply not given.)

No field has a .catch. zod's .catch(fallback) turns a value that fails to parse into the fallback, silently, and a client's patch is checked by the same schema, so a bad value sent by a client would be stored as the fallback instead of being refused. A .catch anywhere in a field does not compile (past a few levels, or inside an object's .catchall(), whose schema zod's types do not keep, checkRegistry() finds it). Let a bad value fail; older stored shapes are what migrate is for.

Every record carries its id. A record read anywhere — a selector, a handle, tx.get — has id: Id<'note'> next to its fields, so a kind may not declare a field named id.

Addressing: id ​

idrecordsexample
omitteda single value, which always existssettings
truemany, each with its own opaque string idnote['n1'], image['img-7']
() => parentKindone per parent, keyed by the parent's idnoteBody[noteId]

A single value always exists, starting from its schema's defaults, so its schema must parse from nothing ({}) — every field has a default — or it does not compile.

The third form is for the common "one of these per note" shape — a note's body, a note's draft. Its id is the parent's id, so noteBody(id) accepts an Id<'note'> directly, it needs no field of its own to say whose it is, and it is removed with its parent. It is still a root in its own right (a note's body is lazy while the note is instant). With defaulted: true it exists whenever its parent does, starting from its schema's defaults (so the schema must parse from {}, as a single value's does): a missing record reads as the default, is never absent, and is written the first time it changes — a draft for every conversation, without writing one per conversation.

A kind never has two-part keys: something that is "many per parent" is either a field inside the parent (small, changes with it) or its own kind with id: true and belongsTo (changes independently).

Changes are tracked, field by field. On the server a record changes only through tx.update(kind, id, draft => …), which records exactly which fields changed (see the server); only those fields travel to clients. Two writers never merge inside one change: the server's queue applies one change at a time, and the latest one applied wins.

Field modifiers ​

Three modifiers change how one field is handled, without changing its type. Each starts from the field's zod schema, and the others chain after it, each offered once and only where it applies:

ts
kind(
  'reply',
  {
    status: z.enum(['streaming', 'done']).default('streaming'),
    token: serverOnly(z.string().min(1)), // zod's methods go inside
    busy: memoryOnly(z.boolean().default(false)),
    text: memoryOnly(z.string().default('')).appendable(), // modifiers chain, in any order
  },
  { id: true, load: 'lazy', ops: ['create', 'update'] },
);
  • serverOnly(schema) — stored and tracked like any field, never sent to a client: not in snapshots, not in patches, not in the client's types. For server-internal state that belongs with a record (a session token, a recovery breadcrumb, a counter).
  • memoryOnly(schema) — not durable: synced like any field, kept in the server's memory, and reset to its default when the server restarts, so the schema must have one (memoryOnly(z.boolean().default(false))); without one, it does not compile, and .memoryOnly() is not offered. For state that is only true while the process runs ("a turn is active", "a prompt is waiting", text still streaming). This is about the value's lifetime, not about storage — how your store keeps everything else is still yours — but Twinstate must know which values it never hands to the store: it does not call the adapter on every change (a streaming reply is not a write per token), never evicts a record whose memory-only values it could not reload, and needs no adapter for a kind that is memoryOnly: true (every field so).
  • appendable(schema) — text that grows is sent as its new suffix (below). For open-ended text: an enum or a literal cannot grow, so it does not compile.

Modifiers go on a kind's own fields. A modified field is Twinstate's, not a zod schema, so it cannot sit inside a z.object or a z.array — a field's nested value is one opaque piece of data, and putting a modifier there is a compile error naming the fix. A nested value that needs its own handling is an embedded kind, ref'd from the record: its fields take modifiers like any kind's, and it is delivered inside the record that refers to it (see ref or a field). For a single small value (a secret inside some metadata), a field of the record is simpler.

Every field's handling is a recorded decision. Forgetting serverOnly would send a field to every client, so the lock (see changing a schema) records each field's effective settings — who sees it, how long it lives, how its changes travel, its default — and twinstate lock does not record a new or changed field until it is confirmed.

Validation ​

Every change is checked against the kind's schema, and then against its validate hook if it has one — the place for rules that span fields:

ts
validate: (next) => {
  if (next.mode === 'coding' && !next.project) return invalid('coding needs a project');
},

validate returns its verdict rather than throwing, and its return type is Rejection | undefined, so an async validate — which would never be waited for — does not compile. A rejection throws inside the change, the draft is discarded, nothing is persisted or sent, and the mutation that caused it is rejected with the reason; the whole turn is rejected even if the handler catches the error.

How a kind reaches a client ​

Every kind declares exactly one of three, and a kind that declares none, or more than one, does not compile:

declaredthe kind ison a clientread with
load: 'instant'a rootalways, from startupuseShared(select)
load: 'lazy'a rootwhile an entry that loads it is mounteduseShared(handle), the handle from its entry
belongsTo: { … }a childwith its root, and removed with itas an ordered array on the root
embedded: trueembeddedinside every record that refs itthrough that record's resolved ref
  • instant roots all travel in the startup snapshot, so they must stay small; the test suite enforces a size budget. Settings, list rows, small facts.
  • lazy roots are loaded by an entry — by id, or with no id for a single lazy value such as "recent activity" — and each gets its own subscription (a topic on the wire — "topic" never appears in app code). The heavy detail of one thing: a note's body, a thread's transcript. A lazy root with id: true can also be read through a query, a window instead of one record.
  • Children (belongsTo) belong to one lazy root, by the field by, and are delivered with it — and when it is removed, they disappear from every client with it: a thread's messages arrive with the thread, without the thread having to hold an ever-growing list of their ids. Reading the root returns its children as an array in order (useShared(transcript).messages). A child kind that declares query is not delivered whole: it is read through windows over one parent's children (a long transcript, paged).
  • Embedded records have no subscription and no parent of their own: an image, an upload. They travel with whatever refs them, and more than one record may ref the same one. How long one lives is yours to decide: one that nothing refs any more is simply not delivered anywhere, and is removed when your code removes it (see what your store and handlers own).

instant is simply what the app itself loads and never releases; lazy is what a screen loads while it needs it. Keep instant to small facts every screen on every device needs, and let everything else load when it is needed — the snapshot budget enforces the first half.

A kind has one way to reach a client. When something feels like it should be instant in one place and lazy in another, it is almost always two kinds: the part everyone needs and the part one screen needs, sharing an id — a conversation's summary and its transcript, a document's title and its body. A kind that switched strategy per client would break the rule that a read's type says whether it can be missing. When a collection outgrows "every record on every device", it is a query; when different screens or devices want different amounts, that is what their entries load (see React).

Who may write a kind ​

Clients write only through the mutations the registry declares — there is no other channel. A kind is client-editable field by field exactly where the registry declares a patch for it, and the patch names those fields:

ts
updateNoteBody: patch(noteBody, { fields: ['text', 'related'] }), // clients may set these; every other field is server-written

The list is required, and everything not in it is server-written, so a field added to the kind later is not client-writable until someone adds it here — the safe default. Everything else changes only through named mutations whose handlers decide what changes (pinNote, renameNote), and the server rejects anything that bypasses the types.

A value whose writes must merge rather than overwrite gets a named mutation whose handler does the merge, never a patch: a patch would let a stale replay overwrite a newer value. The merge must be idempotent, because a mutation can be resent: "keep the later value" (markRead({ id, at })) is; "add one" is not — record each contribution under tx.idFor(…) and count them instead. checkResend fails a mutation that is not.

ops ​

ops lists the operations this kind has: what its store adapter must implement (a memoryOnly kind has none), and what any code — handlers, server mutations, background jobs — may do to its records. Some records are written once and never edited — a sent message, a published revision:

ts
kind('message', { … }, { …, ops: ['create'] });             // created, never edited
kind('job',     { … }, { …, ops: ['create', 'update'] });   // never deleted on its own
kind('settings', { … }, { …, ops: ['update'] });            // a single value: always exists

ops is not a client permission — mutations are that: a client can only ask for what a mutation declares. ops says what can ever happen to a record, by anyone: no handler or background job can remove a kind without remove in its ops, because tx.remove(kind, …) does not compile for it. A sent message stays unedited because nothing in the codebase can edit it, not because no mutation happens to.

ops is required, so that what a kind allows is always a decision someone made and a reviewer can see — never a default nobody noticed. A single value (id omitted) always exists, so it can be neither created nor removed: its ops must be ['update'], and anything else does not compile; so must a defaulted kind's, which always exists with its parent. The declaration drives the types: tx.update(message, …) does not compile, a kind without update has no patch, an effect's draft of it has only the operations listed, and the kind's store adapter has only the methods listed. When a parent is removed, its children and the records keyed by its id — and theirs, all the way down — disappear from every client with it, whatever their ops; removing them from storage is the parent's store adapter's job (a folder deleted, a database cascade). ops is about which operations exist, and is unrelated to appendable, which is about how a field's changes travel.

A field can point at another kind in two ways, and the difference is delivery.

ts
images: ref('image').array(),     // "part of me": stored as ids, read back as image records
related: link('note').nullable(), // "another thing you can open": an Id<'note'>, or null
  • ref — part of me. The target is an embedded kind — a ref to anything else does not compile — and its records are delivered in the same stream, in the same flush, as the record that refers to them. When you read a record, its ref fields come back resolved: body.images is an array of image records, not ids. A handler's tx.get sees what is stored instead: ref and link fields as ids. Following a ref never loads anything, so it can never cause a loading waterfall, and an embedded record is held once however many records ref it.
  • link — another root. The field holds a branded id of a root with its own ids. If the target kind is instant, it resolves to the target's record (its title, its state) from the always-present replica, typed T | null — null when there is no such record to show; for a lazy target its type is just the id. It never resolves into lazy data; you open the target by navigating to its entry, and a target that is gone shows that entry's absent element. A link is only a reference: what happens to it when its target is deleted — clearing it, deleting what holds it — is your store's and your handlers' decision (see what your store and handlers own).

A ref or a link is one of the target's ids, .array() of them (in order), or .nullable(). It goes on a kind's own fields, never inside a z.object, and it is never an order or a child's by; a link may be a window's filter.

A relation names its target ('image'), rather than importing it, so kinds may point at each other in any order: a folder links to its parent folder, a page to its shelf and the shelf back to its top page. (A reference to the kind itself, link(() => folder) inside folder's own declaration, is a cycle TypeScript cannot type.) The name is still checked by the compiler, in registry(), which sees every kind at once: a name that is no kind of the registry, a ref to a root, or a link to anything but a root with its own ids does not compile, and the error names the kind and the field (noteBody.images: no kind is named 'imag' in this registry). Renaming a kind (its name, not its variable) is then a compile error at registry(), naming every relation that still uses the old name. A parent (id: () => note, belongsTo.kind) and idOf(note) take the kind itself: its sort (a root, lazy, with its own ids) is checked at the kind, and registry() checks the parent is in the registry and that a child's by holds its id. Taking the kind cannot form a cycle as long as a kind never names its own children or itself that way (to point back at a root, use a link).

Branded ids ​

ts
type Id<Name extends string> = string & { readonly __kind: Name };

A raw string cannot be used to load or write anything; an Id<'note'> comes from:

  • a record: the id of anything read, or a link field;
  • newId(note), on the client, for a record it is about to create (createNote({ id: newId(note), title })): a random UUID, which fits the id grammar. Like parseId, it is exported from twinstate/client only — a handler takes its ids from its arguments or tx.idFor;
  • parseId(note, routeParam), for an address a user navigated to — it returns Id<'note'> | null, so a malformed address is handled, not thrown. It is exported from twinstate/client only, so server code cannot turn a string into an id;
  • idOf(note), the zod schema for an id in mutation arguments — a client-chosen create id, typed Id<'note'> on what it takes as well as what it gives, so a client passing a raw string does not compile either, and validated at the boundary against the id grammar — one or more segments of lowercase letters, digits, - and _, joined by ., at most 200 characters, and no segment a name Windows reserves (con, nul, com1…) — so an id is always safe as a file name: it never contains .. or /, and two ids never differ only by case, which would collide as one file on macOS or Windows;
  • on the server, in a mutation's turn, tx.idFor(kind, 'label'), derived from the mutation's own identity (its client and mutation id, or, for a server mutation, its name and the key it was sent with) — the same on every resend, different for every mutation, and fresh each time for a server mutation sent without a key;
  • tx.childId(kind, parentId, localPart), for an id that encodes its parent — <parentId>.<localPart> — so a store can find a child from its id alone (a transcript's message m3 in file <conversation>/transcript.jsonl). Twinstate treats it as one opaque id and never parses it; the adapter may split it at the last ..

Casting a string to an Id (as Id<…>) is a lint error (typescript-eslint's no-unsafe-type-assertion, or twinstate/no-brand-cast where an app cannot yet turn that on everywhere); tests use testId(note, 'n1').

The graph rules ​

Most rules about how kinds relate are enforced by the types — those that need every kind at once by registry()'s, with one message per mistake; the rest by checkRegistry() (see testing):

ruleenforced by
every kind reaches clients exactly one way: a root, a child or embeddedthe compiler
kind names are unique, and none is twinstate, default or instant (reserved)the compiler (registry())
ref targets only embedded kinds — a root is pointed at with a linkthe compiler (registry())
link targets only roots with their own idsthe compiler (registry())
every relation's target, and every parent, is in the registrythe compiler (registry())
a child's parent is a lazy root, and by holds its idthe compiler (by holding that parent's id: registry())
every embedded kind is the target of some ref — or it could never be deliveredthe compiler (registry())
a patch names its fields, and never an appendable, serverOnly or ref onethe compiler
no ref cyclescheckRegistry

A ref, or a field in the parent? ​

Decide this when you declare the kind: moving a field into a kind of its own later is a migration across kinds (see splitting a kind). Size alone is not a reason to split a record: tracked updates send only the fields that changed, however big the parent is. Make something its own kind when any of these holds:

reasonexamplekind
more than one record refers to itan upload referenced by a draft, then by the message it was sent withembedded (ref)
it has different writersserver-computed upload metadata inside a draft the user patchesembedded (ref)
something must name it by itself"retry this upload", "open this step in a side panel", moving it between parentsembedded or a child
it grows without bounda thread's messages — many records, so they can be pageda child
it needs its own handlinga step whose text streams (appendable), or holds a secret (serverOnly)embedded (ref)

Otherwise nest it: if it only makes sense inside its parent, has the same writers, nothing else refers to it, and it stays small, a field is simpler. The test: would any code ever need to name this thing by itself?

What your store and handlers own ​

Twinstate keeps every client's copy of the server's state correct and live, and never loses a client's change on the way. It is not your database: some questions every data model has to answer are yours, and it helps to answer them while you declare your kinds rather than after the first bug.

questionwhat Twinstate doeswhat you decide
what goes when a record goesremoves it from every client, with its children and the records keyed by its id, all the way downhow your store removes them — a folder deleted, a database ON DELETE CASCADE — and whatever else should go with it, in the handler that deletes
links to something deletednothing: a link is a reference. An instant target that is gone resolves to null; a lazy one shows its entry's absent elementwhether to clear or delete what links to it — your database's foreign keys, or your delete handler
embedded records nobody refers tostops delivering themwhen to remove them: in the handler that drops the last ref, or with a sweep
a turn that writes several recordshands them to your store together, inside your transaction if you give onewhether they must land all or nothing (see transactions)
data that cannot be readdoes not serve it, reports it (onUnreadable), and never overwrites itwhat to do with it — keep it, repair it, remove it
backupskeeps its own records (which mutations it applied) in your store, beside your datathat a backup and a restore take both together

A delete handler is where most of these meet:

ts
deleteNote: async ({ id }, tx) => {
  const body = await tx.get(noteBody, id);
  for (const imageId of body?.images ?? []) await tx.remove(image, imageId); // your decision: in this app images are never shared
  await tx.remove(note, id); // every client drops the note and its body
},

Queries ​

Pagination is part of the core: instant means "every record on every device", which stops scaling as a collection grows, and a collection that must be paged is read through a query — a live, ordered window over a kind.

ts
const activity = kind(
  'activity',
  { text: z.string(), at: z.string(), archived: z.boolean() },
  {
    id: true,
    load: 'lazy',
    ops: ['create', 'update'],
    query: { order: ['at desc'], filter: ['archived'] },
  },
);
activity.query({ order: 'at desc', filter: { archived: false } }, { first: 50 });
message.query({ parent: transcriptId, order: 'at desc' }, { first: 100 }); // a child kind: one parent's children
// load more: page.loadMore() widens the same window, after page.endCursor
  • A kind declares that it is queried, and the orders and filters it allows — a lazy root with id: true, or a child (a window over one parent's children). That is what makes its adapter require window({ order, filter, first, after }), lets .query(...) accept only a declared order, and tells a store which indexes it needs. A filter may also name a memoryOnly field, matched against a value other than its default ({ active: true }): the store never sees such fields, so Twinstate answers that window from memory — which is complete, because a record whose memory-only fields differ from their defaults is never evicted.
  • A query is identified by its kind, order and filter (and its parent, for a child); the window size is a property of the subscription, not of its identity. So a component reads the window through the handle its entry received (useShared(page)), and "load more" widens that same subscription rather than opening another.
  • Cursors, not page numbers. A live list reorders all the time (a note moves to the top when edited), so "page 2" shifts under you. A cursor is the position of the last item you hold — its sort key and id — and stays correct while things move.
  • The server keeps the window live: an item that starts matching enters, the item pushed past the end leaves, reordering is sent as moves.
  • The client holds only the window. So anything global — a count, a badge, "which are unread" — is a small server-computed record, not a selector over a list the client does not fully have. A link to a record outside the window resolves through a single-record load.
  • The result type says it is a window ("these 50, and more exist"), so no code can mistake it for the whole collection.

Extension points (designed, not built) ​

Because every change passes through one place that sees the value before, after, and the exact patches, these hooks can be added to a kind later without changing the model: derive (recompute dependent fields when their inputs change), onChange (side effects keyed to the fields that moved), history and undo (the patches, and Immer's inverse patches), field-level permissions (designed: see sessions and access), and more field encodings: ways a field's changes travel and combine other than a whole new value, for structures such as co-edited text, which a CRDT encoding (a Yjs value the server merges in any order) would carry. Encodings are the framework's, not the app's (see design notes): appendable is the one built in, and an app's own combining logic is a named mutation. And field selection — a subscription asking for only some fields of a kind — can be added the same way (patches already carry their paths, so the server can filter them per subscription); until it is needed, splitting a kind into a summary and a detail is the same thing, decided in the schema, and fully typed.

appendable text ​

ts
text: appendable(z.string()),

A field that usually grows — a streaming reply, a job's log — would be expensive to resend whole on every change (a 20,000-character reply streamed over two minutes is ~12MB resent whole, ~20KB appended). Declaring it appendable changes nothing in your code: you still assign the new value in an update. When the new value extends the old one, the patch is sent as just the suffix, with the length it expects to extend ({ append, at }). Anything else — an edit, a shorter value — goes out as a normal whole-value change.

Clients never send appends. An appendable field is usually memoryOnly state (see the server).

Mutations ​

A mutation is a named, schema-validated request to change state. Every write is one — a client's, or the server's own — and there is no other way to change anything.

ts
mutation(z.strictObject({ … }), {     // the arguments: strict objects at every level, plain JSON
  effect?: (draft, args) => undefined, // what to show before the server answers
  rejects?: ['busy', 'stale'],         // the reasons its handler may reject with, besides the built-in
                                       //   `invalid`, `unavailable`, `error`, `outdated` and `incompatible`
                                       //   (declaring one does not compile)
  from?: 'server',                     // sent only by server code (`server.mutate`): clients cannot send it,
                                       //   it has no effect, and no policy checks it
});

patch(kind, { fields: ['text'] })     // lets clients set these fields: effect included, applied on the
                                      //   server without a handler — `{ extend: (args, tx) => … }` adds
                                      //   work in the same turn, after the patch is applied

There are two kinds, and the difference is who decides what changes:

a named mutation (mutation)a patch
the client says"do this" — pinNote({ id, pinned })"set these fields" — save({ id, patch: { text } })
what it can doanything its handler does: create, update, remove, several recordsupdate existing records only — never create or remove one; it exists only if the kind's ops include update
argumentsyour schemagenerated: an id (none for a single value) and any of the fields it names — strict, so any other field is refused, and a default never fills a field it was not given
on the serveryour handler decides what changesapplied for you (an extend hook may add work)
effectwritten by you, or none (a "sending" state)generated
use it forlogic: validation, several records, merges, server-computed valuesa field the user edits directly — settings, a draft's text

A patch checks each field it is given with that field's own schema, and only those: a field left out keeps its value, never its default. A patch clears a field by sending null, the only "nothing" a record has; undefined is refused.

patch carries fields because they are its allow-list: without one, a patch would cover every field of the kind — including one added later, such as a server-computed wordCount, which any client could then overwrite.

ops and a mutation's fields answer different questions, which is why they live in different places. A kind's ops says what can ever happen to its records, by any code, and shapes its store adapter, if it has one. A mutation says what clients may change through it: a patch's fields, or a named mutation's argument schema — createNote takes only an id and a title, and its handler sets everything else. One kind can have several mutations exposing different fields, so the fields belong to the mutation, not to the kind. (Rails splits it the same way: model rules for every write, strong parameters per action.)

In the outbox rules a patch mutation is simply a patch (typing into a field sends patches, and patches to the same fields coalesce); set is only the wire op that carries a whole record.

  • effect is about the screen. While the mutation waits in the outbox, the client displays the replica with every pending effect applied. An effect receives a draft — a copy-on-write view of the replica (Immer style), covering every kind, lazy ones included — with the same operations a handler's tx has, synchronous and typed by ops: create (if absent), update(kind, id, recipe) (update(kind, recipe) for a single value), remove. It sees the fields clients see: a serverOnly field is neither readable nor writable there, and a recipe returns nothing (Immer would take a returned value for the new record). The real replica is never touched. It is re-run every time the replica changes, so it must be pure: its return type is undefined (an async effect does not compile), and the twinstate/pure-effect lint rule rejects anything it reads from outside its arguments — a free variable that is not an import, Date, Math.random, crypto, window, document, storage, fetch. It is generated for patch; a named mutation without one shows nothing until confirmed (a "sending" state).

    ts
    effect: (draft, a) => { draft.create(note, a.id, { title: a.title, updatedAt: '', pinned: false }) },

    The effect and the handler are two functions — the server loads records, reads the clock and may reject — in one vocabulary. checkEffects checks that they agree: what the effect showed just before the reply equals the replica just after it, on every record either touched, except the fields a fixture lists as server-computed (updatedAt above).

  • Creates are safe to resend by construction. The outbox resends anything unconfirmed — after a reconnect, after the app was killed. So a mutation that creates takes the new record's id in its arguments (id: idOf(note)), chosen by the client, and the server's create is create-if-absent. The server also remembers, durably, which mutations it has applied (see the server), so a resend is recognised even after a restart; create-if-absent is what still holds if that memory is lost.

  • Arguments are strict at every level. A mutation's arguments are z.strictObjects throughout, so a field the client sends that the schema does not know is refused rather than dropped: an old outbox entry whose field was renamed fails loudly instead of losing what was typed. zod's types cannot tell a strict object from one that strips, so the test kit's checkRegistry() reports any z.object or z.looseObject in a mutation's arguments, at any depth (an explicit .catchall(…) is a declared choice, and passes).

  • Rejections are typed. A handler rejects only with a reason its mutation declares, and the client's error is that union plus invalid, unavailable and error (an unexpected throw, with no detail) — and, refused locally by a tab that has stopped, outdated or incompatible, so handling it can be exhaustive.

Events: not state ​

Most things are state: they have a current value, a late-joining device needs it, and a reconnect must catch up on it. A few things are events: "a job just finished — tell the user", a toast, a sound. An event has no current value: it matters when it happens, and less with every minute after.

ts
registry({ …, events: { notice: event(NoticeSchema) } });                // maxAge (ms): 2 minutes by default
registry({ …, events: { ping: event(PingSchema, { maxAge: 0 }) } });     // never replayed
tx.emit(twin.events.notice, payload);                               // on the `instant` topic: every client
tx.emit(twin.events.notice, payload, { on: [conversation, id] });   // on one lazy root's topic: its watchers
useEvent(twin.events.notice, (n) => show(n));                        // on the client, in every open tab
useEvent(twin.events.notice, (n) => toast(n), { perDevice: true });  // once per device

An event travels inside a topic, like a change: it is part of that topic's flush message, after its ops, so the topic's own data is always there first — emit it on the topic that holds the data it is about (delivery is not ordered across topics, so an event on one topic may arrive before another topic's change). By default it goes on the instant topic, which every client holds; on puts it on one lazy root's topic instead, so only the clients watching that root receive it. Because it is part of the topic's stream, it is also part of the topic's ring: a client that reconnects and resumes a topic it was holding receives the events it missed with the changes it missed, in order, once — those younger than the event's maxAge (two minutes unless the event says otherwise, the window after which comparable realtime services stop replaying too). A topic that is reset instead — a gap longer than its ring, or a server restart — drops them: a toast an hour late would be wrong. So does a first subscribe: a page that starts from its cache, or opens a lazy root again, resumes the topic's data but replays none of its events — they happened before it was watching. So twenty seconds offline still shows "your reply is ready"; a night offline does not.

Each tab is its own client, so a plain useEvent runs in every open tab; with perDevice: true, each tab that receives an event takes a Web Lock named for it and, holding it, checks and records the event's id in a small list shared by the device's tabs (localStorage); only the first to record it runs the handler, so a toast appears once per device, however late the other tabs receive it — replayed or not. Every event carries an id (its epoch and a server-wide counter). Server code can consume events too — server.onEvent(twin.events.notice, …) is how a push notification sender hears about them. An event is never part of a snapshot.

What a user must not miss is state, not an event. "Unread", "your reply is ready", a badge count: keep it in a record (an unseen flag, an inbox), and let the event only say now. A device that was away for a day then still sees it, from the state, and a push notification (a separate channel) covers a device that is offline.

Not in the core: device state ​

State that belongs to one device only — a theme, a dismissed hint, a scroll position — has nothing to do with syncing, so it is not part of the registry or the core. The optional twinstate/device utility gives it a typed, tab-following home if you want one:

tierexamplesAPI
UIhover, a menu being open, a gestureplain useState
devicetheme, dismissed hintsuseDevice / setDevice (the utility)
sharedeverything that should follow youuseShared / mutations (the core)