@dikolab/kbdb 0.3.2 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (523) hide show
  1. package/README.md +92 -90
  2. package/dist/chunk-BJXEVALU.mjs +337 -0
  3. package/dist/chunk-BJXEVALU.mjs.map +7 -0
  4. package/dist/cli.cjs +1398 -378
  5. package/dist/cli.cjs.map +4 -4
  6. package/dist/cli.d.ts +9 -0
  7. package/dist/cli.mjs +1138 -342
  8. package/dist/cli.mjs.map +4 -4
  9. package/dist/kbdb-worker.cjs +1115 -135
  10. package/dist/kbdb-worker.cjs.map +4 -4
  11. package/dist/mod.cjs +351 -69
  12. package/dist/mod.cjs.map +4 -4
  13. package/dist/mod.d.ts +23 -2
  14. package/dist/mod.mjs +349 -68
  15. package/dist/mod.mjs.map +4 -4
  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 +22 -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/classes/tfidf-embedding-provider.class.d.ts +28 -0
  38. package/dist/src/shared/embedding/constants/tfidf-defaults.constant.d.ts +4 -0
  39. package/dist/src/shared/embedding/functions/append-vector-entry.function.d.ts +14 -0
  40. package/dist/src/shared/embedding/functions/create-embedding-provider.function.d.ts +15 -0
  41. package/dist/src/shared/embedding/functions/detect-stale-vectors.function.d.ts +16 -0
  42. package/dist/src/shared/embedding/functions/parse-api-embedding-response.function.d.ts +11 -0
  43. package/dist/src/shared/embedding/functions/rebuild-vectors.function.d.ts +15 -0
  44. package/dist/src/shared/embedding/functions/scan-semantic-contradictions.function.d.ts +13 -0
  45. package/dist/src/shared/embedding/index.d.ts +9 -0
  46. package/dist/src/shared/embedding/typings/semantic-contradiction.model.d.ts +21 -0
  47. package/dist/src/shared/embedding/typings/stale-vectors-report.model.d.ts +16 -0
  48. package/dist/src/shared/log/constants/log-colors.constant.d.ts +5 -0
  49. package/dist/src/shared/log/constants/log-defaults.constant.d.ts +3 -0
  50. package/dist/src/shared/log/constants/log-icons.constant.d.ts +3 -0
  51. package/dist/src/shared/log/functions/configure-log.function.d.ts +12 -0
  52. package/dist/src/shared/log/functions/log.function.d.ts +28 -0
  53. package/dist/src/shared/log/functions/parse-log-level.function.d.ts +10 -0
  54. package/dist/src/shared/log/functions/resolve-log-level.function.d.ts +12 -0
  55. package/dist/src/shared/log/functions/write-stderr.function.d.ts +10 -0
  56. package/dist/src/shared/log/index.d.ts +10 -0
  57. package/dist/src/shared/log/typings/log-config.interface.d.ts +7 -0
  58. package/dist/src/shared/log/typings/log-level.type.d.ts +7 -0
  59. package/dist/src/shared/log/typings/log-output.interface.d.ts +4 -0
  60. package/dist/src/shared/mcp/classes/mcp-server.class.d.ts +22 -2
  61. package/dist/src/shared/mcp/functions/create-mcp-server.function.d.ts +6 -1
  62. package/dist/src/shared/mcp/functions/has-sampling-capability.function.d.ts +8 -0
  63. package/dist/src/shared/mcp/functions/run-auto-capture.function.d.ts +26 -0
  64. package/dist/src/shared/mcp/typings/mcp-client.interface.d.ts +2 -0
  65. package/dist/src/shared/mcp/typings/mcp-integrity-check-result.model.d.ts +24 -0
  66. package/dist/src/shared/mcp/typings/mcp-worker-client.interface.d.ts +3 -1
  67. package/dist/src/shared/version/constants/version.constant.d.ts +1 -1
  68. package/dist/src/shared/wasm-codec/typings/paged-search-result.model.d.ts +2 -0
  69. package/dist/src/shared/worker-client/classes/worker-client.class.d.ts +38 -1
  70. package/dist/src/shared/worker-client/constants/request-timeout.constant.d.ts +2 -0
  71. package/dist/src/shared/worker-client/constants/retry-defaults.constant.d.ts +2 -0
  72. package/dist/src/shared/worker-client/functions/get-or-create-client.function.d.ts +20 -0
  73. package/dist/src/shared/worker-client/functions/retry-on-timeout.function.d.ts +18 -0
  74. package/dist/src/shared/worker-client/index.d.ts +4 -1
  75. package/dist/src/shared/worker-client/typings/import-result.model.d.ts +16 -0
  76. package/dist/src/shared/worker-client/typings/integrity-check-result.model.d.ts +24 -0
  77. package/dist/src/shared/worker-client/typings/search-params.model.d.ts +4 -0
  78. package/dist/src/shared/worker-client/typings/search-result.model.d.ts +6 -0
  79. package/dist/src/shared/worker-client/typings/worker-client-options.interface.d.ts +7 -0
  80. package/dist/src/shared/worker-daemon/classes/worker-daemon.class.d.ts +6 -0
  81. package/dist/src/shared/worker-daemon/functions/create-ipc-server.function.d.ts +11 -11
  82. package/dist/src/shared/worker-daemon/functions/embed-after-learn.function.d.ts +13 -0
  83. package/dist/src/shared/worker-daemon/functions/handle-hybrid-search.function.d.ts +44 -0
  84. package/dist/src/shared/worker-daemon/functions/handle-import.function.d.ts +14 -0
  85. package/dist/src/shared/worker-daemon/functions/handle-read-ops.function.d.ts +7 -1
  86. package/dist/src/shared/worker-daemon/functions/handle-write-ops.function.d.ts +9 -4
  87. package/dist/src/shared/worker-daemon/functions/run-worker.function.d.ts +6 -1
  88. package/dist/src/shared/worker-daemon/typings/handler-context.interface.d.ts +3 -0
  89. package/dist/src/shared/worker-daemon/typings/wasm-modules.interface.d.ts +5 -0
  90. package/dist/wasm/default-embedding/kbdb_default_embedding.d.ts +55 -0
  91. package/dist/wasm/default-embedding/kbdb_default_embedding.js +156 -0
  92. package/{src/wasm/query-parser/kbdb_query_parser_bg.wasm → dist/wasm/default-embedding/kbdb_default_embedding_bg.wasm} +0 -0
  93. package/dist/wasm/default-embedding/kbdb_default_embedding_bg.wasm.d.ts +12 -0
  94. package/dist/wasm/default-embedding/package.json +13 -0
  95. package/dist/wasm/fs-database/kbdb_fs_database.d.ts +16 -85
  96. package/dist/wasm/fs-database/kbdb_fs_database.js +16 -85
  97. package/dist/wasm/fs-database/kbdb_fs_database_bg.wasm +0 -0
  98. package/dist/wasm/fs-migration/kbdb_fs_migration.d.ts +38 -0
  99. package/dist/wasm/fs-migration/kbdb_fs_migration.js +130 -0
  100. package/dist/wasm/fs-migration/kbdb_fs_migration_bg.wasm +0 -0
  101. package/dist/wasm/fs-migration/kbdb_fs_migration_bg.wasm.d.ts +9 -0
  102. package/dist/wasm/fs-migration/package.json +13 -0
  103. package/dist/wasm/kb-worker/kbdb_worker.d.ts +20 -115
  104. package/dist/wasm/kb-worker/kbdb_worker.js +20 -115
  105. package/dist/wasm/kb-worker/kbdb_worker_bg.wasm +0 -0
  106. package/dist/wasm/query-parser/kbdb_query_parser_bg.wasm +0 -0
  107. package/dist/worker.d.ts +8 -0
  108. package/dist/worker.mjs +899 -143
  109. package/dist/worker.mjs.map +4 -4
  110. package/docs/details/README.md +4 -0
  111. package/docs/details/agent-tooling.md +132 -0
  112. package/docs/details/cli.md +91 -18
  113. package/docs/details/knowledge-base.md +180 -0
  114. package/docs/details/library-api.md +42 -2
  115. package/docs/details/mcp-server.md +53 -7
  116. package/docs/details/search-and-ranking.md +16 -11
  117. package/docs/goals/cli.md +142 -37
  118. package/docs/goals/content-parser.md +1 -1
  119. package/docs/goals/hybrid-search.md +71 -42
  120. package/docs/goals/mcp.md +24 -19
  121. package/docs/goals/overview.md +1 -1
  122. package/docs/goals/query-parser.md +8 -0
  123. package/docs/goals/semantic-dedup.md +7 -3
  124. package/docs/goals/worker-client.md +62 -1
  125. package/docs/goals/worker-daemon.md +83 -30
  126. package/docs/modules/overview.md +43 -22
  127. package/docs/modules/rust/embedding/module.md +91 -0
  128. package/docs/modules/rust/overview.md +56 -21
  129. package/docs/modules/rust/query-parser/functions/module.md +7 -5
  130. package/docs/modules/rust/query-parser/functions/pipeline.md +6 -138
  131. package/docs/modules/rust/query-parser/module.md +16 -22
  132. package/docs/modules/rust/query-parser/types/module.md +5 -4
  133. package/docs/modules/rust/query-parser/types/token.md +5 -1
  134. package/docs/modules/rust/shared/content-parser/functions.md +1 -1
  135. package/docs/modules/rust/shared/memory/module.md +1 -1
  136. package/docs/modules/rust/shared/module.md +33 -5
  137. package/docs/modules/rust/shared/pipeline/functions.md +141 -0
  138. package/docs/modules/rust/shared/pipeline/module.md +62 -0
  139. package/docs/modules/rust/shared/pipeline/types.md +43 -0
  140. package/docs/modules/rust/shared/section/module.md +1 -1
  141. package/docs/modules/rust/shared/section/types.md +1 -1
  142. package/docs/modules/typescript/cli.md +5 -3
  143. package/docs/modules/typescript/kbdb-worker.md +20 -5
  144. package/docs/modules/typescript/overview.md +28 -6
  145. package/docs/modules/typescript/shared/cli/functions.md +131 -17
  146. package/docs/modules/typescript/shared/cli/module.md +33 -20
  147. package/docs/modules/typescript/shared/cli/typings.md +25 -0
  148. package/docs/modules/typescript/shared/embedding/functions.md +125 -19
  149. package/docs/modules/typescript/shared/embedding/module.md +10 -4
  150. package/docs/modules/typescript/shared/embedding/typings.md +7 -5
  151. package/docs/modules/typescript/shared/log/constants.md +82 -0
  152. package/docs/modules/typescript/shared/log/functions.md +131 -0
  153. package/docs/modules/typescript/shared/log/module.md +153 -0
  154. package/docs/modules/typescript/shared/log/typings.md +82 -0
  155. package/docs/modules/typescript/shared/mcp/module.md +1 -1
  156. package/docs/modules/typescript/shared/mcp/typings.md +8 -1
  157. package/docs/modules/typescript/shared/module.md +22 -6
  158. package/docs/modules/typescript/shared/worker-client/module.md +9 -1
  159. package/docs/modules/typescript/shared/worker-client/typings.md +3 -0
  160. package/docs/modules/typescript/shared/worker-daemon/functions.md +19 -6
  161. package/docs/modules/typescript/shared/worker-daemon/module.md +11 -5
  162. package/docs/modules/typescript/shared/worker-daemon/typings.md +13 -7
  163. package/docs/overview.md +1 -2
  164. package/docs/release-notes/0.4.0.md +80 -0
  165. package/docs/release-notes/0.4.1.md +149 -0
  166. package/docs/release-notes/README.md +1 -0
  167. package/mod.ts +33 -15
  168. package/package.json +12 -11
  169. package/dist/chunk-JG2UCKLI.mjs +0 -95
  170. package/dist/chunk-JG2UCKLI.mjs.map +0 -7
  171. package/src/cli.ts +0 -71
  172. package/src/shared/auto-capture/classes/auto-capture-controller.class.ts +0 -62
  173. package/src/shared/auto-capture/constants/auto-capture-defaults.constant.ts +0 -15
  174. package/src/shared/auto-capture/functions/build-capture-prompt.function.ts +0 -27
  175. package/src/shared/auto-capture/functions/evaluate-trigger.function.ts +0 -50
  176. package/src/shared/auto-capture/index.ts +0 -7
  177. package/src/shared/auto-capture/typings/auto-capture-config.interface.ts +0 -13
  178. package/src/shared/auto-capture/typings/auto-capture-state.interface.ts +0 -13
  179. package/src/shared/auto-capture/typings/auto-capture-trigger.interface.ts +0 -7
  180. package/src/shared/cli/constants/defaults.constant.ts +0 -19
  181. package/src/shared/cli/constants/global-help.constant.ts +0 -73
  182. package/src/shared/cli/constants/help-text.constant.ts +0 -4
  183. package/src/shared/cli/constants/leaf-help.constant.ts +0 -219
  184. package/src/shared/cli/constants/memory-protocol-body.constant.ts +0 -39
  185. package/src/shared/cli/constants/query-guidance-body.constant.ts +0 -37
  186. package/src/shared/cli/constants/subcommand-help.constant.ts +0 -195
  187. package/src/shared/cli/functions/collect-files.function.ts +0 -55
  188. package/src/shared/cli/functions/compute-section-kbid.function.ts +0 -49
  189. package/src/shared/cli/functions/dispatch-command.function.ts +0 -390
  190. package/src/shared/cli/functions/ensure-db.function.ts +0 -21
  191. package/src/shared/cli/functions/error-to-message.function.ts +0 -9
  192. package/src/shared/cli/functions/find-db.function.ts +0 -20
  193. package/src/shared/cli/functions/format-mcp-output.function.ts +0 -41
  194. package/src/shared/cli/functions/format-output.function.ts +0 -95
  195. package/src/shared/cli/functions/format-text-output.function.ts +0 -42
  196. package/src/shared/cli/functions/generate-group-help.function.ts +0 -41
  197. package/src/shared/cli/functions/generate-help.function.ts +0 -654
  198. package/src/shared/cli/functions/handle-data-command.function.ts +0 -67
  199. package/src/shared/cli/functions/handle-mcp.function.ts +0 -56
  200. package/src/shared/cli/functions/handle-migrate.function.ts +0 -64
  201. package/src/shared/cli/functions/hydrate-search-previews.function.ts +0 -29
  202. package/src/shared/cli/functions/install-default-skills.function.ts +0 -296
  203. package/src/shared/cli/functions/is-stdin-tty.function.ts +0 -12
  204. package/src/shared/cli/functions/parse-args.function.ts +0 -156
  205. package/src/shared/cli/functions/prompt-user.function.ts +0 -36
  206. package/src/shared/cli/functions/resolve-skill-names.function.ts +0 -43
  207. package/src/shared/cli/functions/run-agent-create.function.ts +0 -114
  208. package/src/shared/cli/functions/run-agent-delete.function.ts +0 -47
  209. package/src/shared/cli/functions/run-agent-get.function.ts +0 -166
  210. package/src/shared/cli/functions/run-agent-list.function.ts +0 -58
  211. package/src/shared/cli/functions/run-check.function.ts +0 -159
  212. package/src/shared/cli/functions/run-cli.function.ts +0 -299
  213. package/src/shared/cli/functions/run-content.function.ts +0 -47
  214. package/src/shared/cli/functions/run-db-init.function.ts +0 -44
  215. package/src/shared/cli/functions/run-db-migrate.function.ts +0 -40
  216. package/src/shared/cli/functions/run-export.function.ts +0 -40
  217. package/src/shared/cli/functions/run-gc.function.ts +0 -51
  218. package/src/shared/cli/functions/run-init.function.ts +0 -93
  219. package/src/shared/cli/functions/run-learn.function.ts +0 -223
  220. package/src/shared/cli/functions/run-migrate.function.ts +0 -85
  221. package/src/shared/cli/functions/run-rebuild.function.ts +0 -47
  222. package/src/shared/cli/functions/run-recall.function.ts +0 -66
  223. package/src/shared/cli/functions/run-search.function.ts +0 -133
  224. package/src/shared/cli/functions/run-skill-delete.function.ts +0 -47
  225. package/src/shared/cli/functions/run-skill-get.function.ts +0 -90
  226. package/src/shared/cli/functions/run-skill-learn.function.ts +0 -70
  227. package/src/shared/cli/functions/run-skill-list.function.ts +0 -74
  228. package/src/shared/cli/functions/run-status.function.ts +0 -29
  229. package/src/shared/cli/functions/run-unlearn.function.ts +0 -58
  230. package/src/shared/cli/functions/version-gate.function.ts +0 -44
  231. package/src/shared/cli/functions/wrap-command.function.ts +0 -34
  232. package/src/shared/cli/index.ts +0 -55
  233. package/src/shared/cli/typings/agent-create-client.interface.ts +0 -47
  234. package/src/shared/cli/typings/agent-get-client.interface.ts +0 -39
  235. package/src/shared/cli/typings/check-client.interface.ts +0 -66
  236. package/src/shared/cli/typings/cli-deps.interface.ts +0 -54
  237. package/src/shared/cli/typings/cli-options.interface.ts +0 -72
  238. package/src/shared/cli/typings/command-result.model.ts +0 -15
  239. package/src/shared/cli/typings/disconnectable-client.interface.ts +0 -29
  240. package/src/shared/cli/typings/dispatch-client.type.ts +0 -46
  241. package/src/shared/cli/typings/learn-client.interface.ts +0 -53
  242. package/src/shared/cli/typings/learn-io.interface.ts +0 -5
  243. package/src/shared/cli/typings/learn-result.model.ts +0 -27
  244. package/src/shared/cli/typings/search-client.interface.ts +0 -73
  245. package/src/shared/cli/typings/search-display.model.ts +0 -54
  246. package/src/shared/dir-resolver/functions/join-path.function.ts +0 -13
  247. package/src/shared/dir-resolver/functions/resolve-base-dir.function.ts +0 -25
  248. package/src/shared/dir-resolver/functions/resolve-wasm-dir.function.ts +0 -5
  249. package/src/shared/dir-resolver/functions/resolve-worker-script.function.ts +0 -13
  250. package/src/shared/dir-resolver/index.ts +0 -11
  251. package/src/shared/dir-resolver/typings/base-dir.interface.ts +0 -4
  252. package/src/shared/embedding/classes/null-embedding-provider.class.ts +0 -29
  253. package/src/shared/embedding/constants/near-duplicate-thresholds.constant.ts +0 -17
  254. package/src/shared/embedding/functions/build-vector-index.function.ts +0 -79
  255. package/src/shared/embedding/functions/cosine-similarity.function.ts +0 -31
  256. package/src/shared/embedding/functions/detect-near-duplicates.function.ts +0 -69
  257. package/src/shared/embedding/functions/jaccard-coefficient.function.ts +0 -26
  258. package/src/shared/embedding/functions/read-vector-index-meta.function.ts +0 -44
  259. package/src/shared/embedding/functions/rrf-fuse.function.ts +0 -33
  260. package/src/shared/embedding/functions/search-vectors.function.ts +0 -59
  261. package/src/shared/embedding/index.ts +0 -20
  262. package/src/shared/embedding/typings/embedding-config.interface.ts +0 -23
  263. package/src/shared/embedding/typings/embedding-provider.interface.ts +0 -25
  264. package/src/shared/embedding/typings/near-duplicate-candidate.model.ts +0 -25
  265. package/src/shared/embedding/typings/near-duplicate-result.model.ts +0 -26
  266. package/src/shared/embedding/typings/vector-index-entry.model.ts +0 -13
  267. package/src/shared/embedding/typings/vector-index-meta.model.ts +0 -14
  268. package/src/shared/embedding/typings/vector-search-result.model.ts +0 -8
  269. package/src/shared/hash/functions/compute-sha256.ts +0 -17
  270. package/src/shared/hash/index.ts +0 -1
  271. package/src/shared/mcp/classes/mcp-server.class.ts +0 -480
  272. package/src/shared/mcp/constants/mcp-error-codes.constant.ts +0 -30
  273. package/src/shared/mcp/constants/tool-agent-create.constant.ts +0 -39
  274. package/src/shared/mcp/constants/tool-agent-delete.constant.ts +0 -26
  275. package/src/shared/mcp/constants/tool-agent-get.constant.ts +0 -24
  276. package/src/shared/mcp/constants/tool-agent-list.constant.ts +0 -18
  277. package/src/shared/mcp/constants/tool-auto-capture-review.constant.ts +0 -32
  278. package/src/shared/mcp/constants/tool-check.constant.ts +0 -21
  279. package/src/shared/mcp/constants/tool-content.constant.ts +0 -29
  280. package/src/shared/mcp/constants/tool-export.constant.ts +0 -27
  281. package/src/shared/mcp/constants/tool-gc.constant.ts +0 -21
  282. package/src/shared/mcp/constants/tool-learn.constant.ts +0 -58
  283. package/src/shared/mcp/constants/tool-rebuild.constant.ts +0 -21
  284. package/src/shared/mcp/constants/tool-recall.constant.ts +0 -36
  285. package/src/shared/mcp/constants/tool-retrieve.constant.ts +0 -31
  286. package/src/shared/mcp/constants/tool-search.constant.ts +0 -51
  287. package/src/shared/mcp/constants/tool-skill-delete.constant.ts +0 -24
  288. package/src/shared/mcp/constants/tool-skill-get.constant.ts +0 -27
  289. package/src/shared/mcp/constants/tool-skill-learn.constant.ts +0 -37
  290. package/src/shared/mcp/constants/tool-skill-list.constant.ts +0 -18
  291. package/src/shared/mcp/constants/tool-status.constant.ts +0 -20
  292. package/src/shared/mcp/constants/tool-unlearn.constant.ts +0 -25
  293. package/src/shared/mcp/functions/as-boolean-or-undefined.function.ts +0 -11
  294. package/src/shared/mcp/functions/as-string-array-or-undefined.function.ts +0 -17
  295. package/src/shared/mcp/functions/as-string-array.function.ts +0 -15
  296. package/src/shared/mcp/functions/as-string.function.ts +0 -10
  297. package/src/shared/mcp/functions/build-skills-text.function.ts +0 -43
  298. package/src/shared/mcp/functions/create-mcp-server.function.ts +0 -14
  299. package/src/shared/mcp/functions/create-prompt-definitions.function.ts +0 -102
  300. package/src/shared/mcp/functions/create-resource-templates.function.ts +0 -23
  301. package/src/shared/mcp/functions/create-tool-definitions.function.ts +0 -530
  302. package/src/shared/mcp/functions/extract-skill-arguments.function.ts +0 -27
  303. package/src/shared/mcp/functions/handle-agent-create.function.ts +0 -116
  304. package/src/shared/mcp/functions/handle-agent-delete.function.ts +0 -50
  305. package/src/shared/mcp/functions/handle-agent-get.function.ts +0 -160
  306. package/src/shared/mcp/functions/handle-agent-list.function.ts +0 -50
  307. package/src/shared/mcp/functions/handle-agent-prompt.function.ts +0 -68
  308. package/src/shared/mcp/functions/handle-completion.function.ts +0 -114
  309. package/src/shared/mcp/functions/handle-mcp-request.function.ts +0 -202
  310. package/src/shared/mcp/functions/handle-prompt-get.function.ts +0 -220
  311. package/src/shared/mcp/functions/handle-recall.function.ts +0 -66
  312. package/src/shared/mcp/functions/handle-resource-read.function.ts +0 -56
  313. package/src/shared/mcp/functions/handle-roots-list.function.ts +0 -29
  314. package/src/shared/mcp/functions/handle-skill-prompt.function.ts +0 -44
  315. package/src/shared/mcp/functions/handle-tool-auto-capture-review.function.ts +0 -24
  316. package/src/shared/mcp/functions/handle-tool-call.function.ts +0 -560
  317. package/src/shared/mcp/functions/handle-tool-check.function.ts +0 -21
  318. package/src/shared/mcp/functions/handle-tool-content.function.ts +0 -23
  319. package/src/shared/mcp/functions/handle-tool-export.function.ts +0 -25
  320. package/src/shared/mcp/functions/handle-tool-gc.function.ts +0 -21
  321. package/src/shared/mcp/functions/handle-tool-learn.function.ts +0 -69
  322. package/src/shared/mcp/functions/handle-tool-rebuild.function.ts +0 -21
  323. package/src/shared/mcp/functions/handle-tool-retrieve.function.ts +0 -40
  324. package/src/shared/mcp/functions/handle-tool-search.function.ts +0 -47
  325. package/src/shared/mcp/functions/handle-tool-skill-delete.function.ts +0 -34
  326. package/src/shared/mcp/functions/handle-tool-skill-get.function.ts +0 -59
  327. package/src/shared/mcp/functions/handle-tool-skill-learn.function.ts +0 -61
  328. package/src/shared/mcp/functions/handle-tool-skill-list.function.ts +0 -39
  329. package/src/shared/mcp/functions/handle-tool-status.function.ts +0 -21
  330. package/src/shared/mcp/functions/handle-tool-unlearn.function.ts +0 -24
  331. package/src/shared/mcp/functions/parse-agent-meta.function.ts +0 -27
  332. package/src/shared/mcp/functions/parse-skill-arguments.function.ts +0 -36
  333. package/src/shared/mcp/functions/parse-skill-content.function.ts +0 -38
  334. package/src/shared/mcp/functions/read-agent-meta.function.ts +0 -41
  335. package/src/shared/mcp/functions/resolve-skill-refs.function.ts +0 -50
  336. package/src/shared/mcp/functions/run-startup-health-check.function.ts +0 -34
  337. package/src/shared/mcp/functions/serialize-skill-content.function.ts +0 -12
  338. package/src/shared/mcp/functions/should-emit-log.function.ts +0 -38
  339. package/src/shared/mcp/index.ts +0 -28
  340. package/src/shared/mcp/typings/agent-types.interface.ts +0 -39
  341. package/src/shared/mcp/typings/log-types.interface.ts +0 -26
  342. package/src/shared/mcp/typings/mcp-capabilities.interface.ts +0 -16
  343. package/src/shared/mcp/typings/mcp-client.interface.ts +0 -317
  344. package/src/shared/mcp/typings/mcp-completion.interface.ts +0 -45
  345. package/src/shared/mcp/typings/mcp-content-result.model.ts +0 -9
  346. package/src/shared/mcp/typings/mcp-export-result.model.ts +0 -11
  347. package/src/shared/mcp/typings/mcp-gc-result.model.ts +0 -15
  348. package/src/shared/mcp/typings/mcp-integrity-check-result.model.ts +0 -17
  349. package/src/shared/mcp/typings/mcp-integrity-error.model.ts +0 -15
  350. package/src/shared/mcp/typings/mcp-notification.interface.ts +0 -9
  351. package/src/shared/mcp/typings/mcp-rebuild-result.model.ts +0 -9
  352. package/src/shared/mcp/typings/mcp-request.interface.ts +0 -11
  353. package/src/shared/mcp/typings/mcp-resource-result.interface.ts +0 -12
  354. package/src/shared/mcp/typings/mcp-resource-template.interface.ts +0 -11
  355. package/src/shared/mcp/typings/mcp-response.interface.ts +0 -18
  356. package/src/shared/mcp/typings/mcp-server-info.interface.ts +0 -7
  357. package/src/shared/mcp/typings/mcp-server-state.interface.ts +0 -17
  358. package/src/shared/mcp/typings/mcp-tool-annotations.interface.ts +0 -32
  359. package/src/shared/mcp/typings/mcp-tool-definition.interface.ts +0 -16
  360. package/src/shared/mcp/typings/mcp-tool-result.interface.ts +0 -19
  361. package/src/shared/mcp/typings/mcp-types.interface.ts +0 -158
  362. package/src/shared/mcp/typings/mcp-worker-client.interface.ts +0 -243
  363. package/src/shared/mcp/typings/prompt-types.interface.ts +0 -39
  364. package/src/shared/mcp/typings/remove-section-result.model.ts +0 -10
  365. package/src/shared/mcp/typings/sampling-types.interface.ts +0 -48
  366. package/src/shared/mcp/typings/skill-types.interface.ts +0 -29
  367. package/src/shared/mcp/typings/tool-call-result.model.ts +0 -18
  368. package/src/shared/mod.ts +0 -1
  369. package/src/shared/platform/functions/get-ipc-path.function.ts +0 -19
  370. package/src/shared/platform/functions/get-tmpdir.function.ts +0 -8
  371. package/src/shared/platform/functions/is-process-alive.function.ts +0 -17
  372. package/src/shared/platform/index.ts +0 -3
  373. package/src/shared/runtime/functions/detect-runtime.ts +0 -14
  374. package/src/shared/runtime/functions/get-args.ts +0 -16
  375. package/src/shared/runtime/index.ts +0 -3
  376. package/src/shared/runtime/typings/runtime.ts +0 -2
  377. package/src/shared/sync/functions/build-import-report.function.ts +0 -40
  378. package/src/shared/sync/functions/parse-export-entry.function.ts +0 -45
  379. package/src/shared/sync/functions/resolve-conflict.function.ts +0 -31
  380. package/src/shared/sync/functions/serialize-export-entry.function.ts +0 -18
  381. package/src/shared/sync/index.ts +0 -9
  382. package/src/shared/sync/typings/conflict-resolution.type.ts +0 -8
  383. package/src/shared/sync/typings/export-entry.interface.ts +0 -13
  384. package/src/shared/sync/typings/export-options.interface.ts +0 -9
  385. package/src/shared/sync/typings/import-options.interface.ts +0 -7
  386. package/src/shared/sync/typings/import-report.interface.ts +0 -15
  387. package/src/shared/version/constants/version.constant.ts +0 -2
  388. package/src/shared/version/index.ts +0 -1
  389. package/src/shared/wasm-codec/functions/decode-add-section-result.function.ts +0 -112
  390. package/src/shared/wasm-codec/functions/decode-compose-output.function.ts +0 -16
  391. package/src/shared/wasm-codec/functions/decode-document-manifest-list.function.ts +0 -70
  392. package/src/shared/wasm-codec/functions/decode-document-manifest.function.ts +0 -87
  393. package/src/shared/wasm-codec/functions/decode-f32.function.ts +0 -16
  394. package/src/shared/wasm-codec/functions/decode-key-value-text.function.ts +0 -15
  395. package/src/shared/wasm-codec/functions/decode-one-recall-result.function.ts +0 -86
  396. package/src/shared/wasm-codec/functions/decode-option-string.function.ts +0 -24
  397. package/src/shared/wasm-codec/functions/decode-recall-document.function.ts +0 -59
  398. package/src/shared/wasm-codec/functions/decode-recall-reference.function.ts +0 -52
  399. package/src/shared/wasm-codec/functions/decode-recall-result.function.ts +0 -267
  400. package/src/shared/wasm-codec/functions/decode-recall-sibling.function.ts +0 -43
  401. package/src/shared/wasm-codec/functions/decode-remove-flag.function.ts +0 -3
  402. package/src/shared/wasm-codec/functions/decode-scored-results.function.ts +0 -194
  403. package/src/shared/wasm-codec/functions/decode-section-match.function.ts +0 -80
  404. package/src/shared/wasm-codec/functions/decode-section-record-list.function.ts +0 -20
  405. package/src/shared/wasm-codec/functions/decode-section-record-trailing.function.ts +0 -75
  406. package/src/shared/wasm-codec/functions/decode-section-record.function.ts +0 -85
  407. package/src/shared/wasm-codec/functions/decode-section-records.function.ts +0 -249
  408. package/src/shared/wasm-codec/functions/decode-section-type.function.ts +0 -30
  409. package/src/shared/wasm-codec/functions/decode-string.function.ts +0 -22
  410. package/src/shared/wasm-codec/functions/decode-u32.function.ts +0 -16
  411. package/src/shared/wasm-codec/functions/decode-u64.function.ts +0 -16
  412. package/src/shared/wasm-codec/functions/decode-wasm-list.function.ts +0 -31
  413. package/src/shared/wasm-codec/functions/encode-add-section-params.function.ts +0 -102
  414. package/src/shared/wasm-codec/functions/encode-group-params.function.ts +0 -28
  415. package/src/shared/wasm-codec/functions/encode-identifier-list.function.ts +0 -17
  416. package/src/shared/wasm-codec/functions/encode-kbid-list.function.ts +0 -17
  417. package/src/shared/wasm-codec/functions/encode-option-string.function.ts +0 -14
  418. package/src/shared/wasm-codec/functions/encode-recall-params.function.ts +0 -68
  419. package/src/shared/wasm-codec/functions/encode-search-params.function.ts +0 -12
  420. package/src/shared/wasm-codec/functions/encode-section-type.function.ts +0 -18
  421. package/src/shared/wasm-codec/functions/encode-string.function.ts +0 -9
  422. package/src/shared/wasm-codec/functions/encode-type-filter-param.function.ts +0 -13
  423. package/src/shared/wasm-codec/functions/encode-u32.function.ts +0 -5
  424. package/src/shared/wasm-codec/functions/encode-update-section-params.function.ts +0 -16
  425. package/src/shared/wasm-codec/index.ts +0 -49
  426. package/src/shared/wasm-codec/typings/add-section-input.model.ts +0 -45
  427. package/src/shared/wasm-codec/typings/add-section-result.model.ts +0 -28
  428. package/src/shared/wasm-codec/typings/document-manifest.model.ts +0 -20
  429. package/src/shared/wasm-codec/typings/document-section.model.ts +0 -12
  430. package/src/shared/wasm-codec/typings/item-decoder.type.ts +0 -10
  431. package/src/shared/wasm-codec/typings/near-duplicate.model.ts +0 -16
  432. package/src/shared/wasm-codec/typings/paged-search-result.model.ts +0 -22
  433. package/src/shared/wasm-codec/typings/section-match.model.ts +0 -31
  434. package/src/shared/wasm-codec/typings/section-record-trailing.model.ts +0 -38
  435. package/src/shared/wasm-codec/typings/section-record.model.ts +0 -66
  436. package/src/shared/wasm-codec/typings/section-type-result.model.ts +0 -12
  437. package/src/shared/worker-client/classes/worker-client.class.ts +0 -466
  438. package/src/shared/worker-client/functions/compute-context-id.function.ts +0 -18
  439. package/src/shared/worker-client/functions/create-worker-client.function.ts +0 -70
  440. package/src/shared/worker-client/functions/discover-daemon.function.ts +0 -47
  441. package/src/shared/worker-client/functions/handle-ipc-data.function.ts +0 -49
  442. package/src/shared/worker-client/functions/resolve-db-path.function.ts +0 -21
  443. package/src/shared/worker-client/functions/send-ipc-request.function.ts +0 -39
  444. package/src/shared/worker-client/functions/spawn-daemon.function.ts +0 -35
  445. package/src/shared/worker-client/functions/wait-for-daemon.function.ts +0 -34
  446. package/src/shared/worker-client/index.ts +0 -44
  447. package/src/shared/worker-client/typings/add-section-result.model.ts +0 -39
  448. package/src/shared/worker-client/typings/content-result.model.ts +0 -12
  449. package/src/shared/worker-client/typings/daemon-info.model.ts +0 -7
  450. package/src/shared/worker-client/typings/export-result.model.ts +0 -14
  451. package/src/shared/worker-client/typings/gc-result.model.ts +0 -18
  452. package/src/shared/worker-client/typings/integrity-check-result.model.ts +0 -43
  453. package/src/shared/worker-client/typings/json-rpc-response.interface.ts +0 -17
  454. package/src/shared/worker-client/typings/migrate-result.model.ts +0 -11
  455. package/src/shared/worker-client/typings/pending-call.interface.ts +0 -7
  456. package/src/shared/worker-client/typings/rebuild-result.model.ts +0 -12
  457. package/src/shared/worker-client/typings/recall-document.model.ts +0 -16
  458. package/src/shared/worker-client/typings/recall-params.model.ts +0 -15
  459. package/src/shared/worker-client/typings/recall-reference.model.ts +0 -32
  460. package/src/shared/worker-client/typings/recall-result.model.ts +0 -98
  461. package/src/shared/worker-client/typings/recall-sibling.model.ts +0 -11
  462. package/src/shared/worker-client/typings/recall-single-result.model.ts +0 -41
  463. package/src/shared/worker-client/typings/remove-section-result.model.ts +0 -7
  464. package/src/shared/worker-client/typings/search-params.model.ts +0 -14
  465. package/src/shared/worker-client/typings/search-result.model.ts +0 -43
  466. package/src/shared/worker-client/typings/section.model.ts +0 -43
  467. package/src/shared/worker-client/typings/status-result.model.ts +0 -14
  468. package/src/shared/worker-client/typings/version-status.model.ts +0 -28
  469. package/src/shared/worker-client/typings/worker-client-error.interface.ts +0 -8
  470. package/src/shared/worker-client/typings/worker-client-options.interface.ts +0 -30
  471. package/src/shared/worker-daemon/classes/ipc-error.class.ts +0 -22
  472. package/src/shared/worker-daemon/classes/worker-daemon.class.ts +0 -1291
  473. package/src/shared/worker-daemon/constants/daemon-defaults.constant.ts +0 -29
  474. package/src/shared/worker-daemon/constants/wasm-method-map.constant.ts +0 -69
  475. package/src/shared/worker-daemon/functions/build-ipc-error-response.function.ts +0 -16
  476. package/src/shared/worker-daemon/functions/check-catalog-version.function.ts +0 -54
  477. package/src/shared/worker-daemon/functions/check-preconditions.function.ts +0 -28
  478. package/src/shared/worker-daemon/functions/create-host-imports.function.ts +0 -328
  479. package/src/shared/worker-daemon/functions/create-ipc-server.function.ts +0 -87
  480. package/src/shared/worker-daemon/functions/detect-stale-pid.function.ts +0 -33
  481. package/src/shared/worker-daemon/functions/dispatch-request.function.ts +0 -190
  482. package/src/shared/worker-daemon/functions/handle-check-version.function.ts +0 -74
  483. package/src/shared/worker-daemon/functions/handle-config-method.function.ts +0 -27
  484. package/src/shared/worker-daemon/functions/handle-read-ops.function.ts +0 -236
  485. package/src/shared/worker-daemon/functions/handle-write-ops.function.ts +0 -257
  486. package/src/shared/worker-daemon/functions/load-wasm-modules.function.ts +0 -95
  487. package/src/shared/worker-daemon/functions/parse-auto-capture-section.function.ts +0 -51
  488. package/src/shared/worker-daemon/functions/parse-catalog-version.function.ts +0 -20
  489. package/src/shared/worker-daemon/functions/parse-embedding-section.function.ts +0 -38
  490. package/src/shared/worker-daemon/functions/parse-worker-toml.function.ts +0 -104
  491. package/src/shared/worker-daemon/functions/read-config.function.ts +0 -83
  492. package/src/shared/worker-daemon/functions/run-startup-integrity-check.function.ts +0 -55
  493. package/src/shared/worker-daemon/functions/run-worker.function.ts +0 -57
  494. package/src/shared/worker-daemon/functions/scan-near-duplicates.function.ts +0 -92
  495. package/src/shared/worker-daemon/functions/start-daemon.function.ts +0 -74
  496. package/src/shared/worker-daemon/functions/wasm-bridge.function.ts +0 -144
  497. package/src/shared/worker-daemon/functions/wasm-memory-helpers.function.ts +0 -41
  498. package/src/shared/worker-daemon/functions/write-lock.function.ts +0 -49
  499. package/src/shared/worker-daemon/index.ts +0 -16
  500. package/src/shared/worker-daemon/typings/allocator-ref.interface.ts +0 -16
  501. package/src/shared/worker-daemon/typings/daemon-config.interface.ts +0 -20
  502. package/src/shared/worker-daemon/typings/fs-adapter.interface.ts +0 -22
  503. package/src/shared/worker-daemon/typings/handler-context.interface.ts +0 -19
  504. package/src/shared/worker-daemon/typings/ipc-handler.interface.ts +0 -39
  505. package/src/shared/worker-daemon/typings/memory-ref.interface.ts +0 -13
  506. package/src/shared/worker-daemon/typings/wasm-fn.type.ts +0 -2
  507. package/src/shared/worker-daemon/typings/wasm-modules.interface.ts +0 -7
  508. package/src/shared/worker-daemon/typings/write-lock.interface.ts +0 -13
  509. package/src/wasm/fs-database/kbdb_fs_database.d.ts +0 -259
  510. package/src/wasm/fs-database/kbdb_fs_database.js +0 -515
  511. package/src/wasm/fs-database/kbdb_fs_database_bg.wasm +0 -0
  512. package/src/wasm/fs-database/kbdb_fs_database_bg.wasm.d.ts +0 -35
  513. package/src/wasm/fs-database/package.json +0 -13
  514. package/src/wasm/kb-worker/kbdb_worker.d.ts +0 -650
  515. package/src/wasm/kb-worker/kbdb_worker.js +0 -1181
  516. package/src/wasm/kb-worker/kbdb_worker_bg.wasm +0 -0
  517. package/src/wasm/kb-worker/kbdb_worker_bg.wasm.d.ts +0 -77
  518. package/src/wasm/kb-worker/package.json +0 -13
  519. package/src/wasm/query-parser/kbdb_query_parser.d.ts +0 -195
  520. package/src/wasm/query-parser/kbdb_query_parser.js +0 -403
  521. package/src/wasm/query-parser/kbdb_query_parser_bg.wasm.d.ts +0 -25
  522. package/src/wasm/query-parser/package.json +0 -13
  523. package/src/worker.ts +0 -42
package/dist/cli.mjs CHANGED
@@ -1,11 +1,20 @@
1
1
  import {
2
2
  computeSha256,
3
+ configureLog,
3
4
  detectRuntime,
4
5
  getArgs,
5
6
  getIpcPath,
7
+ log,
8
+ parseLogLevel,
9
+ parseWorkerToml,
6
10
  resolveBaseDir,
11
+ resolveLogLevel,
7
12
  resolveWorkerScript
8
- } from "./chunk-JG2UCKLI.mjs";
13
+ } from "./chunk-BJXEVALU.mjs";
14
+
15
+ // src/cli.ts
16
+ import { readFileSync as readFileSync4 } from "node:fs";
17
+ import { join as join9 } from "node:path";
9
18
 
10
19
  // src/shared/cli/constants/defaults.constant.ts
11
20
  var DEFAULT_LIMIT = 20;
@@ -41,19 +50,31 @@ function parseArgs(argv) {
41
50
  }
42
51
  return options;
43
52
  case "--version":
44
- case "-v":
45
53
  options.command = "version";
46
54
  return options;
55
+ case "-v":
56
+ case "--verbose": {
57
+ const next = argv[i + 1];
58
+ if (next && !next.startsWith("-")) {
59
+ options.logLevel = parseLogLevel(next);
60
+ i++;
61
+ } else {
62
+ options.logLevel = 2 /* WARNING */;
63
+ }
64
+ break;
65
+ }
66
+ case "-vv":
67
+ case "--verbose-info":
68
+ options.logLevel = 1 /* INFO */;
69
+ break;
70
+ case "-vvv":
71
+ case "--verbose-debug":
72
+ options.logLevel = 0 /* DEBUG */;
73
+ break;
47
74
  case "--init":
48
- console.error(
49
- 'warning: --init is deprecated, use "kbdb db init"'
50
- );
51
75
  options.command = "init";
52
76
  break;
53
77
  case "--migrate":
54
- console.error(
55
- 'warning: --migrate is deprecated, use "kbdb db migrate"'
56
- );
57
78
  options.command = "migrate";
58
79
  break;
59
80
  case "--db":
@@ -62,6 +83,7 @@ function parseArgs(argv) {
62
83
  case "--format":
63
84
  case "-f":
64
85
  options.format = argv[++i] ?? DEFAULT_FORMAT;
86
+ options.formatExplicit = true;
65
87
  break;
66
88
  case "--mode":
67
89
  case "-m":
@@ -119,10 +141,31 @@ function parseArgs(argv) {
119
141
  case "-c":
120
142
  options.content = true;
121
143
  break;
144
+ case "--relaxed":
145
+ options.relaxed = true;
146
+ break;
147
+ case "--from":
148
+ options.from = argv[++i];
149
+ break;
150
+ case "--dry-run":
151
+ options.dryRun = true;
152
+ break;
153
+ case "--export-format":
154
+ options.exportFormat = argv[++i] ?? "git";
155
+ break;
156
+ case "--timeout-ms":
157
+ options.timeoutMs = parseInt(argv[++i] ?? "", 10) || void 0;
158
+ break;
159
+ case "--retry":
160
+ options.retry = parseInt(argv[++i] ?? "", 10) || void 0;
161
+ break;
162
+ case "--non-interactive":
163
+ options.nonInteractive = true;
164
+ break;
122
165
  default:
123
166
  if (!options.command) {
124
167
  options.command = arg;
125
- } else if (!options.args.length && (options.command === "db" || options.command === "skill" || options.command === "agent")) {
168
+ } else if (!options.args.length && (options.command === "db" || options.command === "skill" || options.command === "agent" || options.command === "worker")) {
126
169
  options.command = `${options.command}-${arg}`;
127
170
  } else {
128
171
  options.args.push(arg);
@@ -195,6 +238,7 @@ function formatMcp(paged) {
195
238
 
196
239
  // src/shared/cli/functions/run-search.function.ts
197
240
  async function runSearch(client, options) {
241
+ log("searching: " + options.args.join(" "), 0 /* DEBUG */);
198
242
  const query = options.args.join(" ").trim();
199
243
  if (!query) {
200
244
  return {
@@ -211,8 +255,13 @@ async function runSearch(client, options) {
211
255
  mode: options.mode,
212
256
  limit: options.limit,
213
257
  offset: options.offset,
214
- algo: options.algo
258
+ algo: options.algo,
259
+ relaxed: options.relaxed
215
260
  });
261
+ log(
262
+ "search returned " + results.total.toString() + " results",
263
+ 0 /* DEBUG */
264
+ );
216
265
  return {
217
266
  items: results.items.map((r) => ({
218
267
  kbid: r.kbid,
@@ -231,13 +280,41 @@ async function runSearch(client, options) {
231
280
  offset: results.offset,
232
281
  limit: results.limit,
233
282
  has_more: results.has_more,
234
- relaxed: results.relaxed ?? false
283
+ relaxed: results.relaxed ?? false,
284
+ elapsed_ms: results.elapsed_ms,
285
+ search_mode: results.search_mode,
286
+ retrieval_method: results.retrieval_method
235
287
  };
236
288
  }
237
289
 
290
+ // src/shared/cli/functions/resolve-kbid-prefix.function.ts
291
+ var SECTION_TYPES = ["text", "code", "image"];
292
+ async function resolveKbidPrefix(prefix, client) {
293
+ if (prefix.length >= 26) return prefix;
294
+ const seen = /* @__PURE__ */ new Set();
295
+ for (const type of SECTION_TYPES) {
296
+ const records = await client.listByType(type);
297
+ for (const r of records) {
298
+ if (r.kbid.startsWith(prefix)) seen.add(r.kbid);
299
+ }
300
+ }
301
+ if (seen.size === 0) {
302
+ const msg = `no section matches prefix "${prefix}"`;
303
+ log(msg, 3 /* ERROR */);
304
+ throw new Error(msg);
305
+ }
306
+ if (seen.size > 1) {
307
+ const msg = `ambiguous prefix "${prefix}": ${seen.size.toString()} matches`;
308
+ log(msg, 3 /* ERROR */);
309
+ throw new Error(msg);
310
+ }
311
+ return [...seen][0];
312
+ }
313
+
238
314
  // src/shared/cli/functions/run-recall.function.ts
239
315
  var MAX_RECALL_DEPTH = 3;
240
316
  async function runRecall(client, options) {
317
+ log("running recall", 0 /* DEBUG */);
241
318
  if (options.args.length === 0) {
242
319
  return { error: "no kbid provided" };
243
320
  }
@@ -245,14 +322,18 @@ async function runRecall(client, options) {
245
322
  MAX_RECALL_DEPTH,
246
323
  Math.max(0, options.depth ?? 0)
247
324
  );
248
- if (options.args.length === 1) {
249
- return client.recall({ kbid: options.args[0], depth });
325
+ const resolved = await Promise.all(
326
+ options.args.map((a) => resolveKbidPrefix(a, client))
327
+ );
328
+ if (resolved.length === 1) {
329
+ return client.recall({ kbid: resolved[0], depth });
250
330
  }
251
- return client.recall({ kbids: options.args, depth });
331
+ return client.recall({ kbids: resolved, depth });
252
332
  }
253
333
 
254
334
  // src/shared/cli/functions/run-export.function.ts
255
335
  async function runExport(client, options) {
336
+ log("running export", 0 /* DEBUG */);
256
337
  const path = options.args[0];
257
338
  return client.export({ path });
258
339
  }
@@ -261,6 +342,10 @@ async function runExport(client, options) {
261
342
  import { readFileSync, readdirSync, statSync } from "node:fs";
262
343
  import { basename, extname, join } from "node:path";
263
344
  async function runLearn(client, options, io) {
345
+ log(
346
+ "learning " + options.args.length.toString() + " targets",
347
+ 0 /* DEBUG */
348
+ );
264
349
  const results = [];
265
350
  let stdinConsumed = false;
266
351
  const readStdin = io?.readStdin ?? readProcessStdin;
@@ -299,6 +384,10 @@ async function runLearn(client, options, io) {
299
384
  );
300
385
  }
301
386
  }
387
+ log(
388
+ "learned " + results.length.toString() + " sections",
389
+ 0 /* DEBUG */
390
+ );
302
391
  return results;
303
392
  }
304
393
  function mapAddSectionResult(result, path, size) {
@@ -362,8 +451,10 @@ function isSupportedFile(path) {
362
451
 
363
452
  // src/shared/cli/functions/run-unlearn.function.ts
364
453
  async function runUnlearn(client, options) {
454
+ log("running unlearn", 0 /* DEBUG */);
365
455
  const results = [];
366
- for (const kbid of options.args) {
456
+ for (const arg of options.args) {
457
+ const kbid = await resolveKbidPrefix(arg, client);
367
458
  const result = await client.removeSection(kbid);
368
459
  results.push({ kbid, removed: result.removed });
369
460
  }
@@ -372,7 +463,11 @@ async function runUnlearn(client, options) {
372
463
 
373
464
  // src/shared/cli/functions/run-content.function.ts
374
465
  async function runContent(client, options) {
375
- return client.content(options.args);
466
+ log("running content", 0 /* DEBUG */);
467
+ const resolved = await Promise.all(
468
+ options.args.map((a) => resolveKbidPrefix(a, client))
469
+ );
470
+ return client.content(resolved);
376
471
  }
377
472
 
378
473
  // src/shared/cli/functions/run-check.function.ts
@@ -386,6 +481,7 @@ function parseDivergentContent(encoded) {
386
481
  }).filter((entry) => entry.kbids.length > 0);
387
482
  }
388
483
  async function runCheck(client, _options) {
484
+ log("running check", 0 /* DEBUG */);
389
485
  const raw = await client.integrityCheck();
390
486
  return {
391
487
  ok: raw.ok,
@@ -400,21 +496,34 @@ async function runCheck(client, _options) {
400
496
 
401
497
  // src/shared/cli/functions/run-gc.function.ts
402
498
  async function runGc(client, _options) {
499
+ log("running gc", 0 /* DEBUG */);
403
500
  return client.gc();
404
501
  }
405
502
 
406
503
  // src/shared/cli/functions/run-rebuild.function.ts
407
504
  async function runRebuild(client, _options) {
505
+ log("running rebuild", 0 /* DEBUG */);
408
506
  return client.rebuildIndexes();
409
507
  }
410
508
 
411
509
  // src/shared/cli/functions/find-db.function.ts
412
510
  import { existsSync } from "node:fs";
413
- import { join as join2, resolve } from "node:path";
511
+ import { dirname, join as join2, resolve } from "node:path";
414
512
  function findDb(dbPath) {
415
- const base = dbPath ? resolve(dbPath) : process.cwd();
416
- const kbdbDir = join2(base, ".kbdb");
417
- return existsSync(kbdbDir) ? kbdbDir : null;
513
+ if (dbPath) {
514
+ const target = join2(resolve(dbPath), ".kbdb");
515
+ return existsSync(target) ? target : null;
516
+ }
517
+ let current = process.cwd();
518
+ let parent = dirname(current);
519
+ while (parent !== current) {
520
+ const candidate2 = join2(current, ".kbdb");
521
+ if (existsSync(candidate2)) return candidate2;
522
+ current = parent;
523
+ parent = dirname(current);
524
+ }
525
+ const candidate = join2(current, ".kbdb");
526
+ return existsSync(candidate) ? candidate : null;
418
527
  }
419
528
 
420
529
  // src/shared/cli/functions/run-init.function.ts
@@ -549,6 +658,7 @@ function createScaffold(dbDir) {
549
658
  writeFileSync2(join4(dbDir, ".gitignore"), GITIGNORE);
550
659
  }
551
660
  function runInit(options) {
661
+ log("running init", 0 /* DEBUG */);
552
662
  const basePath = options.dbPath ? resolve2(options.dbPath) : process.cwd();
553
663
  const dbDir = join4(basePath, ".kbdb");
554
664
  try {
@@ -600,11 +710,13 @@ function askReadline(question) {
600
710
 
601
711
  // src/shared/cli/functions/run-status.function.ts
602
712
  async function runStatus(client, _options) {
713
+ log("running status", 0 /* DEBUG */);
603
714
  return client.dbStatus();
604
715
  }
605
716
 
606
717
  // src/shared/cli/functions/run-db-init.function.ts
607
718
  function runDbInit(options, runInitFn) {
719
+ log("running db-init", 0 /* DEBUG */);
608
720
  const result = runInitFn(options);
609
721
  if (result.ok) {
610
722
  return {
@@ -624,6 +736,7 @@ function runDbInit(options, runInitFn) {
624
736
 
625
737
  // src/shared/cli/functions/run-db-migrate.function.ts
626
738
  async function runDbMigrate(client, options) {
739
+ log("running db-migrate", 0 /* DEBUG */);
627
740
  const dbPath = options.dbPath ?? process.cwd();
628
741
  return client.migrateDatabase(dbPath);
629
742
  }
@@ -651,6 +764,7 @@ function serializeSkillContent(skill) {
651
764
 
652
765
  // src/shared/cli/functions/run-skill-learn.function.ts
653
766
  async function runSkillLearn(client, options) {
767
+ log("running skill-learn", 0 /* DEBUG */);
654
768
  const name = options.name;
655
769
  if (!name) {
656
770
  return { error: "--name is required", exitCode: 1 };
@@ -681,6 +795,7 @@ async function runSkillLearn(client, options) {
681
795
 
682
796
  // src/shared/cli/functions/run-skill-list.function.ts
683
797
  async function runSkillList(client, _options) {
798
+ log("running skill-list", 0 /* DEBUG */);
684
799
  const records = await client.listByType("skill");
685
800
  const items = records.map((r) => {
686
801
  let argumentCount = 0;
@@ -708,9 +823,11 @@ async function runSkillList(client, _options) {
708
823
  function parseSkillContent(json) {
709
824
  const raw = JSON.parse(json);
710
825
  if (typeof raw["name"] !== "string" || !raw["name"]) {
826
+ log("skill name is required", 3 /* ERROR */);
711
827
  throw new Error("skill name is required");
712
828
  }
713
829
  if (typeof raw["body"] !== "string") {
830
+ log("skill body is required", 3 /* ERROR */);
714
831
  throw new Error("skill body is required");
715
832
  }
716
833
  return {
@@ -723,6 +840,7 @@ function parseSkillContent(json) {
723
840
 
724
841
  // src/shared/cli/functions/run-skill-get.function.ts
725
842
  async function runSkillGet(client, options) {
843
+ log("running skill-get", 0 /* DEBUG */);
726
844
  const identifier = options.args[0] ?? options.name;
727
845
  if (!identifier) {
728
846
  return {
@@ -759,6 +877,7 @@ async function runSkillGet(client, options) {
759
877
 
760
878
  // src/shared/cli/functions/run-skill-delete.function.ts
761
879
  async function runSkillDelete(client, options) {
880
+ log("running skill-delete", 0 /* DEBUG */);
762
881
  const kbid = options.args[0];
763
882
  if (!kbid) {
764
883
  return { error: "kbid is required", exitCode: 1 };
@@ -776,6 +895,7 @@ async function runSkillDelete(client, options) {
776
895
 
777
896
  // src/shared/cli/functions/run-agent-create.function.ts
778
897
  async function runAgentCreate(client, options) {
898
+ log("running agent-create", 0 /* DEBUG */);
779
899
  const name = options.name;
780
900
  if (!name) {
781
901
  return { error: "--name is required", exitCode: 1 };
@@ -821,6 +941,7 @@ async function runAgentCreate(client, options) {
821
941
 
822
942
  // src/shared/cli/functions/run-agent-list.function.ts
823
943
  async function runAgentList(client, _options) {
944
+ log("running agent-list", 0 /* DEBUG */);
824
945
  const docs = await client.listDocumentsByType("agent");
825
946
  const items = docs.map((d) => ({
826
947
  docid: d.docid,
@@ -877,6 +998,7 @@ async function resolveSkills(client, skillRefs) {
877
998
  });
878
999
  }
879
1000
  async function runAgentGet(client, options) {
1001
+ log("running agent-get", 0 /* DEBUG */);
880
1002
  const docid = options.args[0];
881
1003
  if (!docid) {
882
1004
  return { error: "docid is required", exitCode: 1 };
@@ -898,6 +1020,7 @@ async function runAgentGet(client, options) {
898
1020
 
899
1021
  // src/shared/cli/functions/run-agent-delete.function.ts
900
1022
  async function runAgentDelete(client, options) {
1023
+ log("running agent-delete", 0 /* DEBUG */);
901
1024
  const docid = options.args[0];
902
1025
  if (!docid) {
903
1026
  return { error: "docid is required", exitCode: 1 };
@@ -909,8 +1032,23 @@ async function runAgentDelete(client, options) {
909
1032
  };
910
1033
  }
911
1034
 
1035
+ // src/shared/cli/functions/run-import.function.ts
1036
+ async function runImport(client, options) {
1037
+ const from = options.from;
1038
+ if (!from) {
1039
+ const msg = "import requires --from <path>";
1040
+ log(msg, 3 /* ERROR */);
1041
+ throw new Error(msg);
1042
+ }
1043
+ return client.import({
1044
+ from,
1045
+ dryRun: options.dryRun === true
1046
+ });
1047
+ }
1048
+
912
1049
  // src/shared/cli/functions/dispatch-command.function.ts
913
1050
  async function dispatchCommand(client, options, io) {
1051
+ log("dispatching command: " + options.command, 0 /* DEBUG */);
914
1052
  switch (options.command) {
915
1053
  case "learn":
916
1054
  return handleLearn(client, options, io);
@@ -932,6 +1070,8 @@ async function dispatchCommand(client, options, io) {
932
1070
  return handleStatus(client, options);
933
1071
  case "export":
934
1072
  return handleExport(client, options);
1073
+ case "import":
1074
+ return handleImport(client, options);
935
1075
  case "db-init":
936
1076
  return handleDbInit(options);
937
1077
  case "db-migrate":
@@ -969,6 +1109,7 @@ async function dispatchCommand(client, options, io) {
969
1109
  return result;
970
1110
  }
971
1111
  default:
1112
+ log("unknown command: " + options.command, 2 /* WARNING */);
972
1113
  return {
973
1114
  error: `unknown command: ${options.command}`,
974
1115
  exitCode: 1
@@ -1054,6 +1195,20 @@ async function handleExport(client, options) {
1054
1195
  };
1055
1196
  }
1056
1197
  }
1198
+ async function handleImport(client, options) {
1199
+ try {
1200
+ const result = await runImport(client, options);
1201
+ return {
1202
+ output: JSON.stringify(result, null, 2),
1203
+ exitCode: 0
1204
+ };
1205
+ } catch (err) {
1206
+ return {
1207
+ error: `import failed: ${errorToMessage(err)}`,
1208
+ exitCode: 1
1209
+ };
1210
+ }
1211
+ }
1057
1212
  async function handleContent(client, options) {
1058
1213
  try {
1059
1214
  const result = await runContent(client, options);
@@ -1154,7 +1309,7 @@ async function hydrateSearchPreviews(client, paged) {
1154
1309
  }
1155
1310
 
1156
1311
  // src/shared/version/constants/version.constant.ts
1157
- var VERSION = "0.2.2";
1312
+ var VERSION = "0.4.1";
1158
1313
 
1159
1314
  // src/shared/cli/functions/generate-help.function.ts
1160
1315
  var KNOWN_COMMANDS = /* @__PURE__ */ new Set([
@@ -1171,7 +1326,8 @@ var KNOWN_COMMANDS = /* @__PURE__ */ new Set([
1171
1326
  "mcp",
1172
1327
  "db",
1173
1328
  "skill",
1174
- "agent"
1329
+ "agent",
1330
+ "worker"
1175
1331
  ]);
1176
1332
  var GROUP_SUBCOMMANDS = {
1177
1333
  db: [
@@ -1189,6 +1345,10 @@ var GROUP_SUBCOMMANDS = {
1189
1345
  ["list", "List all agents"],
1190
1346
  ["get", "Retrieve an agent by docid"],
1191
1347
  ["delete", "Remove an agent"]
1348
+ ],
1349
+ worker: [
1350
+ ["stop", "Stop the worker daemon"],
1351
+ ["restart", "Restart the worker daemon"]
1192
1352
  ]
1193
1353
  };
1194
1354
  function isKnownCommand(cmd) {
@@ -1257,6 +1417,10 @@ Agents:
1257
1417
  agent get Retrieve an agent by docid
1258
1418
  agent delete Remove an agent
1259
1419
 
1420
+ Worker:
1421
+ worker stop Stop the worker daemon
1422
+ worker restart Restart the worker daemon
1423
+
1260
1424
  Server:
1261
1425
  mcp Start MCP server mode (stdio)
1262
1426
 
@@ -1302,7 +1466,8 @@ Run "kbdb ${group} <subcommand> --help" for details.
1302
1466
  var GROUP_DESCRIPTIONS = {
1303
1467
  db: "Database management",
1304
1468
  skill: "Skill management",
1305
- agent: "Agent management"
1469
+ agent: "Agent management",
1470
+ worker: "Worker daemon management"
1306
1471
  };
1307
1472
  var LEAF_HELP = {
1308
1473
  learn: `kbdb learn - Import content from files or stdin
@@ -1488,11 +1653,11 @@ Options:
1488
1653
  --db <path> Path to .kbdb directory
1489
1654
 
1490
1655
  Environment:
1491
- KBDB_DIR Fallback database path
1656
+ KBDB_DB_DIR Fallback database path
1492
1657
 
1493
1658
  Examples:
1494
1659
  kbdb mcp --db /path/to/project
1495
- KBDB_DIR=/path/to/project kbdb mcp
1660
+ KBDB_DB_DIR=/path/to/project kbdb mcp
1496
1661
  `
1497
1662
  };
1498
1663
  var SUBCOMMAND_HELP = {
@@ -1655,6 +1820,28 @@ Output:
1655
1820
 
1656
1821
  Examples:
1657
1822
  kbdb agent delete agent-code-reviewer
1823
+ `,
1824
+ "worker-stop": `kbdb worker stop - Stop the worker daemon
1825
+
1826
+ Usage: kbdb worker stop [options]
1827
+
1828
+ Options:
1829
+ --db <path> Path to .kbdb directory
1830
+
1831
+ Examples:
1832
+ kbdb worker stop
1833
+ kbdb worker stop --db /path/to/project
1834
+ `,
1835
+ "worker-restart": `kbdb worker restart - Restart the worker daemon
1836
+
1837
+ Usage: kbdb worker restart [options]
1838
+
1839
+ Options:
1840
+ --db <path> Path to .kbdb directory
1841
+
1842
+ Examples:
1843
+ kbdb worker restart
1844
+ kbdb worker restart --db /path/to/project
1658
1845
  `
1659
1846
  };
1660
1847
  function generateSubcommandHelp(command, subcommand) {
@@ -1666,211 +1853,72 @@ function generateSubcommandHelp(command, subcommand) {
1666
1853
  return generateCommandHelp(command);
1667
1854
  }
1668
1855
 
1669
- // src/shared/cli/functions/run-cli.function.ts
1670
- async function runCli(argv, deps2) {
1671
- const options = parseArgs(argv);
1672
- if (options.command === "help" || !options.command) {
1673
- const helpCommand = options.args[0];
1674
- const helpSubcommand = options.args[1];
1675
- const helpText = generateHelp(helpCommand, helpSubcommand);
1676
- if (helpCommand && !isKnownCommand(helpCommand)) {
1677
- return { output: helpText, exitCode: 1 };
1678
- }
1679
- return { output: helpText, exitCode: 0 };
1680
- }
1681
- if (options.command === "version") {
1682
- return { output: VERSION, exitCode: 0 };
1683
- }
1684
- if (options.command === "init" || options.command === "db-init") {
1685
- return handleInit(options, deps2);
1686
- }
1687
- if (options.command === "mcp") {
1688
- return handleMcp(options, deps2);
1689
- }
1690
- if (options.command === "migrate" || options.command === "db-migrate") {
1691
- return handleMigrate(options, deps2);
1692
- }
1693
- return handleDataCommand(options, deps2);
1694
- }
1695
- function handleInit(options, deps2) {
1696
- const result = deps2.runInit(options);
1697
- if (result.ok) {
1698
- return {
1699
- output: result.targetPath,
1700
- exitCode: 0
1701
- };
1702
- }
1703
- return {
1704
- error: `error: ${result.errorMessage ?? "init failed"}`,
1705
- exitCode: 1
1706
- };
1707
- }
1708
- async function handleMcp(options, deps2) {
1709
- const rawDbPath = options.dbPath ?? process.env["KBDB_DIR"];
1710
- if (!rawDbPath) {
1711
- return {
1712
- error: "error: --db or KBDB_DIR required in MCP mode",
1713
- exitCode: 1
1714
- };
1715
- }
1716
- const dbDir = deps2.findDb(rawDbPath);
1717
- if (!dbDir) {
1718
- return {
1719
- error: `error: no .kbdb database found at ${rawDbPath}`,
1720
- exitCode: 1
1721
- };
1722
- }
1723
- let client;
1724
- try {
1725
- client = await deps2.createWorkerClient({
1726
- contextPath: dbDir
1727
- });
1728
- } catch (err) {
1729
- return {
1730
- error: `error: ${errorToMessage(err)}`,
1731
- exitCode: 1
1732
- };
1733
- }
1856
+ // src/shared/worker-client/classes/worker-client.class.ts
1857
+ import { connect } from "node:net";
1858
+
1859
+ // src/shared/worker-client/functions/discover-daemon.function.ts
1860
+ import { existsSync as existsSync4, readFileSync as readFileSync2, unlinkSync } from "node:fs";
1861
+ import { join as join5 } from "node:path";
1862
+ import { tmpdir } from "node:os";
1863
+
1864
+ // src/shared/platform/functions/is-process-alive.function.ts
1865
+ function isProcessAlive(pid) {
1734
1866
  try {
1735
- const gateResult = await versionGate(client, dbDir);
1736
- if (gateResult) return gateResult;
1737
- if (deps2.startMcpServer) {
1738
- await deps2.startMcpServer(dbDir);
1739
- }
1740
- return { exitCode: 0 };
1741
- } catch (err) {
1742
- return {
1743
- error: `error: mcp failed: ${errorToMessage(err)}`,
1744
- exitCode: 1
1745
- };
1746
- } finally {
1747
- client.disconnect();
1867
+ process.kill(pid, 0);
1868
+ return true;
1869
+ } catch {
1870
+ return false;
1748
1871
  }
1749
1872
  }
1750
- async function handleMigrate(options, deps2) {
1751
- const dbDir = deps2.findDb(options.dbPath);
1752
- if (!dbDir) {
1753
- const basePath = options.dbPath ?? process.cwd();
1754
- return {
1755
- error: `error: no .kbdb database found at ${basePath}`,
1756
- exitCode: 1
1757
- };
1758
- }
1759
- let client;
1760
- try {
1761
- client = await deps2.createWorkerClient({
1762
- contextPath: dbDir
1763
- });
1764
- } catch (err) {
1765
- return {
1766
- error: `error: ${errorToMessage(err)}`,
1767
- exitCode: 1
1768
- };
1769
- }
1770
- try {
1771
- const versionStatus = await client.checkVersion(dbDir);
1772
- if (versionStatus.status === "too_new") {
1773
- return {
1774
- error: `error: database version ${versionStatus.currentVersion.toString()} is newer than kbdb version ${versionStatus.requiredVersion.toString()} -- upgrade kbdb`,
1775
- exitCode: 1
1776
- };
1777
- }
1778
- if (versionStatus.status === "needs_migration") {
1779
- const migrateResult = await client.migrateDatabase(dbDir);
1780
- return {
1781
- output: JSON.stringify(migrateResult, null, 2),
1782
- exitCode: 0
1783
- };
1784
- }
1785
- return { output: "already up to date", exitCode: 0 };
1786
- } catch (err) {
1787
- return {
1788
- error: `error: migrate failed: ${errorToMessage(err)}`,
1789
- exitCode: 1
1790
- };
1791
- } finally {
1792
- client.disconnect();
1873
+
1874
+ // src/shared/worker-client/functions/discover-daemon.function.ts
1875
+ function discoverDaemon(contextId) {
1876
+ log("discovering daemon for context: " + contextId, 0 /* DEBUG */);
1877
+ const pidPath = join5(tmpdir(), `kbdb-${contextId}.pid`);
1878
+ if (!existsSync4(pidPath)) {
1879
+ log(
1880
+ "no daemon PID file found for context: " + contextId,
1881
+ 0 /* DEBUG */
1882
+ );
1883
+ return null;
1793
1884
  }
1794
- }
1795
- async function handleDataCommand(options, deps2) {
1796
- let dbDir = deps2.findDb(options.dbPath);
1797
- if (!dbDir) {
1798
- const basePath = options.dbPath ?? process.cwd();
1799
- if (!deps2.isStdinTty()) {
1800
- return {
1801
- error: `error: no .kbdb database found at ${basePath} -- run \`kbdb --init\` to create one`,
1802
- exitCode: 1
1803
- };
1804
- }
1805
- const answer = await deps2.promptUser(
1806
- `No .kbdb database found. Create one in ${basePath}? [y/N] `
1885
+ const pidStr = readFileSync2(pidPath, "utf-8").trim();
1886
+ const pid = parseInt(pidStr, 10);
1887
+ if (isNaN(pid) || !isProcessAlive(pid)) {
1888
+ log(
1889
+ "daemon process not alive for context: " + contextId,
1890
+ 0 /* DEBUG */
1807
1891
  );
1808
- if (answer.toLowerCase() !== "y") {
1809
- return {
1810
- error: "aborted: no database created",
1811
- exitCode: 1
1812
- };
1813
- }
1814
- const initResult = deps2.runInit(options);
1815
- if (!initResult.ok) {
1816
- return {
1817
- error: `error: ${initResult.errorMessage ?? "init failed"}`,
1818
- exitCode: 1
1819
- };
1892
+ try {
1893
+ unlinkSync(pidPath);
1894
+ } catch {
1820
1895
  }
1821
- dbDir = initResult.targetPath;
1822
- }
1823
- let client;
1824
- try {
1825
- client = await deps2.createWorkerClient({
1826
- contextPath: dbDir
1827
- });
1828
- } catch (err) {
1829
- return {
1830
- error: `error: ${errorToMessage(err)}`,
1831
- exitCode: 1
1832
- };
1896
+ return null;
1833
1897
  }
1898
+ log("daemon found: pid=" + pid.toString(), 0 /* DEBUG */);
1899
+ const socketPath = join5(tmpdir(), `kbdb-${contextId}.sock`);
1900
+ const crashPath = join5(tmpdir(), `kbdb-${contextId}.crash`);
1834
1901
  try {
1835
- const gateResult = await versionGate(client, dbDir);
1836
- if (gateResult) return gateResult;
1837
- return await dispatchCommand(client, options);
1838
- } finally {
1839
- client.disconnect();
1840
- }
1841
- }
1842
- async function versionGate(client, dbDir) {
1843
- const versionStatus = await client.checkVersion(dbDir);
1844
- if (versionStatus.status === "needs_migration") {
1845
- return {
1846
- error: "error: database needs migration -- run `kbdb --migrate`",
1847
- exitCode: 1
1848
- };
1849
- }
1850
- if (versionStatus.status === "too_new") {
1851
- return {
1852
- error: `error: database version ${versionStatus.currentVersion.toString()} is newer than kbdb version ${versionStatus.requiredVersion.toString()} -- upgrade kbdb`,
1853
- exitCode: 1
1854
- };
1902
+ unlinkSync(crashPath);
1903
+ } catch {
1855
1904
  }
1856
- return null;
1905
+ return { pid, socketPath };
1857
1906
  }
1858
1907
 
1859
- // src/shared/cli/constants/help-text.constant.ts
1860
- var HELP_TEXT = generateHelp();
1861
-
1862
1908
  // src/shared/worker-client/classes/worker-client.class.ts
1863
- import { connect } from "node:net";
1864
1909
  var WorkerClient = class {
1865
1910
  /**
1866
1911
  * @param socketPath - absolute path to the daemon's IPC socket
1867
1912
  * (or Windows named pipe path)
1868
1913
  * @param contextId - 16-character context identifier sent as
1869
1914
  * `ctx` in every JSON-RPC request
1915
+ * @param requestTimeoutMs - per-request timeout in ms
1916
+ * (0 or undefined disables the timeout)
1870
1917
  */
1871
- constructor(socketPath, contextId) {
1918
+ constructor(socketPath, contextId, requestTimeoutMs) {
1872
1919
  this.socketPath = socketPath;
1873
1920
  this.contextId = contextId;
1921
+ this.requestTimeoutMs = requestTimeoutMs;
1874
1922
  }
1875
1923
  /** Underlying socket; `null` when not connected. */
1876
1924
  socket = null;
@@ -1880,30 +1928,121 @@ var WorkerClient = class {
1880
1928
  pending = /* @__PURE__ */ new Map();
1881
1929
  /** Partial line buffer for split TCP/IPC frames. */
1882
1930
  buffer = "";
1931
+ /** Whether the underlying socket is connected. */
1932
+ get isConnected() {
1933
+ return this.socket !== null;
1934
+ }
1883
1935
  /**
1884
1936
  * Establishes the IPC connection to the worker daemon.
1885
1937
  *
1938
+ * Retries up to 5 times with exponential backoff on
1939
+ * transient errors (`ENOENT`, `ECONNREFUSED`).
1940
+ *
1886
1941
  * @throws {Error} if the connection cannot be established
1887
1942
  */
1888
1943
  async connect() {
1944
+ log("connecting to " + this.socketPath, 0 /* DEBUG */);
1945
+ const maxRetries = 5;
1946
+ let delay = 50;
1947
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
1948
+ try {
1949
+ await this.tryConnect();
1950
+ log("connected", 0 /* DEBUG */);
1951
+ return;
1952
+ } catch (err) {
1953
+ const code = err.code;
1954
+ const retriable = code === "ENOENT" || code === "ECONNREFUSED";
1955
+ if (!retriable || attempt === maxRetries) {
1956
+ throw err;
1957
+ }
1958
+ log(
1959
+ "connect retry: attempt=" + attempt.toString() + " code=" + code + " delay=" + delay.toString() + "ms",
1960
+ 0 /* DEBUG */
1961
+ );
1962
+ await new Promise((r) => setTimeout(r, delay));
1963
+ delay = Math.min(delay * 2, 1e3);
1964
+ }
1965
+ }
1966
+ }
1967
+ /** Destroys the IPC socket and clears the connection state. */
1968
+ disconnect() {
1969
+ log("disconnecting client", 0 /* DEBUG */);
1970
+ if (this.socket) {
1971
+ this.socket.destroy();
1972
+ this.socket = null;
1973
+ }
1974
+ }
1975
+ /**
1976
+ * Kills the daemon process and disconnects the client.
1977
+ *
1978
+ * Discovers the daemon via PID file and sends `SIGTERM`.
1979
+ * Always disconnects the socket regardless of kill outcome.
1980
+ */
1981
+ killDaemon() {
1982
+ const info = discoverDaemon(this.contextId);
1983
+ log(
1984
+ "killing daemon: pid=" + (info ? info.pid.toString() : "unknown"),
1985
+ 0 /* DEBUG */
1986
+ );
1987
+ if (info) {
1988
+ try {
1989
+ process.kill(info.pid, "SIGTERM");
1990
+ } catch {
1991
+ }
1992
+ }
1993
+ this.disconnect();
1994
+ }
1995
+ /**
1996
+ * Single connection attempt with keepalive and
1997
+ * post-connect failure handlers.
1998
+ */
1999
+ async tryConnect() {
1889
2000
  return new Promise((resolve4, reject) => {
1890
- this.socket = connect(this.socketPath, () => {
2001
+ const sock = connect(this.socketPath, () => {
2002
+ sock.removeListener("error", reject);
2003
+ sock.setKeepAlive(true, 3e4);
2004
+ sock.on("error", (err) => {
2005
+ log(
2006
+ "socket error: code=" + (err.code ?? err.message),
2007
+ 0 /* DEBUG */
2008
+ );
2009
+ this.handleSocketFailure(err);
2010
+ });
2011
+ sock.on("close", () => {
2012
+ log("socket closed", 0 /* DEBUG */);
2013
+ if (this.pending.size > 0) {
2014
+ this.handleSocketFailure(
2015
+ new Error("connection closed")
2016
+ );
2017
+ }
2018
+ this.socket = null;
2019
+ });
2020
+ this.socket = sock;
1891
2021
  resolve4();
1892
2022
  });
1893
- this.socket.on("error", (err) => {
1894
- reject(err);
1895
- });
1896
- this.socket.on("data", (chunk) => {
2023
+ sock.on("error", reject);
2024
+ sock.on("data", (chunk) => {
1897
2025
  this.handleData(chunk.toString());
1898
2026
  });
1899
2027
  });
1900
2028
  }
1901
- /** Destroys the IPC socket and clears the connection state. */
1902
- disconnect() {
1903
- if (this.socket) {
1904
- this.socket.destroy();
1905
- this.socket = null;
2029
+ /**
2030
+ * Rejects all pending calls and marks the client as
2031
+ * disconnected.
2032
+ */
2033
+ handleSocketFailure(err) {
2034
+ log(
2035
+ "socket failure: pending=" + this.pending.size.toString() + " err=" + err.message,
2036
+ 0 /* DEBUG */
2037
+ );
2038
+ const sock = this.socket;
2039
+ this.socket = null;
2040
+ for (const [id, call] of this.pending) {
2041
+ this.pending.delete(id);
2042
+ if (call.timer) clearTimeout(call.timer);
2043
+ call.reject(err);
1906
2044
  }
2045
+ if (sock) sock.destroy();
1907
2046
  }
1908
2047
  /**
1909
2048
  * Searches the knowledge base.
@@ -1912,7 +2051,10 @@ var WorkerClient = class {
1912
2051
  * @returns paginated search results with metadata
1913
2052
  */
1914
2053
  async search(params) {
1915
- return this.call("search", params);
2054
+ return this.call("search", {
2055
+ ...params,
2056
+ algo: params.algo
2057
+ });
1916
2058
  }
1917
2059
  /**
1918
2060
  * Retrieves full content and context for one or more sections by
@@ -2163,7 +2305,20 @@ var WorkerClient = class {
2163
2305
  */
2164
2306
  async export(params) {
2165
2307
  return this.call("export", {
2166
- targetPath: params?.path || void 0
2308
+ targetPath: params?.path || void 0,
2309
+ format: params?.format
2310
+ });
2311
+ }
2312
+ /**
2313
+ * Imports an exported database from the given path.
2314
+ *
2315
+ * @param params - source path and dry-run flag
2316
+ * @returns import report with counts and timing
2317
+ */
2318
+ async import(params) {
2319
+ return this.call("importDb", {
2320
+ sourcePath: params.from,
2321
+ dryRun: params.dryRun
2167
2322
  });
2168
2323
  }
2169
2324
  /**
@@ -2180,14 +2335,35 @@ var WorkerClient = class {
2180
2335
  throw new Error("not connected");
2181
2336
  }
2182
2337
  const id = this.nextId++;
2338
+ log(
2339
+ "call: method=" + method + " id=" + id.toString(),
2340
+ 0 /* DEBUG */
2341
+ );
2183
2342
  const request = {
2184
2343
  jsonrpc: "2.0",
2185
2344
  id,
2186
2345
  method,
2187
2346
  params: { ctx: this.contextId, ...params }
2188
2347
  };
2348
+ const timeoutMs = this.requestTimeoutMs;
2189
2349
  return new Promise((resolve4, reject) => {
2190
- this.pending.set(id, { resolve: resolve4, reject });
2350
+ const call = { resolve: resolve4, reject };
2351
+ if (timeoutMs) {
2352
+ call.timer = setTimeout(() => {
2353
+ if (!this.pending.has(id)) return;
2354
+ this.pending.delete(id);
2355
+ log(
2356
+ "request timeout after " + String(timeoutMs) + "ms",
2357
+ 2 /* WARNING */
2358
+ );
2359
+ const err = new Error(
2360
+ `request timeout after ${String(timeoutMs)}ms`
2361
+ );
2362
+ err.code = "REQUEST_TIMEOUT";
2363
+ reject(err);
2364
+ }, timeoutMs);
2365
+ }
2366
+ this.pending.set(id, call);
2191
2367
  socket.write(JSON.stringify(request) + "\n");
2192
2368
  });
2193
2369
  }
@@ -2208,15 +2384,33 @@ var WorkerClient = class {
2208
2384
  const pending = this.pending.get(response.id);
2209
2385
  if (pending) {
2210
2386
  this.pending.delete(response.id);
2387
+ if (pending.timer) clearTimeout(pending.timer);
2211
2388
  if (response.error) {
2389
+ log(
2390
+ "response error: id=" + response.id.toString() + " code=" + response.error.code.toString(),
2391
+ 0 /* DEBUG */
2392
+ );
2212
2393
  const err = new Error(response.error.message);
2213
2394
  err.code = response.error.code;
2214
2395
  pending.reject(err);
2215
2396
  } else {
2397
+ log(
2398
+ "response ok: id=" + response.id.toString(),
2399
+ 0 /* DEBUG */
2400
+ );
2216
2401
  pending.resolve(response.result);
2217
2402
  }
2403
+ } else {
2404
+ log(
2405
+ "unmatched response id=" + response.id.toString(),
2406
+ 0 /* DEBUG */
2407
+ );
2218
2408
  }
2219
- } catch {
2409
+ } catch (parseErr) {
2410
+ log(
2411
+ "json parse error: " + parseErr.message,
2412
+ 0 /* DEBUG */
2413
+ );
2220
2414
  }
2221
2415
  }
2222
2416
  }
@@ -2228,129 +2422,501 @@ import { join as join8 } from "node:path";
2228
2422
  import { tmpdir as tmpdir3 } from "node:os";
2229
2423
 
2230
2424
  // src/shared/worker-client/functions/resolve-db-path.function.ts
2231
- import { existsSync as existsSync4 } from "node:fs";
2232
- import { join as join5, resolve as resolve3 } from "node:path";
2425
+ import { existsSync as existsSync5 } from "node:fs";
2426
+ import { join as join6, resolve as resolve3 } from "node:path";
2233
2427
  function resolveDbPath(targetDir) {
2234
2428
  const base = targetDir ? resolve3(targetDir) : process.cwd();
2235
- const dbPath = join5(base, ".kbdb");
2236
- if (!existsSync4(dbPath)) {
2237
- throw new Error(`database not found: ${dbPath}`);
2429
+ const dbPath = join6(base, ".kbdb");
2430
+ if (!existsSync5(dbPath)) {
2431
+ const msg = `database not found: ${dbPath}`;
2432
+ log(msg, 3 /* ERROR */);
2433
+ throw new Error(msg);
2434
+ }
2435
+ return dbPath;
2436
+ }
2437
+
2438
+ // src/shared/worker-client/functions/compute-context-id.function.ts
2439
+ async function computeContextId(absolutePath) {
2440
+ const hash = await computeSha256(absolutePath);
2441
+ return hash.slice(0, 16);
2442
+ }
2443
+
2444
+ // src/shared/worker-client/functions/spawn-daemon.function.ts
2445
+ import { spawn } from "node:child_process";
2446
+ function spawnDaemon(contextPath, runtime2, workerScript2) {
2447
+ if (!workerScript2) {
2448
+ const msg = "workerScript must be provided (resolve at entry point)";
2449
+ log(msg, 3 /* ERROR */);
2450
+ throw new Error(msg);
2451
+ }
2452
+ const execPath = runtime2 === "deno" ? "deno" : process.execPath;
2453
+ const logLevelEnv = process.env["KBDB_LOG_LEVEL"];
2454
+ const logArgs = logLevelEnv ? ["--log-level", logLevelEnv] : [];
2455
+ const args = runtime2 === "deno" ? ["run", "--allow-all", workerScript2, contextPath, ...logArgs] : [workerScript2, contextPath, ...logArgs];
2456
+ log(
2457
+ "spawning daemon: " + execPath + " " + args.join(" "),
2458
+ 0 /* DEBUG */
2459
+ );
2460
+ const child = spawn(execPath, args, {
2461
+ detached: true,
2462
+ stdio: "ignore"
2463
+ });
2464
+ child.unref();
2465
+ }
2466
+
2467
+ // src/shared/worker-client/functions/wait-for-daemon.function.ts
2468
+ import { existsSync as existsSync6 } from "node:fs";
2469
+ import { join as join7 } from "node:path";
2470
+ import { tmpdir as tmpdir2 } from "node:os";
2471
+ var DEFAULT_TIMEOUT_MS = 1e4;
2472
+ var POLL_INTERVAL_MS = 100;
2473
+ async function waitForDaemon(contextId, timeoutMs = DEFAULT_TIMEOUT_MS) {
2474
+ log("waiting for daemon: contextId=" + contextId, 0 /* DEBUG */);
2475
+ const pidPath = join7(tmpdir2(), `kbdb-${contextId}.pid`);
2476
+ const start = Date.now();
2477
+ let iteration = 0;
2478
+ while (Date.now() - start < timeoutMs) {
2479
+ if (existsSync6(pidPath)) {
2480
+ log("daemon PID file appeared", 0 /* DEBUG */);
2481
+ return true;
2482
+ }
2483
+ iteration++;
2484
+ if (iteration % 10 === 0) {
2485
+ const elapsed2 = Date.now() - start;
2486
+ log(
2487
+ "still waiting for daemon: elapsed=" + elapsed2.toString() + "ms",
2488
+ 0 /* DEBUG */
2489
+ );
2490
+ }
2491
+ await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
2492
+ }
2493
+ const elapsed = Date.now() - start;
2494
+ log(
2495
+ "timed out waiting for daemon: elapsed=" + elapsed.toString() + "ms",
2496
+ 0 /* DEBUG */
2497
+ );
2498
+ return false;
2499
+ }
2500
+
2501
+ // src/shared/worker-client/functions/create-worker-client.function.ts
2502
+ async function createWorkerClient(options) {
2503
+ const dbPath = options?.contextPath ?? resolveDbPath(options?.dbPath);
2504
+ const contextId = await computeContextId(dbPath);
2505
+ log("create-worker-client: contextId=" + contextId, 0 /* DEBUG */);
2506
+ const socketPath = getIpcPath(contextId);
2507
+ let daemon = discoverDaemon(contextId);
2508
+ if (daemon) {
2509
+ log("daemon found: pid=" + daemon.pid.toString(), 0 /* DEBUG */);
2510
+ } else {
2511
+ log("no daemon found", 0 /* DEBUG */);
2512
+ }
2513
+ if (!daemon && options?.autoSpawn !== false) {
2514
+ const runtime2 = detectRuntime();
2515
+ log("auto-spawning daemon", 0 /* DEBUG */);
2516
+ spawnDaemon(dbPath, runtime2, options?.workerScript);
2517
+ log("waiting for daemon after spawn", 0 /* DEBUG */);
2518
+ await waitForDaemon(contextId, options?.connectTimeoutMs);
2519
+ daemon = discoverDaemon(contextId);
2520
+ }
2521
+ if (!daemon) {
2522
+ const msg = `kbdb worker daemon did not start: ${readCrashReason(contextId)}`;
2523
+ log(msg, 3 /* ERROR */);
2524
+ throw new Error(msg);
2525
+ }
2526
+ log("connecting to daemon", 0 /* DEBUG */);
2527
+ const client = new WorkerClient(
2528
+ socketPath,
2529
+ contextId,
2530
+ options?.requestTimeoutMs
2531
+ );
2532
+ await client.connect();
2533
+ return client;
2534
+ }
2535
+ function readCrashReason(contextId) {
2536
+ const crashPath = join8(tmpdir3(), `kbdb-${contextId}.crash`);
2537
+ if (!existsSync7(crashPath)) {
2538
+ return "daemon failed to start (no details available)";
2539
+ }
2540
+ try {
2541
+ const raw = readFileSync3(crashPath, "utf-8");
2542
+ const crash = JSON.parse(raw);
2543
+ unlinkSync2(crashPath);
2544
+ return crash.error ?? "unknown error (crash log empty)";
2545
+ } catch {
2546
+ return "daemon failed to start (crash log unreadable)";
2547
+ }
2548
+ }
2549
+
2550
+ // src/shared/cli/functions/run-worker-stop.function.ts
2551
+ async function runWorkerStop(dbDir) {
2552
+ log("running worker-stop", 0 /* DEBUG */);
2553
+ const contextId = await computeContextId(dbDir);
2554
+ const info = discoverDaemon(contextId);
2555
+ if (!info) {
2556
+ return { output: "no daemon running", exitCode: 0 };
2557
+ }
2558
+ log("pid found: " + info.pid.toString(), 0 /* DEBUG */);
2559
+ try {
2560
+ process.kill(info.pid, "SIGTERM");
2561
+ log("sigterm sent to pid=" + info.pid.toString(), 0 /* DEBUG */);
2562
+ } catch {
2563
+ return {
2564
+ error: "error: failed to stop daemon",
2565
+ exitCode: 1
2566
+ };
2567
+ }
2568
+ const deadline = Date.now() + 5e3;
2569
+ let pollIteration = 0;
2570
+ while (Date.now() < deadline) {
2571
+ try {
2572
+ process.kill(info.pid, 0);
2573
+ } catch {
2574
+ log(
2575
+ "process exited: pid=" + info.pid.toString(),
2576
+ 0 /* DEBUG */
2577
+ );
2578
+ break;
2579
+ }
2580
+ pollIteration++;
2581
+ if (pollIteration % 5 === 0) {
2582
+ log(
2583
+ "waiting for exit: pid=" + info.pid.toString() + " poll=" + pollIteration.toString(),
2584
+ 0 /* DEBUG */
2585
+ );
2586
+ }
2587
+ await new Promise((r) => setTimeout(r, 100));
2588
+ }
2589
+ if (Date.now() >= deadline) {
2590
+ log(
2591
+ "timed out waiting for exit: pid=" + info.pid.toString(),
2592
+ 0 /* DEBUG */
2593
+ );
2594
+ }
2595
+ return {
2596
+ output: `stopped daemon (pid ${info.pid.toString()})`,
2597
+ exitCode: 0
2598
+ };
2599
+ }
2600
+
2601
+ // src/shared/cli/functions/run-worker-restart.function.ts
2602
+ async function runWorkerRestart(dbDir) {
2603
+ log("running worker-restart", 0 /* DEBUG */);
2604
+ const stopResult = await runWorkerStop(dbDir);
2605
+ if (stopResult.exitCode !== 0) return stopResult;
2606
+ return {
2607
+ output: "daemon will restart on next command",
2608
+ exitCode: 0
2609
+ };
2610
+ }
2611
+
2612
+ // src/shared/cli/functions/resolve-raw-db-path.function.ts
2613
+ function resolveRawDbPath(options) {
2614
+ return options.dbPath ?? process.env["KBDB_DB_DIR"];
2615
+ }
2616
+
2617
+ // src/shared/worker-client/functions/retry-on-timeout.function.ts
2618
+ async function retryOnTimeout(createClient, operation, maxRetries) {
2619
+ let lastError = new Error("retryOnTimeout exhausted");
2620
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
2621
+ log(
2622
+ "retry-on-timeout: attempt=" + attempt.toString() + " max=" + maxRetries.toString(),
2623
+ 0 /* DEBUG */
2624
+ );
2625
+ const client = await createClient();
2626
+ try {
2627
+ const result = await operation(client);
2628
+ log(
2629
+ "retry-on-timeout: success on attempt=" + attempt.toString(),
2630
+ 0 /* DEBUG */
2631
+ );
2632
+ return { client, result };
2633
+ } catch (err) {
2634
+ const code = err.code;
2635
+ if (code !== "REQUEST_TIMEOUT" || attempt >= maxRetries) {
2636
+ log(
2637
+ "retry-on-timeout: non-retriable error code=" + String(code),
2638
+ 0 /* DEBUG */
2639
+ );
2640
+ client.disconnect();
2641
+ throw err;
2642
+ }
2643
+ lastError = err;
2644
+ if (client.killDaemon) {
2645
+ log(
2646
+ "retry " + String(attempt + 1) + "/" + String(maxRetries) + ": killing daemon",
2647
+ 2 /* WARNING */
2648
+ );
2649
+ client.killDaemon();
2650
+ } else {
2651
+ client.disconnect();
2652
+ }
2653
+ }
2654
+ }
2655
+ log(
2656
+ "retry-on-timeout: all retries exhausted max=" + maxRetries.toString(),
2657
+ 0 /* DEBUG */
2658
+ );
2659
+ throw lastError;
2660
+ }
2661
+
2662
+ // src/shared/worker-client/constants/request-timeout.constant.ts
2663
+ var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
2664
+
2665
+ // src/shared/worker-client/constants/retry-defaults.constant.ts
2666
+ var DEFAULT_RETRY_COUNT = 5;
2667
+
2668
+ // src/shared/cli/functions/run-cli.function.ts
2669
+ async function runCli(argv, deps2) {
2670
+ const options = parseArgs(argv);
2671
+ const logLevel = resolveLogLevel(options.logLevel);
2672
+ configureLog({ level: logLevel });
2673
+ log("command: " + options.command, 0 /* DEBUG */);
2674
+ if (options.command === "init") {
2675
+ log('--init is deprecated, use "kbdb db init"', 2 /* WARNING */);
2676
+ }
2677
+ if (options.command === "migrate") {
2678
+ log(
2679
+ '--migrate is deprecated, use "kbdb db migrate"',
2680
+ 2 /* WARNING */
2681
+ );
2682
+ }
2683
+ const nonInteractive = options.nonInteractive || process.env["KBDB_NON_INTERACTIVE"] === "1" || process.env["KBDB_NON_INTERACTIVE"] === "true";
2684
+ const effectiveDeps = nonInteractive ? { ...deps2, isStdinTty: () => false } : deps2;
2685
+ if (!options.formatExplicit) {
2686
+ options.format = effectiveDeps.isStdoutTty() ? "text" : "json";
2687
+ }
2688
+ if (options.command === "help" || !options.command) {
2689
+ const helpCommand = options.args[0];
2690
+ const helpSubcommand = options.args[1];
2691
+ const helpText = generateHelp(helpCommand, helpSubcommand);
2692
+ if (helpCommand && !isKnownCommand(helpCommand)) {
2693
+ return { output: helpText, exitCode: 1 };
2694
+ }
2695
+ return { output: helpText, exitCode: 0 };
2696
+ }
2697
+ if (options.command === "version") {
2698
+ return { output: VERSION, exitCode: 0 };
2699
+ }
2700
+ if (options.command === "init" || options.command === "db-init") {
2701
+ return handleInit(options, effectiveDeps);
2702
+ }
2703
+ if (options.command === "mcp") {
2704
+ return handleMcp(options, effectiveDeps);
2705
+ }
2706
+ if (options.command === "migrate" || options.command === "db-migrate") {
2707
+ return handleMigrate(options, effectiveDeps);
2708
+ }
2709
+ if (options.command === "worker-stop") {
2710
+ return handleWorkerLifecycle(
2711
+ options,
2712
+ effectiveDeps,
2713
+ runWorkerStop
2714
+ );
2715
+ }
2716
+ if (options.command === "worker-restart") {
2717
+ return handleWorkerLifecycle(
2718
+ options,
2719
+ effectiveDeps,
2720
+ runWorkerRestart
2721
+ );
2722
+ }
2723
+ return handleDataCommand(options, effectiveDeps);
2724
+ }
2725
+ function handleInit(options, deps2) {
2726
+ const result = deps2.runInit(options);
2727
+ if (result.ok) {
2728
+ return {
2729
+ output: result.targetPath,
2730
+ exitCode: 0
2731
+ };
2732
+ }
2733
+ return {
2734
+ error: `error: ${result.errorMessage ?? "init failed"}`,
2735
+ exitCode: 1
2736
+ };
2737
+ }
2738
+ function resolveTimeoutMs(options) {
2739
+ return options.timeoutMs ?? (parseInt(process.env["KBDB_DAEMON_TIMEOUT"] ?? "", 10) || DEFAULT_REQUEST_TIMEOUT_MS);
2740
+ }
2741
+ function resolveRetryCount(options) {
2742
+ return options.retry ?? (parseInt(process.env["KBDB_RETRY"] ?? "", 10) || DEFAULT_RETRY_COUNT);
2743
+ }
2744
+ async function handleMcp(options, deps2) {
2745
+ const explicitPath = resolveRawDbPath(options);
2746
+ const dbDir = deps2.findDb(explicitPath);
2747
+ if (!dbDir) {
2748
+ return {
2749
+ error: "error: no .kbdb database found at " + (explicitPath ?? process.cwd()),
2750
+ exitCode: 1
2751
+ };
2752
+ }
2753
+ const timeoutMs = resolveTimeoutMs(options);
2754
+ const maxRetries = resolveRetryCount(options);
2755
+ let client;
2756
+ try {
2757
+ client = await deps2.createWorkerClient({
2758
+ contextPath: dbDir,
2759
+ requestTimeoutMs: timeoutMs
2760
+ });
2761
+ } catch (err) {
2762
+ return {
2763
+ error: `error: ${errorToMessage(err)}`,
2764
+ exitCode: 1
2765
+ };
2238
2766
  }
2239
- return dbPath;
2240
- }
2241
-
2242
- // src/shared/worker-client/functions/compute-context-id.function.ts
2243
- async function computeContextId(absolutePath) {
2244
- const hash = await computeSha256(absolutePath);
2245
- return hash.slice(0, 16);
2246
- }
2247
-
2248
- // src/shared/worker-client/functions/discover-daemon.function.ts
2249
- import { existsSync as existsSync5, readFileSync as readFileSync2, unlinkSync } from "node:fs";
2250
- import { join as join6 } from "node:path";
2251
- import { tmpdir } from "node:os";
2252
-
2253
- // src/shared/platform/functions/is-process-alive.function.ts
2254
- function isProcessAlive(pid) {
2255
2767
  try {
2256
- process.kill(pid, 0);
2257
- return true;
2258
- } catch {
2259
- return false;
2768
+ const gateResult = await versionGate(client, dbDir);
2769
+ if (gateResult) return gateResult;
2770
+ if (deps2.startMcpServer) {
2771
+ await deps2.startMcpServer(
2772
+ dbDir,
2773
+ () => deps2.createWorkerClient({
2774
+ contextPath: dbDir,
2775
+ requestTimeoutMs: timeoutMs
2776
+ }),
2777
+ maxRetries
2778
+ );
2779
+ }
2780
+ return { exitCode: 0 };
2781
+ } catch (err) {
2782
+ return {
2783
+ error: `error: mcp failed: ${errorToMessage(err)}`,
2784
+ exitCode: 1
2785
+ };
2786
+ } finally {
2787
+ client.disconnect();
2260
2788
  }
2261
2789
  }
2262
-
2263
- // src/shared/worker-client/functions/discover-daemon.function.ts
2264
- function discoverDaemon(contextId) {
2265
- const pidPath = join6(tmpdir(), `kbdb-${contextId}.pid`);
2266
- if (!existsSync5(pidPath)) return null;
2267
- const pidStr = readFileSync2(pidPath, "utf-8").trim();
2268
- const pid = parseInt(pidStr, 10);
2269
- if (isNaN(pid) || !isProcessAlive(pid)) {
2270
- try {
2271
- unlinkSync(pidPath);
2272
- } catch {
2273
- }
2274
- return null;
2790
+ async function handleMigrate(options, deps2) {
2791
+ const dbDir = deps2.findDb(options.dbPath);
2792
+ if (!dbDir) {
2793
+ const basePath = options.dbPath ?? process.cwd();
2794
+ return {
2795
+ error: `error: no .kbdb database found at ${basePath}`,
2796
+ exitCode: 1
2797
+ };
2275
2798
  }
2276
- const socketPath = join6(tmpdir(), `kbdb-${contextId}.sock`);
2277
- const crashPath = join6(tmpdir(), `kbdb-${contextId}.crash`);
2799
+ let client;
2278
2800
  try {
2279
- unlinkSync(crashPath);
2280
- } catch {
2801
+ client = await deps2.createWorkerClient({
2802
+ contextPath: dbDir
2803
+ });
2804
+ } catch (err) {
2805
+ return {
2806
+ error: `error: ${errorToMessage(err)}`,
2807
+ exitCode: 1
2808
+ };
2809
+ }
2810
+ try {
2811
+ const versionStatus = await client.checkVersion(dbDir);
2812
+ if (versionStatus.status === "too_new") {
2813
+ return {
2814
+ error: `error: database version ${versionStatus.currentVersion.toString()} is newer than kbdb version ${versionStatus.requiredVersion.toString()} -- upgrade kbdb`,
2815
+ exitCode: 1
2816
+ };
2817
+ }
2818
+ if (versionStatus.status === "needs_migration") {
2819
+ const migrateResult = await client.migrateDatabase(dbDir);
2820
+ return {
2821
+ output: JSON.stringify(migrateResult, null, 2),
2822
+ exitCode: 0
2823
+ };
2824
+ }
2825
+ return { output: "already up to date", exitCode: 0 };
2826
+ } catch (err) {
2827
+ return {
2828
+ error: `error: migrate failed: ${errorToMessage(err)}`,
2829
+ exitCode: 1
2830
+ };
2831
+ } finally {
2832
+ client.disconnect();
2281
2833
  }
2282
- return { pid, socketPath };
2283
2834
  }
2284
-
2285
- // src/shared/worker-client/functions/spawn-daemon.function.ts
2286
- import { spawn } from "node:child_process";
2287
- function spawnDaemon(contextPath, runtime2, workerScript2) {
2288
- if (!workerScript2) {
2289
- throw new Error(
2290
- "workerScript must be provided (resolve at entry point)"
2835
+ async function handleDataCommand(options, deps2) {
2836
+ const explicitPath = resolveRawDbPath(options);
2837
+ let dbDir = deps2.findDb(explicitPath);
2838
+ if (!dbDir) {
2839
+ const basePath = explicitPath ?? process.cwd();
2840
+ if (!deps2.isStdinTty()) {
2841
+ return {
2842
+ error: `error: no .kbdb database found at ${basePath} -- run \`kbdb --init\` to create one`,
2843
+ exitCode: 1
2844
+ };
2845
+ }
2846
+ const answer = await deps2.promptUser(
2847
+ `No .kbdb database found. Create one in ${basePath}? [y/N] `
2291
2848
  );
2849
+ if (answer.toLowerCase() !== "y") {
2850
+ return {
2851
+ error: "aborted: no database created",
2852
+ exitCode: 1
2853
+ };
2854
+ }
2855
+ const initResult = deps2.runInit(options);
2856
+ if (!initResult.ok) {
2857
+ return {
2858
+ error: `error: ${initResult.errorMessage ?? "init failed"}`,
2859
+ exitCode: 1
2860
+ };
2861
+ }
2862
+ dbDir = initResult.targetPath;
2292
2863
  }
2293
- const execPath = runtime2 === "deno" ? "deno" : process.execPath;
2294
- const args = runtime2 === "deno" ? ["run", "--allow-all", workerScript2, contextPath] : [workerScript2, contextPath];
2295
- const child = spawn(execPath, args, {
2296
- detached: true,
2297
- stdio: "ignore"
2298
- });
2299
- child.unref();
2300
- }
2301
-
2302
- // src/shared/worker-client/functions/wait-for-daemon.function.ts
2303
- import { existsSync as existsSync6 } from "node:fs";
2304
- import { join as join7 } from "node:path";
2305
- import { tmpdir as tmpdir2 } from "node:os";
2306
- var DEFAULT_TIMEOUT_MS = 1e4;
2307
- var POLL_INTERVAL_MS = 100;
2308
- async function waitForDaemon(contextId, timeoutMs = DEFAULT_TIMEOUT_MS) {
2309
- const pidPath = join7(tmpdir2(), `kbdb-${contextId}.pid`);
2310
- const start = Date.now();
2311
- while (Date.now() - start < timeoutMs) {
2312
- if (existsSync6(pidPath)) return true;
2313
- await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
2864
+ log("db path: " + dbDir, 0 /* DEBUG */);
2865
+ const timeoutMs = resolveTimeoutMs(options);
2866
+ const maxRetries = resolveRetryCount(options);
2867
+ try {
2868
+ const { client, result } = await retryOnTimeout(
2869
+ () => deps2.createWorkerClient({
2870
+ contextPath: dbDir,
2871
+ requestTimeoutMs: timeoutMs
2872
+ }),
2873
+ async (c) => {
2874
+ const gateResult = await versionGate(c, dbDir);
2875
+ if (gateResult) return gateResult;
2876
+ return dispatchCommand(c, options);
2877
+ },
2878
+ maxRetries
2879
+ );
2880
+ client.disconnect();
2881
+ return result;
2882
+ } catch (err) {
2883
+ return {
2884
+ error: `error: ${errorToMessage(err)}`,
2885
+ exitCode: 1
2886
+ };
2314
2887
  }
2315
- return false;
2316
2888
  }
2317
-
2318
- // src/shared/worker-client/functions/create-worker-client.function.ts
2319
- async function createWorkerClient(options) {
2320
- const dbPath = options?.contextPath ?? resolveDbPath(options?.dbPath);
2321
- const contextId = await computeContextId(dbPath);
2322
- const socketPath = getIpcPath(contextId);
2323
- let daemon = discoverDaemon(contextId);
2324
- if (!daemon && options?.autoSpawn !== false) {
2325
- const runtime2 = detectRuntime();
2326
- spawnDaemon(dbPath, runtime2, options?.workerScript);
2327
- await waitForDaemon(contextId, options?.connectTimeoutMs);
2328
- daemon = discoverDaemon(contextId);
2329
- }
2330
- if (!daemon) {
2331
- throw new Error(
2332
- `kbdb worker daemon did not start: ${readCrashReason(contextId)}`
2333
- );
2889
+ async function handleWorkerLifecycle(options, deps2, action) {
2890
+ const explicitPath = resolveRawDbPath(options);
2891
+ const dbDir = deps2.findDb(explicitPath);
2892
+ if (!dbDir) {
2893
+ return {
2894
+ error: "error: no .kbdb database found at " + (explicitPath ?? process.cwd()),
2895
+ exitCode: 1
2896
+ };
2334
2897
  }
2335
- const client = new WorkerClient(socketPath, contextId);
2336
- await client.connect();
2337
- return client;
2898
+ return action(dbDir);
2338
2899
  }
2339
- function readCrashReason(contextId) {
2340
- const crashPath = join8(tmpdir3(), `kbdb-${contextId}.crash`);
2341
- if (!existsSync7(crashPath)) {
2342
- return "daemon failed to start (no details available)";
2900
+ async function versionGate(client, dbDir) {
2901
+ const versionStatus = await client.checkVersion(dbDir);
2902
+ if (versionStatus.status === "needs_migration") {
2903
+ return {
2904
+ error: "error: database needs migration -- run `kbdb --migrate`",
2905
+ exitCode: 1
2906
+ };
2343
2907
  }
2344
- try {
2345
- const raw = readFileSync3(crashPath, "utf-8");
2346
- const crash = JSON.parse(raw);
2347
- unlinkSync2(crashPath);
2348
- return crash.error ?? "unknown error (crash log empty)";
2349
- } catch {
2350
- return "daemon failed to start (crash log unreadable)";
2908
+ if (versionStatus.status === "too_new") {
2909
+ return {
2910
+ error: `error: database version ${versionStatus.currentVersion.toString()} is newer than kbdb version ${versionStatus.requiredVersion.toString()} -- upgrade kbdb`,
2911
+ exitCode: 1
2912
+ };
2351
2913
  }
2914
+ return null;
2352
2915
  }
2353
2916
 
2917
+ // src/shared/cli/constants/help-text.constant.ts
2918
+ var HELP_TEXT = generateHelp();
2919
+
2354
2920
  // src/shared/mcp/classes/mcp-server.class.ts
2355
2921
  import { createInterface as createInterface2 } from "node:readline";
2356
2922
 
@@ -2384,6 +2950,10 @@ function createToolDefinitions() {
2384
2950
  type: "string",
2385
2951
  enum: ["lexical", "vector", "hybrid"],
2386
2952
  description: "Search algorithm (default: lexical)"
2953
+ },
2954
+ relaxed: {
2955
+ type: "boolean",
2956
+ description: "Use relaxed (OR) matching when the strict query returns no results"
2387
2957
  }
2388
2958
  },
2389
2959
  required: ["query"]
@@ -3064,6 +3634,7 @@ function asStringArray2(value) {
3064
3634
  return [];
3065
3635
  }
3066
3636
  async function handleToolCall(client, name, args) {
3637
+ log("tool call: " + name, 0 /* DEBUG */);
3067
3638
  try {
3068
3639
  switch (name) {
3069
3640
  case "search":
@@ -3107,6 +3678,7 @@ async function handleToolCall(client, name, args) {
3107
3678
  case "auto-capture-review":
3108
3679
  return handleAutoCaptureReview();
3109
3680
  default:
3681
+ log("unknown tool: " + name, 2 /* WARNING */);
3110
3682
  return {
3111
3683
  content: [
3112
3684
  {
@@ -3118,6 +3690,10 @@ async function handleToolCall(client, name, args) {
3118
3690
  };
3119
3691
  }
3120
3692
  } catch (err) {
3693
+ log(
3694
+ "tool call failed: " + name + ": " + (err instanceof Error ? err.message : String(err)),
3695
+ 3 /* ERROR */
3696
+ );
3121
3697
  return {
3122
3698
  content: [
3123
3699
  {
@@ -3135,7 +3711,8 @@ async function handleSearch2(client, args) {
3135
3711
  mode: args["mode"],
3136
3712
  limit: args["limit"],
3137
3713
  offset: args["offset"],
3138
- algo: args["algo"]
3714
+ algo: args["algo"],
3715
+ relaxed: args["relaxed"]
3139
3716
  });
3140
3717
  const stripped = {
3141
3718
  ...results,
@@ -3491,6 +4068,7 @@ async function handleResourceRead(client, uri) {
3491
4068
  ]
3492
4069
  };
3493
4070
  }
4071
+ log(`Unknown resource URI: ${uri}`, 3 /* ERROR */);
3494
4072
  throw new Error(`Unknown resource URI: ${uri}`);
3495
4073
  }
3496
4074
 
@@ -3567,6 +4145,7 @@ async function handleAgentPrompt(name, client) {
3567
4145
  const agents = await client.listDocumentsByType("agent");
3568
4146
  const doc = agents.find((a) => a.title === agentName);
3569
4147
  if (!doc) {
4148
+ log("agent not found: " + agentName, 3 /* ERROR */);
3570
4149
  throw new Error("agent not found: " + agentName);
3571
4150
  }
3572
4151
  const sections = doc.sections;
@@ -3611,6 +4190,7 @@ async function handleSkillPrompt(name, promptArgs, client) {
3611
4190
  }
3612
4191
  }
3613
4192
  if (matchContent === void 0) {
4193
+ log(`Prompt not found: ${name}`, 3 /* ERROR */);
3614
4194
  throw new Error(`Prompt not found: ${name}`);
3615
4195
  }
3616
4196
  const parsed = JSON.parse(matchContent);
@@ -3702,6 +4282,131 @@ function shouldEmitLog(messageLevel, threshold) {
3702
4282
  return messageIndex >= thresholdIndex;
3703
4283
  }
3704
4284
 
4285
+ // src/shared/auto-capture/functions/build-capture-prompt.function.ts
4286
+ function buildCapturePrompt(recentContext) {
4287
+ return "Review the following conversation context and identify factual knowledge worth storing in the knowledge base.\n\nRules:\n- Include durable facts, decisions, preferences, and corrections that would be useful in future sessions.\n- Exclude ephemeral, task-specific, or temporary information that has no lasting value.\n- Format each piece of extracted knowledge as a concise statement suitable for direct storage.\n- If no durable knowledge is found, respond with an empty list.\n\nConversation context:\n" + recentContext;
4288
+ }
4289
+
4290
+ // src/shared/mcp/functions/has-sampling-capability.function.ts
4291
+ function hasSamplingCapability(hostCapabilities) {
4292
+ if (hostCapabilities === null) return false;
4293
+ return Boolean(hostCapabilities["sampling"]);
4294
+ }
4295
+
4296
+ // src/shared/mcp/functions/run-auto-capture.function.ts
4297
+ function isSamplingResponse(v) {
4298
+ if (typeof v !== "object" || v === null) return false;
4299
+ const obj = v;
4300
+ const content = obj["content"];
4301
+ if (typeof content !== "object" || content === null) return false;
4302
+ return typeof content["text"] === "string";
4303
+ }
4304
+ async function runAutoCapture(controller, config, client, hostCapabilities, requestSampling) {
4305
+ try {
4306
+ const trigger = controller.evaluate();
4307
+ log("auto-capture trigger evaluated", 0 /* DEBUG */);
4308
+ if (!trigger.shouldCapture) return;
4309
+ if (!hasSamplingCapability(hostCapabilities)) return;
4310
+ const prompt = buildCapturePrompt("recent conversation context");
4311
+ const messages = [
4312
+ { role: "user", content: { type: "text", text: prompt } }
4313
+ ];
4314
+ const raw = await requestSampling(messages, 1024);
4315
+ if (!isSamplingResponse(raw)) return;
4316
+ const text = raw.content.text.trim();
4317
+ if (!text) return;
4318
+ if (config.dryRun) return;
4319
+ log("auto-capture storing knowledge", 0 /* DEBUG */);
4320
+ await client.addSection({
4321
+ sectionType: "text/markdown",
4322
+ content: text,
4323
+ title: "Auto-captured knowledge"
4324
+ });
4325
+ } catch {
4326
+ log("auto-capture error (non-fatal)", 0 /* DEBUG */);
4327
+ }
4328
+ }
4329
+
4330
+ // src/shared/auto-capture/functions/evaluate-trigger.function.ts
4331
+ function evaluateTrigger(config, state) {
4332
+ log("evaluating auto-capture trigger conditions", 0 /* DEBUG */);
4333
+ if (!config.enabled) {
4334
+ return {
4335
+ shouldCapture: false,
4336
+ reason: "auto-capture is disabled"
4337
+ };
4338
+ }
4339
+ if (state.totalCapturesThisSession >= config.maxCapturesPerSession) {
4340
+ return {
4341
+ shouldCapture: false,
4342
+ reason: "session capture limit reached"
4343
+ };
4344
+ }
4345
+ const elapsed = state.lastCaptureTimestamp ? Date.now() - state.lastCaptureTimestamp : Infinity;
4346
+ if (elapsed < config.minIntervalMs) {
4347
+ return {
4348
+ shouldCapture: false,
4349
+ reason: "within minimum interval"
4350
+ };
4351
+ }
4352
+ if (state.toolCallsSinceLastCapture < config.triggerAfterToolCalls) {
4353
+ return {
4354
+ shouldCapture: false,
4355
+ reason: "tool call threshold not yet reached"
4356
+ };
4357
+ }
4358
+ return { shouldCapture: true, reason: "trigger threshold met" };
4359
+ }
4360
+
4361
+ // src/shared/auto-capture/classes/auto-capture-controller.class.ts
4362
+ var AutoCaptureController = class {
4363
+ toolCallsSinceLastCapture = 0;
4364
+ lastCaptureTimestamp = 0;
4365
+ totalCapturesThisSession = 0;
4366
+ config;
4367
+ /** @param config - the auto-capture configuration to use */
4368
+ constructor(config) {
4369
+ this.config = config;
4370
+ }
4371
+ /** Record one tool call for trigger counting. */
4372
+ recordToolCall() {
4373
+ this.toolCallsSinceLastCapture += 1;
4374
+ }
4375
+ /**
4376
+ * Evaluates the current state against the trigger criteria.
4377
+ *
4378
+ * When the trigger fires, advances the session counters so the
4379
+ * next evaluation respects rate limiting and the session cap.
4380
+ *
4381
+ * @returns the trigger decision with a human-readable reason
4382
+ */
4383
+ evaluate() {
4384
+ log("evaluating auto-capture trigger", 0 /* DEBUG */);
4385
+ const trigger = evaluateTrigger(this.config, this.state());
4386
+ if (trigger.shouldCapture) {
4387
+ this.totalCapturesThisSession += 1;
4388
+ this.lastCaptureTimestamp = Date.now();
4389
+ this.toolCallsSinceLastCapture = 0;
4390
+ }
4391
+ return trigger;
4392
+ }
4393
+ /** Reset all counters, e.g. on client disconnect. */
4394
+ reset() {
4395
+ log("resetting auto-capture controller", 0 /* DEBUG */);
4396
+ this.toolCallsSinceLastCapture = 0;
4397
+ this.lastCaptureTimestamp = 0;
4398
+ this.totalCapturesThisSession = 0;
4399
+ }
4400
+ /** Returns a snapshot of the current controller state. */
4401
+ state() {
4402
+ return {
4403
+ toolCallsSinceLastCapture: this.toolCallsSinceLastCapture,
4404
+ lastCaptureTimestamp: this.lastCaptureTimestamp,
4405
+ totalCapturesThisSession: this.totalCapturesThisSession
4406
+ };
4407
+ }
4408
+ };
4409
+
3705
4410
  // src/shared/mcp/constants/mcp-error-codes.constant.ts
3706
4411
  var PARSE_ERROR = -32700;
3707
4412
  var METHOD_NOT_FOUND = -32601;
@@ -3711,21 +4416,63 @@ var RESOURCE_NOT_FOUND = -32002;
3711
4416
  var McpServer = class {
3712
4417
  client;
3713
4418
  contextPath;
4419
+ autoCaptureConfig;
4420
+ clientFactory;
4421
+ maxRetries;
4422
+ autoCaptureController = null;
3714
4423
  initialized = false;
3715
4424
  hostCapabilities = null;
3716
4425
  logLevel = null;
3717
4426
  subscriptions = /* @__PURE__ */ new Set();
3718
4427
  nextRequestId = 1;
3719
4428
  pendingRequests = /* @__PURE__ */ new Map();
3720
- constructor(client, contextPath) {
4429
+ /**
4430
+ * @param client - worker client providing knowledge-base operations
4431
+ * @param contextPath - absolute path to the `.kbdb` directory
4432
+ * @param autoCaptureConfig - optional auto-capture configuration;
4433
+ * when provided the server activates auto-capture on connection
4434
+ * @param clientFactory - creates a fresh worker client (for retry)
4435
+ * @param maxRetries - max retries on REQUEST_TIMEOUT
4436
+ */
4437
+ constructor(client, contextPath, autoCaptureConfig, clientFactory, maxRetries) {
3721
4438
  this.client = client;
3722
4439
  this.contextPath = contextPath ?? "";
4440
+ this.autoCaptureConfig = autoCaptureConfig ?? null;
4441
+ this.clientFactory = clientFactory ?? null;
4442
+ this.maxRetries = maxRetries ?? DEFAULT_RETRY_COUNT;
4443
+ }
4444
+ async reconnectClient() {
4445
+ if (!this.clientFactory) {
4446
+ log("no client factory for reconnect", 3 /* ERROR */);
4447
+ throw new Error("no client factory for reconnect");
4448
+ }
4449
+ this.client.disconnect();
4450
+ this.client = await this.clientFactory();
4451
+ log("MCP client reconnected", 0 /* DEBUG */);
4452
+ }
4453
+ async withRetry(fn) {
4454
+ for (let attempt = 0; ; attempt++) {
4455
+ try {
4456
+ return await fn();
4457
+ } catch (err) {
4458
+ const code = err.code;
4459
+ if (code !== "REQUEST_TIMEOUT" || attempt >= this.maxRetries || !this.clientFactory) {
4460
+ throw err;
4461
+ }
4462
+ log(
4463
+ "request timeout, reconnecting (attempt " + (attempt + 1).toString() + "/" + this.maxRetries.toString() + ")",
4464
+ 2 /* WARNING */
4465
+ );
4466
+ await this.reconnectClient();
4467
+ }
4468
+ }
3723
4469
  }
3724
4470
  async listen() {
3725
4471
  const rl = createInterface2({
3726
4472
  input: process.stdin,
3727
4473
  terminal: false
3728
4474
  });
4475
+ log("MCP server listening on stdin", 0 /* DEBUG */);
3729
4476
  let pending = Promise.resolve();
3730
4477
  await new Promise((resolve4) => {
3731
4478
  rl.on("line", (line) => {
@@ -3733,7 +4480,10 @@ var McpServer = class {
3733
4480
  });
3734
4481
  rl.on("close", () => {
3735
4482
  void pending.then(() => {
4483
+ this.autoCaptureController?.reset();
4484
+ this.autoCaptureController = null;
3736
4485
  this.client.disconnect();
4486
+ log("MCP stdin closed", 0 /* DEBUG */);
3737
4487
  resolve4();
3738
4488
  });
3739
4489
  });
@@ -3797,6 +4547,7 @@ var McpServer = class {
3797
4547
  */
3798
4548
  async requestSampling(messages, maxTokens) {
3799
4549
  if (!this.hostCapabilities?.["sampling"]) {
4550
+ log("Host does not support sampling", 3 /* ERROR */);
3800
4551
  throw new Error("Host does not support sampling");
3801
4552
  }
3802
4553
  return this.sendRequest("sampling/createMessage", {
@@ -3843,10 +4594,15 @@ var McpServer = class {
3843
4594
  return null;
3844
4595
  }
3845
4596
  const request = parsed;
4597
+ log("MCP request: " + request.method, 0 /* DEBUG */);
3846
4598
  if (request.id === void 0) {
3847
4599
  if (request.method === "notifications/initialized" || request.method === "notifications/cancelled") {
3848
4600
  if (request.method === "notifications/initialized" && !this.initialized) {
3849
4601
  this.initialized = true;
4602
+ log("MCP initialized", 1 /* INFO */);
4603
+ if (this.autoCaptureConfig !== null) {
4604
+ this.autoCaptureController = new AutoCaptureController(this.autoCaptureConfig);
4605
+ }
3850
4606
  void this.runStartupHealthCheck();
3851
4607
  }
3852
4608
  }
@@ -3880,7 +4636,7 @@ var McpServer = class {
3880
4636
  protocolVersion: "2025-11-25",
3881
4637
  serverInfo: {
3882
4638
  name: "kbdb",
3883
- version: "0.1.0"
4639
+ version: VERSION
3884
4640
  },
3885
4641
  capabilities: {
3886
4642
  tools: {},
@@ -3921,11 +4677,10 @@ var McpServer = class {
3921
4677
  const rawName = params["name"];
3922
4678
  const name = typeof rawName === "string" ? rawName : "";
3923
4679
  const args = params["arguments"] ?? {};
3924
- const result = await handleToolCall(
3925
- this.client,
3926
- name,
3927
- args
4680
+ const result = await this.withRetry(
4681
+ () => handleToolCall(this.client, name, args)
3928
4682
  );
4683
+ this.afterToolCall();
3929
4684
  return { jsonrpc: "2.0", id, result };
3930
4685
  }
3931
4686
  case "resources/read": {
@@ -3933,9 +4688,8 @@ var McpServer = class {
3933
4688
  const rawUri = params["uri"];
3934
4689
  const uri = typeof rawUri === "string" ? rawUri : "";
3935
4690
  try {
3936
- const result = await handleResourceRead(
3937
- this.client,
3938
- uri
4691
+ const result = await this.withRetry(
4692
+ () => handleResourceRead(this.client, uri)
3939
4693
  );
3940
4694
  return { jsonrpc: "2.0", id, result };
3941
4695
  } catch (err) {
@@ -4040,6 +4794,23 @@ var McpServer = class {
4040
4794
  const json = JSON.stringify(response);
4041
4795
  process.stdout.write(json + "\n");
4042
4796
  }
4797
+ /**
4798
+ * Records a tool call in the auto-capture controller and fires
4799
+ * a capture when the trigger condition is met.
4800
+ */
4801
+ afterToolCall() {
4802
+ const ctrl = this.autoCaptureController;
4803
+ const cfg = this.autoCaptureConfig;
4804
+ if (ctrl === null || cfg === null) return;
4805
+ ctrl.recordToolCall();
4806
+ void runAutoCapture(
4807
+ ctrl,
4808
+ cfg,
4809
+ this.client,
4810
+ this.hostCapabilities,
4811
+ (messages, maxTokens) => this.requestSampling(messages, maxTokens)
4812
+ );
4813
+ }
4043
4814
  /**
4044
4815
  * Runs an integrity check immediately after the MCP handshake
4045
4816
  * completes. Emits a `notifications/message` warning when the
@@ -4064,8 +4835,15 @@ var McpServer = class {
4064
4835
  };
4065
4836
 
4066
4837
  // src/shared/mcp/functions/create-mcp-server.function.ts
4067
- function createMcpServer(client) {
4068
- return new McpServer(client);
4838
+ function createMcpServer(client, contextPath, autoCaptureConfig, clientFactory, maxRetries) {
4839
+ log("creating MCP server", 0 /* DEBUG */);
4840
+ return new McpServer(
4841
+ client,
4842
+ contextPath,
4843
+ autoCaptureConfig,
4844
+ clientFactory,
4845
+ maxRetries
4846
+ );
4069
4847
  }
4070
4848
 
4071
4849
  // src/cli.ts
@@ -4074,18 +4852,36 @@ var baseDir = resolveBaseDir(import.meta.url, import.meta.dirname);
4074
4852
  var workerScript = resolveWorkerScript(baseDir.scriptDir, runtime);
4075
4853
  var deps = {
4076
4854
  isStdinTty,
4855
+ isStdoutTty: () => process.stdout.isTTY,
4077
4856
  promptUser,
4078
4857
  createWorkerClient: (opts) => createWorkerClient({ ...opts, workerScript }),
4079
4858
  findDb,
4080
4859
  runInit,
4081
- startMcpServer: async (contextPath) => {
4860
+ startMcpServer: async (contextPath, clientFactory, maxRetries) => {
4861
+ log("starting MCP server", 1 /* INFO */);
4082
4862
  const client = await createWorkerClient({
4083
4863
  contextPath,
4084
4864
  workerScript
4085
4865
  });
4086
4866
  try {
4087
- const server = createMcpServer(client);
4867
+ const tomlPath = join9(contextPath, "worker.toml");
4868
+ let autoCaptureConfig;
4869
+ try {
4870
+ const tomlText = readFileSync4(tomlPath, "utf-8");
4871
+ const daemonConfig = parseWorkerToml(tomlText, contextPath);
4872
+ autoCaptureConfig = daemonConfig.autoCapture;
4873
+ } catch {
4874
+ }
4875
+ const server = createMcpServer(
4876
+ client,
4877
+ contextPath,
4878
+ autoCaptureConfig,
4879
+ clientFactory,
4880
+ maxRetries
4881
+ );
4882
+ log("MCP server listening on stdio", 0 /* DEBUG */);
4088
4883
  await server.listen();
4884
+ log("MCP server closed", 1 /* INFO */);
4089
4885
  } finally {
4090
4886
  client.disconnect();
4091
4887
  }
@@ -4097,7 +4893,7 @@ async function main() {
4097
4893
  console.log(result.output);
4098
4894
  }
4099
4895
  if (result.error) {
4100
- console.error(result.error);
4896
+ log(result.error, 3 /* ERROR */);
4101
4897
  }
4102
4898
  if (result.exitCode !== 0) {
4103
4899
  process.exitCode = result.exitCode;
@@ -4105,7 +4901,7 @@ async function main() {
4105
4901
  }
4106
4902
  main().catch((err) => {
4107
4903
  const msg = err instanceof Error ? err.message : String(err);
4108
- console.error(`error: ${msg}`);
4904
+ log("error: " + msg, 3 /* ERROR */);
4109
4905
  process.exitCode = 1;
4110
4906
  });
4111
4907
  //# sourceMappingURL=cli.mjs.map