@dikolab/kbdb 0.1.6 → 0.2.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 (193) hide show
  1. package/README.md +30 -9
  2. package/dist/cli.cjs +181 -50
  3. package/dist/cli.cjs.map +3 -3
  4. package/dist/cli.mjs +181 -50
  5. package/dist/cli.mjs.map +3 -3
  6. package/dist/kbdb-worker.cjs +283 -29
  7. package/dist/kbdb-worker.cjs.map +4 -4
  8. package/dist/mod.cjs +13 -2
  9. package/dist/mod.cjs.map +2 -2
  10. package/dist/mod.mjs +13 -2
  11. package/dist/mod.mjs.map +2 -2
  12. package/dist/src/shared/cli/functions/format-output.function.d.ts +7 -7
  13. package/dist/src/shared/cli/functions/run-search.function.d.ts +25 -16
  14. package/dist/src/shared/cli/index.d.ts +1 -1
  15. package/dist/src/shared/cli/typings/cli-options.interface.d.ts +2 -0
  16. package/dist/src/shared/cli/typings/search-display.model.d.ts +25 -7
  17. package/dist/src/shared/mcp/functions/handle-recall.function.d.ts +29 -0
  18. package/dist/src/shared/mcp/typings/mcp-client.interface.d.ts +30 -11
  19. package/dist/src/shared/version/constants/version.constant.d.ts +1 -1
  20. package/dist/src/shared/wasm-codec/functions/decode-recall-result.function.d.ts +28 -0
  21. package/dist/src/shared/wasm-codec/functions/decode-scored-results.function.d.ts +14 -7
  22. package/dist/src/shared/wasm-codec/functions/encode-recall-params.function.d.ts +21 -0
  23. package/dist/src/shared/wasm-codec/functions/encode-search-params.function.d.ts +1 -1
  24. package/dist/src/shared/wasm-codec/index.d.ts +5 -2
  25. package/dist/src/shared/worker-client/classes/worker-client.class.d.ts +13 -3
  26. package/dist/src/shared/worker-client/index.d.ts +2 -1
  27. package/dist/src/shared/worker-client/typings/recall-result.model.d.ts +94 -0
  28. package/dist/src/shared/worker-client/typings/search-params.model.d.ts +2 -0
  29. package/dist/src/shared/worker-client/typings/search-result.model.d.ts +23 -7
  30. package/dist/src/shared/worker-daemon/classes/worker-daemon.class.d.ts +1 -0
  31. package/dist/wasm/fs-database/kbdb_fs_database.d.ts +18 -0
  32. package/dist/wasm/fs-database/kbdb_fs_database.js +30 -0
  33. package/dist/wasm/fs-database/kbdb_fs_database_bg.wasm +0 -0
  34. package/dist/wasm/fs-database/kbdb_fs_database_bg.wasm.d.ts +2 -0
  35. package/dist/wasm/kb-worker/kbdb_worker.d.ts +38 -0
  36. package/dist/wasm/kb-worker/kbdb_worker.js +56 -0
  37. package/dist/wasm/kb-worker/kbdb_worker_bg.wasm +0 -0
  38. package/dist/wasm/kb-worker/kbdb_worker_bg.wasm.d.ts +3 -0
  39. package/dist/worker.mjs +283 -29
  40. package/dist/worker.mjs.map +4 -4
  41. package/docs/details/README.md +26 -0
  42. package/docs/details/cli.md +608 -0
  43. package/docs/details/library-api.md +406 -0
  44. package/docs/details/mcp-server.md +430 -0
  45. package/docs/details/search-and-ranking.md +457 -0
  46. package/docs/details/storage.md +529 -0
  47. package/docs/goals/agents.md +751 -0
  48. package/docs/goals/architecture.svg +198 -0
  49. package/docs/goals/cli.md +2308 -0
  50. package/docs/goals/content-composer.md +609 -0
  51. package/docs/goals/content-parser.md +279 -0
  52. package/docs/goals/database.md +1452 -0
  53. package/docs/goals/document.md +368 -0
  54. package/docs/goals/mcp.md +1467 -0
  55. package/docs/goals/overview.md +124 -0
  56. package/docs/goals/query-parser.md +271 -0
  57. package/docs/goals/query-result.md +693 -0
  58. package/docs/goals/skills.md +738 -0
  59. package/docs/goals/worker-client.md +944 -0
  60. package/docs/goals/worker-daemon.md +1447 -0
  61. package/docs/modules/overview.md +298 -0
  62. package/docs/modules/rust/fs-database/functions/document.md +48 -0
  63. package/docs/modules/rust/fs-database/functions/integrity.md +68 -0
  64. package/docs/modules/rust/fs-database/functions/io.md +87 -0
  65. package/docs/modules/rust/fs-database/functions/module.md +22 -0
  66. package/docs/modules/rust/fs-database/functions/query-exec.md +44 -0
  67. package/docs/modules/rust/fs-database/functions/section.md +59 -0
  68. package/docs/modules/rust/fs-database/indexes/btree.md +35 -0
  69. package/docs/modules/rust/fs-database/indexes/corpus.md +61 -0
  70. package/docs/modules/rust/fs-database/indexes/inverted.md +60 -0
  71. package/docs/modules/rust/fs-database/indexes/module.md +64 -0
  72. package/docs/modules/rust/fs-database/indexes/positional.md +39 -0
  73. package/docs/modules/rust/fs-database/module.md +149 -0
  74. package/docs/modules/rust/fs-database/types/catalog.md +53 -0
  75. package/docs/modules/rust/fs-database/types/module.md +12 -0
  76. package/docs/modules/rust/fs-database/types/section.md +101 -0
  77. package/docs/modules/rust/kb-worker/functions/compose.md +57 -0
  78. package/docs/modules/rust/kb-worker/functions/module.md +20 -0
  79. package/docs/modules/rust/kb-worker/functions/retrieve.md +194 -0
  80. package/docs/modules/rust/kb-worker/functions/search.md +173 -0
  81. package/docs/modules/rust/kb-worker/functions/write.md +172 -0
  82. package/docs/modules/rust/kb-worker/module.md +171 -0
  83. package/docs/modules/rust/kb-worker/types/cache.md +90 -0
  84. package/docs/modules/rust/kb-worker/types/context.md +26 -0
  85. package/docs/modules/rust/kb-worker/types/module.md +16 -0
  86. package/docs/modules/rust/kb-worker/types/status.md +29 -0
  87. package/docs/modules/rust/kb-worker/types/token.md +50 -0
  88. package/docs/modules/rust/overview.md +495 -0
  89. package/docs/modules/rust/query-parser/functions/extract.md +56 -0
  90. package/docs/modules/rust/query-parser/functions/module.md +16 -0
  91. package/docs/modules/rust/query-parser/functions/parse.md +33 -0
  92. package/docs/modules/rust/query-parser/functions/pipeline.md +103 -0
  93. package/docs/modules/rust/query-parser/functions/rank.md +85 -0
  94. package/docs/modules/rust/query-parser/module.md +136 -0
  95. package/docs/modules/rust/query-parser/types/cache.md +39 -0
  96. package/docs/modules/rust/query-parser/types/keyphrase.md +60 -0
  97. package/docs/modules/rust/query-parser/types/module.md +17 -0
  98. package/docs/modules/rust/query-parser/types/token.md +42 -0
  99. package/docs/modules/rust/shared/content-composer/functions.md +114 -0
  100. package/docs/modules/rust/shared/content-composer/module.md +147 -0
  101. package/docs/modules/rust/shared/content-composer/types.md +93 -0
  102. package/docs/modules/rust/shared/content-parser/functions.md +72 -0
  103. package/docs/modules/rust/shared/content-parser/module.md +99 -0
  104. package/docs/modules/rust/shared/content-parser/types.md +71 -0
  105. package/docs/modules/rust/shared/corpus/module.md +24 -0
  106. package/docs/modules/rust/shared/corpus/types.md +141 -0
  107. package/docs/modules/rust/shared/document/module.md +25 -0
  108. package/docs/modules/rust/shared/document/types.md +154 -0
  109. package/docs/modules/rust/shared/encode/module.md +22 -0
  110. package/docs/modules/rust/shared/encode/traits.md +304 -0
  111. package/docs/modules/rust/shared/error/module.md +28 -0
  112. package/docs/modules/rust/shared/error/types.md +302 -0
  113. package/docs/modules/rust/shared/kbid/module.md +24 -0
  114. package/docs/modules/rust/shared/kbid/types.md +147 -0
  115. package/docs/modules/rust/shared/memory/functions.md +209 -0
  116. package/docs/modules/rust/shared/memory/module.md +24 -0
  117. package/docs/modules/rust/shared/module.md +168 -0
  118. package/docs/modules/rust/shared/query/module.md +27 -0
  119. package/docs/modules/rust/shared/query/types.md +236 -0
  120. package/docs/modules/rust/shared/section/module.md +25 -0
  121. package/docs/modules/rust/shared/section/types.md +294 -0
  122. package/docs/modules/rust/shared/term/module.md +25 -0
  123. package/docs/modules/rust/shared/term/types.md +139 -0
  124. package/docs/modules/typescript/cli.md +129 -0
  125. package/docs/modules/typescript/kbdb-worker.md +135 -0
  126. package/docs/modules/typescript/overview.md +378 -0
  127. package/docs/modules/typescript/shared/cli/constants.md +23 -0
  128. package/docs/modules/typescript/shared/cli/functions.md +630 -0
  129. package/docs/modules/typescript/shared/cli/module.md +125 -0
  130. package/docs/modules/typescript/shared/cli/typings.md +172 -0
  131. package/docs/modules/typescript/shared/hash/functions.md +20 -0
  132. package/docs/modules/typescript/shared/hash/module.md +21 -0
  133. package/docs/modules/typescript/shared/mcp/classes.md +179 -0
  134. package/docs/modules/typescript/shared/mcp/functions.md +386 -0
  135. package/docs/modules/typescript/shared/mcp/module.md +160 -0
  136. package/docs/modules/typescript/shared/mcp/typings.md +522 -0
  137. package/docs/modules/typescript/shared/module.md +94 -0
  138. package/docs/modules/typescript/shared/platform/functions.md +42 -0
  139. package/docs/modules/typescript/shared/platform/module.md +25 -0
  140. package/docs/modules/typescript/shared/runtime/functions.md +26 -0
  141. package/docs/modules/typescript/shared/runtime/module.md +27 -0
  142. package/docs/modules/typescript/shared/runtime/typings.md +13 -0
  143. package/docs/modules/typescript/shared/version/module.md +27 -0
  144. package/docs/modules/typescript/shared/wasm-codec/functions.md +391 -0
  145. package/docs/modules/typescript/shared/wasm-codec/module.md +98 -0
  146. package/docs/modules/typescript/shared/worker-client/classes.md +264 -0
  147. package/docs/modules/typescript/shared/worker-client/functions.md +175 -0
  148. package/docs/modules/typescript/shared/worker-client/module.md +84 -0
  149. package/docs/modules/typescript/shared/worker-client/typings.md +508 -0
  150. package/docs/modules/typescript/shared/worker-daemon/classes.md +239 -0
  151. package/docs/modules/typescript/shared/worker-daemon/constants.md +37 -0
  152. package/docs/modules/typescript/shared/worker-daemon/functions.md +221 -0
  153. package/docs/modules/typescript/shared/worker-daemon/module.md +112 -0
  154. package/docs/modules/typescript/shared/worker-daemon/typings.md +126 -0
  155. package/docs/overview.md +188 -0
  156. package/docs/release-notes/0.1.0.md +189 -0
  157. package/docs/release-notes/0.1.1.md +46 -0
  158. package/docs/release-notes/0.1.2.md +38 -0
  159. package/docs/release-notes/0.1.3.md +42 -0
  160. package/docs/release-notes/0.2.0.md +147 -0
  161. package/docs/release-notes/README.md +9 -0
  162. package/package.json +8 -2
  163. package/src/shared/cli/functions/dispatch-command.function.ts +3 -3
  164. package/src/shared/cli/functions/format-output.function.ts +41 -34
  165. package/src/shared/cli/functions/parse-args.function.ts +7 -0
  166. package/src/shared/cli/functions/run-search.function.ts +53 -27
  167. package/src/shared/cli/index.ts +4 -1
  168. package/src/shared/cli/typings/cli-options.interface.ts +2 -0
  169. package/src/shared/cli/typings/search-display.model.ts +26 -7
  170. package/src/shared/mcp/functions/create-tool-definitions.function.ts +64 -4
  171. package/src/shared/mcp/functions/handle-recall.function.ts +66 -0
  172. package/src/shared/mcp/functions/handle-tool-call.function.ts +11 -1
  173. package/src/shared/mcp/typings/mcp-client.interface.ts +33 -15
  174. package/src/shared/version/constants/version.constant.ts +1 -1
  175. package/src/shared/wasm-codec/functions/decode-recall-result.function.ts +267 -0
  176. package/src/shared/wasm-codec/functions/decode-scored-results.function.ts +81 -27
  177. package/src/shared/wasm-codec/functions/encode-recall-params.function.ts +68 -0
  178. package/src/shared/wasm-codec/functions/encode-search-params.function.ts +4 -1
  179. package/src/shared/wasm-codec/index.ts +11 -3
  180. package/src/shared/worker-client/classes/worker-client.class.ts +24 -4
  181. package/src/shared/worker-client/index.ts +11 -1
  182. package/src/shared/worker-client/typings/recall-result.model.ts +98 -0
  183. package/src/shared/worker-client/typings/search-params.model.ts +2 -0
  184. package/src/shared/worker-client/typings/search-result.model.ts +24 -7
  185. package/src/shared/worker-daemon/classes/worker-daemon.class.ts +25 -4
  186. package/src/wasm/fs-database/kbdb_fs_database.d.ts +18 -0
  187. package/src/wasm/fs-database/kbdb_fs_database.js +30 -0
  188. package/src/wasm/fs-database/kbdb_fs_database_bg.wasm +0 -0
  189. package/src/wasm/fs-database/kbdb_fs_database_bg.wasm.d.ts +2 -0
  190. package/src/wasm/kb-worker/kbdb_worker.d.ts +38 -0
  191. package/src/wasm/kb-worker/kbdb_worker.js +56 -0
  192. package/src/wasm/kb-worker/kbdb_worker_bg.wasm +0 -0
  193. package/src/wasm/kb-worker/kbdb_worker_bg.wasm.d.ts +3 -0
@@ -0,0 +1,239 @@
1
+ # worker-daemon/classes -- WorkerDaemon
2
+
3
+ *Core daemon class that loads WASM modules, manages
4
+ the IPC server, routes requests, and handles lifecycle
5
+ (startup, idle tracking, graceful shutdown).*
6
+
7
+ ## Source
8
+
9
+ `src/shared/worker-daemon/classes/`
10
+
11
+ ## Classes
12
+
13
+ ### `WorkerDaemon`
14
+
15
+ **File:** `worker-daemon.class.ts`
16
+
17
+ The main daemon class. Orchestrates WASM module
18
+ loading, IPC server creation, request routing, idle
19
+ timeout tracking, and graceful shutdown.
20
+
21
+ #### Constructor
22
+
23
+ ```ts
24
+ class WorkerDaemon {
25
+ constructor(
26
+ ctx: string,
27
+ targetDir: string,
28
+ config: DaemonConfig,
29
+ wasmDir?: string,
30
+ );
31
+ }
32
+ ```
33
+
34
+ | Parameter | Type | Description |
35
+ |-------------|----------------|-------------------------|
36
+ | `ctx` | `string` | Context ID (16-hex) |
37
+ | `targetDir` | `string` | Absolute path to the |
38
+ | | | `.kbdb` directory |
39
+ | `config` | `DaemonConfig` | Parsed config from |
40
+ | | | `worker.toml` |
41
+ | `wasmDir` | `string?` | Path to WASM build |
42
+ | | | output directory |
43
+
44
+ #### Properties
45
+
46
+ | Property | Type | Description |
47
+ |-------------------|----------------|------------------------|
48
+ | `ctx` | `string` | Context ID |
49
+ | `targetDir` | `string` | Database directory |
50
+ | `config` | `DaemonConfig` | Daemon config |
51
+ | `connectionCount` | `number` | Active IPC connections |
52
+
53
+ #### Public Methods
54
+
55
+ ##### `checkPreconditions`
56
+
57
+ ```ts
58
+ checkPreconditions(): void;
59
+ ```
60
+
61
+ Validates startup preconditions before WASM module
62
+ loading. Checks that:
63
+
64
+ 1. Database directory exists.
65
+ 2. Directory is readable and writable.
66
+ 3. `catalog.toml` reports a compatible version.
67
+
68
+ Throws on any failure. `startDaemon` catches the
69
+ error, prints to stderr, and exits with code 1.
70
+
71
+ ##### `start`
72
+
73
+ ```ts
74
+ async start(): Promise<void>;
75
+ ```
76
+
77
+ Startup sequence:
78
+
79
+ 1. Calls `loadWasmModules(config, wasmDir)` to
80
+ compile and instantiate the WASM modules.
81
+ 2. Initializes the worker context.
82
+ 3. Writes the PID file (`kbdb-{ctx}.pid`) to the
83
+ OS temporary directory.
84
+ 4. Calls `createIpcServer(ipcPath, handler)` to
85
+ bind the IPC socket.
86
+ 5. Begins listening for connections and resets the
87
+ idle timer.
88
+
89
+ ##### `stop`
90
+
91
+ ```ts
92
+ stop(): void;
93
+ ```
94
+
95
+ Graceful shutdown sequence:
96
+
97
+ 1. Clears the idle timer.
98
+ 2. Stops accepting new connections.
99
+ 3. Purges WASM module references.
100
+ 4. Removes the PID file.
101
+ 5. Removes the IPC socket file.
102
+ 6. Calls `process.exit(0)`.
103
+
104
+ ##### `handleRequest`
105
+
106
+ ```ts
107
+ async handleRequest(
108
+ request: IpcRequest,
109
+ ): Promise<IpcResponse>;
110
+ ```
111
+
112
+ Handles a single JSON-RPC 2.0 request. Validates
113
+ context, resets the idle timer, routes to the
114
+ appropriate handler, and returns a response.
115
+ Requests whose `ctx` param does not match the
116
+ daemon's context ID are rejected with error
117
+ code `-32001`.
118
+
119
+ ##### `incrementConnections` / `decrementConnections`
120
+
121
+ ```ts
122
+ incrementConnections(): void;
123
+ decrementConnections(): void;
124
+ ```
125
+
126
+ Adjust the active connection count. Called by the
127
+ IPC server on connect/disconnect events.
128
+
129
+ ##### `injectModulesForTesting`
130
+
131
+ ```ts
132
+ injectModulesForTesting(modules: WasmModules): void;
133
+ ```
134
+
135
+ Injects pre-built WASM modules for unit testing.
136
+ Must not be called in production code.
137
+
138
+ #### Private Behavior
139
+
140
+ ##### Idle Timeout Tracking
141
+
142
+ The daemon maintains an internal idle timer. The
143
+ timer resets on every:
144
+
145
+ - Client connection.
146
+ - Client disconnection.
147
+ - IPC request received.
148
+
149
+ When the timer reaches `config.timeoutMs` with no
150
+ active connections, the daemon calls `stop()`.
151
+
152
+ ##### Connection Counting
153
+
154
+ Tracks the number of active client connections. The
155
+ daemon stays alive regardless of the idle timer as
156
+ long as at least one connection is open.
157
+
158
+ ##### Startup Preconditions
159
+
160
+ Before WASM modules are loaded, the daemon checks
161
+ three preconditions. Failure causes `startDaemon` to
162
+ print the error to stderr and exit with code 1:
163
+
164
+ 1. Database directory exists.
165
+ 2. Directory is readable and writable.
166
+ 3. `catalog.toml` version is compatible.
167
+
168
+ ##### Request Routing
169
+
170
+ Routes incoming JSON-RPC 2.0 requests. Daemon-state
171
+ methods are handled inline; all other methods are
172
+ looked up in `WASM_METHOD_MAP`:
173
+
174
+ | IPC Method | Handler / WASM Export |
175
+ |----------------------|--------------------------------|
176
+ | `status` | daemon state (busy/idle) |
177
+ | `idle_at` | last idle Unix timestamp |
178
+ | `config_{key}` | `DaemonConfig` property lookup |
179
+ | `checkVersion` | catalog version check |
180
+ | `search` | `worker_search` |
181
+ | `recall` | `worker_recall` |
182
+ | `addSection` | `worker_add_section` |
183
+ | `updateSection` | `worker_update_section` |
184
+ | `removeSection` | `worker_remove_section` |
185
+ | `readSections` | `worker_read_sections` |
186
+ | `groupSections` | `worker_group_sections` |
187
+ | `removeGrouping` | `worker_remove_grouping` |
188
+ | `retrieveDocument` | `worker_retrieve_doc` |
189
+ | `content` | `worker_compose` |
190
+ | `integrityCheck` | `worker_check_integrity` |
191
+ | `gc` | `worker_garbage_collect` |
192
+ | `rebuildIndexes` | `worker_rebuild_indexes` |
193
+ | `initDirectory` | `worker_init_directory` |
194
+ | `dbStatus` | `worker_status` |
195
+ | `invalidate` | `worker_invalidate` |
196
+ | `invalidateAll` | `worker_invalidate_all` |
197
+ | `get_result_status` | `worker_result_status` |
198
+ | `get_result` | `worker_get_result` |
199
+ | `query` | `worker_query` |
200
+ | `listByType` / `list_by_type` | `worker_list_by_type` |
201
+ | `listDocumentsByType` | `worker_list_docs_by_type` |
202
+
203
+ Snake_case aliases (`add_section`, `remove_section`,
204
+ etc.) are also accepted and map to the same exports.
205
+
206
+ ##### Context Validation
207
+
208
+ Every IPC request includes a `ctx` param. The daemon
209
+ validates it against its own context ID before
210
+ processing. Mismatches are rejected with JSON-RPC
211
+ error code `-32001` (context mismatch).
212
+
213
+ ##### `handleListByType(params)`
214
+
215
+ Handles `listByType` / `list_by_type` IPC requests.
216
+ Receives `{ ctx, sectionType }` and delegates to
217
+ `worker_list_by_type` in the WASM engine, which
218
+ scans the sections directory and returns all records
219
+ whose `type` field matches `sectionType`.
220
+
221
+ Returns: array of section records filtered by type.
222
+
223
+ ##### `handleListDocumentsByType(params)`
224
+
225
+ Handles `listDocumentsByType` IPC requests.
226
+ Receives `{ ctx, docType }` and delegates to
227
+ `worker_list_docs_by_type` in the WASM engine,
228
+ which scans the documents directory and returns all
229
+ manifests whose `type` field matches `docType`.
230
+
231
+ Returns: array of document manifests filtered by
232
+ type.
233
+
234
+ ## Testing
235
+
236
+ ```
237
+ src/shared/worker-daemon/
238
+ └── worker-daemon.spec.ts
239
+ ```
@@ -0,0 +1,37 @@
1
+ # worker-daemon/constants -- Daemon Defaults
2
+
3
+ *Default values for daemon configuration when
4
+ `worker.toml` is missing or incomplete.*
5
+
6
+ ## Source
7
+
8
+ `src/shared/worker-daemon/constants/`
9
+
10
+ ### `daemon-defaults`
11
+
12
+ **File:** `daemon-defaults.constant.ts`
13
+
14
+ ```ts
15
+ const DEFAULT_ITEM_LIMIT = 1000;
16
+ const DEFAULT_INDEX_LIMIT = 100;
17
+ const DEFAULT_TIMEOUT_MS = 300_000;
18
+ const DEFAULT_ITEM_TTL_MS = 60_000;
19
+ ```
20
+
21
+ | Constant | Value | Description |
22
+ |-----------------------|-----------|----------------|
23
+ | `DEFAULT_ITEM_LIMIT` | `1000` | Max content |
24
+ | | | objects held |
25
+ | | | in cache |
26
+ | `DEFAULT_INDEX_LIMIT` | `100` | Max index |
27
+ | | | segments held |
28
+ | | | in cache |
29
+ | `DEFAULT_TIMEOUT_MS` | `300000` | Daemon idle |
30
+ | | | timeout in ms |
31
+ | | | (5 minutes) |
32
+ | `DEFAULT_ITEM_TTL_MS` | `60000` | Per-item cache |
33
+ | | | TTL in ms |
34
+ | | | (1 minute) |
35
+
36
+ These constants are used by `readConfig()` to fill
37
+ missing keys when parsing `worker.toml`.
@@ -0,0 +1,221 @@
1
+ # worker-daemon/functions -- Daemon Functions
2
+
3
+ *Worker entry point, daemon entry point, host I/O
4
+ imports, WASM module loading, IPC server creation,
5
+ and configuration reading.*
6
+
7
+ ## Source
8
+
9
+ `src/shared/worker-daemon/functions/`
10
+
11
+ ## Functions
12
+
13
+ ### `runWorker`
14
+
15
+ **File:** `run-worker.function.ts`
16
+
17
+ Worker daemon entry point extracted from
18
+ `src/worker.ts`. Validates the context path argument,
19
+ resolves it to an absolute path, checks existence, and
20
+ delegates to `startDaemon`.
21
+
22
+ ```ts
23
+ async function runWorker(
24
+ argv: string[],
25
+ deps: WorkerDeps,
26
+ ): Promise<WorkerResult>;
27
+ ```
28
+
29
+ ```ts
30
+ interface WorkerDeps {
31
+ existsSync: (path: string) => boolean;
32
+ startDaemon: (
33
+ contextPath: string,
34
+ wasmDir?: string,
35
+ ) => Promise<void>;
36
+ wasmDir?: string;
37
+ }
38
+
39
+ interface WorkerResult {
40
+ error?: string;
41
+ exitCode: number;
42
+ }
43
+ ```
44
+
45
+ Returns a `WorkerResult` without touching process
46
+ globals, making it fully testable.
47
+
48
+ ### `startDaemon`
49
+
50
+ **File:** `start-daemon.function.ts`
51
+
52
+ Entry point for the daemon process. Called from
53
+ `runWorker` after path validation.
54
+
55
+ ```ts
56
+ async function startDaemon(
57
+ contextPath: string,
58
+ wasmDir?: string,
59
+ ): Promise<void>;
60
+ ```
61
+
62
+ 1. Calls `readConfig(contextPath)` to load
63
+ `worker.toml`.
64
+ 2. Computes the context ID from `contextPath`
65
+ (SHA-256 prefix, 16 hex characters).
66
+ 3. Creates a new `WorkerDaemon(ctx, contextPath,
67
+ config, wasmDir)`.
68
+ 4. Calls `daemon.checkPreconditions()`. Failures
69
+ are written to stderr and a crash log, then
70
+ `process.exit(1)` is called.
71
+ 5. Calls `daemon.start()`.
72
+ 6. Registers OS signal handlers (`SIGTERM`,
73
+ `SIGINT`) that call `daemon.stop()`.
74
+
75
+ ### `createHostImports`
76
+
77
+ **File:** `create-host-imports.function.ts`
78
+
79
+ Creates the host I/O import functions required by
80
+ `kb-worker.wasm`. All functions access WASM linear
81
+ memory through a deferred `MemoryRef` that is wired
82
+ up after module instantiation.
83
+
84
+ ```ts
85
+ function createHostImports(
86
+ contextPath: string,
87
+ memoryRef?: MemoryRef,
88
+ fs?: FsAdapter,
89
+ allocator?: AllocatorRef,
90
+ ): Record<string, WebAssembly.ImportValue>;
91
+ ```
92
+
93
+ | Parameter | Description |
94
+ |---------------|------------------------------------|
95
+ | `contextPath` | Absolute path to `.kbdb` directory |
96
+ | `memoryRef` | Deferred WASM memory reference |
97
+ | `fs` | Filesystem adapter (default: real |
98
+ | | `node:fs` operations) |
99
+ | `allocator` | Deferred WASM allocator reference |
100
+
101
+ **Host imports provided:**
102
+
103
+ | Import name | Description |
104
+ |-------------------|---------------------------------|
105
+ | `host_read_file` | Read a file into WASM memory |
106
+ | `host_write_file` | Write WASM memory to a file |
107
+ | `host_rename` | Rename a file |
108
+ | `host_remove_file`| Delete a file |
109
+ | `host_list_dir` | List directory entries |
110
+ | `host_mkdir` | Create a directory (recursive) |
111
+ | `host_file_exists`| Check if a file exists |
112
+
113
+ All paths received from WASM are resolved relative
114
+ to `contextPath`.
115
+
116
+ **Supporting interfaces:**
117
+
118
+ ```ts
119
+ interface FsAdapter {
120
+ readFileSync(path: string): Buffer;
121
+ writeFileSync(path: string, data: Uint8Array): void;
122
+ renameSync(oldPath: string, newPath: string): void;
123
+ unlinkSync(path: string): void;
124
+ readdirSync(path: string): string[];
125
+ mkdirSync(path: string): void;
126
+ existsSync(path: string): boolean;
127
+ }
128
+
129
+ interface MemoryRef {
130
+ memory: WebAssembly.Memory | null;
131
+ }
132
+
133
+ interface AllocatorRef {
134
+ alloc: ((size: number) => number) | null;
135
+ }
136
+ ```
137
+
138
+ ### `loadWasmModules`
139
+
140
+ **File:** `load-wasm-modules.function.ts`
141
+
142
+ Compiles and instantiates the `kb-worker.wasm` module
143
+ along with its host imports.
144
+
145
+ ```ts
146
+ async function loadWasmModules(
147
+ config: DaemonConfig,
148
+ wasmDir?: string,
149
+ ): Promise<WasmModules>;
150
+ ```
151
+
152
+ Loading sequence:
153
+
154
+ 1. Builds `createHostImports` with a deferred
155
+ `MemoryRef` and `AllocatorRef`.
156
+ 2. Compiles and instantiates `kb-worker.wasm`,
157
+ passing host imports.
158
+ 3. Wires the exported `memory` and `kbdb_alloc`
159
+ function back into the deferred refs.
160
+
161
+ Returns a `WasmModules` object containing the
162
+ instantiated module and its exported memory.
163
+
164
+ ### `createIpcServer`
165
+
166
+ **File:** `create-ipc-server.function.ts`
167
+
168
+ Creates a local IPC server bound to the given socket
169
+ path and returns the `net.Server` instance.
170
+
171
+ ```ts
172
+ function createIpcServer(
173
+ ipcPath: string,
174
+ handler: IpcHandler,
175
+ ): net.Server;
176
+ ```
177
+
178
+ Platform behavior:
179
+
180
+ - **Linux / macOS** -- Unix domain socket.
181
+ - **Windows** -- Named pipe.
182
+
183
+ Messages are newline-delimited JSON-RPC 2.0. Each
184
+ message is a single line of JSON followed by `\n`.
185
+
186
+ Incoming requests are parsed and forwarded to
187
+ `handler`. Responses are serialized and written back
188
+ to the connection.
189
+
190
+ ### `readConfig`
191
+
192
+ **File:** `read-config.function.ts`
193
+
194
+ Reads daemon configuration from `worker.toml` in
195
+ the `.kbdb` directory.
196
+
197
+ ```ts
198
+ function readConfig(
199
+ contextPath: string,
200
+ ): DaemonConfig;
201
+ ```
202
+
203
+ Reads `${contextPath}/worker.toml`. Missing keys
204
+ are filled with defaults from
205
+ [daemon-defaults.constant.ts](constants.md). If the
206
+ file does not exist, returns a `DaemonConfig` with
207
+ all defaults.
208
+
209
+ ## Testing
210
+
211
+ Each function has a `.spec.ts` at the module root:
212
+
213
+ ```
214
+ src/shared/worker-daemon/
215
+ ├── run-worker.spec.ts
216
+ ├── start-daemon.spec.ts
217
+ ├── create-host-imports.spec.ts
218
+ ├── load-wasm-modules.spec.ts
219
+ ├── create-ipc-server.spec.ts
220
+ └── read-config.spec.ts
221
+ ```
@@ -0,0 +1,112 @@
1
+ # worker-daemon -- Daemon Process Module
2
+
3
+ *Background process that loads WASM modules once,
4
+ listens on IPC, serves JSON-RPC 2.0 requests, manages
5
+ cache + context + idle timeout. Spawned on demand by
6
+ worker-client, shuts down on idle timeout or OS
7
+ signal.*
8
+
9
+ ## Source
10
+
11
+ `src/shared/worker-daemon/`
12
+
13
+ ## Responsibility
14
+
15
+ The worker-daemon module implements a detached
16
+ background process that:
17
+
18
+ - Loads and compiles the three WASM modules once at
19
+ startup (`query-parser.wasm`, `fs-database.wasm`,
20
+ `kb-worker.wasm`).
21
+ - Reads configuration from `worker.toml` in the
22
+ context directory.
23
+ - Listens on a local IPC socket (Unix domain socket
24
+ or Windows named pipe) for JSON-RPC 2.0 requests.
25
+ - Maintains an in-memory LRU cache with TTL expiry
26
+ for indexes, content objects, and manifests.
27
+ - Tracks active connections and resets the idle timer
28
+ on every connect, disconnect, or request.
29
+ - Shuts down gracefully on idle timeout or OS signal.
30
+
31
+ The daemon is **not** a persistent server. It is a
32
+ short-lived process spawned by
33
+ [worker-client](../worker-client/module.md) that
34
+ exists only to amortize WASM compilation cost and
35
+ share cached data across connections.
36
+
37
+ See [Worker Daemon](../../../../goals/worker-daemon.md)
38
+ for the full behavioral specification.
39
+
40
+ ## Directory Layout
41
+
42
+ ```
43
+ src/shared/worker-daemon/
44
+ ├── index.ts
45
+ ├── classes/
46
+ │ └── worker-daemon.class.ts
47
+ ├── functions/
48
+ │ ├── create-host-imports.function.ts
49
+ │ ├── create-ipc-server.function.ts
50
+ │ ├── load-wasm-modules.function.ts
51
+ │ ├── read-config.function.ts
52
+ │ ├── run-worker.function.ts
53
+ │ └── start-daemon.function.ts
54
+ ├── typings/
55
+ │ ├── daemon-config.interface.ts
56
+ │ ├── ipc-handler.interface.ts
57
+ │ └── wasm-modules.interface.ts
58
+ ├── constants/
59
+ │ └── daemon-defaults.constant.ts
60
+ └── *.spec.ts
61
+ ```
62
+
63
+ ## Exports
64
+
65
+ - **[classes.md](classes.md)** -- `WorkerDaemon`.
66
+ - **[functions.md](functions.md)** -- `startDaemon`,
67
+ `runWorker`, `createHostImports`, `loadWasmModules`,
68
+ `createIpcServer`, `readConfig`.
69
+ - **[typings.md](typings.md)** -- `DaemonConfig`,
70
+ `IpcHandler`, `IpcRequest`, `IpcResponse`,
71
+ `IpcErrorDetail`, `WasmModules`.
72
+ - **[constants.md](constants.md)** --
73
+ `DEFAULT_ITEM_LIMIT`, `DEFAULT_INDEX_LIMIT`,
74
+ `DEFAULT_TIMEOUT_MS`, `DEFAULT_ITEM_TTL_MS`.
75
+
76
+ ## Startup Sequence
77
+
78
+ ```
79
+ src/worker.ts (entry point)
80
+
81
+ ├─ startDaemon(contextPath)
82
+ │ ├─ readConfig(contextPath)
83
+ │ │ └─ reads worker.toml from .kbdb dir
84
+ │ ├─ new WorkerDaemon(ctx, config)
85
+ │ └─ daemon.start()
86
+ │ ├─ loadWasmModules(config)
87
+ │ │ ├─ allocate shared WebAssembly.Memory
88
+ │ │ ├─ compile query-parser.wasm ─┐
89
+ │ │ ├─ compile fs-database.wasm ──┤
90
+ │ │ │ (parallel, standalone, │
91
+ │ │ │ shared memory) │
92
+ │ │ └─ compile kb-worker.wasm ────┘
93
+ │ │ (imports both modules)
94
+ │ ├─ init cache
95
+ │ ├─ write PID file
96
+ │ │ └─ kb-worker-{ctx}.pid
97
+ │ ├─ createIpcServer(ctx, handler)
98
+ │ │ └─ kb-worker-{ctx}.sock
99
+ │ └─ listen for connections
100
+ └─ daemon running
101
+ ```
102
+
103
+ ## Shutdown Sequence
104
+
105
+ On idle timeout or OS signal (`SIGTERM`, `SIGINT`):
106
+
107
+ 1. Stop accepting new connections.
108
+ 2. Wait for in-flight requests to complete.
109
+ 3. Purge all cached data.
110
+ 4. Remove PID file from OS temporary directory.
111
+ 5. Remove IPC socket file (Unix only).
112
+ 6. Exit process.