# syncbase API reference

> This document is written to be read by people and by coding agents. The same content is served as plain Markdown at [`/docs.md`](/docs.md); an index for LLM tooling lives at [`/llms.txt`](/llms.txt). Every code block is complete enough to copy.

syncbase is a local-first sync engine. Your app reads and writes a local replica of the data it is allowed to see; a sequencer at the edge orders every write; fan-out servers push the result to every connected client — browser tabs, phones and agents — in milliseconds.

**Status:** `0.1.0`, pre-release. APIs below match the source in `packages/*` at this version. Breaking changes are possible before `1.0`.

## Packages

| Package | Purpose |
| --- | --- |
| `@syncbase/client` | Models, decorators, `SyncedStore`, queries, commands, CRDT codecs, transports, persistence |
| `@syncbase/react` | `SyncbaseProvider`, `observer`, `useModel`, `useCollection`, `useQuery`, `useCrdt`, `useAwareness`, DevTools |
| `@syncbase/reactive` | The reactive core: `Signal`, `Computed`, `Reaction`, `batch`, `untrack` (no external signal library) |
| `@syncbase/cf` | Cloudflare server: `createSyncbaseWorker`, `WorkspaceSequencer`, `WorkspaceFanout`, compaction, JWT auth, write policies |
| `@syncbase/wasm` | Precompiled Rust engine (`syncbase-core`) for browsers and Workers |
| `@syncbase/schema` | Language-neutral schema DSL, `schema.ir.json`, breaking-change diffing, codegen |
| `@syncbase/node` | Standalone server on Bun/Node with disk SQLite and S3/R2 object storage |
| `@syncbase/react-native` | React Native bridge (MMKV/AsyncStorage persistence, AppState/NetInfo) |
| `@syncbase/vite` | Vite plugin: Stage 3 decorators in Rollup/esbuild builds, ES-module workers |
| `@syncbase/cli` | `syncbase codegen`, `diff`, `migrate`, `inspect`, `token` |
| Swift / Kotlin | UniFFI bindings to the same Rust core (`packages/swift`, `packages/kotlin`) |

## Mental model

Five facts explain the whole system.

1. **Every client holds a replica.** The Rust engine runs in a dedicated Worker (WASM) and persists immutable segments plus a WAL to OPFS. Reads are synchronous memory reads.
2. **Every write is optimistic.** A mutation is applied to a local *overlay* on top of confirmed state, rendered immediately and queued for the server.
3. **One sequencer orders everything.** Each workspace has one Sequencer Durable Object. It validates writes, runs commands authoritatively, assigns a monotonically increasing `seq` and appends to its WAL.
4. **Fan-out pushes, filtered.** Fan-out Durable Objects hold hibernated WebSockets and forward each committed batch only to clients whose *sync groups* and *subscriptions* match.
5. **Clients rebase.** When a server batch arrives the client drops its overlay, applies the batch in `seq` order, removes confirmed mutations and replays the rest. Intent is preserved because commands are replayed, not their results.

```
client  write ──▶ overlay ──▶ render (0 ms)
          │
          └──▶ fan-out DO ──▶ sequencer DO  (validate · command · seq · WAL)
                                   │
          ◀── delta (seq n) ◀──────┘    flush ──▶ R2 segments ──▶ compactor
client  drop overlay · apply seq n · replay pending
```

## Quickstart

### 1. Install

```bash
bun add @syncbase/client @syncbase/react @syncbase/wasm
bun add -d @syncbase/vite @syncbase/cli
```

Models use TypeScript Stage 3 decorators (TypeScript ≥ 5.0, no `experimentalDecorators`). With Vite, add the plugin:

```ts
// vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import syncbase from "@syncbase/vite";

export default defineConfig({ plugins: [react(), syncbase()] });
```

### 2. Define models

```ts
// models.ts
import { Model, model, field, belongsTo, hasMany, type ReactiveCollection } from "@syncbase/client";

@model({ name: "Team", loadStrategy: "instant" })
export class Team extends Model {
  @field() accessor name = "";
  @hasMany(() => Issue, { foreignKey: "teamId" }) accessor issues!: ReactiveCollection<Issue>;
}

@model({
  name: "Issue",
  loadStrategy: "partial",
  syncGroups: (i: Issue) => [`team:${i.teamId}`],
})
export class Issue extends Model {
  @field({ indexed: true }) accessor teamId = "";
  @field({ fullText: true }) accessor title = "";
  @field({ enumValues: ["todo", "doing", "done"] }) accessor status = "todo";
  @field({ type: "number", default: () => 0 }) accessor priority = 0;
  @belongsTo(() => Team) accessor team: Team | undefined;
}

export const MODELS = [Team, Issue];
```

### 3. Create a store and connect

```ts
// store.ts
import { SyncedStore, WebSocketSyncTransport } from "@syncbase/client";
import { MODELS } from "./models";

export const store = new SyncedStore({
  models: MODELS,
  userId: "alice",
  syncGroups: ["team:eng"],
  persistence: "my-app",                 // OPFS, with IndexedDB fallback
  transport: new WebSocketSyncTransport({
    baseUrl: "https://sync.example.com",
    token: await getToken(),             // HS256 JWT, see Authorization
  }),
});

await store.restoreFromPersistence();    // instant warm start from disk
await store.connect();                   // bootstrap / catch up, then live
```

### 4. Render

```tsx
import { Suspense } from "react";
import { SyncbaseProvider, observer, useCollection } from "@syncbase/react";

const IssueList = observer(({ team }: { team: Team }) => {
  const issues = useCollection(team.issues); // suspends until the slice is hydrated
  return (
    <ul>
      {issues.map((issue) => (
        <li key={issue.id} onClick={() => { issue.status = "done"; issue.save(); }}>
          {issue.title} — {issue.status}
        </li>
      ))}
    </ul>
  );
});

export const App = () => (
  <SyncbaseProvider store={store}>
    <Suspense fallback={null}><Root /></Suspense>
  </SyncbaseProvider>
);
```

`issue.save()` re-renders every observer immediately, sends a field-level patch, and every other client viewing that issue updates within one round trip to the edge.

## Models

A model is a class that extends `Model` and is registered with `@model`. Schema is extracted at runtime from the decorators — no codegen is required for TypeScript apps.

### `@model(options)`

| Option | Type | Default | Meaning |
| --- | --- | --- | --- |
| `name` | `string` | class name | Stable model name on the wire and in storage. Set it explicitly; minifiers rename classes. |
| `loadStrategy` | `"instant" \| "partial" \| "lazy" \| "placeholder" \| "explicit" \| "local"` | `"partial"` | When rows are loaded. See below. |
| `indexes` | `{ name: string; fields: string[] }[]` | `[]` | Extra composite indexes. |
| `syncGroups` | `(row) => string[]` | — | Computes the sync groups a row belongs to. Authorization and routing derive from this. |
| `syncGroupTemplates` | `string[]` | `[]` | Declarative form, e.g. `["team:{teamId}"]`. Used by schema extraction and diffing. |
| `allowedSyncGroupPrefixes` | `string[]` | `[]` | Restrict which group prefixes a row may carry. |

**Load strategies**

- `instant` — loaded with the bootstrap. Use for small, always-needed tables (teams, users, labels).
- `partial` — loaded per indexed slice on first read, e.g. `team.issues` or `store.where(Issue, "teamId", id)`. Reading an unhydrated slice suspends.
- `lazy` — loaded by primary key on first access (`store.getSuspense`).
- `placeholder`, `explicit` — loaded only when your code asks.
- `local` — never synced; lives only in this client.

### `@field(options)`

Works on `accessor` fields (recommended) and on plain class fields.

```ts
@field() accessor title = "";
@field({ type: "number", default: () => Date.now() }) accessor createdAt = Date.now();
@field<string[]>({ type: "json", default: () => [] }) accessor labels: string[] = [];
```

| Option | Type | Default | Meaning |
| --- | --- | --- | --- |
| `type` | `"string" \| "number" \| "boolean" \| "bytes" \| "json"` | `"string"` | Stored value type. |
| `indexed` | `boolean` | `false` | Build a posting-list index. Required for `where()` slices and `hasMany` foreign keys. |
| `fullText` | `boolean` | `false` | Tokenize into full-text postings (`__ft:<field>`). Enables `query().search()`. |
| `lazy` | `boolean` | `false` | Value is fetched on first read instead of with the row. |
| `optional` | `boolean` | `false` | Field may be absent. |
| `enumValues` | `readonly string[]` | — | Allowed values. |
| `default` | `() => T` | — | Default for new rows. |

Every field is merged **per field, last-writer-wins** by `seq`. Two clients editing different fields of the same row never conflict.

### Relations

```ts
@belongsTo(() => Team, { foreignKey: "teamId" }) accessor team: Team | undefined;
@hasMany(() => Issue, { foreignKey: "teamId" }) accessor issues!: ReactiveCollection<Issue>;
```

- `belongsTo(target, { foreignKey?, indexed?, load?: "lazy" | "eager" })` resolves the parent from the store. Reading an unhydrated lazy parent suspends.
- `hasMany(target, { foreignKey, load?: "partial" | "instant" })` returns a `ReactiveCollection` backed by the target's index on `foreignKey`.

### `@crdtField(codec, { lazy? })`

Declares a field whose value is a CRDT document. See [CRDT fields](#crdt-fields).

### Instance API

| Member | Description |
| --- | --- |
| `id: string` | Primary key (generated if not given). |
| `save(): Promise<this>` | Persist changed fields. A new model emits a `put`; an existing one emits a `patch` of only dirty fields. |
| `delete(): Promise<void>` | Tombstone the row. A later `put` can recreate it; `patch` and CRDT updates do not resurrect it. |
| `isNew`, `isDirty`, `isDeleted` | Lifecycle flags (reactive). |
| `lifecycle` | `"new" \| "persisted" \| "deleted"`. |
| `syncGroups: string[]` | Groups this row belongs to. |

## Store

`SyncedStore` owns the object pool, the local engine, the optimistic overlay, subscriptions and the connection.

### `new SyncedStore(options)`

| Option | Type | Description |
| --- | --- | --- |
| `models` | `ModelClass[]` | All model classes. Required. |
| `commands` | `CommandDefinition[]` | Semantic commands this client may run. |
| `transport` | `SyncTransport` | `WebSocketSyncTransport`, or `InMemorySyncTransport` for tests. Omit for a local-only store. |
| `localEngine` | `LocalEngineAdapter` | Override the engine. Default in browsers: the WASM engine in an OPFS Worker (SharedWorker leader across tabs). |
| `userId` | `string` | Acting user or agent id. |
| `clientId` | `string` | Stable id for this replica. Generated if omitted. |
| `syncGroups` | `string[]` | Groups this client subscribes to. Must be a subset of what its token grants. |
| `persistence` | `string \| SyncPersistence` | A database name (OPFS → IndexedDB) or a custom adapter. Omit for memory only. |
| `maxCachedModels` | `number` | Soft cap on hydrated models before LRU dehydration of unwatched slices. |
| `dehydrateAfterMs` | `number` | Grace period before an unwatched partial slice is dehydrated (default `30000`). |
| `schemaVersion` | `number` | This client's schema version (default `1`). |
| `migrations` | `MigrationRegistry \| Migration[]` | Forward migrations for rows and pending ops persisted by older versions. |
| `onUpgradeRequired` | `(info) => void` | Called when the server rejects this client's schema version (HTTP 426). |

### Methods

| Method | Description |
| --- | --- |
| `connect(): Promise<void>` | Bootstrap (or catch up from `headSeq`) and open the live socket. Reconnects with backoff. |
| `disconnect()` / `dispose()` | Close the connection / release everything. |
| `restoreFromPersistence(): Promise<boolean>` | Load the persisted replica and pending writes. Returns `false` on a cold start. |
| `flushPersistence()` / `clearPersistence()` | Force a write to disk / wipe local data. |
| `create(Model, fields?, { id?, syncGroups? })` | New unsaved instance bound to the store. Call `save()`. |
| `get(Model, id)` | Synchronous lookup. Returns `undefined` if not loaded. |
| `getSuspense(Model, id)` | Like `get`, but loads by id and throws the promise for `<Suspense>`. |
| `all(Model)` | All hydrated rows of a model (reactive). |
| `where(Model, field, value)` | Cached `ReactiveCollection` for an indexed equality slice. Registers a server subscription while watched. |
| `query(Model)` | Fluent query builder. See [Queries](#queries). |
| `runCommand(cmd, target, payload)` | Run a semantic command. See [Commands](#commands). |
| `createOverlay`, `applyLocalToOverlay`, `promoteOverlay`, `discardOverlay`, `listOverlays` | Named drafts. See [Overlays](#overlays). |
| `setAwareness(channel, bytes)`, `awareness(channel)` | Ephemeral presence. See [Presence](#presence). |
| `setSyncGroups(groups)`, `revokeSyncGroups(groups)` | Change subscriptions; revoked rows are purged locally. |
| `getDiagnostics()` | `{ connectionState, headSeq, pendingCount, hydratedModels, activeSubscriptions, … }`. |

### Reactive properties

`connectionState` (`"disconnected" | "connecting" | "connected"`), `pendingCount`, `headSeq`, `syncGroups`, `upgradeRequired`. Reading them inside an observer re-renders on change.

## Queries

```ts
const urgent = store
  .query(Issue)
  .where("teamId", team.id)          // first string equality → indexed slice, loads & subscribes
  .whereIn("status", ["todo", "doing"])
  .whereRange("priority", { gte: 2 })
  .search("checkout crash")          // every token must match (fullText fields)
  .orderBy("priority", "desc")
  .orderBy("createdAt")              // tie-breaker
  .limit(20)
  .all({ suspend: true });
```

| Method | Description |
| --- | --- |
| `where(field, value)` | Equality. The first string equality selects the indexed partial-load slice; others filter locally. |
| `whereIn(field, values)` | Membership. |
| `whereRange(field, { gt?, gte?, lt?, lte? })` | Numeric or lexicographic range. |
| `filter(fn)` | Arbitrary predicate over live models. |
| `search(text, fields?)` | Case-insensitive tokenized full-text search. |
| `orderBy(field, "asc" \| "desc")` | Sort; repeat for tie-breakers. |
| `offset(n)`, `limit(n)` | Paging. |
| `all({ suspend? })`, `first({ suspend? })`, `count({ suspend? })` | Execute. With `suspend: true` an unhydrated slice throws its load promise. |

Queries are reactive: evaluated inside `observer` or `useQuery`, they re-run when any row they read changes. There is no SQL engine; queries compose over indexed slices in memory.

### `ReactiveCollection<T>`

| Member | Description |
| --- | --- |
| `items` | Rows; suspends if the slice is not hydrated. |
| `current` | Rows loaded so far; never suspends. |
| `load(): Promise<T[]>` | Hydrate explicitly (outside React). |
| `filter(fn)`, `sort(fn)` | Convenience, reactive. |

A watched collection holds a server subscription (an FNV-1a hash of `(model, index, key)`). When nothing watches it for `dehydrateAfterMs`, it unsubscribes and may be evicted from memory.

## Mutations

### Field edits

```ts
const issue = store.create(Issue, { teamId: "eng", title: "Checkout crashes on Safari" });
await issue.save();            // put

issue.status = "doing";
issue.priority = 3;
await issue.save();            // patch { status, priority }

await issue.delete();          // tombstone
```

`save()` resolves once the write is in the local overlay and queued — not when the server confirms. The UI never waits for the network. Server rejections (validation, authorization) remove the write on the next rebase and the view reverts.

### Commands

A command is a named, deterministic function that turns a payload plus the current row into primitive ops. It runs **optimistically on the client** and **authoritatively on the sequencer**, and is replayed — not its result — when the client rebases. Use commands whenever the new value depends on the old one.

```ts
import { defineCommand } from "@syncbase/client";

export const recordUsage = defineCommand<{ tokens: number }>({
  name: "recordUsage",
  model: "AgentRun",
  apply: ({ model, id, current, payload }) => {
    const prev = current?.fields.tokensUsed?.kind === "scalar"
      ? Number(current.fields.tokensUsed.value ?? 0) : 0;
    return [{ op: "patch", model, id, fields: { tokensUsed: prev + payload.tokens } }];
  },
});

const store = new SyncedStore({ models, commands: [recordUsage] /* … */ });
await store.runCommand(recordUsage, run, { tokens: 1840 });
```

Ten agents calling `recordUsage` concurrently produce the correct sum. Ten agents writing `run.tokensUsed = x` produce one winner.

`apply` must be pure and deterministic: no clocks, randomness or I/O. It returns any of these ops:

```ts
type MutationOp =
  | { op: "put";         model; id; fields; syncGroups }
  | { op: "patch";       model; id; fields; syncGroups? }
  | { op: "delete";      model; id; syncGroups? }
  | { op: "crdtUpdate";  model; id; field; update: Uint8Array }
  | { op: "command";     name; model; id; payload }
  | { op: "batch";       model; id; ops: MutationOp[] };   // atomic multi-row
```

The server must register the same command definitions (see [Server](#server-cloudflare)). For cross-platform apps, declare commands in `@syncbase/schema` instead (`cmd.increment`, `cmd.set`, `cmd.setAdd`, `cmd.setRemove`, `cmd.append`) and generate handlers for every language.

## CRDT fields

LWW is right for most fields and wrong for text that several writers edit at once. A `@crdtField` stores an opaque CRDT document; updates are binary deltas that merge commutatively and are never overwritten.

```ts
import * as Y from "yjs";
import { crdtField, createYjsCodec, type CrdtFieldController } from "@syncbase/client";

const yjs = createYjsCodec(Y);

@model({ name: "ChatMessage", loadStrategy: "partial" })
export class ChatMessage extends Model {
  @field({ indexed: true }) accessor runId = "";
  @crdtField(yjs) accessor body!: CrdtFieldController<Y.Doc>;
}

// An agent streams tokens while a human edits the same message.
const text = message.body.doc.getText("body");
for await (const token of llm.stream(prompt)) text.insert(text.length, token);
```

Local edits on `controller.doc` are captured automatically (via the codec's `onLocalUpdate`), sent as `crdtUpdate` ops, relayed peer-to-peer through the fan-out DO with no sequencer round trip, and later sequenced and compacted into checkpoints.

**Built-in codecs** (also understood by the Rust compactor): `createYjsCodec(Y)` (rich text, Yjs-compatible via `yrs`), `FractionalOrderCrdtCodec` (list ordering, with `fractionalKeyBetween`), `PnCounterCrdtCodec` (counters), `LwwSetCrdtCodec` (sets), `SimpleTextCrdtCodec`.

**Custom codecs** implement:

```ts
interface CrdtCodec<TDoc> {
  readonly name: string;
  createDoc(): TDoc;
  applyUpdate(doc: TDoc, update: Uint8Array): void;
  encodeState(doc: TDoc): Uint8Array;
  mergeUpdates(updates: Uint8Array[]): Uint8Array;
  onLocalUpdate?(doc: TDoc, listener: (update: Uint8Array) => void): () => void;
}
```

`CrdtFieldController<TDoc>`: `doc`, `version` (reactive), `peekDoc()`, `commitUpdate(bytes)`, `encodeSnapshot()`.

## Overlays

An overlay is a named, private layer of pending writes on top of confirmed state — a draft, a sandbox, a branch. It shares the confirmed base without copying it, is invisible to the live view, and is promoted or discarded as a unit. This is the primitive for **agent proposals that a human approves**.

```ts
store.createOverlay("agent:triage");

for (const issue of untriaged) {
  await store.applyLocalToOverlay("agent:triage", {
    op: "patch", model: "Issue", id: issue.id,
    fields: { priority: score(issue), status: "todo" },
  });
}

// A person reviews the diff, then either ships it to the server…
await store.promoteOverlay("agent:triage");
// …or drops it in O(1), confirmed state untouched.
store.discardOverlay("agent:triage");
```

| Method | Description |
| --- | --- |
| `createOverlay(name, { fromOptimistic? })` | New overlay. `fromOptimistic: true` starts from the current optimistic view instead of confirmed state. |
| `applyLocalToOverlay(name, op)` | Apply any `MutationOp` (including commands) into the overlay only. |
| `promoteOverlay(name)` | Move its writes into the live overlay and send them to the server. |
| `discardOverlay(name): boolean` | Drop it. |
| `listOverlays(): string[]` | Active overlays. |

## Presence

Awareness frames are ephemeral bytes on a channel — cursors, selections, "agent is reading file X". They travel through fan-out DOs only, are never persisted and never reach the sequencer.

```ts
const enc = new TextEncoder();
store.setAwareness(`run:${run.id}`, enc.encode(JSON.stringify({ step: "running tests" })));

for (const peer of store.awareness(`run:${run.id}`).values()) {
  // { channel, clientId, userId, payload: Uint8Array, timestampMs }
}
```

## React

All bindings are built on `useSyncExternalStore` and support Suspense and transitions.

```tsx
import {
  SyncbaseProvider, useSyncbase, observer,
  useModel, useCollection, useQuery, useCrdt, useAwareness, SyncbaseDevTools,
} from "@syncbase/react";
```

| API | Description |
| --- | --- |
| `<SyncbaseProvider store>` | Provides the store. |
| `useSyncbase()` | Returns the store. |
| `observer(Component)` | Tracks every model field, relation, collection and CRDT read during render; re-renders on exactly those. Unhydrated reads suspend. |
| `useModel(Model, id, { suspense = true })` | One row by id. |
| `useCollection(collection, { suspense = true })` | Rows of a `ReactiveCollection`. |
| `useQuery(store => expr)` | Any reactive expression, e.g. a `store.query(…).all()`. |
| `useCrdt(model, field)` | `{ doc, controller, version }`; re-renders on local and remote updates. |
| `useAwareness(channel)` | `{ peers, setAwareness }`. |
| `<SyncbaseDevTools />` | Inspector for overlay, pending ops, subscriptions and connection. |

`observer` and hooks can be mixed. Prefer `observer` for components that read many fields.

## Agents

An agent is a client like any other: it gets a token with the sync groups it may see, creates a `SyncedStore` with the same models, and writes through the same API. Run it in a browser, a Worker, Bun or Node.

```ts
// agent.ts — runs in Bun / Node / a Worker
import { SyncedStore, WebSocketSyncTransport } from "@syncbase/client";
import { MODELS, recordUsage, AgentRun, AgentStep } from "./models";

const store = new SyncedStore({
  models: MODELS,
  commands: [recordUsage],
  userId: "agent:reviewer",
  syncGroups: ["proj:42"],
  transport: new WebSocketSyncTransport({ baseUrl: SYNC_URL, token: AGENT_TOKEN }),
});
await store.connect();

const run = await store.query(AgentRun).where("projectId", "42").first({ suspend: false });
run.status = "running";
await run.save();

await store.create(AgentStep, { runId: run.id, projectId: "42", kind: "tool", summary: "bun test" }).save();
await store.runCommand(recordUsage, run, { tokens: 1840, costCents: 2.1 });
```

Guidelines for agents writing to syncbase:

- **Write fields, not rows.** Set only the fields you mean to change, then `save()`; other writers' fields survive.
- **Use commands for read-modify-write.** Counters, appends and reorders belong in a command.
- **Stream text into CRDT fields.** Never rewrite a long string field token by token.
- **Propose in an overlay** when a human should approve; promote on approval.
- **Publish presence** on a channel so people can see what you are doing.
- **Scope the token.** Give each agent only the sync groups its task needs.

## Authorization

Authorization is routing. Every row carries `syncGroups` (for example `user:alice`, `team:eng`, `proj:42`). A client receives exactly the rows where its groups intersect the row's groups — in bootstrap, partial loads and live deltas.

### Tokens

Clients authenticate with an HS256 JWT:

```ts
interface SyncbaseJwtClaims {
  sub: string;          // user or agent id
  workspaceId: string;  // one sequencer per workspace
  syncGroups: string[]; // what this principal may read and write
  roles?: string[];
  iat?: number;
  exp?: number;
}
```

```ts
import { signSyncbaseToken } from "@syncbase/cf";
const token = await signSyncbaseToken(
  { sub: "agent:reviewer", workspaceId: "acme", syncGroups: ["proj:42"] },
  env.JWT_SECRET,
  { expiresInSeconds: 3600 },
);
```

Or from the CLI: `syncbase token --secret $JWT_SECRET --user alice --workspace acme --groups team:eng,user:alice --ttl 3600`.

The token is sent as `Authorization: Bearer <jwt>` or `?token=<jwt>` on the WebSocket URL.

### Write policies

The sequencer rejects writes to rows outside the writer's groups and writes that assign groups the writer does not hold. Add per-model rules with `createPolicyBeforeWriteHook`:

```ts
import { createPolicyBeforeWriteHook, getScalarField } from "@syncbase/cf";

const beforeWrite = createPolicyBeforeWriteHook({
  Issue: {
    allowDelete: ({ userId, currentRow }) =>
      getScalarField(currentRow, "creatorId") === userId || "only the creator can delete",
  },
  ApprovalGate: {
    allowPatch: ({ userId }) => !userId.startsWith("agent:") || "agents cannot approve",
  },
});
```

Each rule receives `{ workspaceId, userId, userSyncGroups, op, currentRow }` and returns `true` to allow, or `false` / a string reason to reject. Rules: `allowPut`, `allowPatch`, `allowDelete`, `allowCrdt`, `allowCommand`.

## Server (Cloudflare)

The server is a stateless Worker plus two Durable Object classes and an R2 bucket. There is no external database.

| Component | Role |
| --- | --- |
| Edge Worker | Authenticates, serves bootstrap and partial loads straight from R2 + edge cache via range reads, routes sockets. |
| `WorkspaceFanout` DO | Hibernated WebSockets, sync-group and subscription filtering, presence, CRDT relay, cross-user write batching. |
| `WorkspaceSequencer` DO | One per workspace. Manifest + hot WAL in DO SQLite, validation, commands, `seq`, flushes L0 segments to R2. |
| Compactor | Cron. Merges segments, folds CRDT updates, prunes tombstones, atomically swaps the manifest. |

The template in `templates/cloudflare` is complete. Its shape:

```ts
import {
  WorkspaceSequencer, WorkspaceFanout, createSyncbaseWorker,
  createJwtAuthenticator, createWasmSegmentCodec, compactWorkspaceR2,
} from "@syncbase/cf";
import { buildSchemaDescriptor } from "@syncbase/client";
import { initSyncbaseWasmSync } from "@syncbase/wasm";
import wasmModule from "@syncbase/wasm/syncbase_wasm_bg.wasm";
import { MODELS } from "./models";

const SCHEMA = buildSchemaDescriptor(MODELS);

export class WorkspaceSequencerDO {
  sequencer: WorkspaceSequencer;
  constructor(ctx: DurableObjectState, env: Env) {
    const wasm = initSyncbaseWasmSync(wasmModule);
    this.sequencer = new WorkspaceSequencer({
      workspaceId: ctx.id.name!, schema: SCHEMA, sql: ctx.storage.sql,
      r2: env.SYNCBASE_R2, wasm, segmentCodec: createWasmSegmentCodec(wasm),
      onBroadcast: (batch) => /* POST to the workspace's fan-out DO */,
    });
  }
  // fetch(): /commit, /delta, /hot-rows, /compact …
}

export class WorkspaceFanoutDO { /* new WorkspaceFanout({ commitMultiUserToSequencer, … }) */ }

export default {
  fetch(request: Request, env: Env) {
    const wasm = initSyncbaseWasmSync(wasmModule);
    return createSyncbaseWorker<Env>({
      schema: SCHEMA,
      segmentCodec: createWasmSegmentCodec(wasm),
      authenticate: createJwtAuthenticator({ getSecret: (e) => e.JWT_SECRET }),
      getR2: (e) => e.SYNCBASE_R2,
      getSequencer: (e, workspaceId) => /* stub client */,
      getFanout: (e, workspaceId, shard) => /* stub client */,
      upgradeToFanout: (req, e, auth, shard) => /* forward to fan-out DO */,
    }).fetch(request, env);
  },
  scheduled: (_, env) => /* compactWorkspaceR2 for each workspace */,
};
```

```toml
# wrangler.toml
name = "syncbase-edge"
main = "src/index.ts"
compatibility_date = "2026-01-01"
compatibility_flags = ["nodejs_compat"]

[[r2_buckets]]
binding = "SYNCBASE_R2"
bucket_name = "syncbase-segments"

[[durable_objects.bindings]]
name = "SEQUENCER"
class_name = "WorkspaceSequencerDO"

[[durable_objects.bindings]]
name = "FANOUT"
class_name = "WorkspaceFanoutDO"

[[migrations]]
tag = "v1"
new_sqlite_classes = ["WorkspaceSequencerDO", "WorkspaceFanoutDO"]
```

```bash
wrangler r2 bucket create syncbase-segments
wrangler secret put JWT_SECRET
wrangler deploy
```

### `createSyncbaseWorker(config)`

| Option | Description |
| --- | --- |
| `schema` | `SchemaDescriptor` from `buildSchemaDescriptor(models)`. |
| `authenticate(request, env)` | Returns `{ workspaceId, userId, syncGroups }` or `null`. |
| `getR2(env)` | The segment bucket. |
| `getSequencer(env, workspaceId)` | Client for the sequencer DO (`commitBatch`, `readDelta`, `readHotRows`). |
| `getFanout?(env, workspaceId, shard)` | Enables write coalescing and hot-tail reads from fan-out. |
| `upgradeToFanout(request, env, auth, shard)` | Hands the WebSocket to a fan-out DO. |
| `hotReadSource?` | `"fanout-preferred"` (default with fan-out), `"sequencer"`, or `"r2-only"`. |
| `resolvePartitions?(auth)` | Partition ids for sharded workspaces (`PartitionedWorkspaceSequencer`). |
| `schemaVersion?`, `minClientSchemaVersion?`, `migrations?` | Version negotiation and on-read migrations. |

### Self-hosting

`@syncbase/node` runs the same sequencer and fan-out on Bun or Node with disk SQLite and any S3-compatible object store: `createStandaloneSyncbaseServer({ … })`.

## Wire protocol

| Endpoint | Method | Purpose |
| --- | --- | --- |
| `/sync/ws` | GET (upgrade) | Live socket: mutations up; batches, presence, CRDT relay, revocations down. |
| `/sync/bootstrap` | POST | Initial load of `instant` models for the caller's groups, from R2 segments + hot rows. |
| `/sync/partial` | POST | Load one indexed slice `(model, index, key)`. |
| `/sync/delta` | POST | Catch up from `afterSeq`. |
| `/sync/mutate` | POST | Submit mutations over HTTP (coalesced by fan-out). |

Frames are binary `SBW1` by default (`binary: false` on the transport selects JSON). A server batch carries the committed events in `seq` order and the `clientEventId`s it confirmed or rejected. Clients detect gaps through `prevSeq` and catch up with `/sync/delta`.

## Schema, codegen and migrations

For apps that span TypeScript, Swift and Kotlin, declare the schema once with `@syncbase/schema`:

```ts
// schema.ts
import { defineSchema, f, m, cmd } from "@syncbase/schema";

export default defineSchema({
  version: 2,
  models: {
    Issue: m.model({
      loadStrategy: "partial",
      syncGroups: ["team:{teamId}"],
      fields: {
        teamId: f.ref("Team"),
        title: f.string(),
        status: f.enum(["todo", "doing", "done"]),
        votes: f.int(),
      },
      crdt: { body: f.crdt("yjs") },
    }),
  },
  commands: {
    vote: cmd.for("Issue", { payload: { by: f.int() }, op: cmd.increment("votes", "by") }),
  },
});
```

```bash
syncbase codegen schema.ts --out gen --targets ir,ts,swift,kotlin,rust
syncbase diff gen/schema.ir.json schema.ts     # fails CI on breaking changes
syncbase migrate ./data --schema schema.ts --apply
syncbase inspect ./data                         # dump WAL and segments
```

Codegen emits TypeScript `@model` classes, Swift `@Observable` types, Kotlin `StateFlow` models and Rust schema metadata from one canonical `schema.ir.json`. Migrations (`mig.step(from, to, [...])`) run forward on persisted client replicas, on pending writes, and on read for server segments not yet compacted.

## Storage engine

- **Segments (`SBSEG001`)** — immutable, block-based files: data blocks sorted by `(model, id)` with per-field `(seq, value)` entries, tombstones, sync groups and CRDT state; posting-list index blocks; a directory, footer and 32-byte trailer with CRC32. A lookup needs a few HTTP range reads (on R2) or file reads (on OPFS) and under 1 MB of memory.
- **One format everywhere** — the same segments live in R2 and in the browser's OPFS. A cold client bootstraps by range-reading cacheable, immutable files from the edge.
- **Manifest** — `generation`, `head_seq`, active segments per level, swapped atomically by the compactor.
- **Compaction** — streaming k-way merge resolving per-field LWW, folding CRDT updates into checkpoints, pruning tombstones below a watermark, rebuilding postings.
- **Traits** — `ObjectStore` and `WalStore` keep the Rust core independent of Cloudflare.

Verified with proptest state machines against brute-force oracles, crash-consistency tests that fail the k-th write and require recovery to a step boundary, deterministic network simulation, and Quint specifications of flush/compaction CAS and partitioned moves.

## Limits

| Limit | Value |
| --- | --- |
| Storage per workspace sequencer | 10 GB (SQLite Durable Object), most data lives in R2 |
| Max row value | 8 MB |
| Sequencer throughput | ~1,000 requests/s per DO; fan-out batches many writes into one request. Shard large workspaces with `PartitionedWorkspaceSequencer`. |
| Memory per Worker isolate | 128 MB |

## Not yet

syncbase is honest about what it does not do at `0.1`:

- No SQL or incremental view maintenance; queries compose over indexed slices.
- No Postgres or CDC ingest; syncbase is the database of record.
- No declarative permission language; policies are code.
- Server runtime is Cloudflare or the Node/Bun standalone server.
