# any docs — complete documentation --- Source: https://docs.any.org/index.html # Any A reactive, **local-first** database. Documents live on your devices, merge as CRDTs, sync end-to-end encrypted, and answer Mongo-style queries with live subscriptions — online or not. Chat and a block editor are built in as CRDT modules, and anyrt runs sandboxed Python programs, scheduled jobs, and agents right alongside your data. **Developer preview.** APIs may change; MIT licensed. [Preview status](https://docs.any.org/understanding/preview.md.txt). local-first e2e encrypted crdt mongo queries sse live queries wasm-sandboxed programs single go binary ## Get started The block below is the whole loop; [Install](https://docs.any.org/quickstart/install.md.txt) explains each line. A binary with nothing configured joins the **production** any-sync network — [Networks](https://docs.any.org/quickstart/networks.md.txt) if you want a sandbox. ```sh $ export ANY_DATA_DIR="$HOME/.any-demo" $ export ANY_INDEX_EMBEDDER=local $ any init A new wallet was generated. Write down the recovery phrase below. You will NOT see it again. Anyone with this phrase owns the account. { "accountId": "A8tR…", "created": true } $ any run & LISTENING 127.0.0.1:7001 $ until any status >/dev/null 2>&1; do sleep 0.2; done $ API=http://127.0.0.1:7001/v1 $ S=$(curl -fsS $API/spaces -H 'content-type: application/json' -d '{"name":"notes"}' | jq -er .id) $ curl -fsS $API/spaces/$S/objects -H 'content-type: application/json' \ -d '{"type":"page","initialProperties":{"any":{"name":"hello"}}}' { "objectId": "bafyrei…" } $ curl -fsSN $API/spaces/$S/objects/query/subscribe -H 'content-type: application/json' \ -d '{"sort":["-modifiedAt"],"limit":20}' event: ready data: {} event: snapshot data: {"records":[{"id":"bafyrei…","any":{"type":"page","name":"hello"},…}]} event: changes data: [{"versionId":"…","updated":[…]}] ``` ### Database Spaces of objects and datasets, typed properties, Mongo-style filters, aggregation pipelines, version history — every byte CRDT-merged and encrypted. [Learn more](https://docs.any.org/database/index.md.txt) ### Sync & realtime Windowed live queries over SSE, head-sync with peers, sync status, an ephemeral event bus, end-to-end encrypted push. [Learn more](https://docs.any.org/realtime/index.md.txt) ### Runtime Python programs in a wasm cage with a recorded effect boundary; cron / once / event triggers pinned to a device; the bao agent. [Learn more](https://docs.any.org/programs/index.md.txt) ## Everything [**1. Understanding any** — Local-first, encryption, CRDT consistency, the invariants.](https://docs.any.org/understanding/index.md.txt) [**2. Quickstart** — Install, first space in curl, CLI, JS, Python, mobile, anyrt.](https://docs.any.org/quickstart/index.md.txt) [**3. Tutorial** — Objects, properties, datasets, apps — four parts that build on each other.](https://docs.any.org/tutorial/index.md.txt) [**4. Database** — Spaces, objects, types, collections, reading & writing, aggregation, history.](https://docs.any.org/database/index.md.txt) [**5. Realtime** — Subscribe, sync status, space list, event bus.](https://docs.any.org/realtime/index.md.txt) [**6. Auth & identity** — Mnemonic accounts, devices, identities directory.](https://docs.any.org/auth/index.md.txt) [**7. Collaboration** — Members, invites, ACL, one-to-one spaces, bundles.](https://docs.any.org/collaboration/index.md.txt) [**8. Modules** — Chat, block editor, the page type, any:// links and backlinks.](https://docs.any.org/types/index.md.txt) [**9. Files** — Encrypted attachments, durability, cache.](https://docs.any.org/files/index.md.txt) [**10. Search** — Full-text, vector, hybrid — with a local embedder.](https://docs.any.org/search/index.md.txt) [**11. Notifications** — E2E push and process progress.](https://docs.any.org/notifications/index.md.txt) [**12. Programs** — Sandboxed Python, effects, traces that replay bit-exact.](https://docs.any.org/programs/index.md.txt) [**13. Scheduling** — Cron, once and event triggers as synced records.](https://docs.any.org/scheduling/index.md.txt) [**14. Agents** — bao: conversations, tools, memory, connectors.](https://docs.any.org/agents/index.md.txt) [**15. Operations** — Server lifecycle, config, networks, builds.](https://docs.any.org/operations/index.md.txt) [**16. Testing** — e2e patterns and the kernel-fidelity harness.](https://docs.any.org/testing/index.md.txt) [**17. Reference** — HTTP API, CLI, events, errors, config, glossary.](https://docs.any.org/reference/index.md.txt) ## Why local-first > **Why it matters.** A hosted backend is available exactly when its vendor is. In any every device holds the full state of every space it belongs to, every write lands locally first, and peers converge later through encrypted sync — the network is an optimisation, not a dependency. Relay nodes store ciphertext and can't read a single document. - **Reactive** — every read has a live form: `/query` gives a snapshot, `/query/subscribe` keeps a window of results current. - **Mongo-style queries** — `$eq`, `$in`, `$regex`, `$text`, nested paths, array matching, `$group`/`$unwind` pipelines. - **CRDT** — concurrent edits from any number of devices merge deterministically; versions are content-addressed changes you can diff and view. - **Built-in messenger and editor** — chat messages with reactions, mentions and read tracking; block documents with a markdown bridge; ready-made apps (wiki, journal, contacts, CRM) installed from a server catalog. - **Runtime in your data** — programs, triggers and agent memory are records in your encrypted space, not rows in a vendor's database. Also available as [`llms.txt`](https://docs.any.org/llms.txt) for language models. --- Source: https://docs.any.org/understanding/index.html # Understanding any `any` is a reactive, local-first, end-to-end-encrypted database with Mongo-style queries, built-in chat and editor CRDTs, and a sandboxed Python runtime for jobs and agents that live inside your own data. This section explains the model; the quickstart gets you running in five minutes. ## The three pieces | Piece | Component | What it does | | --- | --- | --- | | **Runtime** | anyrt | Programs in wasm, scheduled jobs, agents — talks to the database over the same HTTP API. | | **Sync** | any-sync | CRDT changes, ACLs, head-sync, p2p LAN; nodes relay ciphertext and keys never leave devices. | | **Database** | any-store | Local document DB: queries, indexes, live windowed subscriptions, full-text + vectors. | **Database.** Every device runs the whole database locally. Reads are indexed queries against a file on disk; writes commit locally and return immediately. The server process (`any run`) exposes it on `127.0.0.1:7001` as HTTP/JSON with Server-Sent Events for live updates. **Sync.** A write becomes a signed, encrypted *change* in a per-object DAG. any-sync nodes store and relay those changes to the other members of the space; devices on the same LAN also sync directly over p2p. Convergence is guaranteed by the CRDT — there is no server-side "truth" that a device must defer to. **Runtime.** anyrt runs Python programs inside a wasm cage. Programs can only touch the world through a recorded *effect boundary*, so every run is a replayable trace, and scheduled triggers are ordinary records in the database. ## How a write flows ``` client ──POST /v1/spaces/:id/modify──▶ any server │ 1. validate against dataset handler / schema │ 2. append a change to the object's DAG (local disk) │ 3. apply CRDT ops to any-store rows │ 4. emit windowed deltas to open subscriptions ▼ {versionId, changeId, recordIds} ← returned to the client │ ▼ (background) encrypt + sign → any-sync nodes / LAN peers → other members │ ▼ their server applies the same change, their subscriptions see the same delta ``` Steps 1–4 happen on your machine, online or not. The background leg runs whenever a peer is reachable. The reply to a write carries the change's ids, never the record body — you read state back through a query or a subscription, which is also where remote changes arrive. ## How a read flows Reads never leave the device. `POST /v1/spaces/:id/query` runs a filter/sort/limit against the local store and returns a snapshot; `POST /v1/spaces/:id/query/subscribe` returns the same snapshot and then streams `added` / `updated` / `removed` deltas for as long as the connection stays open. See [Reading data](https://docs.any.org/database/reading-data.md.txt) and [Subscriptions](https://docs.any.org/realtime/subscribe.md.txt). > **Why it matters.** Because the database is local, latency is disk latency, not network latency; because sync is a CRDT over an encrypted DAG, the nodes in between hold nothing they can read; and because the runtime lives on the same machine, an agent can work on your data without that data ever being uploaded to anyone. ## Vocabulary | Term | Meaning | | --- | --- | | **Account** | An identity derived from a BIP-39 mnemonic. One server process serves one account. | | **Space** | The unit of sharing and permissions: an encrypted container of objects with its own ACL and members. | | **Object** | A content-addressed DAG of changes. Holds property values plus zero or more datasets. | | **Dataset** | A named storage collection of records on an object (`chat_messages`, `editor_blocks`, a runtime dataset's `_`, …). | | **Type** | What an object is — exactly one, in `any.type`: its properties, its layout, and the parts whose datasets the object takes. | | **Collection** | What an object is filed under — any number, in `any.collections`: property definitions only. | | **Module** | The server code that serves a kind of dataset — `editor` blocks, `chat` messages, generic `records` — for every type whose part declares it. | | **Change** | One signed, encrypted write appended to an object's DAG. Its CID is the `changeId`. | | **Program** | Python code stored in a space and executed by anyrt inside the effect boundary. | | **Trigger** | A record describing when to run a program: cron, once, or on an event. | [**Local-first** — Offline is the normal case; sync is how devices catch up.](https://docs.any.org/understanding/local-first.md.txt) [**Encryption** — What nodes see, what they don't, and where the keys come from.](https://docs.any.org/understanding/encryption.md.txt) [**Architecture** — any-store → any-sync → SDK → any → clients: what each layer owns, and the node roles.](https://docs.any.org/understanding/architecture.md.txt) [**Spaces and trees** — ACL plus object trees; changes, heads, head-sync, derived ids, the space lifecycle.](https://docs.any.org/understanding/spaces-and-trees.md.txt) [**The record CRDT** — Datasets, records, per-path ops, `\_ver`, handlers, tombstones — with a worked merge.](https://docs.any.org/understanding/record-crdt.md.txt) [**The tech space** — The account's private space: the space list, devices, profile, account-scoped values, mirrors.](https://docs.any.org/understanding/tech-space.md.txt) [**Versioning and re-index** — Handler versions, rebuilding rows from the DAG, why there are no migrations, index generations.](https://docs.any.org/understanding/versioning-and-reindex.md.txt) [**CRDTs and consistency** — Per-path last-writer-wins on DAG order, and what that means versus transactions.](https://docs.any.org/understanding/crdt-and-consistency.md.txt) [**The zen of any** — The invariants the API keeps, and why.](https://docs.any.org/understanding/zen-of-any.md.txt) [**Developer workflow** — init, run, the CLI, the web UI, the data dir.](https://docs.any.org/understanding/dev-workflow.md.txt) [**Best practices** — Eleven rules for a client that stays correct and cheap.](https://docs.any.org/understanding/best-practices.md.txt) [**Programs and effects** — Sandboxed Python, the effect boundary, replay, triggers as data.](https://docs.any.org/understanding/programs-and-effects.md.txt) --- Source: https://docs.any.org/understanding/preview.html # Preview status and license `any` is a **developer preview**. The data model, the HTTP API and the on-disk format can still change between releases, and a breaking wire change is absorbed by bumping the `/v1/` prefix rather than by a migration. Use a separate account and data root for experiments. ## License `any`, `anyrt` and the SDKs they build on ([any-sync](https://github.com/anyproto/any-sync), [any-store](https://github.com/anyproto/any-store), [any-sync-sdk](https://github.com/anyproto/any-sync-sdk)) are released under the **MIT** license. ## What runs on your device The `any` binary is the server and the CLI: `any run` owns the any-store database, the search index and the sync engine; every other `any ` is an HTTP client of it. The companion `anyrt` runtime executes programs, agent sessions and triggers in a wasm cage against that server. Standalone, they are two processes; a host app can embed both ([Install](https://docs.any.org/quickstart/install.md.txt), [anyrt](https://docs.any.org/quickstart/anyrt.md.txt), [Embedding anyrt](https://docs.any.org/agents/embedding-anyrt.md.txt)). The server binds to loopback. Its API serves the account loaded into that process and currently has no per-caller authentication — with the plan to ship proper auth and access capabilities support. It is designed to be used by software on the same device. [Security model →](https://docs.any.org/operations/security-model.md.txt) ## Offline behavior Database operations work against local state. Sync needs a reachable peer. Fetching an uncached file needs a source that holds its bytes. Calling an external model or connector needs that service to be available. Scheduled programs need a device with the `anyrt` runtime running. [Local-first →](https://docs.any.org/understanding/local-first.md.txt) --- Source: https://docs.any.org/understanding/local-first.html # Local-first In `any`, offline is the default. Every read and write is served from the database on your disk. Sync runs in the background, carrying your changes to other devices and members and bringing theirs to you. A successful write means *this device* has appended the change. It does not mean another device has received it, or that a sync node holds a copy — `/sync-status` below is how you learn that. ## What "local" means here The `any` server process owns an any-store database under the account's data dir (`//sdk/`). A query is an indexed read against that file. A write validates, appends a change to the object's DAG, applies the CRDT ops to the rows, and returns — all before any network I/O. ```bash # works with the network cable unplugged curl -X POST http://127.0.0.1:7001/v1/spaces/$SPACE/objects \ -H 'content-type: application/json' \ -d '{"type":"page","initialProperties":{"any":{"name":"Offline note"}}}' ``` The reply is `201` with the new object's id. It will sync later; nothing about the request depends on whether "later" is milliseconds or days away. ## What sync is A change is a signed, encrypted node in a per-object DAG (a git-like history: each change lists the heads it was built on). Sync is the exchange of DAG changes between peers: - **Network sync** — the space's responsible any-sync nodes store ciphertext changes and relay them. A device that comes online pulls what it missed and pushes what it wrote. - **Local-network sync** — devices on one LAN discover each other over mDNS and exchange changes directly for the spaces they share, including while the nodes are unreachable (config `p2p.enabled`, on by default). Both paths deliver the same changes; a space can be fully `synced` with `networkPeers: 0` when everything converged over the LAN. ## Head-sync and convergence Peers compare *heads* — the tips of each object's DAG. If two peers have the same heads for every object, they hold the same state. A local write goes out at once, streamed as a head update to the connected nodes and peers. A **head-sync round** is the catch-up for anything a stream missed: it diffs the head sets against the responsible nodes and exchanges the missing changes. It runs on a periodic timer (~30 s); you can force one: ```bash curl -X POST http://127.0.0.1:7001/v1/spaces/$SPACE/sync # → 204 when the round completes any space sync $SPACE ``` Convergence follows from the CRDT: once two peers have applied the same set of changes, in any order, they hold identical rows ([CRDTs and consistency](https://docs.any.org/understanding/crdt-and-consistency.md.txt)). There is no reconciliation step, no conflict dialog, no server copy that wins. The merge is per-path last-writer-wins on DAG order, not a transaction: it does not enforce an invariant across fields, and two concurrent writes to the same field keep one value. ## Observing sync state Sync state is a first-class read, cheap enough to poll on a render tick: ```bash curl http://127.0.0.1:7001/v1/spaces/$SPACE/sync-status ``` ```json { "spaceId": "bafy…", "state": "syncing", "synced": 1, "total": 3, "networkPeers": 1, "localPeers": 0, "p2p": "notconnected", "lastSyncedAt": "2026-08-24T10:12:00Z" } ``` | `state` | Meaning | | --- | --- | | `synced` | Every object's heads match the responsible peers. | | `syncing` | Changes are in flight in one direction or the other. | | `unknown` | Space not loaded yet on this device (or an object id nobody has seen). | | `offline` | No responsible node reachable; local reads and writes continue. | | `error` | The network is incompatible with this build. | The rollup reports `synced`, `syncing` and `unknown`; `offline` and `error` are reserved in the vocabulary for reachability and network-compatibility signals, so render them rather than failing on them. Per-object state lives at `…/sync-status/objects/:objectId`, and both levels stream transitions over SSE ([Sync status](https://docs.any.org/realtime/sync-status.md.txt)). ## Boot catch-up When the server starts, it binds the listener first and runs the space loading + offline catch-up on a background pass. `GET /v1/health` reports `"bootstrapping": true` while that pass runs; reads against a space that has not had its turn yet serve the pre-offline state. Per-space convergence is what `/sync-status` reports, not the health flag. > **Why it matters.** A hosted backend answers a query with the truth as the server sees it, and returns an error when it cannot. any answers with the truth as *this device* sees it, always. That is the property that makes an app usable on a plane, a phone in a tunnel, or a laptop whose owner simply never turned sync on — and it is why the API never asks you to handle a "not connected" error on a read or write. ## What still needs a network | Operation | Offline behavior | | --- | --- | | Query or edit data already on this device | Local state; the write syncs later. | | Receive changes from another device | Needs a reachable peer: LAN p2p or a sync node. | | Read a file whose bytes are cached locally | Local. | | Read an uncached file | Needs a peer or a file node that holds the bytes ([Files](https://docs.any.org/files/index.md.txt)). | | Search with `index.embedder: local` | Local once the model and llama.cpp libraries are present. | | Call an external model or connector from a program | Needs that service; the effect is recorded either way. | A newly joined space may still be loading: the account's space list and the materialized content of that space are separate states ([space lifecycle](https://docs.any.org/database/spaces.md.txt)). ## What does not sync - **Local-scope fields** — dataset fields declared `local` (chat's `unread` flags, for example) are device-only; they never enter the DAG ([System fields](https://docs.any.org/database/system-fields.md.txt)). - **Account-scope settings** — per-space `settings` sync across the account's own devices through the tech space, never to other members. - **The search index** — derived state, rebuilt locally from the change feed ([Indexing](https://docs.any.org/search/indexing.md.txt)). - **Run traces** kept by `anyrt` — trace bodies live in the server's device-local store; only a per-run summary syncs ([Traces and replay](https://docs.any.org/programs/traces-and-replay.md.txt)). > **Note.** Timestamps such as `modifiedAt` are the *author's* clock. They converge (every peer ends up with the same value), but they are display and sort quality only — never use them as a fence for "has this synced yet". Use `/sync-status` for that. --- Source: https://docs.any.org/understanding/architecture.html # Architecture any is five layers, each with one job: an embedded document database, a peer-to-peer sync protocol, an SDK that turns signed changes into queryable records, a local HTTP server, and whatever talks to that server. Knowing which layer owns a behaviour tells you where its guarantees come from — and where its limits are. ## The stack | Layer | What it owns | | --- | --- | | **Clients** | Web UI, CLI, JS / Python / mobile bindings, anyrt (programs and agents) — all speak HTTP/JSON + SSE. | | **any** | HTTP façade on `127.0.0.1:7001`, CLI client, search and link index, event bus, markdown bridge, bundles engine and usecase catalog, local store. | | **any-sync-sdk** | Space / Object / record CRDT, types, collections and properties, datasets and handlers, tech space, queries and subscribe. | | **[any-sync](https://github.com/anyproto/any-sync)** | The protocol: spaces, ACLs, object trees (signed + encrypted change DAGs), head-sync, files, nodeconf, mDNS p2p. | | **[any-store](https://github.com/anyproto/any-store)** | Embedded document DB: storage collections, Mongo filters, modifiers, indexes, transactions, FTS + vector indexes. | Everything above the any-sync layer runs inside one process on your machine. Below it sits the network — and, as the next sections show, the network holds only ciphertext. ## any-store — the database [any-store](https://github.com/anyproto/any-store) is an embedded document database. It stores anyenc documents (a binary JSON-like encoding) in storage collections, filters them with a MongoDB-style query language (`$eq`, `$in`, `$gt`, `$elemMatch`, `$regex`, `$and`/`$or`, …), mutates them with modifiers (`$set`, `$unset`, `$inc`, …), and picks indexes with a cost-based planner. It provides ACID transactions with a single writer and snapshot-isolated reads, plus BM25 full-text and vector indexes that the [search index](https://docs.any.org/search/index.md.txt) is built on. It has no notion of sync, peers, encryption or subscriptions. Every layer above it is what turns a local file into a shared database. ## any-sync — the protocol [any-sync](https://github.com/anyproto/any-sync) is the open protocol for end-to-end-encrypted, local-first collaboration. Its unit of sharing is a **space**: a collection of objects with an access control list. Its unit of data is an **object tree**: a content-addressed DAG of changes, each one signed by its author and encrypted with the space's read key. Devices exchange changes; nobody exchanges "state". [Spaces and trees](https://docs.any.org/understanding/spaces-and-trees.md.txt) covers the mechanics; here is the map. ### Nodes and their roles The infrastructure side is a set of nodes, each with a fixed job. The protocol is symmetric — a node runs the same code paths as a device, so every node is just another peer. | Node type | nodeconf `types` | Responsibility | | --- | --- | --- | | **Sync node** | `tree` | Stores and relays spaces: ACL records and object-tree changes, all ciphertext. Each space is served by several sync nodes for redundancy. | | **File node** | `file`, `fileV2` | Stores encrypted file blocks (IPLD DAGs). Backs the durability tier of [files](https://docs.any.org/files/index.md.txt). | | **Consensus node** | `consensus` | Validates ACL changes: an ACL is a linked list of signed records, and a sync node asks a consensus node to confirm a new record is a conflict-free extension before accepting it. | | **Coordinator node** | `coordinator` | Keeps the network configuration; registers spaces, tracks their status, runs the deletion log, stores invite files, and tells clients which sync nodes serve a space. | The production configuration also lists naming and payment-processing nodes; any does not use them. ### What a network is A **network** is a nodeconf: a YAML document with a network id (its public key), and a list of nodes — peer id, addresses, types. The `any` binary embeds the production nodeconf and joins it unless configured otherwise ([Networks](https://docs.any.org/operations/networks.md.txt)). Which sync nodes serve a given space is not negotiated — it is computed. Every space header carries a `replicationKey`; the nodeconf hashes it through a consistent-hash ring of partitions to pick the responsible nodes. A device asks the coordinator for the current configuration, computes the same answer, and connects to those nodes. Adding a node changes the configuration and reshards spaces between nodes. ### What nodes can see Every change on the wire has a cleartext envelope — previous change ids, the ACL head it was written under, the read-key id, the author's public key, the signature — and an encrypted payload. Nodes verify the envelope: signature valid, author present in the ACL at that head, DAG links resolvable. They never hold a read key, so the payload is opaque to them ([Encryption](https://docs.any.org/understanding/encryption.md.txt)). Two consequences are worth stating plainly. A sync node cannot serve a query, so **every query runs on a device**; and an ACL change needs a consensus node, so **changing membership requires network access** while every other write works offline. ### Two transports Devices reach each other two ways, and both carry the same changes: through the network's sync nodes, and directly over the LAN, where any-sync discovers peers with mDNS and syncs the spaces both sides have access to. A device that has both acts as a bridge for one that has only the LAN ([Local-first](https://docs.any.org/understanding/local-first.md.txt)). ## any-sync-sdk — records out of changes any-sync stores and delivers encrypted blobs; it does not know what is in them. The SDK is the layer that decides: it defines that a change is a batch of per-record ops on a named **dataset**, applies those ops to any-store rows through a per-field version gate, and exposes the result as queries and windowed subscriptions. It owns: - **Spaces** as an API: create, join, invite, ACL operations, members, delete-and-offload. - **Objects** with many datasets each; the DAG itself is hidden — callers see `Modify` / `Delete` / `Query`. - **The record CRDT** — per-path last-writer-wins on DAG order, upsert, sticky tombstones, content-addressed record ids ([Record CRDT](https://docs.any.org/understanding/record-crdt.md.txt)). - **Types, collections and properties** — the `objects` storage collection with one row per object, property definitions as records on the type and collection objects that own them, scopes on declarations. - **Dataset handlers** — the SDK's own (spaceIndex, bundles, files, …), modules the host registers (any's chat and editor), and runtime-declared schemas — run identically on every peer at apply time. - **The tech space** — the account's private space holding the space list, devices, profile and account-scoped values ([Tech space](https://docs.any.org/understanding/tech-space.md.txt)). - **Versioning** — the version-driven re-index that rebuilds rows from the DAG when handler logic changes ([Versioning and re-index](https://docs.any.org/understanding/versioning-and-reindex.md.txt)). Where encryption happens: here. The SDK's auth module derives account keys from the mnemonic; changes are signed and encrypted inside the SDK before any-sync ever sees them, and decrypted after any-sync hands them back. ## any — the local server any wraps the SDK in a single binary: `any run` opens the SDK and serves HTTP/JSON on `127.0.0.1:7001`; every other `any ` is an HTTP client for that server. Endpoints map 1:1 onto SDK methods, and the server adds only what the SDK deliberately leaves to consumers: the search and link index over the change feed, the ephemeral event bus, the markdown bridge, the bundles engine and usecase catalog, the device-local store, process reporting. The rules it holds itself to are on [The zen of any](https://docs.any.org/understanding/zen-of-any.md.txt). ```bash curl http://127.0.0.1:7001/v1/health # { "status": "ok", "version": "any v0.1.2 (commit 1a2b3c4, built 2026-09-09)", "account": "A8tR…", "bootstrapping": false, … } ``` The loopback address is the trust boundary: no TLS, no per-client authentication, and a refusal to bind anything else. A server a host app spawns in managed mode additionally gates logout, account switch and shutdown behind a control token ([Security model](https://docs.any.org/operations/security-model.md.txt)). ## Clients and anyrt Everything above the server is a client of it — the web UI, the CLI, the language bindings, and **anyrt**, the sandboxed runtime that executes Python programs and agents. anyrt talks to the same HTTP API as any other client, so a program or an agent reads and writes your data on the machine; anything it sends out — a model call, a connector request — goes through its logged effects ([Programs and effects](https://docs.any.org/understanding/programs-and-effects.md.txt)). > **Why it matters.** In a hosted backend the database, the auth, the business logic and the sync all live on a server you rent. Here the sync network is a relay for ciphertext, and the database, the auth and the logic run on your device. Content reaches an outside party only through an outside provider — the online embedder of the default `index.embedder: auto`, an agent's model — and only what that provider is sent. That is why the API can promise offline reads and writes, why membership is enforced by signatures instead of sessions, and why the design choices on the following pages look the way they do. ## Further reading - [Spaces and trees](https://docs.any.org/understanding/spaces-and-trees.md.txt) — the any-sync data model and lifecycle. - [Record CRDT](https://docs.any.org/understanding/record-crdt.md.txt) — what the SDK does with a change. - [Tech space](https://docs.any.org/understanding/tech-space.md.txt) — the account's private space. - [Versioning and re-index](https://docs.any.org/understanding/versioning-and-reindex.md.txt) — how rows survive code changes without migrations. --- Source: https://docs.any.org/understanding/spaces-and-trees.html # Spaces and trees A space is the unit of membership and sync: one access control list and every object shared under it. An object is an any-sync **tree** — a content-addressed DAG of changes, each signed by its author and encrypted with the space's read key. Every guarantee the API makes about sharing, offline work and convergence comes from these two structures. ## Anatomy of a space ``` space (id = CID of the signed header + "." + replication key) ├── header identity, timestamp, spaceType, replicationKey, seed — cleartext ├── ACL list chain of signed records: root → invite → join → accept → … ├── settings tree object deletions — an object tree └── object trees one per object: chat, page, type, spaceIndex, … └── change → change → change (DAG; tips are the heads) ``` - The **header** is signed at creation and hashed into the space id. It carries the `spaceType` (`any.space`, `any.techspace`, `any.onetoone`) and the `replicationKey` that decides which sync nodes are responsible for the space. The coordinator rejects headers with unknown types, and because the header is content-addressed it can never change. - The **ACL** is an append-only chain of records — `AclRoot`, `AclAccountInvite`, `AclAccountRequestJoin` / `AclAccountInviteJoin`, `AclAccountRequestAccept` / `Decline` / `Cancel`, `AclAccountsAdd`, `AclAccountPermissionChanges`, `AclAccountRemove`, `AclReadKeyChange`, `AclOwnershipChange`. It names member public keys and their permission (`none`, `reader`, `guest`, `writer`, `admin`, `owner`) and carries the read keys, encrypted to each member ([ACL](https://docs.any.org/collaboration/acl.md.txt)). - The **settings tree** is an ordinary object tree with a fixed job: it records object deletions, so a delete propagates like any other change. - **Object trees** hold the data. Every object you create (`POST /v1/spaces/:id/objects`) is one tree. ## An object is a DAG of changes Each change in a tree has this shape: ``` Change { id CID of the serialized change ← the changeId every write returns previousIds the heads this change was built on ← DAG edges aclHeadId the ACL record in force when it was written readKeyId which read key encrypts data identity author's public key signature over the change, by the author's account key data encrypted payload (the record CRDT batch) isSnapshot marks a snapshot node timestamp author's clock } ``` The root change is a snapshot. Every later change points at the heads it saw; a change written while another device also wrote creates a fork, and the next change that sees both heads references both, merging the branches. Reading the tree from any head and following `previousIds` yields the full history; where several orders are possible, a topological sort on the change hashes fixes one, the same on every peer. Changes can arrive out of order. A tree keeps unattached changes on a wait list until their parents arrive, then attaches them — so a receiver never applies a change before its causal ancestors, which is what makes "modify before create" impossible at the protocol level ([CRDTs and consistency](https://docs.any.org/understanding/crdt-and-consistency.md.txt)). ## The life of a change 1. **Author.** A write (`/modify`, a chat send, a block patch) is validated locally and encoded as one CRDT batch — one dataset, one or more records, per-path ops. 2. **Sign and encrypt.** The SDK encrypts the batch with the current read key, wraps it in a change referencing the current heads and ACL head, and signs it with the account key. The CID of the result is the `changeId`. 3. **Append and apply.** The change is appended to the local tree and applied to any-store rows in one transaction; the reply returns `{versionId, changeId, recordIds}`. Subscriptions fire after the commit. 4. **Deliver.** The change is streamed at once as a head update to connected sync nodes and LAN peers; head-sync rounds catch up anyone who missed it. Receivers verify the signature against the ACL, attach the change, decrypt it with their copy of the read key, and apply the same batch through the same handlers ([Record CRDT](https://docs.any.org/understanding/record-crdt.md.txt)). Steps 1–3 are local and synchronous. Step 4 happens whenever a peer is reachable. ## Heads and head-sync The **heads** of a tree are the changes nothing points to yet. Two peers whose head sets match for every tree hold the same data — so peers compare heads, not content. A **head-sync round** is a diff exchange: a device and a responsible node compare hashed ranges of `(treeId, heads)`, find trees that are new, changed or missing on either side, and fetch the missing changes for those trees. It runs on a periodic timer (`syncPeriod`, ~30 s) and on demand — local writes travel as streamed head updates, not diff rounds: ```bash curl -X POST http://127.0.0.1:7001/v1/spaces/$SPACE/sync # one round, 204 on completion any space sync $SPACE ``` A device that lacks a space **pulls** it — header, ACL and settings root first — then fetches the object trees through head-sync; when a node lacks a space, the device sends it a **space push** and a follow-up diff uploads the trees. Per-space and per-object progress is what [`/sync-status`](https://docs.any.org/realtime/sync-status.md.txt) reports. > **Note.** Head-sync skips trees that still sit on their root change alone. That is why every freshly minted bundle root gets an `any.name` change right away — a tree with no second change is not part of anyone's diff. ## Coordinator versus sync nodes | | Coordinator | Sync nodes | | --- | --- | --- | | Holds | network configuration, the registry of spaces and their status, invite files, the deletion log | the spaces' ACLs and object trees — ciphertext only | | Talks to a device for | "which nodes serve space X", space registration, deletion, space-status checks, the 1-1 inbox | head-sync rounds and change streaming | | Enforces | valid space headers and `spaceType`, owner-only deletion | valid signatures and ACL membership on every change; ACL changes are confirmed by a consensus node first | | Can read | that a space exists, its type, who owns it | who the members are, DAG shape, timing, sizes — never a field value beyond the cleartext custody fields of file rows | The consensus nodes sit behind the sync nodes: an ACL is a linked list, and a sync node asks a consensus node to confirm each new record extends the list without conflict before accepting it. ACL changes therefore need the network; everything else does not. ## Derived ids Some trees and spaces have ids that are computed rather than minted. A **derived object** starts from a root change that carries only `(spaceId, changeType, payload, parentId)` — no identity, signature or timestamp — so its CID, and thus the object id, is a pure function of its inputs: each space's `spaceIndex` object and bundle roots installed with `"derived": true` work this way. A **derived space** — the tech space, one-to-one spaces, the well-known per-account spaces — starts from a deterministic header: still signed, but with no timestamp or random seed. Either way every device evaluates the same function and lands on the same id with zero communication ([Derived objects](https://docs.any.org/database/derived-objects.md.txt)). The price is permanence. A derived tree cannot be deleted — deleting and re-deriving would yield the same id with a fresh history — and any-sync refuses a derived object as a parent, so children of a derived root are bound by seed, not by `parentId`. ## Space lifecycle - **Create** — `POST /v1/spaces`: sign a header, build the ACL root with the creator as owner and the first read key, create the settings tree, write the space's row into the tech space. The coordinator learns about the space when the first head-sync registers it. - **Join** — an owner or admin mints a request-to-join invite (`POST …/invites`); the joiner submits the token (`POST /v1/spaces/join`), and every device of the joiner's account lists the space as `joining` until an owner or admin accepts (`…/acl/accept`) or declines, or any of those devices withdraws (`…/acl/cancel-join`). A direct add by identity (`…/acl/add`) and a guest key skip the request. The joiner's read keys arrive through the ACL, and only then does its device pull the space's trees ([Invites](https://docs.any.org/collaboration/invites.md.txt)). - **Delete** — `DELETE /v1/spaces/:id` is offline-first: the tech-space row is tombstoned (`remoteStatus=deleted`, so the account's other devices follow), all local state is **offloaded** immediately — watchers closed, CRDT collections and the per-space DB file dropped, disk reclaimed — and, for a space the account owns, a background reconciler sends the signed `SpaceDelete` to the coordinator when it can (a joined space is only offloaded). The coordinator schedules the space for removal after a deletion period and the responsible nodes clear it; the reconciler also detects spaces the coordinator reports gone (deleted on another device, or by the owner of a space you joined) and offloads them. The row stays in the tech space as a sticky `status: "deleted"` tombstone ([Spaces](https://docs.any.org/database/spaces.md.txt)). - **Derived spaces** never delete; a one-to-one space is offloaded on every device of the account but never removed from the network, and is re-derivable. > **Why it matters.** Because a space is an ACL plus signed trees, membership is a property of the data, not of a session. A node cannot forge a change (no key), cannot admit a member (no consensus-validated ACL record), and cannot read a change (no read key). A device can leave the network for a month and rejoin with nothing but heads to compare. Those are not features layered on top of the sync — they are what the sync is. ## Further reading - [Encryption](https://docs.any.org/understanding/encryption.md.txt) — the key hierarchy behind `readKeyId` and the ACL. - [Local-first](https://docs.any.org/understanding/local-first.md.txt) — head-sync from the client's side. - [Collaboration](https://docs.any.org/collaboration/index.md.txt) — the endpoint surface for members, invites and ACL operations. --- Source: https://docs.any.org/understanding/record-crdt.html # The record CRDT any-sync delivers signed, encrypted changes; any-store holds documents. The record CRDT is the layer between them: it defines a change as a batch of per-record operations on a named dataset and applies it to rows through a per-path version gate, so that every peer holding the same changes — in any order — ends with identical rows. ## Datasets, records, ops ``` object (one any-sync tree) └── dataset "chat_messages" named storage collection; one handler └── record { id, …fields, _ver } anyenc document └── op $set / $unset / $addToSet / $pull / $inc / $incGated / delete ``` One change belongs to exactly one dataset and may touch many records. Each record change carries an `id`, an `upsert` flag and an ordered list of ops. Ops address dotted paths; `$set` and `$unset` also have a multi-field form whose payload is an object of `path: value` entries, each applied as its own gated write. There is no `insert`. A record is created by an `upsert: true` change whose ops populate it; a strict (default) modify on an absent id is a no-op, so a typo cannot conjure a record. Reserved names — a top-level `id` or `_`-prefixed field — are rejected at validation, before apply ([Writing data](https://docs.any.org/database/writing-data.md.txt)). ## Versions and `_ver` Every peer's any-sync assigns each change it holds a **versionId**: an opaque string that sorts lexicographically in DAG order for that peer's view of that tree. It is peer-local — two peers may spell the same change differently — but the relative order of any two changes converges once both peers hold both. Each record carries `_ver`, a map from field path to the versionId of the last write that landed there: ```json { "id": "m1", "text": "hello", "edited": true, "_ver": { "id": "!A0", "text": "!C4", "edited": "!C4" } } ``` The apply rule is one comparison per path: ``` if incoming.versionId > record._ver[path]: write the value, _ver[path] = incoming.versionId else: skip this path ``` `_ver` is a tree. A write to `a.b` stamps exactly that path; a whole-object `$set` of `a` collapses the subtree to one string, and a `*` entry holds the default for keys a broad write claimed without enumerating. A broad write over finer entries merges per leaf — newer leaves survive, older ones are replaced — so "replace the whole object" and "edit one key" race to the same result in every delivery order. `_ver.id` is special: it is the **creation marker**, the versionId of the earliest upsert that targeted the id, updated only downward (`min`). That is what makes `sort: ["-_ver.id"]` a stable creation order on every peer ([System fields](https://docs.any.org/database/system-fields.md.txt)). ## Content-addressed record ids A record change with an empty `id` gets one derived from the enclosing change: ``` DeriveRecordId(changeId) = base58(xxh3-64(changeId)) ≈ 11 chars ``` The first empty-id record in a batch takes that value; later ones append `:1`, `:2`, …. Because `changeId` is a CID, the id is globally unique with no coordination, and it is the same on every peer. It is why `recordIds[0]` in a write reply is the id of the message or block you just created, and why property ids (`propId`) look the way they do. ## Handlers Every dataset has a **handler** — a compiled-in one (the `chat` and `editor` module handlers, the `objects` row, spaceIndex, …) or the generic schema handler compiled from a declaration: a [runtime dataset](https://docs.any.org/database/runtime-datasets.md.txt), or a built-in one with no code of its own such as the `dataview` type's views. Hooks run inside the apply transaction on every peer, identically, for every synced change: | Hook | Runs | Typical rule | | --- | --- | --- | | `BeforeCreate` | before a record's first materialization | required fields, id rules, stamp `creator` / `createdAt` from the change envelope | | `BeforeModify` | per op on an existing record | field pinned, author-only edit (`ctx.Before.creator == ctx.Change.Creator`), value shape, bump `modifiedAt` | | `BeforeDelete` | per record delete | author-only delete | A handler writes through a **sink**: `Derive` queues a same-record op that lands with the change's own versionId (this is how server-stamped fields exist without a server), `Project` queues a sibling write to another dataset on the same object. Hooks may read only what converges — the change envelope, the record's pre-op state, and the create-time fields of records in the change's causal past — never replica-local data, so their verdicts are the same everywhere. Rejections are **op-granular and never fatal on the apply path**: an op that fails validation is dropped and recorded (a failed `BeforeCreate` or `BeforeDelete` drops that record's change), the rest of the change still commits, and the writer's own pre-check is the only place a whole change is refused. Which fields a peer may write is also declared, as a **scope** on the field or property: `synced` rides the DAG, `derived` is handler-only, `local` never leaves the device, `account` travels through the [tech space](https://docs.any.org/understanding/tech-space.md.txt). An inbound DAG op addressing a local or account path is dropped per-op on every peer. ## Merge rules by op | Op | Gated by `_ver`? | Updates `_ver`? | Behaviour under concurrency | | --- | --- | --- | --- | | `$set`, `$unset` | yes | yes | last writer in DAG order wins, per path | | `$addToSet`, `$pull` | yes (against a newer `$set`) | no | commutative — concurrent adds all land | | `$inc` | yes (against a newer `$set`) | no | commutative counter | | `$incGated` | yes | yes | LWW on the post-increment value; not convergent under arbitrary order | | `delete` | — | collapses to `{id, "*"}` | wins absolutely; the tombstone is sticky | Two concurrent creates of the same id merge per field. A delete on an absent id writes a tombstone so it still wins against a create it has not seen. Every later modify on a tombstone is dropped — and reported to the local writer as a rejection, never silently. ## Worked example: two concurrent edits Devices A and B both hold message `m1` with `_ver.text = "!B2"`, then go offline. ``` A: $set text = "meet at 10" → change cA, parents [c0] B: $set pinned = true → change cB, parents [c0] ``` Say DAG order puts `cA` before `cB`. A applies its own change (`!C3`), then receives `cB`, which sorts after it (`!C4`). B applies its own `cB` (`!C3`), then receives `cA` — which sorts *before* `cB`, so B gives it an id below the one it already holds (`!C2z`). Each write touches a different path, so both gates pass on both devices: ``` A: text ← "meet at 10" (!C3) then pinned ← true (!C4) B: pinned ← true (!C3) then text ← "meet at 10" (!C2z) both: { "text": "meet at 10", "pinned": true } ✓ identical rows ``` The `_ver` strings differ between A and B (they are peer-local); the order they encode and the rows do not. Now suppose B had instead written `$set text = "meet at 11"`. Both changes hit the same path; the DAG order — the same on every peer once both changes are present — picks one, and the other is gone everywhere with no error to either author. Design records so that the fields people edit at the same time are *different* fields ([CRDTs and consistency](https://docs.any.org/understanding/crdt-and-consistency.md.txt)). ## Tombstones and counters A deleted record stays as a tombstone `{ id, _deletedAt, _ver: { id, "*" } }` so late writes have something to lose against. Queries and subscriptions skip tombstones; indexers read them through the store's find path (`IncludeDeleted`) to evict documents. Three peer-local counters ride the apply path, each answering one question: | Counter | Where | Answers | | --- | --- | --- | | `versionId` | `_ver` on each record | which write landed last on this path | | `addSeq` | `_addSeq` on each record; per-object watermark | is any-store caught up with any-sync (the restore watermark) | | `applySeq` | `_applySeq`; the `Changes()` feed | is a consumer (the [search indexer](https://docs.any.org/search/indexing.md.txt)) caught up with any-store — it also counts local and account writes, which never enter the DAG | All three are local to a peer. None is a timestamp, and none should be compared across devices. ## The DataVersion gate Every change carries a **DataVersion**: a compiled-in handler stamps an opaque label (`chat_messages-v5`), a runtime dataset stamps the schema state it was written against (`typeId:shortId`). A receiving peer **parks** a change when it has no handler for the change's dataset, or when the change names schema state it has not applied yet — the change is persisted in the tree, kept in a `_detached` storage collection, invisible to queries — and drains it when the registration appears. An opaque label is carried but not compared. For runtime datasets that means "schema first, then data" holds in either arrival order: a record written against a field definition you have not yet received waits for the definition instead of being applied wrongly or dropped. ## Why there is no rollback and no total order - **No total order.** Concurrent branches have no "before" and "after" until they meet; DAG order gives every peer the same tie-break, not a wall clock. Version history is therefore a walk over a DAG with a cursor, and `timestamp` is display-only ([Version history](https://docs.any.org/database/version-history.md.txt)). - **No rollback.** A change that entered the tree is signed and content-addressed; other peers may already have built on it. Correction is another change. Validation drops ops on apply rather than refusing the change, precisely so a tree can always be replayed to the same state. - **No conflict surface.** Every merge is decided by rule. What a local writer gets back is validation — a handler rejection or a tombstone rejection in `rejections` — never a conflict: a tombstone rejection is just a fact about a record that no longer exists. > **Why it matters.** The CRDT is deliberately narrow: per-path LWW plus a few commutative ops. That is enough to make "apply this set of changes in any order" a pure function — which is what lets a device be offline for a week, a handler be re-run over history to rebuild rows ([Versioning and re-index](https://docs.any.org/understanding/versioning-and-reindex.md.txt)), and a second device restore an account from the DAG alone. --- Source: https://docs.any.org/understanding/tech-space.html # The tech space Every account has exactly one **tech space**: a space derived from the account keys, with an owner-only ACL, that syncs only between that account's own devices. It is where any keeps everything that is *about the account* rather than about a shared space — starting with the list of spaces itself. ## What it is - **Derived.** Its id is a pure function of the account key; every device of the account computes the same id and re-creates it on first login. Its header carries `spaceType: any.techspace`. - **Owner-only.** The ACL has one member and the network refuses any further ACL record. Nothing in it can be shared; there is no such thing as a shared account. - **Unlisted.** It never appears in `GET /v1/spaces`, and its datasets are read through dedicated endpoints. Its id (`techSpaceId` on `GET /v1/account`) is a `:spaceId` only on a closed set of per-space routes — account-level bundles and the records and types on their roots; every other per-space route answers `405 space.unsupported`. It uses the same [record CRDT](https://docs.any.org/understanding/record-crdt.md.txt) as every other space, so writes to it sync, merge and converge like any other data. - **First.** It loads before regular spaces at boot, because the space list comes from it. ## What it holds The tech space carries one derived **index object** whose datasets are the account's system data: | Dataset | One row per | Read through | Written by | | --- | --- | --- | --- | | `spaces` | space the account participates in | `GET /v1/spaces`, `POST /v1/spaces/query[/subscribe]` | the SDK on create / join / delete, and the mirrors below | | `profile` | the account | `GET /v1/account`, `POST /v1/spaces/query` with `"dataset": "profile"` | `PUT /v1/account/metadata` | | `devices` | device (row id = peer id) | `GET /v1/devices`, `POST /v1/devices/query[/subscribe]` | `PUT /v1/devices/me`, `POST /v1/devices/activate`, engine boot | | `identities` | account identity ever encountered | `GET /v1/identities[/…]` | the SDK, from ACL records, one-to-one invites and the identity repository | | `inboxCursor` | the account | — | the coordinator-inbox receiver (one-to-one and direct-add invites) | | `crdtVersion` | the account | `GET /v1/health` (`crdtVersion`) | every release, on open ([Versioning](https://docs.any.org/understanding/versioning-and-reindex.md.txt)) | | `bundles` | account-level bundle, such as favourites | `GET /v1/spaces//bundles` | `POST /v1/spaces//bundles` ([Bundles](https://docs.any.org/collaboration/bundles.md.txt)) | A `spaces` row is the account's view of a space: ```json { "id": "bafy…", "type": "any.space", "name": "Team", "icon": "…", "remoteStatus": "active", "createdAt": { "$date": "2026-08-01T09:00:00.000Z" }, "ownRole": "writer", "push": { "spaceKey": "…", "encKey": "…", "encKeyId": "…" }, "settings": { "notifyMode": "mentions" }, "derived": false } ``` Fields mix scopes on purpose: `type`, `name`, `description`, `icon`, `remoteStatus`, `settings`, `derived` are **synced** across the account's devices, so a join pending (`joining`), a decline or a delete observed on one device converges the rest; `createdAt` is **derived** — stamped from the change that added the row (create for the author, join for a joiner), the same on every device; `ownRole` and `push` are **local** — each device derives them from the same converged inputs, so replicating them would only add lag — and so is `localStatus` (absent while the space is simply active), because a space offloaded on one device must stay loaded on another. Raw rows withhold private guest and invite keys. ## The space list is a view `GET /v1/spaces` maps `spaces` rows into `SpaceInfo`, filtering to active rows by default; `GET /v1/spaces?status=one_to_one_pending` or `status=deleted` selects the others. `POST /v1/spaces/query` and `POST /v1/spaces/query/subscribe` expose the raw rows through the same windowed primitive every dataset uses: ```bash curl -N -X POST http://127.0.0.1:7001/v1/spaces/query/subscribe \ -H 'content-type: application/json' \ -d '{"sort":["-createdAt"],"limit":50}' # event: ready → snapshot{records} → changes[{added,updated,removed}] … ``` Because the list is a dataset, everything that changes a row arrives as a row update on that stream: a join completing on another device, a rename, a role change, a push-key rotation, a settings edit ([Live space list](https://docs.any.org/realtime/space-list.md.txt)). The `dataset` field of these two endpoints accepts only `spaces` and `profile` — the `identities` rows carry each contact's profile-decryption key, and are read through `GET /v1/identities` where that key is stripped. ## Mirrors: how rows stay current Several row fields are **derived from other places** and mirrored in by SDK watchers on each device: | Field | Source of truth | Mirror | | --- | --- | --- | | `name`, `description`, `icon` | the target space's own `spaceIndex` object — encrypted in-space CRDT data, so every member sees a rename | each device's indexer hook writes the converged value onto the account's row after `PATCH /v1/spaces/:id` or a peer's edit, skipped when already equal | | `ownRole` | the space's ACL | the ACL mirror watcher, once at space load and once per applied ACL record | | `push.{spaceKey,encKey,encKeyId}` | ACL key material | the same watcher; `encKey` rotates with the read key | | `type` | the space header | backfilled once, set-once, on the first successful load of a row registered before the header was readable | A mirror is asynchronous, which shows up in one place: an immediate re-read after `PATCH /v1/spaces/:id` can briefly return the old name. Subscribe to the space list or to the `spaceIndex` object if you need the moment it lands. ## Account-scoped values A property declared `scope: account` is **shared across the account's devices but invisible to other members** — a personal flag on a shared object, or a chat's `notifyMode`. The tech space is its transport: for every target space the account is in, it holds one derived **carrier object** (`account_values` dataset, one record per `(objectId, dataset, recordId)`), and a per-device mirror replays converged carrier values into the target rows at their normal paths, stamped with the tech tree's versions. The write path is the ordinary one — `POST …/types/:t/properties` with `"scope": "account"`, then a value write — and reads see the value at its usual path. Deleting the object tombstones its carrier records; leaving or deleting the space drops the carrier ([System fields](https://docs.any.org/database/system-fields.md.txt)). Values of `scope: local` take the shorter route: written straight into the device's row, no DAG, no tech space. Dataset record fields can declare `account` but are not writable at that scope. ## Devices and the account's own state The `devices` dataset is what gives the account a notion of "my devices": one row per peer id with name, OS, version, installed apps and active-app claims, all synced through the tech space and nowhere else. The self row is upserted at engine boot; election of the active device for an app slug is computed by readers from the converged claim data, never from version ids ([Devices](https://docs.any.org/auth/devices.md.txt)). Per-space `settings` (the `notifyMode` for push, for example) live on the `spaces` row for the same reason — they are the account's preference about a space, not the space's data — and so sync to the account's other devices without ever reaching other members ([Push](https://docs.any.org/notifications/push.md.txt)). ## Why account-only Everything here is *about you*: which spaces you are in, what you call your devices, how you want to be notified, what you flagged for yourself. Keeping that in a space only your keys can open gives three properties at once: - **Multi-device for free.** A second device restored from the mnemonic derives the same tech space, pulls it first, and immediately knows every space to join, every device sibling, and every account-scoped value — before any shared space has loaded. - **Privacy by construction.** Other members never see your space list, your device names, your read markers or your settings, because those rows never enter a shared tree. - **One CRDT.** Account state converges by the same rules as everything else; there is no separate "preferences sync" with its own conflict story. > **Why it matters.** A hosted backend stores your account profile, device list and per-user preferences in tables only the server can join. any stores them in a space only you can decrypt, replicated by the same protocol as your documents — so "which devices are mine" is a query, and answering it needs no server at all. ## Further reading - [Accounts](https://docs.any.org/auth/accounts.md.txt) — mnemonic, account id, restoring a device. - [Spaces](https://docs.any.org/database/spaces.md.txt) — the `SpaceInfo` shape and status vocabulary. - [Identities](https://docs.any.org/auth/identities.md.txt) — the encrypted profile directory. --- Source: https://docs.any.org/understanding/versioning-and-reindex.html # Versioning and re-index Rows in any-store are not the source of truth — the object trees are. Every row is the result of replaying a tree through the current dataset handlers, so when handler logic changes, the fix is not a migration script: the SDK wipes the rows and replays the tree. This page explains the versions that trigger that, what happens during a rebuild, and how the search index keeps up. ## Three kinds of version | Version | Lives | Gates | Bump when | | --- | --- | --- | --- | | **CRDT version** | one account-wide mark on the tech space, stamped by every release on open and never lowered | **releases** — a server whose supported version is below the stored mark refuses to open the account (`409 sdk.crdt_version_newer`), and turns read-only if the raise arrives from another device while it runs | a release writes data the previous release cannot read | | **DataVersion** | on every change (an opaque label such as `chat_messages-v5` for a compiled-in handler; the `typeId:shortId` schema state for a runtime dataset) | **peers** — a receiver parks a change for a dataset it has no handler for, or for schema state it has not applied yet | never by hand — a compiled-in label is carried but not compared; a runtime dataset's stamp follows its declaration | | **HandlerVersion** | on the local registration only; persisted per object as `dataset → version` on the object's `_meta` row | **this device's rows** — a stored version that differs from the registered one marks the dataset stale | the *rows on disk* are wrong under the new logic: a derived field with a new shape, a stamp computed differently, a date stored as an instant instead of a number | The distinction matters. The CRDT version mark is what keeps an older release from misreading newer data — it fences the whole account, visibly: `GET /v1/health` reports `crdtVersion.newer` as the client's "upgrade required" signal. Bumping HandlerVersion never leaves the device — it only says "my rows need rebuilding". A runtime-declared schema also has a **SchemaRev**, which evicts and reloads a resident handler when the declaration changes; because runtime schemas evolve additively, that never requires recomputing stored rows. ## The version-driven re-index When an object's controller is built, it reads the stored `dataset → version` map and diffs it against the registered handlers. Any dataset whose versions differ is the object's re-index verdict, and its next load rebuilds it: ``` load object 1. capture local-scope values (they never entered the DAG; nothing could replay them) 2. rewind the addSeq watermark to 0 and persist it together with the captured leaves 3. wipe the object's rows its row in shared storage collections, its per-object ones, its history rows 4. replay the whole tree every change, through the CURRENT handlers 5. restore the local values, stamp the current versions, clear the in-flight mark ``` The compare is per `(object, dataset)`; the wipe and replay are per object, because one tree carries every dataset of that object and a partial replay would double-apply the rest. Properties of the mechanism: - **Lazy, per object.** The rebuild rides object load — the cold-restore path that opens the tree anyway — so startup stays flat and objects nobody opens cost nothing until they are opened. - **Converged by a background sweep.** Lazy alone would leave the `objects` storage collection mixing rows built by the old handler with rows built by the new one for as long as some object stayed unopened, and a sort or filter over a rebuilt field would read both shapes. When a space store starts, a paced sweep scans `_meta` for stale objects and loads them. Nothing waits on it; a store with nothing stale pays one scan. - **Crash-safe by construction.** The rewound watermark is durable before the wipe and the stored versions stay stale until the replay stamps them, so an interruption anywhere simply rebuilds again on the next load — or, once versions are stamped, resumes from the persisted watermark. - **Not a deletion.** The wipe emits no `removed` events and writes no delete marker, since a delete stamp is sticky and would evict the object from every consumer index for good. - **Read state and history follow.** Read-tracking classification is suppressed during the replay (otherwise every replayed change would mark the object unread), and the per-object history index is wiped with the rows and lazily rebuilt. Type objects rebuild too. While a type's `shortIds` / `properties` / `datasets` datasets are empty mid-replay, an inbound change for that type fails the DataVersion lookup and is parked, then drained once the definitions are back — only a local write in that window sees a transient `type_unknown` rejection. ## What clients see during the window A subscription is not told about the wipe — the rebuild never touches the subscribe engine. A held window keeps its rows and then sees the replay as one `updated` delta per change in the tree, with intermediate partial documents, converging when the replay ends. Snapshot reads against a space mid-sweep can return both shapes of a rebuilt field at once; a sort over that field groups by type until the sweep finishes. Two rules keep a client correct across this: - **Render from the window, not from a second store.** Applying `added` / `updated` / `removed` to the held rows lands on the converged state automatically ([Subscriptions](https://docs.any.org/realtime/subscribe.md.txt)). - **Do not fence on shape.** A field that is `{"$date": …}` on one row and still in its old shape on another during the window is not a schema error; it is a rebuild in flight. ## Why no migrations Every alternative to "wipe and replay" needs migration code per version pair — code that must produce exactly the rows a fresh replay would, on every platform, for every data shape ever written. The DAG already *is* the migration input: it holds every change verbatim, signed, in causal order, and the CRDT's apply is a pure function of it. Replaying is cheaper to write and impossible to get subtly different from a fresh install. The same reasoning governs the wire. Stored values never move: a property's `kind` and `scope` are pinned at creation, and a change of meaning is a new property with a new content-addressed id. Runtime schemas grow additively — an added field can never be `required`, because fresh devices replay the dataset's own history against the current schema. A stamp is always computed from the change envelope, never from replica state, so a re-run stamps the same value. > **Note.** The trade is explicit and pre-release: when a handler's stored shape changes, existing rows are rebuilt on every device from history rather than converted in place, and code built against the old shape reads the new one after the sweep. An object that has never applied a change on this device has no stored versions and is never rebuilt. ## Generation and the search index Consumers that keep their own derived state — the [search index](https://docs.any.org/search/indexing.md.txt) above all — follow the change feed `Space.Changes()`, keyed by the per-space `applySeq`. A rebuild keeps that axis climbing: re-applied rows surface as changed again with fresh sequence numbers, so an indexer simply re-chunks them incrementally. Only a rebuilt SDK store — a wiped `sdk.db` — restarts the axis at zero, and that mints a new per-space **Generation**. An older backup restored keeps its Generation but falls behind the indexer's cursor. The indexer persists the Generation next to its cursor and, on every worker start, compares: ``` stored generation ≠ current generation → drop the space's index docs, cursor = 0, reindex stored cursor > MaxApplySeq → same (an older store restored under a newer cursor) otherwise → resume from the stored cursor ``` Without that check a cursor could name a position the feed will never report again: `ChangedSince` would return nothing, forever, with no error, and the index would silently freeze. The [search index is derived state](https://docs.any.org/operations/data-dir.md.txt) either way — deleting `/index/` with the server stopped is safe: the next start finds no cursor and re-indexes every space from the change feed. > **Why it matters.** A hosted backend migrates a table once, on the server, under a maintenance window. any has as many copies of every row as the account has devices, no server to run a script on, and no window in which nobody writes. The only migration that can be correct on every copy is the one the data model already performs on every apply — so that is the only one any performs. ## Further reading - [The record CRDT](https://docs.any.org/understanding/record-crdt.md.txt) — handlers, the DataVersion gate and parking. - [Runtime datasets](https://docs.any.org/database/runtime-datasets.md.txt) — additive-only schema evolution. - [Data dir](https://docs.any.org/operations/data-dir.md.txt) — what is source of truth on disk and what is derived. --- Source: https://docs.any.org/understanding/encryption.html # Encryption Space content is encrypted on the device before it syncs, under keys only space members hold: any-sync nodes store and relay changes but cannot read them, and see only the metadata listed below. Requests to outside providers — the online embedder that `index.embedder: auto` uses once `index.openai.apiKey` is set, an agent's model or connectors — carry readable content to that provider; without a key, and with `index.embedder: local`, search indexing stays on the device ([Embedders](https://docs.any.org/search/embedders.md.txt)). ## The key hierarchy | Key | Where it comes from | What it does | | --- | --- | --- | | **Account key** (Ed25519) | Derived from the BIP-39 mnemonic (SLIP-10 / SLIP-21). The mnemonic is shown once at `any init` / `POST /v1/auth`. | Your identity. Signs every change you write and every ACL record. | | **Device key** | Generated per device: fresh on every `any init --mnemonic` restore, and minted once per account as `device.key` on a managed server. | Identifies this peer on the network. Never copy `wallet.key` between machines — two devices with one device key fight over one network identity. | | **Space read key** (symmetric) | Created with the space; delivered to each member through the ACL, encrypted to their account key. Rotates when a member is removed. | Encrypts the payload of every change in the space. | | **Profile key** (symmetric) | Account-derived. Shared with a contact only through a shared space's ACL metadata or a 1-1 invite. | Encrypts your name / description / icon in the identity repository. | | **Push keys** | Derived from ACL state — the space push key from the ACL's first metadata key, the payload key from the current read key. Never synced; each device mirrors them onto its own space-list row as `SpaceInfo.push`. | Sign push topics; encrypt push payloads. | The mnemonic is the root of all of it. Restoring an account on a second device with the same phrase yields the same account key and, through the ACLs, the same read keys. ## What a change looks like on the wire ``` TreeChange { treeHeadIds: [ …heads this change was built on… ] ← cleartext (DAG structure) aclHeadId: … ← cleartext (which ACL state applies) readKeyId: … ← cleartext (which read key decrypts it) timestamp: … ← cleartext (author's clock) identity: ← cleartext changesData: encrypt(readKey, CRDT ops) ← CIPHERTEXT } signature: sign(accountKey, change) ← cleartext, on the raw change ``` Nodes verify the signature and the DAG links; they never hold a read key, so `data` is opaque to them. ## What nodes see, and what they don't | Nodes can see | Nodes cannot see | | --- | --- | | That a space exists, its id, its header `spaceType` | Its name, description, icon (these live in an encrypted in-space object) | | The ACL: which account public keys are members, with what permission | Members' names or profiles (encrypted in the identity repo) | | Object ids, change ids, DAG shape, change sizes and timing | Any field value, any record, any property | | Encrypted file DAGs and their sizes | File names, mime types, contents (sealed under the read key) | | Push topics (hashed chat ids) and ciphertext payloads | Message text, sender name | Space name and description are not exempt: they are stored in a derived in-space object (`spaceIndexObjectId`) as ordinary encrypted CRDT data, and each device mirrors them into its own local space list. ## Consequences you will notice in the API **Profiles resolve late.** A contact's `name` in `GET /v1/identities` or a members list is empty until their profile key arrives through a shared ACL or a 1-1 invite. Render a fallback and let the `updated` subscribe frame fill it in ([Identities](https://docs.any.org/auth/identities.md.txt)). **Pending spaces are not downloaded.** `GET /v1/spaces/:id` on a pending join or incoming 1-1 serves the tech-space row only; the server refuses to pull a space's ciphertext ahead of acceptance. **Removing a member rotates the key.** any-sync switches the space to a new read key when a member is removed; changes written afterwards are unreadable to the removed identity. Old changes they already received stay readable to them — encryption is forward-looking. **Files are space data.** Inline files (< 4096 B) ride the CRDT; larger files become an encrypted UnixFS DAG. The cleartext part of a file row is `rootCid`, `size`, `objectId`, and the broker's custody receipt; name, mime, and key are one sealed member-only blob ([Files](https://docs.any.org/files/index.md.txt)). **Push is sender-encrypted.** The sending device encrypts the notification payload; the push server fans out opaque ciphertext; the receiving phone decrypts with keys it cached from `SpaceInfo.push` while `any` was running ([Push](https://docs.any.org/notifications/push.md.txt)). > **Why it matters.** Hosted backends encrypt in transit and at rest, and hold the keys. Here the keys are derived from a phrase only you hold and distributed only through the ACL, so the operators of the sync nodes are in the same position as an attacker who copied their disks: they have ciphertext, DAG shape, and membership — nothing else. ## The local boundary Encryption protects data *between* devices. On the device itself the server is plaintext behind `127.0.0.1` — the trust boundary is the loopback interface, and anyone with a shell on the machine can call the API ([Security model](https://docs.any.org/operations/security-model.md.txt)). The data dir is not encrypted at rest either: records, the local store and the search index are readable by anyone who can read the directory ([Data directory](https://docs.any.org/operations/data-dir.md.txt)). A standalone `wallet.key` holds the mnemonic and is plain JSON unless encrypted with a passkey supplied via `ANY_WALLET_PASSKEY` or `--passkey-stdin`; the server never prompts for it interactively. A server started with `--mode managed` keeps no account key on disk at all: its host supplies the phrase over `POST /v1/auth` on every launch ([Accounts](https://docs.any.org/auth/accounts.md.txt)). > **Note.** There is no key escrow and no recovery flow. Lose the mnemonic and every device key derived from it, and the data is unrecoverable by design. Back the phrase up when `any init` prints it. --- Source: https://docs.any.org/understanding/crdt-and-consistency.html # CRDTs and consistency any never rejects a write because someone else wrote first, and never shows two members different final states. It gets there with a specific, narrow CRDT: per-path last-writer-wins over a causal DAG. Knowing exactly what that guarantees — and what it does not — is the difference between a client that feels instant and one that quietly loses edits. ## The unit of write: a change Every write (`/modify`, a chat send, a block patch, a property set) becomes one **change** appended to the target object's DAG. A change carries: - `prevIds` — the heads it was built on (its causal parents); - a batch of per-record ops: `$set`, `$unset`, `$inc`, `$addToSet`, `$pull`, `delete`, keyed by dotted paths; - the author's signature and the read-key id. The change's CID is the `changeId` every write returns. It is the same on every peer, which is why it doubles as a **version** for history reads ([Version history](https://docs.any.org/database/version-history.md.txt)). ## Ordering: DAG order, not clocks Each peer's any-sync assigns every change it has seen a lexicographically sortable `versionId`. That order is: - **causal** — a change always sorts after its `prevIds`; - **deterministic** for concurrent branches — every peer resolves the same tie the same way once it has both branches; - **peer-local in its string form** — two peers may spell the "same" change with different `versionId` strings. Compare versionIds only within one peer, within one object. There is **no total order across peers in real time**. Two members editing while apart each hold a linear history that is correct for what they have seen; the merge point is when both branches arrive. ## Merging: per-path LWW Each record stores a `_ver` map: the versionId of the last change that wrote each path. Applying an op is a gate: ``` if op.versionId > record._ver[path]: apply, and _ver[path] = op.versionId else: drop (an older write for this path) ``` Because the rule is per *path*, not per record, concurrent edits to different fields of the same record both survive: ``` peer A: $set title = "Draft 2" peer B: $set tags = ["idea"] └──────────── merge ────────────┘ { title: "Draft 2", tags: ["idea"] } on both peers ``` Concurrent edits to the **same** path pick one winner by DAG order — the other value is gone, on every peer, with no error surfaced to either author. Three ops escape LWW because they compose instead: | Op | Merge rule | | --- | --- | | `$inc` | Commutative counter — both increments apply. | | `$addToSet` / `$pull` | Set semantics — concurrent adds all land. Concurrent add + pull of the same element has no per-element guarantee. | | `delete` | **Delete wins absolutely.** A tombstone is sticky; every later modify on that record id is dropped and reported to the local writer as a rejection. | Creates are upserts: two concurrent creates of the same id merge per field, and the record's creation marker `_ver.id` converges to the causally earliest one (the `min` rule), so a chat sorted by `-_ver.id` orders identically everywhere. ## Versus transactions | Property | Transactional DB (Postgres, a hosted backend) | any | | --- | --- | --- | | A write can fail because of another writer | Yes — serialization failure, OCC version mismatch, unique violation | No. Writes always commit locally. Only *validation* (schema, handler rules, a storage collection the object's type does not declare, tombstone) rejects. | | Read-your-writes | Yes | Yes, on the writing device. | | Cross-record atomicity | Yes — a transaction spans rows and tables | One change spans the records of one object's dataset batch and applies atomically on each peer. Nothing spans objects. | | Invariants like "balance ≥ 0" | Enforced by the DB under contention | Cannot be enforced across concurrent writers. Model it as a counter (`$inc`) if it must converge, or accept that two offline decrements both apply. | | Conflict visibility | Loser retries | Loser is silently overwritten per path; deleted records reject later writes. | | "The" current state | The server's | Each device's, converging as changes arrive. | > **Why it matters.** Transactions buy you invariants by making writers wait for one another, which needs a single authority that is online. any's model buys you writes that never wait and never need a server, at the price of invariants that must be expressible as commutative operations or per-path overwrites. Design your records so that the fields people edit concurrently are *different* fields, keep counters as counters, and let deletes be final. ## What this means for a client - **Write narrowly.** `$set` the path you changed (`style.checked`), not the whole record; a whole-record `$set` overwrites every sibling field a peer touched. The editor's markdown `PATCH` exists for exactly this reason ([Editor](https://docs.any.org/types/editor.md.txt)). - **Stamp your own writes.** A write returns `versionId`; stamp it on the paths you touched so the matching subscribe delta is recognisable as your own ([Subscriptions](https://docs.any.org/realtime/subscribe.md.txt)). - **Never fence on timestamps.** `modifiedAt` and chat `createdAt` are the author's clock. They converge, but two authors' clocks are not comparable. Order by `_ver.id` for creation order, by `-modifiedAt` for display recency only. - **Treat a tombstone rejection as final.** A write against a deleted record id returns it in `rejections`; recreate under a new id if you need the data back. - **Local scope is outside the CRDT.** Fields declared `local` mint their own version ids, never enter the DAG, and never sync — they annotate synced records on this device only ([System fields](https://docs.any.org/database/system-fields.md.txt)). > **Note.** Validation is not merge. A dataset handler (chat's "author-only edit", a runtime schema's `required`) rejects a change *before* it enters the DAG on the writer, and drops the offending op *after* delivery on readers. Both keep the DAG applying; neither is a conflict — a conflict never surfaces to any caller. --- Source: https://docs.any.org/understanding/zen-of-any.html # The zen of any The API is small on purpose. Every rule below is something the server refuses to bend, so a client can rely on it without reading the source. ## 1. One surface: HTTP/JSON on loopback Every caller — the CLI, the web UI, a language binding, an agent — goes through `http://127.0.0.1:7001/v1/…`. Nothing opens the database or talks to sync peers directly. The CLI is a thin client: `any space get X` *is* `GET /v1/spaces/X`, exit code included. ``` 0 success 1 user error / 4xx 2 server error / 5xx 3 can't reach server ``` The server refuses to bind anything but a loopback address and does not authenticate callers — the loopback interface is the trust boundary. What a server gates is ownership: a host-managed server accepts login, sign-out, account switches and shutdown only with its control token ([Security model](https://docs.any.org/operations/security-model.md.txt)). ## 2. Reads go through `/query` and `/query/subscribe` Every dataset — objects, chat messages, editor blocks, files, devices, the space list — is read through the same two POSTs with the same body (`filter` / `sort` / `limit` / `offset` / `includeTotal` / `projection`) and the same SSE frame set (`ready` → `snapshot` → `changes` → `closed`). One read path per dataset, one wire shape per snapshot. ```bash curl -X POST http://127.0.0.1:7001/v1/spaces/$SPACE/query \ -H 'content-type: application/json' \ -d '{"objectId":"'$OBJ'","dataset":"chat_messages","sort":["-_ver.id"],"limit":50}' ``` The single exception is `GET …/editor/:collection/markdown`, which is a render transform, not a dataset read. ## 3. Writes go through the module's handler Module storage collections are written only by their bespoke endpoints — chat's send/edit/delete/react, editor's block create/patch/delete — because the handler is what stamps `creator` / `createdAt`, enforces author-only rules, and keys reactions per identity. Generic datasets go through `/modify` (and `/upsert` for id-keyed ingest). Every write returns one shape and never the record body: ```json { "versionId": "…", "changeId": "bafy…", "recordIds": ["…"] } ``` Read the result back through a query; that is also where everyone else's writes arrive. ## 4. Endpoints map 1:1 onto SDK methods If the SDK has it, there is an endpoint. If it does not, there is not — the server does not invent aggregating conveniences. The named exceptions are documented as such: `/search` and the link index behind `/backlinks` (consumer-side indexes over the change feed), the markdown bridge, the ephemeral `/events` bus and `/processes`, the device-local `/v1/local` store, and the usecase catalog under `/v1/catalog`. When a route is registered ahead of its SDK method it returns `501 sdk.not_implemented` rather than pretending. ## 5. Every route lives under `/v1/` Health, shutdown, OpenAPI — all versioned from day one. Breaking changes are absorbed by bumping the prefix, never by changing a path in place. The full spec is served at `GET /v1/openapi.json`. ## 6. Errors have one shape ```json { "error": { "code": "space.not_found", "message": "space bafy… not found", "details": { } } } ``` Same body for every non-2xx. `code` is a dotted, machine-readable handle grouped by area (`auth.*`, `space.*`, `object.*`, `dataset.*`, `markdown.*`, `index.*`, …); `message` is safe to display; `details` is structured context and never contains secrets or filesystem paths ([Errors](https://docs.any.org/reference/errors.md.txt)). ## 7. POSTs are not idempotent Each POST produces a new DAG change; retrying a create makes two objects. The deliberate exceptions address a stable key: `POST /v1/spaces/:id/upsert`, where the caller-supplied record id is the idempotency key and an identical re-run diffs to nothing ([Upsert](https://docs.any.org/database/upsert.md.txt)), and the adopt-or-install calls — catalog setup, bundle ensure, derived spaces — which land on the same install however often they run ([Bundles](https://docs.any.org/collaboration/bundles.md.txt)). ## 8. Bodies are strict, output is pretty JSON Request schemas are closed: an unknown top-level key is `400 request.unknown_field` naming the accepted set, so a `filters` typo fails loudly instead of querying the whole space. Responses and CLI output are pretty-printed JSON — no table rendering, no `--output` flag. ## 9. Timestamps are instants Every server-stamped time and every `date` / `datetime` property is `{"$date": "2026-08-05T17:00:00.000Z"}` in both directions, filters included. A bare string or number does not error — it compares only within its own type bracket, so it silently matches nothing ([Data types](https://docs.any.org/database/data-types.md.txt)). ## 10. Subscriptions are windows, and `closed` is terminal A live stream holds a bounded window and delivers deltas to it; on `overflow` or `drifted` the server closes it rather than dropping events, and recovery is always "open a fresh POST and take the new snapshot" — never "replay the gap". > **Why it matters.** Each of these rules removes a class of client bug. One read path means one parser; one write shape means one place to stamp versions; strict bodies mean typos cannot silently widen a query; terminal `closed` means no client ever reconciles a partial event stream against a snapshot. A hosted backend can afford ad-hoc endpoints because it owns the only copy of the data — a local-first system has as many copies as devices, and consistency of *behaviour* across them is what keeps those copies consistent. ## Further reading - [Best practices](https://docs.any.org/understanding/best-practices.md.txt) — the call patterns built on these rules. - [HTTP API reference](https://docs.any.org/reference/http-api.md.txt) — the endpoint catalog. --- Source: https://docs.any.org/understanding/dev-workflow.html # Developer workflow Development against any is one long-running server process on your machine and whatever clients you point at it. This page is the loop you will repeat: init, run, call, inspect. ## 1. Init an account ```bash any init ``` Creates `~/.any/` (mode 0700), generates an account, writes `~/.any//wallet.key`, and prints the BIP-39 mnemonic to stderr **once**. Back it up. Re-running `any init` when an account exists is a no-op that lists them. To attach a second machine to the same account, restore from the phrase — the account id is the same, the device key is fresh: ```bash any init --mnemonic-stdin < phrase.txt # never copy wallet.key between machines ``` ## 2. Run the server ```bash any run # foreground, 127.0.0.1:7001 any run --addr 127.0.0.1:0 # ephemeral port; prints "LISTENING " on stdout any run --account # pick one when the data dir holds several any run --mode managed # a host-owned server: phrase per launch, control token ``` `any run` is foreground-only: run it in a terminal, tmux, or a user service. It never creates a wallet — on a fresh data dir it starts *unauthorized* and every route except `/v1/health`, `/v1/shutdown`, `/v1/openapi.json`, `/v1/auth` answers `401 auth.required` until `POST /v1/auth` (or `any auth login`) boots an account in place. The default `standalone` mode is the one to develop against; `managed` is how an app shell embeds the server ([Accounts](https://docs.any.org/auth/accounts.md.txt)). Stop it with Ctrl-C or: ```bash any stop # finds the server by its account lock, SIGTERM — # drains in-flight, 10 s deadline ``` ## 3. Check health ```bash any status # GET /v1/health ``` ```json { "status": "ok", "version": "any v0.1.2 (commit 1a2b3c4, built 2026-09-09)", "startedAt": "2026-08-24T09:00:00Z", "networkId": "N83gJpVd…", "account": "A8tR…", "bootstrapping": false } ``` `networkId` is the any-sync network the server joined ([Networks](https://docs.any.org/operations/networks.md.txt)). `bootstrapping: true` means the background space-loading pass is still running; the server is serving already. `crdtVersion` (`{supported, stored, newer}`) is the account's data-model version: every release stamps its own on first open and the mark only rises, so a release older than the data refuses to boot (`409 sdk.crdt_version_newer`) or, when the raise arrives from another device while running, turns read-only — `newer: true` is the client's "upgrade required" signal. ## 4. Call it Everything is `http://127.0.0.1:7001/v1/…` with JSON bodies. Pick whichever client fits: | Client | When | | --- | --- | | `curl` | Exploring; the [curl quickstart](https://docs.any.org/quickstart/curl.md.txt) creates a space, an object, and a subscription. | | `any …` CLI | Scripts and shells — subcommands mirroring the endpoints, pretty JSON on stdout, `jq`-friendly ([CLI quickstart](https://docs.any.org/quickstart/cli.md.txt)). | | Web UI | `http://127.0.0.1:7001/ui` — a debug harness with a space picker, object tree, chat, members, and a network log. Disable with `webUI.enabled: false`. | | Your app | Any HTTP client; live updates are SSE over a streaming POST ([JavaScript](https://docs.any.org/quickstart/javascript.md.txt), [Python](https://docs.any.org/quickstart/python.md.txt)). | ```bash any --verbose space get $SPACE # log the HTTP exchange to stderr any --addr 127.0.0.1:7002 status # a second server on another port ``` Without `--addr` the CLI finds the server serving the data dir's account through its `server.addr` file, so an ephemeral-port server needs no flag. When the server is down the CLI exits 3 with `start it with any run in another terminal`; it never auto-starts one. ## 5. Inspect - **Sync** — `any sync-status space $SPACE`, `any sync-status subscribe`. - **Search index** — `any search $SPACE "reranker"`; check `vectorStatus` in the reply. - **Raw datasets** — `any query-subscribe $SPACE $OBJ --dataset chat_messages --limit 20 --sort='-_ver.id'` prints one JSON line per SSE frame. - **Diagnostics** — `any debug space $SPACE` / `any debug object $SPACE $OBJ` dump head-sync counters and per-object tree state (unstable output, diagnostic only). - **Logs** — one stream on stderr through the SDK logger; `--log-level debug` or `ANY_LOG_LEVEL=debug`. Add an absolute file path under `log.outputPaths` in `config.yaml` to tee to a file ([Debugging](https://docs.any.org/operations/debugging.md.txt)). ## The data dir ``` ~/.any/ # dataDir — a ROOT that can hold several accounts ├── config.yaml # optional ├── models/ # shared embedder model cache (~600 MB, downloaded once) └── / ├── wallet.key # standalone: account + device keys (0600) ├── device.key # managed: this device's key only (0600) ├── server.lock # single-instance lock (an OS file lock) ├── server.pid # holder's pid, for error messages only ├── server.addr # holder's bound address, read by the CLI ├── sdk/ # any-store databases — owned by the SDK ├── files/ # file bytes, one CARv2 per root CID └── index/ # local search index — derived, safe to delete ``` Two servers may share a root as long as they serve different accounts on different ports. The `index/` directory is derived state: removing it with the server stopped is safe, and the next start re-indexes every space from the change feed. Never delete `files/` by hand — a file that has not been backed up yet has its only copy there ([Data dir](https://docs.any.org/operations/data-dir.md.txt)). Config precedence is file → `ANY_*` env → flags; the file is looked up at `--config`, `$XDG_CONFIG_HOME/any/config.yaml`, `~/.config/any/config.yaml`, then `/config.yaml` ([Configuration](https://docs.any.org/operations/configuration.md.txt)). ## Building from source ```bash make build # → bin/any (+ bin/llamacpp for the local embedder) go test ./... ``` `make build` adds the local embedder (`-tags llamacpp`) and its llama.cpp libraries; a bare `go build` serves full-text search, and vector search only through an online provider named by `index.openai.*`. `go test ./...` runs everything except the local-embedder tests, which `make test` adds. On NixOS run builds and the binary through `nix develop -c …` so the local embedder finds `libffi` ([Builds and CI](https://docs.any.org/operations/builds-and-ci.md.txt)). > **Note.** An unconfigured binary syncs against the **production** network. For experiments use a staging or local nodeconf via `ANY_NETWORK_NODECONF_PATH`, or the embedded placeholder that joins no network at all ([Networks](https://docs.any.org/quickstart/networks.md.txt)). --- Source: https://docs.any.org/understanding/best-practices.html # Best practices None of these are new endpoints. They are the patterns that make a client correct on a CRDT and cheap on a local store, condensed from what has broken in real clients. ## 1. Writes go through the module's handler Chat and editor storage collections are written only through `…/chat/messages` and `…/editor/:collection/blocks` — the handler stamps `creator` / `createdAt` / `modifiedAt`, enforces author-only edit/delete, and keys reactions per identity. For documents pick the route by change shape: targeted edit → `PATCH …/editor/editor_blocks/markdown` with `{edits:[{oldText,newText}]}` (a stale quote fails with `markdown.no_match` instead of clobbering concurrent edits); full rewrite → `PUT`; tail growth → `POST …/markdown/append`. Never `GET → string-replace → PUT`. Every write returns `{versionId, changeId, recordIds}`, never the record. Stamp `versionId` on the paths you touched so you recognise your own change when it arrives on the stream. ## 2. Preflight-validate against the object's owners An object's `any.type` decides which storage collections it accepts: one lives on an object only while a part of its type declares it, so an `editor_blocks` write to an object whose type is not a document type is `400 dataset.not_declared` — and no write sets a type for you. Set the type deliberately, at create (`{"type": "page"}`) or with `POST …/properties/:objectId/type/:typeId`, and check the row before writing; `GET /v1/spaces/:id/datasets` lists each storage collection's declaring `owners`. Property values are admitted only under an **owner** the object has — its type or one of its collections filed through `POST …/properties/:objectId/collections/:collectionId` — and are checked against the declared `kind` (`400 property.kind_mismatch`) and the `xFormat` slug (`400 property.format_violation`); read `GET …/types/:id/properties` or `GET …/collections/:id/properties` once and validate before you write rather than after a 400. ## 3. Reads go through query / subscribe - **Prefer `query`.** Open a `subscribe` only when the UI renders changes live. - **Always set `limit`.** An unbounded read is a bug: it can produce a huge snapshot or overflow a subscribe mailbox, and drift detection is off when `limit == 0`. - **Page on a cursor, not `offset`.** Offsets float under writes. Page with `{"_ver.id": {"$lt": ""}}` and the same sort — indexed, absolute, and correct while the storage collection mutates. - **Recency is `-modifiedAt`**, creation order `-createdAt` — author's clock, display quality only. - **Timestamps are `{"$date": …}`** in filters too; a bare value compares only within its own type bracket, so it silently returns nothing. - **Aggregate server-side.** Counts and top-N go through `…/aggregate`, `$match` first ([Aggregation](https://docs.any.org/database/aggregation.md.txt)). ## 4. Chat: newest-first, subscribe first Find the chat through the catalog (`POST /v1/catalog/general-chat/setup`, the chat is the returned `bundle.rootId`) so every client lands on the one object. Open the view with a **subscribe** — its `snapshot` *is* the initial load; a separate query first opens a gap/dup race. Sort `-_ver.id` everywhere: the window holds the top of the sort, so descending is the only direction where new messages enter it. Page history with `{"_ver.id": {"$lt": oldest}}` ([Chat](https://docs.any.org/types/chat.md.txt)). ## 5. Hold a window; recover by resubscribing A subscription is a moving window, not a feed to accumulate. Keep the window in memory, apply `added` / `updated` / `removed`, and keep no second store to reconcile. Every `closed` reason is terminal — `drifted` (more than `driftBudgetPercent` of the window left without replacement, default 30) and `overflow` (mailbox of `mailboxCapacity` filled, default 256) included. The fresh snapshot already reflects current state; rebuilding it from a delta is the expensive path the server refuses. Window size costs the client memory, not the server ([Subscriptions](https://docs.any.org/realtime/subscribe.md.txt)). ## 6. Search: hybrid, then read `vectorStatus` Default `mode: "hybrid"`; pin `fts` for exact ids and error strings. Check `vectorStatus` before trusting an empty result: `used` / `unavailable` (embedder down — retry may differ) / `disabled` (never on this server) / `skipped`. Hits carry `{scope, objectId, dataset, recordId, data, score}`, not records — hydrate through `/query`. Scores compare only within one response ([Search](https://docs.any.org/search/index.md.txt)). ## 7. Direct chats: derive by identity, approve incoming `POST /v1/spaces/one-to-one {"otherIdentity"}` — both sides compute the same space id, no invite. Incoming requests are `GET /v1/spaces?status=one_to_one_pending`; accept or decline by row id. Classify on `spaceType == "any.onetoone"` ([One-to-one](https://docs.any.org/collaboration/one-to-one.md.txt)). ## 8. Members carry roles; the directory carries names `GET /v1/spaces/:id/members` is the roster *with* permissions — the only source of roles. `GET /v1/identities` resolves a display name for any account id across spaces and carries no rights. Profiles are encrypted: tolerate empty names and let `updated` frames fill them ([Members and roles](https://docs.any.org/collaboration/members-and-roles.md.txt)). ## 9. Files: attach and move on, render by URL `POST …/files` returns 201 once the row is durable in the CRDT; the network backup always runs in the background, so the receipt says `durable: false` for anything but an inline file or one deduplicated against an already backed-up file. Do not block UI on `durable`. A member's incoming file becomes fetchable when its row gains `networkSign` on the files/query subscribe; `409 file.not_available` before that is "wait", not "error". Point `` / `