@dikolab/kbdb 0.3.2 → 0.4.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 (466) hide show
  1. package/README.md +83 -89
  2. package/dist/chunk-BJPSPNGX.mjs +223 -0
  3. package/dist/chunk-BJPSPNGX.mjs.map +7 -0
  4. package/dist/cli.cjs +956 -319
  5. package/dist/cli.cjs.map +4 -4
  6. package/dist/cli.d.ts +9 -0
  7. package/dist/cli.mjs +840 -321
  8. package/dist/cli.mjs.map +4 -4
  9. package/dist/kbdb-worker.cjs +714 -94
  10. package/dist/kbdb-worker.cjs.map +4 -4
  11. package/dist/mod.cjs +122 -16
  12. package/dist/mod.cjs.map +3 -3
  13. package/dist/mod.d.ts +23 -2
  14. package/dist/mod.mjs +121 -16
  15. package/dist/mod.mjs.map +3 -3
  16. package/dist/src/shared/cli/functions/dispatch-command.function.d.ts +2 -1
  17. package/dist/src/shared/cli/functions/find-db.function.d.ts +7 -8
  18. package/dist/src/shared/cli/functions/handle-mcp.function.d.ts +1 -1
  19. package/dist/src/shared/cli/functions/parse-args.function.d.ts +4 -3
  20. package/dist/src/shared/cli/functions/resolve-kbid-prefix.function.d.ts +27 -0
  21. package/dist/src/shared/cli/functions/resolve-raw-db-path.function.d.ts +10 -0
  22. package/dist/src/shared/cli/functions/run-cli.function.d.ts +3 -1
  23. package/dist/src/shared/cli/functions/run-content.function.d.ts +8 -3
  24. package/dist/src/shared/cli/functions/run-import.function.d.ts +27 -0
  25. package/dist/src/shared/cli/functions/run-recall.function.d.ts +10 -4
  26. package/dist/src/shared/cli/functions/run-search.function.d.ts +7 -0
  27. package/dist/src/shared/cli/functions/run-unlearn.function.d.ts +9 -4
  28. package/dist/src/shared/cli/functions/run-worker-restart.function.d.ts +11 -0
  29. package/dist/src/shared/cli/functions/run-worker-stop.function.d.ts +11 -0
  30. package/dist/src/shared/cli/index.d.ts +2 -0
  31. package/dist/src/shared/cli/typings/cli-deps.interface.d.ts +4 -1
  32. package/dist/src/shared/cli/typings/cli-options.interface.d.ts +17 -0
  33. package/dist/src/shared/cli/typings/dispatch-client.type.d.ts +2 -1
  34. package/dist/src/shared/cli/typings/search-display.model.d.ts +6 -0
  35. package/dist/src/shared/embedding/classes/api-embedding-provider.class.d.ts +33 -0
  36. package/dist/src/shared/embedding/classes/onnx-embedding-provider.class.d.ts +33 -0
  37. package/dist/src/shared/embedding/functions/append-vector-entry.function.d.ts +14 -0
  38. package/dist/src/shared/embedding/functions/create-embedding-provider.function.d.ts +12 -0
  39. package/dist/src/shared/embedding/functions/detect-stale-vectors.function.d.ts +16 -0
  40. package/dist/src/shared/embedding/functions/parse-api-embedding-response.function.d.ts +11 -0
  41. package/dist/src/shared/embedding/functions/rebuild-vectors.function.d.ts +15 -0
  42. package/dist/src/shared/embedding/functions/scan-semantic-contradictions.function.d.ts +13 -0
  43. package/dist/src/shared/embedding/index.d.ts +7 -0
  44. package/dist/src/shared/embedding/typings/semantic-contradiction.model.d.ts +21 -0
  45. package/dist/src/shared/embedding/typings/stale-vectors-report.model.d.ts +16 -0
  46. package/dist/src/shared/mcp/classes/mcp-server.class.d.ts +22 -2
  47. package/dist/src/shared/mcp/functions/create-mcp-server.function.d.ts +6 -1
  48. package/dist/src/shared/mcp/functions/has-sampling-capability.function.d.ts +8 -0
  49. package/dist/src/shared/mcp/functions/run-auto-capture.function.d.ts +26 -0
  50. package/dist/src/shared/mcp/typings/mcp-client.interface.d.ts +2 -0
  51. package/dist/src/shared/mcp/typings/mcp-integrity-check-result.model.d.ts +24 -0
  52. package/dist/src/shared/mcp/typings/mcp-worker-client.interface.d.ts +3 -1
  53. package/dist/src/shared/version/constants/version.constant.d.ts +1 -1
  54. package/dist/src/shared/wasm-codec/typings/paged-search-result.model.d.ts +2 -0
  55. package/dist/src/shared/worker-client/classes/worker-client.class.d.ts +31 -1
  56. package/dist/src/shared/worker-client/constants/request-timeout.constant.d.ts +2 -0
  57. package/dist/src/shared/worker-client/constants/retry-defaults.constant.d.ts +2 -0
  58. package/dist/src/shared/worker-client/functions/get-or-create-client.function.d.ts +20 -0
  59. package/dist/src/shared/worker-client/functions/retry-on-timeout.function.d.ts +17 -0
  60. package/dist/src/shared/worker-client/index.d.ts +4 -1
  61. package/dist/src/shared/worker-client/typings/import-result.model.d.ts +16 -0
  62. package/dist/src/shared/worker-client/typings/integrity-check-result.model.d.ts +24 -0
  63. package/dist/src/shared/worker-client/typings/search-params.model.d.ts +4 -0
  64. package/dist/src/shared/worker-client/typings/search-result.model.d.ts +6 -0
  65. package/dist/src/shared/worker-client/typings/worker-client-options.interface.d.ts +7 -0
  66. package/dist/src/shared/worker-daemon/classes/worker-daemon.class.d.ts +5 -0
  67. package/dist/src/shared/worker-daemon/functions/create-ipc-server.function.d.ts +11 -11
  68. package/dist/src/shared/worker-daemon/functions/embed-after-learn.function.d.ts +13 -0
  69. package/dist/src/shared/worker-daemon/functions/handle-hybrid-search.function.d.ts +44 -0
  70. package/dist/src/shared/worker-daemon/functions/handle-import.function.d.ts +14 -0
  71. package/dist/src/shared/worker-daemon/functions/handle-read-ops.function.d.ts +7 -1
  72. package/dist/src/shared/worker-daemon/functions/handle-write-ops.function.d.ts +9 -4
  73. package/dist/src/shared/worker-daemon/typings/handler-context.interface.d.ts +3 -0
  74. package/dist/wasm/fs-database/kbdb_fs_database.d.ts +16 -85
  75. package/dist/wasm/fs-database/kbdb_fs_database.js +16 -85
  76. package/dist/wasm/fs-database/kbdb_fs_database_bg.wasm +0 -0
  77. package/dist/wasm/kb-worker/kbdb_worker.d.ts +20 -115
  78. package/dist/wasm/kb-worker/kbdb_worker.js +20 -115
  79. package/dist/wasm/kb-worker/kbdb_worker_bg.wasm +0 -0
  80. package/dist/wasm/query-parser/kbdb_query_parser_bg.wasm +0 -0
  81. package/dist/worker.d.ts +8 -0
  82. package/dist/worker.mjs +606 -102
  83. package/dist/worker.mjs.map +4 -4
  84. package/docs/details/README.md +4 -0
  85. package/docs/details/agent-tooling.md +122 -0
  86. package/docs/details/cli.md +70 -13
  87. package/docs/details/knowledge-base.md +173 -0
  88. package/docs/details/library-api.md +42 -2
  89. package/docs/details/mcp-server.md +38 -7
  90. package/docs/details/search-and-ranking.md +11 -10
  91. package/docs/goals/cli.md +110 -34
  92. package/docs/goals/mcp.md +22 -19
  93. package/docs/goals/query-parser.md +8 -0
  94. package/docs/goals/worker-client.md +62 -1
  95. package/docs/goals/worker-daemon.md +52 -10
  96. package/docs/modules/typescript/cli.md +1 -1
  97. package/docs/modules/typescript/shared/cli/functions.md +116 -13
  98. package/docs/modules/typescript/shared/cli/module.md +33 -20
  99. package/docs/modules/typescript/shared/cli/typings.md +4 -0
  100. package/docs/modules/typescript/shared/embedding/functions.md +104 -25
  101. package/docs/modules/typescript/shared/mcp/module.md +1 -1
  102. package/docs/modules/typescript/shared/mcp/typings.md +8 -1
  103. package/docs/modules/typescript/shared/worker-client/module.md +9 -1
  104. package/docs/modules/typescript/shared/worker-client/typings.md +3 -0
  105. package/docs/modules/typescript/shared/worker-daemon/module.md +6 -3
  106. package/docs/overview.md +1 -2
  107. package/docs/release-notes/0.4.0.md +80 -0
  108. package/docs/release-notes/README.md +1 -0
  109. package/mod.ts +33 -15
  110. package/package.json +11 -10
  111. package/dist/chunk-JG2UCKLI.mjs +0 -95
  112. package/dist/chunk-JG2UCKLI.mjs.map +0 -7
  113. package/src/cli.ts +0 -71
  114. package/src/shared/auto-capture/classes/auto-capture-controller.class.ts +0 -62
  115. package/src/shared/auto-capture/constants/auto-capture-defaults.constant.ts +0 -15
  116. package/src/shared/auto-capture/functions/build-capture-prompt.function.ts +0 -27
  117. package/src/shared/auto-capture/functions/evaluate-trigger.function.ts +0 -50
  118. package/src/shared/auto-capture/index.ts +0 -7
  119. package/src/shared/auto-capture/typings/auto-capture-config.interface.ts +0 -13
  120. package/src/shared/auto-capture/typings/auto-capture-state.interface.ts +0 -13
  121. package/src/shared/auto-capture/typings/auto-capture-trigger.interface.ts +0 -7
  122. package/src/shared/cli/constants/defaults.constant.ts +0 -19
  123. package/src/shared/cli/constants/global-help.constant.ts +0 -73
  124. package/src/shared/cli/constants/help-text.constant.ts +0 -4
  125. package/src/shared/cli/constants/leaf-help.constant.ts +0 -219
  126. package/src/shared/cli/constants/memory-protocol-body.constant.ts +0 -39
  127. package/src/shared/cli/constants/query-guidance-body.constant.ts +0 -37
  128. package/src/shared/cli/constants/subcommand-help.constant.ts +0 -195
  129. package/src/shared/cli/functions/collect-files.function.ts +0 -55
  130. package/src/shared/cli/functions/compute-section-kbid.function.ts +0 -49
  131. package/src/shared/cli/functions/dispatch-command.function.ts +0 -390
  132. package/src/shared/cli/functions/ensure-db.function.ts +0 -21
  133. package/src/shared/cli/functions/error-to-message.function.ts +0 -9
  134. package/src/shared/cli/functions/find-db.function.ts +0 -20
  135. package/src/shared/cli/functions/format-mcp-output.function.ts +0 -41
  136. package/src/shared/cli/functions/format-output.function.ts +0 -95
  137. package/src/shared/cli/functions/format-text-output.function.ts +0 -42
  138. package/src/shared/cli/functions/generate-group-help.function.ts +0 -41
  139. package/src/shared/cli/functions/generate-help.function.ts +0 -654
  140. package/src/shared/cli/functions/handle-data-command.function.ts +0 -67
  141. package/src/shared/cli/functions/handle-mcp.function.ts +0 -56
  142. package/src/shared/cli/functions/handle-migrate.function.ts +0 -64
  143. package/src/shared/cli/functions/hydrate-search-previews.function.ts +0 -29
  144. package/src/shared/cli/functions/install-default-skills.function.ts +0 -296
  145. package/src/shared/cli/functions/is-stdin-tty.function.ts +0 -12
  146. package/src/shared/cli/functions/parse-args.function.ts +0 -156
  147. package/src/shared/cli/functions/prompt-user.function.ts +0 -36
  148. package/src/shared/cli/functions/resolve-skill-names.function.ts +0 -43
  149. package/src/shared/cli/functions/run-agent-create.function.ts +0 -114
  150. package/src/shared/cli/functions/run-agent-delete.function.ts +0 -47
  151. package/src/shared/cli/functions/run-agent-get.function.ts +0 -166
  152. package/src/shared/cli/functions/run-agent-list.function.ts +0 -58
  153. package/src/shared/cli/functions/run-check.function.ts +0 -159
  154. package/src/shared/cli/functions/run-cli.function.ts +0 -299
  155. package/src/shared/cli/functions/run-content.function.ts +0 -47
  156. package/src/shared/cli/functions/run-db-init.function.ts +0 -44
  157. package/src/shared/cli/functions/run-db-migrate.function.ts +0 -40
  158. package/src/shared/cli/functions/run-export.function.ts +0 -40
  159. package/src/shared/cli/functions/run-gc.function.ts +0 -51
  160. package/src/shared/cli/functions/run-init.function.ts +0 -93
  161. package/src/shared/cli/functions/run-learn.function.ts +0 -223
  162. package/src/shared/cli/functions/run-migrate.function.ts +0 -85
  163. package/src/shared/cli/functions/run-rebuild.function.ts +0 -47
  164. package/src/shared/cli/functions/run-recall.function.ts +0 -66
  165. package/src/shared/cli/functions/run-search.function.ts +0 -133
  166. package/src/shared/cli/functions/run-skill-delete.function.ts +0 -47
  167. package/src/shared/cli/functions/run-skill-get.function.ts +0 -90
  168. package/src/shared/cli/functions/run-skill-learn.function.ts +0 -70
  169. package/src/shared/cli/functions/run-skill-list.function.ts +0 -74
  170. package/src/shared/cli/functions/run-status.function.ts +0 -29
  171. package/src/shared/cli/functions/run-unlearn.function.ts +0 -58
  172. package/src/shared/cli/functions/version-gate.function.ts +0 -44
  173. package/src/shared/cli/functions/wrap-command.function.ts +0 -34
  174. package/src/shared/cli/index.ts +0 -55
  175. package/src/shared/cli/typings/agent-create-client.interface.ts +0 -47
  176. package/src/shared/cli/typings/agent-get-client.interface.ts +0 -39
  177. package/src/shared/cli/typings/check-client.interface.ts +0 -66
  178. package/src/shared/cli/typings/cli-deps.interface.ts +0 -54
  179. package/src/shared/cli/typings/cli-options.interface.ts +0 -72
  180. package/src/shared/cli/typings/command-result.model.ts +0 -15
  181. package/src/shared/cli/typings/disconnectable-client.interface.ts +0 -29
  182. package/src/shared/cli/typings/dispatch-client.type.ts +0 -46
  183. package/src/shared/cli/typings/learn-client.interface.ts +0 -53
  184. package/src/shared/cli/typings/learn-io.interface.ts +0 -5
  185. package/src/shared/cli/typings/learn-result.model.ts +0 -27
  186. package/src/shared/cli/typings/search-client.interface.ts +0 -73
  187. package/src/shared/cli/typings/search-display.model.ts +0 -54
  188. package/src/shared/dir-resolver/functions/join-path.function.ts +0 -13
  189. package/src/shared/dir-resolver/functions/resolve-base-dir.function.ts +0 -25
  190. package/src/shared/dir-resolver/functions/resolve-wasm-dir.function.ts +0 -5
  191. package/src/shared/dir-resolver/functions/resolve-worker-script.function.ts +0 -13
  192. package/src/shared/dir-resolver/index.ts +0 -11
  193. package/src/shared/dir-resolver/typings/base-dir.interface.ts +0 -4
  194. package/src/shared/embedding/classes/null-embedding-provider.class.ts +0 -29
  195. package/src/shared/embedding/constants/near-duplicate-thresholds.constant.ts +0 -17
  196. package/src/shared/embedding/functions/build-vector-index.function.ts +0 -79
  197. package/src/shared/embedding/functions/cosine-similarity.function.ts +0 -31
  198. package/src/shared/embedding/functions/detect-near-duplicates.function.ts +0 -69
  199. package/src/shared/embedding/functions/jaccard-coefficient.function.ts +0 -26
  200. package/src/shared/embedding/functions/read-vector-index-meta.function.ts +0 -44
  201. package/src/shared/embedding/functions/rrf-fuse.function.ts +0 -33
  202. package/src/shared/embedding/functions/search-vectors.function.ts +0 -59
  203. package/src/shared/embedding/index.ts +0 -20
  204. package/src/shared/embedding/typings/embedding-config.interface.ts +0 -23
  205. package/src/shared/embedding/typings/embedding-provider.interface.ts +0 -25
  206. package/src/shared/embedding/typings/near-duplicate-candidate.model.ts +0 -25
  207. package/src/shared/embedding/typings/near-duplicate-result.model.ts +0 -26
  208. package/src/shared/embedding/typings/vector-index-entry.model.ts +0 -13
  209. package/src/shared/embedding/typings/vector-index-meta.model.ts +0 -14
  210. package/src/shared/embedding/typings/vector-search-result.model.ts +0 -8
  211. package/src/shared/hash/functions/compute-sha256.ts +0 -17
  212. package/src/shared/hash/index.ts +0 -1
  213. package/src/shared/mcp/classes/mcp-server.class.ts +0 -480
  214. package/src/shared/mcp/constants/mcp-error-codes.constant.ts +0 -30
  215. package/src/shared/mcp/constants/tool-agent-create.constant.ts +0 -39
  216. package/src/shared/mcp/constants/tool-agent-delete.constant.ts +0 -26
  217. package/src/shared/mcp/constants/tool-agent-get.constant.ts +0 -24
  218. package/src/shared/mcp/constants/tool-agent-list.constant.ts +0 -18
  219. package/src/shared/mcp/constants/tool-auto-capture-review.constant.ts +0 -32
  220. package/src/shared/mcp/constants/tool-check.constant.ts +0 -21
  221. package/src/shared/mcp/constants/tool-content.constant.ts +0 -29
  222. package/src/shared/mcp/constants/tool-export.constant.ts +0 -27
  223. package/src/shared/mcp/constants/tool-gc.constant.ts +0 -21
  224. package/src/shared/mcp/constants/tool-learn.constant.ts +0 -58
  225. package/src/shared/mcp/constants/tool-rebuild.constant.ts +0 -21
  226. package/src/shared/mcp/constants/tool-recall.constant.ts +0 -36
  227. package/src/shared/mcp/constants/tool-retrieve.constant.ts +0 -31
  228. package/src/shared/mcp/constants/tool-search.constant.ts +0 -51
  229. package/src/shared/mcp/constants/tool-skill-delete.constant.ts +0 -24
  230. package/src/shared/mcp/constants/tool-skill-get.constant.ts +0 -27
  231. package/src/shared/mcp/constants/tool-skill-learn.constant.ts +0 -37
  232. package/src/shared/mcp/constants/tool-skill-list.constant.ts +0 -18
  233. package/src/shared/mcp/constants/tool-status.constant.ts +0 -20
  234. package/src/shared/mcp/constants/tool-unlearn.constant.ts +0 -25
  235. package/src/shared/mcp/functions/as-boolean-or-undefined.function.ts +0 -11
  236. package/src/shared/mcp/functions/as-string-array-or-undefined.function.ts +0 -17
  237. package/src/shared/mcp/functions/as-string-array.function.ts +0 -15
  238. package/src/shared/mcp/functions/as-string.function.ts +0 -10
  239. package/src/shared/mcp/functions/build-skills-text.function.ts +0 -43
  240. package/src/shared/mcp/functions/create-mcp-server.function.ts +0 -14
  241. package/src/shared/mcp/functions/create-prompt-definitions.function.ts +0 -102
  242. package/src/shared/mcp/functions/create-resource-templates.function.ts +0 -23
  243. package/src/shared/mcp/functions/create-tool-definitions.function.ts +0 -530
  244. package/src/shared/mcp/functions/extract-skill-arguments.function.ts +0 -27
  245. package/src/shared/mcp/functions/handle-agent-create.function.ts +0 -116
  246. package/src/shared/mcp/functions/handle-agent-delete.function.ts +0 -50
  247. package/src/shared/mcp/functions/handle-agent-get.function.ts +0 -160
  248. package/src/shared/mcp/functions/handle-agent-list.function.ts +0 -50
  249. package/src/shared/mcp/functions/handle-agent-prompt.function.ts +0 -68
  250. package/src/shared/mcp/functions/handle-completion.function.ts +0 -114
  251. package/src/shared/mcp/functions/handle-mcp-request.function.ts +0 -202
  252. package/src/shared/mcp/functions/handle-prompt-get.function.ts +0 -220
  253. package/src/shared/mcp/functions/handle-recall.function.ts +0 -66
  254. package/src/shared/mcp/functions/handle-resource-read.function.ts +0 -56
  255. package/src/shared/mcp/functions/handle-roots-list.function.ts +0 -29
  256. package/src/shared/mcp/functions/handle-skill-prompt.function.ts +0 -44
  257. package/src/shared/mcp/functions/handle-tool-auto-capture-review.function.ts +0 -24
  258. package/src/shared/mcp/functions/handle-tool-call.function.ts +0 -560
  259. package/src/shared/mcp/functions/handle-tool-check.function.ts +0 -21
  260. package/src/shared/mcp/functions/handle-tool-content.function.ts +0 -23
  261. package/src/shared/mcp/functions/handle-tool-export.function.ts +0 -25
  262. package/src/shared/mcp/functions/handle-tool-gc.function.ts +0 -21
  263. package/src/shared/mcp/functions/handle-tool-learn.function.ts +0 -69
  264. package/src/shared/mcp/functions/handle-tool-rebuild.function.ts +0 -21
  265. package/src/shared/mcp/functions/handle-tool-retrieve.function.ts +0 -40
  266. package/src/shared/mcp/functions/handle-tool-search.function.ts +0 -47
  267. package/src/shared/mcp/functions/handle-tool-skill-delete.function.ts +0 -34
  268. package/src/shared/mcp/functions/handle-tool-skill-get.function.ts +0 -59
  269. package/src/shared/mcp/functions/handle-tool-skill-learn.function.ts +0 -61
  270. package/src/shared/mcp/functions/handle-tool-skill-list.function.ts +0 -39
  271. package/src/shared/mcp/functions/handle-tool-status.function.ts +0 -21
  272. package/src/shared/mcp/functions/handle-tool-unlearn.function.ts +0 -24
  273. package/src/shared/mcp/functions/parse-agent-meta.function.ts +0 -27
  274. package/src/shared/mcp/functions/parse-skill-arguments.function.ts +0 -36
  275. package/src/shared/mcp/functions/parse-skill-content.function.ts +0 -38
  276. package/src/shared/mcp/functions/read-agent-meta.function.ts +0 -41
  277. package/src/shared/mcp/functions/resolve-skill-refs.function.ts +0 -50
  278. package/src/shared/mcp/functions/run-startup-health-check.function.ts +0 -34
  279. package/src/shared/mcp/functions/serialize-skill-content.function.ts +0 -12
  280. package/src/shared/mcp/functions/should-emit-log.function.ts +0 -38
  281. package/src/shared/mcp/index.ts +0 -28
  282. package/src/shared/mcp/typings/agent-types.interface.ts +0 -39
  283. package/src/shared/mcp/typings/log-types.interface.ts +0 -26
  284. package/src/shared/mcp/typings/mcp-capabilities.interface.ts +0 -16
  285. package/src/shared/mcp/typings/mcp-client.interface.ts +0 -317
  286. package/src/shared/mcp/typings/mcp-completion.interface.ts +0 -45
  287. package/src/shared/mcp/typings/mcp-content-result.model.ts +0 -9
  288. package/src/shared/mcp/typings/mcp-export-result.model.ts +0 -11
  289. package/src/shared/mcp/typings/mcp-gc-result.model.ts +0 -15
  290. package/src/shared/mcp/typings/mcp-integrity-check-result.model.ts +0 -17
  291. package/src/shared/mcp/typings/mcp-integrity-error.model.ts +0 -15
  292. package/src/shared/mcp/typings/mcp-notification.interface.ts +0 -9
  293. package/src/shared/mcp/typings/mcp-rebuild-result.model.ts +0 -9
  294. package/src/shared/mcp/typings/mcp-request.interface.ts +0 -11
  295. package/src/shared/mcp/typings/mcp-resource-result.interface.ts +0 -12
  296. package/src/shared/mcp/typings/mcp-resource-template.interface.ts +0 -11
  297. package/src/shared/mcp/typings/mcp-response.interface.ts +0 -18
  298. package/src/shared/mcp/typings/mcp-server-info.interface.ts +0 -7
  299. package/src/shared/mcp/typings/mcp-server-state.interface.ts +0 -17
  300. package/src/shared/mcp/typings/mcp-tool-annotations.interface.ts +0 -32
  301. package/src/shared/mcp/typings/mcp-tool-definition.interface.ts +0 -16
  302. package/src/shared/mcp/typings/mcp-tool-result.interface.ts +0 -19
  303. package/src/shared/mcp/typings/mcp-types.interface.ts +0 -158
  304. package/src/shared/mcp/typings/mcp-worker-client.interface.ts +0 -243
  305. package/src/shared/mcp/typings/prompt-types.interface.ts +0 -39
  306. package/src/shared/mcp/typings/remove-section-result.model.ts +0 -10
  307. package/src/shared/mcp/typings/sampling-types.interface.ts +0 -48
  308. package/src/shared/mcp/typings/skill-types.interface.ts +0 -29
  309. package/src/shared/mcp/typings/tool-call-result.model.ts +0 -18
  310. package/src/shared/mod.ts +0 -1
  311. package/src/shared/platform/functions/get-ipc-path.function.ts +0 -19
  312. package/src/shared/platform/functions/get-tmpdir.function.ts +0 -8
  313. package/src/shared/platform/functions/is-process-alive.function.ts +0 -17
  314. package/src/shared/platform/index.ts +0 -3
  315. package/src/shared/runtime/functions/detect-runtime.ts +0 -14
  316. package/src/shared/runtime/functions/get-args.ts +0 -16
  317. package/src/shared/runtime/index.ts +0 -3
  318. package/src/shared/runtime/typings/runtime.ts +0 -2
  319. package/src/shared/sync/functions/build-import-report.function.ts +0 -40
  320. package/src/shared/sync/functions/parse-export-entry.function.ts +0 -45
  321. package/src/shared/sync/functions/resolve-conflict.function.ts +0 -31
  322. package/src/shared/sync/functions/serialize-export-entry.function.ts +0 -18
  323. package/src/shared/sync/index.ts +0 -9
  324. package/src/shared/sync/typings/conflict-resolution.type.ts +0 -8
  325. package/src/shared/sync/typings/export-entry.interface.ts +0 -13
  326. package/src/shared/sync/typings/export-options.interface.ts +0 -9
  327. package/src/shared/sync/typings/import-options.interface.ts +0 -7
  328. package/src/shared/sync/typings/import-report.interface.ts +0 -15
  329. package/src/shared/version/constants/version.constant.ts +0 -2
  330. package/src/shared/version/index.ts +0 -1
  331. package/src/shared/wasm-codec/functions/decode-add-section-result.function.ts +0 -112
  332. package/src/shared/wasm-codec/functions/decode-compose-output.function.ts +0 -16
  333. package/src/shared/wasm-codec/functions/decode-document-manifest-list.function.ts +0 -70
  334. package/src/shared/wasm-codec/functions/decode-document-manifest.function.ts +0 -87
  335. package/src/shared/wasm-codec/functions/decode-f32.function.ts +0 -16
  336. package/src/shared/wasm-codec/functions/decode-key-value-text.function.ts +0 -15
  337. package/src/shared/wasm-codec/functions/decode-one-recall-result.function.ts +0 -86
  338. package/src/shared/wasm-codec/functions/decode-option-string.function.ts +0 -24
  339. package/src/shared/wasm-codec/functions/decode-recall-document.function.ts +0 -59
  340. package/src/shared/wasm-codec/functions/decode-recall-reference.function.ts +0 -52
  341. package/src/shared/wasm-codec/functions/decode-recall-result.function.ts +0 -267
  342. package/src/shared/wasm-codec/functions/decode-recall-sibling.function.ts +0 -43
  343. package/src/shared/wasm-codec/functions/decode-remove-flag.function.ts +0 -3
  344. package/src/shared/wasm-codec/functions/decode-scored-results.function.ts +0 -194
  345. package/src/shared/wasm-codec/functions/decode-section-match.function.ts +0 -80
  346. package/src/shared/wasm-codec/functions/decode-section-record-list.function.ts +0 -20
  347. package/src/shared/wasm-codec/functions/decode-section-record-trailing.function.ts +0 -75
  348. package/src/shared/wasm-codec/functions/decode-section-record.function.ts +0 -85
  349. package/src/shared/wasm-codec/functions/decode-section-records.function.ts +0 -249
  350. package/src/shared/wasm-codec/functions/decode-section-type.function.ts +0 -30
  351. package/src/shared/wasm-codec/functions/decode-string.function.ts +0 -22
  352. package/src/shared/wasm-codec/functions/decode-u32.function.ts +0 -16
  353. package/src/shared/wasm-codec/functions/decode-u64.function.ts +0 -16
  354. package/src/shared/wasm-codec/functions/decode-wasm-list.function.ts +0 -31
  355. package/src/shared/wasm-codec/functions/encode-add-section-params.function.ts +0 -102
  356. package/src/shared/wasm-codec/functions/encode-group-params.function.ts +0 -28
  357. package/src/shared/wasm-codec/functions/encode-identifier-list.function.ts +0 -17
  358. package/src/shared/wasm-codec/functions/encode-kbid-list.function.ts +0 -17
  359. package/src/shared/wasm-codec/functions/encode-option-string.function.ts +0 -14
  360. package/src/shared/wasm-codec/functions/encode-recall-params.function.ts +0 -68
  361. package/src/shared/wasm-codec/functions/encode-search-params.function.ts +0 -12
  362. package/src/shared/wasm-codec/functions/encode-section-type.function.ts +0 -18
  363. package/src/shared/wasm-codec/functions/encode-string.function.ts +0 -9
  364. package/src/shared/wasm-codec/functions/encode-type-filter-param.function.ts +0 -13
  365. package/src/shared/wasm-codec/functions/encode-u32.function.ts +0 -5
  366. package/src/shared/wasm-codec/functions/encode-update-section-params.function.ts +0 -16
  367. package/src/shared/wasm-codec/index.ts +0 -49
  368. package/src/shared/wasm-codec/typings/add-section-input.model.ts +0 -45
  369. package/src/shared/wasm-codec/typings/add-section-result.model.ts +0 -28
  370. package/src/shared/wasm-codec/typings/document-manifest.model.ts +0 -20
  371. package/src/shared/wasm-codec/typings/document-section.model.ts +0 -12
  372. package/src/shared/wasm-codec/typings/item-decoder.type.ts +0 -10
  373. package/src/shared/wasm-codec/typings/near-duplicate.model.ts +0 -16
  374. package/src/shared/wasm-codec/typings/paged-search-result.model.ts +0 -22
  375. package/src/shared/wasm-codec/typings/section-match.model.ts +0 -31
  376. package/src/shared/wasm-codec/typings/section-record-trailing.model.ts +0 -38
  377. package/src/shared/wasm-codec/typings/section-record.model.ts +0 -66
  378. package/src/shared/wasm-codec/typings/section-type-result.model.ts +0 -12
  379. package/src/shared/worker-client/classes/worker-client.class.ts +0 -466
  380. package/src/shared/worker-client/functions/compute-context-id.function.ts +0 -18
  381. package/src/shared/worker-client/functions/create-worker-client.function.ts +0 -70
  382. package/src/shared/worker-client/functions/discover-daemon.function.ts +0 -47
  383. package/src/shared/worker-client/functions/handle-ipc-data.function.ts +0 -49
  384. package/src/shared/worker-client/functions/resolve-db-path.function.ts +0 -21
  385. package/src/shared/worker-client/functions/send-ipc-request.function.ts +0 -39
  386. package/src/shared/worker-client/functions/spawn-daemon.function.ts +0 -35
  387. package/src/shared/worker-client/functions/wait-for-daemon.function.ts +0 -34
  388. package/src/shared/worker-client/index.ts +0 -44
  389. package/src/shared/worker-client/typings/add-section-result.model.ts +0 -39
  390. package/src/shared/worker-client/typings/content-result.model.ts +0 -12
  391. package/src/shared/worker-client/typings/daemon-info.model.ts +0 -7
  392. package/src/shared/worker-client/typings/export-result.model.ts +0 -14
  393. package/src/shared/worker-client/typings/gc-result.model.ts +0 -18
  394. package/src/shared/worker-client/typings/integrity-check-result.model.ts +0 -43
  395. package/src/shared/worker-client/typings/json-rpc-response.interface.ts +0 -17
  396. package/src/shared/worker-client/typings/migrate-result.model.ts +0 -11
  397. package/src/shared/worker-client/typings/pending-call.interface.ts +0 -7
  398. package/src/shared/worker-client/typings/rebuild-result.model.ts +0 -12
  399. package/src/shared/worker-client/typings/recall-document.model.ts +0 -16
  400. package/src/shared/worker-client/typings/recall-params.model.ts +0 -15
  401. package/src/shared/worker-client/typings/recall-reference.model.ts +0 -32
  402. package/src/shared/worker-client/typings/recall-result.model.ts +0 -98
  403. package/src/shared/worker-client/typings/recall-sibling.model.ts +0 -11
  404. package/src/shared/worker-client/typings/recall-single-result.model.ts +0 -41
  405. package/src/shared/worker-client/typings/remove-section-result.model.ts +0 -7
  406. package/src/shared/worker-client/typings/search-params.model.ts +0 -14
  407. package/src/shared/worker-client/typings/search-result.model.ts +0 -43
  408. package/src/shared/worker-client/typings/section.model.ts +0 -43
  409. package/src/shared/worker-client/typings/status-result.model.ts +0 -14
  410. package/src/shared/worker-client/typings/version-status.model.ts +0 -28
  411. package/src/shared/worker-client/typings/worker-client-error.interface.ts +0 -8
  412. package/src/shared/worker-client/typings/worker-client-options.interface.ts +0 -30
  413. package/src/shared/worker-daemon/classes/ipc-error.class.ts +0 -22
  414. package/src/shared/worker-daemon/classes/worker-daemon.class.ts +0 -1291
  415. package/src/shared/worker-daemon/constants/daemon-defaults.constant.ts +0 -29
  416. package/src/shared/worker-daemon/constants/wasm-method-map.constant.ts +0 -69
  417. package/src/shared/worker-daemon/functions/build-ipc-error-response.function.ts +0 -16
  418. package/src/shared/worker-daemon/functions/check-catalog-version.function.ts +0 -54
  419. package/src/shared/worker-daemon/functions/check-preconditions.function.ts +0 -28
  420. package/src/shared/worker-daemon/functions/create-host-imports.function.ts +0 -328
  421. package/src/shared/worker-daemon/functions/create-ipc-server.function.ts +0 -87
  422. package/src/shared/worker-daemon/functions/detect-stale-pid.function.ts +0 -33
  423. package/src/shared/worker-daemon/functions/dispatch-request.function.ts +0 -190
  424. package/src/shared/worker-daemon/functions/handle-check-version.function.ts +0 -74
  425. package/src/shared/worker-daemon/functions/handle-config-method.function.ts +0 -27
  426. package/src/shared/worker-daemon/functions/handle-read-ops.function.ts +0 -236
  427. package/src/shared/worker-daemon/functions/handle-write-ops.function.ts +0 -257
  428. package/src/shared/worker-daemon/functions/load-wasm-modules.function.ts +0 -95
  429. package/src/shared/worker-daemon/functions/parse-auto-capture-section.function.ts +0 -51
  430. package/src/shared/worker-daemon/functions/parse-catalog-version.function.ts +0 -20
  431. package/src/shared/worker-daemon/functions/parse-embedding-section.function.ts +0 -38
  432. package/src/shared/worker-daemon/functions/parse-worker-toml.function.ts +0 -104
  433. package/src/shared/worker-daemon/functions/read-config.function.ts +0 -83
  434. package/src/shared/worker-daemon/functions/run-startup-integrity-check.function.ts +0 -55
  435. package/src/shared/worker-daemon/functions/run-worker.function.ts +0 -57
  436. package/src/shared/worker-daemon/functions/scan-near-duplicates.function.ts +0 -92
  437. package/src/shared/worker-daemon/functions/start-daemon.function.ts +0 -74
  438. package/src/shared/worker-daemon/functions/wasm-bridge.function.ts +0 -144
  439. package/src/shared/worker-daemon/functions/wasm-memory-helpers.function.ts +0 -41
  440. package/src/shared/worker-daemon/functions/write-lock.function.ts +0 -49
  441. package/src/shared/worker-daemon/index.ts +0 -16
  442. package/src/shared/worker-daemon/typings/allocator-ref.interface.ts +0 -16
  443. package/src/shared/worker-daemon/typings/daemon-config.interface.ts +0 -20
  444. package/src/shared/worker-daemon/typings/fs-adapter.interface.ts +0 -22
  445. package/src/shared/worker-daemon/typings/handler-context.interface.ts +0 -19
  446. package/src/shared/worker-daemon/typings/ipc-handler.interface.ts +0 -39
  447. package/src/shared/worker-daemon/typings/memory-ref.interface.ts +0 -13
  448. package/src/shared/worker-daemon/typings/wasm-fn.type.ts +0 -2
  449. package/src/shared/worker-daemon/typings/wasm-modules.interface.ts +0 -7
  450. package/src/shared/worker-daemon/typings/write-lock.interface.ts +0 -13
  451. package/src/wasm/fs-database/kbdb_fs_database.d.ts +0 -259
  452. package/src/wasm/fs-database/kbdb_fs_database.js +0 -515
  453. package/src/wasm/fs-database/kbdb_fs_database_bg.wasm +0 -0
  454. package/src/wasm/fs-database/kbdb_fs_database_bg.wasm.d.ts +0 -35
  455. package/src/wasm/fs-database/package.json +0 -13
  456. package/src/wasm/kb-worker/kbdb_worker.d.ts +0 -650
  457. package/src/wasm/kb-worker/kbdb_worker.js +0 -1181
  458. package/src/wasm/kb-worker/kbdb_worker_bg.wasm +0 -0
  459. package/src/wasm/kb-worker/kbdb_worker_bg.wasm.d.ts +0 -77
  460. package/src/wasm/kb-worker/package.json +0 -13
  461. package/src/wasm/query-parser/kbdb_query_parser.d.ts +0 -195
  462. package/src/wasm/query-parser/kbdb_query_parser.js +0 -403
  463. package/src/wasm/query-parser/kbdb_query_parser_bg.wasm +0 -0
  464. package/src/wasm/query-parser/kbdb_query_parser_bg.wasm.d.ts +0 -25
  465. package/src/wasm/query-parser/package.json +0 -13
  466. package/src/worker.ts +0 -42
package/dist/worker.mjs CHANGED
@@ -1,29 +1,26 @@
1
1
  import {
2
+ DB_FORMAT_VERSION,
3
+ DEFAULT_INDEX_LIMIT,
4
+ DEFAULT_ITEM_LIMIT,
5
+ DEFAULT_ITEM_TTL_MS,
6
+ DEFAULT_TIMEOUT_MS,
7
+ WORKER_TOML_FILENAME,
2
8
  computeSha256,
3
9
  getArgs,
4
10
  getIpcPath,
5
11
  isRemoteUrl,
6
12
  joinPath,
13
+ parseWorkerToml,
7
14
  resolveBaseDir,
8
15
  resolveWasmDir
9
- } from "./chunk-JG2UCKLI.mjs";
16
+ } from "./chunk-BJPSPNGX.mjs";
10
17
 
11
18
  // src/worker.ts
12
- import { existsSync as existsSync3 } from "node:fs";
19
+ import { existsSync as existsSync5 } from "node:fs";
13
20
 
14
21
  // src/shared/worker-daemon/functions/read-config.function.ts
15
22
  import { readFileSync } from "node:fs";
16
23
  import { join } from "node:path";
17
-
18
- // src/shared/worker-daemon/constants/daemon-defaults.constant.ts
19
- var DEFAULT_ITEM_LIMIT = 1e3;
20
- var DEFAULT_INDEX_LIMIT = 100;
21
- var DEFAULT_TIMEOUT_MS = 3e5;
22
- var DEFAULT_ITEM_TTL_MS = 6e4;
23
- var WORKER_TOML_FILENAME = "worker.toml";
24
- var DB_FORMAT_VERSION = 1;
25
-
26
- // src/shared/worker-daemon/functions/read-config.function.ts
27
24
  function readConfig(contextPath) {
28
25
  const configPath = join(contextPath, WORKER_TOML_FILENAME);
29
26
  try {
@@ -39,59 +36,23 @@ function readConfig(contextPath) {
39
36
  };
40
37
  }
41
38
  }
42
- function parseWorkerToml(text, contextPath) {
43
- const config = {
44
- contextPath,
45
- itemLimit: DEFAULT_ITEM_LIMIT,
46
- indexLimit: DEFAULT_INDEX_LIMIT,
47
- timeoutMs: DEFAULT_TIMEOUT_MS,
48
- itemTtlMs: DEFAULT_ITEM_TTL_MS
49
- };
50
- const result = { ...config };
51
- for (const line of text.split("\n")) {
52
- const trimmed = line.trim();
53
- if (trimmed.startsWith("#") || !trimmed.includes("=")) {
54
- continue;
55
- }
56
- const eqIdx = trimmed.indexOf("=");
57
- const key = trimmed.slice(0, eqIdx).trim();
58
- const value = trimmed.slice(eqIdx + 1).trim();
59
- switch (key) {
60
- case "item_limit":
61
- result.itemLimit = parseInt(value, 10) || DEFAULT_ITEM_LIMIT;
62
- break;
63
- case "index_limit":
64
- result.indexLimit = parseInt(value, 10) || DEFAULT_INDEX_LIMIT;
65
- break;
66
- case "timeout_ms":
67
- result.timeoutMs = parseInt(value, 10) || DEFAULT_TIMEOUT_MS;
68
- break;
69
- case "item_ttl_ms":
70
- result.itemTtlMs = parseInt(value, 10) || DEFAULT_ITEM_TTL_MS;
71
- break;
72
- default:
73
- break;
74
- }
75
- }
76
- return result;
77
- }
78
39
 
79
40
  // src/shared/worker-daemon/functions/start-daemon.function.ts
80
- import { writeFileSync as writeFileSync3 } from "node:fs";
81
- import { join as join4 } from "node:path";
41
+ import { writeFileSync as writeFileSync4 } from "node:fs";
42
+ import { join as join7 } from "node:path";
82
43
  import { tmpdir as tmpdir2 } from "node:os";
83
44
 
84
45
  // src/shared/worker-daemon/classes/worker-daemon.class.ts
85
46
  import {
86
- existsSync as existsSync2,
87
- readFileSync as readFileSync4,
88
- readdirSync as readdirSync2,
47
+ existsSync as existsSync4,
48
+ readFileSync as readFileSync6,
49
+ readdirSync as readdirSync3,
89
50
  accessSync,
90
- writeFileSync as writeFileSync2,
51
+ writeFileSync as writeFileSync3,
91
52
  unlinkSync as unlinkSync2,
92
53
  constants
93
54
  } from "node:fs";
94
- import { join as join3 } from "node:path";
55
+ import { join as join6 } from "node:path";
95
56
  import { tmpdir } from "node:os";
96
57
 
97
58
  // src/shared/worker-daemon/functions/load-wasm-modules.function.ts
@@ -353,8 +314,11 @@ function rethrow(stage, label, err, path) {
353
314
 
354
315
  // src/shared/worker-daemon/functions/create-ipc-server.function.ts
355
316
  import { createServer } from "node:net";
317
+ var LISTEN_BACKLOG = 256;
318
+ var KEEPALIVE_MS = 3e4;
356
319
  function createIpcServer(socketPath, handler) {
357
320
  const server = createServer((socket) => {
321
+ socket.setKeepAlive(true, KEEPALIVE_MS);
358
322
  let buffer = "";
359
323
  let processingQueue = Promise.resolve();
360
324
  socket.on("data", (chunk) => {
@@ -374,11 +338,21 @@ function createIpcServer(socketPath, handler) {
374
338
  );
375
339
  });
376
340
  });
377
- server.on("error", (err) => {
378
- console.error(`kbdb-worker: ipc server error: ${err.message}`);
341
+ return new Promise((resolve2, reject) => {
342
+ server.once("error", reject);
343
+ server.listen(
344
+ { path: socketPath, backlog: LISTEN_BACKLOG },
345
+ () => {
346
+ server.removeListener("error", reject);
347
+ server.on("error", (err) => {
348
+ console.error(
349
+ `kbdb-worker: ipc server error: ${err.message}`
350
+ );
351
+ });
352
+ resolve2(server);
353
+ }
354
+ );
379
355
  });
380
- server.listen(socketPath);
381
- return server;
382
356
  }
383
357
  function bigintReplacer(_key, value) {
384
358
  return typeof value === "bigint" ? Number(value) : value;
@@ -401,6 +375,454 @@ async function handleLine(line, handler, socket) {
401
375
  socket.write(JSON.stringify(response, bigintReplacer) + "\n");
402
376
  }
403
377
 
378
+ // src/shared/embedding/classes/null-embedding-provider.class.ts
379
+ var NullEmbeddingProvider = class {
380
+ /**
381
+ * Returns an empty `Float32Array` for each input text.
382
+ *
383
+ * @param texts - input strings (contents are ignored)
384
+ */
385
+ embed(texts) {
386
+ return Promise.resolve(texts.map(() => new Float32Array(0)));
387
+ }
388
+ /** Always returns 0 -- no dimensions when disabled. */
389
+ dimensions() {
390
+ return 0;
391
+ }
392
+ /** Always returns `'none'`. */
393
+ modelName() {
394
+ return "none";
395
+ }
396
+ };
397
+
398
+ // src/shared/embedding/classes/onnx-embedding-provider.class.ts
399
+ var OnnxEmbeddingProvider = class {
400
+ /** Path to the ONNX model file. */
401
+ model;
402
+ /** Number of embedding dimensions the model produces. */
403
+ dims;
404
+ /**
405
+ * @param model - filesystem path to the ONNX model file
406
+ * @param dimensions - number of dimensions the model produces
407
+ */
408
+ constructor(model, dimensions) {
409
+ this.model = model;
410
+ this.dims = dimensions;
411
+ }
412
+ /**
413
+ * Not yet implemented.
414
+ *
415
+ * @throws {Error} always -- ONNX Runtime is an optional peer
416
+ * dependency not yet wired
417
+ */
418
+ embed(_texts) {
419
+ return Promise.reject(
420
+ new Error(
421
+ "ONNX Runtime not available; install onnxruntime-node"
422
+ )
423
+ );
424
+ }
425
+ /** Returns the configured number of embedding dimensions. */
426
+ dimensions() {
427
+ return this.dims;
428
+ }
429
+ /** Returns the configured model file path. */
430
+ modelName() {
431
+ return this.model;
432
+ }
433
+ };
434
+
435
+ // src/shared/embedding/functions/parse-api-embedding-response.function.ts
436
+ function parseApiEmbeddingResponse(raw) {
437
+ if (!isEmbeddingApiResponse(raw)) {
438
+ throw new Error("Unexpected embedding API response shape");
439
+ }
440
+ return raw.data.map((entry) => new Float32Array(entry.embedding));
441
+ }
442
+ function isEmbeddingApiResponse(value) {
443
+ if (typeof value !== "object" || value === null) {
444
+ return false;
445
+ }
446
+ const candidate = value;
447
+ if (!Array.isArray(candidate["data"])) {
448
+ return false;
449
+ }
450
+ return candidate["data"].every(isEmbeddingEntry);
451
+ }
452
+ function isEmbeddingEntry(value) {
453
+ if (typeof value !== "object" || value === null) {
454
+ return false;
455
+ }
456
+ const candidate = value;
457
+ return Array.isArray(candidate["embedding"]);
458
+ }
459
+
460
+ // src/shared/embedding/classes/api-embedding-provider.class.ts
461
+ var ApiEmbeddingProvider = class {
462
+ /** Remote endpoint URL for embedding requests. */
463
+ endpoint;
464
+ /** Number of dimensions in the returned vectors. */
465
+ dims;
466
+ /** Model name sent in the request body. */
467
+ model;
468
+ /**
469
+ * @param endpoint - URL to POST embedding requests to
470
+ * @param dimensions - number of vector dimensions expected
471
+ * @param model - optional model name; defaults to `'api'`
472
+ */
473
+ constructor(endpoint, dimensions, model) {
474
+ this.endpoint = endpoint;
475
+ this.dims = dimensions;
476
+ this.model = model ?? "api";
477
+ }
478
+ /**
479
+ * Posts texts to the endpoint and returns one `Float32Array`
480
+ * per input.
481
+ *
482
+ * @throws {Error} when the HTTP response status is not 2xx
483
+ */
484
+ async embed(texts) {
485
+ const response = await fetch(this.endpoint, {
486
+ method: "POST",
487
+ headers: { "Content-Type": "application/json" },
488
+ body: JSON.stringify({ input: texts, model: this.model })
489
+ });
490
+ if (!response.ok) {
491
+ throw new Error(
492
+ `Embedding API error: ${String(response.status)}`
493
+ );
494
+ }
495
+ const json = await response.json();
496
+ return parseApiEmbeddingResponse(json);
497
+ }
498
+ /** Returns the configured number of embedding dimensions. */
499
+ dimensions() {
500
+ return this.dims;
501
+ }
502
+ /** Returns the configured model name, defaulting to `'api'`. */
503
+ modelName() {
504
+ return this.model;
505
+ }
506
+ };
507
+
508
+ // src/shared/embedding/functions/create-embedding-provider.function.ts
509
+ function createEmbeddingProvider(config) {
510
+ if (!config || config.provider === "none") {
511
+ return new NullEmbeddingProvider();
512
+ }
513
+ if (config.provider === "onnx") {
514
+ return new OnnxEmbeddingProvider(
515
+ config.model ?? "",
516
+ config.dimensions ?? 0
517
+ );
518
+ }
519
+ return new ApiEmbeddingProvider(
520
+ config.endpoint ?? "",
521
+ config.dimensions ?? 0,
522
+ config.model
523
+ );
524
+ }
525
+
526
+ // src/shared/worker-daemon/functions/handle-hybrid-search.function.ts
527
+ import { existsSync as existsSync2 } from "node:fs";
528
+ import { join as join3 } from "node:path";
529
+
530
+ // src/shared/embedding/functions/search-vectors.function.ts
531
+ import { readFileSync as readFileSync4 } from "node:fs";
532
+
533
+ // src/shared/embedding/functions/cosine-similarity.function.ts
534
+ function cosineSimilarity(a, b) {
535
+ let dot = 0;
536
+ let magA = 0;
537
+ let magB = 0;
538
+ for (let i = 0; i < a.length; i++) {
539
+ const ai = a[i] ?? 0;
540
+ const bi = b[i] ?? 0;
541
+ dot += ai * bi;
542
+ magA += ai * ai;
543
+ magB += bi * bi;
544
+ }
545
+ if (magA === 0 || magB === 0) {
546
+ return 0;
547
+ }
548
+ return dot / (Math.sqrt(magA) * Math.sqrt(magB));
549
+ }
550
+
551
+ // src/shared/embedding/functions/search-vectors.function.ts
552
+ var HEADER_SIZE = 32;
553
+ var KBID_WIDTH = 64;
554
+ function searchVectors(filePath, queryVector, topN) {
555
+ const buf = readFileSync4(filePath);
556
+ if (buf.length < HEADER_SIZE) {
557
+ return [];
558
+ }
559
+ const dimensions = buf.readUInt32LE(8);
560
+ const count = buf.readUInt32LE(12);
561
+ const modelLen = buf.readUInt32LE(16);
562
+ const dataStart = HEADER_SIZE + modelLen;
563
+ const recordSize = KBID_WIDTH + dimensions * 4;
564
+ const results = [];
565
+ for (let i = 0; i < count; i++) {
566
+ const recOffset = dataStart + i * recordSize;
567
+ const kbid = buf.toString("utf-8", recOffset, recOffset + KBID_WIDTH).replace(/\0/g, "");
568
+ const vector = new Float32Array(dimensions);
569
+ for (let d = 0; d < dimensions; d++) {
570
+ vector[d] = buf.readFloatLE(recOffset + KBID_WIDTH + d * 4);
571
+ }
572
+ const score = cosineSimilarity(queryVector, vector);
573
+ results.push({ kbid, score });
574
+ }
575
+ results.sort((a, b) => b.score - a.score);
576
+ return results.slice(0, topN);
577
+ }
578
+
579
+ // src/shared/embedding/functions/rrf-fuse.function.ts
580
+ var DEFAULT_K = 60;
581
+ function rrfFuse(lexicalRanks, vectorRanks, k = DEFAULT_K) {
582
+ const scores = /* @__PURE__ */ new Map();
583
+ for (const [kbid, rank] of lexicalRanks) {
584
+ scores.set(kbid, (scores.get(kbid) ?? 0) + 1 / (k + rank));
585
+ }
586
+ for (const [kbid, rank] of vectorRanks) {
587
+ scores.set(kbid, (scores.get(kbid) ?? 0) + 1 / (k + rank));
588
+ }
589
+ return scores;
590
+ }
591
+
592
+ // src/shared/worker-daemon/classes/ipc-error.class.ts
593
+ var IpcError = class extends Error {
594
+ /** JSON-RPC error code. */
595
+ code;
596
+ /**
597
+ * @param code - JSON-RPC error code (e.g. `-32601` for
598
+ * method-not-found, `-32000` for application errors)
599
+ * @param message - human-readable error description
600
+ */
601
+ constructor(code, message) {
602
+ super(message);
603
+ this.code = code;
604
+ this.name = "IpcError";
605
+ }
606
+ };
607
+
608
+ // src/shared/worker-daemon/functions/handle-hybrid-search.function.ts
609
+ async function fuseSearchResults(lexical, algo, query, provider, targetDir) {
610
+ if (algo === "lexical") {
611
+ return {
612
+ ...lexical,
613
+ search_mode: "lexical",
614
+ retrieval_method: "lexical"
615
+ };
616
+ }
617
+ assertProvider(provider);
618
+ const embeddings = await provider.embed([query]);
619
+ if (embeddings.length === 0 || embeddings[0].length === 0) {
620
+ return {
621
+ ...lexical,
622
+ search_mode: algo,
623
+ retrieval_method: "lexical"
624
+ };
625
+ }
626
+ const queryVec = embeddings[0];
627
+ const vectorPath = join3(targetDir, "vectors.idx");
628
+ const vectorResults = existsSync2(vectorPath) ? searchVectors(vectorPath, queryVec, lexical.limit) : [];
629
+ if (algo === "vector") {
630
+ return buildVectorOnly(vectorResults, lexical);
631
+ }
632
+ return buildHybrid(lexical, vectorResults);
633
+ }
634
+ function assertProvider(provider) {
635
+ if (!provider || provider.dimensions() === 0) {
636
+ throw new IpcError(
637
+ -32e3,
638
+ "embedding provider not configured; set [embedding] in worker.toml"
639
+ );
640
+ }
641
+ }
642
+ function buildVectorOnly(vectorResults, lexical) {
643
+ const lookup = new Map(
644
+ lexical.items.map((item) => [item.kbid, item])
645
+ );
646
+ const items = vectorResults.map((vr) => {
647
+ const existing = lookup.get(vr.kbid);
648
+ if (existing) {
649
+ return { ...existing, score: vr.score };
650
+ }
651
+ return emptyItem(vr.kbid, vr.score);
652
+ });
653
+ return {
654
+ items,
655
+ total: items.length,
656
+ offset: lexical.offset,
657
+ limit: lexical.limit,
658
+ has_more: false,
659
+ relaxed: lexical.relaxed,
660
+ search_mode: "vector",
661
+ retrieval_method: "vector"
662
+ };
663
+ }
664
+ function buildHybrid(lexical, vectorResults) {
665
+ const lexRanks = /* @__PURE__ */ new Map();
666
+ lexical.items.forEach((item, i) => {
667
+ lexRanks.set(item.kbid, i + 1);
668
+ });
669
+ const vecRanks = /* @__PURE__ */ new Map();
670
+ vectorResults.forEach((vr, i) => {
671
+ vecRanks.set(vr.kbid, i + 1);
672
+ });
673
+ const fused = rrfFuse(lexRanks, vecRanks);
674
+ const sorted = [...fused.entries()].sort((a, b) => b[1] - a[1]);
675
+ const lookup = new Map(
676
+ lexical.items.map((item) => [item.kbid, item])
677
+ );
678
+ const items = sorted.slice(0, lexical.limit).map(([kbid, score]) => {
679
+ const existing = lookup.get(kbid);
680
+ if (existing) {
681
+ return { ...existing, score };
682
+ }
683
+ return emptyItem(kbid, score);
684
+ });
685
+ return {
686
+ items,
687
+ total: sorted.length,
688
+ offset: lexical.offset,
689
+ limit: lexical.limit,
690
+ has_more: sorted.length > lexical.limit,
691
+ relaxed: lexical.relaxed,
692
+ search_mode: "hybrid",
693
+ retrieval_method: "rrf"
694
+ };
695
+ }
696
+ function emptyItem(kbid, score) {
697
+ return {
698
+ kbid,
699
+ heading: null,
700
+ type: "",
701
+ docids: [],
702
+ score,
703
+ confidence: 0,
704
+ snippet: "",
705
+ matched_terms: [],
706
+ matched_fields: [],
707
+ created_at: ""
708
+ };
709
+ }
710
+
711
+ // src/shared/embedding/functions/rebuild-vectors.function.ts
712
+ import { readdirSync as readdirSync2, readFileSync as readFileSync5, existsSync as existsSync3 } from "node:fs";
713
+ import { join as join5 } from "node:path";
714
+
715
+ // src/shared/embedding/functions/build-vector-index.function.ts
716
+ import { writeFileSync as writeFileSync2 } from "node:fs";
717
+ import { join as join4 } from "node:path";
718
+ var MAGIC = "KBVX";
719
+ var VERSION = 1;
720
+ var KBID_WIDTH2 = 64;
721
+ var HEADER_SIZE2 = 32;
722
+ function writeHeader(buf, dimensions, count, modelLen) {
723
+ buf.write(MAGIC, 0, "ascii");
724
+ buf.writeUInt32LE(VERSION, 4);
725
+ buf.writeUInt32LE(dimensions, 8);
726
+ buf.writeUInt32LE(count, 12);
727
+ buf.writeUInt32LE(modelLen, 16);
728
+ }
729
+ function writeRecord(buf, offset, entry, dimensions, encoder3) {
730
+ const kbidBytes = encoder3.encode(entry.kbid);
731
+ kbidBytes.forEach((b, i) => {
732
+ if (i < KBID_WIDTH2) buf.writeUInt8(b, offset + i);
733
+ });
734
+ for (let d = 0; d < dimensions; d++) {
735
+ buf.writeFloatLE(
736
+ entry.vector[d] ?? 0,
737
+ offset + KBID_WIDTH2 + d * 4
738
+ );
739
+ }
740
+ }
741
+ function buildVectorIndex(dirPath, modelName, dimensions, entries) {
742
+ const encoder3 = new TextEncoder();
743
+ const modelBytes = encoder3.encode(modelName);
744
+ const modelLen = modelBytes.length;
745
+ const recordSize = KBID_WIDTH2 + dimensions * 4;
746
+ const totalSize = HEADER_SIZE2 + modelLen + entries.length * recordSize;
747
+ const buf = Buffer.alloc(totalSize, 0);
748
+ writeHeader(buf, dimensions, entries.length, modelLen);
749
+ modelBytes.forEach((b, i) => buf.writeUInt8(b, HEADER_SIZE2 + i));
750
+ let recOffset = HEADER_SIZE2 + modelLen;
751
+ for (const entry of entries) {
752
+ writeRecord(buf, recOffset, entry, dimensions, encoder3);
753
+ recOffset += recordSize;
754
+ }
755
+ writeFileSync2(join4(dirPath, "vectors.idx"), buf);
756
+ return Promise.resolve();
757
+ }
758
+
759
+ // src/shared/embedding/functions/rebuild-vectors.function.ts
760
+ var SECTION_SEPARATOR = "\n---\n";
761
+ function extractBody(raw) {
762
+ const sep = raw.indexOf(SECTION_SEPARATOR);
763
+ return sep >= 0 ? raw.slice(sep + SECTION_SEPARATOR.length) : raw;
764
+ }
765
+ function collectSections(sectionsDir) {
766
+ let shards;
767
+ try {
768
+ shards = readdirSync2(sectionsDir);
769
+ } catch {
770
+ return [];
771
+ }
772
+ const result = [];
773
+ for (const shard of shards) {
774
+ let files;
775
+ try {
776
+ files = readdirSync2(join5(sectionsDir, shard));
777
+ } catch {
778
+ continue;
779
+ }
780
+ for (const file of files) {
781
+ if (!file.endsWith(".section")) continue;
782
+ const kbid = file.slice(0, -8);
783
+ try {
784
+ const raw = readFileSync5(
785
+ join5(sectionsDir, shard, file),
786
+ "utf-8"
787
+ );
788
+ const body = extractBody(raw);
789
+ if (body.length > 0) {
790
+ result.push({ kbid, body });
791
+ }
792
+ } catch {
793
+ continue;
794
+ }
795
+ }
796
+ }
797
+ return result;
798
+ }
799
+ async function rebuildVectors(targetDir, provider) {
800
+ if (provider.dimensions() === 0) {
801
+ return 0;
802
+ }
803
+ const sectionsDir = join5(targetDir, "sections");
804
+ if (!existsSync3(sectionsDir)) {
805
+ return 0;
806
+ }
807
+ const sections = collectSections(sectionsDir);
808
+ if (sections.length === 0) {
809
+ return 0;
810
+ }
811
+ const texts = sections.map((s) => s.body);
812
+ const vectors = await provider.embed(texts);
813
+ const entries = sections.map((s, i) => ({
814
+ kbid: s.kbid,
815
+ vector: vectors[i] ?? new Float32Array(provider.dimensions())
816
+ }));
817
+ await buildVectorIndex(
818
+ targetDir,
819
+ provider.modelName(),
820
+ provider.dimensions(),
821
+ entries
822
+ );
823
+ return sections.length;
824
+ }
825
+
404
826
  // src/shared/wasm-codec/functions/encode-string.function.ts
405
827
  var encoder = new TextEncoder();
406
828
  function encodeString(value) {
@@ -1218,7 +1640,9 @@ var WASM_METHOD_MAP = {
1218
1640
  list_docs_by_type: "worker_list_docs_by_type",
1219
1641
  recall: "worker_recall",
1220
1642
  export: "worker_export",
1221
- exportDb: "worker_export"
1643
+ exportDb: "worker_export",
1644
+ importDb: "worker_import",
1645
+ import_db: "worker_import"
1222
1646
  };
1223
1647
  var CONFIG_PREFIX = "config_";
1224
1648
  var CONFIG_KEY_MAP = {
@@ -1227,7 +1651,7 @@ var CONFIG_KEY_MAP = {
1227
1651
  item_limit: "itemLimit",
1228
1652
  index_limit: "indexLimit"
1229
1653
  };
1230
- var IpcError = class extends Error {
1654
+ var IpcError2 = class extends Error {
1231
1655
  /** JSON-RPC error code. */
1232
1656
  code;
1233
1657
  constructor(code, message) {
@@ -1249,6 +1673,7 @@ var WorkerDaemon = class {
1249
1673
  }
1250
1674
  _connectionCount = 0;
1251
1675
  _wasmModules = null;
1676
+ _embeddingProvider = null;
1252
1677
  _idleAt = 0;
1253
1678
  _idleTimer = null;
1254
1679
  _server = null;
@@ -1287,7 +1712,7 @@ var WorkerDaemon = class {
1287
1712
  * catches this, prints to stderr, and exits with code 1
1288
1713
  */
1289
1714
  checkPreconditions() {
1290
- if (!existsSync2(this.targetDir)) {
1715
+ if (!existsSync4(this.targetDir)) {
1291
1716
  throw new Error(
1292
1717
  `database directory not found: ${this.targetDir}`
1293
1718
  );
@@ -1321,19 +1746,20 @@ var WorkerDaemon = class {
1321
1746
  this._wasmDir
1322
1747
  );
1323
1748
  this._wasmModules = wasmModules;
1749
+ this._embeddingProvider = createEmbeddingProvider(
1750
+ this.config.embedding
1751
+ );
1324
1752
  this.initWorkerContext();
1325
1753
  this.runStartupIntegrityCheck();
1326
- const pidPath = join3(tmpdir(), `kbdb-${this.ctx}.pid`);
1327
- writeFileSync2(pidPath, process.pid.toString());
1328
1754
  const ipcPath = getIpcPath(this.ctx);
1329
- if (existsSync2(ipcPath)) {
1755
+ if (existsSync4(ipcPath)) {
1330
1756
  try {
1331
1757
  unlinkSync2(ipcPath);
1332
1758
  } catch {
1333
1759
  }
1334
1760
  }
1335
1761
  const handler = (req) => this.handleRequest(req);
1336
- this._server = createIpcServer(ipcPath, handler);
1762
+ this._server = await createIpcServer(ipcPath, handler);
1337
1763
  this._server.on("connection", () => {
1338
1764
  this.incrementConnections();
1339
1765
  this.resetIdleTimer();
@@ -1344,6 +1770,8 @@ var WorkerDaemon = class {
1344
1770
  this.resetIdleTimer();
1345
1771
  }
1346
1772
  });
1773
+ const pidPath = join6(tmpdir(), `kbdb-${this.ctx}.pid`);
1774
+ writeFileSync3(pidPath, process.pid.toString());
1347
1775
  this.resetIdleTimer();
1348
1776
  }
1349
1777
  /**
@@ -1363,7 +1791,7 @@ var WorkerDaemon = class {
1363
1791
  this._server = null;
1364
1792
  }
1365
1793
  this._wasmModules = null;
1366
- const pidPath = join3(tmpdir(), `kbdb-${this.ctx}.pid`);
1794
+ const pidPath = join6(tmpdir(), `kbdb-${this.ctx}.pid`);
1367
1795
  try {
1368
1796
  unlinkSync2(pidPath);
1369
1797
  } catch {
@@ -1373,7 +1801,7 @@ var WorkerDaemon = class {
1373
1801
  unlinkSync2(ipcPath);
1374
1802
  } catch {
1375
1803
  }
1376
- const crashPath = join3(tmpdir(), `kbdb-${this.ctx}.crash`);
1804
+ const crashPath = join6(tmpdir(), `kbdb-${this.ctx}.crash`);
1377
1805
  try {
1378
1806
  unlinkSync2(crashPath);
1379
1807
  } catch {
@@ -1410,7 +1838,7 @@ var WorkerDaemon = class {
1410
1838
  };
1411
1839
  } catch (err) {
1412
1840
  this._idleAt = Math.floor(Date.now() / 1e3);
1413
- if (err instanceof IpcError) {
1841
+ if (err instanceof IpcError2) {
1414
1842
  return this.errorResponse(
1415
1843
  request.id,
1416
1844
  err.code,
@@ -1468,10 +1896,10 @@ var WorkerDaemon = class {
1468
1896
  }
1469
1897
  /** Reads catalog.toml and validates the version field. */
1470
1898
  checkCatalogVersion() {
1471
- const catalogPath = join3(this.targetDir, "catalog.toml");
1899
+ const catalogPath = join6(this.targetDir, "catalog.toml");
1472
1900
  let text;
1473
1901
  try {
1474
- text = readFileSync4(catalogPath, "utf-8");
1902
+ text = readFileSync6(catalogPath, "utf-8");
1475
1903
  } catch {
1476
1904
  throw new Error(
1477
1905
  `cannot read database directory: ${this.targetDir} -- permission denied`
@@ -1530,7 +1958,7 @@ var WorkerDaemon = class {
1530
1958
  if (wasmMethod !== void 0) {
1531
1959
  return this.dispatchWasm(method, wasmMethod, params);
1532
1960
  }
1533
- throw new IpcError(-32601, `Method not found: ${method}`);
1961
+ throw new IpcError2(-32601, `Method not found: ${method}`);
1534
1962
  }
1535
1963
  async dispatchWasm(method, wasmExport, params) {
1536
1964
  if (method === "search" || method === "query") {
@@ -1596,13 +2024,16 @@ var WorkerDaemon = class {
1596
2024
  return this.handleGc();
1597
2025
  }
1598
2026
  if (method === "rebuildIndexes" || method === "rebuild_indexes") {
1599
- return this.handleRebuild();
2027
+ return await this.handleRebuild();
1600
2028
  }
1601
2029
  if (method === "initDirectory" || method === "init_directory") {
1602
2030
  return this.handleInitDirectory(params);
1603
2031
  }
2032
+ if (method === "importDb" || method === "import_db") {
2033
+ return await this.handleImport(params);
2034
+ }
1604
2035
  if (method === "migrateDatabase") {
1605
- throw new IpcError(
2036
+ throw new IpcError2(
1606
2037
  -32601,
1607
2038
  "migrateDatabase is not yet supported"
1608
2039
  );
@@ -1613,12 +2044,25 @@ var WorkerDaemon = class {
1613
2044
  }
1614
2045
  }
1615
2046
  // -- Search/query (token-based async) --
1616
- handleSearch(params) {
2047
+ async handleSearch(params) {
1617
2048
  const query = params["query"] ?? "";
1618
2049
  const mode = params["mode"] ?? "and";
1619
2050
  const limit = Number(params["limit"] ?? 20);
1620
2051
  const offset = Number(params["offset"] ?? 0);
2052
+ const algo = params["algo"] ?? "lexical";
1621
2053
  const encoded = encodeSearchParams(query, mode, limit, offset);
2054
+ const start = Date.now();
2055
+ const lexical = this.runLexicalSearch(encoded);
2056
+ const fused = await fuseSearchResults(
2057
+ lexical,
2058
+ algo,
2059
+ query,
2060
+ this._embeddingProvider ?? void 0,
2061
+ this.targetDir
2062
+ );
2063
+ return { ...fused, elapsed_ms: Date.now() - start };
2064
+ }
2065
+ runLexicalSearch(encoded) {
1622
2066
  const searchFn = this.getExport("worker_search");
1623
2067
  const ptr = this.wasmAlloc(encoded.length);
1624
2068
  this.wasmWrite(ptr, encoded);
@@ -1627,20 +2071,17 @@ var WorkerDaemon = class {
1627
2071
  const statusFn = this.getExport("worker_result_status");
1628
2072
  const status = statusFn(token);
1629
2073
  if (status === 3) {
1630
- const getResultFn2 = this.getExport("worker_get_result");
1631
- getResultFn2(token);
2074
+ this.getExport("worker_get_result")(token);
1632
2075
  const errBytes = this.readReturnSlot();
1633
- const errMsg = new TextDecoder().decode(errBytes);
1634
- throw new IpcError(-32e3, errMsg);
2076
+ throw new IpcError2(-32e3, new TextDecoder().decode(errBytes));
1635
2077
  }
1636
2078
  const getResultFn = this.getExport("worker_get_result");
1637
2079
  const rc = getResultFn(token);
1638
2080
  if (rc === -1) {
1639
2081
  const errBytes = this.readReturnSlot();
1640
- throw new IpcError(-32e3, new TextDecoder().decode(errBytes));
2082
+ throw new IpcError2(-32e3, new TextDecoder().decode(errBytes));
1641
2083
  }
1642
- const resultBytes = this.readReturnSlot();
1643
- return decodePagedSearchResult(resultBytes);
2084
+ return decodePagedSearchResult(this.readReturnSlot());
1644
2085
  }
1645
2086
  // -- Token status/result (u32 direct params) --
1646
2087
  handleResultStatus(params) {
@@ -1655,7 +2096,7 @@ var WorkerDaemon = class {
1655
2096
  const rc = fn(token);
1656
2097
  if (rc === -1) {
1657
2098
  const errBytes = this.readReturnSlot();
1658
- throw new IpcError(-32e3, new TextDecoder().decode(errBytes));
2099
+ throw new IpcError2(-32e3, new TextDecoder().decode(errBytes));
1659
2100
  }
1660
2101
  const bytes = this.readReturnSlot();
1661
2102
  return decodePagedSearchResult(bytes);
@@ -1682,7 +2123,11 @@ var WorkerDaemon = class {
1682
2123
  const encoded = encodeAddSectionParams(input);
1683
2124
  const bytes = this.callWasmSync("worker_add_section", encoded);
1684
2125
  const decoded = decodeAddSectionResult(bytes);
1685
- const nearDups = decoded.nearDuplicates.length > 0 ? decoded.nearDuplicates : this.scanNearDuplicates(input.content, decoded.kbid);
2126
+ const wasmDups = decoded.nearDuplicates;
2127
+ const tsDups = wasmDups.length > 0 ? [] : this.scanNearDuplicates(input.content, decoded.kbid);
2128
+ const nearDups = (wasmDups.length > 0 ? wasmDups : tsDups).map(
2129
+ (d) => ({ ...d, method: "jaccard" })
2130
+ );
1686
2131
  return {
1687
2132
  kbid: decoded.kbid,
1688
2133
  indexed_terms_count: decoded.indexedTermsCount,
@@ -1771,7 +2216,7 @@ var WorkerDaemon = class {
1771
2216
  this.wasmFree(ptr, encoded.length);
1772
2217
  if (rc === -1) {
1773
2218
  const errBytes = this.readReturnSlot();
1774
- throw new IpcError(
2219
+ throw new IpcError2(
1775
2220
  -32e3,
1776
2221
  new TextDecoder().decode(errBytes) || "invalidate failed"
1777
2222
  );
@@ -1810,7 +2255,12 @@ var WorkerDaemon = class {
1810
2255
  this.callWasmZeroArg("worker_status");
1811
2256
  const bytes = this.readReturnSlot();
1812
2257
  const text = new TextDecoder().decode(bytes);
1813
- return decodeKeyValueText(text);
2258
+ const kv = decodeKeyValueText(text);
2259
+ const mem = this._wasmModules?.memory;
2260
+ if (mem) {
2261
+ kv["wasm_memory_bytes"] = String(mem.buffer.byteLength);
2262
+ }
2263
+ return kv;
1814
2264
  }
1815
2265
  handleIntegrityCheck() {
1816
2266
  this.callWasmZeroArg("worker_check_integrity");
@@ -1833,13 +2283,13 @@ var WorkerDaemon = class {
1833
2283
  stale_sources: staleSources
1834
2284
  };
1835
2285
  }
1836
- handleRebuild() {
2286
+ async handleRebuild() {
1837
2287
  const fn = this.getExport("worker_rebuild_indexes");
1838
2288
  const rc = fn();
1839
2289
  if (rc === -1) {
1840
2290
  const errBytes = this.readReturnSlot();
1841
2291
  const errMsg = new TextDecoder().decode(errBytes);
1842
- throw new IpcError(-32e3, errMsg || "rebuild failed");
2292
+ throw new IpcError2(-32e3, errMsg || "rebuild failed");
1843
2293
  }
1844
2294
  const resultBytes = this.readReturnSlot();
1845
2295
  const reindexed = resultBytes.length >= 4 ? new DataView(
@@ -1847,7 +2297,18 @@ var WorkerDaemon = class {
1847
2297
  resultBytes.byteOffset,
1848
2298
  resultBytes.byteLength
1849
2299
  ).getUint32(0, true) : 0;
1850
- return { ok: true, sections_reindexed: reindexed };
2300
+ let vectorsRebuilt = 0;
2301
+ if (this._embeddingProvider !== null) {
2302
+ vectorsRebuilt = await rebuildVectors(
2303
+ this.targetDir,
2304
+ this._embeddingProvider
2305
+ );
2306
+ }
2307
+ return {
2308
+ ok: true,
2309
+ sections_reindexed: reindexed,
2310
+ vectors_rebuilt: vectorsRebuilt
2311
+ };
1851
2312
  }
1852
2313
  // -- Export (read operation, no lock required) --
1853
2314
  handleExport(params) {
@@ -1865,14 +2326,57 @@ var WorkerDaemon = class {
1865
2326
  elapsed_ms: elapsed
1866
2327
  };
1867
2328
  }
2329
+ async handleImport(params) {
2330
+ const sourcePath = params["sourcePath"] ?? "";
2331
+ const dryRun = params["dryRun"] === true;
2332
+ const start = Date.now();
2333
+ const sectionCount = this.countFiles(
2334
+ join6(sourcePath, "sections"),
2335
+ ".section"
2336
+ );
2337
+ const documentCount = this.countFiles(
2338
+ join6(sourcePath, "documents"),
2339
+ ".toml"
2340
+ );
2341
+ let rebuilt = false;
2342
+ if (!dryRun && sectionCount > 0) {
2343
+ await this.handleRebuild();
2344
+ rebuilt = true;
2345
+ }
2346
+ return {
2347
+ sections_imported: sectionCount,
2348
+ documents_imported: documentCount,
2349
+ rebuilt,
2350
+ dry_run: dryRun,
2351
+ elapsed_ms: Date.now() - start
2352
+ };
2353
+ }
2354
+ countFiles(dir, ext) {
2355
+ if (!existsSync4(dir)) return 0;
2356
+ return this.collectFiles(dir, ext).length;
2357
+ }
2358
+ collectFiles(dir, ext) {
2359
+ const result = [];
2360
+ for (const entry of readdirSync3(dir, {
2361
+ withFileTypes: true
2362
+ })) {
2363
+ const full = join6(dir, entry.name);
2364
+ if (entry.isDirectory()) {
2365
+ result.push(...this.collectFiles(full, ext));
2366
+ } else if (entry.name.endsWith(ext)) {
2367
+ result.push(full);
2368
+ }
2369
+ }
2370
+ return result;
2371
+ }
1868
2372
  // -- Near-duplicate detection --
1869
2373
  scanNearDuplicates(content, newKbid) {
1870
2374
  const newTerms = this.extractTermSet(content);
1871
2375
  if (newTerms.size === 0) return [];
1872
- const sectionsDir = join3(this.targetDir, "sections");
2376
+ const sectionsDir = join6(this.targetDir, "sections");
1873
2377
  let shards;
1874
2378
  try {
1875
- shards = readdirSync2(sectionsDir);
2379
+ shards = readdirSync3(sectionsDir);
1876
2380
  } catch {
1877
2381
  return [];
1878
2382
  }
@@ -1880,7 +2384,7 @@ var WorkerDaemon = class {
1880
2384
  for (const shard of shards) {
1881
2385
  let files;
1882
2386
  try {
1883
- files = readdirSync2(join3(sectionsDir, shard));
2387
+ files = readdirSync3(join6(sectionsDir, shard));
1884
2388
  } catch {
1885
2389
  continue;
1886
2390
  }
@@ -1889,8 +2393,8 @@ var WorkerDaemon = class {
1889
2393
  const kbid = file.slice(0, -8);
1890
2394
  if (kbid === newKbid) continue;
1891
2395
  try {
1892
- const data = readFileSync4(
1893
- join3(sectionsDir, shard, file),
2396
+ const data = readFileSync6(
2397
+ join6(sectionsDir, shard, file),
1894
2398
  "utf-8"
1895
2399
  );
1896
2400
  const sep = data.indexOf("\n---\n");
@@ -2046,7 +2550,7 @@ var WorkerDaemon = class {
2046
2550
  if (rc === -1) {
2047
2551
  const errBytes = this.readReturnSlot();
2048
2552
  const errMsg = new TextDecoder().decode(errBytes);
2049
- throw new IpcError(-32e3, errMsg || exportName + " failed");
2553
+ throw new IpcError2(-32e3, errMsg || exportName + " failed");
2050
2554
  }
2051
2555
  return this.readReturnSlot();
2052
2556
  }
@@ -2056,7 +2560,7 @@ var WorkerDaemon = class {
2056
2560
  if (rc === -1) {
2057
2561
  const errBytes = this.readReturnSlot();
2058
2562
  const errMsg = new TextDecoder().decode(errBytes);
2059
- throw new IpcError(-32e3, errMsg || exportName + " failed");
2563
+ throw new IpcError2(-32e3, errMsg || exportName + " failed");
2060
2564
  }
2061
2565
  }
2062
2566
  invokeWasmRaw(exportName, input) {
@@ -2064,10 +2568,10 @@ var WorkerDaemon = class {
2064
2568
  }
2065
2569
  handleCheckVersion(params) {
2066
2570
  const targetPath = typeof params.targetPath === "string" ? params.targetPath : this.targetDir;
2067
- const catalogPath = join3(targetPath, "catalog.toml");
2571
+ const catalogPath = join6(targetPath, "catalog.toml");
2068
2572
  let text;
2069
2573
  try {
2070
- text = readFileSync4(catalogPath, "utf-8");
2574
+ text = readFileSync6(catalogPath, "utf-8");
2071
2575
  } catch {
2072
2576
  return {
2073
2577
  status: "needs_migration",
@@ -2108,7 +2612,7 @@ var WorkerDaemon = class {
2108
2612
  const key = method.slice(CONFIG_PREFIX.length);
2109
2613
  const prop = CONFIG_KEY_MAP[key];
2110
2614
  if (prop === void 0) {
2111
- throw new IpcError(-32601, `Method not found: ${method}`);
2615
+ throw new IpcError2(-32601, `Method not found: ${method}`);
2112
2616
  }
2113
2617
  return this.config[prop];
2114
2618
  }
@@ -2161,12 +2665,12 @@ async function startDaemon(contextPath, wasmDir2) {
2161
2665
  }
2162
2666
  function writeCrashLog(contextId, message) {
2163
2667
  try {
2164
- const crashPath = join4(tmpdir2(), `kbdb-${contextId}.crash`);
2668
+ const crashPath = join7(tmpdir2(), `kbdb-${contextId}.crash`);
2165
2669
  const payload = JSON.stringify({
2166
2670
  error: message,
2167
2671
  timestamp: Date.now()
2168
2672
  });
2169
- writeFileSync3(crashPath, payload);
2673
+ writeFileSync4(crashPath, payload);
2170
2674
  } catch {
2171
2675
  }
2172
2676
  }
@@ -2197,7 +2701,7 @@ var baseDir = resolveBaseDir(import.meta.url, import.meta.dirname);
2197
2701
  var wasmDir = resolveWasmDir(baseDir.scriptDir);
2198
2702
  async function main() {
2199
2703
  const result = await runWorker(getArgs(), {
2200
- existsSync: existsSync3,
2704
+ existsSync: existsSync5,
2201
2705
  startDaemon,
2202
2706
  wasmDir
2203
2707
  });