@kedem/okdb 2.3.5 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +427 -0
  2. package/algorithm-worker-thread.js +1 -1
  3. package/bin/okdb.js +1 -1
  4. package/docs/auth-and-sync.md +30 -5
  5. package/docs/auth-permissions.md +19 -6
  6. package/docs/change-log.md +79 -59
  7. package/docs/data-model.md +20 -18
  8. package/docs/deployment.md +25 -0
  9. package/docs/diagnostics.md +59 -17
  10. package/docs/embeddings.md +57 -6
  11. package/docs/fts.md +50 -5
  12. package/docs/functions.md +21 -8
  13. package/docs/http-api.md +139 -98
  14. package/docs/http-cluster.md +30 -8
  15. package/docs/indexes.md +5 -4
  16. package/docs/licensing.md +6 -1
  17. package/docs/logging.md +18 -0
  18. package/docs/migration.md +153 -2
  19. package/docs/pipelines.md +6 -1
  20. package/docs/plugins.md +12 -18
  21. package/docs/process-registry.md +50 -39
  22. package/docs/processors.md +40 -22
  23. package/docs/querying.md +50 -36
  24. package/docs/queue.md +110 -14
  25. package/docs/subscriptions.md +37 -24
  26. package/docs/sync.md +96 -37
  27. package/docs/time-machine.md +23 -17
  28. package/docs/transactions.md +11 -19
  29. package/docs/ttl.md +118 -67
  30. package/docs/upgrade-2.0.md +2 -2
  31. package/docs/views.md +75 -52
  32. package/okdb-functions-sandbox-worker.js +1 -1
  33. package/okdb-http-worker-child.js +1 -1
  34. package/okdb-views-bootstrap-worker.js +1 -1
  35. package/okdb.js +1 -1
  36. package/package.json +1 -1
  37. package/public/sections/db/parts/type-viewer.ok.js +1 -1
  38. package/public/sections/embeddings/parts/engines-overview.ok.js +1 -1
  39. package/public/sections/queue/parts/queue-jobs.ok.js +1 -1
  40. package/public/sections/system/modals/data-ops-modal.ok.js +1 -1
  41. package/types/environment.d.ts +320 -52
  42. package/types/features/admin.d.ts +8 -2
  43. package/types/features/api.d.ts +10 -16
  44. package/types/features/auth.d.ts +135 -16
  45. package/types/features/embeddings.d.ts +639 -31
  46. package/types/features/engines.d.ts +368 -14
  47. package/types/features/files.d.ts +0 -3
  48. package/types/features/fts.d.ts +98 -26
  49. package/types/features/functions.d.ts +175 -15
  50. package/types/features/mcp.d.ts +23 -10
  51. package/types/features/pipelines.d.ts +268 -9
  52. package/types/features/queue.d.ts +230 -34
  53. package/types/features/sync.d.ts +177 -14
  54. package/types/features/time-machine.d.ts +117 -16
  55. package/types/features/views.d.ts +230 -39
  56. package/types/index.d.ts +357 -254
  57. package/types/okdb.d.ts +397 -0
  58. package/types/options.d.ts +309 -48
  59. package/public/test-cron-input.html +0 -60
  60. package/public/test-json-input.html +0 -280
package/docs/migration.md CHANGED
@@ -1,6 +1,13 @@
1
1
  # Migration & Export
2
2
 
3
- OKDB's migration feature handles export/import of all types and records as JSON, plus blob export/import for file storage, and blob integrity tools.
3
+ OKDB's migration feature handles export/import of all types and records as JSON / NDJSON, plus blob export/import for file storage, blob integrity tools, and hot filesystem **backup / restore** of the whole store.
4
+
5
+ | You want | Use |
6
+ | ----------------------------------------- | --------------------------------------------------------------------------------- |
7
+ | a restorable copy of the whole store | [`migrate.backup(dir)`](#hot-backup-and-restore) / `okdb backup` + `okdb restore` |
8
+ | a copy that is a store of its own | [`OKDB.clone(src, dst)`](#cloning-a-store-new-identity) / `OKDB.reidentify(dir)` |
9
+ | portable, version-independent data | [`migrate.exportToFile()`](#streaming-export-ndjson) / `okdb export` |
10
+ | a small in-memory snapshot (tests, demos) | `migrate.export()` / `exportJSON()` |
4
11
 
5
12
  ---
6
13
 
@@ -126,7 +133,151 @@ console.log(`Rebuilt ref-counts for ${rebuilt} blobs`);
126
133
 
127
134
  ---
128
135
 
129
- ## Full backup workflow
136
+ ## Streaming export (NDJSON)
137
+
138
+ ```javascript
139
+ await okdb.migrate.exportToFile('./export.ndjson', { envName: 'default', types: null, includeChanges: false });
140
+ await okdb.migrate.exportToStream(writable, { envName: 'default' }); // any Writable; you close it
141
+ await okdb.migrate.exportEnvsToStream(writable, { envNames: null }); // every user env, one stream
142
+ await okdb.migrate.importFromFile('./export.ndjson', { dropExisting: false, batchSize: 500 });
143
+ ```
144
+
145
+ One JSON record per line (`header`, `env`, `schema`, `data`, `change`). The export is
146
+ **cooperative**: rows are read and written in 1 000-row chunks, the loop yields between
147
+ chunks, and `drain` is awaited whenever the stream's `write()` returns `false` — exporting
148
+ 200 000 docs holds the event loop for at most one chunk (≈10 ms, down from a ≈0.6 s single
149
+ stall) and buffers ≈0.3 MB instead of the whole 52 MB export, however slow the consumer.
150
+
151
+ **Consistency is per chunk, not point-in-time.** Each chunk is read from its own LMDB
152
+ snapshot and released before the next `await` (a snapshot reader may not be held across an
153
+ await — see the safe-range contract in [querying.md](querying.md)); the next chunk resumes
154
+ strictly after the last exported key. So every key is exported at most once, a key that
155
+ exists for the whole export is exported exactly once with the value it had when its chunk
156
+ was read, and rows written concurrently may or may not appear. Different types (and chunks)
157
+ reflect different moments. For a point-in-time copy use [`backup()`](#hot-backup-and-restore)
158
+ (one snapshot per env), or export a quiescent store.
159
+
160
+ ---
161
+
162
+ ## Hot backup and restore
163
+
164
+ ```javascript
165
+ const r = await okdb.migrate.backup('/backups/okdb-2026-09-24', { envNames: null, compact: true });
166
+ // r = { ok, dest, envs: [{ name, dest, sizeBefore, sizeAfter, timeMachine }], blobs: { count, bytes }, skipped, manifest }
167
+ ```
168
+
169
+ ```bash
170
+ okdb backup /backups/okdb-2026-09-24 --path ./okdb-data
171
+ okdb restore /backups/okdb-2026-09-24 --path ./okdb-restored # target must not exist or be empty
172
+ ```
173
+
174
+ `destDir` must not exist (or be empty) and must not be inside the store — a backup never
175
+ overwrites. The result directory **is a store**: open OKDB on it (or on a copy of it).
176
+
177
+ **What is copied**
178
+
179
+ | Part | How | Notes |
180
+ | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
181
+ | every env (`~system`, `default`, user envs, `~log`, `~sub`, embeddings sub-envs) | LMDB native copy (`mdb_env_copy2`, compacting when `compact`) — one read snapshot per env, safe against concurrent writers | each env lands at its path relative to the store root, so the copied env registry resolves it. `envNames` narrows the set; `~system` (env registry, identity, licenses, token secret) is always included so the copy opens — unselected envs open empty |
182
+ | each env's time-machine history (`<env>/time-machine/`) | LMDB native copy, immediately **before** its env | history is not derivable (the changelog it was built from is GC'd). Two LMDB envs cannot share one snapshot: diffs for writes committed _while the env file itself is copied_ are missing from the copy; the restored time machine resumes from the env's cursor, so a key written in that window gets one coarser diff on its next write |
183
+ | file blobs (`~blobs/`) | file copy **after** all env metadata, skipping the `tmp/` upload staging dir | an upload during the backup is at worst an orphan blob; a file _deleted_ during the backup (refs → 0 unlinks the blob) can leave a `~files` record without bytes — run `migrate.validateBlobIntegrity()` on the restored store |
184
+ | `okdb-backup.json` | written last | manifest (version, envs, blob count, exclusions); its presence marks a complete backup — `okdb restore` refuses a directory without it |
185
+
186
+ **What is not copied**
187
+
188
+ - `~fts/` — full-text indexes are derived, and live in a separate LMDB env whose indexing
189
+ cursor is stored in the data env, so no copy order would make the pair consistent. The
190
+ restored store notices the missing `~fts` files on its first open and **rebuilds every
191
+ index from the documents** (demoting them to `creating` until done — `fts.ready()` waits;
192
+ cost: one full re-tokenize of the indexed types).
193
+ - `~processes` — the live process registry (disposable; rebuilt by the running processes).
194
+ - quarantined envs (failed to open) — reported in `skipped`.
195
+
196
+ **Restore** = put the backup directory where the store should live and open it:
197
+ `okdb restore <backup> --path <target>` copies it into a new/empty target. Things to know:
198
+
199
+ - The restored store has the **same node identity** as the source. Do not run it as a sync
200
+ peer alongside the original — restore replaces a node, it does not clone one. To bring the
201
+ copy up as a **new** node instead, use `okdb restore <backup> --path <target> --new-identity`
202
+ (or `OKDB.reidentify(target)`) — see [Cloning a store](#cloning-a-store-new-identity).
203
+ - An env registered with an absolute path _outside_ the store (legacy / hand-edited records
204
+ only; `createEnvironment` always places envs under the root) is copied to its default
205
+ placement and flagged `outOfTree` in the manifest; while its original path still exists,
206
+ the restored store opens that original directory. `okdb restore` warns about this.
207
+
208
+ **Remote backups (HTTP / MCP).** `POST /api/system/backup` (MCP `system_backup`) writes only
209
+ under the server's backup root — the `backup.root` constructor / config-file option, default
210
+ `<store>-backups` next to the store (`/data/okdb` → `/data/okdb-backups`). `destDir` is
211
+ relative to that root (default: a timestamped name); anything resolving outside it (`..`,
212
+ another absolute path, a symlink pointing out) is refused with `400 BACKUP_PATH_OUTSIDE_ROOT`,
213
+ an existing non-empty directory with `409 BACKUP_DEST_NOT_EMPTY`. The route is marked
214
+ destructive (it can fill the server's disk), so MCP clients must confirm it.
215
+
216
+ ```javascript
217
+ new OKDB('/data/okdb', { backup: { root: '/mnt/backups/okdb' } });
218
+ ```
219
+
220
+ ---
221
+
222
+ ## Cloning a store (new identity)
223
+
224
+ Every store has a node identity (`db.id`), created on its first open. A byte copy keeps it, so
225
+ two copies of one store behave as one node: they join the same bus group (and receive each
226
+ other's change and compaction signals), share the sync node id, keypair and token secret, and
227
+ match the same licence activation. Use `OKDB.clone()` whenever a copy must be a store of its
228
+ own — test templates, a staging copy, a backup brought up next to the original.
229
+
230
+ ```javascript
231
+ await OKDB.clone('/data/template', '/tmp/test-42'); // → { path, files, bytes, ms }
232
+ const db = new OKDB('/tmp/test-42');
233
+ await db.open(); // the first open gives the copy its own identity
234
+ db.id; // new UUID
235
+ db.formerIds; // [ '<template id>' ]
236
+ ```
237
+
238
+ - **The source must be closed** by every process. A copy of a running store is not consistent
239
+ across its LMDB files, so `clone()` refuses with `STORE_IN_USE` when a process has the store
240
+ open (detected on Linux from the LMDB file locks; on other platforms this is your
241
+ responsibility). For a store that must stay up, take a [hot backup](#hot-backup-and-restore)
242
+ and re-identify it: `await db.migrate.backup(dir); OKDB.reidentify(dir)`.
243
+ - `dstPath` must not exist or be empty (`CLONE_DEST_NOT_EMPTY`), and must not overlap the source.
244
+ - **Everything is copied** — every env, `~fts`, time-machine history, `~vectors`, `~blobs`, views,
245
+ indexes and processor cursors — **except** LMDB `lock.mdb` files, the disposable `~processes`
246
+ env, upload staging (`~blobs/tmp`) and compaction leftovers. The copy is fast (a file copy,
247
+ reflinked where the filesystem supports it: a small store clones in a few milliseconds) and
248
+ opens with every index, view and search index ready — nothing is rebuilt or reprocessed.
249
+ - Envs are expected to live under the store directory (the default). If an env was registered at
250
+ an absolute path outside it and that directory exists, the copy's first open refuses with
251
+ `REIDENTIFY_OUT_OF_TREE_ENV` instead of opening the source's files.
252
+
253
+ **`OKDB.reidentify(path)`** marks a closed copy you made yourself (`cp -r`, a restored backup) to
254
+ take a new identity on its next open — the same step `clone()` ends with. It only writes a small
255
+ marker file (`okdb-reidentify.json`) at the store root; the store's **first open** applies it,
256
+ exactly once, even when several processes open the copy at the same time. Marking is idempotent,
257
+ and a marked copy that is copied again before it is opened still gives each copy its own identity.
258
+ A store that has already been opened under its new identity is an ordinary store: copying it
259
+ again needs another `clone()` / `reidentify()`.
260
+
261
+ **What the first open changes** — and what it keeps:
262
+
263
+ | Area | On the copy |
264
+ | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
265
+ | Identity | a new `db.id`; the old one is kept in `db.formerIds`. The bus group (`okdb-<id>`) follows the id, so the copy and the source never hear each other. |
266
+ | Secrets | a new token secret (sessions signed by the source stop validating, unless you set `auth.token.secret` yourself) and a new sync keypair (minted on first sync use). Stored users and API tokens are data and are copied. |
267
+ | Sync | not a member of anything: no `~sync_nodes` / `~sync_links` rows, no peer cursors. They are removed from the copy's changelog too, so nothing it later sends can delete them in the source's cluster. `db.sync.join(...)` makes it a new node, which pulls the topology back. |
268
+ | Licences | records are kept. A node-bound (standard) activation shows `wrong_node` on the copy; activate it again with the copy's own PIN. Open and internal licences, and `OKDB_LICENSE_FILE` installs of them, keep working. |
269
+ | Processes | leases, want-markers, the migration lock and process-keyed control rows are dropped — they belonged to the source's processes. |
270
+ | Changelog | kept as-is, origins included. Changes stamped with a former identity up to the point the copy was made count as the copy's own (`originMode: 'self'`); a former identity's later changes — the source's, synced in — are remote. |
271
+ | Data and derived | untouched: documents, indexes, views, FTS, time machine, vectors, files, queue jobs and every processor cursor. |
272
+
273
+ Queue jobs that were claimed when the source closed are recovered by the normal claim-timeout
274
+ path, as after a restart.
275
+
276
+ ---
277
+
278
+ ## Logical backup workflow
279
+
280
+ A version-independent alternative to the hot backup (slower; re-derives indexes on import):
130
281
 
131
282
  ```javascript
132
283
  // 1. Export type data
package/docs/pipelines.md CHANGED
@@ -87,7 +87,7 @@ await analytics.pipelines.remove('articles-ingest');
87
87
 
88
88
  **Pipelines are structurally atomic — the pipeline is the engine.** Member topology (the set/order of roles) is immutable — `update()` refuses `engines` changes — and members cannot be added or removed at runtime; new arrangements of engines are new pipeline _types_ (templates / `createPipeline` families), not record surgery. Public engine lifecycle surfaces enforce this: `DELETE`/`stop`/`start`/`restart` on an engine that is a pipeline member is refused with `ENGINE_MANAGED_BY_PIPELINE` (HTTP 409) pointing at the owning pipeline — operate on the pipeline instead. Per-member config patches and diagnostics (pause/resume/retry, reset-cursor, index reload) remain available.
89
89
 
90
- `replaceMember()` is the supported _parameter_ mutation: it swaps one member for another **existing engine of the same type**, re-points sibling members whose `config.<role>` referenced the old name (the indexer's and search engine's `embedder` field), restarts them, and rewrites the record. It does not re-embed — follow with `rebuild()` (UI: "Re-embed all") when the new member produces different output. `remove()` deletes env-owned members unless another pipeline record in the env still references them.
90
+ `replaceMember()` is the supported _parameter_ mutation: it swaps one member for another **existing engine of the same type**, re-points sibling members whose `config.<role>` referenced the old name (the indexer's and search engine's `embedder` field), restarts them, and rewrites the record. It does not re-embed — follow with `rebuild()` (UI: "Re-embed all") when the new member produces different output; replacing the embedder with one of another provider/model/dims marks the pipeline `stale` (new embeds held) until you do. `remove()` deletes env-owned members unless another pipeline record in the env still references them.
91
91
 
92
92
  ### HTTP API surface
93
93
 
@@ -528,6 +528,11 @@ Aggregate health is derived at runtime from persisted pipeline `status` and curr
528
528
  - no members online and all are `error` / `stopped` / `missing` → health `error`
529
529
  - otherwise → health `degraded`
530
530
 
531
+ Embeddings pipelines also report `stale` + `vector_space` (independent of `health`): `stale: true`
532
+ means the embedder's provider/model/dims changed since the stored vectors were embedded — search
533
+ serves the old vectors with a warning, new embeds are held, and `rebuild()` ("Re-embed all")
534
+ clears it. See [Embeddings → Stale pipelines](./embeddings.md#stale-pipelines-embedder-model-changed).
535
+
531
536
  ### Safe delete behavior
532
537
 
533
538
  `remove()` deletes the pipeline record and uninstalls engines owned by the same env.
package/docs/plugins.md CHANGED
@@ -9,9 +9,7 @@ Plugins are first-class addons that extend OKDB before it opens. They integrate
9
9
  ```javascript
10
10
  const okdb = new OKDB('./db');
11
11
 
12
- okdb.plugins.register(MyPlugin, {
13
- /* options */
14
- });
12
+ okdb.plugins.register(MyPlugin, {/* options */});
15
13
 
16
14
  await okdb.open();
17
15
  ```
@@ -36,9 +34,9 @@ module.exports = {
36
34
  // Must NOT do IO. Returns the plugin instance.
37
35
  register(okdb, options) {
38
36
  // Attach routes, listen to events, etc.
39
- okdb.http.get('/api/my-plugin/ping', async (req, res) => {
40
- res.json({ ok: true });
41
- });
37
+ // http.add(method, path, handler) — the handler gets { params, query, body, ... }
38
+ // and returns { result }; the response body is the { data, error, meta } envelope.
39
+ okdb.http.add('GET', '/api/my-plugin/ping', async () => ({ result: { ok: true } }));
42
40
 
43
41
  // The returned object becomes the instance
44
42
  return {
@@ -57,20 +55,14 @@ module.exports = {
57
55
 
58
56
  ```javascript
59
57
  const MyPlugin = require('./my-plugin');
60
- okdb.plugins.register(MyPlugin, {
61
- /* options passed to register() */
62
- });
58
+ okdb.plugins.register(MyPlugin, {/* options passed to register() */});
63
59
  await okdb.open();
64
60
  ```
65
61
 
66
- After registration, `okdb.my-plugin` is set to the instance object — so the plugin becomes a property on `okdb`:
67
-
68
- ```javascript
69
- okdb['my-plugin']; // → the instance returned by register()
70
- ```
62
+ The instance is kept internally (`okdb.plugins._plugins[i].instance`) — it is **not** attached as a property on `okdb`. If callers need it, keep your own reference (e.g. export it from the plugin module).
71
63
 
72
64
  :::note
73
- Plugin name must not conflict with existing OKDB properties (`env`, `put`, `get`, `http`, etc.). Registration throws `PLUGIN_NAME_CONFLICT` if there's a clash.
65
+ Plugin name must not conflict with existing OKDB properties (`env`, `put`, `get`, `http`, etc.). Registration throws `PLUGIN_NAME_CONFLICT` if there's a clash, `PLUGIN_ALREADY_REGISTERED` for a duplicate name, and `BAD_PLUGIN` when `name` is missing or `register()` doesn't return an object.
74
66
  :::
75
67
 
76
68
  ---
@@ -83,7 +75,7 @@ Plugin name must not conflict with existing OKDB properties (`env`, `put`, `get`
83
75
  | `instance.start(okdb)` | async | **yes** | Start servers, timers, workers |
84
76
  | `instance.stop(okdb)` | async | **yes** | Stop everything started in `start()` |
85
77
 
86
- If any plugin's `start()` throws, all already-started plugins are stopped in reverse order before the error propagates.
78
+ `start`/`stop` are optional. Plugins start in registration order at the end of `open()` and stop in reverse order during `close()`. If any plugin's `start()` throws, all already-started plugins are stopped in reverse order (the throwing plugin's `stop()` is not called), then `open()` releases everything else it had opened and rethrows the error; the instance is left stopped, so `close()` is a no-op.
87
79
 
88
80
  ---
89
81
 
@@ -136,9 +128,11 @@ const names = okdb.plugins._plugins.map((p) => p.module.name);
136
128
  // e.g. ['schema', 'auth', 'payments']
137
129
  ```
138
130
 
139
- The `okdb.info` response also includes the plugin list:
131
+ `okdb.info` (and `GET /api/info`) also includes the plugin list:
140
132
 
141
133
  ```javascript
134
+ okdb.info.plugins; // → ['schema', 'auth', 'payments']
135
+
142
136
  const info = await fetch('/api/info').then((r) => r.json());
143
- info.plugins; // → ['schema', 'auth', 'payments']
137
+ info.data.plugins; // → ['schema', 'auth', 'payments']
144
138
  ```
@@ -1,8 +1,8 @@
1
1
  # Process Registry
2
2
 
3
3
  The process registry is a root-wide **task manager** for every okdb process sharing one data
4
- directory: the HTTP-cluster primary and its workers, queue/function child processes, a standalone
5
- CLI server, and opted-in embedded nodes. It gives the admin UI (System → **Processes**) and the HTTP API
4
+ directory: the HTTP-cluster primary and its workers, a standalone CLI server, and every embedded
5
+ library process. It gives the admin UI (System → **Processes**) and the HTTP API
6
6
  a single, live view of the whole process tree — and a durable, safe way to control it (pause/resume,
7
7
  decommission, retry/reset, hard-kill).
8
8
 
@@ -10,8 +10,10 @@ It generalizes the same **durable-state-as-coordination** model used by live sub
10
10
  authority for every action is a durable record; the UDP bus only carries a lossy "go re-read it now"
11
11
  hint. A forged or dropped bus packet can therefore neither trigger nor lose a control action.
12
12
 
13
- > **Opt-in.** The registry is off by default so embedders and tests are unaffected. `bin/okdb` and the
14
- > HTTP cluster turn it on automatically; a library embedder opts in with `new OKDB(path, { processes: … })`.
13
+ > **On by default.** Every process that opens okdb registers itself at `open()` — registration is
14
+ > intrinsic, not gated on `http.listen()`. A library process publishes a `standalone` row by default;
15
+ > `processes: { register: false }` makes it a reader only, and `processes: false` opts out entirely
16
+ > (opens nothing, registers nothing).
15
17
 
16
18
  ---
17
19
 
@@ -25,7 +27,7 @@ The primary entity is the **process**, not the processor. Each long-lived proces
25
27
  ```js
26
28
  {
27
29
  nodeKey, // identity: `${pid}:${startedAt}` (wall-clock startedAt — same-host, see Liveness)
28
- kind, // primary | http-server | queue-worker | fn-runner | cli | standalone | embedded
30
+ kind, // primary | http-server | cli | standalone | embedded
29
31
  pid, ppid, host,
30
32
  supervisorKey, // nodeKey of the supervising process (null = a root) → builds the tree
31
33
  slot, slotKey, // supervised position; slotKey is the STABLE durable control key (see below)
@@ -54,10 +56,10 @@ writes emit **no** signal — the panel polls. Only desired-state/command writes
54
56
 
55
57
  ### Supervisor-published registration
56
58
 
57
- Children (http-servers, queue/fn runners) lack a stable cross-restart identity and some run with the
58
- bus off, so they do **not** self-register. Their **supervisor** — which already tracks each child's
59
- pid/slot and heartbeats it — writes the child's `node` row (`publishChildRow`) and removes it on exit.
60
- Roots (primary/cli/standalone) and opted-in embedded nodes self-publish via their heartbeat.
59
+ HTTP-cluster workers (`http-server`) lack a stable cross-restart identity, so they do **not**
60
+ self-register (they open the registry as readers). Their **supervisor** — which already tracks each
61
+ child's pid/slot and heartbeats it — writes the child's `node` row (`publishChildRow`) and removes it on
62
+ exit. Roots (primary/cli/standalone) and embedded nodes self-publish via their heartbeat.
61
63
 
62
64
  ### Liveness — wall-clock, read-time staleness
63
65
 
@@ -82,21 +84,21 @@ self-heals within one beat.
82
84
  All routes require `system:read` (views) or `system:write` (control).
83
85
 
84
86
  > **Naming.** The canonical surface is **`processes`** — `okdb.processes` and
85
- > `GET /api/processes[/tree]`. `/api/processes*` is the route surface (the former `okdb.fleet` accessor alias was removed). The tables
86
- > below still use `/api/processes*`; `/api/processes*` is equivalent for the read views.
87
-
88
- | Method & path | Purpose |
89
- | ---------------------------------------------------- | -------------------------------------------------------------- |
90
- | `GET /api/processes` (or `/api/processes`) | flat list of live processes (grouped, each with `instances[]`) |
91
- | `GET /api/processes/tree` (or `/api/processes/tree`) | nested process → instance → work tree (`supervisorKey`) |
92
- | `POST /api/processors/:id/pause`/`resume` | durable pause/resume of a processor (desired-state) |
93
- | `POST /api/processors/:id/retry` | retry an errored processor (durable command epoch) |
94
- | `POST /api/processors/cursor/reset` | reset a processor cursor to 0 (durable + command epoch) |
95
- | `POST /api/processes/:nodeKey/decommission` | gracefully stop a supervised process and keep it down |
96
- | `POST /api/processes/:nodeKey/recommission` | reverse a decommission/kill — the supervisor re-forks the slot |
97
- | `POST /api/processes/:nodeKey/kill?force=1` | hard-kill (guarded; see Control tiers) |
98
-
99
- When the registry is off (single-process / embedders), `/api/processes[/tree]` returns a degenerate
87
+ > `GET /api/processes[/tree]` (the former `okdb.fleet` accessor alias was removed). Don't confuse it
88
+ > with **processors** (`/api/processors/*`), the change-subscription primitives a process runs.
89
+
90
+ | Method & path | Purpose |
91
+ | ------------------------------------------- | -------------------------------------------------------------- |
92
+ | `GET /api/processes` | flat list of live processes (grouped, each with `instances[]`) |
93
+ | `GET /api/processes/tree` | nested process → instance → work tree (`supervisorKey`) |
94
+ | `POST /api/processors/:id/pause`/`resume` | durable pause/resume of a processor (desired-state) |
95
+ | `POST /api/processors/:id/retry` | retry an errored processor (durable command epoch) |
96
+ | `POST /api/processors/cursor/reset` | reset a processor cursor to 0 (durable + command epoch) |
97
+ | `POST /api/processes/:nodeKey/decommission` | gracefully stop a supervised process and keep it down |
98
+ | `POST /api/processes/:nodeKey/recommission` | reverse a decommission/kill — the supervisor re-forks the slot |
99
+ | `POST /api/processes/:nodeKey/kill?force=1` | hard-kill (guarded; see Control tiers) |
100
+
101
+ When the registry is off (`processes: false`), `/api/processes[/tree]` returns a degenerate
100
102
  single-root node so the API still answers.
101
103
 
102
104
  ---
@@ -132,12 +134,12 @@ Every decommission / recommission / kill writes a structured **audit** entry to
132
134
 
133
135
  `caps` is published per kind and **enforced by the routes**:
134
136
 
135
- | kind | controllable | decommissionable | killable | kill confirm |
136
- | -------------------------------------------- | ------------ | ---------------- | -------- | ------------ |
137
- | `primary` | if owner | no (root) | yes | cluster-wide |
138
- | `cli` / `standalone` | if owner | no (root) | yes | confirm |
139
- | `http-server` / `queue-worker` / `fn-runner` | no | yes | yes | force |
140
- | `embedded` | no | no | **no** | — |
137
+ | kind | controllable | decommissionable | killable | kill confirm |
138
+ | -------------------- | ------------ | ---------------- | -------- | ------------ |
139
+ | `primary` | if owner | no (root) | yes | cluster-wide |
140
+ | `cli` / `standalone` | if owner | no (root) | yes | confirm |
141
+ | `http-server` | no | yes | yes | force |
142
+ | `embedded` | no | no | **no** | — |
141
143
 
142
144
  Roots have no supervisor to route a decommission through — stop a root via its own shutdown or a
143
145
  confirmed kill. `embedded` is **observe-only**: okdb must never `process.exit` a host application, so an
@@ -156,23 +158,32 @@ LMDB; "kill" there would be a sync-protocol RPC) and are surfaced by the Sync vi
156
158
  ## Embedding
157
159
 
158
160
  ```js
159
- // Observe-only: appear in the registry, expose nothing controllable.
160
- const db = new OKDB('./data', { processes: { register: true, kind: 'embedded' } });
161
+ // Default: publishes a `standalone` row (killable/controllable per the table above).
162
+ const db = new OKDB('./data');
161
163
 
162
- // A library server that wants the full registry (and is the processor owner):
163
- const db = new OKDB('./data', { processes: { kind: 'standalone', listenAddr: ':8484' } });
164
+ // Observe-only: appear in the registry, expose nothing controllable or killable.
165
+ const db = new OKDB('./data', { processes: { kind: 'embedded', name: 'oasis-worker' } });
166
+
167
+ // Reader only: read the registry, publish no row.
168
+ const db = new OKDB('./data', { processes: { register: false } });
169
+
170
+ // Invisible: no registry at all.
171
+ const db = new OKDB('./data', { processes: false });
164
172
  ```
165
173
 
166
- `register: true` makes a process publish its own row even when it is not a `processors`-role owner.
167
- `bin/okdb` sets `kind` automatically (`primary` / `http-server`); embedders pass it explicitly.
174
+ `processes` also takes `name` (a label shown in the admin), `listenAddr`, and `kill: false` (see
175
+ below). `bin/okdb` sets `kind` automatically (`primary` / `http-server` / `cli`).
168
176
 
169
177
  ---
170
178
 
171
179
  ## Operational notes
172
180
 
173
- - **Bus secret & kill safety.** The `PROC` hint is only a nudge, so a weak/default bus secret cannot
174
- forge a control action — the durable `~system` record (written behind HTTP auth) is the sole
175
- authority. Still, set `OKDB_BUS_SECRET` in production so unrelated processes don't cross-poke.
181
+ - **Bus framing & kill safety.** The `PROC` hint is only a nudge: a forged datagram can at most trigger
182
+ a harmless re-read, never a control action — the durable `~system` record (written behind HTTP auth)
183
+ is the sole authority. Bus datagrams are framed with a prefix derived from the store's identity
184
+ (`okdb-<db id>`), so processes on the same data path form their own group automatically and unrelated
185
+ stores on the network don't cross-poke. There is nothing to configure (and no `OKDB_BUS_SECRET`); the
186
+ prefix is a namespace, not authentication — it travels in cleartext.
176
187
  - **Hard-kill kill-switch.** The irreversible hard-kill tier is enabled by default but can be locked
177
188
  down — `OKDB_PROCESS_KILL=off` or `new OKDB(path, { processes: { kill: false } })`. **Recommended in
178
189
  production.** When off, every node's `caps.killable` is `false`, so the UI hides the Kill button and
@@ -20,37 +20,47 @@ OKDB's own features (indexes, views, FTS, materializer, embeddings, time-machine
20
20
 
21
21
  ## Modes — the delivery guarantee
22
22
 
23
- A mode names the **delivery guarantee**: how many instances run the handler. All drains run on the owner process's **event loop**, chunked into cooperative quanta (`FLUSH_QUANTUM`-bounded batches with a yield between them) so a large drain never blocks the loop monolithically. There is no execution placement to configure — no thread pool, no `runIn`; the only thread in the engine is the **sandbox** that runs untrusted user-function code. Handlers register per process: pass `handler:'<name>'` (named registry), `module:{path,export}`, or — for internal features — a closure paired with a reconstructible `quantum`.
23
+ A mode names the **delivery guarantee**: how many instances run the handler. All drains run on the owner process's **event loop**, chunked into cooperative quanta (`FLUSH_QUANTUM`-bounded batches with a yield between them) so a large drain never blocks the loop monolithically. There is no execution placement to configure — no thread pool, no `runIn`; the only thread in the engine is the **sandbox** that runs untrusted user-function code. Handlers register per process: pass `handler:'<name>'` (named registry), `module:{path,export}`, or — for internal features — a closure paired with a reconstructible `quantum` (see [Registering a processor](#registering-a-processor)).
24
24
 
25
- | mode | cardinality | cursor | use when |
26
- | -------- | ----------------------------------- | --------------------------- | ---------------------------------------------------------------------------------------------- |
27
- | `inline` | every writer, inside commit | — | derived state must be consistent the instant the write returns, and the work is cheap |
28
- | `single` | exactly one claimant topology-wide | durable (at-least-once) | background derived work drained on the loop; the lease makes it 1-of-N across processes |
29
- | `fanout` | every registered instance, own loop | ephemeral (resume-from-now) | N-of-N consumers: each instance runs its own copy, effects must be process-local or convergent |
25
+ The public vocabulary is two options: **`mode ∈ {'sync', 'async'}`** (timing) and, for `async` only, **`distribution ∈ {'single', 'fanout'}`**. They resolve to one of three internal tokens, which is what `status().mode` reports:
30
26
 
31
- > **Deprecated aliases.** `single` and `fanout` were previously named `worker` and `async` (released in 1.8.x). The old names still work as **deprecated aliases** — `register()`/`setMode()` accept them and map to the canonical names, warning once per process. `stop.status().mode` always reports the canonical `single`/`fanout`/`inline`.
27
+ | `mode` / `distribution` | status token | cardinality | cursor | use when |
28
+ | ------------------------------------------------------ | ------------ | ----------------------------------- | --------------------------- | ---------------------------------------------------------------------------------------------- |
29
+ | `'sync'` | `inline` | every writer, inside commit | — | derived state must be consistent the instant the write returns, and the work is cheap |
30
+ | `'async'` (default), `distribution:'single'` (default) | `single` | exactly one claimant topology-wide | durable (at-least-once) | background derived work drained on the loop; the lease makes it 1-of-N across processes |
31
+ | `'async'`, `distribution:'fanout'` | `fanout` | every registered instance, own loop | ephemeral (resume-from-now) | N-of-N consumers: each instance runs its own copy, effects must be process-local or convergent |
32
+
33
+ Omitting `mode` is `{mode:'async', distribution:'single'}`. `distribution` without an explicit `mode`, or with `mode:'sync'`, throws.
34
+
35
+ > **Deprecated aliases.** The single-string names `'inline'`, `'single'`, `'worker'` (pre-2.0 name for `single`) and `'fanout'` still work — `register()`/`setMode()` map them to the canonical pair, warning once per process; combining one with `distribution` throws. **Bare `'async'` is not an alias:** in 1.8.x it meant fanout, but it is now the canonical timing name and resolves to `{async, single}` (1-of-N) — a one-time log flags the change. Old fanout callers must pass `distribution:'fanout'`.
32
36
 
33
37
  **Cardinality contracts:**
34
38
 
35
39
  - `single` (1-of-N): a cluster-wide lease ensures exactly one process drains the log at a time. Others wait and take over if the holder dies. Use for derived state that must have a single authoritative writer. The drain runs on the holder's main loop, chunked; the cursor advances only on a successful drain (at-least-once → write idempotent handlers).
36
40
  - `fanout` (N-of-N): no lease; every registered instance runs independently from its own in-memory cursor (seeded to "now" at registration — no history replay on restart). Use for process-local derived state, or idempotent/convergent effects. `bootstrap` is always `'none'` — fanout processors do not run snapshot bootstraps.
37
- - `inline` (every writer): runs synchronously inside the commit. **M3 closure advisory**: a plain-closure inline handler is fine for a single writer process, but with multiple writer processes (HTTP cluster workers, fn runners, workers) other instances' writes silently bypass it — `register()` warns once. Declare `definition: { durable: true }` (your code reconstructs the handler on every instance at open — the views/indexes pattern) to silence it. `setMode(…, 'inline')` — which actively creates the multi-writer hazard — hard-rejects plain closures (`PROC_INLINE_REQUIRES_DURABLE_DEFINITION`).
41
+ - `inline` (every writer): runs synchronously inside the commit. A handler registered here must exist on **every** writer process (HTTP cluster workers, fn runners, peer nodes) or their writes silently bypass it. Named and module handlers are reconstructible by construction. A closure is accepted only with `definition: { durable: true }` — your code promises to re-register it on every instance at open (the views/indexes pattern). `setMode(…, 'inline')` re-checks this and rejects a closure without it (`PROC_INLINE_REQUIRES_DURABLE_DEFINITION`).
38
42
 
39
43
  ---
40
44
 
41
45
  ## Registering a processor
42
46
 
43
47
  ```javascript
48
+ // ./order-stats.js
49
+ exports.apply = async (ctx, changes, info) => {
50
+ // ctx = { env, payload } info = { mode, type, fromClock, toClock }
51
+ for (const c of changes) {
52
+ // c.type, c.key, c.action ('put' | 'remove' | schema actions such as 'registerType'), c.clock, c.value?
53
+ }
54
+ };
55
+
56
+ // registration
44
57
  const stop = env.processor.register('Order', {
45
- mode: 'fanout',
58
+ mode: 'async', // default; distribution defaults to 'single'
46
59
  name: 'order-stats', // shown in admin / status
47
60
  cursorKey: 'order-stats', // durable resume key — unique per processor
48
- originMode: 'all', // 'self' | 'remote' | 'all'
49
- handler: async (changes, info) => {
50
- for (const c of changes) {
51
- // c.type, c.key, c.action ('put' | 'remove'), c.clock, c.value?
52
- }
53
- },
61
+ originMode: 'all', // 'self' (default) | 'remote' | 'all'
62
+ module: { path: require.resolve('./order-stats.js'), export: 'apply' },
63
+ payload: { bucket: 'daily' }, // optional — handed to the handler as ctx.payload
54
64
  });
55
65
 
56
66
  // Control surface:
@@ -58,13 +68,21 @@ await stop(); // unregister + release the lease
58
68
  stop.status(); // live status { state, lastClock, lag, mode, ... }
59
69
  stop.pause();
60
70
  stop.resume();
71
+ stop.retry();
72
+ stop.kick(); // schedule a drain now
73
+ await stop.awaitIdle();
61
74
  ```
62
75
 
63
- The `handler` is always a **closure** (a function). The portable `handler: {module, export}` form — which ran on a worker thread — was removed alongside the worker-thread executor; passing it now throws. Move shared handler logic into a module your closure calls (`const apply = require('./my-handler'); handler: (changes, info) => apply(changes, info)`) if you want to reuse it across registrations.
76
+ The handler must be **reconstructible by any process**, so it is named, not passed as a bare closure. Exactly one of:
77
+
78
+ - `module: { path, export }` — a file `require()`d by the registering process (`export` defaults to `'process'`, then the module's default export).
79
+ - `handler: '<name>'` — a function registered in-process with `OKDBProcessor.registerHandler(name, fn)` (the class from `src/runtime/okdb-processor.js`; it is not re-exported from the package root).
80
+
81
+ Both are called as `fn(ctx, changes, info)`. A bare closure (`handler: async (changes) => …`) **throws** `processor: closure handlers are not accepted`. Closures are only accepted on internal paths — paired with a `quantum` (FTS, time machine, materializer) or with `definition: { durable: true }` (inline index/view processors) — and are called with the legacy `(changes, info)` signature.
64
82
 
65
- `changes` are change-log records (`{ type, key, action, clock, ... }`). With the default `hydrateValues: true`, `put` records also carry `.value` (the current document); otherwise read the document via `info.env.get(c.type, c.key)`.
83
+ `changes` are change-log records (`{ type, key, action, clock, origin, ... }`). With the default `hydrateValues: true`, `put` records also carry `.value` (the current document); otherwise read the document via `ctx.env.get(c.type, c.key)`.
66
84
 
67
- `originMode` filters by who wrote the change: `self` (this instance's writes only), `remote` (other instances/processes), or `all`.
85
+ `originMode` filters by who wrote the change (compared to the change's `origin`, the writing store's identity — shared by every process on the same path): `self` (default — this store's writes, including a cloned store's history from before the copy), `remote` (writes synced in from other stores), or `all`. It applies on every delivery path — inline, async live drains, log replay and the snapshot bootstrap (which judges each doc by its latest change). A drain chunk whose changes are all filtered out is not delivered, and the cursor still moves past it. A `quantum` module receives the mode as `payload.originMode` and applies it itself with `filterByOrigin` (`src/runtime/okdb-processor-origin.js`), as the built-in quanta do. Async processors with `remote`/`all` also wake on cross-process writes via the bus.
68
86
 
69
87
  **`rebuild` (snapshot-bootstrap processors).** With `bootstrap: 'snapshot'` you may pass `rebuild: async () => { ... }` — a feature-owned **full rebuild** (scan the actual docs, then reposition the cursor via `setCursor` + `markSnapshotComplete`). It runs whenever the processor bootstraps with an **un-positioned cursor**: after a cursor reset (the admin ⟲ "full reprocess"), or when a build handoff was interrupted by a crash. Without it, the framework's only option is replaying the changelog from 0 — which is **not** a rebuild: sync-GC prunes the changelog (its horizon ignores processor cursors), so replay-from-0 can silently yield a partial derived store. FTS registers one (re-scans all docs of the type into every index, clearing first).
70
88
 
@@ -92,15 +110,15 @@ Cross-process wakes ride the UDP bus (`SYSTEM_POKE`), which is lossy by design.
92
110
 
93
111
  ## Cookbook
94
112
 
95
- - **A background derived indexer (like FTS)** — `mode: 'single'`, closure handler, drained on the loop in chunked quanta.
96
- - **An immediate-consistency derived field** — `mode: 'inline'` (cheap work only; it runs on the write path).
97
- - **A light aggregate on the main loop** — `mode: 'fanout'`.
113
+ - **A background derived indexer (like FTS)** — `mode: 'async'` (distribution `single`), module or named handler, drained on the loop in chunked quanta.
114
+ - **An immediate-consistency derived field** — `mode: 'sync'` (cheap work only; it runs on the write path).
115
+ - **A per-process cache / light aggregate on each process's loop** — `mode: 'async', distribution: 'fanout'`.
98
116
 
99
117
  ---
100
118
 
101
119
  ## Runtime mode switching (M6)
102
120
 
103
- `env.processor.setMode(logicalKey, mode)` (HTTP: `POST /api/processors/:logicalKey/mode`)
121
+ `env.processor.setMode(logicalKey, mode, distribution?)` (HTTP: `POST /api/processors/:logicalKey/mode`)
104
122
  switches a processor's mode at runtime through a durable config record (registry
105
123
  desired-state scope `'procmode'`) + a clock-boundary handoff:
106
124