@kedem/okdb 3.0.0 → 3.1.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 (64) hide show
  1. package/CHANGELOG.md +114 -3
  2. package/README.md +72 -36
  3. package/bin/okdb +1 -1
  4. package/docs/auth-and-sync.md +30 -24
  5. package/docs/auth-permissions.md +5 -4
  6. package/docs/c-bridge.md +94 -0
  7. package/docs/change-log.md +79 -36
  8. package/docs/data-model.md +35 -9
  9. package/docs/deployment.md +42 -38
  10. package/docs/diagnostics.md +61 -125
  11. package/docs/embeddings.md +143 -51
  12. package/docs/encryption.md +132 -0
  13. package/docs/files.md +64 -27
  14. package/docs/fts.md +48 -23
  15. package/docs/functions.md +109 -56
  16. package/docs/getting-started.md +121 -9
  17. package/docs/http-api.md +66 -11
  18. package/docs/http-cluster.md +80 -88
  19. package/docs/index.md +33 -15
  20. package/docs/indexes.md +53 -17
  21. package/docs/licensing.md +19 -5
  22. package/docs/logging.md +11 -22
  23. package/docs/manifest.json +6 -3
  24. package/docs/migration.md +41 -16
  25. package/docs/pipelines.md +111 -46
  26. package/docs/plugins.md +47 -15
  27. package/docs/process-registry.md +23 -24
  28. package/docs/processors.md +26 -23
  29. package/docs/querying.md +102 -29
  30. package/docs/queue.md +165 -51
  31. package/docs/resolved-fields.md +24 -1
  32. package/docs/subscriptions.md +4 -4
  33. package/docs/sync.md +9 -6
  34. package/docs/time-machine.md +52 -14
  35. package/docs/transactions.md +63 -15
  36. package/docs/ttl.md +34 -13
  37. package/docs/upgrade-2.0.md +32 -15
  38. package/docs/upgrade-2.1.md +10 -12
  39. package/docs/upgrade-3.0.md +144 -0
  40. package/docs/views.md +165 -61
  41. package/index.js +1 -1
  42. package/native/linux-x64-gnu/okdb +0 -0
  43. package/native/linux-x64-gnu/okdb-node.linux-x64-gnu.node +0 -0
  44. package/native-loader.js +1 -1
  45. package/okdb-native.js +1 -1
  46. package/package.json +1 -1
  47. package/public/features/files/parts/files-blob-status.ok.js +1 -1
  48. package/types/environment.d.ts +32 -11
  49. package/types/errors.d.ts +20 -0
  50. package/types/features/admin.d.ts +3 -5
  51. package/types/features/api.d.ts +5 -7
  52. package/types/features/embeddings.d.ts +8 -7
  53. package/types/features/engines.d.ts +9 -1
  54. package/types/features/files.d.ts +2 -1
  55. package/types/features/fts.d.ts +3 -3
  56. package/types/features/functions.d.ts +14 -8
  57. package/types/features/pipelines.d.ts +10 -10
  58. package/types/features/queue.d.ts +15 -10
  59. package/types/features/sync.d.ts +7 -0
  60. package/types/features/time-machine.d.ts +3 -0
  61. package/types/index.d.ts +3 -0
  62. package/types/okdb.d.ts +70 -7
  63. package/types/options.d.ts +12 -8
  64. package/docs/OKDB-ARCHITECTURE.md +0 -1061
package/docs/licensing.md CHANGED
@@ -29,10 +29,15 @@ With no license stored, OKDB applies the free tier:
29
29
  | Limit | Free tier |
30
30
  | ------------------------------ | --------- |
31
31
  | Environments (incl. `default`) | 5 |
32
- | Types per env | 10 |
32
+ | Types per env | 10 ¹ |
33
33
  | Embeddings pipelines per env | 2 |
34
34
  | Total writes | 1,000,000 |
35
35
 
36
+ ¹ A type okdb keeps for its own bookkeeping in each env counts toward this limit, so an env holds nine of your types before
37
+ `registerType` is refused.
38
+
39
+ The published `@kedem/okdb` package always enforces the tier: `db.licenses.effective().enforced` is `true`.
40
+
36
41
  The free tier is sized so an embedded code index (e.g. okcode: a management env plus one env per
37
42
  workspace, each with an embeddings pipeline) works out of the box for up to three workspaces,
38
43
  semantic search included. `embeddings` covers embeddings **pipelines** — their embedder, indexer
@@ -122,7 +127,7 @@ The list shows each license's status:
122
127
  | `wrong_node` | The activation belongs to a different node identity (see below) |
123
128
  | `invalid` | The blob is corrupt or not signed by the key this build trusts |
124
129
 
125
- `okdb serve` also prints a one-line license summary at startup (licensee and expiry, or the
130
+ The `okdb` server also prints a license summary at startup (licensee and expiry, or the
126
131
  current free-tier usage).
127
132
 
128
133
  ---
@@ -132,7 +137,10 @@ current free-tier usage).
132
137
  An embedded application installs its license with `db.licenses` (available after `open()`;
133
138
  calling it before throws `INVALID_STATE`):
134
139
 
140
+ <!-- licensed: a license file from your vendor -->
141
+
135
142
  ```js
143
+ const fs = require('node:fs');
136
144
  const db = new OKDB('./data');
137
145
  await db.open();
138
146
 
@@ -147,7 +155,7 @@ if (lic.needsActivation) {
147
155
 
148
156
  db.licenses.effective(); // { free, id, type, licensee, expiresAt, features, limits, enforced }
149
157
  db.licenses.list(); // every stored license, summarized
150
- await db.licenses.remove(id);
158
+ await db.licenses.remove(lic.id);
151
159
  ```
152
160
 
153
161
  - **Input**: `add()` takes the license text — a blob, an activation token (auto-detected), a
@@ -163,8 +171,14 @@ await db.licenses.remove(id);
163
171
  `LICENSE_ACTIVATION_INVALID`; a wrong argument shape throws `INVALID_INPUT`.
164
172
  - **Nothing sensitive leaves the store**: results are summaries (never the blob or token), and
165
173
  okdb never logs license or token content. The PIN is safe to share.
166
- - `effective().enforced` is `false` on dev builds, where features and limits are reported but
167
- not checked.
174
+ - `effective()` with no license stored reports the free tier:
175
+
176
+ ```js
177
+ const tier = db.licenses.effective();
178
+ // → { free: true, type: 'free', features: { fts: true, sync: false, ... },
179
+ // limits: { envs: 5, typesPerEnv: 10, ... }, enforced: true }
180
+ if (!tier.features.engines) console.log('engines need a license');
181
+ ```
168
182
 
169
183
  ### `OKDB_LICENSE_FILE`
170
184
 
package/docs/logging.md CHANGED
@@ -8,7 +8,7 @@ OKDB has a built-in structured logger available as `okdb.log`. Logs are emitted
8
8
 
9
9
  Every log call produces an entry with this shape:
10
10
 
11
- ```js
11
+ ```ts
12
12
  {
13
13
  level: 'info' | 'warn' | 'error' | 'debug',
14
14
  msg: string, // human-readable message
@@ -37,8 +37,8 @@ Every log call produces an entry with this shape:
37
37
  ```js
38
38
  okdb.log.info('server started', { port: 3000 });
39
39
  okdb.log.warn('slow query', { ms: 420, type: 'events' });
40
- okdb.log.error('unexpected failure', { err: err.message });
41
- okdb.log.debug('cache miss', { key });
40
+ okdb.log.error('unexpected failure', { err: 'connection reset' });
41
+ okdb.log.debug('cache miss', { key: 'user:42' });
42
42
  ```
43
43
 
44
44
  ---
@@ -59,7 +59,8 @@ envLog.info('env opened');
59
59
  // → { ..., meta: { feature: 'env', env: 'demo-places' }, ... }
60
60
 
61
61
  // Run-scoped child — created per function invocation
62
- const runLog = okdb.log.child({ feature: 'functions', env, fn, runId, runnerId });
62
+ const [envName, fn, runId, runnerId] = ['default', 'myFunction', 'abc123', 'fn-1'];
63
+ const runLog = okdb.log.child({ feature: 'functions', env: envName, fn, runId, runnerId });
63
64
  runLog.info('function invoked');
64
65
  runLog.info('result ready', { value: 42 });
65
66
  // → { ..., meta: { feature: 'functions', env, fn, runId, runnerId }, context: { value: 42 }, ts }
@@ -73,19 +74,15 @@ runLog.info('result ready', { value: 42 });
73
74
 
74
75
  ### `okdb.log.attach(fn)` — Custom Sink
75
76
 
76
- Attach a function to receive every log entry:
77
+ Attach a function to receive every log entry; call the returned function to detach it:
77
78
 
78
79
  ```js
79
- okdb.log.attach((entry) => {
80
+ const seen = [];
81
+ const detach = okdb.log.attach((entry) => {
80
82
  // entry: { level, msg, meta, context, ts }
81
- myExternalLogger.log(entry);
83
+ seen.push(entry); // forward to your own logger here
82
84
  });
83
- ```
84
-
85
- To detach, call the returned function:
86
-
87
- ```js
88
- const detach = okdb.log.attach(fn);
85
+ okdb.log.info('hello');
89
86
  detach();
90
87
  ```
91
88
 
@@ -99,14 +96,6 @@ okdb.events.on('log', (entry) => {
99
96
  });
100
97
  ```
101
98
 
102
- ### `okdb.logs` — Ring Buffer
103
-
104
- A circular buffer of recent log entries is available for inspection:
105
-
106
- ```js
107
- okdb.logs; // array of recent entries, newest last
108
- ```
109
-
110
99
  ### Persisted history — `GET /api/system/logs`
111
100
 
112
101
  Every non-debug entry is also written (batched, ≤1 commit/s) to the `~log` env's
@@ -129,6 +118,6 @@ callers still means "strictly older than this ts". `limit` defaults to 50, max 2
129
118
 
130
119
  ## `attachConsole()` — Console Output
131
120
 
132
- `okdb.log.attachConsole()` adds a human-readable console sink. It is called automatically when OKDB starts in development mode.
121
+ `okdb.log.attachConsole()` adds a human-readable console sink. Every instance attaches one at construction. Its threshold is the `OKDB_LOG_LEVEL` environment variable (`debug | info | warn | error`, default `info`); other sinks still receive every entry. The `okdb` CLI's console level is `--log-level` / `logLevel` in `.kdbconfig` / `OKDB_LOG_LEVEL`.
133
122
 
134
123
  Function-scoped logs (`meta.feature === 'functions'`) are suppressed from the console because they are stored in function run records and displayed in the Admin UI instead. All other features are printed.
@@ -9,7 +9,8 @@
9
9
  { "file": "querying.md", "label": "Querying" },
10
10
  { "file": "indexes.md", "label": "Indexes" },
11
11
  { "file": "transactions.md", "label": "Transactions" },
12
- { "file": "change-log.md", "label": "Change Log & Events" }
12
+ { "file": "change-log.md", "label": "Change Log & Events" },
13
+ { "file": "encryption.md", "label": "Encryption & Key Rotation" }
13
14
  ]
14
15
  },
15
16
  {
@@ -38,13 +39,15 @@
38
39
  { "file": "http-cluster.md", "label": "HTTP Clustering" },
39
40
  { "file": "process-registry.md", "label": "Process Registry" },
40
41
  { "file": "plugins.md", "label": "Plugins" },
42
+ { "file": "c-bridge.md", "label": "C Bridge" },
41
43
  { "file": "processors.md", "label": "Processors (modes & registration)" },
42
44
  { "file": "licensing.md", "label": "Licensing" },
43
45
  { "file": "logging.md", "label": "Logging" },
44
46
  { "file": "diagnostics.md", "label": "Diagnostics" },
45
47
  { "file": "migration.md", "label": "Migration" },
46
- { "file": "upgrade-2.0.md", "label": "Upgrading to 2.0" },
47
- { "file": "upgrade-2.1.md", "label": "Upgrading to 2.1" }
48
+ { "file": "upgrade-3.0.md", "label": "Upgrading to 3.0" },
49
+ { "file": "upgrade-2.0.md", "label": "Upgrading to 2.0 (history)" },
50
+ { "file": "upgrade-2.1.md", "label": "Upgrading to 2.1 (history)" }
48
51
  ]
49
52
  }
50
53
  ]
package/docs/migration.md CHANGED
@@ -19,7 +19,7 @@ const data = await okdb.migrate.export();
19
19
 
20
20
  Returns an object:
21
21
 
22
- ```javascript
22
+ ```text
23
23
  {
24
24
  types: {
25
25
  users: {
@@ -52,6 +52,10 @@ const data = await okdb.migrate.export({
52
52
  ### Export to JSON string
53
53
 
54
54
  ```javascript
55
+ const fs = require('node:fs');
56
+ await okdb.registerType('users');
57
+ await okdb.put('users', 'alice', { name: 'Alice', role: 'admin' });
58
+
55
59
  const json = await okdb.migrate.exportJSON({ pretty: true });
56
60
  fs.writeFileSync('./backup.json', json);
57
61
  ```
@@ -60,6 +64,8 @@ fs.writeFileSync('./backup.json', json);
60
64
 
61
65
  ## Import
62
66
 
67
+ <!-- continues -->
68
+
63
69
  ```javascript
64
70
  const data = JSON.parse(fs.readFileSync('./backup.json', 'utf8'));
65
71
  await okdb.migrate.import(data);
@@ -73,9 +79,11 @@ Import recreates all types, populates records with their exact versions (preserv
73
79
 
74
80
  ### Import from JSON string
75
81
 
82
+ <!-- continues -->
83
+
76
84
  ```javascript
77
- const json = fs.readFileSync('./backup.json', 'utf8');
78
- await okdb.migrate.importJSON(json);
85
+ const saved = fs.readFileSync('./backup.json', 'utf8');
86
+ await okdb.migrate.importJSON(saved);
79
87
  ```
80
88
 
81
89
  ---
@@ -136,21 +144,28 @@ console.log(`Rebuilt ref-counts for ${rebuilt} blobs`);
136
144
  ## Streaming export (NDJSON)
137
145
 
138
146
  ```javascript
147
+ const fs = require('node:fs');
148
+ await okdb.registerType('users');
149
+ await okdb.put('users', 'alice', { name: 'Alice' });
150
+
139
151
  await okdb.migrate.exportToFile('./export.ndjson', { envName: 'default', types: null, includeChanges: false });
152
+
153
+ const writable = fs.createWriteStream('./all.ndjson');
140
154
  await okdb.migrate.exportToStream(writable, { envName: 'default' }); // any Writable; you close it
141
155
  await okdb.migrate.exportEnvsToStream(writable, { envNames: null }); // every user env, one stream
156
+ writable.end();
157
+
142
158
  await okdb.migrate.importFromFile('./export.ndjson', { dropExisting: false, batchSize: 500 });
159
+ await okdb.migrate.importFromStream(fs.createReadStream('./export.ndjson'), { dropExisting: false });
143
160
  ```
144
161
 
145
162
  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.
163
+ **cooperative**: rows are read and written in 1 000-row chunks, the event loop gets a turn
164
+ between chunks, and `drain` is awaited whenever the stream's `write()` returns `false` — so a
165
+ large export never stalls the process and buffers about one chunk, however slow the consumer.
150
166
 
151
167
  **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
168
+ snapshot and released before the next chunk; the next chunk resumes
154
169
  strictly after the last exported key. So every key is exported at most once, a key that
155
170
  exists for the whole export is exported exactly once with the value it had when its chunk
156
171
  was read, and rows written concurrently may or may not appear. Different types (and chunks)
@@ -162,7 +177,7 @@ reflect different moments. For a point-in-time copy use [`backup()`](#hot-backup
162
177
  ## Hot backup and restore
163
178
 
164
179
  ```javascript
165
- const r = await okdb.migrate.backup('/backups/okdb-2026-09-24', { envNames: null, compact: true });
180
+ const r = await okdb.migrate.backup('./backups/okdb-2026-09-24', { envNames: null, compact: true });
166
181
  // r = { ok, dest, envs: [{ name, dest, sizeBefore, sizeAfter, timeMachine }], blobs: { count, bytes }, skipped, manifest }
167
182
  ```
168
183
 
@@ -180,7 +195,7 @@ overwrites. The result directory **is a store**: open OKDB on it (or on a copy o
180
195
  | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
181
196
  | 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
197
  | 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 |
198
+ | each env's file blobs (`<env>/~blobs/`) | file copy right **after** its env, 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
199
  | `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
200
 
186
201
  **What is not copied**
@@ -211,7 +226,9 @@ under the server's backup root — the `backup.root` constructor / config-file o
211
226
  relative to that root (default: a timestamped name); anything resolving outside it (`..`,
212
227
  another absolute path, a symlink pointing out) is refused with `400 BACKUP_PATH_OUTSIDE_ROOT`,
213
228
  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.
229
+ destructive (it can fill the server's disk), so MCP clients must confirm it. In-process,
230
+ `okdb.migrate.backupRoot()` returns the root and `okdb.migrate.resolveBackupDest(destDir)` applies
231
+ the same checks to a name.
215
232
 
216
233
  ```javascript
217
234
  new OKDB('/data/okdb', { backup: { root: '/mnt/backups/okdb' } });
@@ -228,8 +245,12 @@ match the same licence activation. Use `OKDB.clone()` whenever a copy must be a
228
245
  own — test templates, a staging copy, a backup brought up next to the original.
229
246
 
230
247
  ```javascript
231
- await OKDB.clone('/data/template', '/tmp/test-42'); // → { path, files, bytes, ms }
232
- const db = new OKDB('/tmp/test-42');
248
+ const template = new OKDB('./template'); // any closed store
249
+ await template.open();
250
+ await template.close();
251
+
252
+ await OKDB.clone('./template', './test-42'); // → { path, files, bytes, ms }
253
+ const db = new OKDB('./test-42');
233
254
  await db.open(); // the first open gives the copy its own identity
234
255
  db.id; // new UUID
235
256
  db.formerIds; // [ '<template id>' ]
@@ -237,8 +258,7 @@ db.formerIds; // [ '<template id>' ]
237
258
 
238
259
  - **The source must be closed** by every process. A copy of a running store is not consistent
239
260
  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)
261
+ open (detected from the LMDB file locks). For a store that must stay up, take a [hot backup](#hot-backup-and-restore)
242
262
  and re-identify it: `await db.migrate.backup(dir); OKDB.reidentify(dir)`.
243
263
  - `dstPath` must not exist or be empty (`CLONE_DEST_NOT_EMPTY`), and must not overlap the source.
244
264
  - **Everything is copied** — every env, `~fts`, time-machine history, `~vectors`, `~blobs`, views,
@@ -280,6 +300,9 @@ path, as after a restart.
280
300
  A version-independent alternative to the hot backup (slower; re-derives indexes on import):
281
301
 
282
302
  ```javascript
303
+ const fs = require('node:fs');
304
+ fs.mkdirSync('./backup', { recursive: true });
305
+
283
306
  // 1. Export type data
284
307
  const json = await okdb.migrate.exportJSON({ pretty: false });
285
308
  fs.writeFileSync('./backup/data.json', json);
@@ -292,6 +315,8 @@ console.log('Backup complete');
292
315
 
293
316
  Restore:
294
317
 
318
+ <!-- continues -->
319
+
295
320
  ```javascript
296
321
  // 1. Import type data
297
322
  await okdb.migrate.importJSON(fs.readFileSync('./backup/data.json', 'utf8'));