@dikolab/kbdb 0.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 (308) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +270 -0
  3. package/dist/chunk-QCCN7OZH.mjs +82 -0
  4. package/dist/chunk-QCCN7OZH.mjs.map +7 -0
  5. package/dist/cli.cjs +3598 -0
  6. package/dist/cli.cjs.map +7 -0
  7. package/dist/cli.mjs +3537 -0
  8. package/dist/cli.mjs.map +7 -0
  9. package/dist/kbdb-worker.cjs +1659 -0
  10. package/dist/kbdb-worker.cjs.map +7 -0
  11. package/dist/mod.cjs +538 -0
  12. package/dist/mod.cjs.map +7 -0
  13. package/dist/mod.d.ts +3 -0
  14. package/dist/mod.mjs +507 -0
  15. package/dist/mod.mjs.map +7 -0
  16. package/dist/src/cli.d.ts +1 -0
  17. package/dist/src/shared/cli/constants/defaults.constant.d.ts +11 -0
  18. package/dist/src/shared/cli/constants/help-text.constant.d.ts +2 -0
  19. package/dist/src/shared/cli/functions/dispatch-command.function.d.ts +37 -0
  20. package/dist/src/shared/cli/functions/ensure-db.function.d.ts +11 -0
  21. package/dist/src/shared/cli/functions/error-to-message.function.d.ts +7 -0
  22. package/dist/src/shared/cli/functions/find-db.function.d.ts +13 -0
  23. package/dist/src/shared/cli/functions/format-output.function.d.ts +15 -0
  24. package/dist/src/shared/cli/functions/generate-help.function.d.ts +31 -0
  25. package/dist/src/shared/cli/functions/is-stdin-tty.function.d.ts +7 -0
  26. package/dist/src/shared/cli/functions/parse-args.function.d.ts +25 -0
  27. package/dist/src/shared/cli/functions/prompt-user.function.d.ts +13 -0
  28. package/dist/src/shared/cli/functions/run-agent-create.function.d.ts +58 -0
  29. package/dist/src/shared/cli/functions/run-agent-delete.function.d.ts +32 -0
  30. package/dist/src/shared/cli/functions/run-agent-get.function.d.ts +46 -0
  31. package/dist/src/shared/cli/functions/run-agent-list.function.d.ts +45 -0
  32. package/dist/src/shared/cli/functions/run-check.function.d.ts +64 -0
  33. package/dist/src/shared/cli/functions/run-cli.function.d.ts +39 -0
  34. package/dist/src/shared/cli/functions/run-content.function.d.ts +40 -0
  35. package/dist/src/shared/cli/functions/run-db-init.function.d.ts +23 -0
  36. package/dist/src/shared/cli/functions/run-db-migrate.function.d.ts +32 -0
  37. package/dist/src/shared/cli/functions/run-gc.function.d.ts +38 -0
  38. package/dist/src/shared/cli/functions/run-init.function.d.ts +27 -0
  39. package/dist/src/shared/cli/functions/run-learn.function.d.ts +46 -0
  40. package/dist/src/shared/cli/functions/run-migrate.function.d.ts +57 -0
  41. package/dist/src/shared/cli/functions/run-rebuild.function.d.ts +40 -0
  42. package/dist/src/shared/cli/functions/run-search.function.d.ts +39 -0
  43. package/dist/src/shared/cli/functions/run-skill-delete.function.d.ts +30 -0
  44. package/dist/src/shared/cli/functions/run-skill-get.function.d.ts +49 -0
  45. package/dist/src/shared/cli/functions/run-skill-learn.function.d.ts +36 -0
  46. package/dist/src/shared/cli/functions/run-skill-list.function.d.ts +43 -0
  47. package/dist/src/shared/cli/functions/run-status.function.d.ts +22 -0
  48. package/dist/src/shared/cli/functions/run-unlearn.function.d.ts +45 -0
  49. package/dist/src/shared/cli/index.d.ts +35 -0
  50. package/dist/src/shared/cli/typings/cli-options.interface.d.ts +53 -0
  51. package/dist/src/shared/cli/typings/command-result.model.d.ts +15 -0
  52. package/dist/src/shared/cli/typings/learn-result.model.d.ts +11 -0
  53. package/dist/src/shared/cli/typings/search-display.model.d.ts +17 -0
  54. package/dist/src/shared/dir-resolver/functions/resolve-base-dir.function.d.ts +3 -0
  55. package/dist/src/shared/dir-resolver/functions/resolve-wasm-dir.function.d.ts +1 -0
  56. package/dist/src/shared/dir-resolver/functions/resolve-worker-script.function.d.ts +2 -0
  57. package/dist/src/shared/dir-resolver/index.d.ts +4 -0
  58. package/dist/src/shared/dir-resolver/typings/base-dir.interface.d.ts +4 -0
  59. package/dist/src/shared/hash/functions/compute-sha256.d.ts +10 -0
  60. package/dist/src/shared/hash/index.d.ts +1 -0
  61. package/dist/src/shared/mcp/classes/mcp-server.class.d.ts +55 -0
  62. package/dist/src/shared/mcp/constants/mcp-error-codes.constant.d.ts +26 -0
  63. package/dist/src/shared/mcp/functions/create-mcp-server.function.d.ts +11 -0
  64. package/dist/src/shared/mcp/functions/create-prompt-definitions.function.d.ts +41 -0
  65. package/dist/src/shared/mcp/functions/create-resource-templates.function.d.ts +7 -0
  66. package/dist/src/shared/mcp/functions/create-tool-definitions.function.d.ts +7 -0
  67. package/dist/src/shared/mcp/functions/extract-skill-arguments.function.d.ts +13 -0
  68. package/dist/src/shared/mcp/functions/handle-agent-create.function.d.ts +29 -0
  69. package/dist/src/shared/mcp/functions/handle-agent-delete.function.d.ts +28 -0
  70. package/dist/src/shared/mcp/functions/handle-agent-get.function.d.ts +29 -0
  71. package/dist/src/shared/mcp/functions/handle-agent-list.function.d.ts +31 -0
  72. package/dist/src/shared/mcp/functions/handle-completion.function.d.ts +58 -0
  73. package/dist/src/shared/mcp/functions/handle-prompt-get.function.d.ts +23 -0
  74. package/dist/src/shared/mcp/functions/handle-resource-read.function.d.ts +26 -0
  75. package/dist/src/shared/mcp/functions/handle-roots-list.function.d.ts +21 -0
  76. package/dist/src/shared/mcp/functions/handle-tool-call.function.d.ts +26 -0
  77. package/dist/src/shared/mcp/functions/parse-skill-content.function.d.ts +15 -0
  78. package/dist/src/shared/mcp/functions/serialize-skill-content.function.d.ts +9 -0
  79. package/dist/src/shared/mcp/functions/should-emit-log.function.d.ts +20 -0
  80. package/dist/src/shared/mcp/index.d.ts +9 -0
  81. package/dist/src/shared/mcp/typings/agent-types.interface.d.ts +38 -0
  82. package/dist/src/shared/mcp/typings/log-types.interface.d.ts +17 -0
  83. package/dist/src/shared/mcp/typings/mcp-client.interface.d.ts +217 -0
  84. package/dist/src/shared/mcp/typings/mcp-types.interface.d.ts +149 -0
  85. package/dist/src/shared/mcp/typings/prompt-types.interface.d.ts +37 -0
  86. package/dist/src/shared/mcp/typings/remove-section-result.model.d.ts +10 -0
  87. package/dist/src/shared/mcp/typings/sampling-types.interface.d.ts +46 -0
  88. package/dist/src/shared/mcp/typings/skill-types.interface.d.ts +28 -0
  89. package/dist/src/shared/mod.d.ts +1 -0
  90. package/dist/src/shared/platform/functions/get-ipc-path.function.d.ts +11 -0
  91. package/dist/src/shared/platform/functions/get-tmpdir.function.d.ts +4 -0
  92. package/dist/src/shared/platform/functions/is-process-alive.function.d.ts +10 -0
  93. package/dist/src/shared/platform/index.d.ts +3 -0
  94. package/dist/src/shared/runtime/functions/detect-runtime.d.ts +8 -0
  95. package/dist/src/shared/runtime/functions/get-args.d.ts +7 -0
  96. package/dist/src/shared/runtime/index.d.ts +3 -0
  97. package/dist/src/shared/runtime/typings/runtime.d.ts +2 -0
  98. package/dist/src/shared/version/constants/version.constant.d.ts +2 -0
  99. package/dist/src/shared/version/index.d.ts +1 -0
  100. package/dist/src/shared/wasm-codec/functions/decode-compose-output.function.d.ts +5 -0
  101. package/dist/src/shared/wasm-codec/functions/decode-document-manifest-list.function.d.ts +14 -0
  102. package/dist/src/shared/wasm-codec/functions/decode-document-manifest.function.d.ts +40 -0
  103. package/dist/src/shared/wasm-codec/functions/decode-f32.function.d.ts +2 -0
  104. package/dist/src/shared/wasm-codec/functions/decode-key-value-text.function.d.ts +1 -0
  105. package/dist/src/shared/wasm-codec/functions/decode-remove-flag.function.d.ts +1 -0
  106. package/dist/src/shared/wasm-codec/functions/decode-scored-results.function.d.ts +10 -0
  107. package/dist/src/shared/wasm-codec/functions/decode-section-record-list.function.d.ts +13 -0
  108. package/dist/src/shared/wasm-codec/functions/decode-section-records.function.d.ts +50 -0
  109. package/dist/src/shared/wasm-codec/functions/decode-string.function.d.ts +5 -0
  110. package/dist/src/shared/wasm-codec/functions/decode-u32.function.d.ts +2 -0
  111. package/dist/src/shared/wasm-codec/functions/decode-u64.function.d.ts +2 -0
  112. package/dist/src/shared/wasm-codec/functions/encode-add-section-params.function.d.ts +10 -0
  113. package/dist/src/shared/wasm-codec/functions/encode-group-params.function.d.ts +10 -0
  114. package/dist/src/shared/wasm-codec/functions/encode-identifier-list.function.d.ts +1 -0
  115. package/dist/src/shared/wasm-codec/functions/encode-kbid-list.function.d.ts +1 -0
  116. package/dist/src/shared/wasm-codec/functions/encode-option-string.function.d.ts +1 -0
  117. package/dist/src/shared/wasm-codec/functions/encode-search-params.function.d.ts +1 -0
  118. package/dist/src/shared/wasm-codec/functions/encode-section-type.function.d.ts +1 -0
  119. package/dist/src/shared/wasm-codec/functions/encode-string.function.d.ts +1 -0
  120. package/dist/src/shared/wasm-codec/functions/encode-type-filter-param.function.d.ts +11 -0
  121. package/dist/src/shared/wasm-codec/functions/encode-u32.function.d.ts +1 -0
  122. package/dist/src/shared/wasm-codec/functions/encode-update-section-params.function.d.ts +2 -0
  123. package/dist/src/shared/wasm-codec/index.d.ts +29 -0
  124. package/dist/src/shared/worker-client/classes/worker-client.class.d.ts +230 -0
  125. package/dist/src/shared/worker-client/functions/compute-context-id.function.d.ts +11 -0
  126. package/dist/src/shared/worker-client/functions/create-worker-client.function.d.ts +18 -0
  127. package/dist/src/shared/worker-client/functions/discover-daemon.function.d.ts +14 -0
  128. package/dist/src/shared/worker-client/functions/resolve-db-path.function.d.ts +11 -0
  129. package/dist/src/shared/worker-client/functions/spawn-daemon.function.d.ts +11 -0
  130. package/dist/src/shared/worker-client/functions/wait-for-daemon.function.d.ts +13 -0
  131. package/dist/src/shared/worker-client/index.d.ts +22 -0
  132. package/dist/src/shared/worker-client/typings/add-section-result.model.d.ts +22 -0
  133. package/dist/src/shared/worker-client/typings/content-result.model.d.ts +12 -0
  134. package/dist/src/shared/worker-client/typings/daemon-info.model.d.ts +7 -0
  135. package/dist/src/shared/worker-client/typings/gc-result.model.d.ts +12 -0
  136. package/dist/src/shared/worker-client/typings/integrity-check-result.model.d.ts +36 -0
  137. package/dist/src/shared/worker-client/typings/migrate-result.model.d.ts +11 -0
  138. package/dist/src/shared/worker-client/typings/rebuild-result.model.d.ts +12 -0
  139. package/dist/src/shared/worker-client/typings/remove-section-result.model.d.ts +7 -0
  140. package/dist/src/shared/worker-client/typings/search-params.model.d.ts +12 -0
  141. package/dist/src/shared/worker-client/typings/search-result.model.d.ts +14 -0
  142. package/dist/src/shared/worker-client/typings/section.model.d.ts +26 -0
  143. package/dist/src/shared/worker-client/typings/status-result.model.d.ts +14 -0
  144. package/dist/src/shared/worker-client/typings/version-status.model.d.ts +24 -0
  145. package/dist/src/shared/worker-client/typings/worker-client-error.interface.d.ts +8 -0
  146. package/dist/src/shared/worker-client/typings/worker-client-options.interface.d.ts +30 -0
  147. package/dist/src/shared/worker-daemon/classes/worker-daemon.class.d.ts +147 -0
  148. package/dist/src/shared/worker-daemon/constants/daemon-defaults.constant.d.ts +24 -0
  149. package/dist/src/shared/worker-daemon/functions/create-host-imports.function.d.ts +68 -0
  150. package/dist/src/shared/worker-daemon/functions/create-ipc-server.function.d.ts +18 -0
  151. package/dist/src/shared/worker-daemon/functions/load-wasm-modules.function.d.ts +19 -0
  152. package/dist/src/shared/worker-daemon/functions/read-config.function.d.ts +12 -0
  153. package/dist/src/shared/worker-daemon/functions/run-worker.function.d.ts +26 -0
  154. package/dist/src/shared/worker-daemon/functions/start-daemon.function.d.ts +13 -0
  155. package/dist/src/shared/worker-daemon/index.d.ts +9 -0
  156. package/dist/src/shared/worker-daemon/typings/daemon-config.interface.d.ts +13 -0
  157. package/dist/src/shared/worker-daemon/typings/ipc-handler.interface.d.ts +36 -0
  158. package/dist/src/shared/worker-daemon/typings/wasm-modules.interface.d.ts +7 -0
  159. package/dist/src/worker.d.ts +1 -0
  160. package/dist/vitest.config.d.ts +2 -0
  161. package/dist/worker.mjs +1615 -0
  162. package/dist/worker.mjs.map +7 -0
  163. package/mod.ts +17 -0
  164. package/package.json +85 -0
  165. package/src/cli.ts +62 -0
  166. package/src/shared/cli/constants/defaults.constant.ts +19 -0
  167. package/src/shared/cli/constants/help-text.constant.ts +4 -0
  168. package/src/shared/cli/functions/dispatch-command.function.ts +338 -0
  169. package/src/shared/cli/functions/ensure-db.function.ts +21 -0
  170. package/src/shared/cli/functions/error-to-message.function.ts +9 -0
  171. package/src/shared/cli/functions/find-db.function.ts +20 -0
  172. package/src/shared/cli/functions/format-output.function.ts +64 -0
  173. package/src/shared/cli/functions/generate-help.function.ts +599 -0
  174. package/src/shared/cli/functions/is-stdin-tty.function.ts +12 -0
  175. package/src/shared/cli/functions/parse-args.function.ts +133 -0
  176. package/src/shared/cli/functions/prompt-user.function.ts +36 -0
  177. package/src/shared/cli/functions/run-agent-create.function.ts +114 -0
  178. package/src/shared/cli/functions/run-agent-delete.function.ts +47 -0
  179. package/src/shared/cli/functions/run-agent-get.function.ts +166 -0
  180. package/src/shared/cli/functions/run-agent-list.function.ts +58 -0
  181. package/src/shared/cli/functions/run-check.function.ts +78 -0
  182. package/src/shared/cli/functions/run-cli.function.ts +299 -0
  183. package/src/shared/cli/functions/run-content.function.ts +47 -0
  184. package/src/shared/cli/functions/run-db-init.function.ts +44 -0
  185. package/src/shared/cli/functions/run-db-migrate.function.ts +40 -0
  186. package/src/shared/cli/functions/run-gc.function.ts +45 -0
  187. package/src/shared/cli/functions/run-init.function.ts +91 -0
  188. package/src/shared/cli/functions/run-learn.function.ts +171 -0
  189. package/src/shared/cli/functions/run-migrate.function.ts +85 -0
  190. package/src/shared/cli/functions/run-rebuild.function.ts +47 -0
  191. package/src/shared/cli/functions/run-search.function.ts +62 -0
  192. package/src/shared/cli/functions/run-skill-delete.function.ts +47 -0
  193. package/src/shared/cli/functions/run-skill-get.function.ts +90 -0
  194. package/src/shared/cli/functions/run-skill-learn.function.ts +70 -0
  195. package/src/shared/cli/functions/run-skill-list.function.ts +74 -0
  196. package/src/shared/cli/functions/run-status.function.ts +29 -0
  197. package/src/shared/cli/functions/run-unlearn.function.ts +58 -0
  198. package/src/shared/cli/index.ts +48 -0
  199. package/src/shared/cli/typings/cli-options.interface.ts +55 -0
  200. package/src/shared/cli/typings/command-result.model.ts +15 -0
  201. package/src/shared/cli/typings/learn-result.model.ts +11 -0
  202. package/src/shared/cli/typings/search-display.model.ts +17 -0
  203. package/src/shared/dir-resolver/functions/resolve-base-dir.function.ts +25 -0
  204. package/src/shared/dir-resolver/functions/resolve-wasm-dir.function.ts +5 -0
  205. package/src/shared/dir-resolver/functions/resolve-worker-script.function.ts +13 -0
  206. package/src/shared/dir-resolver/index.ts +7 -0
  207. package/src/shared/dir-resolver/typings/base-dir.interface.ts +4 -0
  208. package/src/shared/hash/functions/compute-sha256.ts +17 -0
  209. package/src/shared/hash/index.ts +1 -0
  210. package/src/shared/mcp/classes/mcp-server.class.ts +448 -0
  211. package/src/shared/mcp/constants/mcp-error-codes.constant.ts +30 -0
  212. package/src/shared/mcp/functions/create-mcp-server.function.ts +14 -0
  213. package/src/shared/mcp/functions/create-prompt-definitions.function.ts +102 -0
  214. package/src/shared/mcp/functions/create-resource-templates.function.ts +23 -0
  215. package/src/shared/mcp/functions/create-tool-definitions.function.ts +401 -0
  216. package/src/shared/mcp/functions/extract-skill-arguments.function.ts +27 -0
  217. package/src/shared/mcp/functions/handle-agent-create.function.ts +116 -0
  218. package/src/shared/mcp/functions/handle-agent-delete.function.ts +50 -0
  219. package/src/shared/mcp/functions/handle-agent-get.function.ts +160 -0
  220. package/src/shared/mcp/functions/handle-agent-list.function.ts +50 -0
  221. package/src/shared/mcp/functions/handle-completion.function.ts +114 -0
  222. package/src/shared/mcp/functions/handle-prompt-get.function.ts +214 -0
  223. package/src/shared/mcp/functions/handle-resource-read.function.ts +56 -0
  224. package/src/shared/mcp/functions/handle-roots-list.function.ts +29 -0
  225. package/src/shared/mcp/functions/handle-tool-call.function.ts +464 -0
  226. package/src/shared/mcp/functions/parse-skill-content.function.ts +38 -0
  227. package/src/shared/mcp/functions/serialize-skill-content.function.ts +12 -0
  228. package/src/shared/mcp/functions/should-emit-log.function.ts +38 -0
  229. package/src/shared/mcp/index.ts +28 -0
  230. package/src/shared/mcp/typings/agent-types.interface.ts +39 -0
  231. package/src/shared/mcp/typings/log-types.interface.ts +26 -0
  232. package/src/shared/mcp/typings/mcp-client.interface.ts +252 -0
  233. package/src/shared/mcp/typings/mcp-types.interface.ts +158 -0
  234. package/src/shared/mcp/typings/prompt-types.interface.ts +39 -0
  235. package/src/shared/mcp/typings/remove-section-result.model.ts +10 -0
  236. package/src/shared/mcp/typings/sampling-types.interface.ts +48 -0
  237. package/src/shared/mcp/typings/skill-types.interface.ts +29 -0
  238. package/src/shared/mod.ts +1 -0
  239. package/src/shared/platform/functions/get-ipc-path.function.ts +19 -0
  240. package/src/shared/platform/functions/get-tmpdir.function.ts +8 -0
  241. package/src/shared/platform/functions/is-process-alive.function.ts +17 -0
  242. package/src/shared/platform/index.ts +3 -0
  243. package/src/shared/runtime/functions/detect-runtime.ts +14 -0
  244. package/src/shared/runtime/functions/get-args.ts +16 -0
  245. package/src/shared/runtime/index.ts +3 -0
  246. package/src/shared/runtime/typings/runtime.ts +2 -0
  247. package/src/shared/version/constants/version.constant.ts +2 -0
  248. package/src/shared/version/index.ts +1 -0
  249. package/src/shared/wasm-codec/functions/decode-compose-output.function.ts +16 -0
  250. package/src/shared/wasm-codec/functions/decode-document-manifest-list.function.ts +70 -0
  251. package/src/shared/wasm-codec/functions/decode-document-manifest.function.ts +87 -0
  252. package/src/shared/wasm-codec/functions/decode-f32.function.ts +16 -0
  253. package/src/shared/wasm-codec/functions/decode-key-value-text.function.ts +15 -0
  254. package/src/shared/wasm-codec/functions/decode-remove-flag.function.ts +3 -0
  255. package/src/shared/wasm-codec/functions/decode-scored-results.function.ts +54 -0
  256. package/src/shared/wasm-codec/functions/decode-section-record-list.function.ts +20 -0
  257. package/src/shared/wasm-codec/functions/decode-section-records.function.ts +162 -0
  258. package/src/shared/wasm-codec/functions/decode-string.function.ts +22 -0
  259. package/src/shared/wasm-codec/functions/decode-u32.function.ts +16 -0
  260. package/src/shared/wasm-codec/functions/decode-u64.function.ts +16 -0
  261. package/src/shared/wasm-codec/functions/encode-add-section-params.function.ts +34 -0
  262. package/src/shared/wasm-codec/functions/encode-group-params.function.ts +28 -0
  263. package/src/shared/wasm-codec/functions/encode-identifier-list.function.ts +17 -0
  264. package/src/shared/wasm-codec/functions/encode-kbid-list.function.ts +17 -0
  265. package/src/shared/wasm-codec/functions/encode-option-string.function.ts +14 -0
  266. package/src/shared/wasm-codec/functions/encode-search-params.function.ts +9 -0
  267. package/src/shared/wasm-codec/functions/encode-section-type.function.ts +18 -0
  268. package/src/shared/wasm-codec/functions/encode-string.function.ts +9 -0
  269. package/src/shared/wasm-codec/functions/encode-type-filter-param.function.ts +13 -0
  270. package/src/shared/wasm-codec/functions/encode-u32.function.ts +5 -0
  271. package/src/shared/wasm-codec/functions/encode-update-section-params.function.ts +16 -0
  272. package/src/shared/wasm-codec/index.ts +36 -0
  273. package/src/shared/worker-client/classes/worker-client.class.ts +427 -0
  274. package/src/shared/worker-client/functions/compute-context-id.function.ts +18 -0
  275. package/src/shared/worker-client/functions/create-worker-client.function.ts +70 -0
  276. package/src/shared/worker-client/functions/discover-daemon.function.ts +47 -0
  277. package/src/shared/worker-client/functions/resolve-db-path.function.ts +21 -0
  278. package/src/shared/worker-client/functions/spawn-daemon.function.ts +35 -0
  279. package/src/shared/worker-client/functions/wait-for-daemon.function.ts +34 -0
  280. package/src/shared/worker-client/index.ts +31 -0
  281. package/src/shared/worker-client/typings/add-section-result.model.ts +22 -0
  282. package/src/shared/worker-client/typings/content-result.model.ts +12 -0
  283. package/src/shared/worker-client/typings/daemon-info.model.ts +7 -0
  284. package/src/shared/worker-client/typings/gc-result.model.ts +12 -0
  285. package/src/shared/worker-client/typings/integrity-check-result.model.ts +43 -0
  286. package/src/shared/worker-client/typings/migrate-result.model.ts +11 -0
  287. package/src/shared/worker-client/typings/rebuild-result.model.ts +12 -0
  288. package/src/shared/worker-client/typings/remove-section-result.model.ts +7 -0
  289. package/src/shared/worker-client/typings/search-params.model.ts +12 -0
  290. package/src/shared/worker-client/typings/search-result.model.ts +14 -0
  291. package/src/shared/worker-client/typings/section.model.ts +27 -0
  292. package/src/shared/worker-client/typings/status-result.model.ts +14 -0
  293. package/src/shared/worker-client/typings/version-status.model.ts +28 -0
  294. package/src/shared/worker-client/typings/worker-client-error.interface.ts +8 -0
  295. package/src/shared/worker-client/typings/worker-client-options.interface.ts +30 -0
  296. package/src/shared/worker-daemon/classes/worker-daemon.class.ts +1001 -0
  297. package/src/shared/worker-daemon/constants/daemon-defaults.constant.ts +29 -0
  298. package/src/shared/worker-daemon/functions/create-host-imports.function.ts +312 -0
  299. package/src/shared/worker-daemon/functions/create-ipc-server.function.ts +83 -0
  300. package/src/shared/worker-daemon/functions/load-wasm-modules.function.ts +98 -0
  301. package/src/shared/worker-daemon/functions/read-config.function.ts +83 -0
  302. package/src/shared/worker-daemon/functions/run-worker.function.ts +57 -0
  303. package/src/shared/worker-daemon/functions/start-daemon.function.ts +74 -0
  304. package/src/shared/worker-daemon/index.ts +16 -0
  305. package/src/shared/worker-daemon/typings/daemon-config.interface.ts +13 -0
  306. package/src/shared/worker-daemon/typings/ipc-handler.interface.ts +39 -0
  307. package/src/shared/worker-daemon/typings/wasm-modules.interface.ts +7 -0
  308. package/src/worker.ts +34 -0
@@ -0,0 +1,1659 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ // src/worker.ts
5
+ var import_node_fs6 = require("node:fs");
6
+
7
+ // src/shared/runtime/functions/detect-runtime.ts
8
+ function detectRuntime() {
9
+ if (typeof globalThis !== "undefined" && "Deno" in globalThis) {
10
+ return "deno";
11
+ }
12
+ return "node";
13
+ }
14
+
15
+ // src/shared/runtime/functions/get-args.ts
16
+ function getArgs() {
17
+ if (detectRuntime() === "deno") {
18
+ const g = globalThis;
19
+ const deno = g["Deno"];
20
+ return deno?.args ?? [];
21
+ }
22
+ return process.argv.slice(2);
23
+ }
24
+
25
+ // src/shared/dir-resolver/functions/resolve-base-dir.function.ts
26
+ var import_node_path = require("node:path");
27
+ var import_node_url = require("node:url");
28
+ function resolveScriptDir(entryUrl, entryDirname) {
29
+ if (entryDirname) return entryDirname;
30
+ if (entryUrl.startsWith("file:"))
31
+ return (0, import_node_path.dirname)((0, import_node_url.fileURLToPath)(entryUrl));
32
+ return (0, import_node_path.dirname)(entryUrl);
33
+ }
34
+ function resolveBaseDir(entryUrl, entryDirname) {
35
+ const scriptDir = typeof __dirname !== "undefined" ? __dirname : resolveScriptDir(entryUrl, entryDirname);
36
+ return { scriptDir, cwd: process.cwd() };
37
+ }
38
+
39
+ // src/shared/dir-resolver/functions/resolve-wasm-dir.function.ts
40
+ var import_node_path2 = require("node:path");
41
+ function resolveWasmDir(scriptDir) {
42
+ return (0, import_node_path2.join)(scriptDir, "wasm");
43
+ }
44
+
45
+ // src/shared/worker-daemon/functions/read-config.function.ts
46
+ var import_node_fs = require("node:fs");
47
+ var import_node_path3 = require("node:path");
48
+
49
+ // src/shared/worker-daemon/constants/daemon-defaults.constant.ts
50
+ var DEFAULT_ITEM_LIMIT = 1e3;
51
+ var DEFAULT_INDEX_LIMIT = 100;
52
+ var DEFAULT_TIMEOUT_MS = 3e5;
53
+ var DEFAULT_ITEM_TTL_MS = 6e4;
54
+ var WORKER_TOML_FILENAME = "worker.toml";
55
+ var DB_FORMAT_VERSION = 1;
56
+
57
+ // src/shared/worker-daemon/functions/read-config.function.ts
58
+ function readConfig(contextPath) {
59
+ const configPath = (0, import_node_path3.join)(contextPath, WORKER_TOML_FILENAME);
60
+ try {
61
+ const text = (0, import_node_fs.readFileSync)(configPath, "utf-8");
62
+ return parseWorkerToml(text, contextPath);
63
+ } catch {
64
+ return {
65
+ contextPath,
66
+ itemLimit: DEFAULT_ITEM_LIMIT,
67
+ indexLimit: DEFAULT_INDEX_LIMIT,
68
+ timeoutMs: DEFAULT_TIMEOUT_MS,
69
+ itemTtlMs: DEFAULT_ITEM_TTL_MS
70
+ };
71
+ }
72
+ }
73
+ function parseWorkerToml(text, contextPath) {
74
+ const config = {
75
+ contextPath,
76
+ itemLimit: DEFAULT_ITEM_LIMIT,
77
+ indexLimit: DEFAULT_INDEX_LIMIT,
78
+ timeoutMs: DEFAULT_TIMEOUT_MS,
79
+ itemTtlMs: DEFAULT_ITEM_TTL_MS
80
+ };
81
+ const result = { ...config };
82
+ for (const line of text.split("\n")) {
83
+ const trimmed = line.trim();
84
+ if (trimmed.startsWith("#") || !trimmed.includes("=")) {
85
+ continue;
86
+ }
87
+ const eqIdx = trimmed.indexOf("=");
88
+ const key = trimmed.slice(0, eqIdx).trim();
89
+ const value = trimmed.slice(eqIdx + 1).trim();
90
+ switch (key) {
91
+ case "item_limit":
92
+ result.itemLimit = parseInt(value, 10) || DEFAULT_ITEM_LIMIT;
93
+ break;
94
+ case "index_limit":
95
+ result.indexLimit = parseInt(value, 10) || DEFAULT_INDEX_LIMIT;
96
+ break;
97
+ case "timeout_ms":
98
+ result.timeoutMs = parseInt(value, 10) || DEFAULT_TIMEOUT_MS;
99
+ break;
100
+ case "item_ttl_ms":
101
+ result.itemTtlMs = parseInt(value, 10) || DEFAULT_ITEM_TTL_MS;
102
+ break;
103
+ default:
104
+ break;
105
+ }
106
+ }
107
+ return result;
108
+ }
109
+
110
+ // src/shared/worker-daemon/functions/start-daemon.function.ts
111
+ var import_node_fs5 = require("node:fs");
112
+ var import_node_path8 = require("node:path");
113
+ var import_node_os3 = require("node:os");
114
+
115
+ // src/shared/hash/functions/compute-sha256.ts
116
+ async function computeSha256(input) {
117
+ const data = new TextEncoder().encode(input);
118
+ const hash = await crypto.subtle.digest("SHA-256", data);
119
+ const bytes = new Uint8Array(hash);
120
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
121
+ }
122
+
123
+ // src/shared/worker-daemon/classes/worker-daemon.class.ts
124
+ var import_node_fs4 = require("node:fs");
125
+ var import_node_path7 = require("node:path");
126
+ var import_node_os2 = require("node:os");
127
+
128
+ // src/shared/worker-daemon/functions/load-wasm-modules.function.ts
129
+ var import_node_fs3 = require("node:fs");
130
+ var import_node_path5 = require("node:path");
131
+
132
+ // src/shared/worker-daemon/functions/create-host-imports.function.ts
133
+ var import_node_fs2 = require("node:fs");
134
+ var import_node_path4 = require("node:path");
135
+ var nodeFsAdapter = {
136
+ readFileSync: (p) => (0, import_node_fs2.readFileSync)(p),
137
+ writeFileSync: (p, d) => {
138
+ (0, import_node_fs2.writeFileSync)(p, d);
139
+ },
140
+ renameSync: (o, n) => {
141
+ (0, import_node_fs2.renameSync)(o, n);
142
+ },
143
+ unlinkSync: (p) => {
144
+ (0, import_node_fs2.unlinkSync)(p);
145
+ },
146
+ readdirSync: (p) => (0, import_node_fs2.readdirSync)(p),
147
+ mkdirSync: (p) => {
148
+ (0, import_node_fs2.mkdirSync)(p, { recursive: true });
149
+ },
150
+ existsSync: (p) => (0, import_node_fs2.existsSync)(p)
151
+ };
152
+ var nullMemory = { memory: null };
153
+ var nullAllocator = { alloc: null };
154
+ function createHostImports(contextPath, memoryRef = nullMemory, fs = nodeFsAdapter, allocator = nullAllocator) {
155
+ function getBuffer() {
156
+ if (!memoryRef.memory) {
157
+ throw new Error("WASM memory not initialized");
158
+ }
159
+ return memoryRef.memory.buffer;
160
+ }
161
+ function readPathArg(ptr, len) {
162
+ const bytes = new Uint8Array(getBuffer(), ptr, len);
163
+ const relative = new TextDecoder().decode(bytes);
164
+ return (0, import_node_path4.join)(contextPath, relative);
165
+ }
166
+ return {
167
+ /**
168
+ * Reads a file at the path encoded in shared memory and writes
169
+ * the result back via the out-pointer protocol.
170
+ *
171
+ * `outPtr` and `outLen` are WASM linear-memory addresses. On
172
+ * success, the host allocates a buffer via `allocator.alloc`,
173
+ * copies the file data there, and writes the allocated pointer
174
+ * as a LE u32 to `outPtr` and the data length as a LE u32 to
175
+ * `outLen`. Returns 0 on success, -1 on error or when the
176
+ * allocator is not yet available.
177
+ */
178
+ host_read_file(pathPtr, pathLen, outPtr, outLen) {
179
+ try {
180
+ if (!allocator.alloc) return -1;
181
+ const filePath = readPathArg(pathPtr, pathLen);
182
+ const data = fs.readFileSync(filePath);
183
+ const dataLen = data.byteLength;
184
+ const dv = new DataView(getBuffer());
185
+ if (dataLen === 0) {
186
+ dv.setUint32(outPtr, 0, true);
187
+ dv.setUint32(outLen, 0, true);
188
+ return 0;
189
+ }
190
+ const dataPtr = allocator.alloc(dataLen);
191
+ if (dataPtr === 0) return -1;
192
+ const memView = new Uint8Array(getBuffer());
193
+ memView.set(
194
+ new Uint8Array(
195
+ data.buffer,
196
+ data.byteOffset,
197
+ data.byteLength
198
+ ),
199
+ dataPtr
200
+ );
201
+ dv.setUint32(outPtr, dataPtr, true);
202
+ dv.setUint32(outLen, dataLen, true);
203
+ return 0;
204
+ } catch {
205
+ return -1;
206
+ }
207
+ },
208
+ /**
209
+ * Writes bytes from shared memory (`dataPtr`, `dataLen`) to the
210
+ * file at the path encoded in shared memory. Returns 0 on
211
+ * success, -1 on error.
212
+ */
213
+ host_write_file(pathPtr, pathLen, dataPtr, dataLen) {
214
+ try {
215
+ const filePath = readPathArg(pathPtr, pathLen);
216
+ const data = new Uint8Array(getBuffer(), dataPtr, dataLen);
217
+ fs.writeFileSync(filePath, data);
218
+ return 0;
219
+ } catch {
220
+ return -1;
221
+ }
222
+ },
223
+ /**
224
+ * Renames the file at `oldPtr/oldLen` to `newPtr/newLen`.
225
+ * Both paths are resolved relative to `contextPath`. Returns 0
226
+ * on success, -1 on error.
227
+ */
228
+ host_rename(oldPtr, oldLen, newPtr, newLen) {
229
+ try {
230
+ const oldPath = readPathArg(oldPtr, oldLen);
231
+ const newPath = readPathArg(newPtr, newLen);
232
+ fs.renameSync(oldPath, newPath);
233
+ return 0;
234
+ } catch {
235
+ return -1;
236
+ }
237
+ },
238
+ /**
239
+ * Deletes the file at the path encoded in shared memory.
240
+ * Returns 0 on success, -1 on error.
241
+ */
242
+ host_remove_file(pathPtr, pathLen) {
243
+ try {
244
+ const filePath = readPathArg(pathPtr, pathLen);
245
+ fs.unlinkSync(filePath);
246
+ return 0;
247
+ } catch {
248
+ return -1;
249
+ }
250
+ },
251
+ /**
252
+ * Lists the directory at the path encoded in shared memory and
253
+ * writes the result back via the out-pointer protocol.
254
+ *
255
+ * `outPtr` and `outLen` are WASM linear-memory addresses. On
256
+ * success, the host allocates a buffer via `allocator.alloc`,
257
+ * copies a newline-delimited UTF-8 listing there, and writes
258
+ * the allocated pointer as a LE u32 to `outPtr` and the byte
259
+ * length as a LE u32 to `outLen`. Returns 0 on success, -1 on
260
+ * error or when the allocator is not yet available.
261
+ */
262
+ host_list_dir(pathPtr, pathLen, outPtr, outLen) {
263
+ try {
264
+ if (!allocator.alloc) return -1;
265
+ const dirPath = readPathArg(pathPtr, pathLen);
266
+ const entries = fs.readdirSync(dirPath);
267
+ const text = entries.join("\n");
268
+ const encoded = new TextEncoder().encode(text);
269
+ const dv = new DataView(getBuffer());
270
+ if (encoded.length === 0) {
271
+ dv.setUint32(outPtr, 0, true);
272
+ dv.setUint32(outLen, 0, true);
273
+ return 0;
274
+ }
275
+ const dataPtr = allocator.alloc(encoded.length);
276
+ if (dataPtr === 0) return -1;
277
+ new Uint8Array(getBuffer(), dataPtr, encoded.length).set(
278
+ encoded
279
+ );
280
+ dv.setUint32(outPtr, dataPtr, true);
281
+ dv.setUint32(outLen, encoded.length, true);
282
+ return 0;
283
+ } catch {
284
+ return -1;
285
+ }
286
+ },
287
+ /**
288
+ * Creates the directory at the path encoded in shared memory,
289
+ * including any missing parent directories (recursive). Returns
290
+ * 0 on success, -1 on error.
291
+ */
292
+ host_mkdir(pathPtr, pathLen) {
293
+ try {
294
+ const dirPath = readPathArg(pathPtr, pathLen);
295
+ fs.mkdirSync(dirPath);
296
+ return 0;
297
+ } catch {
298
+ return -1;
299
+ }
300
+ },
301
+ /**
302
+ * Checks whether the file at the path encoded in shared memory
303
+ * exists. Returns 1 if it exists, 0 if it does not.
304
+ */
305
+ host_file_exists(pathPtr, pathLen) {
306
+ const filePath = readPathArg(pathPtr, pathLen);
307
+ return fs.existsSync(filePath) ? 1 : 0;
308
+ }
309
+ };
310
+ }
311
+
312
+ // src/shared/worker-daemon/functions/load-wasm-modules.function.ts
313
+ async function loadWasmModules(config, wasmDir2) {
314
+ const memoryRef = { memory: null };
315
+ const allocator = { alloc: null };
316
+ const hostImports = createHostImports(
317
+ config.contextPath,
318
+ memoryRef,
319
+ void 0,
320
+ allocator
321
+ );
322
+ const wkPath = (0, import_node_path5.join)(wasmDir2, "kb-worker", "kbdb_worker_bg.wasm");
323
+ const wkBytes = readWasmFileOrThrow(wkPath, "kb-worker");
324
+ let wkModule;
325
+ try {
326
+ wkModule = await WebAssembly.compile(wkBytes);
327
+ } catch (err) {
328
+ rethrow("compile", "kb-worker", err);
329
+ }
330
+ let kbWorker;
331
+ try {
332
+ kbWorker = await WebAssembly.instantiate(wkModule, {
333
+ env: { ...hostImports }
334
+ });
335
+ } catch (err) {
336
+ rethrow("instantiate", "kb-worker", err);
337
+ }
338
+ const memory = kbWorker.exports["memory"];
339
+ memoryRef.memory = memory;
340
+ allocator.alloc = (size) => {
341
+ const fn_ = kbWorker.exports["kbdb_alloc"];
342
+ if (typeof fn_ !== "function") return 0;
343
+ return fn_(size);
344
+ };
345
+ return { memory, kbWorker };
346
+ }
347
+ function readWasmFileOrThrow(path, label) {
348
+ try {
349
+ const buf = (0, import_node_fs3.readFileSync)(path);
350
+ return buf.buffer.slice(
351
+ buf.byteOffset,
352
+ buf.byteOffset + buf.byteLength
353
+ );
354
+ } catch (err) {
355
+ rethrow("load", label, err, path);
356
+ }
357
+ }
358
+ function rethrow(stage, label, err, path) {
359
+ const detail = err instanceof Error ? err.message : String(err);
360
+ const suffix = path ? ` (path: ${path})` : "";
361
+ const message = `failed to ${stage} ${label} WASM: ${detail}${suffix}`;
362
+ console.error(`kbdb-worker: ${message}`);
363
+ throw new Error(message, { cause: err });
364
+ }
365
+
366
+ // src/shared/worker-daemon/functions/create-ipc-server.function.ts
367
+ var import_node_net = require("node:net");
368
+ function createIpcServer(socketPath, handler) {
369
+ const server = (0, import_node_net.createServer)((socket) => {
370
+ let buffer = "";
371
+ socket.on("data", (chunk) => {
372
+ buffer += chunk.toString();
373
+ const lines = buffer.split("\n");
374
+ buffer = lines.pop() ?? "";
375
+ for (const line of lines) {
376
+ if (!line.trim()) continue;
377
+ void handleLine(line, handler, socket);
378
+ }
379
+ });
380
+ socket.on("error", (err) => {
381
+ console.error(
382
+ `kbdb-worker: ipc connection error: ${err.message}`
383
+ );
384
+ });
385
+ });
386
+ server.on("error", (err) => {
387
+ console.error(`kbdb-worker: ipc server error: ${err.message}`);
388
+ });
389
+ server.listen(socketPath);
390
+ return server;
391
+ }
392
+ function bigintReplacer(_key, value) {
393
+ return typeof value === "bigint" ? Number(value) : value;
394
+ }
395
+ async function handleLine(line, handler, socket) {
396
+ let response;
397
+ try {
398
+ const request = JSON.parse(line);
399
+ response = await handler(request);
400
+ } catch {
401
+ response = {
402
+ jsonrpc: "2.0",
403
+ id: 0,
404
+ error: {
405
+ code: -32700,
406
+ message: "Parse error"
407
+ }
408
+ };
409
+ }
410
+ socket.write(JSON.stringify(response, bigintReplacer) + "\n");
411
+ }
412
+
413
+ // src/shared/platform/functions/get-ipc-path.function.ts
414
+ var import_node_path6 = require("node:path");
415
+
416
+ // src/shared/platform/functions/get-tmpdir.function.ts
417
+ var import_node_os = require("node:os");
418
+ function getTmpdir() {
419
+ return (0, import_node_os.tmpdir)();
420
+ }
421
+
422
+ // src/shared/platform/functions/get-ipc-path.function.ts
423
+ function getIpcPath(ctx) {
424
+ if (process.platform === "win32") {
425
+ return `\\\\.\\pipe\\kbdb-${ctx}`;
426
+ }
427
+ return (0, import_node_path6.join)(getTmpdir(), `kbdb-${ctx}.sock`);
428
+ }
429
+
430
+ // src/shared/wasm-codec/functions/encode-string.function.ts
431
+ var encoder = new TextEncoder();
432
+ function encodeString(value) {
433
+ const utf8 = encoder.encode(value);
434
+ const result = new Uint8Array(4 + utf8.length);
435
+ new DataView(result.buffer).setUint32(0, utf8.length, true);
436
+ result.set(utf8, 4);
437
+ return result;
438
+ }
439
+
440
+ // src/shared/wasm-codec/functions/encode-u32.function.ts
441
+ function encodeU32(value) {
442
+ const result = new Uint8Array(4);
443
+ new DataView(result.buffer).setUint32(0, value, true);
444
+ return result;
445
+ }
446
+
447
+ // src/shared/wasm-codec/functions/encode-option-string.function.ts
448
+ function encodeOptionString(value) {
449
+ if (value == null) {
450
+ return new Uint8Array([0]);
451
+ }
452
+ const encoded = encodeString(value);
453
+ const result = new Uint8Array(1 + encoded.length);
454
+ result[0] = 1;
455
+ result.set(encoded, 1);
456
+ return result;
457
+ }
458
+
459
+ // src/shared/wasm-codec/functions/encode-section-type.function.ts
460
+ function encodeSectionType(kind, mimeType) {
461
+ if (kind === "text") {
462
+ return new Uint8Array([0]);
463
+ }
464
+ const tag = kind === "code" ? 1 : 2;
465
+ const mime = mimeType ?? "text/plain";
466
+ const encoded = encodeString(mime);
467
+ const result = new Uint8Array(1 + encoded.length);
468
+ result[0] = tag;
469
+ result.set(encoded, 1);
470
+ return result;
471
+ }
472
+
473
+ // src/shared/wasm-codec/functions/encode-add-section-params.function.ts
474
+ function encodeAddSectionParams(params) {
475
+ const parts = [
476
+ encodeSectionType(params.sectionType, params.mimeType),
477
+ encodeString(params.content),
478
+ encodeOptionString(params.title),
479
+ encodeOptionString(params.description),
480
+ encodeOptionString(params.docid),
481
+ encodeOptionString(params.typeName)
482
+ ];
483
+ const totalLen = parts.reduce((sum, p) => sum + p.length, 0);
484
+ const result = new Uint8Array(totalLen);
485
+ let offset = 0;
486
+ for (const part of parts) {
487
+ result.set(part, offset);
488
+ offset += part.length;
489
+ }
490
+ return result;
491
+ }
492
+
493
+ // src/shared/wasm-codec/functions/encode-update-section-params.function.ts
494
+ function encodeUpdateSectionParams(oldKbid, params) {
495
+ const kbidBytes = encodeString(oldKbid);
496
+ const paramBytes = encodeAddSectionParams(params);
497
+ const result = new Uint8Array(kbidBytes.length + paramBytes.length);
498
+ result.set(kbidBytes, 0);
499
+ result.set(paramBytes, kbidBytes.length);
500
+ return result;
501
+ }
502
+
503
+ // src/shared/wasm-codec/functions/encode-kbid-list.function.ts
504
+ function encodeKbidList(kbids) {
505
+ if (kbids.length === 0) {
506
+ return new Uint8Array(0);
507
+ }
508
+ const parts = [encodeU32(kbids.length), ...kbids.map(encodeString)];
509
+ const totalLen = parts.reduce((sum, p) => sum + p.length, 0);
510
+ const result = new Uint8Array(totalLen);
511
+ let offset = 0;
512
+ for (const part of parts) {
513
+ result.set(part, offset);
514
+ offset += part.length;
515
+ }
516
+ return result;
517
+ }
518
+
519
+ // src/shared/wasm-codec/functions/encode-group-params.function.ts
520
+ function encodeGroupParams(title, kbids, docType = "") {
521
+ const titleBytes = encodeString(title);
522
+ const listBytes = encodeKbidList(kbids);
523
+ const docTypeBytes = encodeString(docType);
524
+ const result = new Uint8Array(
525
+ titleBytes.length + listBytes.length + docTypeBytes.length
526
+ );
527
+ result.set(titleBytes, 0);
528
+ result.set(listBytes, titleBytes.length);
529
+ result.set(docTypeBytes, titleBytes.length + listBytes.length);
530
+ return result;
531
+ }
532
+
533
+ // src/shared/wasm-codec/functions/encode-identifier-list.function.ts
534
+ function encodeIdentifierList(ids) {
535
+ if (ids.length === 0) {
536
+ return new Uint8Array(0);
537
+ }
538
+ const parts = [encodeU32(ids.length), ...ids.map(encodeString)];
539
+ const totalLen = parts.reduce((sum, p) => sum + p.length, 0);
540
+ const result = new Uint8Array(totalLen);
541
+ let offset = 0;
542
+ for (const part of parts) {
543
+ result.set(part, offset);
544
+ offset += part.length;
545
+ }
546
+ return result;
547
+ }
548
+
549
+ // src/shared/wasm-codec/functions/encode-search-params.function.ts
550
+ var encoder2 = new TextEncoder();
551
+ function encodeSearchParams(query, mode = "and", limit = 20) {
552
+ return encoder2.encode(`${query}
553
+ ${mode}
554
+ ${String(limit)}`);
555
+ }
556
+
557
+ // src/shared/wasm-codec/functions/encode-type-filter-param.function.ts
558
+ function encodeTypeFilterParam(typeStr) {
559
+ return new TextEncoder().encode(typeStr);
560
+ }
561
+
562
+ // src/shared/wasm-codec/functions/decode-string.function.ts
563
+ var decoder = new TextDecoder();
564
+ function decodeString(bytes, offset) {
565
+ const view = new DataView(
566
+ bytes.buffer,
567
+ bytes.byteOffset,
568
+ bytes.byteLength
569
+ );
570
+ const len = view.getUint32(offset, true);
571
+ const value = decoder.decode(
572
+ bytes.subarray(offset + 4, offset + 4 + len)
573
+ );
574
+ return { value, bytesRead: 4 + len };
575
+ }
576
+
577
+ // src/shared/wasm-codec/functions/decode-u32.function.ts
578
+ function decodeU32(bytes, offset) {
579
+ const view = new DataView(
580
+ bytes.buffer,
581
+ bytes.byteOffset,
582
+ bytes.byteLength
583
+ );
584
+ return {
585
+ value: view.getUint32(offset, true),
586
+ bytesRead: 4
587
+ };
588
+ }
589
+
590
+ // src/shared/wasm-codec/functions/decode-f32.function.ts
591
+ function decodeF32(bytes, offset) {
592
+ const view = new DataView(
593
+ bytes.buffer,
594
+ bytes.byteOffset,
595
+ bytes.byteLength
596
+ );
597
+ return {
598
+ value: view.getFloat32(offset, true),
599
+ bytesRead: 4
600
+ };
601
+ }
602
+
603
+ // src/shared/wasm-codec/functions/decode-u64.function.ts
604
+ function decodeU64(bytes, offset) {
605
+ const view = new DataView(
606
+ bytes.buffer,
607
+ bytes.byteOffset,
608
+ bytes.byteLength
609
+ );
610
+ return {
611
+ value: view.getBigUint64(offset, true),
612
+ bytesRead: 8
613
+ };
614
+ }
615
+
616
+ // src/shared/wasm-codec/functions/decode-scored-results.function.ts
617
+ function decodeScoredResults(bytes) {
618
+ let offset = 0;
619
+ const count = decodeU32(bytes, offset);
620
+ offset += count.bytesRead;
621
+ const results = [];
622
+ for (let i = 0; i < count.value; i++) {
623
+ const kbid = decodeString(bytes, offset);
624
+ offset += kbid.bytesRead;
625
+ const score = decodeF32(bytes, offset);
626
+ offset += score.bytesRead;
627
+ const matchCount = decodeU32(bytes, offset);
628
+ offset += matchCount.bytesRead;
629
+ const matches = [];
630
+ for (let j = 0; j < matchCount.value; j++) {
631
+ const term = decodeString(bytes, offset);
632
+ offset += term.bytesRead;
633
+ const freq = decodeF32(bytes, offset);
634
+ offset += freq.bytesRead;
635
+ matches.push({
636
+ term: term.value,
637
+ frequency: freq.value
638
+ });
639
+ }
640
+ results.push({
641
+ kbid: kbid.value,
642
+ score: score.value,
643
+ matches
644
+ });
645
+ }
646
+ return results;
647
+ }
648
+
649
+ // src/shared/wasm-codec/functions/decode-section-records.function.ts
650
+ function decodeOptionString(bytes, offset) {
651
+ const tag = bytes[offset];
652
+ if (tag === 0) {
653
+ return { value: null, bytesRead: 1 };
654
+ }
655
+ const str = decodeString(bytes, offset + 1);
656
+ return { value: str.value, bytesRead: 1 + str.bytesRead };
657
+ }
658
+ function decodeSectionType(bytes, offset) {
659
+ const tag = bytes[offset];
660
+ if (tag === 0) {
661
+ return { sectionType: "text", bytesRead: 1 };
662
+ }
663
+ const mime = decodeString(bytes, offset + 1);
664
+ const kind = tag === 1 ? "code" : "image";
665
+ return {
666
+ sectionType: kind,
667
+ mimeType: mime.value,
668
+ bytesRead: 1 + mime.bytesRead
669
+ };
670
+ }
671
+ function decodeSectionRecords(bytes) {
672
+ let offset = 0;
673
+ const count = decodeU32(bytes, offset);
674
+ offset += count.bytesRead;
675
+ const records = [];
676
+ for (let i = 0; i < count.value; i++) {
677
+ const kbid = decodeString(bytes, offset);
678
+ offset += kbid.bytesRead;
679
+ const docid = decodeOptionString(bytes, offset);
680
+ offset += docid.bytesRead;
681
+ const st = decodeSectionType(bytes, offset);
682
+ offset += st.bytesRead;
683
+ const title = decodeOptionString(bytes, offset);
684
+ offset += title.bytesRead;
685
+ const description = decodeOptionString(bytes, offset);
686
+ offset += description.bytesRead;
687
+ const content = decodeString(bytes, offset);
688
+ offset += content.bytesRead;
689
+ const size = decodeU32(bytes, offset);
690
+ offset += size.bytesRead;
691
+ const createdAt = decodeU64(bytes, offset);
692
+ offset += createdAt.bytesRead;
693
+ const checksum = decodeString(bytes, offset);
694
+ offset += checksum.bytesRead;
695
+ const tokenCount = decodeU32(bytes, offset);
696
+ offset += tokenCount.bytesRead;
697
+ const headingTokenCount = decodeU32(bytes, offset);
698
+ offset += headingTokenCount.bytesRead;
699
+ const bodyTokenCount = decodeU32(bytes, offset);
700
+ offset += bodyTokenCount.bytesRead;
701
+ const codeTokenCount = decodeU32(bytes, offset);
702
+ offset += codeTokenCount.bytesRead;
703
+ const typeName = decodeString(bytes, offset);
704
+ offset += typeName.bytesRead;
705
+ const record = {
706
+ kbid: kbid.value,
707
+ docid: docid.value,
708
+ sectionType: st.sectionType,
709
+ title: title.value,
710
+ description: description.value,
711
+ content: content.value,
712
+ size: size.value,
713
+ createdAt: createdAt.value,
714
+ checksum: checksum.value,
715
+ tokenCount: tokenCount.value,
716
+ headingTokenCount: headingTokenCount.value,
717
+ bodyTokenCount: bodyTokenCount.value,
718
+ codeTokenCount: codeTokenCount.value,
719
+ typeName: typeName.value
720
+ };
721
+ if (st.mimeType !== void 0) {
722
+ record.mimeType = st.mimeType;
723
+ }
724
+ records.push(record);
725
+ }
726
+ return records;
727
+ }
728
+
729
+ // src/shared/wasm-codec/functions/decode-section-record-list.function.ts
730
+ function decodeSectionRecordList(bytes) {
731
+ return decodeSectionRecords(bytes);
732
+ }
733
+
734
+ // src/shared/wasm-codec/functions/decode-document-manifest.function.ts
735
+ function decodeDocumentManifest(bytes) {
736
+ let offset = 0;
737
+ const docid = decodeString(bytes, offset);
738
+ offset += docid.bytesRead;
739
+ const title = decodeString(bytes, offset);
740
+ offset += title.bytesRead;
741
+ const createdAt = decodeU64(bytes, offset);
742
+ offset += createdAt.bytesRead;
743
+ const docType = decodeString(bytes, offset);
744
+ offset += docType.bytesRead;
745
+ const count = decodeU32(bytes, offset);
746
+ offset += count.bytesRead;
747
+ const sections = [];
748
+ for (let i = 0; i < count.value; i++) {
749
+ const kbid = decodeString(bytes, offset);
750
+ offset += kbid.bytesRead;
751
+ const position = decodeU32(bytes, offset);
752
+ offset += position.bytesRead;
753
+ sections.push({
754
+ kbid: kbid.value,
755
+ position: position.value
756
+ });
757
+ }
758
+ return {
759
+ docid: docid.value,
760
+ title: title.value,
761
+ createdAt: createdAt.value,
762
+ docType: docType.value,
763
+ sections
764
+ };
765
+ }
766
+
767
+ // src/shared/wasm-codec/functions/decode-document-manifest-list.function.ts
768
+ function decodeDocumentManifestList(bytes) {
769
+ let offset = 0;
770
+ const count = decodeU32(bytes, offset);
771
+ offset += count.bytesRead;
772
+ const manifests = [];
773
+ for (let i = 0; i < count.value; i++) {
774
+ const docid = decodeString(bytes, offset);
775
+ offset += docid.bytesRead;
776
+ const title = decodeString(bytes, offset);
777
+ offset += title.bytesRead;
778
+ const createdAt = decodeU64(bytes, offset);
779
+ offset += createdAt.bytesRead;
780
+ const docType = decodeString(bytes, offset);
781
+ offset += docType.bytesRead;
782
+ const secCount = decodeU32(bytes, offset);
783
+ offset += secCount.bytesRead;
784
+ const sections = [];
785
+ for (let j = 0; j < secCount.value; j++) {
786
+ const kbid = decodeString(bytes, offset);
787
+ offset += kbid.bytesRead;
788
+ const position = decodeU32(bytes, offset);
789
+ offset += position.bytesRead;
790
+ sections.push({
791
+ kbid: kbid.value,
792
+ position: position.value
793
+ });
794
+ }
795
+ manifests.push({
796
+ docid: docid.value,
797
+ title: title.value,
798
+ createdAt: createdAt.value,
799
+ docType: docType.value,
800
+ sections
801
+ });
802
+ }
803
+ return manifests;
804
+ }
805
+
806
+ // src/shared/wasm-codec/functions/decode-compose-output.function.ts
807
+ function decodeComposeOutput(bytes) {
808
+ const md = decodeString(bytes, 0);
809
+ const totalChars = decodeU64(bytes, md.bytesRead);
810
+ return {
811
+ markdown: md.value,
812
+ totalChars: totalChars.value
813
+ };
814
+ }
815
+
816
+ // src/shared/wasm-codec/functions/decode-key-value-text.function.ts
817
+ function decodeKeyValueText(text) {
818
+ const result = {};
819
+ for (const line of text.split("\n")) {
820
+ const idx = line.indexOf("=");
821
+ if (idx < 0) continue;
822
+ const key = line.slice(0, idx);
823
+ const value = line.slice(idx + 1);
824
+ if (key) {
825
+ result[key] = value;
826
+ }
827
+ }
828
+ return result;
829
+ }
830
+
831
+ // src/shared/wasm-codec/functions/decode-remove-flag.function.ts
832
+ function decodeRemoveFlag(bytes) {
833
+ return bytes.length > 0 && bytes[0] === 1;
834
+ }
835
+
836
+ // src/shared/worker-daemon/classes/worker-daemon.class.ts
837
+ var WASM_METHOD_MAP = {
838
+ search: "worker_search",
839
+ addSection: "worker_add_section",
840
+ add_section: "worker_add_section",
841
+ updateSection: "worker_update_section",
842
+ update_section: "worker_update_section",
843
+ removeSection: "worker_remove_section",
844
+ remove_section: "worker_remove_section",
845
+ readSections: "worker_read_sections",
846
+ read_sections: "worker_read_sections",
847
+ groupSections: "worker_group_sections",
848
+ group_sections: "worker_group_sections",
849
+ removeGrouping: "worker_remove_grouping",
850
+ remove_grouping: "worker_remove_grouping",
851
+ retrieveDocument: "worker_retrieve_doc",
852
+ retrieve_doc: "worker_retrieve_doc",
853
+ content: "worker_compose",
854
+ compose: "worker_compose",
855
+ integrity_check: "worker_check_integrity",
856
+ integrityCheck: "worker_check_integrity",
857
+ gc: "worker_garbage_collect",
858
+ rebuild_indexes: "worker_rebuild_indexes",
859
+ rebuildIndexes: "worker_rebuild_indexes",
860
+ init_directory: "worker_init_directory",
861
+ initDirectory: "worker_init_directory",
862
+ migrateDatabase: "worker_migrate",
863
+ query: "worker_query",
864
+ get_result_status: "worker_result_status",
865
+ get_result: "worker_get_result",
866
+ invalidate: "worker_invalidate",
867
+ invalidate_all: "worker_invalidate_all",
868
+ invalidateAll: "worker_invalidate_all",
869
+ db_status: "worker_status",
870
+ dbStatus: "worker_status",
871
+ listByType: "worker_list_by_type",
872
+ list_by_type: "worker_list_by_type",
873
+ listDocumentsByType: "worker_list_docs_by_type",
874
+ list_docs_by_type: "worker_list_docs_by_type"
875
+ };
876
+ var CONFIG_PREFIX = "config_";
877
+ var CONFIG_KEY_MAP = {
878
+ timeout_ms: "timeoutMs",
879
+ item_ttl_ms: "itemTtlMs",
880
+ item_limit: "itemLimit",
881
+ index_limit: "indexLimit"
882
+ };
883
+ var IpcError = class extends Error {
884
+ /** JSON-RPC error code. */
885
+ code;
886
+ constructor(code, message) {
887
+ super(message);
888
+ this.code = code;
889
+ this.name = "IpcError";
890
+ }
891
+ };
892
+ var WorkerDaemon = class {
893
+ /** Context ID (16-character hex SHA-256 prefix). */
894
+ ctx;
895
+ /** Absolute path to the `.kbdb` directory. */
896
+ targetDir;
897
+ /** Parsed daemon configuration from `worker.toml`. */
898
+ config;
899
+ /** Number of currently active IPC client connections. */
900
+ get connectionCount() {
901
+ return this._connectionCount;
902
+ }
903
+ _connectionCount = 0;
904
+ _wasmModules = null;
905
+ _idleAt = 0;
906
+ _idleTimer = null;
907
+ _server = null;
908
+ _wasmDir;
909
+ /**
910
+ * @param ctx - context ID (16-hex characters), the first 16 of
911
+ * the SHA-256 hash of `targetDir`
912
+ * @param targetDir - absolute path to the `.kbdb` directory
913
+ * @param config - parsed daemon configuration
914
+ * @param wasmDir - path to the WASM build output directory
915
+ */
916
+ constructor(ctx, targetDir, config, wasmDir2) {
917
+ this.ctx = ctx;
918
+ this.targetDir = targetDir;
919
+ this.config = config;
920
+ this._wasmDir = wasmDir2 ?? "";
921
+ }
922
+ // -----------------------------------------------------------------------
923
+ // Public API
924
+ // -----------------------------------------------------------------------
925
+ /**
926
+ * Validates startup preconditions before WASM module loading.
927
+ *
928
+ * Checks that the database directory exists, is readable and
929
+ * writable, and that `catalog.toml` reports a compatible version.
930
+ *
931
+ * @throws {Error} if any precondition fails -- `startDaemon`
932
+ * catches this, prints to stderr, and exits with code 1
933
+ */
934
+ checkPreconditions() {
935
+ if (!(0, import_node_fs4.existsSync)(this.targetDir)) {
936
+ throw new Error(
937
+ `database directory not found: ${this.targetDir}`
938
+ );
939
+ }
940
+ try {
941
+ (0, import_node_fs4.accessSync)(
942
+ this.targetDir,
943
+ import_node_fs4.constants.R_OK | import_node_fs4.constants.W_OK
944
+ );
945
+ } catch {
946
+ throw new Error(
947
+ `cannot access database directory: ${this.targetDir} -- permission denied`
948
+ );
949
+ }
950
+ this.checkCatalogVersion();
951
+ }
952
+ /**
953
+ * Starts the daemon: loads WASM modules, writes the PID file,
954
+ * creates the IPC socket, and begins listening for connections.
955
+ *
956
+ * Call `checkPreconditions()` before `start()` to validate the
957
+ * database directory. The daemon will not start if any precondition
958
+ * fails.
959
+ *
960
+ * @throws when WASM module loading fails or the IPC socket cannot
961
+ * be created
962
+ */
963
+ async start() {
964
+ const wasmModules = await loadWasmModules(
965
+ this.config,
966
+ this._wasmDir
967
+ );
968
+ this._wasmModules = wasmModules;
969
+ this.initWorkerContext();
970
+ const pidPath = (0, import_node_path7.join)((0, import_node_os2.tmpdir)(), `kbdb-${this.ctx}.pid`);
971
+ (0, import_node_fs4.writeFileSync)(pidPath, process.pid.toString());
972
+ const ipcPath = getIpcPath(this.ctx);
973
+ if ((0, import_node_fs4.existsSync)(ipcPath)) {
974
+ try {
975
+ (0, import_node_fs4.unlinkSync)(ipcPath);
976
+ } catch {
977
+ }
978
+ }
979
+ const handler = (req) => this.handleRequest(req);
980
+ this._server = createIpcServer(ipcPath, handler);
981
+ this._server.on("connection", () => {
982
+ this.incrementConnections();
983
+ this.resetIdleTimer();
984
+ });
985
+ this._server.on("close", () => {
986
+ this.decrementConnections();
987
+ if (this._connectionCount === 0) {
988
+ this.resetIdleTimer();
989
+ }
990
+ });
991
+ this.resetIdleTimer();
992
+ }
993
+ /**
994
+ * Gracefully shuts down the daemon.
995
+ *
996
+ * Stops accepting new connections, clears the idle timer, purges
997
+ * WASM state, removes the PID file and IPC socket file, then exits
998
+ * the process.
999
+ */
1000
+ stop() {
1001
+ if (this._idleTimer !== null) {
1002
+ clearTimeout(this._idleTimer);
1003
+ this._idleTimer = null;
1004
+ }
1005
+ if (this._server !== null) {
1006
+ this._server.close();
1007
+ this._server = null;
1008
+ }
1009
+ this._wasmModules = null;
1010
+ const pidPath = (0, import_node_path7.join)((0, import_node_os2.tmpdir)(), `kbdb-${this.ctx}.pid`);
1011
+ try {
1012
+ (0, import_node_fs4.unlinkSync)(pidPath);
1013
+ } catch {
1014
+ }
1015
+ const ipcPath = getIpcPath(this.ctx);
1016
+ try {
1017
+ (0, import_node_fs4.unlinkSync)(ipcPath);
1018
+ } catch {
1019
+ }
1020
+ const crashPath = (0, import_node_path7.join)((0, import_node_os2.tmpdir)(), `kbdb-${this.ctx}.crash`);
1021
+ try {
1022
+ (0, import_node_fs4.unlinkSync)(crashPath);
1023
+ } catch {
1024
+ }
1025
+ process.exit(0);
1026
+ }
1027
+ /**
1028
+ * Handles a single JSON-RPC 2.0 request.
1029
+ *
1030
+ * Validates context, then routes to a daemon-state handler or a
1031
+ * WASM export. Requests whose `ctx` param does not match the
1032
+ * daemon's context ID are rejected with error code `-32001`.
1033
+ *
1034
+ * @param request - incoming JSON-RPC request
1035
+ * @returns the JSON-RPC response
1036
+ */
1037
+ async handleRequest(request) {
1038
+ const params = request.params;
1039
+ if (params === void 0 || params.ctx !== this.ctx) {
1040
+ return this.errorResponse(
1041
+ request.id,
1042
+ -32001,
1043
+ "context mismatch"
1044
+ );
1045
+ }
1046
+ this.resetIdleTimer();
1047
+ try {
1048
+ const result = await this.dispatch(request.method, params);
1049
+ this._idleAt = Math.floor(Date.now() / 1e3);
1050
+ return {
1051
+ jsonrpc: "2.0",
1052
+ id: request.id,
1053
+ result
1054
+ };
1055
+ } catch (err) {
1056
+ this._idleAt = Math.floor(Date.now() / 1e3);
1057
+ if (err instanceof IpcError) {
1058
+ return this.errorResponse(
1059
+ request.id,
1060
+ err.code,
1061
+ err.message
1062
+ );
1063
+ }
1064
+ const message = err instanceof Error ? err.message : String(err);
1065
+ return this.errorResponse(request.id, -32e3, message);
1066
+ }
1067
+ }
1068
+ /**
1069
+ * Increments the active connection count.
1070
+ *
1071
+ * Call when a new IPC client connects.
1072
+ */
1073
+ incrementConnections() {
1074
+ this._connectionCount++;
1075
+ }
1076
+ /**
1077
+ * Decrements the active connection count, clamped to zero.
1078
+ *
1079
+ * Call when an IPC client disconnects.
1080
+ */
1081
+ decrementConnections() {
1082
+ if (this._connectionCount > 0) {
1083
+ this._connectionCount--;
1084
+ }
1085
+ }
1086
+ /**
1087
+ * Injects pre-built WASM modules for unit testing.
1088
+ *
1089
+ * This method exists solely to support unit tests that cannot
1090
+ * load real WASM binaries. It must not be called in production
1091
+ * code -- production code uses `start()` to load modules.
1092
+ *
1093
+ * @param modules - pre-built WASM module instances
1094
+ * @internal
1095
+ */
1096
+ injectModulesForTesting(modules) {
1097
+ this._wasmModules = modules;
1098
+ }
1099
+ // -----------------------------------------------------------------------
1100
+ // Private helpers
1101
+ // -----------------------------------------------------------------------
1102
+ /** Resets the idle timer; triggers stop() when it fires. */
1103
+ resetIdleTimer() {
1104
+ if (this._idleTimer !== null) {
1105
+ clearTimeout(this._idleTimer);
1106
+ }
1107
+ if (this._connectionCount === 0) {
1108
+ this._idleTimer = setTimeout(() => {
1109
+ this.stop();
1110
+ }, this.config.timeoutMs);
1111
+ }
1112
+ }
1113
+ /** Reads catalog.toml and validates the version field. */
1114
+ checkCatalogVersion() {
1115
+ const catalogPath = (0, import_node_path7.join)(this.targetDir, "catalog.toml");
1116
+ let text;
1117
+ try {
1118
+ text = (0, import_node_fs4.readFileSync)(catalogPath, "utf-8");
1119
+ } catch {
1120
+ throw new Error(
1121
+ `cannot read database directory: ${this.targetDir} -- permission denied`
1122
+ );
1123
+ }
1124
+ const version = parseCatalogVersion(text);
1125
+ if (version === null) {
1126
+ throw new Error(
1127
+ "database version 0 requires migration to version " + String(DB_FORMAT_VERSION) + " -- run `kbdb --migrate` before starting the daemon"
1128
+ );
1129
+ }
1130
+ if (version > DB_FORMAT_VERSION) {
1131
+ throw new Error(
1132
+ "database version " + String(version) + " is newer than kbdb version " + String(DB_FORMAT_VERSION) + " -- upgrade kbdb to open this database"
1133
+ );
1134
+ }
1135
+ if (version < DB_FORMAT_VERSION) {
1136
+ throw new Error(
1137
+ "database version " + String(version) + " requires migration to version " + String(DB_FORMAT_VERSION) + " -- run `kbdb --migrate` before starting the daemon"
1138
+ );
1139
+ }
1140
+ }
1141
+ /** Builds a JSON-RPC error response. */
1142
+ errorResponse(id, code, message) {
1143
+ return {
1144
+ jsonrpc: "2.0",
1145
+ id,
1146
+ error: { code, message }
1147
+ };
1148
+ }
1149
+ /**
1150
+ * Dispatches a request method to the appropriate handler.
1151
+ *
1152
+ * Handles daemon-state methods (`status`, `idle_at`,
1153
+ * `config_{key}`) inline and routes WASM methods to the
1154
+ * correct calling convention for each export.
1155
+ */
1156
+ dispatch(method, params) {
1157
+ if (method === "status") {
1158
+ return this._connectionCount > 0 ? "busy" : "idle";
1159
+ }
1160
+ if (method === "idle_at") {
1161
+ return this._idleAt;
1162
+ }
1163
+ if (method === "checkVersion") {
1164
+ return this.handleCheckVersion(params);
1165
+ }
1166
+ if (method.startsWith(CONFIG_PREFIX)) {
1167
+ return this.handleConfigMethod(method);
1168
+ }
1169
+ const wasmMethod = WASM_METHOD_MAP[method];
1170
+ if (wasmMethod !== void 0) {
1171
+ return this.dispatchWasm(method, wasmMethod, params);
1172
+ }
1173
+ throw new IpcError(-32601, `Method not found: ${method}`);
1174
+ }
1175
+ dispatchWasm(method, wasmExport, params) {
1176
+ if (method === "search" || method === "query") {
1177
+ return this.handleSearch(params);
1178
+ }
1179
+ if (method === "addSection" || method === "add_section") {
1180
+ return this.handleAddSection(params);
1181
+ }
1182
+ if (method === "updateSection" || method === "update_section") {
1183
+ return this.handleUpdateSection(params);
1184
+ }
1185
+ if (method === "removeSection" || method === "remove_section") {
1186
+ return this.handleRemoveSection(params);
1187
+ }
1188
+ if (method === "readSections" || method === "read_sections") {
1189
+ return this.handleReadSections(params);
1190
+ }
1191
+ if (method === "retrieveDocument" || method === "retrieve_doc") {
1192
+ return this.handleRetrieveDoc(params);
1193
+ }
1194
+ if (method === "groupSections" || method === "group_sections") {
1195
+ return this.handleGroupSections(params);
1196
+ }
1197
+ if (method === "removeGrouping" || method === "remove_grouping") {
1198
+ return this.handleRemoveGrouping(params);
1199
+ }
1200
+ if (method === "content" || method === "compose") {
1201
+ return this.handleCompose(params);
1202
+ }
1203
+ if (method === "integrityCheck" || method === "integrity_check") {
1204
+ return this.handleIntegrityCheck();
1205
+ }
1206
+ if (method === "gc") {
1207
+ return this.handleGc();
1208
+ }
1209
+ if (method === "rebuildIndexes" || method === "rebuild_indexes") {
1210
+ return this.handleRebuild();
1211
+ }
1212
+ if (method === "dbStatus" || method === "db_status") {
1213
+ return this.handleDbStatus();
1214
+ }
1215
+ if (method === "initDirectory" || method === "init_directory") {
1216
+ return this.handleInitDirectory(params);
1217
+ }
1218
+ if (method === "invalidate") {
1219
+ return this.handleInvalidate(params);
1220
+ }
1221
+ if (method === "invalidateAll" || method === "invalidate_all") {
1222
+ return this.handleInvalidateAll();
1223
+ }
1224
+ if (method === "get_result_status") {
1225
+ return this.handleResultStatus(params);
1226
+ }
1227
+ if (method === "get_result") {
1228
+ return this.handleGetResult(params);
1229
+ }
1230
+ if (method === "migrateDatabase") {
1231
+ throw new IpcError(
1232
+ -32601,
1233
+ "migrateDatabase is not yet supported"
1234
+ );
1235
+ }
1236
+ if (method === "listByType" || method === "list_by_type") {
1237
+ return this.handleListByType(params);
1238
+ }
1239
+ if (method === "listDocumentsByType" || method === "list_docs_by_type") {
1240
+ return this.handleListDocsByType(params);
1241
+ }
1242
+ return this.invokeWasmRaw(wasmExport, new Uint8Array(0));
1243
+ }
1244
+ // -- Search/query (token-based async) --
1245
+ handleSearch(params) {
1246
+ const query = params["query"] ?? "";
1247
+ const mode = params["mode"] ?? "and";
1248
+ const limit = Number(params["limit"] ?? 20);
1249
+ const encoded = encodeSearchParams(query, mode, limit);
1250
+ const searchFn = this.getExport("worker_search");
1251
+ const ptr = this.wasmAlloc(encoded.length);
1252
+ this.wasmWrite(ptr, encoded);
1253
+ const token = searchFn(ptr, encoded.length);
1254
+ this.wasmFree(ptr, encoded.length);
1255
+ const statusFn = this.getExport("worker_result_status");
1256
+ const status = statusFn(token);
1257
+ if (status === 3) {
1258
+ const getResultFn2 = this.getExport("worker_get_result");
1259
+ getResultFn2(token);
1260
+ const errBytes = this.readReturnSlot();
1261
+ const errMsg = new TextDecoder().decode(errBytes);
1262
+ throw new IpcError(-32e3, errMsg);
1263
+ }
1264
+ const getResultFn = this.getExport("worker_get_result");
1265
+ const rc = getResultFn(token);
1266
+ if (rc === -1) {
1267
+ const errBytes = this.readReturnSlot();
1268
+ throw new IpcError(-32e3, new TextDecoder().decode(errBytes));
1269
+ }
1270
+ const resultBytes = this.readReturnSlot();
1271
+ return decodeScoredResults(resultBytes);
1272
+ }
1273
+ // -- Token status/result (u32 direct params) --
1274
+ handleResultStatus(params) {
1275
+ const token = Number(params["token"] ?? 0);
1276
+ const fn = this.getExport("worker_result_status");
1277
+ const status = fn(token);
1278
+ return { status };
1279
+ }
1280
+ handleGetResult(params) {
1281
+ const token = Number(params["token"] ?? 0);
1282
+ const fn = this.getExport("worker_get_result");
1283
+ const rc = fn(token);
1284
+ if (rc === -1) {
1285
+ const errBytes = this.readReturnSlot();
1286
+ throw new IpcError(-32e3, new TextDecoder().decode(errBytes));
1287
+ }
1288
+ const bytes = this.readReturnSlot();
1289
+ return decodeScoredResults(bytes);
1290
+ }
1291
+ // -- Binary-encoded input methods --
1292
+ handleAddSection(params) {
1293
+ const sectionType = params["sectionType"] ?? "text";
1294
+ const semanticType = sectionType === "text" || sectionType === "code" || sectionType === "image" ? sectionType : "text";
1295
+ const typeName = sectionType !== semanticType ? sectionType : null;
1296
+ const input = {
1297
+ sectionType: semanticType,
1298
+ mimeType: params["mimeType"],
1299
+ content: params["content"] ?? "",
1300
+ title: params["title"] ?? null,
1301
+ description: params["description"] ?? null,
1302
+ docid: params["docid"] ?? null,
1303
+ typeName
1304
+ };
1305
+ const encoded = encodeAddSectionParams(input);
1306
+ const bytes = this.callWasmSync("worker_add_section", encoded);
1307
+ const kbid = new TextDecoder().decode(bytes);
1308
+ return { kbid };
1309
+ }
1310
+ handleUpdateSection(params) {
1311
+ const oldKbid = params["kbid"] ?? "";
1312
+ const updSectionType = params["sectionType"] ?? "text";
1313
+ const updSemanticType = updSectionType === "text" || updSectionType === "code" || updSectionType === "image" ? updSectionType : "text";
1314
+ const updTypeName = updSectionType !== updSemanticType ? updSectionType : null;
1315
+ const input = {
1316
+ sectionType: updSemanticType,
1317
+ mimeType: params["mimeType"],
1318
+ content: params["content"] ?? "",
1319
+ title: params["title"] ?? null,
1320
+ description: params["description"] ?? null,
1321
+ docid: params["docid"] ?? null,
1322
+ typeName: updTypeName
1323
+ };
1324
+ const encoded = encodeUpdateSectionParams(oldKbid, input);
1325
+ const bytes = this.callWasmSync("worker_update_section", encoded);
1326
+ const newKbid = new TextDecoder().decode(bytes);
1327
+ return { kbid: newKbid };
1328
+ }
1329
+ handleReadSections(params) {
1330
+ const kbids = params["kbids"] ?? [];
1331
+ const encoded = encodeKbidList(kbids);
1332
+ const bytes = this.callWasmSync("worker_read_sections", encoded);
1333
+ return decodeSectionRecords(bytes);
1334
+ }
1335
+ handleGroupSections(params) {
1336
+ const title = params["title"] ?? "";
1337
+ const kbids = params["kbids"] ?? [];
1338
+ const docType = params["docType"] ?? "";
1339
+ const encoded = encodeGroupParams(title, kbids, docType);
1340
+ const bytes = this.callWasmSync("worker_group_sections", encoded);
1341
+ const docid = new TextDecoder().decode(bytes);
1342
+ return { docid };
1343
+ }
1344
+ handleCompose(params) {
1345
+ const ids = params["ids"] ?? [];
1346
+ const encoded = encodeIdentifierList(ids);
1347
+ const bytes = this.callWasmSync("worker_compose", encoded);
1348
+ const output = decodeComposeOutput(bytes);
1349
+ return {
1350
+ data: output.markdown,
1351
+ total: Number(output.totalChars)
1352
+ };
1353
+ }
1354
+ // -- Raw UTF-8 string input methods --
1355
+ handleRemoveSection(params) {
1356
+ const kbid = params["kbid"] ?? "";
1357
+ const encoded = new TextEncoder().encode(kbid);
1358
+ const bytes = this.callWasmSync("worker_remove_section", encoded);
1359
+ return { removed: decodeRemoveFlag(bytes) };
1360
+ }
1361
+ handleRetrieveDoc(params) {
1362
+ const docid = params["docid"] ?? "";
1363
+ const encoded = new TextEncoder().encode(docid);
1364
+ const bytes = this.callWasmSync("worker_retrieve_doc", encoded);
1365
+ return decodeDocumentManifest(bytes);
1366
+ }
1367
+ handleRemoveGrouping(params) {
1368
+ const docid = params["docid"] ?? "";
1369
+ const encoded = new TextEncoder().encode(docid);
1370
+ this.callWasmSync("worker_remove_grouping", encoded);
1371
+ return { ok: true };
1372
+ }
1373
+ handleInitDirectory(params) {
1374
+ const path = params["path"] ?? this.targetDir;
1375
+ const encoded = new TextEncoder().encode(path);
1376
+ this.callWasmSync("worker_init_directory", encoded);
1377
+ return { ok: true };
1378
+ }
1379
+ handleInvalidate(params) {
1380
+ const kbid = params["kbid"] ?? "";
1381
+ const encoded = new TextEncoder().encode(kbid);
1382
+ this.callWasmSync("worker_invalidate", encoded);
1383
+ return { ok: true };
1384
+ }
1385
+ handleListByType(params) {
1386
+ const typeStr = params["sectionType"] ?? "";
1387
+ const encoded = encodeTypeFilterParam(typeStr);
1388
+ const bytes = this.callWasmSync("worker_list_by_type", encoded);
1389
+ return decodeSectionRecordList(bytes);
1390
+ }
1391
+ handleListDocsByType(params) {
1392
+ const typeStr = params["docType"] ?? "";
1393
+ const encoded = encodeTypeFilterParam(typeStr);
1394
+ const bytes = this.callWasmSync(
1395
+ "worker_list_docs_by_type",
1396
+ encoded
1397
+ );
1398
+ return decodeDocumentManifestList(bytes);
1399
+ }
1400
+ // -- Zero-arg methods --
1401
+ handleInvalidateAll() {
1402
+ this.callWasmZeroArg("worker_invalidate_all");
1403
+ return { ok: true };
1404
+ }
1405
+ handleDbStatus() {
1406
+ this.callWasmZeroArg("worker_status");
1407
+ const bytes = this.readReturnSlot();
1408
+ const text = new TextDecoder().decode(bytes);
1409
+ return decodeKeyValueText(text);
1410
+ }
1411
+ handleIntegrityCheck() {
1412
+ this.callWasmZeroArg("worker_check_integrity");
1413
+ const bytes = this.readReturnSlot();
1414
+ const text = new TextDecoder().decode(bytes);
1415
+ return decodeKeyValueText(text);
1416
+ }
1417
+ handleGc() {
1418
+ this.callWasmZeroArg("worker_garbage_collect");
1419
+ const bytes = this.readReturnSlot();
1420
+ const text = new TextDecoder().decode(bytes);
1421
+ return decodeKeyValueText(text);
1422
+ }
1423
+ handleRebuild() {
1424
+ this.callWasmZeroArg("worker_rebuild_indexes");
1425
+ return { ok: true };
1426
+ }
1427
+ // -- WASM lifecycle --
1428
+ initWorkerContext() {
1429
+ const pathBytes = new TextEncoder().encode(".");
1430
+ this.callWasmSync("worker_init", pathBytes);
1431
+ }
1432
+ // -- WASM bridge primitives --
1433
+ getExport(name) {
1434
+ if (this._wasmModules === null) {
1435
+ throw new Error("WASM modules not loaded");
1436
+ }
1437
+ const fn = this._wasmModules.kbWorker.exports[name];
1438
+ if (typeof fn !== "function") {
1439
+ throw new Error(`WASM export not found: ${name}`);
1440
+ }
1441
+ return fn;
1442
+ }
1443
+ wasmAlloc(size) {
1444
+ if (size === 0) return 0;
1445
+ const allocFn = this._wasmModules?.kbWorker.exports["kbdb_alloc"];
1446
+ if (typeof allocFn !== "function") return 0;
1447
+ return allocFn(size);
1448
+ }
1449
+ wasmFree(ptr, size) {
1450
+ if (ptr === 0 || size === 0) return;
1451
+ const freeFn = this._wasmModules?.kbWorker.exports["kbdb_free"];
1452
+ if (typeof freeFn === "function") {
1453
+ freeFn(ptr, size);
1454
+ }
1455
+ }
1456
+ wasmWrite(ptr, data) {
1457
+ if (data.length === 0) return;
1458
+ const memory = this._wasmModules?.memory;
1459
+ if (!memory) return;
1460
+ const memView = new Uint8Array(memory.buffer);
1461
+ if (ptr + data.length > memView.length) {
1462
+ throw new Error("WASM memory overflow");
1463
+ }
1464
+ memView.set(data, ptr);
1465
+ }
1466
+ readReturnSlot() {
1467
+ const getPtrFn = this._wasmModules?.kbWorker.exports["get_return_ptr"];
1468
+ const getLenFn = this._wasmModules?.kbWorker.exports["get_return_len"];
1469
+ if (typeof getPtrFn !== "function" || typeof getLenFn !== "function") {
1470
+ return new Uint8Array(0);
1471
+ }
1472
+ const ptr = getPtrFn();
1473
+ const len = getLenFn();
1474
+ if (ptr === 0 || len === 0) {
1475
+ return new Uint8Array(0);
1476
+ }
1477
+ const memory = this._wasmModules?.memory;
1478
+ if (!memory) return new Uint8Array(0);
1479
+ const data = new Uint8Array(memory.buffer, ptr, len).slice();
1480
+ this.wasmFree(ptr, len);
1481
+ return data;
1482
+ }
1483
+ callWasmSync(exportName, input) {
1484
+ const fn = this.getExport(exportName);
1485
+ const ptr = this.wasmAlloc(input.length);
1486
+ this.wasmWrite(ptr, input);
1487
+ const rc = fn(ptr, input.length);
1488
+ this.wasmFree(ptr, input.length);
1489
+ if (rc === -1) {
1490
+ const errBytes = this.readReturnSlot();
1491
+ const errMsg = new TextDecoder().decode(errBytes);
1492
+ throw new IpcError(-32e3, errMsg || exportName + " failed");
1493
+ }
1494
+ return this.readReturnSlot();
1495
+ }
1496
+ callWasmZeroArg(exportName) {
1497
+ const fn = this.getExport(exportName);
1498
+ const rc = fn();
1499
+ if (rc === -1) {
1500
+ const errBytes = this.readReturnSlot();
1501
+ const errMsg = new TextDecoder().decode(errBytes);
1502
+ throw new IpcError(-32e3, errMsg || exportName + " failed");
1503
+ }
1504
+ }
1505
+ invokeWasmRaw(exportName, input) {
1506
+ return this.callWasmSync(exportName, input);
1507
+ }
1508
+ handleCheckVersion(params) {
1509
+ const targetPath = typeof params.targetPath === "string" ? params.targetPath : this.targetDir;
1510
+ const catalogPath = (0, import_node_path7.join)(targetPath, "catalog.toml");
1511
+ let text;
1512
+ try {
1513
+ text = (0, import_node_fs4.readFileSync)(catalogPath, "utf-8");
1514
+ } catch {
1515
+ return {
1516
+ status: "needs_migration",
1517
+ currentVersion: 0,
1518
+ requiredVersion: DB_FORMAT_VERSION
1519
+ };
1520
+ }
1521
+ const version = parseCatalogVersion(text);
1522
+ if (version === null) {
1523
+ return {
1524
+ status: "needs_migration",
1525
+ currentVersion: 0,
1526
+ requiredVersion: DB_FORMAT_VERSION
1527
+ };
1528
+ }
1529
+ if (version > DB_FORMAT_VERSION) {
1530
+ return {
1531
+ status: "too_new",
1532
+ currentVersion: version,
1533
+ requiredVersion: DB_FORMAT_VERSION
1534
+ };
1535
+ }
1536
+ if (version < DB_FORMAT_VERSION) {
1537
+ return {
1538
+ status: "needs_migration",
1539
+ currentVersion: version,
1540
+ requiredVersion: DB_FORMAT_VERSION
1541
+ };
1542
+ }
1543
+ return {
1544
+ status: "compatible",
1545
+ currentVersion: version,
1546
+ requiredVersion: DB_FORMAT_VERSION
1547
+ };
1548
+ }
1549
+ /** Returns a daemon config value by config method name. */
1550
+ handleConfigMethod(method) {
1551
+ const key = method.slice(CONFIG_PREFIX.length);
1552
+ const prop = CONFIG_KEY_MAP[key];
1553
+ if (prop === void 0) {
1554
+ throw new IpcError(-32601, `Method not found: ${method}`);
1555
+ }
1556
+ return this.config[prop];
1557
+ }
1558
+ };
1559
+ function parseCatalogVersion(text) {
1560
+ for (const line of text.split("\n")) {
1561
+ const trimmed = line.trim();
1562
+ if (trimmed.startsWith("#")) continue;
1563
+ const match = /^version\s*=\s*(\d+)/.exec(trimmed);
1564
+ if (match?.[1] !== void 0) {
1565
+ return parseInt(match[1], 10);
1566
+ }
1567
+ }
1568
+ return null;
1569
+ }
1570
+
1571
+ // src/shared/worker-daemon/functions/start-daemon.function.ts
1572
+ async function startDaemon(contextPath, wasmDir2) {
1573
+ const config = readConfig(contextPath);
1574
+ const hash = await computeSha256(contextPath);
1575
+ const contextId = hash.slice(0, 16);
1576
+ const daemon = new WorkerDaemon(
1577
+ contextId,
1578
+ contextPath,
1579
+ config,
1580
+ wasmDir2
1581
+ );
1582
+ try {
1583
+ daemon.checkPreconditions();
1584
+ } catch (err) {
1585
+ const message = err instanceof Error ? err.message : String(err);
1586
+ console.error(`kbdb-worker: ${message}`);
1587
+ writeCrashLog(contextId, message);
1588
+ process.exit(1);
1589
+ }
1590
+ try {
1591
+ await daemon.start();
1592
+ } catch (err) {
1593
+ const message = err instanceof Error ? err.message : String(err);
1594
+ console.error(`kbdb-worker: ${message}`);
1595
+ writeCrashLog(contextId, message);
1596
+ process.exit(1);
1597
+ }
1598
+ process.on("SIGTERM", () => {
1599
+ daemon.stop();
1600
+ });
1601
+ process.on("SIGINT", () => {
1602
+ daemon.stop();
1603
+ });
1604
+ }
1605
+ function writeCrashLog(contextId, message) {
1606
+ try {
1607
+ const crashPath = (0, import_node_path8.join)((0, import_node_os3.tmpdir)(), `kbdb-${contextId}.crash`);
1608
+ const payload = JSON.stringify({
1609
+ error: message,
1610
+ timestamp: Date.now()
1611
+ });
1612
+ (0, import_node_fs5.writeFileSync)(crashPath, payload);
1613
+ } catch {
1614
+ }
1615
+ }
1616
+
1617
+ // src/shared/worker-daemon/functions/run-worker.function.ts
1618
+ var import_node_path9 = require("node:path");
1619
+ async function runWorker(argv, deps) {
1620
+ const contextPath = argv[0];
1621
+ if (!contextPath) {
1622
+ return {
1623
+ error: "usage: kbdb-worker <context-path>",
1624
+ exitCode: 1
1625
+ };
1626
+ }
1627
+ const resolved = (0, import_node_path9.resolve)(contextPath);
1628
+ if (!deps.existsSync(resolved)) {
1629
+ return {
1630
+ error: `error: path not found: ${resolved}`,
1631
+ exitCode: 1
1632
+ };
1633
+ }
1634
+ await deps.startDaemon(resolved, deps.wasmDir);
1635
+ return { exitCode: 0 };
1636
+ }
1637
+
1638
+ // src/worker.ts
1639
+ var import_meta = {};
1640
+ var baseDir = resolveBaseDir(import_meta.url, import_meta.dirname);
1641
+ var wasmDir = resolveWasmDir(baseDir.scriptDir);
1642
+ async function main() {
1643
+ const result = await runWorker(getArgs(), {
1644
+ existsSync: import_node_fs6.existsSync,
1645
+ startDaemon,
1646
+ wasmDir
1647
+ });
1648
+ if (result.error) {
1649
+ console.error(result.error);
1650
+ }
1651
+ if (result.exitCode !== 0) {
1652
+ process.exitCode = result.exitCode;
1653
+ }
1654
+ }
1655
+ main().catch((err) => {
1656
+ console.error(err);
1657
+ process.exitCode = 1;
1658
+ });
1659
+ //# sourceMappingURL=kbdb-worker.cjs.map