@kedem/okdb 2.7.1 → 3.0.1

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 (69) hide show
  1. package/CHANGELOG.md +111 -33
  2. package/README.md +68 -36
  3. package/bin/okdb +2 -0
  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 +78 -35
  8. package/docs/data-model.md +32 -8
  9. package/docs/deployment.md +42 -38
  10. package/docs/diagnostics.md +61 -125
  11. package/docs/embeddings.md +143 -51
  12. package/docs/files.md +53 -18
  13. package/docs/fts.md +48 -23
  14. package/docs/functions.md +107 -56
  15. package/docs/getting-started.md +125 -9
  16. package/docs/http-api.md +68 -11
  17. package/docs/http-cluster.md +80 -88
  18. package/docs/index.md +33 -15
  19. package/docs/indexes.md +53 -17
  20. package/docs/licensing.md +18 -4
  21. package/docs/logging.md +11 -22
  22. package/docs/manifest.json +4 -2
  23. package/docs/migration.md +40 -15
  24. package/docs/pipelines.md +96 -32
  25. package/docs/plugins.md +47 -15
  26. package/docs/process-registry.md +23 -24
  27. package/docs/processors.md +26 -23
  28. package/docs/querying.md +102 -29
  29. package/docs/queue.md +167 -51
  30. package/docs/resolved-fields.md +24 -1
  31. package/docs/subscriptions.md +4 -4
  32. package/docs/sync.md +9 -6
  33. package/docs/time-machine.md +40 -11
  34. package/docs/transactions.md +63 -15
  35. package/docs/ttl.md +34 -13
  36. package/docs/upgrade-2.0.md +32 -15
  37. package/docs/upgrade-2.1.md +10 -12
  38. package/docs/upgrade-3.0.md +144 -0
  39. package/docs/views.md +131 -42
  40. package/index.js +1 -0
  41. package/native/linux-x64-gnu/okdb +0 -0
  42. package/native/linux-x64-gnu/okdb-node.linux-x64-gnu.node +0 -0
  43. package/native-loader.d.ts +20 -0
  44. package/native-loader.js +1 -0
  45. package/okdb-native.js +1 -0
  46. package/package.json +27 -14
  47. package/types/environment.d.ts +32 -11
  48. package/types/errors.d.ts +20 -0
  49. package/types/features/admin.d.ts +3 -5
  50. package/types/features/api.d.ts +5 -7
  51. package/types/features/embeddings.d.ts +8 -7
  52. package/types/features/engines.d.ts +9 -1
  53. package/types/features/files.d.ts +2 -1
  54. package/types/features/fts.d.ts +3 -3
  55. package/types/features/functions.d.ts +14 -8
  56. package/types/features/pipelines.d.ts +10 -10
  57. package/types/features/queue.d.ts +15 -10
  58. package/types/features/sync.d.ts +7 -0
  59. package/types/features/time-machine.d.ts +3 -0
  60. package/types/index.d.ts +3 -0
  61. package/types/okdb.d.ts +70 -7
  62. package/types/options.d.ts +12 -8
  63. package/algorithm-worker-thread.js +0 -1
  64. package/bin/okdb.js +0 -2
  65. package/docs/OKDB-ARCHITECTURE.md +0 -1061
  66. package/okdb-functions-sandbox-worker.js +0 -1
  67. package/okdb-http-worker-child.js +0 -1
  68. package/okdb-views-bootstrap-worker.js +0 -1
  69. package/okdb.js +0 -1
package/docs/indexes.md CHANGED
@@ -7,6 +7,10 @@ Secondary indexes let you scan records by field values without touching every re
7
7
  ## Registering an index
8
8
 
9
9
  ```javascript
10
+ await okdb.registerType('articles');
11
+ await okdb.registerType('users');
12
+ await okdb.registerType('places');
13
+
10
14
  // Single field
11
15
  await okdb.registerIndex('articles', ['author']);
12
16
 
@@ -44,12 +48,16 @@ That means the correct field path is usually `location`, not `location.lat` + `l
44
48
 
45
49
  Indexes build **asynchronously** from existing data after registration. Writes during the build are tracked and the index converges to READY. To wait for completion:
46
50
 
51
+ <!-- continues -->
52
+
47
53
  ```javascript
48
54
  await okdb.indexReady('articles', ['author', 'publishedAt']);
49
55
  ```
50
56
 
51
57
  Check status without waiting:
52
58
 
59
+ <!-- continues -->
60
+
53
61
  ```javascript
54
62
  okdb.getIndexStatus('articles', ['author']);
55
63
  // → 'creating' | 'resetting' | 'waiting' | 'ready' | 'dropping' | 'error'
@@ -60,11 +68,13 @@ okdb.getIndexStatus('articles', ['author']);
60
68
 
61
69
  ## Dropping an index
62
70
 
71
+ <!-- continues -->
72
+
63
73
  ```javascript
64
74
  await okdb.dropIndex('articles', ['author', 'publishedAt']);
65
75
  ```
66
76
 
67
- The index sub-database is deleted. Existing query code that references it will throw `OKDBIndexNotRegisteredError`.
77
+ The index sub-database is deleted. Existing query code that references it will throw an error with `code: 'INDEX_NOT_REGISTERED'` (`name: 'OKDBIndexNotRegisteredError'`).
68
78
 
69
79
  ---
70
80
 
@@ -87,17 +97,21 @@ You rarely need to deal with index names directly — all API methods accept `st
87
97
  A composite index orders records by the first field, then the second within ties, and so on. This mirrors SQL's multi-column index semantics.
88
98
 
89
99
  ```javascript
100
+ await okdb.registerType('orders');
90
101
  await okdb.registerIndex('orders', ['customerId', 'createdAt']);
102
+ await okdb.put('orders', 'o1', { customerId: 'c42', createdAt: Date.now() });
91
103
 
92
104
  // All orders by customer 'c42', newest first
93
105
  for (const { key, value } of okdb.byIndex('orders', ['customerId', 'createdAt'], {
94
- prefix: ['c42'],
106
+ prefix: ['c42'],
95
107
  reverse: true,
96
- limit: 50,
97
- })) { ... }
108
+ limit: 50,
109
+ })) {
110
+ console.log(key, value.createdAt);
111
+ }
98
112
  ```
99
113
 
100
- The trailing `null` sentinel in the LMDB key format ensures that a prefix scan on `['c42']` correctly returns all entries for that customer regardless of their `createdAt` value.
114
+ A prefix scan on `['c42']` returns all entries for that customer regardless of their `createdAt` value.
101
115
 
102
116
  ---
103
117
 
@@ -106,6 +120,7 @@ The trailing `null` sentinel in the LMDB key format ensures that a prefix scan o
106
120
  `countByIndex` counts matching index entries without touching the data store. It takes `start`/`end` (end exclusive — hence the `HIGH_SENTINEL` bound below) or, equivalently, `prefix`:
107
121
 
108
122
  ```javascript
123
+ await okdb.registerType('orders');
109
124
  await okdb.registerIndex('orders', ['status']);
110
125
 
111
126
  const pending = okdb.countByIndex('orders', ['status'], {
@@ -119,6 +134,9 @@ const open = okdb.countByIndex('orders', ['status', 'createdAt'], {
119
134
  start: ['open'],
120
135
  end: ['open', OKDB.HIGH_SENTINEL],
121
136
  });
137
+
138
+ // Same count, prefix form
139
+ const open2 = okdb.countByIndex('orders', ['status', 'createdAt'], { prefix: ['open'] });
122
140
  ```
123
141
 
124
142
  ---
@@ -128,10 +146,14 @@ const open = okdb.countByIndex('orders', ['status', 'createdAt'], {
128
146
  Field paths can use dots to reach nested properties:
129
147
 
130
148
  ```javascript
149
+ await okdb.registerType('users');
131
150
  await okdb.registerIndex('users', ['address.city']);
151
+ await okdb.put('users', 'u1', { name: 'Ada', address: { city: 'Paris' } });
132
152
 
133
153
  // Records where address.city === 'Paris'
134
- for (const { key, value } of okdb.byIndex('users', ['address.city'], { prefix: ['Paris'] })) { ... }
154
+ for (const { key, value } of okdb.byIndex('users', ['address.city'], { prefix: ['Paris'] })) {
155
+ console.log(key, value.name);
156
+ }
135
157
  ```
136
158
 
137
159
  ---
@@ -141,10 +163,15 @@ for (const { key, value } of okdb.byIndex('users', ['address.city'], { prefix: [
141
163
  A unique index prevents two records from having the same value for the indexed fields.
142
164
 
143
165
  ```javascript
166
+ await okdb.registerType('users');
144
167
  await okdb.registerIndex('users', ['email'], { unique: true });
168
+ await okdb.put('users', 'user-1', { email: 'alice@example.com' });
145
169
 
146
- // This will throw OKDBUniqueConstraintError:
147
- await okdb.put('users', 'user-2', { email: 'alice@example.com' }); // if 'alice@example.com' already exists
170
+ try {
171
+ await okdb.put('users', 'user-2', { email: 'alice@example.com' });
172
+ } catch (err) {
173
+ console.log(err.code); // 'UNIQUE_CONSTRAINT' (name: 'OKDBUniqueConstraintError')
174
+ }
148
175
  ```
149
176
 
150
177
  ### Sync conflicts
@@ -155,14 +182,16 @@ When a duplicate arrives via sync (from another node), OKDB doesn't reject it
155
182
 
156
183
  Violations are stored locally (not synced) and resolve automatically when the losing record is removed or updated.
157
184
 
185
+ <!-- continues -->
186
+
158
187
  ```javascript
159
- // List all violations for a type
188
+ // List all violations for a type (optionally for one index: getUniqueViolations('users', ['email']))
160
189
  const violations = okdb.getUniqueViolations('users');
161
190
 
162
191
  // Check if any violations exist for a specific index
163
192
  const hasProb = okdb.hasUniqueViolations('users', ['email']);
164
193
 
165
- // Get a specific violation
194
+ // Get a specific violation (null when there is none)
166
195
  const v = okdb.getUniqueViolation('users', ['email'], 'alice@example.com');
167
196
  // v = { winner, entries, count, detectedAt, ... }
168
197
  ```
@@ -170,12 +199,16 @@ const v = okdb.getUniqueViolation('users', ['email'], 'alice@example.com');
170
199
  Events emitted:
171
200
 
172
201
  ```javascript
173
- okdb.events.on('unique:violation', ({ type, index, indexKey, winner }) => { ... });
174
- okdb.events.on('unique:violation_resolved', ({ type, index, indexKey }) => { ... });
202
+ okdb.events.on('unique:violation', ({ type, index, indexKey, winner }) => {
203
+ console.log('duplicate', type, index, indexKey, 'winner:', winner);
204
+ });
205
+ okdb.events.on('unique:violation_resolved', ({ type, index, indexKey }) => {
206
+ console.log('resolved', type, index, indexKey);
207
+ });
175
208
  ```
176
209
 
177
210
  :::note
178
- Geo indexes cannot be unique. Geohash collisions make uniqueness semantics undefined — the registration will throw.
211
+ Geo indexes cannot be unique. Geohash collisions make uniqueness semantics undefined — the registration throws `INVALID_INDEX_OPTIONS`.
179
212
  :::
180
213
 
181
214
  ---
@@ -185,17 +218,20 @@ Geo indexes cannot be unique. Geohash collisions make uniqueness semantics undef
185
218
  Geospatial indexes use geohash encoding to map `{ lat, lon }` coordinates into a lexicographically ordered string space.
186
219
 
187
220
  ```javascript
221
+ await okdb.registerType('restaurants');
188
222
  await okdb.registerIndex('restaurants', ['coords'], { type: 'geo', precision: 7 });
189
223
 
190
224
  await okdb.put('restaurants', 'r1', { name: 'Le Bistro', coords: { lat: 48.87, lon: 2.31 } });
191
225
 
192
226
  // Radius search
193
227
  const results = okdb.geoQuery('restaurants', 'coords', {
194
- lat: 48.87,
195
- lon: 2.31,
196
- radius: 1000, // metres
228
+ lat: 48.87,
229
+ lon: 2.31,
230
+ radius: 1000, // metres
197
231
  });
198
- for (const { key, value, distance } of results) { ... }
232
+ for (const { key, value, distance } of results) {
233
+ console.log(key, value.name, distance);
234
+ }
199
235
  ```
200
236
 
201
237
  **Precision guide:**
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
+ <!-- not-runnable: needs 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
 
@@ -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.
@@ -38,13 +38,15 @@
38
38
  { "file": "http-cluster.md", "label": "HTTP Clustering" },
39
39
  { "file": "process-registry.md", "label": "Process Registry" },
40
40
  { "file": "plugins.md", "label": "Plugins" },
41
+ { "file": "c-bridge.md", "label": "C Bridge" },
41
42
  { "file": "processors.md", "label": "Processors (modes & registration)" },
42
43
  { "file": "licensing.md", "label": "Licensing" },
43
44
  { "file": "logging.md", "label": "Logging" },
44
45
  { "file": "diagnostics.md", "label": "Diagnostics" },
45
46
  { "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" }
47
+ { "file": "upgrade-3.0.md", "label": "Upgrading to 3.0" },
48
+ { "file": "upgrade-2.0.md", "label": "Upgrading to 2.0 (history)" },
49
+ { "file": "upgrade-2.1.md", "label": "Upgrading to 2.1 (history)" }
48
50
  ]
49
51
  }
50
52
  ]
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
 
@@ -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'));