@dikolab/kbdb 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (466) hide show
  1. package/README.md +83 -89
  2. package/dist/chunk-BJPSPNGX.mjs +223 -0
  3. package/dist/chunk-BJPSPNGX.mjs.map +7 -0
  4. package/dist/cli.cjs +956 -319
  5. package/dist/cli.cjs.map +4 -4
  6. package/dist/cli.d.ts +9 -0
  7. package/dist/cli.mjs +840 -321
  8. package/dist/cli.mjs.map +4 -4
  9. package/dist/kbdb-worker.cjs +714 -94
  10. package/dist/kbdb-worker.cjs.map +4 -4
  11. package/dist/mod.cjs +122 -16
  12. package/dist/mod.cjs.map +3 -3
  13. package/dist/mod.d.ts +23 -2
  14. package/dist/mod.mjs +121 -16
  15. package/dist/mod.mjs.map +3 -3
  16. package/dist/src/shared/cli/functions/dispatch-command.function.d.ts +2 -1
  17. package/dist/src/shared/cli/functions/find-db.function.d.ts +7 -8
  18. package/dist/src/shared/cli/functions/handle-mcp.function.d.ts +1 -1
  19. package/dist/src/shared/cli/functions/parse-args.function.d.ts +4 -3
  20. package/dist/src/shared/cli/functions/resolve-kbid-prefix.function.d.ts +27 -0
  21. package/dist/src/shared/cli/functions/resolve-raw-db-path.function.d.ts +10 -0
  22. package/dist/src/shared/cli/functions/run-cli.function.d.ts +3 -1
  23. package/dist/src/shared/cli/functions/run-content.function.d.ts +8 -3
  24. package/dist/src/shared/cli/functions/run-import.function.d.ts +27 -0
  25. package/dist/src/shared/cli/functions/run-recall.function.d.ts +10 -4
  26. package/dist/src/shared/cli/functions/run-search.function.d.ts +7 -0
  27. package/dist/src/shared/cli/functions/run-unlearn.function.d.ts +9 -4
  28. package/dist/src/shared/cli/functions/run-worker-restart.function.d.ts +11 -0
  29. package/dist/src/shared/cli/functions/run-worker-stop.function.d.ts +11 -0
  30. package/dist/src/shared/cli/index.d.ts +2 -0
  31. package/dist/src/shared/cli/typings/cli-deps.interface.d.ts +4 -1
  32. package/dist/src/shared/cli/typings/cli-options.interface.d.ts +17 -0
  33. package/dist/src/shared/cli/typings/dispatch-client.type.d.ts +2 -1
  34. package/dist/src/shared/cli/typings/search-display.model.d.ts +6 -0
  35. package/dist/src/shared/embedding/classes/api-embedding-provider.class.d.ts +33 -0
  36. package/dist/src/shared/embedding/classes/onnx-embedding-provider.class.d.ts +33 -0
  37. package/dist/src/shared/embedding/functions/append-vector-entry.function.d.ts +14 -0
  38. package/dist/src/shared/embedding/functions/create-embedding-provider.function.d.ts +12 -0
  39. package/dist/src/shared/embedding/functions/detect-stale-vectors.function.d.ts +16 -0
  40. package/dist/src/shared/embedding/functions/parse-api-embedding-response.function.d.ts +11 -0
  41. package/dist/src/shared/embedding/functions/rebuild-vectors.function.d.ts +15 -0
  42. package/dist/src/shared/embedding/functions/scan-semantic-contradictions.function.d.ts +13 -0
  43. package/dist/src/shared/embedding/index.d.ts +7 -0
  44. package/dist/src/shared/embedding/typings/semantic-contradiction.model.d.ts +21 -0
  45. package/dist/src/shared/embedding/typings/stale-vectors-report.model.d.ts +16 -0
  46. package/dist/src/shared/mcp/classes/mcp-server.class.d.ts +22 -2
  47. package/dist/src/shared/mcp/functions/create-mcp-server.function.d.ts +6 -1
  48. package/dist/src/shared/mcp/functions/has-sampling-capability.function.d.ts +8 -0
  49. package/dist/src/shared/mcp/functions/run-auto-capture.function.d.ts +26 -0
  50. package/dist/src/shared/mcp/typings/mcp-client.interface.d.ts +2 -0
  51. package/dist/src/shared/mcp/typings/mcp-integrity-check-result.model.d.ts +24 -0
  52. package/dist/src/shared/mcp/typings/mcp-worker-client.interface.d.ts +3 -1
  53. package/dist/src/shared/version/constants/version.constant.d.ts +1 -1
  54. package/dist/src/shared/wasm-codec/typings/paged-search-result.model.d.ts +2 -0
  55. package/dist/src/shared/worker-client/classes/worker-client.class.d.ts +31 -1
  56. package/dist/src/shared/worker-client/constants/request-timeout.constant.d.ts +2 -0
  57. package/dist/src/shared/worker-client/constants/retry-defaults.constant.d.ts +2 -0
  58. package/dist/src/shared/worker-client/functions/get-or-create-client.function.d.ts +20 -0
  59. package/dist/src/shared/worker-client/functions/retry-on-timeout.function.d.ts +17 -0
  60. package/dist/src/shared/worker-client/index.d.ts +4 -1
  61. package/dist/src/shared/worker-client/typings/import-result.model.d.ts +16 -0
  62. package/dist/src/shared/worker-client/typings/integrity-check-result.model.d.ts +24 -0
  63. package/dist/src/shared/worker-client/typings/search-params.model.d.ts +4 -0
  64. package/dist/src/shared/worker-client/typings/search-result.model.d.ts +6 -0
  65. package/dist/src/shared/worker-client/typings/worker-client-options.interface.d.ts +7 -0
  66. package/dist/src/shared/worker-daemon/classes/worker-daemon.class.d.ts +5 -0
  67. package/dist/src/shared/worker-daemon/functions/create-ipc-server.function.d.ts +11 -11
  68. package/dist/src/shared/worker-daemon/functions/embed-after-learn.function.d.ts +13 -0
  69. package/dist/src/shared/worker-daemon/functions/handle-hybrid-search.function.d.ts +44 -0
  70. package/dist/src/shared/worker-daemon/functions/handle-import.function.d.ts +14 -0
  71. package/dist/src/shared/worker-daemon/functions/handle-read-ops.function.d.ts +7 -1
  72. package/dist/src/shared/worker-daemon/functions/handle-write-ops.function.d.ts +9 -4
  73. package/dist/src/shared/worker-daemon/typings/handler-context.interface.d.ts +3 -0
  74. package/dist/wasm/fs-database/kbdb_fs_database.d.ts +16 -85
  75. package/dist/wasm/fs-database/kbdb_fs_database.js +16 -85
  76. package/dist/wasm/fs-database/kbdb_fs_database_bg.wasm +0 -0
  77. package/dist/wasm/kb-worker/kbdb_worker.d.ts +20 -115
  78. package/dist/wasm/kb-worker/kbdb_worker.js +20 -115
  79. package/dist/wasm/kb-worker/kbdb_worker_bg.wasm +0 -0
  80. package/dist/wasm/query-parser/kbdb_query_parser_bg.wasm +0 -0
  81. package/dist/worker.d.ts +8 -0
  82. package/dist/worker.mjs +606 -102
  83. package/dist/worker.mjs.map +4 -4
  84. package/docs/details/README.md +4 -0
  85. package/docs/details/agent-tooling.md +122 -0
  86. package/docs/details/cli.md +70 -13
  87. package/docs/details/knowledge-base.md +173 -0
  88. package/docs/details/library-api.md +42 -2
  89. package/docs/details/mcp-server.md +38 -7
  90. package/docs/details/search-and-ranking.md +11 -10
  91. package/docs/goals/cli.md +110 -34
  92. package/docs/goals/mcp.md +22 -19
  93. package/docs/goals/query-parser.md +8 -0
  94. package/docs/goals/worker-client.md +62 -1
  95. package/docs/goals/worker-daemon.md +52 -10
  96. package/docs/modules/typescript/cli.md +1 -1
  97. package/docs/modules/typescript/shared/cli/functions.md +116 -13
  98. package/docs/modules/typescript/shared/cli/module.md +33 -20
  99. package/docs/modules/typescript/shared/cli/typings.md +4 -0
  100. package/docs/modules/typescript/shared/embedding/functions.md +104 -25
  101. package/docs/modules/typescript/shared/mcp/module.md +1 -1
  102. package/docs/modules/typescript/shared/mcp/typings.md +8 -1
  103. package/docs/modules/typescript/shared/worker-client/module.md +9 -1
  104. package/docs/modules/typescript/shared/worker-client/typings.md +3 -0
  105. package/docs/modules/typescript/shared/worker-daemon/module.md +6 -3
  106. package/docs/overview.md +1 -2
  107. package/docs/release-notes/0.4.0.md +80 -0
  108. package/docs/release-notes/README.md +1 -0
  109. package/mod.ts +33 -15
  110. package/package.json +11 -10
  111. package/dist/chunk-JG2UCKLI.mjs +0 -95
  112. package/dist/chunk-JG2UCKLI.mjs.map +0 -7
  113. package/src/cli.ts +0 -71
  114. package/src/shared/auto-capture/classes/auto-capture-controller.class.ts +0 -62
  115. package/src/shared/auto-capture/constants/auto-capture-defaults.constant.ts +0 -15
  116. package/src/shared/auto-capture/functions/build-capture-prompt.function.ts +0 -27
  117. package/src/shared/auto-capture/functions/evaluate-trigger.function.ts +0 -50
  118. package/src/shared/auto-capture/index.ts +0 -7
  119. package/src/shared/auto-capture/typings/auto-capture-config.interface.ts +0 -13
  120. package/src/shared/auto-capture/typings/auto-capture-state.interface.ts +0 -13
  121. package/src/shared/auto-capture/typings/auto-capture-trigger.interface.ts +0 -7
  122. package/src/shared/cli/constants/defaults.constant.ts +0 -19
  123. package/src/shared/cli/constants/global-help.constant.ts +0 -73
  124. package/src/shared/cli/constants/help-text.constant.ts +0 -4
  125. package/src/shared/cli/constants/leaf-help.constant.ts +0 -219
  126. package/src/shared/cli/constants/memory-protocol-body.constant.ts +0 -39
  127. package/src/shared/cli/constants/query-guidance-body.constant.ts +0 -37
  128. package/src/shared/cli/constants/subcommand-help.constant.ts +0 -195
  129. package/src/shared/cli/functions/collect-files.function.ts +0 -55
  130. package/src/shared/cli/functions/compute-section-kbid.function.ts +0 -49
  131. package/src/shared/cli/functions/dispatch-command.function.ts +0 -390
  132. package/src/shared/cli/functions/ensure-db.function.ts +0 -21
  133. package/src/shared/cli/functions/error-to-message.function.ts +0 -9
  134. package/src/shared/cli/functions/find-db.function.ts +0 -20
  135. package/src/shared/cli/functions/format-mcp-output.function.ts +0 -41
  136. package/src/shared/cli/functions/format-output.function.ts +0 -95
  137. package/src/shared/cli/functions/format-text-output.function.ts +0 -42
  138. package/src/shared/cli/functions/generate-group-help.function.ts +0 -41
  139. package/src/shared/cli/functions/generate-help.function.ts +0 -654
  140. package/src/shared/cli/functions/handle-data-command.function.ts +0 -67
  141. package/src/shared/cli/functions/handle-mcp.function.ts +0 -56
  142. package/src/shared/cli/functions/handle-migrate.function.ts +0 -64
  143. package/src/shared/cli/functions/hydrate-search-previews.function.ts +0 -29
  144. package/src/shared/cli/functions/install-default-skills.function.ts +0 -296
  145. package/src/shared/cli/functions/is-stdin-tty.function.ts +0 -12
  146. package/src/shared/cli/functions/parse-args.function.ts +0 -156
  147. package/src/shared/cli/functions/prompt-user.function.ts +0 -36
  148. package/src/shared/cli/functions/resolve-skill-names.function.ts +0 -43
  149. package/src/shared/cli/functions/run-agent-create.function.ts +0 -114
  150. package/src/shared/cli/functions/run-agent-delete.function.ts +0 -47
  151. package/src/shared/cli/functions/run-agent-get.function.ts +0 -166
  152. package/src/shared/cli/functions/run-agent-list.function.ts +0 -58
  153. package/src/shared/cli/functions/run-check.function.ts +0 -159
  154. package/src/shared/cli/functions/run-cli.function.ts +0 -299
  155. package/src/shared/cli/functions/run-content.function.ts +0 -47
  156. package/src/shared/cli/functions/run-db-init.function.ts +0 -44
  157. package/src/shared/cli/functions/run-db-migrate.function.ts +0 -40
  158. package/src/shared/cli/functions/run-export.function.ts +0 -40
  159. package/src/shared/cli/functions/run-gc.function.ts +0 -51
  160. package/src/shared/cli/functions/run-init.function.ts +0 -93
  161. package/src/shared/cli/functions/run-learn.function.ts +0 -223
  162. package/src/shared/cli/functions/run-migrate.function.ts +0 -85
  163. package/src/shared/cli/functions/run-rebuild.function.ts +0 -47
  164. package/src/shared/cli/functions/run-recall.function.ts +0 -66
  165. package/src/shared/cli/functions/run-search.function.ts +0 -133
  166. package/src/shared/cli/functions/run-skill-delete.function.ts +0 -47
  167. package/src/shared/cli/functions/run-skill-get.function.ts +0 -90
  168. package/src/shared/cli/functions/run-skill-learn.function.ts +0 -70
  169. package/src/shared/cli/functions/run-skill-list.function.ts +0 -74
  170. package/src/shared/cli/functions/run-status.function.ts +0 -29
  171. package/src/shared/cli/functions/run-unlearn.function.ts +0 -58
  172. package/src/shared/cli/functions/version-gate.function.ts +0 -44
  173. package/src/shared/cli/functions/wrap-command.function.ts +0 -34
  174. package/src/shared/cli/index.ts +0 -55
  175. package/src/shared/cli/typings/agent-create-client.interface.ts +0 -47
  176. package/src/shared/cli/typings/agent-get-client.interface.ts +0 -39
  177. package/src/shared/cli/typings/check-client.interface.ts +0 -66
  178. package/src/shared/cli/typings/cli-deps.interface.ts +0 -54
  179. package/src/shared/cli/typings/cli-options.interface.ts +0 -72
  180. package/src/shared/cli/typings/command-result.model.ts +0 -15
  181. package/src/shared/cli/typings/disconnectable-client.interface.ts +0 -29
  182. package/src/shared/cli/typings/dispatch-client.type.ts +0 -46
  183. package/src/shared/cli/typings/learn-client.interface.ts +0 -53
  184. package/src/shared/cli/typings/learn-io.interface.ts +0 -5
  185. package/src/shared/cli/typings/learn-result.model.ts +0 -27
  186. package/src/shared/cli/typings/search-client.interface.ts +0 -73
  187. package/src/shared/cli/typings/search-display.model.ts +0 -54
  188. package/src/shared/dir-resolver/functions/join-path.function.ts +0 -13
  189. package/src/shared/dir-resolver/functions/resolve-base-dir.function.ts +0 -25
  190. package/src/shared/dir-resolver/functions/resolve-wasm-dir.function.ts +0 -5
  191. package/src/shared/dir-resolver/functions/resolve-worker-script.function.ts +0 -13
  192. package/src/shared/dir-resolver/index.ts +0 -11
  193. package/src/shared/dir-resolver/typings/base-dir.interface.ts +0 -4
  194. package/src/shared/embedding/classes/null-embedding-provider.class.ts +0 -29
  195. package/src/shared/embedding/constants/near-duplicate-thresholds.constant.ts +0 -17
  196. package/src/shared/embedding/functions/build-vector-index.function.ts +0 -79
  197. package/src/shared/embedding/functions/cosine-similarity.function.ts +0 -31
  198. package/src/shared/embedding/functions/detect-near-duplicates.function.ts +0 -69
  199. package/src/shared/embedding/functions/jaccard-coefficient.function.ts +0 -26
  200. package/src/shared/embedding/functions/read-vector-index-meta.function.ts +0 -44
  201. package/src/shared/embedding/functions/rrf-fuse.function.ts +0 -33
  202. package/src/shared/embedding/functions/search-vectors.function.ts +0 -59
  203. package/src/shared/embedding/index.ts +0 -20
  204. package/src/shared/embedding/typings/embedding-config.interface.ts +0 -23
  205. package/src/shared/embedding/typings/embedding-provider.interface.ts +0 -25
  206. package/src/shared/embedding/typings/near-duplicate-candidate.model.ts +0 -25
  207. package/src/shared/embedding/typings/near-duplicate-result.model.ts +0 -26
  208. package/src/shared/embedding/typings/vector-index-entry.model.ts +0 -13
  209. package/src/shared/embedding/typings/vector-index-meta.model.ts +0 -14
  210. package/src/shared/embedding/typings/vector-search-result.model.ts +0 -8
  211. package/src/shared/hash/functions/compute-sha256.ts +0 -17
  212. package/src/shared/hash/index.ts +0 -1
  213. package/src/shared/mcp/classes/mcp-server.class.ts +0 -480
  214. package/src/shared/mcp/constants/mcp-error-codes.constant.ts +0 -30
  215. package/src/shared/mcp/constants/tool-agent-create.constant.ts +0 -39
  216. package/src/shared/mcp/constants/tool-agent-delete.constant.ts +0 -26
  217. package/src/shared/mcp/constants/tool-agent-get.constant.ts +0 -24
  218. package/src/shared/mcp/constants/tool-agent-list.constant.ts +0 -18
  219. package/src/shared/mcp/constants/tool-auto-capture-review.constant.ts +0 -32
  220. package/src/shared/mcp/constants/tool-check.constant.ts +0 -21
  221. package/src/shared/mcp/constants/tool-content.constant.ts +0 -29
  222. package/src/shared/mcp/constants/tool-export.constant.ts +0 -27
  223. package/src/shared/mcp/constants/tool-gc.constant.ts +0 -21
  224. package/src/shared/mcp/constants/tool-learn.constant.ts +0 -58
  225. package/src/shared/mcp/constants/tool-rebuild.constant.ts +0 -21
  226. package/src/shared/mcp/constants/tool-recall.constant.ts +0 -36
  227. package/src/shared/mcp/constants/tool-retrieve.constant.ts +0 -31
  228. package/src/shared/mcp/constants/tool-search.constant.ts +0 -51
  229. package/src/shared/mcp/constants/tool-skill-delete.constant.ts +0 -24
  230. package/src/shared/mcp/constants/tool-skill-get.constant.ts +0 -27
  231. package/src/shared/mcp/constants/tool-skill-learn.constant.ts +0 -37
  232. package/src/shared/mcp/constants/tool-skill-list.constant.ts +0 -18
  233. package/src/shared/mcp/constants/tool-status.constant.ts +0 -20
  234. package/src/shared/mcp/constants/tool-unlearn.constant.ts +0 -25
  235. package/src/shared/mcp/functions/as-boolean-or-undefined.function.ts +0 -11
  236. package/src/shared/mcp/functions/as-string-array-or-undefined.function.ts +0 -17
  237. package/src/shared/mcp/functions/as-string-array.function.ts +0 -15
  238. package/src/shared/mcp/functions/as-string.function.ts +0 -10
  239. package/src/shared/mcp/functions/build-skills-text.function.ts +0 -43
  240. package/src/shared/mcp/functions/create-mcp-server.function.ts +0 -14
  241. package/src/shared/mcp/functions/create-prompt-definitions.function.ts +0 -102
  242. package/src/shared/mcp/functions/create-resource-templates.function.ts +0 -23
  243. package/src/shared/mcp/functions/create-tool-definitions.function.ts +0 -530
  244. package/src/shared/mcp/functions/extract-skill-arguments.function.ts +0 -27
  245. package/src/shared/mcp/functions/handle-agent-create.function.ts +0 -116
  246. package/src/shared/mcp/functions/handle-agent-delete.function.ts +0 -50
  247. package/src/shared/mcp/functions/handle-agent-get.function.ts +0 -160
  248. package/src/shared/mcp/functions/handle-agent-list.function.ts +0 -50
  249. package/src/shared/mcp/functions/handle-agent-prompt.function.ts +0 -68
  250. package/src/shared/mcp/functions/handle-completion.function.ts +0 -114
  251. package/src/shared/mcp/functions/handle-mcp-request.function.ts +0 -202
  252. package/src/shared/mcp/functions/handle-prompt-get.function.ts +0 -220
  253. package/src/shared/mcp/functions/handle-recall.function.ts +0 -66
  254. package/src/shared/mcp/functions/handle-resource-read.function.ts +0 -56
  255. package/src/shared/mcp/functions/handle-roots-list.function.ts +0 -29
  256. package/src/shared/mcp/functions/handle-skill-prompt.function.ts +0 -44
  257. package/src/shared/mcp/functions/handle-tool-auto-capture-review.function.ts +0 -24
  258. package/src/shared/mcp/functions/handle-tool-call.function.ts +0 -560
  259. package/src/shared/mcp/functions/handle-tool-check.function.ts +0 -21
  260. package/src/shared/mcp/functions/handle-tool-content.function.ts +0 -23
  261. package/src/shared/mcp/functions/handle-tool-export.function.ts +0 -25
  262. package/src/shared/mcp/functions/handle-tool-gc.function.ts +0 -21
  263. package/src/shared/mcp/functions/handle-tool-learn.function.ts +0 -69
  264. package/src/shared/mcp/functions/handle-tool-rebuild.function.ts +0 -21
  265. package/src/shared/mcp/functions/handle-tool-retrieve.function.ts +0 -40
  266. package/src/shared/mcp/functions/handle-tool-search.function.ts +0 -47
  267. package/src/shared/mcp/functions/handle-tool-skill-delete.function.ts +0 -34
  268. package/src/shared/mcp/functions/handle-tool-skill-get.function.ts +0 -59
  269. package/src/shared/mcp/functions/handle-tool-skill-learn.function.ts +0 -61
  270. package/src/shared/mcp/functions/handle-tool-skill-list.function.ts +0 -39
  271. package/src/shared/mcp/functions/handle-tool-status.function.ts +0 -21
  272. package/src/shared/mcp/functions/handle-tool-unlearn.function.ts +0 -24
  273. package/src/shared/mcp/functions/parse-agent-meta.function.ts +0 -27
  274. package/src/shared/mcp/functions/parse-skill-arguments.function.ts +0 -36
  275. package/src/shared/mcp/functions/parse-skill-content.function.ts +0 -38
  276. package/src/shared/mcp/functions/read-agent-meta.function.ts +0 -41
  277. package/src/shared/mcp/functions/resolve-skill-refs.function.ts +0 -50
  278. package/src/shared/mcp/functions/run-startup-health-check.function.ts +0 -34
  279. package/src/shared/mcp/functions/serialize-skill-content.function.ts +0 -12
  280. package/src/shared/mcp/functions/should-emit-log.function.ts +0 -38
  281. package/src/shared/mcp/index.ts +0 -28
  282. package/src/shared/mcp/typings/agent-types.interface.ts +0 -39
  283. package/src/shared/mcp/typings/log-types.interface.ts +0 -26
  284. package/src/shared/mcp/typings/mcp-capabilities.interface.ts +0 -16
  285. package/src/shared/mcp/typings/mcp-client.interface.ts +0 -317
  286. package/src/shared/mcp/typings/mcp-completion.interface.ts +0 -45
  287. package/src/shared/mcp/typings/mcp-content-result.model.ts +0 -9
  288. package/src/shared/mcp/typings/mcp-export-result.model.ts +0 -11
  289. package/src/shared/mcp/typings/mcp-gc-result.model.ts +0 -15
  290. package/src/shared/mcp/typings/mcp-integrity-check-result.model.ts +0 -17
  291. package/src/shared/mcp/typings/mcp-integrity-error.model.ts +0 -15
  292. package/src/shared/mcp/typings/mcp-notification.interface.ts +0 -9
  293. package/src/shared/mcp/typings/mcp-rebuild-result.model.ts +0 -9
  294. package/src/shared/mcp/typings/mcp-request.interface.ts +0 -11
  295. package/src/shared/mcp/typings/mcp-resource-result.interface.ts +0 -12
  296. package/src/shared/mcp/typings/mcp-resource-template.interface.ts +0 -11
  297. package/src/shared/mcp/typings/mcp-response.interface.ts +0 -18
  298. package/src/shared/mcp/typings/mcp-server-info.interface.ts +0 -7
  299. package/src/shared/mcp/typings/mcp-server-state.interface.ts +0 -17
  300. package/src/shared/mcp/typings/mcp-tool-annotations.interface.ts +0 -32
  301. package/src/shared/mcp/typings/mcp-tool-definition.interface.ts +0 -16
  302. package/src/shared/mcp/typings/mcp-tool-result.interface.ts +0 -19
  303. package/src/shared/mcp/typings/mcp-types.interface.ts +0 -158
  304. package/src/shared/mcp/typings/mcp-worker-client.interface.ts +0 -243
  305. package/src/shared/mcp/typings/prompt-types.interface.ts +0 -39
  306. package/src/shared/mcp/typings/remove-section-result.model.ts +0 -10
  307. package/src/shared/mcp/typings/sampling-types.interface.ts +0 -48
  308. package/src/shared/mcp/typings/skill-types.interface.ts +0 -29
  309. package/src/shared/mcp/typings/tool-call-result.model.ts +0 -18
  310. package/src/shared/mod.ts +0 -1
  311. package/src/shared/platform/functions/get-ipc-path.function.ts +0 -19
  312. package/src/shared/platform/functions/get-tmpdir.function.ts +0 -8
  313. package/src/shared/platform/functions/is-process-alive.function.ts +0 -17
  314. package/src/shared/platform/index.ts +0 -3
  315. package/src/shared/runtime/functions/detect-runtime.ts +0 -14
  316. package/src/shared/runtime/functions/get-args.ts +0 -16
  317. package/src/shared/runtime/index.ts +0 -3
  318. package/src/shared/runtime/typings/runtime.ts +0 -2
  319. package/src/shared/sync/functions/build-import-report.function.ts +0 -40
  320. package/src/shared/sync/functions/parse-export-entry.function.ts +0 -45
  321. package/src/shared/sync/functions/resolve-conflict.function.ts +0 -31
  322. package/src/shared/sync/functions/serialize-export-entry.function.ts +0 -18
  323. package/src/shared/sync/index.ts +0 -9
  324. package/src/shared/sync/typings/conflict-resolution.type.ts +0 -8
  325. package/src/shared/sync/typings/export-entry.interface.ts +0 -13
  326. package/src/shared/sync/typings/export-options.interface.ts +0 -9
  327. package/src/shared/sync/typings/import-options.interface.ts +0 -7
  328. package/src/shared/sync/typings/import-report.interface.ts +0 -15
  329. package/src/shared/version/constants/version.constant.ts +0 -2
  330. package/src/shared/version/index.ts +0 -1
  331. package/src/shared/wasm-codec/functions/decode-add-section-result.function.ts +0 -112
  332. package/src/shared/wasm-codec/functions/decode-compose-output.function.ts +0 -16
  333. package/src/shared/wasm-codec/functions/decode-document-manifest-list.function.ts +0 -70
  334. package/src/shared/wasm-codec/functions/decode-document-manifest.function.ts +0 -87
  335. package/src/shared/wasm-codec/functions/decode-f32.function.ts +0 -16
  336. package/src/shared/wasm-codec/functions/decode-key-value-text.function.ts +0 -15
  337. package/src/shared/wasm-codec/functions/decode-one-recall-result.function.ts +0 -86
  338. package/src/shared/wasm-codec/functions/decode-option-string.function.ts +0 -24
  339. package/src/shared/wasm-codec/functions/decode-recall-document.function.ts +0 -59
  340. package/src/shared/wasm-codec/functions/decode-recall-reference.function.ts +0 -52
  341. package/src/shared/wasm-codec/functions/decode-recall-result.function.ts +0 -267
  342. package/src/shared/wasm-codec/functions/decode-recall-sibling.function.ts +0 -43
  343. package/src/shared/wasm-codec/functions/decode-remove-flag.function.ts +0 -3
  344. package/src/shared/wasm-codec/functions/decode-scored-results.function.ts +0 -194
  345. package/src/shared/wasm-codec/functions/decode-section-match.function.ts +0 -80
  346. package/src/shared/wasm-codec/functions/decode-section-record-list.function.ts +0 -20
  347. package/src/shared/wasm-codec/functions/decode-section-record-trailing.function.ts +0 -75
  348. package/src/shared/wasm-codec/functions/decode-section-record.function.ts +0 -85
  349. package/src/shared/wasm-codec/functions/decode-section-records.function.ts +0 -249
  350. package/src/shared/wasm-codec/functions/decode-section-type.function.ts +0 -30
  351. package/src/shared/wasm-codec/functions/decode-string.function.ts +0 -22
  352. package/src/shared/wasm-codec/functions/decode-u32.function.ts +0 -16
  353. package/src/shared/wasm-codec/functions/decode-u64.function.ts +0 -16
  354. package/src/shared/wasm-codec/functions/decode-wasm-list.function.ts +0 -31
  355. package/src/shared/wasm-codec/functions/encode-add-section-params.function.ts +0 -102
  356. package/src/shared/wasm-codec/functions/encode-group-params.function.ts +0 -28
  357. package/src/shared/wasm-codec/functions/encode-identifier-list.function.ts +0 -17
  358. package/src/shared/wasm-codec/functions/encode-kbid-list.function.ts +0 -17
  359. package/src/shared/wasm-codec/functions/encode-option-string.function.ts +0 -14
  360. package/src/shared/wasm-codec/functions/encode-recall-params.function.ts +0 -68
  361. package/src/shared/wasm-codec/functions/encode-search-params.function.ts +0 -12
  362. package/src/shared/wasm-codec/functions/encode-section-type.function.ts +0 -18
  363. package/src/shared/wasm-codec/functions/encode-string.function.ts +0 -9
  364. package/src/shared/wasm-codec/functions/encode-type-filter-param.function.ts +0 -13
  365. package/src/shared/wasm-codec/functions/encode-u32.function.ts +0 -5
  366. package/src/shared/wasm-codec/functions/encode-update-section-params.function.ts +0 -16
  367. package/src/shared/wasm-codec/index.ts +0 -49
  368. package/src/shared/wasm-codec/typings/add-section-input.model.ts +0 -45
  369. package/src/shared/wasm-codec/typings/add-section-result.model.ts +0 -28
  370. package/src/shared/wasm-codec/typings/document-manifest.model.ts +0 -20
  371. package/src/shared/wasm-codec/typings/document-section.model.ts +0 -12
  372. package/src/shared/wasm-codec/typings/item-decoder.type.ts +0 -10
  373. package/src/shared/wasm-codec/typings/near-duplicate.model.ts +0 -16
  374. package/src/shared/wasm-codec/typings/paged-search-result.model.ts +0 -22
  375. package/src/shared/wasm-codec/typings/section-match.model.ts +0 -31
  376. package/src/shared/wasm-codec/typings/section-record-trailing.model.ts +0 -38
  377. package/src/shared/wasm-codec/typings/section-record.model.ts +0 -66
  378. package/src/shared/wasm-codec/typings/section-type-result.model.ts +0 -12
  379. package/src/shared/worker-client/classes/worker-client.class.ts +0 -466
  380. package/src/shared/worker-client/functions/compute-context-id.function.ts +0 -18
  381. package/src/shared/worker-client/functions/create-worker-client.function.ts +0 -70
  382. package/src/shared/worker-client/functions/discover-daemon.function.ts +0 -47
  383. package/src/shared/worker-client/functions/handle-ipc-data.function.ts +0 -49
  384. package/src/shared/worker-client/functions/resolve-db-path.function.ts +0 -21
  385. package/src/shared/worker-client/functions/send-ipc-request.function.ts +0 -39
  386. package/src/shared/worker-client/functions/spawn-daemon.function.ts +0 -35
  387. package/src/shared/worker-client/functions/wait-for-daemon.function.ts +0 -34
  388. package/src/shared/worker-client/index.ts +0 -44
  389. package/src/shared/worker-client/typings/add-section-result.model.ts +0 -39
  390. package/src/shared/worker-client/typings/content-result.model.ts +0 -12
  391. package/src/shared/worker-client/typings/daemon-info.model.ts +0 -7
  392. package/src/shared/worker-client/typings/export-result.model.ts +0 -14
  393. package/src/shared/worker-client/typings/gc-result.model.ts +0 -18
  394. package/src/shared/worker-client/typings/integrity-check-result.model.ts +0 -43
  395. package/src/shared/worker-client/typings/json-rpc-response.interface.ts +0 -17
  396. package/src/shared/worker-client/typings/migrate-result.model.ts +0 -11
  397. package/src/shared/worker-client/typings/pending-call.interface.ts +0 -7
  398. package/src/shared/worker-client/typings/rebuild-result.model.ts +0 -12
  399. package/src/shared/worker-client/typings/recall-document.model.ts +0 -16
  400. package/src/shared/worker-client/typings/recall-params.model.ts +0 -15
  401. package/src/shared/worker-client/typings/recall-reference.model.ts +0 -32
  402. package/src/shared/worker-client/typings/recall-result.model.ts +0 -98
  403. package/src/shared/worker-client/typings/recall-sibling.model.ts +0 -11
  404. package/src/shared/worker-client/typings/recall-single-result.model.ts +0 -41
  405. package/src/shared/worker-client/typings/remove-section-result.model.ts +0 -7
  406. package/src/shared/worker-client/typings/search-params.model.ts +0 -14
  407. package/src/shared/worker-client/typings/search-result.model.ts +0 -43
  408. package/src/shared/worker-client/typings/section.model.ts +0 -43
  409. package/src/shared/worker-client/typings/status-result.model.ts +0 -14
  410. package/src/shared/worker-client/typings/version-status.model.ts +0 -28
  411. package/src/shared/worker-client/typings/worker-client-error.interface.ts +0 -8
  412. package/src/shared/worker-client/typings/worker-client-options.interface.ts +0 -30
  413. package/src/shared/worker-daemon/classes/ipc-error.class.ts +0 -22
  414. package/src/shared/worker-daemon/classes/worker-daemon.class.ts +0 -1291
  415. package/src/shared/worker-daemon/constants/daemon-defaults.constant.ts +0 -29
  416. package/src/shared/worker-daemon/constants/wasm-method-map.constant.ts +0 -69
  417. package/src/shared/worker-daemon/functions/build-ipc-error-response.function.ts +0 -16
  418. package/src/shared/worker-daemon/functions/check-catalog-version.function.ts +0 -54
  419. package/src/shared/worker-daemon/functions/check-preconditions.function.ts +0 -28
  420. package/src/shared/worker-daemon/functions/create-host-imports.function.ts +0 -328
  421. package/src/shared/worker-daemon/functions/create-ipc-server.function.ts +0 -87
  422. package/src/shared/worker-daemon/functions/detect-stale-pid.function.ts +0 -33
  423. package/src/shared/worker-daemon/functions/dispatch-request.function.ts +0 -190
  424. package/src/shared/worker-daemon/functions/handle-check-version.function.ts +0 -74
  425. package/src/shared/worker-daemon/functions/handle-config-method.function.ts +0 -27
  426. package/src/shared/worker-daemon/functions/handle-read-ops.function.ts +0 -236
  427. package/src/shared/worker-daemon/functions/handle-write-ops.function.ts +0 -257
  428. package/src/shared/worker-daemon/functions/load-wasm-modules.function.ts +0 -95
  429. package/src/shared/worker-daemon/functions/parse-auto-capture-section.function.ts +0 -51
  430. package/src/shared/worker-daemon/functions/parse-catalog-version.function.ts +0 -20
  431. package/src/shared/worker-daemon/functions/parse-embedding-section.function.ts +0 -38
  432. package/src/shared/worker-daemon/functions/parse-worker-toml.function.ts +0 -104
  433. package/src/shared/worker-daemon/functions/read-config.function.ts +0 -83
  434. package/src/shared/worker-daemon/functions/run-startup-integrity-check.function.ts +0 -55
  435. package/src/shared/worker-daemon/functions/run-worker.function.ts +0 -57
  436. package/src/shared/worker-daemon/functions/scan-near-duplicates.function.ts +0 -92
  437. package/src/shared/worker-daemon/functions/start-daemon.function.ts +0 -74
  438. package/src/shared/worker-daemon/functions/wasm-bridge.function.ts +0 -144
  439. package/src/shared/worker-daemon/functions/wasm-memory-helpers.function.ts +0 -41
  440. package/src/shared/worker-daemon/functions/write-lock.function.ts +0 -49
  441. package/src/shared/worker-daemon/index.ts +0 -16
  442. package/src/shared/worker-daemon/typings/allocator-ref.interface.ts +0 -16
  443. package/src/shared/worker-daemon/typings/daemon-config.interface.ts +0 -20
  444. package/src/shared/worker-daemon/typings/fs-adapter.interface.ts +0 -22
  445. package/src/shared/worker-daemon/typings/handler-context.interface.ts +0 -19
  446. package/src/shared/worker-daemon/typings/ipc-handler.interface.ts +0 -39
  447. package/src/shared/worker-daemon/typings/memory-ref.interface.ts +0 -13
  448. package/src/shared/worker-daemon/typings/wasm-fn.type.ts +0 -2
  449. package/src/shared/worker-daemon/typings/wasm-modules.interface.ts +0 -7
  450. package/src/shared/worker-daemon/typings/write-lock.interface.ts +0 -13
  451. package/src/wasm/fs-database/kbdb_fs_database.d.ts +0 -259
  452. package/src/wasm/fs-database/kbdb_fs_database.js +0 -515
  453. package/src/wasm/fs-database/kbdb_fs_database_bg.wasm +0 -0
  454. package/src/wasm/fs-database/kbdb_fs_database_bg.wasm.d.ts +0 -35
  455. package/src/wasm/fs-database/package.json +0 -13
  456. package/src/wasm/kb-worker/kbdb_worker.d.ts +0 -650
  457. package/src/wasm/kb-worker/kbdb_worker.js +0 -1181
  458. package/src/wasm/kb-worker/kbdb_worker_bg.wasm +0 -0
  459. package/src/wasm/kb-worker/kbdb_worker_bg.wasm.d.ts +0 -77
  460. package/src/wasm/kb-worker/package.json +0 -13
  461. package/src/wasm/query-parser/kbdb_query_parser.d.ts +0 -195
  462. package/src/wasm/query-parser/kbdb_query_parser.js +0 -403
  463. package/src/wasm/query-parser/kbdb_query_parser_bg.wasm +0 -0
  464. package/src/wasm/query-parser/kbdb_query_parser_bg.wasm.d.ts +0 -25
  465. package/src/wasm/query-parser/package.json +0 -13
  466. package/src/worker.ts +0 -42
package/dist/cli.cjs.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/shared/runtime/functions/detect-runtime.ts", "../src/shared/runtime/functions/get-args.ts", "../src/shared/dir-resolver/functions/resolve-base-dir.function.ts", "../src/shared/dir-resolver/functions/join-path.function.ts", "../src/shared/dir-resolver/functions/resolve-worker-script.function.ts", "../src/shared/cli/constants/defaults.constant.ts", "../src/shared/cli/functions/parse-args.function.ts", "../src/shared/cli/functions/format-output.function.ts", "../src/shared/cli/functions/run-search.function.ts", "../src/shared/cli/functions/run-recall.function.ts", "../src/shared/cli/functions/run-export.function.ts", "../src/shared/cli/functions/run-learn.function.ts", "../src/shared/cli/functions/run-unlearn.function.ts", "../src/shared/cli/functions/run-content.function.ts", "../src/shared/cli/functions/run-check.function.ts", "../src/shared/cli/functions/run-gc.function.ts", "../src/shared/cli/functions/run-rebuild.function.ts", "../src/shared/cli/functions/find-db.function.ts", "../src/shared/cli/functions/run-init.function.ts", "../src/shared/cli/functions/install-default-skills.function.ts", "../src/shared/cli/functions/error-to-message.function.ts", "../src/shared/cli/functions/is-stdin-tty.function.ts", "../src/shared/cli/functions/prompt-user.function.ts", "../src/shared/cli/functions/run-status.function.ts", "../src/shared/cli/functions/run-db-init.function.ts", "../src/shared/cli/functions/run-db-migrate.function.ts", "../src/shared/mcp/functions/extract-skill-arguments.function.ts", "../src/shared/mcp/functions/serialize-skill-content.function.ts", "../src/shared/cli/functions/run-skill-learn.function.ts", "../src/shared/cli/functions/run-skill-list.function.ts", "../src/shared/mcp/functions/parse-skill-content.function.ts", "../src/shared/cli/functions/run-skill-get.function.ts", "../src/shared/cli/functions/run-skill-delete.function.ts", "../src/shared/cli/functions/run-agent-create.function.ts", "../src/shared/cli/functions/run-agent-list.function.ts", "../src/shared/cli/functions/run-agent-get.function.ts", "../src/shared/cli/functions/run-agent-delete.function.ts", "../src/shared/cli/functions/dispatch-command.function.ts", "../src/shared/version/constants/version.constant.ts", "../src/shared/cli/functions/generate-help.function.ts", "../src/shared/cli/functions/run-cli.function.ts", "../src/shared/cli/constants/help-text.constant.ts", "../src/shared/worker-client/classes/worker-client.class.ts", "../src/shared/worker-client/functions/create-worker-client.function.ts", "../src/shared/worker-client/functions/resolve-db-path.function.ts", "../src/shared/hash/functions/compute-sha256.ts", "../src/shared/worker-client/functions/compute-context-id.function.ts", "../src/shared/worker-client/functions/discover-daemon.function.ts", "../src/shared/platform/functions/is-process-alive.function.ts", "../src/shared/worker-client/functions/spawn-daemon.function.ts", "../src/shared/worker-client/functions/wait-for-daemon.function.ts", "../src/shared/platform/functions/get-ipc-path.function.ts", "../src/shared/platform/functions/get-tmpdir.function.ts", "../src/shared/mcp/classes/mcp-server.class.ts", "../src/shared/mcp/functions/create-tool-definitions.function.ts", "../src/shared/mcp/functions/create-resource-templates.function.ts", "../src/shared/mcp/functions/handle-agent-create.function.ts", "../src/shared/mcp/functions/handle-agent-list.function.ts", "../src/shared/mcp/functions/handle-agent-get.function.ts", "../src/shared/mcp/functions/handle-agent-delete.function.ts", "../src/shared/mcp/functions/handle-recall.function.ts", "../src/shared/mcp/functions/handle-tool-call.function.ts", "../src/shared/mcp/functions/handle-resource-read.function.ts", "../src/shared/mcp/functions/create-prompt-definitions.function.ts", "../src/shared/mcp/functions/handle-prompt-get.function.ts", "../src/shared/mcp/functions/handle-completion.function.ts", "../src/shared/mcp/functions/handle-roots-list.function.ts", "../src/shared/mcp/functions/should-emit-log.function.ts", "../src/shared/mcp/constants/mcp-error-codes.constant.ts", "../src/shared/mcp/functions/create-mcp-server.function.ts", "../src/cli.ts"],
4
- "sourcesContent": ["import type { Runtime } from '../typings/runtime.ts';\n\n/**\n * Detects the current JavaScript runtime environment.\n *\n * Returns `'deno'` when the global `Deno` object is present,\n * otherwise returns `'node'`.\n */\nexport function detectRuntime(): Runtime {\n if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {\n return 'deno';\n }\n return 'node';\n}\n", "import { detectRuntime } from './detect-runtime.ts';\n\n/**\n * Returns the command-line arguments for the current runtime.\n *\n * In Deno, reads `Deno.args`; in Node.js, slices `process.argv`\n * past the interpreter and script entries.\n */\nexport function getArgs(): string[] {\n if (detectRuntime() === 'deno') {\n const g = globalThis as Record<string, unknown>;\n const deno = g['Deno'] as { args: string[] } | undefined;\n return deno?.args ?? [];\n }\n return process.argv.slice(2);\n}\n", "import { dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { BaseDir } from '../typings/base-dir.interface.ts';\n\nexport function resolveScriptDir(\n entryUrl: string,\n entryDirname?: string,\n): string {\n if (entryDirname) return entryDirname;\n if (entryUrl.startsWith('file:'))\n return dirname(fileURLToPath(entryUrl));\n return dirname(entryUrl);\n}\n\nexport function resolveBaseDir(\n entryUrl: string,\n entryDirname?: string,\n): BaseDir {\n const scriptDir =\n typeof __dirname !== 'undefined'\n ? __dirname\n : resolveScriptDir(entryUrl, entryDirname);\n return { scriptDir, cwd: process.cwd() };\n}\n", "import { join } from 'node:path';\n\nexport function isRemoteUrl(path: string): boolean {\n return path.startsWith('http://') || path.startsWith('https://');\n}\n\nexport function joinPath(base: string, ...segments: string[]): string {\n if (isRemoteUrl(base)) {\n const trailing = base.endsWith('/') ? '' : '/';\n return base + trailing + segments.join('/');\n }\n return join(base, ...segments);\n}\n", "import { joinPath } from './join-path.function.ts';\n\nimport type { Runtime } from '../../runtime/typings/runtime.ts';\n\nexport function resolveWorkerScript(\n scriptDir: string,\n runtime: Runtime,\n): string {\n if (runtime === 'deno') {\n return joinPath(scriptDir, 'worker.ts');\n }\n return joinPath(scriptDir, 'kbdb-worker.cjs');\n}\n", "/** Default maximum number of search results returned per query. */\nexport const DEFAULT_LIMIT = 20;\n\n/** Default output format when `--format` is not specified. */\nexport const DEFAULT_FORMAT = 'json' as const;\n\n/** Default search mode when `--mode` is not specified. */\nexport const DEFAULT_MODE = 'sections' as const;\n\n/**\n * File extensions recognised as importable documents by the learn\n * command. Extensions are lowercase and include the leading dot.\n */\nexport const SUPPORTED_EXTENSIONS = [\n '.md',\n '.txt',\n '.rst',\n '.adoc',\n] as const;\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport {\n DEFAULT_FORMAT,\n DEFAULT_LIMIT,\n DEFAULT_MODE,\n} from '../constants/defaults.constant.ts';\n\n/**\n * Parses a raw argument vector into a structured `CliOptions` object.\n *\n * Recognises `--help` / `-h` and `--version` / `-v` as early-exit\n * flags that set the command and return immediately. All other flags\n * consume the next token as their value. The first non-flag token\n * becomes the command; subsequent non-flag tokens become `args`.\n *\n * Compound commands are supported: when the first positional token is\n * a group name (`db`, `skill`, or `agent`), the next positional token\n * is joined with a hyphen to form the compound command\n * (e.g. `db init` \u2192 `'db-init'`).\n *\n * Context-aware `--help`: when `--help` or `-h` appears after a\n * command has been set, the existing command is moved to `args[0]`\n * and the command is set to `'help'`, enabling per-command help.\n *\n * Deprecated flags `--init` and `--migrate` emit a warning to stderr\n * before setting the corresponding command.\n *\n * @param argv - argument strings (typically `process.argv.slice(2)`)\n * @returns fully populated `CliOptions` with defaults applied\n */\nexport function parseArgs(argv: string[]): CliOptions {\n const options: CliOptions = {\n command: '',\n format: DEFAULT_FORMAT,\n mode: DEFAULT_MODE,\n limit: DEFAULT_LIMIT,\n args: [],\n };\n\n let i = 0;\n while (i < argv.length) {\n const arg = argv[i];\n switch (arg) {\n case '--help':\n case '-h':\n if (options.command) {\n options.args.unshift(options.command);\n options.command = 'help';\n } else {\n options.command = 'help';\n }\n return options;\n case '--version':\n case '-v':\n options.command = 'version';\n return options;\n case '--init':\n // eslint-disable-next-line no-console\n console.error(\n 'warning: --init is deprecated,' + ' use \"kbdb db init\"',\n );\n options.command = 'init';\n break;\n case '--migrate':\n // eslint-disable-next-line no-console\n console.error(\n 'warning: --migrate is deprecated,' +\n ' use \"kbdb db migrate\"',\n );\n options.command = 'migrate';\n break;\n case '--db':\n options.dbPath = argv[++i];\n break;\n case '--format':\n case '-f':\n options.format = (argv[++i] ??\n DEFAULT_FORMAT) as CliOptions['format'];\n break;\n case '--mode':\n case '-m':\n options.mode = (argv[++i] ??\n DEFAULT_MODE) as CliOptions['mode'];\n break;\n case '--limit':\n case '-l':\n options.limit =\n parseInt(argv[++i] ?? '', 10) || DEFAULT_LIMIT;\n break;\n case '--offset':\n case '-o':\n options.offset = Math.max(\n 0,\n parseInt(argv[++i] ?? '', 10) || 0,\n );\n break;\n case '--algo':\n options.algo = argv[++i];\n break;\n case '--title':\n options.title = argv[++i];\n break;\n case '--description':\n options.description = argv[++i];\n break;\n case '--docid':\n options.docid = argv[++i];\n break;\n case '--name':\n options.name = argv[++i];\n break;\n case '--persona':\n options.persona = argv[++i];\n break;\n case '--body':\n options.body = argv[++i];\n break;\n case '--skills':\n options.skills = (argv[++i] ?? '').split(',');\n break;\n case '--tags':\n options.tags = (argv[++i] ?? '').split(',');\n break;\n case '--replace':\n options.replace = true;\n break;\n case '--depth':\n case '-d':\n options.depth = Math.min(\n 3,\n Math.max(0, parseInt(argv[++i] ?? '', 10) || 0),\n );\n break;\n case '--content':\n case '-c':\n options.content = true;\n break;\n default:\n if (!options.command) {\n options.command = arg;\n } else if (\n !options.args.length &&\n (options.command === 'db' ||\n options.command === 'skill' ||\n options.command === 'agent')\n ) {\n options.command = `${options.command}-${arg}`;\n } else {\n options.args.push(arg);\n }\n }\n i++;\n }\n\n return options;\n}\n", "import type { OutputFormat } from '../typings/cli-options.interface.ts';\nimport type { PagedSearchDisplay } from '../typings/search-display.model.ts';\n\n/**\n * Serialises a paged search result into the requested output\n * format string.\n *\n * - `'json'` -- pretty-printed JSON envelope\n * - `'text'` -- numbered human-readable list with paging footer\n * - `'mcp'` -- JSON envelope compatible with MCP protocol\n *\n * @param paged - paginated search results to format\n * @param format - target output format\n * @returns formatted string ready for stdout\n */\nexport function formatOutput(\n paged: PagedSearchDisplay,\n format: OutputFormat,\n): string {\n switch (format) {\n case 'json':\n return JSON.stringify(paged, null, 2);\n case 'text':\n return formatText(paged);\n case 'mcp':\n return formatMcp(paged);\n }\n}\n\nfunction formatText(paged: PagedSearchDisplay): string {\n if (paged.items.length === 0) return 'No results found.';\n const start = paged.offset + 1;\n const end = paged.offset + paged.items.length;\n\n const lines = paged.items\n .map((r, i) => {\n const num = paged.offset + i + 1;\n const heading = r.heading ?? '(untitled)';\n const terms = r.matched_terms.join(', ');\n const fields = r.matched_fields.join(', ');\n const confidencePct = (r.confidence * 100).toFixed(0);\n return (\n `${String(num)}. [${r.kbid}] ${heading}` +\n ` (score: ${r.score.toFixed(4)},` +\n ` confidence: ${confidencePct}%)\\n` +\n ` ${r.snippet || r.preview || '(no snippet)'}\\n` +\n ` type: ${r.type}` +\n ` terms: ${terms}` +\n (fields ? ` fields: ${fields}` : '')\n );\n })\n .join('\\n\\n');\n\n const footer =\n `\\nShowing ${String(start)}-${String(end)}` +\n ` of ${String(paged.total)} results`;\n const hint = paged.has_more\n ? `\\nUse --offset ${String(end)} to see more`\n : '';\n\n return lines + footer + hint;\n}\n\nfunction formatMcp(paged: PagedSearchDisplay): string {\n const mcpItems = paged.items.map((r) => ({\n kbid: r.kbid,\n heading: r.heading,\n type: r.type,\n docids: r.docids,\n snippet: r.snippet,\n matched_terms: r.matched_terms,\n matched_fields: r.matched_fields,\n created_at: r.created_at,\n }));\n return JSON.stringify(\n {\n type: 'text',\n text: paged.items\n .map(\n (r) =>\n `[${r.kbid}] ${r.heading ?? '(untitled)'}` +\n ` \u2014 ${r.snippet || r.preview}`,\n )\n .join('\\n'),\n items: mcpItems,\n total: paged.total,\n offset: paged.offset,\n limit: paged.limit,\n has_more: paged.has_more,\n relaxed: paged.relaxed,\n },\n null,\n 2,\n );\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { PagedSearchDisplay } from '../typings/search-display.model.ts';\n\n/** A single raw search result item returned by the daemon. */\ninterface RawSearchItem {\n /** Knowledge-base identifier of the matched section. */\n readonly kbid: string;\n /** Section heading, or null when untitled. */\n readonly heading: string | null;\n /** MIME type of the section content. */\n readonly type: string;\n /** Document IDs this section belongs to. */\n readonly docids: readonly string[];\n /** Relevance score from the ranking engine. */\n readonly score: number;\n /** KWIC excerpt centered on the highest-scoring matched term. */\n readonly snippet: string;\n /** Query terms that matched within this section. */\n readonly matched_terms: readonly string[];\n /**\n * Fields that contained at least one match.\n * May be absent from older daemon versions.\n */\n readonly matched_fields?: readonly string[];\n /**\n * Normalised confidence score (0.0-1.0) relative to the top result.\n * May be absent from older daemon versions.\n */\n readonly confidence?: number;\n /**\n * ISO 8601 creation timestamp of the section.\n * May be absent from older daemon versions.\n */\n readonly created_at?: string;\n}\n\n/** Raw paginated search response from the daemon. */\ninterface RawSearchResponse {\n /** Result items for the current page. */\n readonly items: readonly RawSearchItem[];\n /** Total number of matches across all pages. */\n readonly total: number;\n /** Number of results skipped. */\n readonly offset: number;\n /** Maximum results per page. */\n readonly limit: number;\n /** Whether more results exist beyond this page. */\n readonly has_more: boolean;\n /**\n * When `true`, the engine relaxed the query to produce results.\n * May be absent from older daemon versions.\n */\n readonly relaxed?: boolean;\n}\n\n/**\n * Minimal client interface required by `runSearch`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface SearchClient {\n /**\n * Searches the knowledge base and returns paginated results.\n *\n * @param params - query, mode, limit, and offset\n */\n search(params: {\n query: string;\n mode?: string;\n limit?: number;\n offset?: number;\n algo?: string;\n }): Promise<RawSearchResponse>;\n}\n\n/**\n * Executes a search query via the provided client and maps the\n * daemon results to the `PagedSearchDisplay` format used by the\n * CLI.\n *\n * Returns an empty paged result without calling the client when\n * `options.args` contains no query terms.\n *\n * @param client - search client to delegate to\n * @param options - parsed CLI options supplying query args and\n * search parameters\n */\nexport async function runSearch(\n client: SearchClient,\n options: CliOptions,\n): Promise<PagedSearchDisplay> {\n const query = options.args.join(' ').trim();\n if (!query) {\n return {\n items: [],\n total: 0,\n offset: 0,\n limit: options.limit,\n has_more: false,\n relaxed: false,\n };\n }\n\n const results = await client.search({\n query,\n mode: options.mode,\n limit: options.limit,\n offset: options.offset,\n algo: options.algo,\n });\n\n return {\n items: results.items.map((r) => ({\n kbid: r.kbid,\n heading: r.heading,\n type: r.type,\n docids: r.docids,\n score: r.score,\n confidence: r.confidence ?? 0,\n snippet: r.snippet,\n matched_terms: r.matched_terms,\n matched_fields: r.matched_fields ?? [],\n created_at: r.created_at ?? '',\n preview: '',\n })),\n total: results.total,\n offset: results.offset,\n limit: results.limit,\n has_more: results.has_more,\n relaxed: results.relaxed ?? false,\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { RecallResult } from '../../worker-client/typings/recall-result.model.ts';\n\n/** Maximum allowed expansion depth for recall operations. */\nconst MAX_RECALL_DEPTH = 3;\n\n/**\n * Minimal client interface required by `runRecall`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface RecallClient {\n /**\n * Retrieves full content and context for one or more sections\n * by their knowledge-base identifiers.\n *\n * @param params - section identifier(s) and optional expansion\n * depth (0--3)\n * @returns a single `RecallResult` when `kbid` is supplied, or\n * a `RecallResult[]` when `kbids` is supplied\n */\n recall(params: {\n kbid?: string;\n kbids?: string[];\n depth?: number;\n }): Promise<RecallResult | RecallResult[]>;\n}\n\n/**\n * Retrieves full content and progressive context for one or more\n * sections by kbid via the provided client.\n *\n * Returns an error result when no kbids are provided in\n * `options.args`. For a single kbid, calls `client.recall` with the\n * `kbid` parameter and returns the single `RecallResult`. For\n * multiple kbids, calls `client.recall` with the `kbids` array.\n *\n * The `depth` option is read from `options.depth`, defaulting to 0\n * and clamped to the range 0--3.\n *\n * @param client - recall client to delegate to\n * @param options - parsed CLI options supplying kbids in `args` and\n * expansion depth in `depth`\n * @returns the `RecallResult` or `RecallResult[]` from the client,\n * or an error object when no kbids are provided\n */\nexport async function runRecall(\n client: RecallClient,\n options: CliOptions,\n): Promise<RecallResult | RecallResult[] | { error: string }> {\n if (options.args.length === 0) {\n return { error: 'no kbid provided' };\n }\n\n const depth = Math.min(\n MAX_RECALL_DEPTH,\n Math.max(0, options.depth ?? 0),\n );\n\n if (options.args.length === 1) {\n return client.recall({ kbid: options.args[0], depth });\n }\n\n return client.recall({ kbids: options.args, depth });\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { ExportResult } from '../../worker-client/typings/export-result.model.ts';\n\n/**\n * Minimal client interface required by `runExport`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface ExportClient {\n /**\n * Exports the database to the given directory path.\n *\n * @param params - optional target path; the daemon defaults to\n * `./kbdb-export/` when `path` is `undefined`\n * @returns export report with the resolved path and file counts\n */\n export(params: { path?: string }): Promise<ExportResult>;\n}\n\n/**\n * Exports the knowledge-base database to a target directory via the\n * provided client.\n *\n * The target path is taken from `options.args[0]`. When no argument\n * is given the daemon resolves its own default (`./kbdb-export/`).\n *\n * @param client - export client to delegate to\n * @param options - parsed CLI options whose first positional\n * argument, if present, is the target directory path\n * @returns the export result containing the resolved path and file\n * counts\n */\nexport async function runExport(\n client: ExportClient,\n options: CliOptions,\n): Promise<ExportResult> {\n const path = options.args[0];\n return client.export({ path });\n}\n", "import { readFileSync, readdirSync, statSync } from 'node:fs';\nimport { basename, extname, join } from 'node:path';\nimport type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { LearnResult } from '../typings/learn-result.model.ts';\nimport { SUPPORTED_EXTENSIONS } from '../constants/defaults.constant.ts';\n\n/** Enriched add-section result returned by the daemon. */\ninterface AddSectionResult {\n /** Knowledge-base identifier assigned to the new section. */\n readonly kbid: string;\n /**\n * Kbid of the section superseded via `--replace`,\n * or `null` / `undefined` when none.\n */\n readonly superseded?: string | null;\n /**\n * Advisory warning strings (e.g. `\"heading_missing\"`).\n * May be absent from older daemon versions.\n */\n readonly warnings?: string[];\n /**\n * Near-duplicate sections with similarity >= 0.85.\n * May be absent from older daemon versions.\n */\n readonly near_duplicates?: {\n readonly kbid: string;\n readonly similarity: number;\n }[];\n}\n\n/**\n * Minimal client interface required by `runLearn`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface LearnClient {\n /**\n * Ingests a content section into the knowledge base.\n *\n * @param params - section metadata and raw text content\n * @returns enriched result containing the new kbid plus\n * optional supersession, warnings, and near-duplicate info\n */\n addSection(params: {\n sectionType: string;\n content: string;\n title?: string;\n description?: string;\n docid?: string;\n tags?: string[];\n replace?: boolean;\n /**\n * Absolute path to the source file. Required for supersession\n * via source key when `replace` is `true`.\n */\n sourcePath?: string;\n }): Promise<AddSectionResult>;\n}\n\n/** Injectable I/O for testing without real stdin. */\nexport interface LearnIO {\n readStdin: () => Promise<string>;\n}\n\n/**\n * Ingests one or more files or directories listed in `options.args`\n * into the knowledge base via the provided client.\n *\n * Each argument is resolved to a set of supported files. Unsupported\n * extensions, dotfiles, dot-directories, and non-existent paths are\n * silently skipped. The `-` argument reads content from stdin\n * (consumed only once).\n *\n * @param client - learn client to delegate ingestion to\n * @param options - parsed CLI options whose `args` list targets to\n * ingest\n * @param io - injectable I/O (defaults to reading process.stdin)\n * @returns one `LearnResult` per file successfully ingested\n */\nexport async function runLearn(\n client: LearnClient,\n options: CliOptions,\n io?: LearnIO,\n): Promise<LearnResult[]> {\n const results: LearnResult[] = [];\n let stdinConsumed = false;\n const readStdin = io?.readStdin ?? readProcessStdin;\n\n for (const target of options.args) {\n if (target === '-') {\n if (stdinConsumed) continue;\n stdinConsumed = true;\n const content = await readStdin();\n const result = await client.addSection({\n sectionType: 'text',\n content,\n title: options.title,\n description: options.description,\n docid: options.docid,\n tags: options.tags,\n replace: options.replace,\n });\n results.push(mapAddSectionResult(result, '-', content.length));\n continue;\n }\n\n const files = collectFiles(target);\n for (const file of files) {\n const content = readFileSync(file, 'utf-8');\n const result = await client.addSection({\n sectionType: 'text',\n content,\n title: options.title,\n description: options.description,\n docid: options.docid,\n tags: options.tags,\n replace: options.replace,\n sourcePath: file,\n });\n results.push(\n mapAddSectionResult(result, file, content.length),\n );\n }\n }\n\n return results;\n}\n\n/**\n * Maps an `AddSectionResult` to a `LearnResult` record.\n *\n * @param result - raw result from `client.addSection()`\n * @param path - source file path or `'-'` for stdin\n * @param size - UTF-8 character count of the ingested content\n */\nfunction mapAddSectionResult(\n result: AddSectionResult,\n path: string,\n size: number,\n): LearnResult {\n return {\n kbid: result.kbid,\n path,\n size,\n skipped: false,\n superseded: result.superseded ?? null,\n warnings: result.warnings ?? [],\n near_duplicates: result.near_duplicates ?? [],\n };\n}\n\nfunction readProcessStdin(): Promise<string> {\n return new Promise<string>((resolve) => {\n const chunks: Buffer[] = [];\n process.stdin.on('data', (chunk: Buffer) => {\n chunks.push(chunk);\n });\n process.stdin.on('end', () => {\n resolve(Buffer.concat(chunks).toString('utf-8'));\n });\n process.stdin.resume();\n });\n}\n\n/**\n * Resolves a single target path to a flat list of supported files.\n *\n * Returns an empty array for non-existent or inaccessible paths.\n *\n * @param target - file or directory path to resolve\n */\nfunction collectFiles(target: string): string[] {\n try {\n const stat = statSync(target);\n if (stat.isFile()) {\n return isSupportedFile(target) ? [target] : [];\n }\n if (stat.isDirectory()) {\n return scanDirectory(target);\n }\n } catch {\n // Non-existent or inaccessible path -- skip\n }\n return [];\n}\n\n/**\n * Recursively scans a directory and returns all supported files,\n * excluding dot-entries at every level.\n *\n * @param dir - absolute or relative directory path to scan\n */\nfunction scanDirectory(dir: string): string[] {\n const files: string[] = [];\n for (const entry of readdirSync(dir)) {\n if (entry.startsWith('.')) continue;\n const full = join(dir, entry);\n try {\n const stat = statSync(full);\n if (stat.isDirectory()) {\n files.push(...scanDirectory(full));\n } else if (isSupportedFile(full)) {\n files.push(full);\n }\n } catch {\n // Skip inaccessible entries\n }\n }\n return files;\n}\n\n/**\n * Returns `true` when the file's extension is in\n * `SUPPORTED_EXTENSIONS`.\n *\n * @param path - file path to check\n */\nfunction isSupportedFile(path: string): boolean {\n if (basename(path).startsWith('.')) return false;\n const ext = extname(path).toLowerCase();\n return (SUPPORTED_EXTENSIONS as readonly string[]).includes(ext);\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\n\n/** Removal result returned by `UnlearnClient.removeSection`. */\ninterface RemoveSectionResult {\n /** `true` when the section was found and successfully removed. */\n readonly removed: boolean;\n /** Time taken to perform the removal, in milliseconds. */\n readonly elapsed_ms: number;\n}\n\n/**\n * Minimal client interface required by `runUnlearn`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface UnlearnClient {\n /**\n * Removes a section from the knowledge base.\n *\n * @param kbid - identifier of the section to remove\n * @returns removal result with `removed` flag and elapsed time\n */\n removeSection(kbid: string): Promise<RemoveSectionResult>;\n}\n\n/** Result record produced for each kbid processed by the unlearn command. */\nexport interface UnlearnResult {\n /** Knowledge-base identifier that was targeted for removal. */\n kbid: string;\n /** `true` when the section was found and successfully removed. */\n removed: boolean;\n}\n\n/**\n * Removes the knowledge-base sections identified by `options.args`\n * via the provided client.\n *\n * Each kbid in `options.args` is processed independently. If a kbid\n * does not exist in the knowledge base, `removed` is set to `false`\n * rather than throwing.\n *\n * @param client - unlearn client to delegate removal to\n * @param options - parsed CLI options whose `args` list the kbids to\n * remove\n * @returns one `UnlearnResult` per kbid processed\n */\nexport async function runUnlearn(\n client: UnlearnClient,\n options: CliOptions,\n): Promise<UnlearnResult[]> {\n const results: UnlearnResult[] = [];\n for (const kbid of options.args) {\n const result = await client.removeSection(kbid);\n results.push({ kbid, removed: result.removed });\n }\n return results;\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\n\n/** Result returned by content composition. */\ninterface ContentResult {\n /** MIME type of the composed output, always `'text/markdown'`. */\n readonly type: 'text/markdown';\n /** The composed Markdown string. */\n readonly data: string;\n /** Character count of `data` (not byte count). */\n readonly total: number;\n}\n\n/**\n * Minimal client interface required by `runContent`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface ContentClient {\n /**\n * Composes a rendered Markdown document from one or more kbid\n * or docid identifiers.\n *\n * @param ids - list of kbid or docid identifiers (may be mixed)\n * @returns composed Markdown result with character count\n */\n content(ids: string[]): Promise<ContentResult>;\n}\n\n/**\n * Composes and returns a rendered Markdown document from the\n * identifiers listed in `options.args`.\n *\n * Delegates to `client.content(ids)`. The caller is responsible for\n * writing the result to stdout.\n *\n * @param client - content client to delegate composition to\n * @param options - parsed CLI options whose `args` list the kbid or\n * docid identifiers to compose\n * @returns the composed content result from the daemon\n */\nexport async function runContent(\n client: ContentClient,\n options: CliOptions,\n): Promise<ContentResult> {\n return client.content(options.args);\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\n\n/** A single integrity error found during a database check. */\ninterface IntegrityError {\n /**\n * The category of integrity violation detected.\n *\n * - `'checksum_mismatch'` -- stored content does not match its hash\n * - `'orphan_section'` -- section not referenced by any document\n * - `'orphan_document'` -- document references no existing sections\n * - `'broken_reference'` -- a marker references a non-existent entity\n * - `'type_mismatch'` -- stored MIME type conflicts with content\n * - `'circular_reference'` -- marker chain contains a cycle\n */\n readonly type:\n | 'checksum_mismatch'\n | 'orphan_section'\n | 'orphan_document'\n | 'broken_reference'\n | 'type_mismatch'\n | 'circular_reference';\n /** Identifier of the entity (kbid or docid) that has the issue. */\n readonly entity: string;\n /** Human-readable description of the specific problem. */\n readonly detail: string;\n}\n\n/**\n * A single entry in the divergent-content map.\n * Groups kbids under a common source key.\n */\ninterface DivergentContentEntry {\n /** Source key that has multiple divergent content versions. */\n readonly sourceKey: string;\n /** Kbids of sections sharing this source key but with different content. */\n readonly kbids: string[];\n}\n\n/**\n * Integrity check report returned by the daemon.\n */\ninterface IntegrityCheckResult {\n /** `true` when all checks passed and no errors were found. */\n readonly ok: boolean;\n /** All integrity errors found; empty when `ok` is `true`. */\n readonly errors: IntegrityError[];\n /** Total number of sections examined. */\n readonly sections_checked: number;\n /** Total number of documents examined. */\n readonly documents_checked: number;\n /** Total number of marker references checked. */\n readonly references_checked: number;\n /** Time taken to complete the check, in milliseconds. */\n readonly elapsed_ms: number;\n /**\n * Sections that share a source key but have divergent content.\n * Each entry groups the kbids under a common source key.\n * Empty when no divergent content is found.\n */\n readonly divergent_content: DivergentContentEntry[];\n}\n\n/** Raw daemon response from `integrityCheck`. */\ninterface RawIntegrityCheckResult {\n /** `true` when all checks passed and no errors were found. */\n readonly ok: boolean;\n /** All integrity errors found; empty when `ok` is `true`. */\n readonly errors: IntegrityError[];\n /** Total number of sections examined. */\n readonly sections_checked: number;\n /** Total number of documents examined. */\n readonly documents_checked: number;\n /** Total number of marker references checked. */\n readonly references_checked: number;\n /** Time taken to complete the check, in milliseconds. */\n readonly elapsed_ms: number;\n /**\n * Encoded divergent-content map.\n *\n * Format: `sk1:kbid1,kbid2;sk2:kbid3,kbid4`\n *\n * Each semicolon-separated segment is a source key followed by\n * a colon and a comma-separated list of kbids. Absent when no\n * divergent content exists.\n */\n readonly divergent_content?: string;\n}\n\n/**\n * Minimal client interface required by `runCheck`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface CheckClient {\n /**\n * Runs an integrity check on the knowledge-base database.\n *\n * @returns a report of all issues found; `ok` is `true` when\n * no errors were detected\n */\n integrityCheck(): Promise<RawIntegrityCheckResult>;\n}\n\n/**\n * Parses the encoded `divergent_content` string from the daemon\n * into a structured array.\n *\n * Input format: `sk1:kbid1,kbid2;sk2:kbid3,kbid4`\n *\n * @param encoded - raw encoded string, or empty / absent\n * @returns structured entries grouped by source key\n */\nfunction parseDivergentContent(\n encoded: string | undefined,\n): DivergentContentEntry[] {\n if (!encoded) return [];\n return encoded\n .split(';')\n .filter((segment) => segment.includes(':'))\n .map((segment) => {\n const colonIdx = segment.indexOf(':');\n const sourceKey = segment.slice(0, colonIdx);\n const kbids = segment\n .slice(colonIdx + 1)\n .split(',')\n .filter((k) => k.length > 0);\n return { sourceKey, kbids };\n })\n .filter((entry) => entry.kbids.length > 0);\n}\n\n/**\n * Runs an integrity check on the database and returns the report.\n *\n * Delegates to `client.integrityCheck()`, then parses the encoded\n * `divergent_content` field into structured form. The caller is\n * responsible for printing the result to stdout and setting the\n * process exit code based on `result.ok`.\n *\n * @param client - check client to delegate to\n * @param _options - parsed CLI options (unused; reserved for future flags)\n * @returns the integrity check report with parsed `divergent_content`\n */\nexport async function runCheck(\n client: CheckClient,\n _options: CliOptions,\n): Promise<IntegrityCheckResult> {\n const raw = await client.integrityCheck();\n return {\n ok: raw.ok,\n errors: raw.errors,\n sections_checked: raw.sections_checked,\n documents_checked: raw.documents_checked,\n references_checked: raw.references_checked,\n elapsed_ms: raw.elapsed_ms,\n divergent_content: parseDivergentContent(raw.divergent_content),\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\n\n/**\n * Garbage collection report returned by the daemon.\n */\ninterface GcResult {\n /** Number of unreferenced sections removed. */\n readonly removed_sections: number;\n /** Total bytes freed by removing unreferenced sections. */\n readonly removed_bytes: number;\n /** Time taken to complete garbage collection, in milliseconds. */\n readonly elapsed_ms: number;\n /**\n * Number of sections whose `source_path` file no longer\n * contains their heading text (advisory; not auto-removed).\n * Absent on older daemon versions.\n */\n readonly stale_sources?: number;\n}\n\n/**\n * Minimal client interface required by `runGc`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface GcClient {\n /**\n * Removes unreferenced sections from the database.\n *\n * @returns a report of sections removed and bytes freed\n */\n gc(): Promise<GcResult>;\n}\n\n/**\n * Runs garbage collection on the database and returns the report.\n *\n * Delegates to `client.gc()`. The caller is responsible for printing\n * the result to stdout.\n *\n * @param client - gc client to delegate to\n * @param _options - parsed CLI options (unused; reserved for future flags)\n * @returns the garbage collection report from the daemon\n */\nexport async function runGc(\n client: GcClient,\n _options: CliOptions,\n): Promise<GcResult> {\n return client.gc();\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\n\n/**\n * Index rebuild report returned by the daemon.\n */\ninterface RebuildResult {\n /** Number of text and code sections that were re-indexed. */\n readonly sections_reindexed: number;\n /** Total number of unique terms written to the rebuilt indexes. */\n readonly terms_indexed: number;\n /** Time taken to complete the rebuild, in milliseconds. */\n readonly elapsed_ms: number;\n}\n\n/**\n * Minimal client interface required by `runRebuild`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface RebuildClient {\n /**\n * Reconstructs all index files from section files and document\n * manifests on disk. Text and code sections are re-tokenized;\n * image sections are skipped.\n *\n * @returns a report of sections and terms re-indexed\n */\n rebuildIndexes(): Promise<RebuildResult>;\n}\n\n/**\n * Rebuilds all database indexes and returns the report.\n *\n * Delegates to `client.rebuildIndexes()`. The caller is responsible\n * for printing the result to stdout.\n *\n * @param client - rebuild client to delegate to\n * @param _options - parsed CLI options (unused; reserved for future flags)\n * @returns the index rebuild report from the daemon\n */\nexport async function runRebuild(\n client: RebuildClient,\n _options: CliOptions,\n): Promise<RebuildResult> {\n return client.rebuildIndexes();\n}\n", "import { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\n\n/**\n * Resolves the absolute path to the `.kbdb` database directory\n * under the given base path (or the current working directory).\n *\n * Unlike `ensureDb`, this function is purely read-only: it never\n * creates the directory. Returns `null` when the `.kbdb` directory\n * does not exist.\n *\n * @param dbPath - optional path to the knowledge-base root directory\n * @returns absolute path to the `.kbdb` directory, or `null` when\n * it does not exist\n */\nexport function findDb(dbPath?: string): string | null {\n const base = dbPath ? resolve(dbPath) : process.cwd();\n const kbdbDir = join(base, '.kbdb');\n return existsSync(kbdbDir) ? kbdbDir : null;\n}\n", "import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport type { CliOptions } from '../typings/cli-options.interface.ts';\nimport { installDefaultSkills } from './install-default-skills.function.ts';\n\n/**\n * Result returned by `runInit` describing whether the directory was\n * successfully initialised.\n */\nexport interface InitResult {\n /** `true` when the database directory was created successfully. */\n readonly ok: boolean;\n /** Absolute path to the directory that was (or should have been) initialised. */\n readonly targetPath: string;\n /**\n * Human-readable error message when `ok` is `false`.\n * `undefined` when `ok` is `true`.\n */\n readonly errorMessage?: string;\n}\n\nconst DB_FORMAT_VERSION = 1;\n\nconst CATALOG_TOML = `version = ${DB_FORMAT_VERSION.toString()}\nsection_count = 0\ndocument_count = 0\ncreated_at = 0\nupdated_at = 0\nchecksum = \"\"\n`;\n\nconst WORKER_TOML = '# kbdb worker configuration\\n';\n\nconst GITIGNORE = [\n '# kbdb binary indexes (auto-generated)',\n 'corpus.bin',\n 'inverted.idx',\n 'positional.idx',\n '',\n].join('\\n');\n\n/**\n * Creates the `.kbdb` directory scaffold directly on disk.\n *\n * This mirrors the Rust `init_directory` in\n * `engine/crates/fs-database/src/scaffold.rs` and does not\n * require a running worker daemon.\n */\nfunction createScaffold(dbDir: string): void {\n mkdirSync(dbDir, { recursive: true });\n mkdirSync(join(dbDir, 'sections'));\n mkdirSync(join(dbDir, 'documents'));\n writeFileSync(join(dbDir, 'catalog.toml'), CATALOG_TOML);\n writeFileSync(join(dbDir, 'corpus.bin'), '');\n writeFileSync(join(dbDir, 'inverted.idx'), '');\n writeFileSync(join(dbDir, 'positional.idx'), '');\n writeFileSync(join(dbDir, 'worker.toml'), WORKER_TOML);\n writeFileSync(join(dbDir, '.gitignore'), GITIGNORE);\n}\n\n/**\n * Initialises a new `.kbdb` database directory.\n *\n * Creates the full scaffold directly on disk without requiring a\n * running worker daemon. Resolves the target path from\n * `options.dbPath` or `process.cwd()`.\n *\n * @param options - parsed CLI options supplying the optional `dbPath`\n * @returns init result indicating success or failure\n */\nexport function runInit(options: CliOptions): InitResult {\n const basePath = options.dbPath\n ? resolve(options.dbPath)\n : process.cwd();\n const dbDir = join(basePath, '.kbdb');\n\n try {\n if (existsSync(dbDir)) {\n return {\n ok: false,\n targetPath: dbDir,\n errorMessage: `database directory already exists: ${dbDir}`,\n };\n }\n createScaffold(dbDir);\n installDefaultSkills(dbDir);\n return { ok: true, targetPath: dbDir };\n } catch (err: unknown) {\n const errorMessage =\n err instanceof Error ? err.message : String(err);\n return { ok: false, targetPath: dbDir, errorMessage };\n }\n}\n", "import { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/**\n * RFC 4648 base32 alphabet (upper-case, no padding).\n * Used to encode the SHA-256-derived kbid bytes.\n */\nconst BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';\n\n/**\n * Encodes a byte array as a lowercase base32 string without padding.\n *\n * Mirrors the `data_encoding::BASE32_NOPAD` encoding used in the\n * Rust engine's `KbId::from_content`.\n *\n * @param bytes - raw bytes to encode\n * @returns lowercase base32-encoded string\n */\nfunction base32Encode(bytes: Uint8Array): string {\n let result = '';\n let bits = 0;\n let value = 0;\n for (const byte of bytes) {\n value = (value << 8) | byte;\n bits += 8;\n while (bits >= 5) {\n result += BASE32_ALPHABET[(value >>> (bits - 5)) & 0x1f];\n bits -= 5;\n }\n }\n if (bits > 0) {\n result += BASE32_ALPHABET[(value << (5 - bits)) & 0x1f];\n }\n return result.toLowerCase();\n}\n\n/**\n * Computes a 26-character kbid for a section using the same algorithm\n * as the Rust engine's `hash_section`.\n *\n * Algorithm:\n * 1. Build input: `\"section <mime> <byteLen>\\0<content>\"`\n * 2. SHA-256 hash the input\n * 3. Take the first 16 bytes\n * 4. Base32 encode (RFC 4648, no padding), lowercased \u2192 26 chars\n *\n * @param mimeType - MIME type string (e.g. `\"text/markdown\"`)\n * @param content - UTF-8 section content string\n * @returns 26-character lowercase base32 kbid\n */\nfunction computeSectionKbid(mimeType: string, content: string): string {\n const contentBytes = Buffer.from(content, 'utf-8');\n const header = `section ${mimeType} ${contentBytes.length.toString()}\\0`;\n const headerBytes = Buffer.from(header, 'utf-8');\n const input = Buffer.concat([headerBytes, contentBytes]);\n const hash = createHash('sha256').update(input).digest();\n const truncated = new Uint8Array(hash.buffer, 0, 16);\n return base32Encode(truncated);\n}\n\n/**\n * Escapes backslashes and double-quotes in a string for TOML inline\n * string values.\n *\n * Mirrors the `escape_toml_str` function in the Rust engine.\n *\n * @param s - string to escape\n * @returns escaped string safe for use inside TOML double-quoted strings\n */\nfunction escapeToml(s: string): string {\n return s.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n}\n\n/**\n * Serializes a skill section record to the `.section` file format.\n *\n * Format:\n * ```\n * kbid = \"...\"\n * section_type = \"text/markdown\"\n * type_name = \"skill\"\n * title = \"...\"\n * description = \"...\"\n * size = 0\n * token_count = 0\n * heading_token_count = 0\n * body_token_count = 0\n * code_token_count = 0\n * created_at = 0\n * checksum = \"...\"\n *\n * ---\n * <json content>\n * ```\n *\n * @param kbid - 26-char content-addressed identifier\n * @param title - skill name used as section title\n * @param description - human-readable description\n * @param content - serialised JSON skill definition\n * @returns file content string\n */\nfunction serializeSkillSection(\n kbid: string,\n title: string,\n description: string,\n content: string,\n): string {\n const size = Buffer.byteLength(content, 'utf-8');\n const header = [\n `kbid = \"${escapeToml(kbid)}\"`,\n `section_type = \"text/markdown\"`,\n `type_name = \"skill\"`,\n `title = \"${escapeToml(title)}\"`,\n `description = \"${escapeToml(description)}\"`,\n `size = ${size.toString()}`,\n `token_count = 0`,\n `heading_token_count = 0`,\n `body_token_count = 0`,\n `code_token_count = 0`,\n `created_at = 0`,\n `checksum = \"${escapeToml(kbid)}\"`,\n '',\n ].join('\\n');\n return `${header}\\n---\\n${content}`;\n}\n\n/** Descriptor for a skill to install. */\ninterface SkillDescriptor {\n /** Unique skill name (kebab-case). */\n readonly name: string;\n /** Human-readable description. */\n readonly description: string;\n /** Template body text. */\n readonly body: string;\n}\n\n/**\n * Installs a single skill section file under `sectionsDir`.\n *\n * Creates the shard subdirectory if it does not exist. Skips\n * writing if the section file already exists, preserving any\n * user modifications.\n *\n * @param sectionsDir - absolute path to `.kbdb/sections`\n * @param skill - skill definition to serialise and store\n */\nfunction installSkill(\n sectionsDir: string,\n skill: SkillDescriptor,\n): void {\n const content = JSON.stringify({\n name: skill.name,\n description: skill.description,\n arguments: [],\n body: skill.body,\n });\n const kbid = computeSectionKbid('text/markdown', content);\n const prefix = kbid.slice(0, 2);\n const shardDir = join(sectionsDir, prefix);\n const filePath = join(shardDir, `${kbid}.section`);\n\n if (existsSync(filePath)) {\n return;\n }\n\n mkdirSync(shardDir, { recursive: true });\n\n const fileContent = serializeSkillSection(\n kbid,\n skill.name,\n skill.description,\n content,\n );\n writeFileSync(filePath, fileContent, 'utf-8');\n}\n\n/**\n * Body text for the `query-guidance` default skill.\n *\n * Teaches AI agents how to effectively search the knowledge base\n * using lexical BM25F queries.\n */\nconst QUERY_GUIDANCE_BODY =\n 'This knowledge base uses lexical search (stemmed BM25F), not' +\n ' semantic/vector search. Follow these guidelines for effective' +\n ' retrieval:\\n\\n' +\n '1. Issue MULTIPLE short keyword queries rather than one long' +\n ' natural-language question. Each query should target 2-3' +\n ' specific terms.\\n\\n' +\n '2. EXPAND SYNONYMS yourself. \"login\" will not match \"sign-in\"' +\n ' unless both terms appear in the content. Try alternative' +\n ' phrasings: search for \"login\", then \"sign-in\", then' +\n ' \"authentication\".\\n\\n' +\n '3. USE BOOLEAN AND PHRASE SYNTAX:\\n' +\n ' - Exact phrases: \"error handling\"\\n' +\n ' - Boolean AND: auth AND token\\n' +\n ' - Boolean OR: cache OR redis\\n' +\n ' - Exclusion: auth -oauth\\n\\n' +\n '4. LEAN ON HEADINGS. Headings carry 2x weight in ranking.' +\n ' Search for terms that are likely in section titles.\\n\\n' +\n '5. STEMMING IS AUTOMATIC. \"connections\" matches \"connect\",' +\n ' \"running\" matches \"run\". You do not need to try inflected' +\n ' forms.\\n\\n' +\n '6. USE RECALL AFTER SEARCH. After finding relevant sections' +\n ' with search, use recall with increasing depth (0-3) to' +\n ' progressively expand context: depth 0 = full content, depth' +\n ' 1 = parent documents + back-references, depth 2 = siblings' +\n ' + forward references, depth 3 = referenced sections.\\n\\n' +\n '7. CODE IDENTIFIERS ARE SPLIT. camelCase and snake_case names' +\n ' are decomposed: getUserById becomes searchable as \"get\",' +\n ' \"user\", \"by\", \"id\".\\n\\n' +\n '8. PAGINATION. Default limit is 20 results. Use offset for' +\n ' additional pages if total > limit.';\n\n/**\n * Body text for the `memory-protocol` default skill.\n *\n * Teaches AI agents when and what to store in the knowledge base\n * to keep it accurate and useful.\n */\nconst MEMORY_PROTOCOL_BODY =\n 'Follow these guidelines to keep the knowledge base accurate' +\n ' and useful:\\n\\n' +\n '1. STORE DURABLE FACTS: decisions, architecture choices,' +\n ' configuration values, corrections to prior knowledge, API' +\n ' contracts, and resolved incidents. These are the facts that' +\n ' matter weeks later.\\n\\n' +\n '2. DO NOT STORE: transient conversation context, debugging' +\n ' output, ephemeral task state, raw log dumps, or information' +\n ' that changes every session. The brain should contain' +\n ' knowledge, not activity logs.\\n\\n' +\n '3. SEARCH BEFORE STORING. Always search the knowledge base' +\n ' before adding new content. If a section already covers the' +\n ' topic, use learn with --replace to update it rather than' +\n ' creating a duplicate.\\n\\n' +\n '4. USE --replace FOR CORRECTIONS. When a fact changes (e.g.,' +\n ' rate limit updated from 100 to 200 req/min), re-learn the' +\n ' corrected content with --replace so the old version is' +\n ' superseded. Without --replace, both the old and new versions' +\n ' coexist with equal ranking.\\n\\n' +\n '5. ATTACH TAGS for scoping. Use tags like project name,' +\n ' domain, or topic (e.g., --tags auth,api,v2) so queries can' +\n ' be filtered by scope later.\\n\\n' +\n '6. PREFER RECENT RESULTS. When search returns multiple' +\n ' sections covering the same topic, prefer the one with the' +\n ' most recent created_at timestamp -- it is more likely to' +\n ' reflect the current state.\\n\\n' +\n '7. USE RECALL AFTER SEARCH. After finding relevant sections,' +\n ' use recall with increasing depth (0-3) to expand context' +\n ' progressively before making decisions.\\n\\n' +\n '8. INCLUDE HEADINGS. Always provide a descriptive title when' +\n ' storing content. Headings carry 2x ranking weight -- omitting' +\n ' them significantly reduces searchability.';\n\n/**\n * Default skills installed on every fresh `kbdb db init`.\n *\n * These provide baseline guidance that improves AI agent\n * effectiveness out of the box. They are regular skill sections\n * and can be deleted by users.\n */\nconst DEFAULT_SKILLS: readonly SkillDescriptor[] = [\n {\n name: 'query-guidance',\n description:\n 'How to effectively search this knowledge base.' +\n ' Read this before issuing search queries.',\n body: QUERY_GUIDANCE_BODY,\n },\n {\n name: 'memory-protocol',\n description:\n 'Guidelines for what to store in this knowledge base' +\n ' and when. Read this before using the learn tool.',\n body: MEMORY_PROTOCOL_BODY,\n },\n];\n\n/**\n * Writes the two default skills (`query-guidance` and\n * `memory-protocol`) as section files directly into the `.kbdb`\n * directory scaffold.\n *\n * Called by `runInit` after the directory scaffold is created.\n * Does not require a running worker daemon. Skips any skill whose\n * section file already exists so user modifications are preserved.\n *\n * @param dbDir - absolute path to the `.kbdb` directory\n */\nexport function installDefaultSkills(dbDir: string): void {\n const sectionsDir = join(dbDir, 'sections');\n for (const skill of DEFAULT_SKILLS) {\n installSkill(sectionsDir, skill);\n }\n}\n", "/**\n * Converts an unknown thrown value to a human-readable message.\n *\n * @param err - the caught value\n * @returns the error message string\n */\nexport function errorToMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n", "/**\n * Returns `true` when stdin is an interactive terminal.\n *\n * @param stdin - readable stream to check (defaults to\n * `process.stdin`)\n */\nexport function isStdinTty(\n stdin: NodeJS.ReadStream = process.stdin,\n): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- isTTY is undefined at runtime for non-TTY despite Node types saying boolean\n return stdin.isTTY ?? false;\n}\n", "import { createInterface } from 'node:readline';\n\n/** Injectable I/O for testing without real stdin. */\nexport interface PromptIO {\n ask: (question: string) => Promise<string>;\n}\n\n/**\n * Prompts the user on stdin (TTY only) and returns the\n * trimmed reply.\n *\n * @param question - the prompt text to display\n * @param io - injectable I/O (defaults to readline on\n * process.stdin/stdout)\n */\nexport async function promptUser(\n question: string,\n io?: PromptIO,\n): Promise<string> {\n const ask = io?.ask ?? askReadline;\n const answer = await ask(question);\n return answer.trim();\n}\n\nfunction askReadline(question: string): Promise<string> {\n return new Promise<string>((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer);\n });\n });\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\n\n/**\n * Minimal client interface required by `runStatus`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface StatusClient {\n dbStatus(): Promise<unknown>;\n}\n\n/**\n * Retrieves the database status and returns the summary report.\n *\n * Delegates to `client.dbStatus()`. The caller is responsible\n * for serialising the result and setting the process exit code.\n *\n * @param client - status client to delegate to\n * @param _options - parsed CLI options (unused; reserved for\n * future flags)\n * @returns the status report from the daemon\n */\nexport async function runStatus(\n client: StatusClient,\n _options: CliOptions,\n): Promise<unknown> {\n return client.dbStatus();\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\nimport type { InitResult } from './run-init.function.ts';\n\n/**\n * Callable signature for the init operation injected into\n * `runDbInit`.\n */\nexport type RunInitFn = (options: CliOptions) => InitResult;\n\n/**\n * Executes the `db init` compound command by delegating to the\n * provided `runInit` function and mapping the result to a\n * `CommandResult`.\n *\n * Accepts `runInit` as an injectable parameter so the function\n * can be tested without touching the filesystem.\n *\n * @param options - parsed CLI options (forwarded to `runInitFn`)\n * @param runInitFn - function that performs the actual\n * initialisation\n * @returns a `CommandResult` with JSON output on success or an\n * error message on failure\n */\nexport function runDbInit(\n options: CliOptions,\n runInitFn: RunInitFn,\n): CommandResult {\n const result = runInitFn(options);\n if (result.ok) {\n return {\n output: JSON.stringify(\n { path: result.targetPath, created: true },\n null,\n 2,\n ),\n exitCode: 0,\n };\n }\n return {\n error: result.errorMessage ?? 'init failed',\n exitCode: 1,\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { MigrateResult } from '../../worker-client/typings/migrate-result.model.ts';\n\n/**\n * Minimal client interface required by `runDbMigrate`.\n *\n * Intentionally narrower than `MigrateClient` from\n * `run-migrate.function.ts` \u2014 this variant skips the version\n * check and unconditionally runs migrations. Callers that need\n * version-aware migration should use `runMigrate` instead.\n */\nexport interface DbMigrateClient {\n /**\n * Runs all pending database migrations.\n *\n * @param targetPath - absolute path to the `.kbdb` database root\n */\n migrateDatabase(targetPath: string): Promise<MigrateResult>;\n}\n\n/**\n * Runs database migrations unconditionally via `client.migrateDatabase`.\n *\n * Resolves the target path from `options.dbPath` when provided,\n * falling back to `process.cwd()`. Does not perform a version\n * compatibility check before migrating \u2014 use `runMigrate` for\n * version-aware migration flows.\n *\n * @param client - database migration client to delegate to\n * @param options - parsed CLI options supplying the optional\n * `dbPath`\n * @returns the migration report returned by the daemon\n */\nexport async function runDbMigrate(\n client: DbMigrateClient,\n options: CliOptions,\n): Promise<MigrateResult> {\n const dbPath = options.dbPath ?? process.cwd();\n return client.migrateDatabase(dbPath);\n}\n", "import type { SkillArgument } from '../typings/skill-types.interface.ts';\n\n/**\n * Extracts `{{argName}}` placeholder names from a skill body string\n * and returns them as `SkillArgument` objects marked as required.\n *\n * Each placeholder is included only once regardless of how many\n * times it appears, and the returned array preserves the order of\n * first occurrence.\n *\n * @param body - skill body template text to scan for placeholders\n * @returns ordered, deduplicated list of argument definitions\n */\nexport function extractSkillArguments(body: string): SkillArgument[] {\n const seen = new Set<string>();\n const args: SkillArgument[] = [];\n const re = /\\{\\{(\\w+)\\}\\}/g;\n let match: RegExpExecArray | null;\n while ((match = re.exec(body)) !== null) {\n const name = match[1];\n if (!seen.has(name)) {\n seen.add(name);\n args.push({ name, required: true });\n }\n }\n return args;\n}\n", "import type { SkillDefinition } from '../typings/skill-types.interface.ts';\n\n/**\n * Serializes a `SkillDefinition` to a JSON string suitable for\n * storage as a knowledge-base section's `content` field.\n *\n * @param skill - skill definition to serialize\n * @returns JSON string representation of the skill\n */\nexport function serializeSkillContent(skill: SkillDefinition): string {\n return JSON.stringify(skill);\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\nimport type { AddSectionResult } from '../../worker-client/typings/add-section-result.model.ts';\nimport { extractSkillArguments } from '../../mcp/functions/extract-skill-arguments.function.ts';\nimport { serializeSkillContent } from '../../mcp/functions/serialize-skill-content.function.ts';\n\n/**\n * Minimal client interface required by `runSkillLearn`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface SkillLearnClient {\n /**\n * Stores a skill section in the knowledge base.\n *\n * @param params - section type, serialized JSON content,\n * and optional title and description\n * @returns result containing the assigned kbid\n */\n addSection(params: {\n readonly sectionType: string;\n readonly content: string;\n readonly title?: string;\n readonly description?: string;\n }): Promise<AddSectionResult>;\n}\n\n/**\n * Creates or updates a skill definition in the knowledge base.\n *\n * Validates that `--name` and `--body` are provided, extracts\n * `{{argName}}` placeholders from the body, serializes the skill\n * to JSON, and stores it as a `'skill'` section.\n *\n * @param client - client used to store the skill section\n * @param options - parsed CLI options with `name` and `body` fields\n * @returns a `CommandResult` with the stored section info or an error\n */\nexport async function runSkillLearn(\n client: SkillLearnClient,\n options: CliOptions,\n): Promise<CommandResult> {\n const name = options.name;\n if (!name) {\n return { error: '--name is required', exitCode: 1 };\n }\n const body = options.body;\n if (!body) {\n return { error: '--body is required', exitCode: 1 };\n }\n const args = extractSkillArguments(body);\n const skill = {\n name,\n description: options.description,\n arguments: args.length > 0 ? args : undefined,\n body,\n };\n const json = serializeSkillContent(skill);\n const result = await client.addSection({\n sectionType: 'skill',\n content: json,\n title: name,\n description: options.description,\n });\n return {\n output: JSON.stringify(result, null, 2),\n exitCode: 0,\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\n\n/**\n * A single row returned by `listByType` for the skill client.\n */\ninterface SkillRecord {\n /** Knowledge-base identifier for the skill section. */\n kbid: string;\n /** Skill name stored as the section title. */\n title: string | null;\n /** Optional skill description stored on the section. */\n description: string | null;\n /** Serialized `SkillDefinition` JSON stored as section content. */\n content: string;\n}\n\n/**\n * Minimal client interface required by `runSkillList`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface SkillListClient {\n /**\n * Retrieves all sections stored with the given type name.\n *\n * @param sectionType - the type name to filter by\n * @returns matching section rows\n */\n listByType(sectionType: string): Promise<SkillRecord[]>;\n}\n\n/**\n * Lists all skill definitions stored in the knowledge base.\n *\n * Calls `client.listByType('skill')` and maps each record to a\n * summary that includes the argument count parsed from the JSON\n * content. Parse errors default the argument count to `0`.\n *\n * @param client - client used to list skill sections\n * @param _options - parsed CLI options (unused; reserved for future flags)\n * @returns a `CommandResult` containing a JSON array of skill summaries\n */\nexport async function runSkillList(\n client: SkillListClient,\n _options: CliOptions,\n): Promise<CommandResult> {\n const records = await client.listByType('skill');\n const items = records.map((r) => {\n let argumentCount = 0;\n try {\n const parsed = JSON.parse(r.content) as Record<\n string,\n unknown\n >;\n if (Array.isArray(parsed['arguments'])) {\n argumentCount = parsed['arguments'].length;\n }\n } catch {\n // ignore parse errors\n }\n return {\n kbid: r.kbid,\n name: r.title,\n description: r.description,\n argumentCount,\n };\n });\n return {\n output: JSON.stringify(items, null, 2),\n exitCode: 0,\n };\n}\n", "import type {\n SkillArgument,\n SkillDefinition,\n} from '../typings/skill-types.interface.ts';\n\n/**\n * Parses a JSON string into a `SkillDefinition`.\n *\n * Validates that the required `name` and `body` fields are present\n * and are non-empty strings, then returns the full definition\n * including optional `description` and `arguments`.\n *\n * @param json - JSON string representing a serialized skill\n * @returns the parsed skill definition\n * @throws {SyntaxError} when `json` is not valid JSON\n * @throws {Error} when `name` is missing or empty\n * @throws {Error} when `body` is missing or not a string\n */\nexport function parseSkillContent(json: string): SkillDefinition {\n const raw = JSON.parse(json) as Record<string, unknown>;\n if (typeof raw['name'] !== 'string' || !raw['name']) {\n throw new Error('skill name is required');\n }\n if (typeof raw['body'] !== 'string') {\n throw new Error('skill body is required');\n }\n return {\n name: raw['name'],\n description:\n typeof raw['description'] === 'string'\n ? raw['description']\n : undefined,\n arguments: Array.isArray(raw['arguments'])\n ? (raw['arguments'] as SkillArgument[])\n : undefined,\n body: raw['body'],\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\nimport { parseSkillContent } from '../../mcp/functions/parse-skill-content.function.ts';\n\n/**\n * Minimal client interface required by `runSkillGet`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface SkillGetClient {\n /**\n * Retrieves one or more sections by their knowledge-base IDs.\n *\n * @param kbids - list of knowledge-base identifiers to fetch\n * @returns matching section rows\n */\n readSections(\n kbids: string[],\n ): Promise<{ kbid: string; content: string }[]>;\n\n /**\n * Retrieves all sections stored with the given type name.\n *\n * @param sectionType - the type name to filter by\n * @returns matching section rows\n */\n listByType(\n sectionType: string,\n ): Promise<\n { kbid: string; title: string | null; content: string }[]\n >;\n}\n\n/**\n * Retrieves a skill definition by name or kbid.\n *\n * Accepts the identifier as the first positional argument or as\n * `options.name`. When the identifier looks like a hex hash\n * (16 or more hex characters) it is tried as a kbid first; if\n * no section is found it falls back to a name lookup. When the\n * identifier is not hex-like it goes directly to name lookup.\n * For name lookups the most recently stored match (last in the\n * array) is returned.\n *\n * @param client - client used to look up the skill section\n * @param options - parsed CLI options; first positional arg or `name`\n * is used as the identifier\n * @returns a `CommandResult` containing the serialized\n * `SkillDefinition` JSON or an error message\n */\nexport async function runSkillGet(\n client: SkillGetClient,\n options: CliOptions,\n): Promise<CommandResult> {\n const identifier = options.args[0] ?? options.name;\n if (!identifier) {\n return {\n error: 'skill name or kbid required',\n exitCode: 1,\n };\n }\n let content: string | undefined;\n // Try as kbid first when it looks like a hex hash.\n if (/^[0-9a-f]{16,}$/i.test(identifier)) {\n const sections = await client.readSections([identifier]);\n if (sections.length > 0) {\n content = sections[0]?.content;\n }\n }\n // If not found by kbid, try by name.\n if (content === undefined) {\n const records = await client.listByType('skill');\n const match = records.filter((r) => r.title === identifier).pop();\n if (match) {\n content = match.content;\n }\n }\n if (content === undefined) {\n return {\n error: `skill not found: ${identifier}`,\n exitCode: 1,\n };\n }\n const skill = parseSkillContent(content);\n return {\n output: JSON.stringify(skill, null, 2),\n exitCode: 0,\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\n\n/**\n * Minimal client interface required by `runSkillDelete`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface SkillDeleteClient {\n /**\n * Removes a section from the knowledge base.\n *\n * @param kbid - knowledge-base identifier of the section to remove\n * @returns result indicating whether the section was found and removed\n */\n removeSection(kbid: string): Promise<{ removed: boolean }>;\n}\n\n/**\n * Deletes a skill section from the knowledge base by its kbid.\n *\n * The kbid must be supplied as the first positional argument. Returns\n * an error result if it is missing.\n *\n * @param client - client used to remove the skill section\n * @param options - parsed CLI options; `args[0]` is the kbid\n * @returns a `CommandResult` with the kbid and removal status\n */\nexport async function runSkillDelete(\n client: SkillDeleteClient,\n options: CliOptions,\n): Promise<CommandResult> {\n const kbid = options.args[0];\n if (!kbid) {\n return { error: 'kbid is required', exitCode: 1 };\n }\n const result = await client.removeSection(kbid);\n return {\n output: JSON.stringify(\n { kbid, removed: result.removed },\n null,\n 2,\n ),\n exitCode: 0,\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\nimport type { AddSectionResult } from '../../worker-client/typings/add-section-result.model.ts';\n\n/**\n * Minimal client interface required by `runAgentCreate`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface AgentCreateClient {\n /**\n * Ingests a content section into the knowledge base.\n *\n * @param params - section type label, raw content, and optional\n * metadata\n * @returns result object containing the assigned knowledge-base\n * identifier\n */\n addSection(params: {\n readonly sectionType: string;\n readonly content: string;\n readonly title?: string;\n readonly description?: string;\n }): Promise<AddSectionResult>;\n\n /**\n * Groups a set of sections under a named document.\n *\n * @param title - human-readable document title\n * @param kbids - identifiers of the sections to group\n * @param docType - application-level document type tag; omit or\n * pass an empty string for untagged documents\n * @returns the assigned document identifier\n */\n groupSections(\n title: string,\n kbids: string[],\n docType?: string,\n ): Promise<string>;\n\n /**\n * Retrieves one or more sections by their identifiers.\n *\n * @param kbids - list of knowledge-base identifiers to fetch\n * @returns sections found; missing kbids are omitted from the result\n */\n readSections(kbids: string[]): Promise<{ kbid: string }[]>;\n}\n\n/**\n * Creates a new agent in the knowledge base.\n *\n * Validates `--name` and `--persona` options, verifies that all\n * referenced skill kbids exist, stores agent metadata as a JSON\n * section, and groups all sections under a single document.\n *\n * @param client - agent create client to delegate operations to\n * @param options - parsed CLI options providing `name`, `persona`,\n * optional `description`, and optional `skills` kbid list\n * @returns a `CommandResult` with serialised creation info or an\n * error message and a non-zero exit code\n */\nexport async function runAgentCreate(\n client: AgentCreateClient,\n options: CliOptions,\n): Promise<CommandResult> {\n const name = options.name;\n if (!name) {\n return { error: '--name is required', exitCode: 1 };\n }\n const persona = options.persona;\n if (!persona) {\n return { error: '--persona is required', exitCode: 1 };\n }\n const skills = options.skills ?? [];\n\n if (skills.length > 0) {\n const sections = await client.readSections(skills);\n const found = new Set(sections.map((s) => s.kbid));\n const missing = skills.filter((k) => !found.has(k));\n if (missing.length > 0) {\n return {\n error: `skill not found: ${missing.join(', ')}`,\n exitCode: 1,\n };\n }\n }\n\n const metadata = JSON.stringify({\n name,\n description: options.description ?? '',\n persona,\n });\n\n const metaResult = await client.addSection({\n sectionType: 'text',\n content: metadata,\n title: name,\n description: options.description,\n });\n\n const allKbids = [metaResult.kbid, ...skills];\n const docid = await client.groupSections(name, allKbids, 'agent');\n\n return {\n output: JSON.stringify(\n { docid, name, skillCount: skills.length },\n null,\n 2,\n ),\n exitCode: 0,\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\n\n/** A document summary as returned by `listDocumentsByType`. */\ninterface DocumentSummary {\n /** Unique document identifier. */\n readonly docid: string;\n /** Human-readable document title used as the agent name. */\n readonly title: string;\n /** Ordered list of section references for this document. */\n readonly sections: readonly { kbid: string; position: number }[];\n}\n\n/**\n * Minimal client interface required by `runAgentList`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface AgentListClient {\n /**\n * Retrieves all documents whose type name matches the given string.\n *\n * @param docType - the application-level document type to filter by\n * @returns all document summaries with a matching type name\n */\n listDocumentsByType(docType: string): Promise<DocumentSummary[]>;\n}\n\n/**\n * Lists all agents stored in the knowledge base.\n *\n * Retrieves all documents with `doc_type: 'agent'` and returns a\n * summary list. The `skillCount` for each agent is\n * `Math.max(0, sections.length - 1)` because the first section\n * always holds the agent's metadata JSON rather than a skill\n * reference.\n *\n * @param client - agent list client to delegate retrieval to\n * @param _options - parsed CLI options (unused; reserved for future\n * filtering flags)\n * @returns a `CommandResult` with serialised agent summary list\n */\nexport async function runAgentList(\n client: AgentListClient,\n _options: CliOptions,\n): Promise<CommandResult> {\n const docs = await client.listDocumentsByType('agent');\n const items = docs.map((d) => ({\n docid: d.docid,\n name: d.title,\n skillCount: Math.max(0, d.sections.length - 1),\n }));\n return {\n output: JSON.stringify(items, null, 2),\n exitCode: 0,\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\n\n/** A document section reference as returned by `retrieveDocument`. */\ninterface DocumentSection {\n /** Knowledge-base identifier of the section. */\n readonly kbid: string;\n /** Zero-based position of the section within the document. */\n readonly position: number;\n}\n\n/** A document record as returned by `retrieveDocument`. */\ninterface AgentDocument {\n /** Unique document identifier. */\n readonly docid: string;\n /** Human-readable document title used as agent name fallback. */\n readonly title: string;\n /** Ordered list of section references. */\n readonly sections: DocumentSection[];\n}\n\n/** A section record as returned by `readSections`. */\ninterface SectionRecord {\n /** Knowledge-base identifier of the section. */\n readonly kbid: string;\n /** Raw text content stored in the section. */\n readonly content: string;\n}\n\n/**\n * Minimal client interface required by `runAgentGet`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface AgentGetClient {\n /**\n * Retrieves a full document record including its ordered sections.\n *\n * @param docid - identifier of the document to retrieve\n * @returns the document record\n */\n retrieveDocument(docid: string): Promise<unknown>;\n\n /**\n * Retrieves one or more sections by their identifiers.\n *\n * @param kbids - list of knowledge-base identifiers to fetch\n * @returns sections found; missing kbids are omitted from the result\n */\n readSections(kbids: string[]): Promise<SectionRecord[]>;\n}\n\n/**\n * Reads agent metadata from the first section's JSON content.\n * Falls back to `fallbackName` when the section is absent or the\n * content cannot be parsed.\n */\nasync function readAgentMeta(\n client: AgentGetClient,\n metaKbid: string,\n fallbackName: string,\n): Promise<{ name: string; description: string; persona: string }> {\n const sections = await client.readSections([metaKbid]);\n const first = sections.at(0);\n if (!first) {\n return { name: fallbackName, description: '', persona: '' };\n }\n try {\n const meta = JSON.parse(first.content) as Record<string, unknown>;\n return {\n name:\n typeof meta['name'] === 'string'\n ? meta['name']\n : fallbackName,\n description:\n typeof meta['description'] === 'string'\n ? meta['description']\n : '',\n persona:\n typeof meta['persona'] === 'string' ? meta['persona'] : '',\n };\n } catch {\n return { name: fallbackName, description: '', persona: '' };\n }\n}\n\n/**\n * Resolves skill names by reading each skill section's JSON content.\n * Returns `null` for any reference whose section no longer exists\n * (dangling reference).\n */\nasync function resolveSkills(\n client: AgentGetClient,\n skillRefs: DocumentSection[],\n): Promise<{ kbid: string; name: string | null; position: number }[]> {\n if (skillRefs.length === 0) {\n return [];\n }\n const kbids = skillRefs.map((r) => r.kbid);\n const sections = await client.readSections(kbids);\n const sectionMap = new Map(sections.map((s) => [s.kbid, s]));\n return skillRefs.map((ref) => {\n const sec = sectionMap.get(ref.kbid);\n if (!sec) {\n return { kbid: ref.kbid, name: null, position: ref.position };\n }\n try {\n const parsed = JSON.parse(sec.content) as Record<\n string,\n unknown\n >;\n const skillName =\n typeof parsed['name'] === 'string' ? parsed['name'] : null;\n return {\n kbid: ref.kbid,\n name: skillName,\n position: ref.position,\n };\n } catch {\n return { kbid: ref.kbid, name: null, position: ref.position };\n }\n });\n}\n\n/**\n * Retrieves a full agent definition from the knowledge base.\n *\n * Reads the agent document identified by `options.args[0]`, extracts\n * metadata (name, description, persona) from the first section, and\n * resolves skill names from the remaining sections. Dangling skill\n * references appear with `name: null`.\n *\n * @param client - agent get client to delegate retrieval to\n * @param options - parsed CLI options; `args[0]` must be the docid\n * @returns a `CommandResult` with serialised agent definition or an\n * error message and a non-zero exit code\n */\nexport async function runAgentGet(\n client: AgentGetClient,\n options: CliOptions,\n): Promise<CommandResult> {\n const docid = options.args[0];\n if (!docid) {\n return { error: 'docid is required', exitCode: 1 };\n }\n\n const doc = (await client.retrieveDocument(docid)) as AgentDocument;\n const metaKbid = doc.sections[0]?.kbid;\n const skillRefs = doc.sections.slice(1);\n\n const { name, description, persona } = metaKbid\n ? await readAgentMeta(client, metaKbid, doc.title)\n : { name: doc.title, description: '', persona: '' };\n\n const skills = await resolveSkills(client, skillRefs);\n\n return {\n output: JSON.stringify(\n { docid, name, description, persona, skills },\n null,\n 2,\n ),\n exitCode: 0,\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\n\n/**\n * Minimal client interface required by `runAgentDelete`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface AgentDeleteClient {\n /**\n * Removes the document grouping for the given document.\n *\n * The sections themselves are not deleted; only the grouping\n * record is removed.\n *\n * @param docid - identifier of the document grouping to remove\n */\n removeGrouping(docid: string): Promise<void>;\n}\n\n/**\n * Deletes an agent from the knowledge base.\n *\n * Removes the document grouping identified by `options.args[0]`.\n * Skill sections referenced by the agent are not deleted; only\n * the grouping record is removed.\n *\n * @param client - agent delete client to delegate removal to\n * @param options - parsed CLI options; `args[0]` must be the docid\n * @returns a `CommandResult` confirming removal or an error message\n * with a non-zero exit code\n */\nexport async function runAgentDelete(\n client: AgentDeleteClient,\n options: CliOptions,\n): Promise<CommandResult> {\n const docid = options.args[0];\n if (!docid) {\n return { error: 'docid is required', exitCode: 1 };\n }\n await client.removeGrouping(docid);\n return {\n output: JSON.stringify({ docid, removed: true }, null, 2),\n exitCode: 0,\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\nimport type { PagedSearchDisplay } from '../typings/search-display.model.ts';\nimport type { LearnIO } from './run-learn.function.ts';\nimport type { SearchClient } from './run-search.function.ts';\nimport type { LearnClient } from './run-learn.function.ts';\nimport type { UnlearnClient } from './run-unlearn.function.ts';\nimport type { ContentClient } from './run-content.function.ts';\nimport type { CheckClient } from './run-check.function.ts';\nimport type { GcClient } from './run-gc.function.ts';\nimport type { RebuildClient } from './run-rebuild.function.ts';\nimport type { StatusClient } from './run-status.function.ts';\nimport type { DbMigrateClient } from './run-db-migrate.function.ts';\nimport type { SkillLearnClient } from './run-skill-learn.function.ts';\nimport type { SkillListClient } from './run-skill-list.function.ts';\nimport type { SkillGetClient } from './run-skill-get.function.ts';\nimport type { SkillDeleteClient } from './run-skill-delete.function.ts';\nimport type { AgentCreateClient } from './run-agent-create.function.ts';\nimport type { AgentListClient } from './run-agent-list.function.ts';\nimport type { AgentGetClient } from './run-agent-get.function.ts';\nimport type { AgentDeleteClient } from './run-agent-delete.function.ts';\nimport type { RecallClient } from './run-recall.function.ts';\nimport type { ExportClient } from './run-export.function.ts';\nimport { runSearch } from './run-search.function.ts';\nimport { runLearn } from './run-learn.function.ts';\nimport { runUnlearn } from './run-unlearn.function.ts';\nimport { runContent } from './run-content.function.ts';\nimport { runCheck } from './run-check.function.ts';\nimport { runGc } from './run-gc.function.ts';\nimport { runRebuild } from './run-rebuild.function.ts';\nimport { runStatus } from './run-status.function.ts';\nimport { runDbInit } from './run-db-init.function.ts';\nimport { runInit } from './run-init.function.ts';\nimport { runDbMigrate } from './run-db-migrate.function.ts';\nimport { runSkillLearn } from './run-skill-learn.function.ts';\nimport { runSkillList } from './run-skill-list.function.ts';\nimport { runSkillGet } from './run-skill-get.function.ts';\nimport { runSkillDelete } from './run-skill-delete.function.ts';\nimport { runAgentCreate } from './run-agent-create.function.ts';\nimport { runAgentList } from './run-agent-list.function.ts';\nimport { runAgentGet } from './run-agent-get.function.ts';\nimport { runAgentDelete } from './run-agent-delete.function.ts';\nimport { runRecall } from './run-recall.function.ts';\nimport { runExport } from './run-export.function.ts';\nimport { formatOutput } from './format-output.function.ts';\nimport { errorToMessage } from './error-to-message.function.ts';\n\n/**\n * Intersection of all data-command client interfaces.\n *\n * Each run* function defines its own minimal interface; this\n * intersection combines them so `dispatchCommand` can route\n * to any command handler with full type safety.\n */\nexport type DispatchClient = SearchClient &\n LearnClient &\n UnlearnClient &\n ContentClient &\n CheckClient &\n GcClient &\n RebuildClient &\n StatusClient &\n DbMigrateClient &\n SkillLearnClient &\n SkillListClient &\n SkillGetClient &\n SkillDeleteClient &\n AgentCreateClient &\n AgentListClient &\n AgentGetClient &\n AgentDeleteClient &\n RecallClient &\n ExportClient;\n\n/**\n * Routes a parsed CLI command to the appropriate handler and\n * returns a `CommandResult` without touching process globals.\n *\n * @param client - worker client covering all data commands\n * @param options - parsed CLI options with command and args\n * @param io - optional injectable I/O for learn stdin\n */\nexport async function dispatchCommand(\n client: DispatchClient,\n options: CliOptions,\n io?: LearnIO,\n): Promise<CommandResult> {\n switch (options.command) {\n case 'learn':\n return handleLearn(client, options, io);\n case 'unlearn':\n return handleUnlearn(client, options);\n case 'search':\n return handleSearch(client, options);\n case 'recall':\n return handleRecall(client, options);\n case 'content':\n return handleContent(client, options);\n case 'check':\n return handleCheck(client, options);\n case 'gc':\n return handleGc(client, options);\n case 'rebuild':\n return handleRebuild(client, options);\n case 'status':\n return handleStatus(client, options);\n case 'export':\n return handleExport(client, options);\n case 'db-init':\n return handleDbInit(options);\n case 'db-migrate':\n return handleDbMigrate(client, options);\n case 'skill-learn': {\n const result = await runSkillLearn(client, options);\n return result;\n }\n case 'skill-list': {\n const result = await runSkillList(client, options);\n return result;\n }\n case 'skill-get': {\n const result = await runSkillGet(client, options);\n return result;\n }\n case 'skill-delete': {\n const result = await runSkillDelete(client, options);\n return result;\n }\n case 'agent-create': {\n const result = await runAgentCreate(client, options);\n return result;\n }\n case 'agent-list': {\n const result = await runAgentList(client, options);\n return result;\n }\n case 'agent-get': {\n const result = await runAgentGet(client, options);\n return result;\n }\n case 'agent-delete': {\n const result = await runAgentDelete(client, options);\n return result;\n }\n default:\n return {\n error: `unknown command: ${options.command}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleLearn(\n client: DispatchClient,\n options: CliOptions,\n io?: LearnIO,\n): Promise<CommandResult> {\n try {\n const results = await runLearn(client, options, io);\n return {\n output: JSON.stringify(results, null, 2),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `learn failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleUnlearn(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const results = await runUnlearn(client, options);\n return {\n output: JSON.stringify(results, null, 2),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `unlearn failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleSearch(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const results = await runSearch(client, options);\n if (options.content) {\n await hydrateSearchPreviews(client, results);\n }\n return {\n output: formatOutput(results, options.format),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `search failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleRecall(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const result = await runRecall(client, options);\n if ('error' in result) {\n return {\n error: `error: ${result.error}`,\n exitCode: 1,\n };\n }\n return {\n output: JSON.stringify(result, null, 2),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `recall failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleExport(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const result = await runExport(client, options);\n return {\n output: JSON.stringify(result, null, 2),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `export failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleContent(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const result = await runContent(client, options);\n return {\n output: JSON.stringify(result, null, 2),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `content failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleCheck(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const result = await runCheck(client, options);\n return {\n output: JSON.stringify(result, null, 2),\n exitCode: result.ok ? 0 : 1,\n };\n } catch (err) {\n return {\n error: `check failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleGc(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const result = await runGc(client, options);\n return {\n output: JSON.stringify(result, null, 2),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `gc failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleRebuild(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const result = await runRebuild(client, options);\n return {\n output: JSON.stringify(result, null, 2),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `rebuild failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleStatus(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const result = await runStatus(client, options);\n return {\n output: JSON.stringify(result, null, 2),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `status failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nfunction handleDbInit(options: CliOptions): CommandResult {\n return runDbInit(options, runInit);\n}\n\nasync function handleDbMigrate(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const result = await runDbMigrate(client, options);\n return {\n output: JSON.stringify(result, null, 2),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `db-migrate failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\n/**\n * Hydrates each result's `preview` field with the actual section\n * content fetched from the client.\n *\n * Failures for individual results are caught and suppressed so that\n * one unavailable section does not prevent other previews from\n * being returned.\n *\n * @param client - content client used to fetch section text\n * @param results - mutable search display records to hydrate\n */\nasync function hydrateSearchPreviews(\n client: ContentClient,\n paged: PagedSearchDisplay,\n): Promise<void> {\n await Promise.all(\n paged.items.map(async (result) => {\n try {\n const contentResult = await client.content([result.kbid]);\n result.preview = contentResult.data;\n } catch {\n // Leave preview as empty string on failure.\n }\n }),\n );\n}\n", "/** Current package version, kept in sync with package.json. */\nexport const VERSION = '0.2.2';\n", "import { VERSION } from '../../version/index.ts';\n\n/**\n * The set of all recognised top-level command names,\n * including group commands (`db`, `skill`, `agent`).\n */\nconst KNOWN_COMMANDS = new Set([\n 'learn',\n 'unlearn',\n 'search',\n 'recall',\n 'content',\n 'check',\n 'gc',\n 'rebuild',\n 'status',\n 'export',\n 'mcp',\n 'db',\n 'skill',\n 'agent',\n]);\n\n/** Subcommands available under each group command. */\nconst GROUP_SUBCOMMANDS: Readonly<\n Record<string, readonly (readonly [string, string])[]>\n> = {\n db: [\n ['init', 'Initialise a new .kbdb directory'],\n ['migrate', 'Migrate database to current format'],\n ],\n skill: [\n ['learn', 'Create a new skill definition'],\n ['list', 'List all skills'],\n ['get', 'Retrieve a skill by name or kbid'],\n ['delete', 'Remove a skill'],\n ],\n agent: [\n ['create', 'Create an agent with skill refs'],\n ['list', 'List all agents'],\n ['get', 'Retrieve an agent by docid'],\n ['delete', 'Remove an agent'],\n ],\n};\n\n/**\n * Returns `true` when `cmd` is a recognised command name.\n *\n * Accepts both simple top-level names (`'learn'`, `'db'`)\n * and the hyphenated compound form produced by `parseArgs`\n * when a group + subcommand precedes `--help`\n * (e.g. `'db-init'`, `'skill-learn'`).\n */\nexport function isKnownCommand(cmd: string): boolean {\n if (KNOWN_COMMANDS.has(cmd)) {\n return true;\n }\n // Check hyphenated compound form: 'db-init', 'skill-learn'\n const dashIdx = cmd.indexOf('-');\n if (dashIdx < 0) {\n return false;\n }\n const group = cmd.slice(0, dashIdx);\n return group in GROUP_SUBCOMMANDS;\n}\n\n/**\n * Generates contextual help text for the `kbdb` CLI.\n *\n * Three levels of detail are produced depending on\n * how many command tokens are supplied:\n *\n * - No arguments: global help listing all commands.\n * - `command` only: command-level help. When `command`\n * is a hyphenated compound (`'db-init'`), it is split\n * into group + subcommand automatically. Group\n * commands show a subcommand listing; leaf commands\n * show detailed help; unknown commands show an error\n * prefix followed by global help.\n * - `command` + `subcommand`: detailed help for that\n * specific subcommand (falls back to group help when\n * the subcommand is not recognised).\n *\n * @param command - optional top-level command token,\n * or a hyphenated compound such as `'db-init'`\n * @param subcommand - optional subcommand token\n */\nexport function generateHelp(\n command?: string,\n subcommand?: string,\n): string {\n if (!command) {\n return generateGlobalHelp();\n }\n // Handle compound form produced by parseArgs:\n // 'db-init' -> group='db', sub='init'\n if (!subcommand && command.includes('-')) {\n const dashIdx = command.indexOf('-');\n const group = command.slice(0, dashIdx);\n const sub = command.slice(dashIdx + 1);\n if (group in GROUP_SUBCOMMANDS) {\n return generateSubcommandHelp(group, sub);\n }\n }\n if (subcommand) {\n return generateSubcommandHelp(command, subcommand);\n }\n return generateCommandHelp(command);\n}\n\n// ---------------------------------------------------------------------------\n// Level 1: Global help\n// ---------------------------------------------------------------------------\n\nfunction generateGlobalHelp(): string {\n return (\n `kbdb v${VERSION} - File-based knowledge base` +\n ` database for AI agents\\n` +\n `\\n` +\n `Usage: kbdb [options]\\n` +\n ` kbdb <command> [options] ...[parameters]\\n` +\n ` kbdb <command> <subcommand> [options]` +\n ` ...[params]\\n` +\n `\\n` +\n `Knowledge Base:\\n` +\n ` learn Import content from` +\n ` files/stdin\\n` +\n ` unlearn Remove sections by kbid\\n` +\n ` search Query the knowledge base\\n` +\n ` recall Retrieve section context` +\n ` by kbid\\n` +\n ` content Compose rendered content` +\n ` from ids\\n` +\n `\\n` +\n `Database:\\n` +\n ` db init Initialise a new .kbdb` +\n ` directory\\n` +\n ` db migrate Migrate database to current` +\n ` format\\n` +\n `\\n` +\n `Maintenance:\\n` +\n ` check Verify knowledge base` +\n ` integrity\\n` +\n ` gc Garbage collect unreferenced\\n` +\n ` sections\\n` +\n ` rebuild Reconstruct all index` +\n ` files\\n` +\n ` status Show database status\\n` +\n ` export Snapshot database for` +\n ` backup\\n` +\n `\\n` +\n `Skills:\\n` +\n ` skill learn Create a new skill` +\n ` definition\\n` +\n ` skill list List all skills\\n` +\n ` skill get Retrieve a skill by name` +\n ` or kbid\\n` +\n ` skill delete Remove a skill\\n` +\n `\\n` +\n `Agents:\\n` +\n ` agent create Create an agent with skill` +\n ` refs\\n` +\n ` agent list List all agents\\n` +\n ` agent get Retrieve an agent by docid\\n` +\n ` agent delete Remove an agent\\n` +\n `\\n` +\n `Server:\\n` +\n ` mcp Start MCP server mode` +\n ` (stdio)\\n` +\n `\\n` +\n `Global Options:\\n` +\n ` -h, --help Show this help message\\n` +\n ` -v, --version Show version information\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n ` --format <fmt> Output format` +\n ` (json|text|mcp)\\n` +\n `\\n` +\n `Run \"kbdb <command> --help\" for detailed` +\n ` information.\\n`\n );\n}\n\n// ---------------------------------------------------------------------------\n// Level 2: Command help\n// ---------------------------------------------------------------------------\n\nfunction generateCommandHelp(command: string): string {\n if (command in GROUP_SUBCOMMANDS) {\n return generateGroupHelp(command);\n }\n const leaf = LEAF_HELP[command];\n if (leaf) {\n return leaf;\n }\n return `Unknown command: ${command}\\n\\n` + generateGlobalHelp();\n}\n\nfunction generateGroupHelp(group: string): string {\n const subs = GROUP_SUBCOMMANDS[group] ?? [];\n const subLines = subs\n .map(([name, desc]) => ` ${name.padEnd(20)}${desc}`)\n .join('\\n');\n const desc = GROUP_DESCRIPTIONS[group] ?? group;\n return (\n `kbdb ${group} - ${desc}\\n` +\n `\\n` +\n `Usage: kbdb ${group} <subcommand> [options]\\n` +\n `\\n` +\n `Subcommands:\\n` +\n `${subLines}\\n` +\n `\\n` +\n `Global Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n ` -h, --help Show this help message\\n` +\n `\\n` +\n `Run \"kbdb ${group} <subcommand> --help\"` +\n ` for details.\\n`\n );\n}\n\n/** One-line description for each group command. */\nconst GROUP_DESCRIPTIONS: Readonly<Record<string, string>> = {\n db: 'Database management',\n skill: 'Skill management',\n agent: 'Agent management',\n};\n\n// ---------------------------------------------------------------------------\n// Leaf command help texts\n// ---------------------------------------------------------------------------\n\nconst LEAF_HELP: Readonly<Record<string, string>> = {\n learn:\n `kbdb learn - Import content from files or stdin\\n` +\n `\\n` +\n `Usage: kbdb learn [options] <path | ->...\\n` +\n `\\n` +\n `Arguments:\\n` +\n ` <path | -> File path, directory,` +\n ` or - for stdin\\n` +\n `\\n` +\n `Options:\\n` +\n ` --title <title> Section title\\n` +\n ` --description <d> Section description\\n` +\n ` --docid <docid> Document ID to group` +\n ` under\\n` +\n ` --tags <t,...> Comma-separated tags\\n` +\n ` --replace Supersede existing section` +\n ` by source key\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON array of { kbid, path, size, skipped,\\n` +\n ` superseded, warnings,` +\n ` near_duplicates }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb learn README.md\\n` +\n ` kbdb learn ./docs/\\n` +\n ` kbdb learn --tags auth,api --replace doc.md\\n` +\n ` cat notes.txt | kbdb learn -\\n`,\n\n unlearn:\n `kbdb unlearn - Remove sections by kbid\\n` +\n `\\n` +\n `Usage: kbdb unlearn [options] <kbid>...\\n` +\n `\\n` +\n `Arguments:\\n` +\n ` <kbid> 26-character knowledge` +\n ` base identifier\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON array of { kbid, removed }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb unlearn abcdef1234567890abcdef1234\\n` +\n ` kbdb unlearn id1 id2 id3\\n`,\n\n search:\n `kbdb search - Query the knowledge base\\n` +\n `\\n` +\n `Usage: kbdb search [options] <query>...\\n` +\n `\\n` +\n `Arguments:\\n` +\n ` <query> One or more query terms\\n` +\n `\\n` +\n `Options:\\n` +\n ` --mode <mode> Result granularity` +\n ` (sections|documents|stats)\\n` +\n ` --limit <n> Max results (default: 20)\\n` +\n ` --format <fmt> Output format` +\n ` (json|text|mcp)\\n` +\n ` --content, -c Hydrate results with` +\n ` section content\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON array of { kbid, score, preview,` +\n ` matches }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb search \"machine learning\"\\n` +\n ` kbdb search --limit 5 --format text query\\n` +\n ` kbdb search --mode documents --content term\\n`,\n\n recall:\n `kbdb recall - Retrieve section context by kbid\\n` +\n `\\n` +\n `Usage: kbdb recall [options] <kbid>...\\n` +\n `\\n` +\n `Arguments:\\n` +\n ` <kbid> 26-character knowledge` +\n ` base identifier\\n` +\n `\\n` +\n `Options:\\n` +\n ` --depth <n>, -d Expansion depth (0-3,` +\n ` default: 0)\\n` +\n ` --tags <t,...> Filter by tags\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON RecallResult or RecallResult[]\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb recall abcdef1234567890abcdef1234\\n` +\n ` kbdb recall kbid1 --depth 2\\n`,\n\n content:\n `kbdb content - Compose rendered content from ids\\n` +\n `\\n` +\n `Usage: kbdb content [options] <id>...\\n` +\n `\\n` +\n `Arguments:\\n` +\n ` <id> kbid or docid identifier\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON { type, data, total }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb content abcdef1234567890abcdef1234\\n` +\n ` kbdb content id1 id2\\n`,\n\n check:\n `kbdb check - Verify knowledge base integrity\\n` +\n `\\n` +\n `Usage: kbdb check [options]\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON { ok, errors }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb check\\n` +\n ` kbdb check --db /path/to/project\\n`,\n\n gc:\n `kbdb gc - Garbage collect unreferenced sections\\n` +\n `\\n` +\n `Usage: kbdb gc [options]\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON { removed_sections, removed_bytes }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb gc\\n` +\n ` kbdb gc --db /path/to/project\\n`,\n\n rebuild:\n `kbdb rebuild - Reconstruct all index files\\n` +\n `\\n` +\n `Usage: kbdb rebuild [options]\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON { sections_reindexed, terms_indexed }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb rebuild\\n` +\n ` kbdb rebuild --db /path/to/project\\n`,\n\n status:\n `kbdb status - Show database status\\n` +\n `\\n` +\n `Usage: kbdb status [options]\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON database status object\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb status\\n` +\n ` kbdb status --db /path/to/project\\n`,\n\n export:\n `kbdb export - Snapshot database for backup\\n` +\n `\\n` +\n `Usage: kbdb export [options] [<path>]\\n` +\n `\\n` +\n `Arguments:\\n` +\n ` <path> Output directory path\\n` +\n ` (default: ./kbdb-export/)\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON { path, sections_exported,` +\n ` documents_exported }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb export\\n` +\n ` kbdb export ./my-backup\\n` +\n ` kbdb export --db /path/to/project\\n`,\n\n mcp:\n `kbdb mcp - Start MCP server mode (stdio)\\n` +\n `\\n` +\n `Usage: kbdb mcp [options]\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Environment:\\n` +\n ` KBDB_DIR Fallback database path\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb mcp --db /path/to/project\\n` +\n ` KBDB_DIR=/path/to/project kbdb mcp\\n`,\n};\n\n// ---------------------------------------------------------------------------\n// Level 3: Subcommand help\n// ---------------------------------------------------------------------------\n\n/**\n * Detailed help texts keyed by `\"group-subcommand\"`.\n * Falls back to group help when the key is absent.\n */\nconst SUBCOMMAND_HELP: Readonly<Record<string, string>> = {\n 'db-init':\n `kbdb db init - Initialise a new .kbdb directory\\n` +\n `\\n` +\n `Usage: kbdb db init [options]\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to create .kbdb in\\n` +\n ` (default: current directory)\\n` +\n ` -h, --help Show this help message\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON { path, created }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb db init\\n` +\n ` kbdb db init --db /path/to/project\\n`,\n\n 'db-migrate':\n `kbdb db migrate - Migrate database to current` +\n ` format\\n` +\n `\\n` +\n `Usage: kbdb db migrate [options]\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path containing .kbdb\\n` +\n ` (default: current directory)\\n` +\n ` -h, --help Show this help message\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON MigrateResult or \"already up to date\"\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb db migrate\\n` +\n ` kbdb db migrate --db /path/to/project\\n`,\n\n 'skill-learn':\n `kbdb skill learn - Create a new skill definition\\n` +\n `\\n` +\n `Usage: kbdb skill learn [options]` +\n ` --name <n> --body <file|->\\n` +\n `\\n` +\n `Options:\\n` +\n ` --name <name> Skill name (required)\\n` +\n ` --description <d> Skill description\\n` +\n ` --body <file|-> Template body file or` +\n ` stdin (required)\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON { kbid, name, arguments }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb skill learn --name summarize` +\n ` --body prompt.txt\\n` +\n ` cat body.txt | kbdb skill learn` +\n ` --name my-skill --body -\\n`,\n\n 'skill-list':\n `kbdb skill list - List all skills\\n` +\n `\\n` +\n `Usage: kbdb skill list [options]\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON array of { kbid, name, description,` +\n ` argumentCount }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb skill list\\n` +\n ` kbdb skill list --db /path/to/project\\n`,\n\n 'skill-get':\n `kbdb skill get - Retrieve a skill by name` +\n ` or kbid\\n` +\n `\\n` +\n `Usage: kbdb skill get [options] <name-or-kbid>\\n` +\n `\\n` +\n `Arguments:\\n` +\n ` <name-or-kbid> Skill name or 26-char` +\n ` kbid\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON SkillDefinition object\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb skill get summarize-document\\n` +\n ` kbdb skill get abcdef1234567890abcdef1234\\n`,\n\n 'skill-delete':\n `kbdb skill delete - Remove a skill\\n` +\n `\\n` +\n `Usage: kbdb skill delete [options] <kbid>\\n` +\n `\\n` +\n `Arguments:\\n` +\n ` <kbid> 26-character kbid of the` +\n ` skill to remove\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON { kbid, removed }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb skill delete abcdef1234567890abcdef1234\\n`,\n\n 'agent-create':\n `kbdb agent create - Create an agent with skill` +\n ` refs\\n` +\n `\\n` +\n `Usage: kbdb agent create [options] --name <n>` +\n ` --persona <file|-> --skills <kbid,...>\\n` +\n `\\n` +\n `Options:\\n` +\n ` --name <name> Agent name (required)\\n` +\n ` --description <d> Agent description\\n` +\n ` --persona <file|-> Persona file or stdin` +\n ` (required)\\n` +\n ` --skills <kbid,...> Comma-separated skill` +\n ` kbids (required)\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON { docid, name, skills }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb agent create --name code-reviewer` +\n ` --persona ./p.txt --skills abc123\\n` +\n ` cat persona.txt | kbdb agent create` +\n ` --name my-agent --persona - --skills abc123\\n`,\n\n 'agent-list':\n `kbdb agent list - List all agents\\n` +\n `\\n` +\n `Usage: kbdb agent list [options]\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON array of { docid, name, description,` +\n ` skillCount }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb agent list\\n` +\n ` kbdb agent list --db /path/to/project\\n`,\n\n 'agent-get':\n `kbdb agent get - Retrieve an agent by docid\\n` +\n `\\n` +\n `Usage: kbdb agent get [options] <docid>\\n` +\n `\\n` +\n `Arguments:\\n` +\n ` <docid> Agent document identifier\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON AgentDefinition object with resolved` +\n ` skills\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb agent get agent-code-reviewer\\n`,\n\n 'agent-delete':\n `kbdb agent delete - Remove an agent\\n` +\n `\\n` +\n `Usage: kbdb agent delete [options] <docid>\\n` +\n `\\n` +\n `Arguments:\\n` +\n ` <docid> Agent document identifier\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON { docid, removed }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb agent delete agent-code-reviewer\\n`,\n};\n\nfunction generateSubcommandHelp(\n command: string,\n subcommand: string,\n): string {\n const key = `${command}-${subcommand}`;\n const text = SUBCOMMAND_HELP[key];\n if (text) {\n return text;\n }\n // Fall back to group help when subcommand is unknown\n return generateCommandHelp(command);\n}\n", "import { VERSION } from '../../version/index.ts';\nimport type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\nimport type { InitResult } from './run-init.function.ts';\nimport type { VersionStatus } from '../../worker-client/typings/version-status.model.ts';\nimport type { MigrateResult } from '../../worker-client/typings/migrate-result.model.ts';\nimport { parseArgs } from './parse-args.function.ts';\nimport { errorToMessage } from './error-to-message.function.ts';\nimport { dispatchCommand } from './dispatch-command.function.ts';\nimport type { DispatchClient } from './dispatch-command.function.ts';\nimport {\n generateHelp,\n isKnownCommand,\n} from './generate-help.function.ts';\n\nexport interface DisconnectableClient extends DispatchClient {\n checkVersion(targetPath: string): Promise<VersionStatus>;\n migrateDatabase(targetPath: string): Promise<MigrateResult>;\n disconnect(): void;\n}\n\n/**\n * Injectable dependencies for the CLI orchestrator.\n *\n * Every external side-effect is injected so the function\n * is fully testable without touching process globals,\n * filesystem, or network.\n */\nexport interface CliDeps {\n isStdinTty: () => boolean;\n promptUser: (question: string) => Promise<string>;\n createWorkerClient: (opts: {\n contextPath: string;\n }) => Promise<DisconnectableClient>;\n findDb: (basePath?: string) => string | null;\n runInit: (options: CliOptions) => InitResult;\n startMcpServer?: (contextPath: string) => Promise<void>;\n}\n\n/**\n * Full CLI orchestrator extracted from `src/cli.ts`.\n *\n * Parses arguments, routes to the appropriate sub-flow\n * (help, version, init, mcp, migrate, data commands), and\n * returns a `CommandResult` without touching process globals.\n *\n * @param argv - raw CLI arguments (typically `process.argv.slice(2)`)\n * @param deps - injectable dependencies\n */\nexport async function runCli(\n argv: string[],\n deps: CliDeps,\n): Promise<CommandResult> {\n const options = parseArgs(argv);\n\n if (options.command === 'help' || !options.command) {\n const helpCommand = options.args[0];\n const helpSubcommand = options.args[1];\n const helpText = generateHelp(helpCommand, helpSubcommand);\n if (helpCommand && !isKnownCommand(helpCommand)) {\n return { output: helpText, exitCode: 1 };\n }\n return { output: helpText, exitCode: 0 };\n }\n\n if (options.command === 'version') {\n return { output: VERSION, exitCode: 0 };\n }\n\n if (options.command === 'init' || options.command === 'db-init') {\n return handleInit(options, deps);\n }\n\n if (options.command === 'mcp') {\n return handleMcp(options, deps);\n }\n\n if (\n options.command === 'migrate' ||\n options.command === 'db-migrate'\n ) {\n return handleMigrate(options, deps);\n }\n\n return handleDataCommand(options, deps);\n}\n\nfunction handleInit(options: CliOptions, deps: CliDeps): CommandResult {\n const result = deps.runInit(options);\n if (result.ok) {\n return {\n output: result.targetPath,\n exitCode: 0,\n };\n }\n return {\n error: `error: ${result.errorMessage ?? 'init failed'}`,\n exitCode: 1,\n };\n}\n\nasync function handleMcp(\n options: CliOptions,\n deps: CliDeps,\n): Promise<CommandResult> {\n const rawDbPath = options.dbPath ?? process.env['KBDB_DIR'];\n if (!rawDbPath) {\n return {\n error: 'error: --db or KBDB_DIR required in MCP mode',\n exitCode: 1,\n };\n }\n const dbDir = deps.findDb(rawDbPath);\n if (!dbDir) {\n return {\n error: `error: no .kbdb database found at ${rawDbPath}`,\n exitCode: 1,\n };\n }\n\n let client: DisconnectableClient;\n try {\n client = await deps.createWorkerClient({\n contextPath: dbDir,\n });\n } catch (err) {\n return {\n error: `error: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n\n try {\n const gateResult = await versionGate(client, dbDir);\n if (gateResult) return gateResult;\n\n if (deps.startMcpServer) {\n await deps.startMcpServer(dbDir);\n }\n return { exitCode: 0 };\n } catch (err) {\n return {\n error: `error: mcp failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n } finally {\n client.disconnect();\n }\n}\n\nasync function handleMigrate(\n options: CliOptions,\n deps: CliDeps,\n): Promise<CommandResult> {\n const dbDir = deps.findDb(options.dbPath);\n if (!dbDir) {\n const basePath = options.dbPath ?? process.cwd();\n return {\n error: `error: no .kbdb database found at ${basePath}`,\n exitCode: 1,\n };\n }\n\n let client: DisconnectableClient;\n try {\n client = await deps.createWorkerClient({\n contextPath: dbDir,\n });\n } catch (err) {\n return {\n error: `error: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n\n try {\n const versionStatus = await client.checkVersion(dbDir);\n\n if (versionStatus.status === 'too_new') {\n return {\n error:\n `error: database version` +\n ` ${versionStatus.currentVersion.toString()}` +\n ` is newer than kbdb version` +\n ` ${versionStatus.requiredVersion.toString()}` +\n ` -- upgrade kbdb`,\n exitCode: 1,\n };\n }\n\n if (versionStatus.status === 'needs_migration') {\n const migrateResult = await client.migrateDatabase(dbDir);\n return {\n output: JSON.stringify(migrateResult, null, 2),\n exitCode: 0,\n };\n }\n\n return { output: 'already up to date', exitCode: 0 };\n } catch (err) {\n return {\n error: `error: migrate failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n } finally {\n client.disconnect();\n }\n}\n\nasync function handleDataCommand(\n options: CliOptions,\n deps: CliDeps,\n): Promise<CommandResult> {\n let dbDir = deps.findDb(options.dbPath);\n\n if (!dbDir) {\n const basePath = options.dbPath ?? process.cwd();\n\n if (!deps.isStdinTty()) {\n return {\n error:\n `error: no .kbdb database found at ${basePath}` +\n ' -- run `kbdb --init` to create one',\n exitCode: 1,\n };\n }\n\n const answer = await deps.promptUser(\n `No .kbdb database found. Create one in ${basePath}? [y/N] `,\n );\n\n if (answer.toLowerCase() !== 'y') {\n return {\n error: 'aborted: no database created',\n exitCode: 1,\n };\n }\n\n const initResult = deps.runInit(options);\n if (!initResult.ok) {\n return {\n error: `error: ${initResult.errorMessage ?? 'init failed'}`,\n exitCode: 1,\n };\n }\n dbDir = initResult.targetPath;\n }\n\n let client: DisconnectableClient;\n try {\n client = await deps.createWorkerClient({\n contextPath: dbDir,\n });\n } catch (err) {\n return {\n error: `error: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n\n try {\n const gateResult = await versionGate(client, dbDir);\n if (gateResult) return gateResult;\n\n return await dispatchCommand(client, options);\n } finally {\n client.disconnect();\n }\n}\n\nasync function versionGate(\n client: DisconnectableClient,\n dbDir: string,\n): Promise<CommandResult | null> {\n const versionStatus = await client.checkVersion(dbDir);\n\n if (versionStatus.status === 'needs_migration') {\n return {\n error:\n 'error: database needs migration' +\n ' -- run `kbdb --migrate`',\n exitCode: 1,\n };\n }\n\n if (versionStatus.status === 'too_new') {\n return {\n error:\n `error: database version` +\n ` ${versionStatus.currentVersion.toString()}` +\n ` is newer than kbdb version` +\n ` ${versionStatus.requiredVersion.toString()}` +\n ` -- upgrade kbdb`,\n exitCode: 1,\n };\n }\n\n return null;\n}\n", "import { generateHelp } from '../functions/generate-help.function.ts';\n\n/** Global help text for the kbdb CLI. */\nexport const HELP_TEXT = generateHelp();\n", "import { connect } from 'node:net';\nimport type { Socket } from 'node:net';\nimport type { SearchParams } from '../typings/search-params.model.ts';\nimport type { PagedSearchResult } from '../typings/search-result.model.ts';\nimport type {\n AddSectionParams,\n Section,\n} from '../typings/section.model.ts';\nimport type { StatusResult } from '../typings/status-result.model.ts';\nimport type { AddSectionResult } from '../typings/add-section-result.model.ts';\nimport type { RemoveSectionResult } from '../typings/remove-section-result.model.ts';\nimport type { ContentResult } from '../typings/content-result.model.ts';\nimport type { IntegrityCheckResult } from '../typings/integrity-check-result.model.ts';\nimport type { GcResult } from '../typings/gc-result.model.ts';\nimport type { RebuildResult } from '../typings/rebuild-result.model.ts';\nimport type { MigrateResult } from '../typings/migrate-result.model.ts';\nimport type { VersionStatus } from '../typings/version-status.model.ts';\nimport type { SectionRecord } from '../../wasm-codec/functions/decode-section-records.function.ts';\nimport type { DocumentManifest } from '../../wasm-codec/functions/decode-document-manifest.function.ts';\nimport type {\n RecallParams,\n RecallResult,\n} from '../typings/recall-result.model.ts';\nimport type { ExportResult } from '../typings/export-result.model.ts';\n\n/** Pending JSON-RPC call awaiting a response from the daemon. */\ninterface PendingCall {\n resolve: (v: unknown) => void;\n reject: (e: Error) => void;\n}\n\n/** Shape of a JSON-RPC 2.0 error object from the daemon. */\ninterface JsonRpcError {\n readonly code: number;\n readonly message: string;\n}\n\n/** Shape of a JSON-RPC 2.0 response from the daemon. */\ninterface JsonRpcResponse {\n readonly id: number;\n readonly result?: unknown;\n readonly error?: JsonRpcError;\n}\n\n/**\n * IPC client that communicates with the worker daemon over a Unix\n * domain socket (or Windows named pipe) using JSON-RPC 2.0 with\n * newline-delimited message framing.\n *\n * Call `connect()` before any other method and `disconnect()` when\n * done to release the underlying socket.\n */\nexport class WorkerClient {\n /** Underlying socket; `null` when not connected. */\n private socket: Socket | null = null;\n\n /** Monotonically increasing request ID counter. */\n private nextId = 1;\n\n /** Map of outstanding request IDs to their resolve/reject pairs. */\n private readonly pending = new Map<number, PendingCall>();\n\n /** Partial line buffer for split TCP/IPC frames. */\n private buffer = '';\n\n /**\n * @param socketPath - absolute path to the daemon's IPC socket\n * (or Windows named pipe path)\n * @param contextId - 16-character context identifier sent as\n * `ctx` in every JSON-RPC request\n */\n constructor(\n private readonly socketPath: string,\n private readonly contextId: string,\n ) {}\n\n /**\n * Establishes the IPC connection to the worker daemon.\n *\n * @throws {Error} if the connection cannot be established\n */\n async connect(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.socket = connect(this.socketPath, () => {\n resolve();\n });\n this.socket.on('error', (err: Error) => {\n reject(err);\n });\n this.socket.on('data', (chunk: Buffer) => {\n this.handleData(chunk.toString());\n });\n });\n }\n\n /** Destroys the IPC socket and clears the connection state. */\n disconnect(): void {\n if (this.socket) {\n this.socket.destroy();\n this.socket = null;\n }\n }\n\n /**\n * Searches the knowledge base.\n *\n * @param params - query parameters including the search string\n * @returns paginated search results with metadata\n */\n async search(params: SearchParams): Promise<PagedSearchResult> {\n return this.call('search', params) as Promise<PagedSearchResult>;\n }\n\n /**\n * Retrieves full content and context for one or more sections by\n * their knowledge-base identifiers.\n *\n * @param params - section identifier(s) and optional expansion depth\n * @returns a single `RecallResult` when `kbid` is provided without\n * `kbids`, or a `RecallResult[]` when `kbids` is provided\n */\n async recall(\n params: RecallParams,\n ): Promise<RecallResult | RecallResult[]> {\n return this.call('recall', params) as Promise<\n RecallResult | RecallResult[]\n >;\n }\n\n /**\n * Adds a new section to the knowledge base.\n *\n * @param params - section content and metadata\n * @returns the result including the assigned knowledge-base\n * identifier and indexing statistics\n */\n async addSection(\n params: AddSectionParams,\n ): Promise<AddSectionResult> {\n return this.call(\n 'addSection',\n params,\n ) as Promise<AddSectionResult>;\n }\n\n /**\n * Replaces an existing section's content and metadata.\n *\n * @param kbid - identifier of the section to update\n * @param params - new content and metadata\n * @returns the knowledge-base identifier of the updated section\n */\n async updateSection(\n kbid: string,\n params: AddSectionParams,\n ): Promise<string> {\n return this.call('updateSection', {\n kbid,\n ...params,\n }) as Promise<string>;\n }\n\n /**\n * Removes a section from the knowledge base.\n *\n * @param kbid - identifier of the section to remove\n * @returns removal result with `removed` flag and elapsed time\n */\n async removeSection(kbid: string): Promise<RemoveSectionResult> {\n return this.call('removeSection', {\n kbid,\n }) as Promise<RemoveSectionResult>;\n }\n\n /**\n * Retrieves multiple sections by their identifiers.\n *\n * @param kbids - list of knowledge-base identifiers to fetch\n * @returns sections in the order their IDs were requested\n */\n async readSections(kbids: string[]): Promise<Section[]> {\n return this.call('readSections', {\n kbids,\n }) as Promise<Section[]>;\n }\n\n /**\n * Groups a set of sections under a named document.\n *\n * @param title - human-readable document title\n * @param kbids - identifiers of the sections to group\n * @param docType - application-level document type tag; omit or\n * pass an empty string for untagged documents\n * @returns the assigned document identifier\n */\n async groupSections(\n title: string,\n kbids: string[],\n docType?: string,\n ): Promise<string> {\n const result = (await this.call('groupSections', {\n title,\n kbids,\n docType: docType ?? '',\n })) as { docid: string } | string;\n return typeof result === 'string' ? result : result.docid;\n }\n\n /**\n * Removes the document grouping for the given document.\n *\n * The sections themselves are not deleted; only the grouping\n * record is removed.\n *\n * @param docid - identifier of the document grouping to remove\n */\n async removeGrouping(docid: string): Promise<void> {\n await this.call('removeGrouping', { docid });\n }\n\n /**\n * Retrieves a full document record including its sections.\n *\n * @param docid - identifier of the document to retrieve\n * @returns the document record as returned by the daemon\n */\n async retrieveDocument(docid: string): Promise<unknown> {\n return this.call('retrieveDocument', { docid });\n }\n\n /**\n * Composes a rendered Markdown document from one or more kbid\n * or docid identifiers.\n *\n * @param ids - list of kbid or docid identifiers (may be mixed)\n * @returns composed Markdown result with character count\n */\n async content(ids: string[]): Promise<ContentResult> {\n return this.call('content', { ids }) as Promise<ContentResult>;\n }\n\n /**\n * Runs an integrity check on the knowledge-base database.\n *\n * @returns a report of all issues found; `ok` is `true` when\n * no errors were detected\n */\n async integrityCheck(): Promise<IntegrityCheckResult> {\n return this.call(\n 'integrityCheck',\n {},\n ) as Promise<IntegrityCheckResult>;\n }\n\n /**\n * Removes unreferenced sections from the database.\n *\n * @returns a report of sections removed and bytes freed\n */\n async gc(): Promise<GcResult> {\n return this.call('gc', {}) as Promise<GcResult>;\n }\n\n /**\n * Reconstructs all index files from section files and document\n * manifests on disk. Text and code sections are re-tokenized;\n * image sections are skipped.\n *\n * @returns a report of sections and terms re-indexed\n */\n async rebuildIndexes(): Promise<RebuildResult> {\n return this.call('rebuildIndexes', {}) as Promise<RebuildResult>;\n }\n\n /**\n * Invalidates the in-memory cache entry for a single section.\n *\n * @param kbid - identifier of the section to evict from cache\n */\n async invalidate(kbid: string): Promise<void> {\n await this.call('invalidate', { kbid });\n }\n\n /** Clears all entries from the daemon's in-memory cache. */\n async invalidateAll(): Promise<void> {\n await this.call('invalidateAll', {});\n }\n\n /**\n * Retrieves diagnostic status information from the daemon.\n *\n * @returns current initialization state and cache statistics\n */\n async status(): Promise<StatusResult> {\n return this.call('status', {}) as Promise<StatusResult>;\n }\n\n /**\n * Returns database metadata and status from the daemon,\n * including document count, section count, index size, and\n * cache statistics.\n *\n * @returns database metadata from the daemon's cached state\n */\n async dbStatus(): Promise<StatusResult> {\n return this.call('dbStatus', {}) as Promise<StatusResult>;\n }\n\n /**\n * Initialises a new `.kbdb` database directory at the given path\n * by sending an init request to the worker daemon.\n *\n * The daemon creates all required subdirectories and seed files via\n * the `worker_init_directory` WASM export.\n *\n * @param targetPath - absolute path to the directory that will\n * contain the new `.kbdb` database\n * @throws {Error} if the `.kbdb` directory already exists or the\n * daemon cannot create the layout\n */\n async initDirectory(targetPath: string): Promise<void> {\n await this.call('initDirectory', { targetPath });\n }\n\n /**\n * Runs all pending database migrations for the `.kbdb` directory\n * at the given path.\n *\n * Delegates to the `worker_migrate` WASM export on the daemon.\n * Each migration step updates `catalog.toml` on success, so\n * retrying after a partial failure is safe.\n *\n * @param targetPath - absolute path to the `.kbdb` database root\n * @returns migration report with old version, new version, and\n * number of migration steps applied\n */\n async migrateDatabase(targetPath: string): Promise<MigrateResult> {\n return this.call('migrateDatabase', {\n targetPath,\n }) as Promise<MigrateResult>;\n }\n\n /**\n * Checks the format version of the `.kbdb` database at the given\n * path against the version required by the current WASM engine.\n *\n * This is a read-only operation: it reads `catalog.toml` and\n * returns the compatibility status without making any changes.\n *\n * @param targetPath - absolute path to the `.kbdb` database root\n * @returns version compatibility report\n */\n async checkVersion(targetPath: string): Promise<VersionStatus> {\n return this.call('checkVersion', {\n targetPath,\n }) as Promise<VersionStatus>;\n }\n\n /**\n * Retrieves all sections whose type name matches the given string.\n *\n * @param sectionType - the application-level type name to filter by\n * @returns all section records with a matching type name\n */\n async listByType(sectionType: string): Promise<SectionRecord[]> {\n return this.call('listByType', {\n sectionType,\n }) as Promise<SectionRecord[]>;\n }\n\n /**\n * Retrieves all documents whose type name matches the given string.\n *\n * @param docType - the application-level document type to filter by\n * @returns all document manifests with a matching type name\n */\n async listDocumentsByType(\n docType: string,\n ): Promise<DocumentManifest[]> {\n return this.call('listDocumentsByType', {\n docType,\n }) as Promise<DocumentManifest[]>;\n }\n\n /**\n * Exports the database to a target directory on disk.\n *\n * Copies section files, document manifests, and `catalog.toml`\n * to `params.path`. Index files are not exported because they\n * are derivable from the section and document data.\n *\n * @param params - optional export parameters\n * @param params.path - target directory path; defaults to\n * `./kbdb-export/` when not provided\n * @returns export report with the resolved path and file counts\n */\n async export(params?: { path?: string }): Promise<ExportResult> {\n return this.call('export', {\n targetPath: params?.path || undefined,\n }) as Promise<ExportResult>;\n }\n\n /**\n * Sends a JSON-RPC 2.0 request and awaits the response.\n *\n * @param method - the RPC method name\n * @param params - parameters to include in the request\n * @throws {Error} if not connected\n * @throws {Error} when the daemon returns an error response\n */\n private async call(\n method: string,\n params: unknown,\n ): Promise<unknown> {\n const socket = this.socket;\n if (!socket) {\n throw new Error('not connected');\n }\n\n const id = this.nextId++;\n const request = {\n jsonrpc: '2.0',\n id,\n method,\n params: { ctx: this.contextId, ...(params as object) },\n };\n\n return new Promise<unknown>((resolve, reject) => {\n this.pending.set(id, { resolve, reject });\n socket.write(JSON.stringify(request) + '\\n');\n });\n }\n\n /**\n * Processes incoming data from the socket, splitting on newlines\n * and dispatching complete JSON-RPC response objects.\n *\n * @param data - raw string chunk received from the socket\n */\n private handleData(data: string): void {\n this.buffer += data;\n const lines = this.buffer.split('\\n');\n this.buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (!line.trim()) continue;\n try {\n const response = JSON.parse(line) as JsonRpcResponse;\n const pending = this.pending.get(response.id);\n if (pending) {\n this.pending.delete(response.id);\n if (response.error) {\n const err = new Error(response.error.message);\n (err as unknown as Record<string, unknown>).code =\n response.error.code;\n pending.reject(err);\n } else {\n pending.resolve(response.result);\n }\n }\n } catch {\n // Ignore unparseable lines\n }\n }\n }\n}\n", "import { existsSync, readFileSync, unlinkSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\nimport { WorkerClient } from '../classes/worker-client.class.ts';\nimport { resolveDbPath } from './resolve-db-path.function.ts';\nimport { computeContextId } from './compute-context-id.function.ts';\nimport { discoverDaemon } from './discover-daemon.function.ts';\nimport { spawnDaemon } from './spawn-daemon.function.ts';\nimport { waitForDaemon } from './wait-for-daemon.function.ts';\nimport { detectRuntime } from '../../runtime/functions/detect-runtime.ts';\nimport { getIpcPath } from '../../platform/functions/get-ipc-path.function.ts';\nimport type { WorkerClientOptions } from '../typings/worker-client-options.interface.ts';\n\n/**\n * Creates and connects a `WorkerClient` to the worker daemon.\n *\n * Resolves the context path, derives a stable context identifier,\n * and checks whether a daemon is already running. If no daemon is\n * found and `autoSpawn` is not `false`, a new daemon process is\n * spawned and the factory waits for its PID file to appear before\n * connecting.\n *\n * @param options - optional configuration for path resolution,\n * auto-spawn behaviour, and connection timeout\n * @returns a connected `WorkerClient` ready to send requests\n * @throws {Error} if the `.kbdb` directory cannot be found\n * @throws {Error} if the socket connection cannot be established\n */\nexport async function createWorkerClient(\n options?: WorkerClientOptions,\n): Promise<WorkerClient> {\n const dbPath =\n options?.contextPath ?? resolveDbPath(options?.dbPath);\n const contextId = await computeContextId(dbPath);\n const socketPath = getIpcPath(contextId);\n\n let daemon = discoverDaemon(contextId);\n\n if (!daemon && options?.autoSpawn !== false) {\n const runtime = detectRuntime();\n spawnDaemon(dbPath, runtime, options?.workerScript);\n await waitForDaemon(contextId, options?.connectTimeoutMs);\n daemon = discoverDaemon(contextId);\n }\n\n if (!daemon) {\n throw new Error(\n `kbdb worker daemon did not start: ${readCrashReason(contextId)}`,\n );\n }\n\n const client = new WorkerClient(socketPath, contextId);\n await client.connect();\n return client;\n}\n\nfunction readCrashReason(contextId: string): string {\n const crashPath = join(tmpdir(), `kbdb-${contextId}.crash`);\n if (!existsSync(crashPath)) {\n return 'daemon failed to start (no details available)';\n }\n try {\n const raw = readFileSync(crashPath, 'utf-8');\n const crash = JSON.parse(raw) as { error?: string };\n unlinkSync(crashPath);\n return crash.error ?? 'unknown error (crash log empty)';\n } catch {\n return 'daemon failed to start (crash log unreadable)';\n }\n}\n", "import { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\n\n/**\n * Resolves the absolute path to the `.kbdb` database directory.\n *\n * Searches for a `.kbdb` sub-directory inside `targetDir`. When\n * `targetDir` is omitted, `process.cwd()` is used as the base.\n *\n * @param targetDir - directory to search in; defaults to cwd\n * @throws {Error} if no `.kbdb` directory exists at the resolved\n * path\n */\nexport function resolveDbPath(targetDir?: string): string {\n const base = targetDir ? resolve(targetDir) : process.cwd();\n const dbPath = join(base, '.kbdb');\n if (!existsSync(dbPath)) {\n throw new Error(`database not found: ${dbPath}`);\n }\n return dbPath;\n}\n", "/**\n * Computes the SHA-256 hash of a UTF-8 string.\n *\n * Uses the Web Crypto API (`crypto.subtle`), which is available\n * in both Deno and Node.js >= 20 without additional imports.\n *\n * @param input - the string to hash\n * @returns lowercase hex-encoded SHA-256 digest (64 characters)\n */\nexport async function computeSha256(input: string): Promise<string> {\n const data = new TextEncoder().encode(input);\n const hash = await crypto.subtle.digest('SHA-256', data);\n const bytes = new Uint8Array(hash);\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n", "import { computeSha256 } from '../../hash/functions/compute-sha256.ts';\n\n/**\n * Computes a short context identifier for an absolute path.\n *\n * Hashes the path with SHA-256 and returns the first 16 hex\n * characters. The result is stable for the same input and unique\n * enough to avoid accidental collisions across typical path sets.\n *\n * @param absolutePath - the absolute filesystem path to identify\n * @returns a 16-character lowercase hex string\n */\nexport async function computeContextId(\n absolutePath: string,\n): Promise<string> {\n const hash = await computeSha256(absolutePath);\n return hash.slice(0, 16);\n}\n", "import { existsSync, readFileSync, unlinkSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\nimport { isProcessAlive } from '../../platform/functions/is-process-alive.function.ts';\nimport type { DaemonInfo } from '../typings/daemon-info.model.ts';\n\nexport type { DaemonInfo };\n\n/**\n * Discovers a running worker daemon for the given context.\n *\n * Reads the PID file at `<tmpdir>/kbdb-<contextId>.pid`. If the\n * file exists and the process is alive, returns its PID and the\n * expected socket path. If the file is stale (process dead or PID\n * unparseable), removes the PID file and returns `null`.\n *\n * @param contextId - the 16-character context identifier\n * @returns daemon location info, or `null` if no live daemon found\n */\nexport function discoverDaemon(contextId: string): DaemonInfo | null {\n const pidPath = join(tmpdir(), `kbdb-${contextId}.pid`);\n\n if (!existsSync(pidPath)) return null;\n\n const pidStr = readFileSync(pidPath, 'utf-8').trim();\n const pid = parseInt(pidStr, 10);\n\n if (isNaN(pid) || !isProcessAlive(pid)) {\n try {\n unlinkSync(pidPath);\n } catch {\n // Stale PID file removal is best-effort\n }\n return null;\n }\n\n const socketPath = join(tmpdir(), `kbdb-${contextId}.sock`);\n\n const crashPath = join(tmpdir(), `kbdb-${contextId}.crash`);\n try {\n unlinkSync(crashPath);\n } catch {\n // stale crash file removal is best-effort\n }\n\n return { pid, socketPath };\n}\n", "/**\n * Checks whether a process with the given PID is alive.\n *\n * Sends signal `0` to the process, which performs a permission\n * check without sending an actual signal. Returns `true` if the\n * process exists and is reachable, `false` otherwise.\n *\n * @param pid - the process identifier to probe\n */\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n", "import { spawn } from 'node:child_process';\nimport type { Runtime } from '../../runtime/typings/runtime.ts';\n\n/**\n * Spawns a detached worker daemon process for the given context.\n *\n * @param contextPath - absolute path to the context directory the\n * daemon should serve\n * @param runtime - the current JavaScript runtime environment\n * @param workerScript - absolute path to the worker daemon script,\n * resolved at the entry point by `resolveWorkerScript`\n */\nexport function spawnDaemon(\n contextPath: string,\n runtime: Runtime,\n workerScript?: string,\n): void {\n if (!workerScript) {\n throw new Error(\n 'workerScript must be provided' + ' (resolve at entry point)',\n );\n }\n const execPath = runtime === 'deno' ? 'deno' : process.execPath;\n\n const args =\n runtime === 'deno'\n ? ['run', '--allow-all', workerScript, contextPath]\n : [workerScript, contextPath];\n\n const child = spawn(execPath, args, {\n detached: true,\n stdio: 'ignore',\n });\n child.unref();\n}\n", "import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\n\n/** Default maximum wait time for the daemon PID file to appear. */\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/** Polling interval in milliseconds between existence checks. */\nconst POLL_INTERVAL_MS = 100;\n\n/**\n * Waits for the worker daemon's PID file to appear on disk.\n *\n * Polls every 100 ms until the PID file at\n * `<tmpdir>/kbdb-<contextId>.pid` exists or the timeout elapses.\n *\n * @param contextId - the 16-character context identifier\n * @param timeoutMs - maximum wait time in milliseconds; defaults\n * to 10 000 ms\n * @returns `true` if the PID file appeared before the timeout,\n * `false` otherwise\n */\nexport async function waitForDaemon(\n contextId: string,\n timeoutMs: number = DEFAULT_TIMEOUT_MS,\n): Promise<boolean> {\n const pidPath = join(tmpdir(), `kbdb-${contextId}.pid`);\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n if (existsSync(pidPath)) return true;\n await new Promise<void>((r) => setTimeout(r, POLL_INTERVAL_MS));\n }\n return false;\n}\n", "import { join } from 'node:path';\nimport { getTmpdir } from './get-tmpdir.function.ts';\n\n/**\n * Returns the platform-appropriate IPC socket path for a given\n * context identifier.\n *\n * On Windows, returns a named pipe path (`\\\\.\\pipe\\kbdb-<ctx>`).\n * On POSIX systems, returns a Unix domain socket path under the\n * system temp directory (`<tmpdir>/kbdb-<ctx>.sock`).\n *\n * @param ctx - unique context identifier embedded in the path\n */\nexport function getIpcPath(ctx: string): string {\n if (process.platform === 'win32') {\n return `\\\\\\\\.\\\\pipe\\\\kbdb-${ctx}`;\n }\n return join(getTmpdir(), `kbdb-${ctx}.sock`);\n}\n", "import { tmpdir } from 'node:os';\n\n/**\n * Returns the operating system's default temporary directory path.\n */\nexport function getTmpdir(): string {\n return tmpdir();\n}\n", "import { createInterface } from 'node:readline';\nimport { createToolDefinitions } from '../functions/create-tool-definitions.function.ts';\nimport { createResourceTemplates } from '../functions/create-resource-templates.function.ts';\nimport { handleToolCall } from '../functions/handle-tool-call.function.ts';\nimport { handleResourceRead } from '../functions/handle-resource-read.function.ts';\nimport { createPromptDefinitions } from '../functions/create-prompt-definitions.function.ts';\nimport { handlePromptGet } from '../functions/handle-prompt-get.function.ts';\nimport { handleCompletion } from '../functions/handle-completion.function.ts';\nimport { handleRootsList } from '../functions/handle-roots-list.function.ts';\nimport { shouldEmitLog } from '../functions/should-emit-log.function.ts';\nimport {\n PARSE_ERROR,\n METHOD_NOT_FOUND,\n RESOURCE_NOT_FOUND,\n} from '../constants/mcp-error-codes.constant.ts';\nimport type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\nimport type {\n McpRequest,\n McpResponse,\n} from '../typings/mcp-types.interface.ts';\nimport type { McpLogLevel } from '../typings/log-types.interface.ts';\nimport type {\n McpCompletionRef,\n McpCompletionArgument,\n} from '../functions/handle-completion.function.ts';\n\n/**\n * MCP server that speaks JSON-RPC 2.0 over stdio. Listens for\n * newline-delimited requests on `process.stdin`, dispatches each\n * to the appropriate knowledge-base operation via\n * `McpWorkerClient`, and writes JSON-RPC responses to\n * `process.stdout`.\n */\nexport class McpServer {\n private readonly client: McpWorkerClient;\n private readonly contextPath: string;\n private initialized = false;\n private hostCapabilities: Record<string, unknown> | null = null;\n private logLevel: McpLogLevel | null = null;\n private readonly subscriptions = new Set<string>();\n private nextRequestId = 1;\n private readonly pendingRequests = new Map<\n number,\n {\n resolve: (value: unknown) => void;\n reject: (reason: unknown) => void;\n timer: ReturnType<typeof setTimeout>;\n }\n >();\n\n constructor(client: McpWorkerClient, contextPath?: string) {\n this.client = client;\n this.contextPath = contextPath ?? '';\n }\n\n async listen(): Promise<void> {\n const rl = createInterface({\n input: process.stdin,\n terminal: false,\n });\n\n let pending = Promise.resolve();\n await new Promise<void>((resolve) => {\n rl.on('line', (line) => {\n pending = pending.then(() => this.dispatchLine(line));\n });\n\n rl.on('close', () => {\n void pending.then(() => {\n this.client.disconnect();\n resolve();\n });\n });\n });\n }\n\n async handleLineForTest(line: string): Promise<McpResponse | null> {\n return this.processLine(line);\n }\n\n /**\n * Sends a JSON-RPC notification (no `id`, no response\n * expected) to stdout.\n */\n notify(method: string, params?: Record<string, unknown>): void {\n const notification: Record<string, unknown> = {\n jsonrpc: '2.0',\n method,\n };\n if (params !== undefined) {\n notification['params'] = params;\n }\n process.stdout.write(JSON.stringify(notification) + '\\n');\n }\n\n /**\n * Emits a log notification if the message severity meets or\n * exceeds the configured log level threshold.\n */\n log(level: McpLogLevel, message: unknown, logger?: string): void {\n if (this.logLevel === null) return;\n if (!shouldEmitLog(level, this.logLevel)) return;\n this.notify('notifications/message', {\n level,\n logger: logger ?? 'kbdb',\n data: message,\n });\n }\n\n /**\n * Sends a JSON-RPC request to the host (server-to-client)\n * and returns a Promise that resolves with the response\n * result. Times out after 30 seconds.\n */\n sendRequest(\n method: string,\n params: Record<string, unknown>,\n ): Promise<unknown> {\n const id = this.nextRequestId++;\n const request = { jsonrpc: '2.0', id, method, params };\n process.stdout.write(JSON.stringify(request) + '\\n');\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this.pendingRequests.delete(id);\n reject(new Error(`Request ${method} timed out`));\n }, 30000);\n this.pendingRequests.set(id, {\n resolve,\n reject,\n timer,\n });\n });\n }\n\n /**\n * Requests the host to generate text via the sampling\n * capability. Throws if the host did not advertise sampling\n * support during initialization.\n */\n async requestSampling(\n messages: {\n role: string;\n content: { type: string; text: string };\n }[],\n maxTokens: number,\n ): Promise<unknown> {\n if (!this.hostCapabilities?.['sampling']) {\n throw new Error('Host does not support sampling');\n }\n return this.sendRequest('sampling/createMessage', {\n messages,\n maxTokens,\n });\n }\n\n private async dispatchLine(line: string): Promise<void> {\n const response = await this.processLine(line);\n if (response !== null) {\n this.send(response);\n }\n }\n\n private async processLine(\n line: string,\n ): Promise<McpResponse | null> {\n if (!line.trim()) return null;\n\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(line) as Record<string, unknown>;\n } catch {\n return {\n jsonrpc: '2.0',\n id: 0,\n error: {\n code: PARSE_ERROR,\n message: 'Parse error',\n },\n };\n }\n\n // Incoming response to an outgoing request (sampling)\n if (\n parsed['id'] !== undefined &&\n typeof parsed['method'] !== 'string'\n ) {\n const responseId = parsed['id'] as number;\n const pending = this.pendingRequests.get(responseId);\n if (pending) {\n this.pendingRequests.delete(responseId);\n clearTimeout(pending.timer);\n if (parsed['error']) {\n const err = parsed['error'] as {\n message?: string;\n };\n pending.reject(\n new Error(err.message ?? 'Request failed'),\n );\n } else {\n pending.resolve(parsed['result']);\n }\n }\n return null;\n }\n\n const request = parsed as unknown as McpRequest;\n\n if (request.id === undefined) {\n if (\n request.method === 'notifications/initialized' ||\n request.method === 'notifications/cancelled'\n ) {\n if (\n request.method === 'notifications/initialized' &&\n !this.initialized\n ) {\n this.initialized = true;\n void this.runStartupHealthCheck();\n }\n }\n return null;\n }\n\n const id = request.id;\n\n if (\n !this.initialized &&\n request.method !== 'initialize' &&\n request.method !== 'ping'\n ) {\n return {\n jsonrpc: '2.0',\n id,\n error: {\n code: RESOURCE_NOT_FOUND,\n message: 'Server not initialized',\n },\n };\n }\n\n const response = await this.handleRequest(request);\n return response;\n }\n\n private async handleRequest(\n request: McpRequest,\n ): Promise<McpResponse> {\n const id = request.id as number | string;\n\n switch (request.method) {\n case 'initialize': {\n const params = request.params ?? {};\n const caps = params['capabilities'];\n this.hostCapabilities = caps\n ? (caps as Record<string, unknown>)\n : null;\n return {\n jsonrpc: '2.0',\n id,\n result: {\n protocolVersion: '2025-11-25',\n serverInfo: {\n name: 'kbdb',\n version: '0.1.0',\n },\n capabilities: {\n tools: {},\n resources: { subscribe: true },\n prompts: {},\n logging: {},\n completions: {},\n },\n },\n };\n }\n\n case 'ping':\n return { jsonrpc: '2.0', id, result: {} };\n\n case 'tools/list':\n return {\n jsonrpc: '2.0',\n id,\n result: {\n tools: createToolDefinitions(),\n },\n };\n\n case 'resources/list':\n return {\n jsonrpc: '2.0',\n id,\n result: { resources: [] },\n };\n\n case 'resources/templates/list':\n return {\n jsonrpc: '2.0',\n id,\n result: {\n resourceTemplates: createResourceTemplates(),\n },\n };\n\n case 'tools/call': {\n const params = request.params ?? {};\n const rawName = params['name'];\n const name = typeof rawName === 'string' ? rawName : '';\n const args = (params['arguments'] ?? {}) as Record<\n string,\n unknown\n >;\n const result = await handleToolCall(\n this.client,\n name,\n args,\n );\n return { jsonrpc: '2.0', id, result };\n }\n\n case 'resources/read': {\n const params = request.params ?? {};\n const rawUri = params['uri'];\n const uri = typeof rawUri === 'string' ? rawUri : '';\n try {\n const result = await handleResourceRead(\n this.client,\n uri,\n );\n return { jsonrpc: '2.0', id, result };\n } catch (err) {\n return {\n jsonrpc: '2.0',\n id,\n error: {\n code: RESOURCE_NOT_FOUND,\n message:\n err instanceof Error\n ? err.message\n : String(err),\n },\n };\n }\n }\n\n case 'prompts/list': {\n const skills = await this.client.listByType('skill');\n const agents =\n await this.client.listDocumentsByType('agent');\n const prompts = createPromptDefinitions(skills, agents);\n return {\n jsonrpc: '2.0',\n id,\n result: { prompts },\n };\n }\n\n case 'prompts/get': {\n const params = request.params ?? {};\n const name =\n typeof params['name'] === 'string' ? params['name'] : '';\n const promptArgs = (params['arguments'] ?? {}) as Record<\n string,\n string\n >;\n try {\n const messages = await handlePromptGet(\n name,\n promptArgs,\n this.client,\n );\n return {\n jsonrpc: '2.0',\n id,\n result: { messages },\n };\n } catch (err) {\n return {\n jsonrpc: '2.0',\n id,\n error: {\n code: RESOURCE_NOT_FOUND,\n message:\n err instanceof Error\n ? err.message\n : String(err),\n },\n };\n }\n }\n\n case 'completion/complete': {\n const params = request.params ?? {};\n const ref = params['ref'] as McpCompletionRef;\n const argument = (params['argument'] ?? {\n name: '',\n value: '',\n }) as McpCompletionArgument;\n const result = await handleCompletion(\n ref,\n argument,\n this.client,\n );\n return { jsonrpc: '2.0', id, result };\n }\n\n case 'roots/list': {\n const roots = handleRootsList(this.contextPath);\n return {\n jsonrpc: '2.0',\n id,\n result: { roots },\n };\n }\n\n case 'logging/setLevel': {\n const params = request.params ?? {};\n const level = params['level'] as McpLogLevel | undefined;\n this.logLevel = level ?? null;\n return { jsonrpc: '2.0', id, result: {} };\n }\n\n case 'resources/subscribe': {\n const params = request.params ?? {};\n const uri =\n typeof params['uri'] === 'string' ? params['uri'] : '';\n this.subscriptions.add(uri);\n return { jsonrpc: '2.0', id, result: {} };\n }\n\n case 'resources/unsubscribe': {\n const params = request.params ?? {};\n const uri =\n typeof params['uri'] === 'string' ? params['uri'] : '';\n this.subscriptions.delete(uri);\n return { jsonrpc: '2.0', id, result: {} };\n }\n\n default:\n return {\n jsonrpc: '2.0',\n id,\n error: {\n code: METHOD_NOT_FOUND,\n message: `Method not found: ` + request.method,\n },\n };\n }\n }\n\n private send(response: McpResponse): void {\n const json = JSON.stringify(response);\n process.stdout.write(json + '\\n');\n }\n\n /**\n * Runs an integrity check immediately after the MCP handshake\n * completes. Emits a `notifications/message` warning when the\n * check detects issues so the connected agent is aware before\n * making requests. The server continues operating regardless of\n * the result.\n */\n private async runStartupHealthCheck(): Promise<void> {\n try {\n const report = await this.client.integrityCheck();\n if (!report.ok) {\n const summary = report.errors\n .map((e) => `${e.type}: ${e.entity} -- ${e.detail}`)\n .join('; ');\n this.notify('notifications/message', {\n level: 'warning',\n logger: 'kbdb',\n data: `Database integrity issues detected: ${summary}`,\n });\n }\n } catch {\n // Health check failure is non-fatal -- server continues\n }\n }\n}\n", "import type { McpToolDefinition } from '../typings/mcp-types.interface.ts';\n\n/**\n * Returns the full list of MCP tool definitions exposed by the\n * knowledge-base server. Each definition includes the tool name,\n * a human-readable description, and a JSON Schema for its inputs.\n */\nexport function createToolDefinitions(): McpToolDefinition[] {\n return [\n {\n name: 'search',\n description:\n 'Query the knowledge base by keywords.' +\n ' Returns ranked results with heading,' +\n ' snippet, and matched terms. Use multiple' +\n ' short keyword queries for best coverage.' +\n ' Use recall to get full content.',\n inputSchema: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'Search query text',\n },\n mode: {\n type: 'string',\n enum: ['sections', 'documents', 'stats'],\n description: 'Search mode (default: sections)',\n },\n limit: {\n type: 'number',\n description: 'Maximum results (default: 20)',\n },\n offset: {\n type: 'number',\n description:\n 'Number of results to skip for' +\n ' pagination (default: 0)',\n },\n algo: {\n type: 'string',\n enum: ['lexical', 'vector', 'hybrid'],\n description: 'Search algorithm (default: lexical)',\n },\n },\n required: ['query'],\n },\n annotations: {\n title: 'Search KB',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'learn',\n description:\n 'Import content into the knowledge base.' +\n ' Use for durable facts, decisions, and' +\n ' corrections. Use replace when updating' +\n ' existing knowledge. Attach tags for scoping.',\n inputSchema: {\n type: 'object',\n properties: {\n content: {\n type: 'string',\n description: 'Text content to add',\n },\n type: {\n type: 'string',\n description:\n 'MIME type (default: text/markdown).' +\n ' Use image/* for images.',\n },\n title: {\n type: 'string',\n description:\n 'Section title.' + ' Required for image/* types.',\n },\n description: {\n type: 'string',\n description: 'Optional section description',\n },\n docid: {\n type: 'string',\n description: 'Document ID to group under',\n },\n tags: {\n type: 'array',\n items: { type: 'string' },\n description: 'Tags for scoping and filtering',\n },\n replace: {\n type: 'boolean',\n description:\n 'Replace existing section with same' +\n ' source key (supersession)',\n },\n },\n required: ['content'],\n },\n annotations: {\n title: 'Import Content',\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'unlearn',\n description:\n 'Remove a section from the knowledge base' +\n ' by its kb-id.',\n inputSchema: {\n type: 'object',\n properties: {\n kbid: {\n type: 'string',\n description: 'Knowledge base ID of the section',\n },\n },\n required: ['kbid'],\n },\n annotations: {\n title: 'Remove Section',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'retrieve',\n description:\n 'Low-level fetch of a section or document' +\n ' by identifier. For AI agent workflows,' +\n ' prefer `recall` which includes metadata,' +\n ' context, and back-references.',\n inputSchema: {\n type: 'object',\n properties: {\n kbid: {\n type: 'string',\n description: 'Section kb-id',\n },\n docid: {\n type: 'string',\n description: 'Document ID',\n },\n },\n },\n annotations: {\n title: 'Fetch Content',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'recall',\n description:\n 'Retrieve full content and context for sections' +\n ' by identifier. Use after search to read relevant' +\n ' results. Returns section text, metadata,' +\n ' references, and back-references.',\n inputSchema: {\n type: 'object',\n properties: {\n kbid: {\n type: 'string',\n description: 'Single section identifier',\n },\n kbids: {\n type: 'array',\n items: { type: 'string' },\n description: 'Batch section identifiers',\n },\n depth: {\n type: 'number',\n description: 'Expansion depth (0-3, default: 0)',\n },\n },\n },\n annotations: {\n title: 'Recall Context',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'status',\n description:\n 'Get database metadata including document count,' +\n ' section count, index size, and cache statistics.',\n inputSchema: {\n type: 'object',\n properties: {},\n },\n annotations: {\n title: 'DB Status',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'content',\n description:\n 'Compose a rendered Markdown document from one or' +\n ' more kbid or docid identifiers.',\n inputSchema: {\n type: 'object',\n properties: {\n ids: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'One or more kbid or docid identifiers' +\n ' (may be mixed)',\n },\n },\n required: ['ids'],\n },\n annotations: {\n title: 'Compose Content',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'check',\n description:\n 'Verify the integrity of the knowledge base.' +\n ' Reports checksum mismatches, orphan sections,' +\n ' broken references, and circular reference chains.',\n inputSchema: {\n type: 'object',\n properties: {},\n },\n annotations: {\n title: 'Integrity Check',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'gc',\n description:\n 'Remove unreferenced sections from the knowledge' +\n ' base. A section is eligible when no document' +\n ' manifest references it.',\n inputSchema: {\n type: 'object',\n properties: {},\n },\n annotations: {\n title: 'Garbage Collect',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n },\n },\n {\n name: 'rebuild',\n description:\n 'Reconstruct all index files from section files' +\n ' and document manifests on disk. Use this to' +\n ' recover from index corruption.',\n inputSchema: {\n type: 'object',\n properties: {},\n },\n annotations: {\n title: 'Rebuild Indexes',\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n },\n {\n name: 'export',\n description:\n 'Export the database as a self-contained' +\n ' directory snapshot (sections, documents,' +\n ' catalog -- no indexes).',\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description:\n 'Export destination path' +\n ' (default: ./kbdb-export/)',\n },\n },\n },\n annotations: {\n title: 'Export Snapshot',\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'skill-learn',\n description:\n 'Create or update a skill definition.' +\n ' Skills are reusable AI agent capabilities' +\n ' with template placeholders.',\n inputSchema: {\n type: 'object',\n properties: {\n name: {\n type: 'string',\n description: 'Skill name',\n },\n description: {\n type: 'string',\n description: 'Skill description',\n },\n body: {\n type: 'string',\n description:\n 'Skill body template.' +\n ' Use {{argName}} for placeholders.',\n },\n },\n required: ['name', 'body'],\n },\n annotations: {\n title: 'Create Skill',\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'skill-list',\n description: 'List all skills in the knowledge base.',\n inputSchema: {\n type: 'object',\n properties: {},\n },\n annotations: {\n title: 'List Skills',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'skill-get',\n description: 'Get a skill definition by name or kbid.',\n inputSchema: {\n type: 'object',\n properties: {\n name: {\n type: 'string',\n description: 'Skill name',\n },\n kbid: {\n type: 'string',\n description: 'Knowledge base ID',\n },\n },\n },\n annotations: {\n title: 'Get Skill',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'skill-delete',\n description: 'Delete a skill by its kbid.',\n inputSchema: {\n type: 'object',\n properties: {\n kbid: {\n type: 'string',\n description: 'Knowledge base ID',\n },\n },\n required: ['kbid'],\n },\n annotations: {\n title: 'Delete Skill',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'agent-create',\n description:\n 'Create an AI agent with a persona and' +\n ' optional skill references.',\n inputSchema: {\n type: 'object',\n properties: {\n name: {\n type: 'string',\n description: 'Agent name',\n },\n description: {\n type: 'string',\n description: 'Agent description',\n },\n persona: {\n type: 'string',\n description: 'Agent persona prompt',\n },\n skills: {\n type: 'array',\n items: { type: 'string' },\n description: 'Skill kbid references to attach',\n },\n },\n required: ['name', 'persona'],\n },\n annotations: {\n title: 'Create Agent',\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'agent-list',\n description: 'List all agents in the knowledge base.',\n inputSchema: {\n type: 'object',\n properties: {},\n },\n annotations: {\n title: 'List Agents',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'agent-get',\n description: 'Get an agent definition by document ID.',\n inputSchema: {\n type: 'object',\n properties: {\n docid: {\n type: 'string',\n description: 'Document ID of the agent',\n },\n },\n required: ['docid'],\n },\n annotations: {\n title: 'Get Agent',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'agent-delete',\n description:\n 'Delete an agent by its document ID.' +\n ' Skill sections are not removed.',\n inputSchema: {\n type: 'object',\n properties: {\n docid: {\n type: 'string',\n description: 'Document ID of the agent',\n },\n },\n required: ['docid'],\n },\n annotations: {\n title: 'Delete Agent',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'auto-capture-review',\n description:\n 'Review and approve pending auto-captured' +\n ' knowledge before storage.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['list', 'approve', 'reject'],\n description: 'Action to perform on pending captures',\n },\n },\n },\n annotations: {\n title: 'Auto-Capture Review',\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n ];\n}\n", "import type { McpResourceTemplate } from '../typings/mcp-types.interface.ts';\n\n/**\n * Returns the list of MCP resource URI templates served by the\n * knowledge-base server. Each template describes the URI pattern,\n * human-readable metadata, and the MIME type of the resource body.\n */\nexport function createResourceTemplates(): McpResourceTemplate[] {\n return [\n {\n uriTemplate: 'kbdb://section/{kb_id}',\n name: 'Section',\n description: 'A knowledge base section by its kb-id.',\n mimeType: 'text/plain',\n },\n {\n uriTemplate: 'kbdb://document/{doc_id}',\n name: 'Document',\n description: 'A document with its ordered sections.',\n mimeType: 'application/json',\n },\n ];\n}\n", "import type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\n\n/** Shape of a content item in an MCP tool call response. */\ninterface ToolContent {\n /** Content type identifier, typically `'text'`. */\n readonly type: string;\n /** The text payload. */\n readonly text: string;\n}\n\n/** Result returned by the agent-create tool handler. */\ninterface ToolCallResult {\n /** One or more content items describing the result. */\n readonly content: ToolContent[];\n /** Set to `true` when the tool encountered an error. */\n readonly isError?: boolean;\n}\n\n/**\n * Narrows an `unknown` value to a string, returning the fallback\n * when the value is not already a string.\n */\nfunction asString(value: unknown, fallback: string): string {\n return typeof value === 'string' ? value : fallback;\n}\n\n/**\n * Narrows an `unknown` value to a `string[]`, returning an empty\n * array when the value is not an array of strings.\n */\nfunction asStringArray(value: unknown): string[] {\n if (\n Array.isArray(value) &&\n value.every((item) => typeof item === 'string')\n ) {\n return value;\n }\n return [];\n}\n\n/**\n * Handles the `agent:create` MCP tool call.\n *\n * Validates required arguments, verifies that referenced skill kbids\n * exist, stores agent metadata as a JSON section, groups all sections\n * into a single document, and returns the resulting document\n * identifier.\n *\n * @param client - the worker client used to execute operations\n * @param args - tool arguments from the MCP request\n * @returns content items with optional `isError` flag\n */\nexport async function handleAgentCreate(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const name = asString(args['name'], '');\n const description = asString(args['description'], '');\n const persona = asString(args['persona'], '');\n const skills = asStringArray(args['skills']);\n\n if (!name) {\n return {\n content: [{ type: 'text', text: 'name is required' }],\n isError: true,\n };\n }\n if (!persona) {\n return {\n content: [{ type: 'text', text: 'persona is required' }],\n isError: true,\n };\n }\n\n if (skills.length > 0) {\n const sections = await client.readSections(skills);\n const found = new Set(sections.map((s) => s.kbid));\n const missing = skills.filter((k) => !found.has(k));\n if (missing.length > 0) {\n return {\n content: [\n {\n type: 'text',\n text: `skill not found: ${missing.join(', ')}`,\n },\n ],\n isError: true,\n };\n }\n }\n\n const metadata = JSON.stringify({ name, description, persona });\n\n const metaResult = await client.addSection({\n sectionType: 'text',\n content: metadata,\n title: name,\n description,\n });\n\n const allKbids = [metaResult.kbid, ...skills];\n const docid = await client.groupSections(name, allKbids, 'agent');\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n docid,\n name,\n skillCount: skills.length,\n }),\n },\n ],\n };\n}\n", "import type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\n\n/** Shape of a content item in an MCP tool call response. */\ninterface ToolContent {\n /** Content type identifier, typically `'text'`. */\n readonly type: string;\n /** The text payload. */\n readonly text: string;\n}\n\n/** Result returned by the agent-list tool handler. */\ninterface ToolCallResult {\n /** One or more content items describing the result. */\n readonly content: ToolContent[];\n /** Set to `true` when the tool encountered an error. */\n readonly isError?: boolean;\n}\n\n/**\n * Handles the `agent:list` MCP tool call.\n *\n * Retrieves all documents with `doc_type: 'agent'` and returns a\n * summary list containing each agent's document identifier, name,\n * and skill count.\n *\n * The `skillCount` is `Math.max(0, sections.length - 1)` because\n * the first section of an agent document always holds the metadata\n * JSON and does not count as a skill reference.\n *\n * @param client - the worker client used to execute operations\n * @returns content items with the serialised agent list\n */\nexport async function handleAgentList(\n client: McpWorkerClient,\n): Promise<ToolCallResult> {\n const docs = await client.listDocumentsByType('agent');\n const items = docs.map((d) => ({\n docid: d.docid,\n name: d.title,\n skillCount: Math.max(0, d.sections.length - 1),\n }));\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(items, null, 2),\n },\n ],\n };\n}\n", "import type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\nimport type { AgentDefinition } from '../typings/agent-types.interface.ts';\n\n/** Shape of a content item in an MCP tool call response. */\ninterface ToolContent {\n /** Content type identifier, typically `'text'`. */\n readonly type: string;\n /** The text payload. */\n readonly text: string;\n}\n\n/** Result returned by the agent-get tool handler. */\ninterface ToolCallResult {\n /** One or more content items describing the result. */\n readonly content: ToolContent[];\n /** Set to `true` when the tool encountered an error. */\n readonly isError?: boolean;\n}\n\n/** Parsed shape of an agent document section list entry. */\ninterface DocumentSection {\n /** Knowledge-base identifier of the section. */\n readonly kbid: string;\n /** Zero-based position of the section within the document. */\n readonly position: number;\n}\n\n/** Parsed shape of a retrieved agent document. */\ninterface AgentDocument {\n /** Document identifier. */\n readonly docid: string;\n /** Document title used as agent name fallback. */\n readonly title: string;\n /** Ordered list of sections in the document. */\n readonly sections: DocumentSection[];\n}\n\n/**\n * Reads the metadata JSON stored in the first section of an agent\n * document and extracts `name`, `description`, and `persona`.\n */\nasync function readAgentMeta(\n client: McpWorkerClient,\n metaKbid: string,\n fallbackName: string,\n): Promise<{ name: string; description: string; persona: string }> {\n const metaSections = await client.readSections([metaKbid]);\n const first = metaSections.at(0);\n if (!first) {\n return { name: fallbackName, description: '', persona: '' };\n }\n try {\n const meta = JSON.parse(first.content) as Record<string, unknown>;\n return {\n name:\n typeof meta['name'] === 'string'\n ? meta['name']\n : fallbackName,\n description:\n typeof meta['description'] === 'string'\n ? meta['description']\n : '',\n persona:\n typeof meta['persona'] === 'string' ? meta['persona'] : '',\n };\n } catch {\n return { name: fallbackName, description: '', persona: '' };\n }\n}\n\n/**\n * Resolves skill names for a list of section references by reading\n * each section's JSON content and extracting the `name` field.\n * Returns `null` for skill references where the section no longer\n * exists (dangling references).\n */\nasync function resolveSkillRefs(\n client: McpWorkerClient,\n skillRefs: DocumentSection[],\n): Promise<{ kbid: string; name: string | null; position: number }[]> {\n if (skillRefs.length === 0) {\n return [];\n }\n const skillKbids = skillRefs.map((s) => s.kbid);\n const skillSections = await client.readSections(skillKbids);\n const sectionMap = new Map(skillSections.map((s) => [s.kbid, s]));\n return skillRefs.map((ref) => {\n const sec = sectionMap.get(ref.kbid);\n if (!sec) {\n return { kbid: ref.kbid, name: null, position: ref.position };\n }\n try {\n const parsed = JSON.parse(sec.content) as Record<\n string,\n unknown\n >;\n const skillName =\n typeof parsed['name'] === 'string' ? parsed['name'] : null;\n return {\n kbid: ref.kbid,\n name: skillName,\n position: ref.position,\n };\n } catch {\n return { kbid: ref.kbid, name: null, position: ref.position };\n }\n });\n}\n\n/**\n * Handles the `agent:get` MCP tool call.\n *\n * Retrieves an agent document by its `docid`, reads the metadata\n * section and skill references, and returns a full `AgentDefinition`.\n * Dangling skill references (sections that no longer exist) appear\n * with `name: null` in the skills list.\n *\n * @param client - the worker client used to execute operations\n * @param args - tool arguments; must include a `docid` string\n * @returns content items containing the serialised `AgentDefinition`\n */\nexport async function handleAgentGet(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const docid = typeof args['docid'] === 'string' ? args['docid'] : '';\n if (!docid) {\n return {\n content: [{ type: 'text', text: 'docid is required' }],\n isError: true,\n };\n }\n\n const doc = (await client.retrieveDocument(docid)) as AgentDocument;\n const metaKbid = doc.sections[0]?.kbid;\n const skillRefs = doc.sections.slice(1);\n\n const { name, description, persona } = metaKbid\n ? await readAgentMeta(client, metaKbid, doc.title)\n : { name: doc.title, description: '', persona: '' };\n\n const skills = await resolveSkillRefs(client, skillRefs);\n\n const agent: AgentDefinition = {\n docid,\n name,\n description,\n persona,\n skills,\n };\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(agent, null, 2),\n },\n ],\n };\n}\n", "import type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\n\n/** Shape of a content item in an MCP tool call response. */\ninterface ToolContent {\n /** Content type identifier, typically `'text'`. */\n readonly type: string;\n /** The text payload. */\n readonly text: string;\n}\n\n/** Result returned by the agent-delete tool handler. */\ninterface ToolCallResult {\n /** One or more content items describing the result. */\n readonly content: ToolContent[];\n /** Set to `true` when the tool encountered an error. */\n readonly isError?: boolean;\n}\n\n/**\n * Handles the `agent:delete` MCP tool call.\n *\n * Removes the document grouping identified by `docid`. The skill\n * sections referenced by the agent are not deleted; only the grouping\n * record is removed.\n *\n * @param client - the worker client used to execute operations\n * @param args - tool arguments; must include a `docid` string\n * @returns content items confirming removal, or an error item\n */\nexport async function handleAgentDelete(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const docid = typeof args['docid'] === 'string' ? args['docid'] : '';\n if (!docid) {\n return {\n content: [{ type: 'text', text: 'docid is required' }],\n isError: true,\n };\n }\n await client.removeGrouping(docid);\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({ docid, removed: true }),\n },\n ],\n };\n}\n", "import type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\n\n/** Shape of a content item in an MCP tool call response. */\ninterface ToolContent {\n /** Content type identifier, typically `'text'`. */\n readonly type: string;\n /** The text payload. */\n readonly text: string;\n}\n\n/** Result returned by a tool call handler. */\ninterface ToolCallResult {\n /** One or more content items describing the result. */\n readonly content: ToolContent[];\n /** Set to `true` when the tool encountered an error. */\n readonly isError?: boolean;\n}\n\n/**\n * Handles the MCP `recall` tool call.\n *\n * Retrieves full content and context for one or more knowledge-base\n * sections by identifier. At least one of `kbid` or `kbids` must be\n * present in `args`; omitting both returns an error result.\n *\n * @param client - the worker client used to execute the operation\n * @param args - tool arguments from the MCP request\n * @returns content with JSON-stringified recall result, or an error\n * content item when required arguments are missing\n */\nexport async function handleRecall(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const kbid =\n typeof args['kbid'] === 'string' ? args['kbid'] : undefined;\n const kbids =\n Array.isArray(args['kbids']) &&\n args['kbids'].every((item: unknown) => typeof item === 'string')\n ? args['kbids']\n : undefined;\n\n if (!kbid && !kbids) {\n return {\n content: [\n {\n type: 'text',\n text: 'Provide kbid or kbids',\n },\n ],\n isError: true,\n };\n }\n\n const depth = typeof args['depth'] === 'number' ? args['depth'] : 0;\n\n const result = await client.recall({ kbid, kbids, depth });\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n}\n", "import type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\nimport { extractSkillArguments } from './extract-skill-arguments.function.ts';\nimport { parseSkillContent } from './parse-skill-content.function.ts';\nimport { serializeSkillContent } from './serialize-skill-content.function.ts';\nimport { handleAgentCreate } from './handle-agent-create.function.ts';\nimport { handleAgentList } from './handle-agent-list.function.ts';\nimport { handleAgentGet } from './handle-agent-get.function.ts';\nimport { handleAgentDelete } from './handle-agent-delete.function.ts';\nimport { handleRecall } from './handle-recall.function.ts';\n\n/** Shape of a content item in an MCP tool call response. */\ninterface ToolContent {\n /** Content type identifier, typically 'text'. */\n readonly type: string;\n /** The text payload. */\n readonly text: string;\n}\n\n/** Result returned by a tool call handler. */\ninterface ToolCallResult {\n /** One or more content items describing the result. */\n readonly content: ToolContent[];\n /** Set to `true` when the tool encountered an error. */\n readonly isError?: boolean;\n}\n\n/**\n * Narrows an `unknown` value to a string, returning the fallback\n * when the value is not already a string.\n */\nfunction asString(value: unknown, fallback: string): string {\n return typeof value === 'string' ? value : fallback;\n}\n\n/**\n * Narrows an `unknown` value to a boolean, returning `undefined`\n * when the value is not a boolean.\n */\nfunction asBooleanOrUndefined(value: unknown): boolean | undefined {\n return typeof value === 'boolean' ? value : undefined;\n}\n\n/**\n * Narrows an `unknown` value to a `string[]`, returning `undefined`\n * when the value is not an array of strings.\n */\nfunction asStringArrayOrUndefined(\n value: unknown,\n): string[] | undefined {\n if (\n Array.isArray(value) &&\n value.every((item) => typeof item === 'string')\n ) {\n return value;\n }\n return undefined;\n}\n\n/**\n * Narrows an `unknown` value to a `string[]`, returning an empty\n * array when the value is not an array of strings.\n */\nfunction asStringArray(value: unknown): string[] {\n if (\n Array.isArray(value) &&\n value.every((item) => typeof item === 'string')\n ) {\n return value;\n }\n return [];\n}\n\n/**\n * Dispatches an MCP tool call to the appropriate knowledge-base\n * operation and returns the result formatted as MCP content.\n *\n * @param client - the worker client used to execute operations\n * @param name - the tool name to invoke\n * @param args - tool arguments from the MCP request\n * @returns content items with optional isError flag\n */\nexport async function handleToolCall(\n client: McpWorkerClient,\n name: string,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n try {\n switch (name) {\n case 'search':\n return await handleSearch(client, args);\n case 'learn':\n return await handleLearn(client, args);\n case 'unlearn':\n return await handleUnlearn(client, args);\n case 'retrieve':\n return await handleRetrieve(client, args);\n case 'recall':\n return await handleRecall(client, args);\n case 'status':\n return await handleStatus(client);\n case 'content':\n return await handleContent(client, args);\n case 'check':\n return await handleCheck(client);\n case 'gc':\n return await handleGc(client);\n case 'rebuild':\n return await handleRebuild(client);\n case 'export':\n return await handleExport(client, args);\n case 'skill-learn':\n return await handleSkillLearn(client, args);\n case 'skill-list':\n return await handleSkillList(client);\n case 'skill-get':\n return await handleSkillGet(client, args);\n case 'skill-delete':\n return await handleSkillDelete(client, args);\n case 'agent-create':\n return await handleAgentCreate(client, args);\n case 'agent-list':\n return await handleAgentList(client);\n case 'agent-get':\n return await handleAgentGet(client, args);\n case 'agent-delete':\n return await handleAgentDelete(client, args);\n case 'auto-capture-review':\n return handleAutoCaptureReview();\n default:\n return {\n content: [\n {\n type: 'text',\n text: `Unknown tool: ${name}`,\n },\n ],\n isError: true,\n };\n }\n } catch (err) {\n return {\n content: [\n {\n type: 'text',\n text: err instanceof Error ? err.message : String(err),\n },\n ],\n isError: true,\n };\n }\n}\n\nasync function handleSearch(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const results = await client.search({\n query: asString(args['query'], ''),\n mode: args['mode'] as string | undefined,\n limit: args['limit'] as number | undefined,\n offset: args['offset'] as number | undefined,\n algo: args['algo'] as string | undefined,\n });\n\n const stripped = {\n ...results,\n items: results.items.map(\n ({\n score: _score,\n confidence: _confidence,\n ...rest\n }: (typeof results.items)[number] & {\n confidence?: number;\n }) => rest,\n ),\n };\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(stripped, null, 2),\n },\n ],\n };\n}\n\nasync function handleLearn(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const sectionType = asString(args['type'], 'text/markdown');\n const title =\n typeof args['title'] === 'string' ? args['title'] : undefined;\n const description =\n typeof args['description'] === 'string'\n ? args['description']\n : undefined;\n const docid =\n typeof args['docid'] === 'string' ? args['docid'] : undefined;\n const tags = asStringArrayOrUndefined(args['tags']);\n const replace = asBooleanOrUndefined(args['replace']);\n if (sectionType.startsWith('image/') && !title) {\n return {\n content: [\n {\n type: 'text',\n text: 'title is required for image/* types',\n },\n ],\n isError: true,\n };\n }\n const result = await client.addSection({\n sectionType,\n content: asString(args['content'], ''),\n title,\n description,\n docid,\n tags,\n replace,\n });\n const normalized = {\n kbid: result.kbid,\n indexed_terms_count: result.indexed_terms_count ?? 0,\n elapsed_ms: result.elapsed_ms ?? 0,\n superseded: result.superseded ?? null,\n warnings: result.warnings ?? [],\n near_duplicates: (result.near_duplicates ?? []).map((d) => ({\n kbid: d.kbid,\n similarity: d.similarity,\n ...(d.method !== undefined ? { method: d.method } : {}),\n })),\n };\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(normalized),\n },\n ],\n };\n}\n\nasync function handleUnlearn(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const result = await client.removeSection(\n asString(args['kbid'], ''),\n );\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(result),\n },\n ],\n };\n}\n\nasync function handleRetrieve(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n if (typeof args['kbid'] === 'string') {\n const sections = await client.readSections([args['kbid']]);\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(sections, null, 2),\n },\n ],\n };\n }\n if (typeof args['docid'] === 'string') {\n const doc = await client.retrieveDocument(args['docid']);\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(doc, null, 2),\n },\n ],\n };\n }\n return {\n content: [\n {\n type: 'text',\n text: 'Provide kbid or docid',\n },\n ],\n isError: true,\n };\n}\n\nasync function handleStatus(\n client: McpWorkerClient,\n): Promise<ToolCallResult> {\n const status = await client.dbStatus();\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(status, null, 2),\n },\n ],\n };\n}\n\nasync function handleContent(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const ids = asStringArray(args['ids']);\n const result = await client.content(ids);\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(result),\n },\n ],\n };\n}\n\nasync function handleCheck(\n client: McpWorkerClient,\n): Promise<ToolCallResult> {\n const report = await client.integrityCheck();\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(report, null, 2),\n },\n ],\n };\n}\n\nasync function handleGc(\n client: McpWorkerClient,\n): Promise<ToolCallResult> {\n const report = await client.gc();\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(report, null, 2),\n },\n ],\n };\n}\n\nasync function handleRebuild(\n client: McpWorkerClient,\n): Promise<ToolCallResult> {\n const report = await client.rebuildIndexes();\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(report, null, 2),\n },\n ],\n };\n}\n\nasync function handleSkillLearn(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const name = asString(args['name'], '');\n if (!name) {\n return {\n content: [{ type: 'text', text: 'name is required' }],\n isError: true,\n };\n }\n const body = asString(args['body'], '');\n if (!body) {\n return {\n content: [{ type: 'text', text: 'body is required' }],\n isError: true,\n };\n }\n const description =\n typeof args['description'] === 'string'\n ? args['description']\n : undefined;\n const skillArgs = extractSkillArguments(body);\n const skill = {\n name,\n description,\n arguments: skillArgs.length > 0 ? skillArgs : undefined,\n body,\n };\n const json = serializeSkillContent(skill);\n const result = await client.addSection({\n sectionType: 'skill',\n content: json,\n title: name,\n description,\n });\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({ kbid: result.kbid, name }),\n },\n ],\n };\n}\n\nasync function handleSkillList(\n client: McpWorkerClient,\n): Promise<ToolCallResult> {\n const records = await client.listByType('skill');\n const items = records.map((r) => {\n let argumentCount = 0;\n try {\n const parsed = JSON.parse(r.content) as Record<\n string,\n unknown\n >;\n if (Array.isArray(parsed['arguments'])) {\n argumentCount = parsed['arguments'].length;\n }\n } catch {\n // ignore parse errors\n }\n return {\n kbid: r.kbid,\n name: r.title,\n description: r.description,\n argumentCount,\n };\n });\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(items, null, 2),\n },\n ],\n };\n}\n\nasync function handleSkillGet(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const kbid =\n typeof args['kbid'] === 'string' ? args['kbid'] : undefined;\n const name =\n typeof args['name'] === 'string' ? args['name'] : undefined;\n if (!kbid && !name) {\n return {\n content: [\n {\n type: 'text',\n text: 'name or kbid is required',\n },\n ],\n isError: true,\n };\n }\n let content: string | undefined;\n if (kbid) {\n const sections = await client.readSections([kbid]);\n if (sections.length > 0) {\n content = sections[0]?.content;\n }\n }\n if (content === undefined && name) {\n const records = await client.listByType('skill');\n const match = records.filter((r) => r.title === name).pop();\n if (match) {\n content = match.content;\n }\n }\n if (content === undefined) {\n const identifier = kbid ?? name ?? '';\n return {\n content: [\n {\n type: 'text',\n text: `skill not found: ${identifier}`,\n },\n ],\n isError: true,\n };\n }\n const skill = parseSkillContent(content);\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(skill, null, 2),\n },\n ],\n };\n}\n\nasync function handleSkillDelete(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const kbid = asString(args['kbid'], '');\n if (!kbid) {\n return {\n content: [{ type: 'text', text: 'kbid is required' }],\n isError: true,\n };\n }\n const result = await client.removeSection(kbid);\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({ kbid, removed: result.removed }),\n },\n ],\n };\n}\n\nfunction handleAutoCaptureReview(): ToolCallResult {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n pending: [],\n message: 'No pending auto-captured knowledge entries.',\n }),\n },\n ],\n };\n}\n\nasync function handleExport(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const path =\n typeof args['path'] === 'string' ? args['path'] : undefined;\n const result = await client.export(\n path !== undefined ? { path } : {},\n );\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(result),\n },\n ],\n };\n}\n", "import type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\n\n/** A single content item in an MCP resource read response. */\ninterface ResourceContent {\n /** The resource URI that was read. */\n readonly uri: string;\n /** MIME type of the content body. */\n readonly mimeType: string;\n /** Text body of the resource. */\n readonly text: string;\n}\n\n/** Result returned by a resource read operation. */\ninterface ResourceReadResult {\n /** One or more content items for the requested URI. */\n readonly contents: ResourceContent[];\n}\n\n/**\n * Handles an MCP `resources/read` request by dispatching to the\n * appropriate knowledge-base operation based on the resource URI.\n *\n * @param client - the worker client used to fetch the resource\n * @param uri - the resource URI from the MCP request\n * @returns contents array for the MCP response\n * @throws {Error} when the URI does not match any known pattern\n */\nexport async function handleResourceRead(\n client: McpWorkerClient,\n uri: string,\n): Promise<ResourceReadResult> {\n const sectionMatch = uri.match(/^kbdb:\\/\\/section\\/(.+)$/);\n if (sectionMatch) {\n const sections = await client.readSections([sectionMatch[1]]);\n const text = sections.length > 0 ? sections[0].content : '';\n return {\n contents: [{ uri, mimeType: 'text/plain', text }],\n };\n }\n\n const docMatch = uri.match(/^kbdb:\\/\\/document\\/(.+)$/);\n if (docMatch) {\n const doc = await client.retrieveDocument(docMatch[1]);\n return {\n contents: [\n {\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(doc, null, 2),\n },\n ],\n };\n }\n\n throw new Error(`Unknown resource URI: ${uri}`);\n}\n", "import type { McpPrompt } from '../typings/prompt-types.interface.ts';\nimport type { McpPromptArgument } from '../typings/prompt-types.interface.ts';\n\n/** Minimal skill section record shape required by this function. */\ninterface SkillSectionRecord {\n /** Knowledge-base identifier of the section. */\n readonly kbid: string;\n /** Human-readable section title used as the prompt name. */\n readonly title: string | null;\n /** JSON-encoded skill definition content. */\n readonly content: string;\n /** Optional human-readable section description. */\n readonly description?: string | null;\n}\n\n/** Minimal document manifest shape required by this function. */\ninterface AgentDocumentRecord {\n /** Unique document identifier. */\n readonly docid: string;\n /** Human-readable document title used in the prompt name. */\n readonly title: string;\n /** Ordered section references belonging to the document. */\n readonly sections: readonly {\n readonly kbid: string;\n readonly position: number;\n }[];\n}\n\n/**\n * Parses the `arguments` field from a skill's JSON content string.\n *\n * Returns the array of prompt argument definitions when the content\n * is valid JSON with an `arguments` array, or `undefined` when JSON\n * parsing fails or the field is absent.\n */\nfunction parseSkillArguments(\n content: string,\n): readonly McpPromptArgument[] | undefined {\n try {\n const parsed = JSON.parse(content) as Record<string, unknown>;\n if (!Array.isArray(parsed['arguments'])) {\n return undefined;\n }\n return (parsed['arguments'] as Record<string, unknown>[]).map(\n (arg) => ({\n name: typeof arg['name'] === 'string' ? arg['name'] : '',\n description:\n typeof arg['description'] === 'string'\n ? arg['description']\n : undefined,\n required:\n typeof arg['required'] === 'boolean'\n ? arg['required']\n : undefined,\n }),\n );\n } catch {\n return undefined;\n }\n}\n\n/**\n * Builds the list of MCP prompt definitions from skill sections and\n * agent document manifests stored in the knowledge base.\n *\n * Skills are mapped first (in input order), followed by agents.\n * Each skill becomes a prompt whose name is the section title and\n * whose arguments are extracted from the JSON content. Each agent\n * becomes a prompt prefixed with `\"agent:\"` and carries an empty\n * arguments array.\n *\n * @param skills - skill section records from `listByType('skill')`\n * @param agents - agent document manifests from\n * `listDocumentsByType('agent')`\n * @returns ordered list of MCP prompt definitions\n */\nexport function createPromptDefinitions(\n skills: readonly SkillSectionRecord[],\n agents: readonly AgentDocumentRecord[],\n): McpPrompt[] {\n const skillPrompts: McpPrompt[] = skills\n .filter(\n (r): r is SkillSectionRecord & { title: string } =>\n r.title !== null,\n )\n .map((record) => {\n const args = parseSkillArguments(record.content);\n const prompt: McpPrompt = {\n name: record.title,\n description: record.description ?? undefined,\n arguments: args,\n };\n return prompt;\n });\n\n const agentPrompts: McpPrompt[] = agents.map((doc) => ({\n name: `agent:${doc.title}`,\n arguments: [],\n }));\n\n return [...skillPrompts, ...agentPrompts];\n}\n", "import type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\nimport type { McpPromptMessage } from '../typings/prompt-types.interface.ts';\n\n/** Parsed shape of an agent metadata section. */\ninterface AgentMeta {\n /** Agent persona text. */\n readonly persona: string;\n}\n\n/** Minimal section shape returned by readSections. */\ninterface ReadSection {\n /** Knowledge-base identifier. */\n readonly kbid: string;\n /** Raw text content. */\n readonly content: string;\n}\n\n/** Minimal agent document shape from listDocumentsByType. */\ninterface AgentDocument {\n /** Document title. */\n readonly title: string;\n /** Ordered section references. */\n readonly sections: readonly {\n readonly kbid: string;\n readonly position: number;\n }[];\n}\n\n/**\n * Parses agent metadata from a raw JSON content string.\n *\n * Returns default values when parsing fails or required fields are\n * absent.\n */\nfunction parseAgentMeta(content: string): AgentMeta {\n try {\n const parsed = JSON.parse(content) as Record<string, unknown>;\n return {\n persona:\n typeof parsed['persona'] === 'string'\n ? parsed['persona']\n : '',\n };\n } catch {\n return { persona: '' };\n }\n}\n\n/**\n * Builds the skills listing user message text from an array of\n * skill section content strings. Sections whose JSON is not parseable\n * or whose name cannot be determined are omitted silently.\n *\n * Returns `null` when no valid skills remain after filtering.\n */\nfunction buildSkillsText(skillSections: ReadSection[]): string | null {\n const lines: string[] = [];\n for (const sec of skillSections) {\n try {\n const parsed = JSON.parse(sec.content) as Record<\n string,\n unknown\n >;\n const name =\n typeof parsed['name'] === 'string' ? parsed['name'] : null;\n if (name === null) {\n continue;\n }\n const description =\n typeof parsed['description'] === 'string'\n ? parsed['description']\n : '';\n lines.push(`- ${name}: ${description}`);\n } catch {\n // skip unparseable sections\n }\n }\n if (lines.length === 0) {\n return null;\n }\n return `Available skills:\\n${lines.join('\\n')}`;\n}\n\n/**\n * Handles an MCP `prompts/get` request for an agent prompt.\n *\n * Looks up the agent by title via `listDocumentsByType('agent')`,\n * extracts its persona from the metadata section, then reads all\n * skill sections and composes the response. Returns an assistant\n * message with the persona and, when skills exist, a user message\n * listing them.\n */\nasync function handleAgentPrompt(\n name: string,\n client: McpWorkerClient,\n): Promise<McpPromptMessage[]> {\n const agentName = name.slice(6);\n const agents = await client.listDocumentsByType('agent');\n const doc = agents.find((a) => a.title === agentName) as\n | AgentDocument\n | undefined;\n if (!doc) {\n throw new Error('agent not found: ' + agentName);\n }\n const sections = doc.sections;\n\n const metaSection = sections.at(0);\n const skillRefs = sections.slice(1);\n\n let persona = '';\n if (metaSection !== undefined) {\n const metaSections = await client.readSections([\n metaSection.kbid,\n ]);\n const metaContent = metaSections.at(0);\n if (metaContent !== undefined) {\n persona = parseAgentMeta(metaContent.content).persona;\n }\n }\n\n const messages: McpPromptMessage[] = [\n {\n role: 'assistant',\n content: { type: 'text', text: persona },\n },\n ];\n\n if (skillRefs.length === 0) {\n return messages;\n }\n\n const skillKbids = skillRefs.map((s) => s.kbid);\n const skillSections = await client.readSections(skillKbids);\n const skillsText = buildSkillsText(skillSections);\n\n if (skillsText !== null) {\n messages.push({\n role: 'user',\n content: { type: 'text', text: skillsText },\n });\n }\n\n return messages;\n}\n\n/**\n * Handles an MCP `prompts/get` request for a skill prompt.\n *\n * Looks up the skill by name in the `listByType('skill')` results,\n * picks the most recent match (last occurrence), parses its body,\n * and substitutes `{{argName}}` placeholders from `promptArgs`.\n * Unresolved placeholders are left as-is.\n *\n * @throws {Error} when no skill with the given name is found\n */\nasync function handleSkillPrompt(\n name: string,\n promptArgs: Record<string, string>,\n client: McpWorkerClient,\n): Promise<McpPromptMessage[]> {\n const sections = await client.listByType('skill');\n let matchContent: string | undefined;\n for (const sec of sections) {\n if (sec.title === name) {\n matchContent = sec.content;\n }\n }\n if (matchContent === undefined) {\n throw new Error(`Prompt not found: ${name}`);\n }\n\n const parsed = JSON.parse(matchContent) as Record<string, unknown>;\n const body =\n typeof parsed['body'] === 'string' ? parsed['body'] : '';\n\n const rendered = body.replace(\n /\\{\\{(\\w+)\\}\\}/g,\n (_match, key: string) =>\n key in promptArgs ? (promptArgs[key] ?? _match) : _match,\n );\n\n return [\n {\n role: 'user',\n content: { type: 'text', text: rendered },\n },\n ];\n}\n\n/**\n * Handles an MCP `prompts/get` request.\n *\n * Dispatches to the agent handler when `name` starts with `\"agent:\"`,\n * otherwise treats the name as a skill prompt.\n *\n * For skill prompts: looks up by title using `listByType('skill')`,\n * substitutes `{{argName}}` placeholders in the body, and returns a\n * single user message.\n *\n * For agent prompts: looks up the agent by title via\n * `listDocumentsByType('agent')`, builds an assistant message from\n * the persona section, and (when skills exist) a user message\n * listing their names and descriptions.\n *\n * @param name - prompt name from the MCP request\n * @param promptArgs - argument key-value map from the MCP request\n * @param client - worker client used to access the knowledge base\n * @returns ordered list of prompt messages to return to the caller\n * @throws {Error} when a skill prompt name is not found in the store\n */\nexport async function handlePromptGet(\n name: string,\n promptArgs: Record<string, string>,\n client: McpWorkerClient,\n): Promise<McpPromptMessage[]> {\n if (name.startsWith('agent:')) {\n return handleAgentPrompt(name, client);\n }\n return handleSkillPrompt(name, promptArgs, client);\n}\n", "import type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\n\n/**\n * Discriminated reference used in MCP completion requests.\n * Identifies whether the completion target is a prompt or a resource.\n */\nexport interface McpCompletionRef {\n /**\n * The reference type: `'ref/prompt'` for named prompts (skills\n * and agents) or `'ref/resource'` for resource URIs.\n */\n readonly type: 'ref/prompt' | 'ref/resource';\n /** Prompt name, present when `type` is `'ref/prompt'`. */\n readonly name?: string;\n /** Resource URI, present when `type` is `'ref/resource'`. */\n readonly uri?: string;\n}\n\n/**\n * Completion argument supplied by the client, describing which\n * argument is being completed and the current partial value.\n */\nexport interface McpCompletionArgument {\n /** The argument name being completed. */\n readonly name: string;\n /** The partial value typed so far; used for prefix filtering. */\n readonly value: string;\n}\n\n/**\n * Result returned by `handleCompletion`, containing the list of\n * matching completion values and pagination metadata.\n */\nexport interface McpCompletionResult {\n /** Completion payload. */\n readonly completion: {\n /** Matching completion strings for the given prefix. */\n readonly values: string[];\n /**\n * Whether more results are available beyond what is returned.\n * Always `false` in this implementation.\n */\n readonly hasMore: boolean;\n /** Total number of values returned. */\n readonly total: number;\n };\n}\n\n/**\n * Handles an MCP `completion/complete` request.\n *\n * For `ref/prompt` references, builds a list of all skill titles and\n * agent titles (prefixed with `agent:`) and filters by the supplied\n * argument value prefix. For `ref/resource` references, returns an\n * empty result \u2014 resource completion is not implemented.\n *\n * @param ref - discriminated reference identifying the completion target\n * @param argument - current argument name and partial value\n * @param client - worker client used to fetch skills and agents\n * @returns matching completion values with pagination metadata\n */\nexport async function handleCompletion(\n ref: McpCompletionRef,\n argument: McpCompletionArgument,\n client: McpWorkerClient,\n): Promise<McpCompletionResult> {\n if (ref.type !== 'ref/prompt') {\n return { completion: { values: [], hasMore: false, total: 0 } };\n }\n\n const [skills, agents] = await Promise.all([\n client.listByType('skill'),\n client.listDocumentsByType('agent'),\n ]);\n\n const names: string[] = [];\n\n for (const skill of skills) {\n if (skill.title !== null) {\n names.push(skill.title);\n }\n }\n\n for (const agent of agents) {\n names.push(`agent:${agent.title}`);\n }\n\n const prefix = argument.value;\n\n function matchesPrefix(candidate: string): boolean {\n if (prefix.length === 0) {\n return true;\n }\n if (candidate.startsWith(prefix)) {\n return true;\n }\n // For agent-prefixed names, also match against the title portion.\n const AGENT_PREFIX = 'agent:';\n if (candidate.startsWith(AGENT_PREFIX)) {\n return candidate.slice(AGENT_PREFIX.length).startsWith(prefix);\n }\n return false;\n }\n\n const values = names.filter(matchesPrefix);\n\n return {\n completion: {\n values,\n hasMore: false,\n total: values.length,\n },\n };\n}\n", "/**\n * Represents a single file-system root entry advertised to MCP\n * clients via the `roots/list` response.\n */\nexport interface McpRoot {\n /** Absolute file URI for the root directory. */\n readonly uri: string;\n /** Human-readable label for the root. */\n readonly name: string;\n}\n\n/**\n * Returns the list of MCP roots for the given database context path.\n *\n * Produces a single root entry whose URI is `file://` concatenated\n * with the supplied `contextPath`. This tells MCP clients which\n * file-system directory the server is authoritative for.\n *\n * @param contextPath - absolute path to the kbdb database directory\n * @returns array containing a single root for the context path\n */\nexport function handleRootsList(contextPath: string): McpRoot[] {\n return [\n {\n uri: `file://${contextPath}`,\n name: 'kbdb database',\n },\n ];\n}\n", "import type { McpLogLevel } from '../typings/log-types.interface.ts';\n\n/**\n * Ordered list of MCP log severity levels, from least severe\n * (`debug`) to most severe (`emergency`). Used to compare levels\n * when filtering log output.\n */\nexport const LOG_LEVEL_ORDER: McpLogLevel[] = [\n 'debug',\n 'info',\n 'notice',\n 'warning',\n 'error',\n 'critical',\n 'alert',\n 'emergency',\n];\n\n/**\n * Determines whether a log message at `messageLevel` should be\n * emitted when the server's log threshold is `threshold`.\n *\n * Returns `true` when `messageLevel` is at the same severity as\n * `threshold` or higher. Returns `false` when the message level is\n * below the threshold.\n *\n * @param messageLevel - severity of the log message to evaluate\n * @param threshold - minimum severity level required to emit\n * @returns `true` if the message meets or exceeds the threshold\n */\nexport function shouldEmitLog(\n messageLevel: McpLogLevel,\n threshold: McpLogLevel,\n): boolean {\n const messageIndex = LOG_LEVEL_ORDER.indexOf(messageLevel);\n const thresholdIndex = LOG_LEVEL_ORDER.indexOf(threshold);\n return messageIndex >= thresholdIndex;\n}\n", "/**\n * JSON-RPC 2.0 parse error code. Returned when the\n * server receives malformed JSON.\n */\nexport const PARSE_ERROR = -32700;\n\n/**\n * JSON-RPC 2.0 method not found error code. Returned\n * when the requested method does not exist.\n */\nexport const METHOD_NOT_FOUND = -32601;\n\n/**\n * JSON-RPC 2.0 invalid params error code. Returned\n * when method parameters are invalid or missing.\n */\nexport const INVALID_PARAMS = -32602;\n\n/**\n * JSON-RPC 2.0 internal error code. Returned when an\n * unexpected server-side error occurs.\n */\nexport const INTERNAL_ERROR = -32603;\n\n/**\n * MCP-specific resource not found error code. Returned\n * when a well-formed URI does not match any resource\n * in the knowledge base.\n */\nexport const RESOURCE_NOT_FOUND = -32002;\n", "import { McpServer } from '../classes/mcp-server.class.ts';\nimport type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\n\n/**\n * Factory that constructs a new `McpServer` bound to the given\n * worker client. Call `server.listen()` on the returned instance\n * to start processing stdio input.\n *\n * @param client - worker client providing knowledge-base operations\n * @returns a configured `McpServer` ready to listen\n */\nexport function createMcpServer(client: McpWorkerClient): McpServer {\n return new McpServer(client);\n}\n", "/**\n * @module\n *\n * CLI and MCP server executable for kbdb. Provides the\n * `kbdb` command with 18 subcommands for managing a\n * file-based knowledge base, and an MCP server mode\n * for AI agent integration.\n */\n\nimport { getArgs, detectRuntime } from './shared/runtime/index.ts';\nimport {\n resolveBaseDir,\n resolveWorkerScript,\n} from './shared/dir-resolver/index.ts';\nimport {\n runCli,\n isStdinTty,\n promptUser,\n findDb,\n runInit,\n} from './shared/cli/index.ts';\nimport type { CliDeps } from './shared/cli/index.ts';\nimport { createWorkerClient } from './shared/worker-client/index.ts';\nimport { createMcpServer } from './shared/mcp/index.ts';\n\nconst runtime = detectRuntime();\nconst baseDir = resolveBaseDir(import.meta.url, import.meta.dirname);\nconst workerScript = resolveWorkerScript(baseDir.scriptDir, runtime);\n\nconst deps: CliDeps = {\n isStdinTty,\n promptUser,\n createWorkerClient: (opts) =>\n createWorkerClient({ ...opts, workerScript }),\n findDb,\n runInit,\n startMcpServer: async (contextPath) => {\n const client = await createWorkerClient({\n contextPath,\n workerScript,\n });\n try {\n const server = createMcpServer(client);\n await server.listen();\n } finally {\n client.disconnect();\n }\n },\n};\n\nasync function main(): Promise<void> {\n const result = await runCli(getArgs(), deps);\n if (result.output) {\n // eslint-disable-next-line no-console\n console.log(result.output);\n }\n if (result.error) {\n // eslint-disable-next-line no-console\n console.error(result.error);\n }\n if (result.exitCode !== 0) {\n process.exitCode = result.exitCode;\n }\n}\n\nmain().catch((err: unknown) => {\n const msg = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console\n console.error(`error: ${msg}`);\n process.exitCode = 1;\n});\n"],
5
- "mappings": ";;;;AAQO,SAAS,gBAAyB;AACtC,MAAI,OAAO,eAAe,eAAe,UAAU,YAAY;AAC5D,WAAO;AAAA,EACV;AACA,SAAO;AACV;;;ACLO,SAAS,UAAoB;AACjC,MAAI,cAAc,MAAM,QAAQ;AAC7B,UAAM,IAAI;AACV,UAAM,OAAO,EAAE,MAAM;AACrB,WAAO,MAAM,QAAQ,CAAC;AAAA,EACzB;AACA,SAAO,QAAQ,KAAK,MAAM,CAAC;AAC9B;;;ACfA,uBAAwB;AACxB,sBAA8B;AAIvB,SAAS,iBACb,UACA,cACO;AACP,MAAI,aAAc,QAAO;AACzB,MAAI,SAAS,WAAW,OAAO;AAC5B,eAAO,8BAAQ,+BAAc,QAAQ,CAAC;AACzC,aAAO,0BAAQ,QAAQ;AAC1B;AAEO,SAAS,eACb,UACA,cACQ;AACR,QAAM,YACH,OAAO,cAAc,cAChB,YACA,iBAAiB,UAAU,YAAY;AAC/C,SAAO,EAAE,WAAW,KAAK,QAAQ,IAAI,EAAE;AAC1C;;;ACxBA,IAAAA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e,QAAQ,IAAI,UAAU,OAAO,GAAG;AAE3D,UAAQ,MAAM,UAAU,GAAG,EAAE;AAC7B,UAAQ,WAAW;AACtB,CAAC;",
6
- "names": ["import_node_path", "runtime", "import_node_path", "resolve", "import_node_fs", "import_node_path", "import_node_fs", "import_node_path", "import_node_fs", "import_node_path", "resolve", "desc", "deps", "resolve", "import_node_fs", "import_node_path", "import_node_os", "import_node_fs", "import_node_path", "import_node_fs", "import_node_path", "runtime", "workerScript", "import_node_fs", "import_node_path", "import_node_os", "import_node_path", "import_node_os", "runtime", "import_node_readline", "readAgentMeta", "handleRecall", "asString", "asStringArray", "handleSearch", "handleLearn", "handleUnlearn", "handleRecall", "handleStatus", "handleContent", "handleCheck", "handleGc", "handleRebuild", "handleExport", "resolve"]
3
+ "sources": ["../src/cli.ts", "../src/shared/runtime/functions/detect-runtime.ts", "../src/shared/runtime/functions/get-args.ts", "../src/shared/dir-resolver/functions/resolve-base-dir.function.ts", "../src/shared/dir-resolver/functions/join-path.function.ts", "../src/shared/dir-resolver/functions/resolve-worker-script.function.ts", "../src/shared/cli/constants/defaults.constant.ts", "../src/shared/cli/functions/parse-args.function.ts", "../src/shared/cli/functions/format-output.function.ts", "../src/shared/cli/functions/run-search.function.ts", "../src/shared/cli/functions/resolve-kbid-prefix.function.ts", "../src/shared/cli/functions/run-recall.function.ts", "../src/shared/cli/functions/run-export.function.ts", "../src/shared/cli/functions/run-learn.function.ts", "../src/shared/cli/functions/run-unlearn.function.ts", "../src/shared/cli/functions/run-content.function.ts", "../src/shared/cli/functions/run-check.function.ts", "../src/shared/cli/functions/run-gc.function.ts", "../src/shared/cli/functions/run-rebuild.function.ts", "../src/shared/cli/functions/find-db.function.ts", "../src/shared/cli/functions/run-init.function.ts", "../src/shared/cli/functions/install-default-skills.function.ts", "../src/shared/cli/functions/error-to-message.function.ts", "../src/shared/cli/functions/is-stdin-tty.function.ts", "../src/shared/cli/functions/prompt-user.function.ts", "../src/shared/cli/functions/run-status.function.ts", "../src/shared/cli/functions/run-db-init.function.ts", "../src/shared/cli/functions/run-db-migrate.function.ts", "../src/shared/mcp/functions/extract-skill-arguments.function.ts", "../src/shared/mcp/functions/serialize-skill-content.function.ts", "../src/shared/cli/functions/run-skill-learn.function.ts", "../src/shared/cli/functions/run-skill-list.function.ts", "../src/shared/mcp/functions/parse-skill-content.function.ts", "../src/shared/cli/functions/run-skill-get.function.ts", "../src/shared/cli/functions/run-skill-delete.function.ts", "../src/shared/cli/functions/run-agent-create.function.ts", "../src/shared/cli/functions/run-agent-list.function.ts", "../src/shared/cli/functions/run-agent-get.function.ts", "../src/shared/cli/functions/run-agent-delete.function.ts", "../src/shared/cli/functions/run-import.function.ts", "../src/shared/cli/functions/dispatch-command.function.ts", "../src/shared/version/constants/version.constant.ts", "../src/shared/cli/functions/generate-help.function.ts", "../src/shared/worker-client/classes/worker-client.class.ts", "../src/shared/worker-client/functions/create-worker-client.function.ts", "../src/shared/worker-client/functions/resolve-db-path.function.ts", "../src/shared/hash/functions/compute-sha256.ts", "../src/shared/worker-client/functions/compute-context-id.function.ts", "../src/shared/worker-client/functions/discover-daemon.function.ts", "../src/shared/platform/functions/is-process-alive.function.ts", "../src/shared/worker-client/functions/spawn-daemon.function.ts", "../src/shared/worker-client/functions/wait-for-daemon.function.ts", "../src/shared/platform/functions/get-ipc-path.function.ts", "../src/shared/platform/functions/get-tmpdir.function.ts", "../src/shared/cli/functions/run-worker-stop.function.ts", "../src/shared/cli/functions/run-worker-restart.function.ts", "../src/shared/cli/functions/resolve-raw-db-path.function.ts", "../src/shared/worker-client/functions/retry-on-timeout.function.ts", "../src/shared/worker-client/constants/request-timeout.constant.ts", "../src/shared/worker-client/constants/retry-defaults.constant.ts", "../src/shared/cli/functions/run-cli.function.ts", "../src/shared/cli/constants/help-text.constant.ts", "../src/shared/mcp/classes/mcp-server.class.ts", "../src/shared/mcp/functions/create-tool-definitions.function.ts", "../src/shared/mcp/functions/create-resource-templates.function.ts", "../src/shared/mcp/functions/handle-agent-create.function.ts", "../src/shared/mcp/functions/handle-agent-list.function.ts", "../src/shared/mcp/functions/handle-agent-get.function.ts", "../src/shared/mcp/functions/handle-agent-delete.function.ts", "../src/shared/mcp/functions/handle-recall.function.ts", "../src/shared/mcp/functions/handle-tool-call.function.ts", "../src/shared/mcp/functions/handle-resource-read.function.ts", "../src/shared/mcp/functions/create-prompt-definitions.function.ts", "../src/shared/mcp/functions/handle-prompt-get.function.ts", "../src/shared/mcp/functions/handle-completion.function.ts", "../src/shared/mcp/functions/handle-roots-list.function.ts", "../src/shared/mcp/functions/should-emit-log.function.ts", "../src/shared/auto-capture/functions/build-capture-prompt.function.ts", "../src/shared/mcp/functions/has-sampling-capability.function.ts", "../src/shared/mcp/functions/run-auto-capture.function.ts", "../src/shared/auto-capture/functions/evaluate-trigger.function.ts", "../src/shared/auto-capture/classes/auto-capture-controller.class.ts", "../src/shared/mcp/constants/mcp-error-codes.constant.ts", "../src/shared/mcp/functions/create-mcp-server.function.ts", "../src/shared/worker-daemon/constants/daemon-defaults.constant.ts", "../src/shared/worker-daemon/functions/parse-embedding-section.function.ts", "../src/shared/auto-capture/constants/auto-capture-defaults.constant.ts", "../src/shared/worker-daemon/functions/parse-auto-capture-section.function.ts", "../src/shared/worker-daemon/functions/parse-worker-toml.function.ts"],
4
+ "sourcesContent": ["/**\n * @module\n *\n * CLI and MCP server executable for kbdb. Provides the\n * `kbdb` command with 18 subcommands for managing a\n * file-based knowledge base, and an MCP server mode\n * for AI agent integration.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { getArgs, detectRuntime } from './shared/runtime/index.ts';\nimport {\n resolveBaseDir,\n resolveWorkerScript,\n} from './shared/dir-resolver/index.ts';\nimport {\n runCli,\n isStdinTty,\n promptUser,\n findDb,\n runInit,\n} from './shared/cli/index.ts';\nimport type { CliDeps } from './shared/cli/index.ts';\nimport { createWorkerClient } from './shared/worker-client/index.ts';\nimport { createMcpServer } from './shared/mcp/index.ts';\nimport type { McpWorkerClient } from './shared/mcp/typings/mcp-client.interface.ts';\nimport { parseWorkerToml } from './shared/worker-daemon/functions/parse-worker-toml.function.ts';\n\nconst runtime = detectRuntime();\nconst baseDir = resolveBaseDir(import.meta.url, import.meta.dirname);\nconst workerScript = resolveWorkerScript(baseDir.scriptDir, runtime);\n\nconst deps: CliDeps = {\n isStdinTty,\n isStdoutTty: () => process.stdout.isTTY,\n promptUser,\n createWorkerClient: (opts) =>\n createWorkerClient({ ...opts, workerScript }),\n findDb,\n runInit,\n startMcpServer: async (contextPath, clientFactory, maxRetries) => {\n const client = await createWorkerClient({\n contextPath,\n workerScript,\n });\n try {\n const tomlPath = join(contextPath, 'worker.toml');\n let autoCaptureConfig;\n try {\n const tomlText = readFileSync(tomlPath, 'utf-8');\n const daemonConfig = parseWorkerToml(tomlText, contextPath);\n autoCaptureConfig = daemonConfig.autoCapture;\n } catch {\n // worker.toml absent or unreadable -- auto-capture stays off\n }\n const server = createMcpServer(\n client,\n contextPath,\n autoCaptureConfig,\n clientFactory as\n | (() => Promise<McpWorkerClient>)\n | undefined,\n maxRetries,\n );\n await server.listen();\n } finally {\n client.disconnect();\n }\n },\n};\n\nasync function main(): Promise<void> {\n const result = await runCli(getArgs(), deps);\n if (result.output) {\n // eslint-disable-next-line no-console\n console.log(result.output);\n }\n if (result.error) {\n // eslint-disable-next-line no-console\n console.error(result.error);\n }\n if (result.exitCode !== 0) {\n process.exitCode = result.exitCode;\n }\n}\n\nmain().catch((err: unknown) => {\n const msg = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console\n console.error(`error: ${msg}`);\n process.exitCode = 1;\n});\n", "import type { Runtime } from '../typings/runtime.ts';\n\n/**\n * Detects the current JavaScript runtime environment.\n *\n * Returns `'deno'` when the global `Deno` object is present,\n * otherwise returns `'node'`.\n */\nexport function detectRuntime(): Runtime {\n if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {\n return 'deno';\n }\n return 'node';\n}\n", "import { detectRuntime } from './detect-runtime.ts';\n\n/**\n * Returns the command-line arguments for the current runtime.\n *\n * In Deno, reads `Deno.args`; in Node.js, slices `process.argv`\n * past the interpreter and script entries.\n */\nexport function getArgs(): string[] {\n if (detectRuntime() === 'deno') {\n const g = globalThis as Record<string, unknown>;\n const deno = g['Deno'] as { args: string[] } | undefined;\n return deno?.args ?? [];\n }\n return process.argv.slice(2);\n}\n", "import { dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { BaseDir } from '../typings/base-dir.interface.ts';\n\nexport function resolveScriptDir(\n entryUrl: string,\n entryDirname?: string,\n): string {\n if (entryDirname) return entryDirname;\n if (entryUrl.startsWith('file:'))\n return dirname(fileURLToPath(entryUrl));\n return dirname(entryUrl);\n}\n\nexport function resolveBaseDir(\n entryUrl: string,\n entryDirname?: string,\n): BaseDir {\n const scriptDir =\n typeof __dirname !== 'undefined'\n ? __dirname\n : resolveScriptDir(entryUrl, entryDirname);\n return { scriptDir, cwd: process.cwd() };\n}\n", "import { join } from 'node:path';\n\nexport function isRemoteUrl(path: string): boolean {\n return path.startsWith('http://') || path.startsWith('https://');\n}\n\nexport function joinPath(base: string, ...segments: string[]): string {\n if (isRemoteUrl(base)) {\n const trailing = base.endsWith('/') ? '' : '/';\n return base + trailing + segments.join('/');\n }\n return join(base, ...segments);\n}\n", "import { joinPath } from './join-path.function.ts';\n\nimport type { Runtime } from '../../runtime/typings/runtime.ts';\n\nexport function resolveWorkerScript(\n scriptDir: string,\n runtime: Runtime,\n): string {\n if (runtime === 'deno') {\n return joinPath(scriptDir, 'worker.ts');\n }\n return joinPath(scriptDir, 'kbdb-worker.cjs');\n}\n", "/** Default maximum number of search results returned per query. */\nexport const DEFAULT_LIMIT = 20;\n\n/** Default output format when `--format` is not specified. */\nexport const DEFAULT_FORMAT = 'json' as const;\n\n/** Default search mode when `--mode` is not specified. */\nexport const DEFAULT_MODE = 'sections' as const;\n\n/**\n * File extensions recognised as importable documents by the learn\n * command. Extensions are lowercase and include the leading dot.\n */\nexport const SUPPORTED_EXTENSIONS = [\n '.md',\n '.txt',\n '.rst',\n '.adoc',\n] as const;\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport {\n DEFAULT_FORMAT,\n DEFAULT_LIMIT,\n DEFAULT_MODE,\n} from '../constants/defaults.constant.ts';\n\n/**\n * Parses a raw argument vector into a structured `CliOptions` object.\n *\n * Recognises `--help` / `-h` and `--version` / `-v` as early-exit\n * flags that set the command and return immediately. All other flags\n * consume the next token as their value. The first non-flag token\n * becomes the command; subsequent non-flag tokens become `args`.\n *\n * Compound commands are supported: when the first positional token is\n * a group name (`db`, `skill`, `agent`, or `worker`), the next\n * positional token is joined with a hyphen to form the compound\n * command (e.g. `db init` \u2192 `'db-init'`,\n * `worker stop` \u2192 `'worker-stop'`).\n *\n * Context-aware `--help`: when `--help` or `-h` appears after a\n * command has been set, the existing command is moved to `args[0]`\n * and the command is set to `'help'`, enabling per-command help.\n *\n * Deprecated flags `--init` and `--migrate` emit a warning to stderr\n * before setting the corresponding command.\n *\n * @param argv - argument strings (typically `process.argv.slice(2)`)\n * @returns fully populated `CliOptions` with defaults applied\n */\nexport function parseArgs(argv: string[]): CliOptions {\n const options: CliOptions = {\n command: '',\n format: DEFAULT_FORMAT,\n mode: DEFAULT_MODE,\n limit: DEFAULT_LIMIT,\n args: [],\n };\n\n let i = 0;\n while (i < argv.length) {\n const arg = argv[i];\n switch (arg) {\n case '--help':\n case '-h':\n if (options.command) {\n options.args.unshift(options.command);\n options.command = 'help';\n } else {\n options.command = 'help';\n }\n return options;\n case '--version':\n case '-v':\n options.command = 'version';\n return options;\n case '--init':\n // eslint-disable-next-line no-console\n console.error(\n 'warning: --init is deprecated,' + ' use \"kbdb db init\"',\n );\n options.command = 'init';\n break;\n case '--migrate':\n // eslint-disable-next-line no-console\n console.error(\n 'warning: --migrate is deprecated,' +\n ' use \"kbdb db migrate\"',\n );\n options.command = 'migrate';\n break;\n case '--db':\n options.dbPath = argv[++i];\n break;\n case '--format':\n case '-f':\n options.format = (argv[++i] ??\n DEFAULT_FORMAT) as CliOptions['format'];\n options.formatExplicit = true;\n break;\n case '--mode':\n case '-m':\n options.mode = (argv[++i] ??\n DEFAULT_MODE) as CliOptions['mode'];\n break;\n case '--limit':\n case '-l':\n options.limit =\n parseInt(argv[++i] ?? '', 10) || DEFAULT_LIMIT;\n break;\n case '--offset':\n case '-o':\n options.offset = Math.max(\n 0,\n parseInt(argv[++i] ?? '', 10) || 0,\n );\n break;\n case '--algo':\n options.algo = argv[++i];\n break;\n case '--title':\n options.title = argv[++i];\n break;\n case '--description':\n options.description = argv[++i];\n break;\n case '--docid':\n options.docid = argv[++i];\n break;\n case '--name':\n options.name = argv[++i];\n break;\n case '--persona':\n options.persona = argv[++i];\n break;\n case '--body':\n options.body = argv[++i];\n break;\n case '--skills':\n options.skills = (argv[++i] ?? '').split(',');\n break;\n case '--tags':\n options.tags = (argv[++i] ?? '').split(',');\n break;\n case '--replace':\n options.replace = true;\n break;\n case '--depth':\n case '-d':\n options.depth = Math.min(\n 3,\n Math.max(0, parseInt(argv[++i] ?? '', 10) || 0),\n );\n break;\n case '--content':\n case '-c':\n options.content = true;\n break;\n case '--relaxed':\n options.relaxed = true;\n break;\n case '--from':\n options.from = argv[++i];\n break;\n case '--dry-run':\n options.dryRun = true;\n break;\n case '--export-format':\n options.exportFormat = (argv[++i] ??\n 'git') as CliOptions['exportFormat'];\n break;\n case '--timeout-ms':\n options.timeoutMs =\n parseInt(argv[++i] ?? '', 10) || undefined;\n break;\n case '--retry':\n options.retry = parseInt(argv[++i] ?? '', 10) || undefined;\n break;\n default:\n if (!options.command) {\n options.command = arg;\n } else if (\n !options.args.length &&\n (options.command === 'db' ||\n options.command === 'skill' ||\n options.command === 'agent' ||\n options.command === 'worker')\n ) {\n options.command = `${options.command}-${arg}`;\n } else {\n options.args.push(arg);\n }\n }\n i++;\n }\n\n return options;\n}\n", "import type { OutputFormat } from '../typings/cli-options.interface.ts';\nimport type { PagedSearchDisplay } from '../typings/search-display.model.ts';\n\n/**\n * Serialises a paged search result into the requested output\n * format string.\n *\n * - `'json'` -- pretty-printed JSON envelope\n * - `'text'` -- numbered human-readable list with paging footer\n * - `'mcp'` -- JSON envelope compatible with MCP protocol\n *\n * @param paged - paginated search results to format\n * @param format - target output format\n * @returns formatted string ready for stdout\n */\nexport function formatOutput(\n paged: PagedSearchDisplay,\n format: OutputFormat,\n): string {\n switch (format) {\n case 'json':\n return JSON.stringify(paged, null, 2);\n case 'text':\n return formatText(paged);\n case 'mcp':\n return formatMcp(paged);\n }\n}\n\nfunction formatText(paged: PagedSearchDisplay): string {\n if (paged.items.length === 0) return 'No results found.';\n const start = paged.offset + 1;\n const end = paged.offset + paged.items.length;\n\n const lines = paged.items\n .map((r, i) => {\n const num = paged.offset + i + 1;\n const heading = r.heading ?? '(untitled)';\n const terms = r.matched_terms.join(', ');\n const fields = r.matched_fields.join(', ');\n const confidencePct = (r.confidence * 100).toFixed(0);\n return (\n `${String(num)}. [${r.kbid}] ${heading}` +\n ` (score: ${r.score.toFixed(4)},` +\n ` confidence: ${confidencePct}%)\\n` +\n ` ${r.snippet || r.preview || '(no snippet)'}\\n` +\n ` type: ${r.type}` +\n ` terms: ${terms}` +\n (fields ? ` fields: ${fields}` : '')\n );\n })\n .join('\\n\\n');\n\n const footer =\n `\\nShowing ${String(start)}-${String(end)}` +\n ` of ${String(paged.total)} results`;\n const hint = paged.has_more\n ? `\\nUse --offset ${String(end)} to see more`\n : '';\n\n return lines + footer + hint;\n}\n\nfunction formatMcp(paged: PagedSearchDisplay): string {\n const mcpItems = paged.items.map((r) => ({\n kbid: r.kbid,\n heading: r.heading,\n type: r.type,\n docids: r.docids,\n snippet: r.snippet,\n matched_terms: r.matched_terms,\n matched_fields: r.matched_fields,\n created_at: r.created_at,\n }));\n return JSON.stringify(\n {\n type: 'text',\n text: paged.items\n .map(\n (r) =>\n `[${r.kbid}] ${r.heading ?? '(untitled)'}` +\n ` \u2014 ${r.snippet || r.preview}`,\n )\n .join('\\n'),\n items: mcpItems,\n total: paged.total,\n offset: paged.offset,\n limit: paged.limit,\n has_more: paged.has_more,\n relaxed: paged.relaxed,\n },\n null,\n 2,\n );\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { PagedSearchDisplay } from '../typings/search-display.model.ts';\n\n/** A single raw search result item returned by the daemon. */\ninterface RawSearchItem {\n /** Knowledge-base identifier of the matched section. */\n readonly kbid: string;\n /** Section heading, or null when untitled. */\n readonly heading: string | null;\n /** MIME type of the section content. */\n readonly type: string;\n /** Document IDs this section belongs to. */\n readonly docids: readonly string[];\n /** Relevance score from the ranking engine. */\n readonly score: number;\n /** KWIC excerpt centered on the highest-scoring matched term. */\n readonly snippet: string;\n /** Query terms that matched within this section. */\n readonly matched_terms: readonly string[];\n /**\n * Fields that contained at least one match.\n * May be absent from older daemon versions.\n */\n readonly matched_fields?: readonly string[];\n /**\n * Normalised confidence score (0.0-1.0) relative to the top result.\n * May be absent from older daemon versions.\n */\n readonly confidence?: number;\n /**\n * ISO 8601 creation timestamp of the section.\n * May be absent from older daemon versions.\n */\n readonly created_at?: string;\n}\n\n/** Raw paginated search response from the daemon. */\ninterface RawSearchResponse {\n /** Result items for the current page. */\n readonly items: readonly RawSearchItem[];\n /** Total number of matches across all pages. */\n readonly total: number;\n /** Number of results skipped. */\n readonly offset: number;\n /** Maximum results per page. */\n readonly limit: number;\n /** Whether more results exist beyond this page. */\n readonly has_more: boolean;\n /**\n * When `true`, the engine relaxed the query to produce results.\n * May be absent from older daemon versions.\n */\n readonly relaxed?: boolean;\n /** Server-side computation time in milliseconds. */\n readonly elapsed_ms?: number;\n /** Algorithm that produced these results. */\n readonly search_mode?: string;\n /** Retrieval strategy used (e.g. `'lexical'`, `'rrf'`). */\n readonly retrieval_method?: string;\n}\n\n/**\n * Minimal client interface required by `runSearch`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface SearchClient {\n /**\n * Searches the knowledge base and returns paginated results.\n *\n * @param params - query, mode, limit, and offset\n */\n search(params: {\n query: string;\n mode?: string;\n limit?: number;\n offset?: number;\n algo?: string;\n relaxed?: boolean;\n }): Promise<RawSearchResponse>;\n}\n\n/**\n * Executes a search query via the provided client and maps the\n * daemon results to the `PagedSearchDisplay` format used by the\n * CLI.\n *\n * Returns an empty paged result without calling the client when\n * `options.args` contains no query terms.\n *\n * @param client - search client to delegate to\n * @param options - parsed CLI options supplying query args and\n * search parameters\n */\nexport async function runSearch(\n client: SearchClient,\n options: CliOptions,\n): Promise<PagedSearchDisplay> {\n const query = options.args.join(' ').trim();\n if (!query) {\n return {\n items: [],\n total: 0,\n offset: 0,\n limit: options.limit,\n has_more: false,\n relaxed: false,\n };\n }\n\n const results = await client.search({\n query,\n mode: options.mode,\n limit: options.limit,\n offset: options.offset,\n algo: options.algo,\n relaxed: options.relaxed,\n });\n\n return {\n items: results.items.map((r) => ({\n kbid: r.kbid,\n heading: r.heading,\n type: r.type,\n docids: r.docids,\n score: r.score,\n confidence: r.confidence ?? 0,\n snippet: r.snippet,\n matched_terms: r.matched_terms,\n matched_fields: r.matched_fields ?? [],\n created_at: r.created_at ?? '',\n preview: '',\n })),\n total: results.total,\n offset: results.offset,\n limit: results.limit,\n has_more: results.has_more,\n relaxed: results.relaxed ?? false,\n elapsed_ms: results.elapsed_ms,\n search_mode: results.search_mode,\n retrieval_method: results.retrieval_method,\n };\n}\n", "/**\n * Minimal client interface for listing section kbids.\n *\n * Decouples prefix resolution from the concrete\n * `WorkerClient` so tests can use lightweight mocks.\n */\nexport interface PrefixResolver {\n /** Returns all sections of the given type. */\n listByType(\n sectionType: string,\n ): Promise<readonly { kbid: string }[]>;\n}\n\n/** Section types to scan when resolving a kbid prefix. */\nconst SECTION_TYPES = ['text', 'code', 'image'] as const;\n\n/**\n * Resolves a potentially short kbid prefix to its full\n * 26-character identifier.\n *\n * Full-length identifiers (>= 26 chars) are returned as-is.\n * For shorter prefixes, all section types are scanned to find\n * matching kbids. Throws when no match is found or the prefix\n * is ambiguous (matches more than one kbid).\n *\n * @param prefix - full or partial kbid string\n * @param client - client providing `listByType`\n * @returns the resolved full kbid\n * @throws when no match or ambiguous match is found\n */\nexport async function resolveKbidPrefix(\n prefix: string,\n client: PrefixResolver,\n): Promise<string> {\n if (prefix.length >= 26) return prefix;\n\n const seen = new Set<string>();\n for (const type of SECTION_TYPES) {\n const records = await client.listByType(type);\n for (const r of records) {\n if (r.kbid.startsWith(prefix)) seen.add(r.kbid);\n }\n }\n\n if (seen.size === 0) {\n throw new Error(`no section matches prefix \"${prefix}\"`);\n }\n if (seen.size > 1) {\n throw new Error(\n `ambiguous prefix \"${prefix}\":` +\n ` ${seen.size.toString()} matches`,\n );\n }\n\n return [...seen][0];\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { RecallResult } from '../../worker-client/typings/recall-result.model.ts';\nimport type { PrefixResolver } from './resolve-kbid-prefix.function.ts';\nimport { resolveKbidPrefix } from './resolve-kbid-prefix.function.ts';\n\n/** Maximum allowed expansion depth for recall operations. */\nconst MAX_RECALL_DEPTH = 3;\n\n/**\n * Minimal client interface required by `runRecall`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n * Extends `PrefixResolver` so short kbid prefixes can be resolved\n * before the recall call is made.\n */\nexport interface RecallClient extends PrefixResolver {\n /**\n * Retrieves full content and context for one or more sections\n * by their knowledge-base identifiers.\n *\n * @param params - section identifier(s) and optional expansion\n * depth (0--3)\n * @returns a single `RecallResult` when `kbid` is supplied, or\n * a `RecallResult[]` when `kbids` is supplied\n */\n recall(params: {\n kbid?: string;\n kbids?: string[];\n depth?: number;\n }): Promise<RecallResult | RecallResult[]>;\n}\n\n/**\n * Retrieves full content and progressive context for one or more\n * sections by kbid via the provided client.\n *\n * Returns an error result when no kbids are provided in\n * `options.args`. Short kbid prefixes in `options.args` are\n * resolved to full identifiers before the recall call. For a single\n * kbid, calls `client.recall` with the `kbid` parameter and returns\n * the single `RecallResult`. For multiple kbids, calls\n * `client.recall` with the `kbids` array.\n *\n * The `depth` option is read from `options.depth`, defaulting to 0\n * and clamped to the range 0--3.\n *\n * @param client - recall client to delegate to\n * @param options - parsed CLI options supplying kbids in `args` and\n * expansion depth in `depth`\n * @returns the `RecallResult` or `RecallResult[]` from the client,\n * or an error object when no kbids are provided\n * @throws when a prefix matches no section or is ambiguous\n */\nexport async function runRecall(\n client: RecallClient,\n options: CliOptions,\n): Promise<RecallResult | RecallResult[] | { error: string }> {\n if (options.args.length === 0) {\n return { error: 'no kbid provided' };\n }\n\n const depth = Math.min(\n MAX_RECALL_DEPTH,\n Math.max(0, options.depth ?? 0),\n );\n\n const resolved = await Promise.all(\n options.args.map((a) => resolveKbidPrefix(a, client)),\n );\n\n if (resolved.length === 1) {\n return client.recall({ kbid: resolved[0], depth });\n }\n\n return client.recall({ kbids: resolved, depth });\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { ExportResult } from '../../worker-client/typings/export-result.model.ts';\n\n/**\n * Minimal client interface required by `runExport`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface ExportClient {\n /**\n * Exports the database to the given directory path.\n *\n * @param params - optional target path; the daemon defaults to\n * `./kbdb-export/` when `path` is `undefined`\n * @returns export report with the resolved path and file counts\n */\n export(params: { path?: string }): Promise<ExportResult>;\n}\n\n/**\n * Exports the knowledge-base database to a target directory via the\n * provided client.\n *\n * The target path is taken from `options.args[0]`. When no argument\n * is given the daemon resolves its own default (`./kbdb-export/`).\n *\n * @param client - export client to delegate to\n * @param options - parsed CLI options whose first positional\n * argument, if present, is the target directory path\n * @returns the export result containing the resolved path and file\n * counts\n */\nexport async function runExport(\n client: ExportClient,\n options: CliOptions,\n): Promise<ExportResult> {\n const path = options.args[0];\n return client.export({ path });\n}\n", "import { readFileSync, readdirSync, statSync } from 'node:fs';\nimport { basename, extname, join } from 'node:path';\nimport type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { LearnResult } from '../typings/learn-result.model.ts';\nimport { SUPPORTED_EXTENSIONS } from '../constants/defaults.constant.ts';\n\n/** Enriched add-section result returned by the daemon. */\ninterface AddSectionResult {\n /** Knowledge-base identifier assigned to the new section. */\n readonly kbid: string;\n /**\n * Kbid of the section superseded via `--replace`,\n * or `null` / `undefined` when none.\n */\n readonly superseded?: string | null;\n /**\n * Advisory warning strings (e.g. `\"heading_missing\"`).\n * May be absent from older daemon versions.\n */\n readonly warnings?: string[];\n /**\n * Near-duplicate sections with similarity >= 0.85.\n * May be absent from older daemon versions.\n */\n readonly near_duplicates?: {\n readonly kbid: string;\n readonly similarity: number;\n }[];\n}\n\n/**\n * Minimal client interface required by `runLearn`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface LearnClient {\n /**\n * Ingests a content section into the knowledge base.\n *\n * @param params - section metadata and raw text content\n * @returns enriched result containing the new kbid plus\n * optional supersession, warnings, and near-duplicate info\n */\n addSection(params: {\n sectionType: string;\n content: string;\n title?: string;\n description?: string;\n docid?: string;\n tags?: string[];\n replace?: boolean;\n /**\n * Absolute path to the source file. Required for supersession\n * via source key when `replace` is `true`.\n */\n sourcePath?: string;\n }): Promise<AddSectionResult>;\n}\n\n/** Injectable I/O for testing without real stdin. */\nexport interface LearnIO {\n readStdin: () => Promise<string>;\n}\n\n/**\n * Ingests one or more files or directories listed in `options.args`\n * into the knowledge base via the provided client.\n *\n * Each argument is resolved to a set of supported files. Unsupported\n * extensions, dotfiles, dot-directories, and non-existent paths are\n * silently skipped. The `-` argument reads content from stdin\n * (consumed only once).\n *\n * @param client - learn client to delegate ingestion to\n * @param options - parsed CLI options whose `args` list targets to\n * ingest\n * @param io - injectable I/O (defaults to reading process.stdin)\n * @returns one `LearnResult` per file successfully ingested\n */\nexport async function runLearn(\n client: LearnClient,\n options: CliOptions,\n io?: LearnIO,\n): Promise<LearnResult[]> {\n const results: LearnResult[] = [];\n let stdinConsumed = false;\n const readStdin = io?.readStdin ?? readProcessStdin;\n\n for (const target of options.args) {\n if (target === '-') {\n if (stdinConsumed) continue;\n stdinConsumed = true;\n const content = await readStdin();\n const result = await client.addSection({\n sectionType: 'text',\n content,\n title: options.title,\n description: options.description,\n docid: options.docid,\n tags: options.tags,\n replace: options.replace,\n });\n results.push(mapAddSectionResult(result, '-', content.length));\n continue;\n }\n\n const files = collectFiles(target);\n for (const file of files) {\n const content = readFileSync(file, 'utf-8');\n const result = await client.addSection({\n sectionType: 'text',\n content,\n title: options.title,\n description: options.description,\n docid: options.docid,\n tags: options.tags,\n replace: options.replace,\n sourcePath: file,\n });\n results.push(\n mapAddSectionResult(result, file, content.length),\n );\n }\n }\n\n return results;\n}\n\n/**\n * Maps an `AddSectionResult` to a `LearnResult` record.\n *\n * @param result - raw result from `client.addSection()`\n * @param path - source file path or `'-'` for stdin\n * @param size - UTF-8 character count of the ingested content\n */\nfunction mapAddSectionResult(\n result: AddSectionResult,\n path: string,\n size: number,\n): LearnResult {\n return {\n kbid: result.kbid,\n path,\n size,\n skipped: false,\n superseded: result.superseded ?? null,\n warnings: result.warnings ?? [],\n near_duplicates: result.near_duplicates ?? [],\n };\n}\n\nfunction readProcessStdin(): Promise<string> {\n return new Promise<string>((resolve) => {\n const chunks: Buffer[] = [];\n process.stdin.on('data', (chunk: Buffer) => {\n chunks.push(chunk);\n });\n process.stdin.on('end', () => {\n resolve(Buffer.concat(chunks).toString('utf-8'));\n });\n process.stdin.resume();\n });\n}\n\n/**\n * Resolves a single target path to a flat list of supported files.\n *\n * Returns an empty array for non-existent or inaccessible paths.\n *\n * @param target - file or directory path to resolve\n */\nfunction collectFiles(target: string): string[] {\n try {\n const stat = statSync(target);\n if (stat.isFile()) {\n return isSupportedFile(target) ? [target] : [];\n }\n if (stat.isDirectory()) {\n return scanDirectory(target);\n }\n } catch {\n // Non-existent or inaccessible path -- skip\n }\n return [];\n}\n\n/**\n * Recursively scans a directory and returns all supported files,\n * excluding dot-entries at every level.\n *\n * @param dir - absolute or relative directory path to scan\n */\nfunction scanDirectory(dir: string): string[] {\n const files: string[] = [];\n for (const entry of readdirSync(dir)) {\n if (entry.startsWith('.')) continue;\n const full = join(dir, entry);\n try {\n const stat = statSync(full);\n if (stat.isDirectory()) {\n files.push(...scanDirectory(full));\n } else if (isSupportedFile(full)) {\n files.push(full);\n }\n } catch {\n // Skip inaccessible entries\n }\n }\n return files;\n}\n\n/**\n * Returns `true` when the file's extension is in\n * `SUPPORTED_EXTENSIONS`.\n *\n * @param path - file path to check\n */\nfunction isSupportedFile(path: string): boolean {\n if (basename(path).startsWith('.')) return false;\n const ext = extname(path).toLowerCase();\n return (SUPPORTED_EXTENSIONS as readonly string[]).includes(ext);\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { PrefixResolver } from './resolve-kbid-prefix.function.ts';\nimport { resolveKbidPrefix } from './resolve-kbid-prefix.function.ts';\n\n/** Removal result returned by `UnlearnClient.removeSection`. */\ninterface RemoveSectionResult {\n /** `true` when the section was found and successfully removed. */\n readonly removed: boolean;\n /** Time taken to perform the removal, in milliseconds. */\n readonly elapsed_ms: number;\n}\n\n/**\n * Minimal client interface required by `runUnlearn`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n * Extends `PrefixResolver` so short kbid prefixes can be resolved\n * before each section is removed.\n */\nexport interface UnlearnClient extends PrefixResolver {\n /**\n * Removes a section from the knowledge base.\n *\n * @param kbid - identifier of the section to remove\n * @returns removal result with `removed` flag and elapsed time\n */\n removeSection(kbid: string): Promise<RemoveSectionResult>;\n}\n\n/** Result record produced for each kbid processed by the unlearn command. */\nexport interface UnlearnResult {\n /** Knowledge-base identifier that was targeted for removal. */\n kbid: string;\n /** `true` when the section was found and successfully removed. */\n removed: boolean;\n}\n\n/**\n * Removes the knowledge-base sections identified by `options.args`\n * via the provided client.\n *\n * Short kbid prefixes in `options.args` are resolved to full\n * identifiers before removal. Each kbid is processed independently.\n * If a kbid does not exist in the knowledge base, `removed` is set\n * to `false` rather than throwing.\n *\n * @param client - unlearn client to delegate removal to\n * @param options - parsed CLI options whose `args` list the kbids to\n * remove\n * @returns one `UnlearnResult` per kbid processed\n * @throws when a prefix matches no section or is ambiguous\n */\nexport async function runUnlearn(\n client: UnlearnClient,\n options: CliOptions,\n): Promise<UnlearnResult[]> {\n const results: UnlearnResult[] = [];\n for (const arg of options.args) {\n const kbid = await resolveKbidPrefix(arg, client);\n const result = await client.removeSection(kbid);\n results.push({ kbid, removed: result.removed });\n }\n return results;\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { PrefixResolver } from './resolve-kbid-prefix.function.ts';\nimport { resolveKbidPrefix } from './resolve-kbid-prefix.function.ts';\n\n/** Result returned by content composition. */\ninterface ContentResult {\n /** MIME type of the composed output, always `'text/markdown'`. */\n readonly type: 'text/markdown';\n /** The composed Markdown string. */\n readonly data: string;\n /** Character count of `data` (not byte count). */\n readonly total: number;\n}\n\n/**\n * Minimal client interface required by `runContent`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n * Extends `PrefixResolver` so short kbid prefixes can be resolved\n * before the content call is made.\n */\nexport interface ContentClient extends PrefixResolver {\n /**\n * Composes a rendered Markdown document from one or more kbid\n * or docid identifiers.\n *\n * @param ids - list of kbid or docid identifiers (may be mixed)\n * @returns composed Markdown result with character count\n */\n content(ids: string[]): Promise<ContentResult>;\n}\n\n/**\n * Composes and returns a rendered Markdown document from the\n * identifiers listed in `options.args`.\n *\n * Short kbid prefixes in `options.args` are resolved to full\n * identifiers before calling `client.content`. The caller is\n * responsible for writing the result to stdout.\n *\n * @param client - content client to delegate composition to\n * @param options - parsed CLI options whose `args` list the kbid or\n * docid identifiers to compose\n * @returns the composed content result from the daemon\n * @throws when a prefix matches no section or is ambiguous\n */\nexport async function runContent(\n client: ContentClient,\n options: CliOptions,\n): Promise<ContentResult> {\n const resolved = await Promise.all(\n options.args.map((a) => resolveKbidPrefix(a, client)),\n );\n return client.content(resolved);\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\n\n/** A single integrity error found during a database check. */\ninterface IntegrityError {\n /**\n * The category of integrity violation detected.\n *\n * - `'checksum_mismatch'` -- stored content does not match its hash\n * - `'orphan_section'` -- section not referenced by any document\n * - `'orphan_document'` -- document references no existing sections\n * - `'broken_reference'` -- a marker references a non-existent entity\n * - `'type_mismatch'` -- stored MIME type conflicts with content\n * - `'circular_reference'` -- marker chain contains a cycle\n */\n readonly type:\n | 'checksum_mismatch'\n | 'orphan_section'\n | 'orphan_document'\n | 'broken_reference'\n | 'type_mismatch'\n | 'circular_reference';\n /** Identifier of the entity (kbid or docid) that has the issue. */\n readonly entity: string;\n /** Human-readable description of the specific problem. */\n readonly detail: string;\n}\n\n/**\n * A single entry in the divergent-content map.\n * Groups kbids under a common source key.\n */\ninterface DivergentContentEntry {\n /** Source key that has multiple divergent content versions. */\n readonly sourceKey: string;\n /** Kbids of sections sharing this source key but with different content. */\n readonly kbids: string[];\n}\n\n/**\n * Integrity check report returned by the daemon.\n */\ninterface IntegrityCheckResult {\n /** `true` when all checks passed and no errors were found. */\n readonly ok: boolean;\n /** All integrity errors found; empty when `ok` is `true`. */\n readonly errors: IntegrityError[];\n /** Total number of sections examined. */\n readonly sections_checked: number;\n /** Total number of documents examined. */\n readonly documents_checked: number;\n /** Total number of marker references checked. */\n readonly references_checked: number;\n /** Time taken to complete the check, in milliseconds. */\n readonly elapsed_ms: number;\n /**\n * Sections that share a source key but have divergent content.\n * Each entry groups the kbids under a common source key.\n * Empty when no divergent content is found.\n */\n readonly divergent_content: DivergentContentEntry[];\n}\n\n/** Raw daemon response from `integrityCheck`. */\ninterface RawIntegrityCheckResult {\n /** `true` when all checks passed and no errors were found. */\n readonly ok: boolean;\n /** All integrity errors found; empty when `ok` is `true`. */\n readonly errors: IntegrityError[];\n /** Total number of sections examined. */\n readonly sections_checked: number;\n /** Total number of documents examined. */\n readonly documents_checked: number;\n /** Total number of marker references checked. */\n readonly references_checked: number;\n /** Time taken to complete the check, in milliseconds. */\n readonly elapsed_ms: number;\n /**\n * Encoded divergent-content map.\n *\n * Format: `sk1:kbid1,kbid2;sk2:kbid3,kbid4`\n *\n * Each semicolon-separated segment is a source key followed by\n * a colon and a comma-separated list of kbids. Absent when no\n * divergent content exists.\n */\n readonly divergent_content?: string;\n}\n\n/**\n * Minimal client interface required by `runCheck`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface CheckClient {\n /**\n * Runs an integrity check on the knowledge-base database.\n *\n * @returns a report of all issues found; `ok` is `true` when\n * no errors were detected\n */\n integrityCheck(): Promise<RawIntegrityCheckResult>;\n}\n\n/**\n * Parses the encoded `divergent_content` string from the daemon\n * into a structured array.\n *\n * Input format: `sk1:kbid1,kbid2;sk2:kbid3,kbid4`\n *\n * @param encoded - raw encoded string, or empty / absent\n * @returns structured entries grouped by source key\n */\nfunction parseDivergentContent(\n encoded: string | undefined,\n): DivergentContentEntry[] {\n if (!encoded) return [];\n return encoded\n .split(';')\n .filter((segment) => segment.includes(':'))\n .map((segment) => {\n const colonIdx = segment.indexOf(':');\n const sourceKey = segment.slice(0, colonIdx);\n const kbids = segment\n .slice(colonIdx + 1)\n .split(',')\n .filter((k) => k.length > 0);\n return { sourceKey, kbids };\n })\n .filter((entry) => entry.kbids.length > 0);\n}\n\n/**\n * Runs an integrity check on the database and returns the report.\n *\n * Delegates to `client.integrityCheck()`, then parses the encoded\n * `divergent_content` field into structured form. The caller is\n * responsible for printing the result to stdout and setting the\n * process exit code based on `result.ok`.\n *\n * @param client - check client to delegate to\n * @param _options - parsed CLI options (unused; reserved for future flags)\n * @returns the integrity check report with parsed `divergent_content`\n */\nexport async function runCheck(\n client: CheckClient,\n _options: CliOptions,\n): Promise<IntegrityCheckResult> {\n const raw = await client.integrityCheck();\n return {\n ok: raw.ok,\n errors: raw.errors,\n sections_checked: raw.sections_checked,\n documents_checked: raw.documents_checked,\n references_checked: raw.references_checked,\n elapsed_ms: raw.elapsed_ms,\n divergent_content: parseDivergentContent(raw.divergent_content),\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\n\n/**\n * Garbage collection report returned by the daemon.\n */\ninterface GcResult {\n /** Number of unreferenced sections removed. */\n readonly removed_sections: number;\n /** Total bytes freed by removing unreferenced sections. */\n readonly removed_bytes: number;\n /** Time taken to complete garbage collection, in milliseconds. */\n readonly elapsed_ms: number;\n /**\n * Number of sections whose `source_path` file no longer\n * contains their heading text (advisory; not auto-removed).\n * Absent on older daemon versions.\n */\n readonly stale_sources?: number;\n}\n\n/**\n * Minimal client interface required by `runGc`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface GcClient {\n /**\n * Removes unreferenced sections from the database.\n *\n * @returns a report of sections removed and bytes freed\n */\n gc(): Promise<GcResult>;\n}\n\n/**\n * Runs garbage collection on the database and returns the report.\n *\n * Delegates to `client.gc()`. The caller is responsible for printing\n * the result to stdout.\n *\n * @param client - gc client to delegate to\n * @param _options - parsed CLI options (unused; reserved for future flags)\n * @returns the garbage collection report from the daemon\n */\nexport async function runGc(\n client: GcClient,\n _options: CliOptions,\n): Promise<GcResult> {\n return client.gc();\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\n\n/**\n * Index rebuild report returned by the daemon.\n */\ninterface RebuildResult {\n /** Number of text and code sections that were re-indexed. */\n readonly sections_reindexed: number;\n /** Total number of unique terms written to the rebuilt indexes. */\n readonly terms_indexed: number;\n /** Time taken to complete the rebuild, in milliseconds. */\n readonly elapsed_ms: number;\n}\n\n/**\n * Minimal client interface required by `runRebuild`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface RebuildClient {\n /**\n * Reconstructs all index files from section files and document\n * manifests on disk. Text and code sections are re-tokenized;\n * image sections are skipped.\n *\n * @returns a report of sections and terms re-indexed\n */\n rebuildIndexes(): Promise<RebuildResult>;\n}\n\n/**\n * Rebuilds all database indexes and returns the report.\n *\n * Delegates to `client.rebuildIndexes()`. The caller is responsible\n * for printing the result to stdout.\n *\n * @param client - rebuild client to delegate to\n * @param _options - parsed CLI options (unused; reserved for future flags)\n * @returns the index rebuild report from the daemon\n */\nexport async function runRebuild(\n client: RebuildClient,\n _options: CliOptions,\n): Promise<RebuildResult> {\n return client.rebuildIndexes();\n}\n", "import { existsSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\n\n/**\n * Locates the `.kbdb` database directory.\n *\n * When `dbPath` is provided, checks only that directory.\n * When omitted, walks up from the current working directory\n * until a `.kbdb` directory is found or the filesystem root\n * is reached.\n *\n * @param dbPath - explicit base directory; skips traversal\n * @returns absolute path to `.kbdb`, or `null` when not found\n */\nexport function findDb(dbPath?: string): string | null {\n if (dbPath) {\n const target = join(resolve(dbPath), '.kbdb');\n return existsSync(target) ? target : null;\n }\n let current = process.cwd();\n let parent = dirname(current);\n while (parent !== current) {\n const candidate = join(current, '.kbdb');\n if (existsSync(candidate)) return candidate;\n current = parent;\n parent = dirname(current);\n }\n const candidate = join(current, '.kbdb');\n return existsSync(candidate) ? candidate : null;\n}\n", "import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport type { CliOptions } from '../typings/cli-options.interface.ts';\nimport { installDefaultSkills } from './install-default-skills.function.ts';\n\n/**\n * Result returned by `runInit` describing whether the directory was\n * successfully initialised.\n */\nexport interface InitResult {\n /** `true` when the database directory was created successfully. */\n readonly ok: boolean;\n /** Absolute path to the directory that was (or should have been) initialised. */\n readonly targetPath: string;\n /**\n * Human-readable error message when `ok` is `false`.\n * `undefined` when `ok` is `true`.\n */\n readonly errorMessage?: string;\n}\n\nconst DB_FORMAT_VERSION = 1;\n\nconst CATALOG_TOML = `version = ${DB_FORMAT_VERSION.toString()}\nsection_count = 0\ndocument_count = 0\ncreated_at = 0\nupdated_at = 0\nchecksum = \"\"\n`;\n\nconst WORKER_TOML = '# kbdb worker configuration\\n';\n\nconst GITIGNORE = [\n '# kbdb binary indexes (auto-generated)',\n 'corpus.bin',\n 'inverted.idx',\n 'positional.idx',\n '',\n].join('\\n');\n\n/**\n * Creates the `.kbdb` directory scaffold directly on disk.\n *\n * This mirrors the Rust `init_directory` in\n * `engine/crates/fs-database/src/scaffold.rs` and does not\n * require a running worker daemon.\n */\nfunction createScaffold(dbDir: string): void {\n mkdirSync(dbDir, { recursive: true });\n mkdirSync(join(dbDir, 'sections'));\n mkdirSync(join(dbDir, 'documents'));\n writeFileSync(join(dbDir, 'catalog.toml'), CATALOG_TOML);\n writeFileSync(join(dbDir, 'corpus.bin'), '');\n writeFileSync(join(dbDir, 'inverted.idx'), '');\n writeFileSync(join(dbDir, 'positional.idx'), '');\n writeFileSync(join(dbDir, 'worker.toml'), WORKER_TOML);\n writeFileSync(join(dbDir, '.gitignore'), GITIGNORE);\n}\n\n/**\n * Initialises a new `.kbdb` database directory.\n *\n * Creates the full scaffold directly on disk without requiring a\n * running worker daemon. Resolves the target path from\n * `options.dbPath` or `process.cwd()`.\n *\n * @param options - parsed CLI options supplying the optional `dbPath`\n * @returns init result indicating success or failure\n */\nexport function runInit(options: CliOptions): InitResult {\n const basePath = options.dbPath\n ? resolve(options.dbPath)\n : process.cwd();\n const dbDir = join(basePath, '.kbdb');\n\n try {\n if (existsSync(dbDir)) {\n return {\n ok: false,\n targetPath: dbDir,\n errorMessage: `database directory already exists: ${dbDir}`,\n };\n }\n createScaffold(dbDir);\n installDefaultSkills(dbDir);\n return { ok: true, targetPath: dbDir };\n } catch (err: unknown) {\n const errorMessage =\n err instanceof Error ? err.message : String(err);\n return { ok: false, targetPath: dbDir, errorMessage };\n }\n}\n", "import { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/**\n * RFC 4648 base32 alphabet (upper-case, no padding).\n * Used to encode the SHA-256-derived kbid bytes.\n */\nconst BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';\n\n/**\n * Encodes a byte array as a lowercase base32 string without padding.\n *\n * Mirrors the `data_encoding::BASE32_NOPAD` encoding used in the\n * Rust engine's `KbId::from_content`.\n *\n * @param bytes - raw bytes to encode\n * @returns lowercase base32-encoded string\n */\nfunction base32Encode(bytes: Uint8Array): string {\n let result = '';\n let bits = 0;\n let value = 0;\n for (const byte of bytes) {\n value = (value << 8) | byte;\n bits += 8;\n while (bits >= 5) {\n result += BASE32_ALPHABET[(value >>> (bits - 5)) & 0x1f];\n bits -= 5;\n }\n }\n if (bits > 0) {\n result += BASE32_ALPHABET[(value << (5 - bits)) & 0x1f];\n }\n return result.toLowerCase();\n}\n\n/**\n * Computes a 26-character kbid for a section using the same algorithm\n * as the Rust engine's `hash_section`.\n *\n * Algorithm:\n * 1. Build input: `\"section <mime> <byteLen>\\0<content>\"`\n * 2. SHA-256 hash the input\n * 3. Take the first 16 bytes\n * 4. Base32 encode (RFC 4648, no padding), lowercased \u2192 26 chars\n *\n * @param mimeType - MIME type string (e.g. `\"text/markdown\"`)\n * @param content - UTF-8 section content string\n * @returns 26-character lowercase base32 kbid\n */\nfunction computeSectionKbid(mimeType: string, content: string): string {\n const contentBytes = Buffer.from(content, 'utf-8');\n const header = `section ${mimeType} ${contentBytes.length.toString()}\\0`;\n const headerBytes = Buffer.from(header, 'utf-8');\n const input = Buffer.concat([headerBytes, contentBytes]);\n const hash = createHash('sha256').update(input).digest();\n const truncated = new Uint8Array(hash.buffer, 0, 16);\n return base32Encode(truncated);\n}\n\n/**\n * Escapes backslashes and double-quotes in a string for TOML inline\n * string values.\n *\n * Mirrors the `escape_toml_str` function in the Rust engine.\n *\n * @param s - string to escape\n * @returns escaped string safe for use inside TOML double-quoted strings\n */\nfunction escapeToml(s: string): string {\n return s.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n}\n\n/**\n * Serializes a skill section record to the `.section` file format.\n *\n * Format:\n * ```\n * kbid = \"...\"\n * section_type = \"text/markdown\"\n * type_name = \"skill\"\n * title = \"...\"\n * description = \"...\"\n * size = 0\n * token_count = 0\n * heading_token_count = 0\n * body_token_count = 0\n * code_token_count = 0\n * created_at = 0\n * checksum = \"...\"\n *\n * ---\n * <json content>\n * ```\n *\n * @param kbid - 26-char content-addressed identifier\n * @param title - skill name used as section title\n * @param description - human-readable description\n * @param content - serialised JSON skill definition\n * @returns file content string\n */\nfunction serializeSkillSection(\n kbid: string,\n title: string,\n description: string,\n content: string,\n): string {\n const size = Buffer.byteLength(content, 'utf-8');\n const header = [\n `kbid = \"${escapeToml(kbid)}\"`,\n `section_type = \"text/markdown\"`,\n `type_name = \"skill\"`,\n `title = \"${escapeToml(title)}\"`,\n `description = \"${escapeToml(description)}\"`,\n `size = ${size.toString()}`,\n `token_count = 0`,\n `heading_token_count = 0`,\n `body_token_count = 0`,\n `code_token_count = 0`,\n `created_at = 0`,\n `checksum = \"${escapeToml(kbid)}\"`,\n '',\n ].join('\\n');\n return `${header}\\n---\\n${content}`;\n}\n\n/** Descriptor for a skill to install. */\ninterface SkillDescriptor {\n /** Unique skill name (kebab-case). */\n readonly name: string;\n /** Human-readable description. */\n readonly description: string;\n /** Template body text. */\n readonly body: string;\n}\n\n/**\n * Installs a single skill section file under `sectionsDir`.\n *\n * Creates the shard subdirectory if it does not exist. Skips\n * writing if the section file already exists, preserving any\n * user modifications.\n *\n * @param sectionsDir - absolute path to `.kbdb/sections`\n * @param skill - skill definition to serialise and store\n */\nfunction installSkill(\n sectionsDir: string,\n skill: SkillDescriptor,\n): void {\n const content = JSON.stringify({\n name: skill.name,\n description: skill.description,\n arguments: [],\n body: skill.body,\n });\n const kbid = computeSectionKbid('text/markdown', content);\n const prefix = kbid.slice(0, 2);\n const shardDir = join(sectionsDir, prefix);\n const filePath = join(shardDir, `${kbid}.section`);\n\n if (existsSync(filePath)) {\n return;\n }\n\n mkdirSync(shardDir, { recursive: true });\n\n const fileContent = serializeSkillSection(\n kbid,\n skill.name,\n skill.description,\n content,\n );\n writeFileSync(filePath, fileContent, 'utf-8');\n}\n\n/**\n * Body text for the `query-guidance` default skill.\n *\n * Teaches AI agents how to effectively search the knowledge base\n * using lexical BM25F queries.\n */\nconst QUERY_GUIDANCE_BODY =\n 'This knowledge base uses lexical search (stemmed BM25F), not' +\n ' semantic/vector search. Follow these guidelines for effective' +\n ' retrieval:\\n\\n' +\n '1. Issue MULTIPLE short keyword queries rather than one long' +\n ' natural-language question. Each query should target 2-3' +\n ' specific terms.\\n\\n' +\n '2. EXPAND SYNONYMS yourself. \"login\" will not match \"sign-in\"' +\n ' unless both terms appear in the content. Try alternative' +\n ' phrasings: search for \"login\", then \"sign-in\", then' +\n ' \"authentication\".\\n\\n' +\n '3. USE BOOLEAN AND PHRASE SYNTAX:\\n' +\n ' - Exact phrases: \"error handling\"\\n' +\n ' - Boolean AND: auth AND token\\n' +\n ' - Boolean OR: cache OR redis\\n' +\n ' - Exclusion: auth -oauth\\n\\n' +\n '4. LEAN ON HEADINGS. Headings carry 2x weight in ranking.' +\n ' Search for terms that are likely in section titles.\\n\\n' +\n '5. STEMMING IS AUTOMATIC. \"connections\" matches \"connect\",' +\n ' \"running\" matches \"run\". You do not need to try inflected' +\n ' forms.\\n\\n' +\n '6. USE RECALL AFTER SEARCH. After finding relevant sections' +\n ' with search, use recall with increasing depth (0-3) to' +\n ' progressively expand context: depth 0 = full content, depth' +\n ' 1 = parent documents + back-references, depth 2 = siblings' +\n ' + forward references, depth 3 = referenced sections.\\n\\n' +\n '7. CODE IDENTIFIERS ARE SPLIT. camelCase and snake_case names' +\n ' are decomposed: getUserById becomes searchable as \"get\",' +\n ' \"user\", \"by\", \"id\".\\n\\n' +\n '8. PAGINATION. Default limit is 20 results. Use offset for' +\n ' additional pages if total > limit.';\n\n/**\n * Body text for the `memory-protocol` default skill.\n *\n * Teaches AI agents when and what to store in the knowledge base\n * to keep it accurate and useful.\n */\nconst MEMORY_PROTOCOL_BODY =\n 'Follow these guidelines to keep the knowledge base accurate' +\n ' and useful:\\n\\n' +\n '1. STORE DURABLE FACTS: decisions, architecture choices,' +\n ' configuration values, corrections to prior knowledge, API' +\n ' contracts, and resolved incidents. These are the facts that' +\n ' matter weeks later.\\n\\n' +\n '2. DO NOT STORE: transient conversation context, debugging' +\n ' output, ephemeral task state, raw log dumps, or information' +\n ' that changes every session. The brain should contain' +\n ' knowledge, not activity logs.\\n\\n' +\n '3. SEARCH BEFORE STORING. Always search the knowledge base' +\n ' before adding new content. If a section already covers the' +\n ' topic, use learn with --replace to update it rather than' +\n ' creating a duplicate.\\n\\n' +\n '4. USE --replace FOR CORRECTIONS. When a fact changes (e.g.,' +\n ' rate limit updated from 100 to 200 req/min), re-learn the' +\n ' corrected content with --replace so the old version is' +\n ' superseded. Without --replace, both the old and new versions' +\n ' coexist with equal ranking.\\n\\n' +\n '5. ATTACH TAGS for scoping. Use tags like project name,' +\n ' domain, or topic (e.g., --tags auth,api,v2) so queries can' +\n ' be filtered by scope later.\\n\\n' +\n '6. PREFER RECENT RESULTS. When search returns multiple' +\n ' sections covering the same topic, prefer the one with the' +\n ' most recent created_at timestamp -- it is more likely to' +\n ' reflect the current state.\\n\\n' +\n '7. USE RECALL AFTER SEARCH. After finding relevant sections,' +\n ' use recall with increasing depth (0-3) to expand context' +\n ' progressively before making decisions.\\n\\n' +\n '8. INCLUDE HEADINGS. Always provide a descriptive title when' +\n ' storing content. Headings carry 2x ranking weight -- omitting' +\n ' them significantly reduces searchability.';\n\n/**\n * Default skills installed on every fresh `kbdb db init`.\n *\n * These provide baseline guidance that improves AI agent\n * effectiveness out of the box. They are regular skill sections\n * and can be deleted by users.\n */\nconst DEFAULT_SKILLS: readonly SkillDescriptor[] = [\n {\n name: 'query-guidance',\n description:\n 'How to effectively search this knowledge base.' +\n ' Read this before issuing search queries.',\n body: QUERY_GUIDANCE_BODY,\n },\n {\n name: 'memory-protocol',\n description:\n 'Guidelines for what to store in this knowledge base' +\n ' and when. Read this before using the learn tool.',\n body: MEMORY_PROTOCOL_BODY,\n },\n];\n\n/**\n * Writes the two default skills (`query-guidance` and\n * `memory-protocol`) as section files directly into the `.kbdb`\n * directory scaffold.\n *\n * Called by `runInit` after the directory scaffold is created.\n * Does not require a running worker daemon. Skips any skill whose\n * section file already exists so user modifications are preserved.\n *\n * @param dbDir - absolute path to the `.kbdb` directory\n */\nexport function installDefaultSkills(dbDir: string): void {\n const sectionsDir = join(dbDir, 'sections');\n for (const skill of DEFAULT_SKILLS) {\n installSkill(sectionsDir, skill);\n }\n}\n", "/**\n * Converts an unknown thrown value to a human-readable message.\n *\n * @param err - the caught value\n * @returns the error message string\n */\nexport function errorToMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n", "/**\n * Returns `true` when stdin is an interactive terminal.\n *\n * @param stdin - readable stream to check (defaults to\n * `process.stdin`)\n */\nexport function isStdinTty(\n stdin: NodeJS.ReadStream = process.stdin,\n): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- isTTY is undefined at runtime for non-TTY despite Node types saying boolean\n return stdin.isTTY ?? false;\n}\n", "import { createInterface } from 'node:readline';\n\n/** Injectable I/O for testing without real stdin. */\nexport interface PromptIO {\n ask: (question: string) => Promise<string>;\n}\n\n/**\n * Prompts the user on stdin (TTY only) and returns the\n * trimmed reply.\n *\n * @param question - the prompt text to display\n * @param io - injectable I/O (defaults to readline on\n * process.stdin/stdout)\n */\nexport async function promptUser(\n question: string,\n io?: PromptIO,\n): Promise<string> {\n const ask = io?.ask ?? askReadline;\n const answer = await ask(question);\n return answer.trim();\n}\n\nfunction askReadline(question: string): Promise<string> {\n return new Promise<string>((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer);\n });\n });\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\n\n/**\n * Minimal client interface required by `runStatus`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface StatusClient {\n dbStatus(): Promise<unknown>;\n}\n\n/**\n * Retrieves the database status and returns the summary report.\n *\n * Delegates to `client.dbStatus()`. The caller is responsible\n * for serialising the result and setting the process exit code.\n *\n * @param client - status client to delegate to\n * @param _options - parsed CLI options (unused; reserved for\n * future flags)\n * @returns the status report from the daemon\n */\nexport async function runStatus(\n client: StatusClient,\n _options: CliOptions,\n): Promise<unknown> {\n return client.dbStatus();\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\nimport type { InitResult } from './run-init.function.ts';\n\n/**\n * Callable signature for the init operation injected into\n * `runDbInit`.\n */\nexport type RunInitFn = (options: CliOptions) => InitResult;\n\n/**\n * Executes the `db init` compound command by delegating to the\n * provided `runInit` function and mapping the result to a\n * `CommandResult`.\n *\n * Accepts `runInit` as an injectable parameter so the function\n * can be tested without touching the filesystem.\n *\n * @param options - parsed CLI options (forwarded to `runInitFn`)\n * @param runInitFn - function that performs the actual\n * initialisation\n * @returns a `CommandResult` with JSON output on success or an\n * error message on failure\n */\nexport function runDbInit(\n options: CliOptions,\n runInitFn: RunInitFn,\n): CommandResult {\n const result = runInitFn(options);\n if (result.ok) {\n return {\n output: JSON.stringify(\n { path: result.targetPath, created: true },\n null,\n 2,\n ),\n exitCode: 0,\n };\n }\n return {\n error: result.errorMessage ?? 'init failed',\n exitCode: 1,\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { MigrateResult } from '../../worker-client/typings/migrate-result.model.ts';\n\n/**\n * Minimal client interface required by `runDbMigrate`.\n *\n * Intentionally narrower than `MigrateClient` from\n * `run-migrate.function.ts` \u2014 this variant skips the version\n * check and unconditionally runs migrations. Callers that need\n * version-aware migration should use `runMigrate` instead.\n */\nexport interface DbMigrateClient {\n /**\n * Runs all pending database migrations.\n *\n * @param targetPath - absolute path to the `.kbdb` database root\n */\n migrateDatabase(targetPath: string): Promise<MigrateResult>;\n}\n\n/**\n * Runs database migrations unconditionally via `client.migrateDatabase`.\n *\n * Resolves the target path from `options.dbPath` when provided,\n * falling back to `process.cwd()`. Does not perform a version\n * compatibility check before migrating \u2014 use `runMigrate` for\n * version-aware migration flows.\n *\n * @param client - database migration client to delegate to\n * @param options - parsed CLI options supplying the optional\n * `dbPath`\n * @returns the migration report returned by the daemon\n */\nexport async function runDbMigrate(\n client: DbMigrateClient,\n options: CliOptions,\n): Promise<MigrateResult> {\n const dbPath = options.dbPath ?? process.cwd();\n return client.migrateDatabase(dbPath);\n}\n", "import type { SkillArgument } from '../typings/skill-types.interface.ts';\n\n/**\n * Extracts `{{argName}}` placeholder names from a skill body string\n * and returns them as `SkillArgument` objects marked as required.\n *\n * Each placeholder is included only once regardless of how many\n * times it appears, and the returned array preserves the order of\n * first occurrence.\n *\n * @param body - skill body template text to scan for placeholders\n * @returns ordered, deduplicated list of argument definitions\n */\nexport function extractSkillArguments(body: string): SkillArgument[] {\n const seen = new Set<string>();\n const args: SkillArgument[] = [];\n const re = /\\{\\{(\\w+)\\}\\}/g;\n let match: RegExpExecArray | null;\n while ((match = re.exec(body)) !== null) {\n const name = match[1];\n if (!seen.has(name)) {\n seen.add(name);\n args.push({ name, required: true });\n }\n }\n return args;\n}\n", "import type { SkillDefinition } from '../typings/skill-types.interface.ts';\n\n/**\n * Serializes a `SkillDefinition` to a JSON string suitable for\n * storage as a knowledge-base section's `content` field.\n *\n * @param skill - skill definition to serialize\n * @returns JSON string representation of the skill\n */\nexport function serializeSkillContent(skill: SkillDefinition): string {\n return JSON.stringify(skill);\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\nimport type { AddSectionResult } from '../../worker-client/typings/add-section-result.model.ts';\nimport { extractSkillArguments } from '../../mcp/functions/extract-skill-arguments.function.ts';\nimport { serializeSkillContent } from '../../mcp/functions/serialize-skill-content.function.ts';\n\n/**\n * Minimal client interface required by `runSkillLearn`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface SkillLearnClient {\n /**\n * Stores a skill section in the knowledge base.\n *\n * @param params - section type, serialized JSON content,\n * and optional title and description\n * @returns result containing the assigned kbid\n */\n addSection(params: {\n readonly sectionType: string;\n readonly content: string;\n readonly title?: string;\n readonly description?: string;\n }): Promise<AddSectionResult>;\n}\n\n/**\n * Creates or updates a skill definition in the knowledge base.\n *\n * Validates that `--name` and `--body` are provided, extracts\n * `{{argName}}` placeholders from the body, serializes the skill\n * to JSON, and stores it as a `'skill'` section.\n *\n * @param client - client used to store the skill section\n * @param options - parsed CLI options with `name` and `body` fields\n * @returns a `CommandResult` with the stored section info or an error\n */\nexport async function runSkillLearn(\n client: SkillLearnClient,\n options: CliOptions,\n): Promise<CommandResult> {\n const name = options.name;\n if (!name) {\n return { error: '--name is required', exitCode: 1 };\n }\n const body = options.body;\n if (!body) {\n return { error: '--body is required', exitCode: 1 };\n }\n const args = extractSkillArguments(body);\n const skill = {\n name,\n description: options.description,\n arguments: args.length > 0 ? args : undefined,\n body,\n };\n const json = serializeSkillContent(skill);\n const result = await client.addSection({\n sectionType: 'skill',\n content: json,\n title: name,\n description: options.description,\n });\n return {\n output: JSON.stringify(result, null, 2),\n exitCode: 0,\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\n\n/**\n * A single row returned by `listByType` for the skill client.\n */\ninterface SkillRecord {\n /** Knowledge-base identifier for the skill section. */\n kbid: string;\n /** Skill name stored as the section title. */\n title: string | null;\n /** Optional skill description stored on the section. */\n description: string | null;\n /** Serialized `SkillDefinition` JSON stored as section content. */\n content: string;\n}\n\n/**\n * Minimal client interface required by `runSkillList`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface SkillListClient {\n /**\n * Retrieves all sections stored with the given type name.\n *\n * @param sectionType - the type name to filter by\n * @returns matching section rows\n */\n listByType(sectionType: string): Promise<SkillRecord[]>;\n}\n\n/**\n * Lists all skill definitions stored in the knowledge base.\n *\n * Calls `client.listByType('skill')` and maps each record to a\n * summary that includes the argument count parsed from the JSON\n * content. Parse errors default the argument count to `0`.\n *\n * @param client - client used to list skill sections\n * @param _options - parsed CLI options (unused; reserved for future flags)\n * @returns a `CommandResult` containing a JSON array of skill summaries\n */\nexport async function runSkillList(\n client: SkillListClient,\n _options: CliOptions,\n): Promise<CommandResult> {\n const records = await client.listByType('skill');\n const items = records.map((r) => {\n let argumentCount = 0;\n try {\n const parsed = JSON.parse(r.content) as Record<\n string,\n unknown\n >;\n if (Array.isArray(parsed['arguments'])) {\n argumentCount = parsed['arguments'].length;\n }\n } catch {\n // ignore parse errors\n }\n return {\n kbid: r.kbid,\n name: r.title,\n description: r.description,\n argumentCount,\n };\n });\n return {\n output: JSON.stringify(items, null, 2),\n exitCode: 0,\n };\n}\n", "import type {\n SkillArgument,\n SkillDefinition,\n} from '../typings/skill-types.interface.ts';\n\n/**\n * Parses a JSON string into a `SkillDefinition`.\n *\n * Validates that the required `name` and `body` fields are present\n * and are non-empty strings, then returns the full definition\n * including optional `description` and `arguments`.\n *\n * @param json - JSON string representing a serialized skill\n * @returns the parsed skill definition\n * @throws {SyntaxError} when `json` is not valid JSON\n * @throws {Error} when `name` is missing or empty\n * @throws {Error} when `body` is missing or not a string\n */\nexport function parseSkillContent(json: string): SkillDefinition {\n const raw = JSON.parse(json) as Record<string, unknown>;\n if (typeof raw['name'] !== 'string' || !raw['name']) {\n throw new Error('skill name is required');\n }\n if (typeof raw['body'] !== 'string') {\n throw new Error('skill body is required');\n }\n return {\n name: raw['name'],\n description:\n typeof raw['description'] === 'string'\n ? raw['description']\n : undefined,\n arguments: Array.isArray(raw['arguments'])\n ? (raw['arguments'] as SkillArgument[])\n : undefined,\n body: raw['body'],\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\nimport { parseSkillContent } from '../../mcp/functions/parse-skill-content.function.ts';\n\n/**\n * Minimal client interface required by `runSkillGet`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface SkillGetClient {\n /**\n * Retrieves one or more sections by their knowledge-base IDs.\n *\n * @param kbids - list of knowledge-base identifiers to fetch\n * @returns matching section rows\n */\n readSections(\n kbids: string[],\n ): Promise<{ kbid: string; content: string }[]>;\n\n /**\n * Retrieves all sections stored with the given type name.\n *\n * @param sectionType - the type name to filter by\n * @returns matching section rows\n */\n listByType(\n sectionType: string,\n ): Promise<\n { kbid: string; title: string | null; content: string }[]\n >;\n}\n\n/**\n * Retrieves a skill definition by name or kbid.\n *\n * Accepts the identifier as the first positional argument or as\n * `options.name`. When the identifier looks like a hex hash\n * (16 or more hex characters) it is tried as a kbid first; if\n * no section is found it falls back to a name lookup. When the\n * identifier is not hex-like it goes directly to name lookup.\n * For name lookups the most recently stored match (last in the\n * array) is returned.\n *\n * @param client - client used to look up the skill section\n * @param options - parsed CLI options; first positional arg or `name`\n * is used as the identifier\n * @returns a `CommandResult` containing the serialized\n * `SkillDefinition` JSON or an error message\n */\nexport async function runSkillGet(\n client: SkillGetClient,\n options: CliOptions,\n): Promise<CommandResult> {\n const identifier = options.args[0] ?? options.name;\n if (!identifier) {\n return {\n error: 'skill name or kbid required',\n exitCode: 1,\n };\n }\n let content: string | undefined;\n // Try as kbid first when it looks like a hex hash.\n if (/^[0-9a-f]{16,}$/i.test(identifier)) {\n const sections = await client.readSections([identifier]);\n if (sections.length > 0) {\n content = sections[0]?.content;\n }\n }\n // If not found by kbid, try by name.\n if (content === undefined) {\n const records = await client.listByType('skill');\n const match = records.filter((r) => r.title === identifier).pop();\n if (match) {\n content = match.content;\n }\n }\n if (content === undefined) {\n return {\n error: `skill not found: ${identifier}`,\n exitCode: 1,\n };\n }\n const skill = parseSkillContent(content);\n return {\n output: JSON.stringify(skill, null, 2),\n exitCode: 0,\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\n\n/**\n * Minimal client interface required by `runSkillDelete`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface SkillDeleteClient {\n /**\n * Removes a section from the knowledge base.\n *\n * @param kbid - knowledge-base identifier of the section to remove\n * @returns result indicating whether the section was found and removed\n */\n removeSection(kbid: string): Promise<{ removed: boolean }>;\n}\n\n/**\n * Deletes a skill section from the knowledge base by its kbid.\n *\n * The kbid must be supplied as the first positional argument. Returns\n * an error result if it is missing.\n *\n * @param client - client used to remove the skill section\n * @param options - parsed CLI options; `args[0]` is the kbid\n * @returns a `CommandResult` with the kbid and removal status\n */\nexport async function runSkillDelete(\n client: SkillDeleteClient,\n options: CliOptions,\n): Promise<CommandResult> {\n const kbid = options.args[0];\n if (!kbid) {\n return { error: 'kbid is required', exitCode: 1 };\n }\n const result = await client.removeSection(kbid);\n return {\n output: JSON.stringify(\n { kbid, removed: result.removed },\n null,\n 2,\n ),\n exitCode: 0,\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\nimport type { AddSectionResult } from '../../worker-client/typings/add-section-result.model.ts';\n\n/**\n * Minimal client interface required by `runAgentCreate`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface AgentCreateClient {\n /**\n * Ingests a content section into the knowledge base.\n *\n * @param params - section type label, raw content, and optional\n * metadata\n * @returns result object containing the assigned knowledge-base\n * identifier\n */\n addSection(params: {\n readonly sectionType: string;\n readonly content: string;\n readonly title?: string;\n readonly description?: string;\n }): Promise<AddSectionResult>;\n\n /**\n * Groups a set of sections under a named document.\n *\n * @param title - human-readable document title\n * @param kbids - identifiers of the sections to group\n * @param docType - application-level document type tag; omit or\n * pass an empty string for untagged documents\n * @returns the assigned document identifier\n */\n groupSections(\n title: string,\n kbids: string[],\n docType?: string,\n ): Promise<string>;\n\n /**\n * Retrieves one or more sections by their identifiers.\n *\n * @param kbids - list of knowledge-base identifiers to fetch\n * @returns sections found; missing kbids are omitted from the result\n */\n readSections(kbids: string[]): Promise<{ kbid: string }[]>;\n}\n\n/**\n * Creates a new agent in the knowledge base.\n *\n * Validates `--name` and `--persona` options, verifies that all\n * referenced skill kbids exist, stores agent metadata as a JSON\n * section, and groups all sections under a single document.\n *\n * @param client - agent create client to delegate operations to\n * @param options - parsed CLI options providing `name`, `persona`,\n * optional `description`, and optional `skills` kbid list\n * @returns a `CommandResult` with serialised creation info or an\n * error message and a non-zero exit code\n */\nexport async function runAgentCreate(\n client: AgentCreateClient,\n options: CliOptions,\n): Promise<CommandResult> {\n const name = options.name;\n if (!name) {\n return { error: '--name is required', exitCode: 1 };\n }\n const persona = options.persona;\n if (!persona) {\n return { error: '--persona is required', exitCode: 1 };\n }\n const skills = options.skills ?? [];\n\n if (skills.length > 0) {\n const sections = await client.readSections(skills);\n const found = new Set(sections.map((s) => s.kbid));\n const missing = skills.filter((k) => !found.has(k));\n if (missing.length > 0) {\n return {\n error: `skill not found: ${missing.join(', ')}`,\n exitCode: 1,\n };\n }\n }\n\n const metadata = JSON.stringify({\n name,\n description: options.description ?? '',\n persona,\n });\n\n const metaResult = await client.addSection({\n sectionType: 'text',\n content: metadata,\n title: name,\n description: options.description,\n });\n\n const allKbids = [metaResult.kbid, ...skills];\n const docid = await client.groupSections(name, allKbids, 'agent');\n\n return {\n output: JSON.stringify(\n { docid, name, skillCount: skills.length },\n null,\n 2,\n ),\n exitCode: 0,\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\n\n/** A document summary as returned by `listDocumentsByType`. */\ninterface DocumentSummary {\n /** Unique document identifier. */\n readonly docid: string;\n /** Human-readable document title used as the agent name. */\n readonly title: string;\n /** Ordered list of section references for this document. */\n readonly sections: readonly { kbid: string; position: number }[];\n}\n\n/**\n * Minimal client interface required by `runAgentList`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface AgentListClient {\n /**\n * Retrieves all documents whose type name matches the given string.\n *\n * @param docType - the application-level document type to filter by\n * @returns all document summaries with a matching type name\n */\n listDocumentsByType(docType: string): Promise<DocumentSummary[]>;\n}\n\n/**\n * Lists all agents stored in the knowledge base.\n *\n * Retrieves all documents with `doc_type: 'agent'` and returns a\n * summary list. The `skillCount` for each agent is\n * `Math.max(0, sections.length - 1)` because the first section\n * always holds the agent's metadata JSON rather than a skill\n * reference.\n *\n * @param client - agent list client to delegate retrieval to\n * @param _options - parsed CLI options (unused; reserved for future\n * filtering flags)\n * @returns a `CommandResult` with serialised agent summary list\n */\nexport async function runAgentList(\n client: AgentListClient,\n _options: CliOptions,\n): Promise<CommandResult> {\n const docs = await client.listDocumentsByType('agent');\n const items = docs.map((d) => ({\n docid: d.docid,\n name: d.title,\n skillCount: Math.max(0, d.sections.length - 1),\n }));\n return {\n output: JSON.stringify(items, null, 2),\n exitCode: 0,\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\n\n/** A document section reference as returned by `retrieveDocument`. */\ninterface DocumentSection {\n /** Knowledge-base identifier of the section. */\n readonly kbid: string;\n /** Zero-based position of the section within the document. */\n readonly position: number;\n}\n\n/** A document record as returned by `retrieveDocument`. */\ninterface AgentDocument {\n /** Unique document identifier. */\n readonly docid: string;\n /** Human-readable document title used as agent name fallback. */\n readonly title: string;\n /** Ordered list of section references. */\n readonly sections: DocumentSection[];\n}\n\n/** A section record as returned by `readSections`. */\ninterface SectionRecord {\n /** Knowledge-base identifier of the section. */\n readonly kbid: string;\n /** Raw text content stored in the section. */\n readonly content: string;\n}\n\n/**\n * Minimal client interface required by `runAgentGet`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface AgentGetClient {\n /**\n * Retrieves a full document record including its ordered sections.\n *\n * @param docid - identifier of the document to retrieve\n * @returns the document record\n */\n retrieveDocument(docid: string): Promise<unknown>;\n\n /**\n * Retrieves one or more sections by their identifiers.\n *\n * @param kbids - list of knowledge-base identifiers to fetch\n * @returns sections found; missing kbids are omitted from the result\n */\n readSections(kbids: string[]): Promise<SectionRecord[]>;\n}\n\n/**\n * Reads agent metadata from the first section's JSON content.\n * Falls back to `fallbackName` when the section is absent or the\n * content cannot be parsed.\n */\nasync function readAgentMeta(\n client: AgentGetClient,\n metaKbid: string,\n fallbackName: string,\n): Promise<{ name: string; description: string; persona: string }> {\n const sections = await client.readSections([metaKbid]);\n const first = sections.at(0);\n if (!first) {\n return { name: fallbackName, description: '', persona: '' };\n }\n try {\n const meta = JSON.parse(first.content) as Record<string, unknown>;\n return {\n name:\n typeof meta['name'] === 'string'\n ? meta['name']\n : fallbackName,\n description:\n typeof meta['description'] === 'string'\n ? meta['description']\n : '',\n persona:\n typeof meta['persona'] === 'string' ? meta['persona'] : '',\n };\n } catch {\n return { name: fallbackName, description: '', persona: '' };\n }\n}\n\n/**\n * Resolves skill names by reading each skill section's JSON content.\n * Returns `null` for any reference whose section no longer exists\n * (dangling reference).\n */\nasync function resolveSkills(\n client: AgentGetClient,\n skillRefs: DocumentSection[],\n): Promise<{ kbid: string; name: string | null; position: number }[]> {\n if (skillRefs.length === 0) {\n return [];\n }\n const kbids = skillRefs.map((r) => r.kbid);\n const sections = await client.readSections(kbids);\n const sectionMap = new Map(sections.map((s) => [s.kbid, s]));\n return skillRefs.map((ref) => {\n const sec = sectionMap.get(ref.kbid);\n if (!sec) {\n return { kbid: ref.kbid, name: null, position: ref.position };\n }\n try {\n const parsed = JSON.parse(sec.content) as Record<\n string,\n unknown\n >;\n const skillName =\n typeof parsed['name'] === 'string' ? parsed['name'] : null;\n return {\n kbid: ref.kbid,\n name: skillName,\n position: ref.position,\n };\n } catch {\n return { kbid: ref.kbid, name: null, position: ref.position };\n }\n });\n}\n\n/**\n * Retrieves a full agent definition from the knowledge base.\n *\n * Reads the agent document identified by `options.args[0]`, extracts\n * metadata (name, description, persona) from the first section, and\n * resolves skill names from the remaining sections. Dangling skill\n * references appear with `name: null`.\n *\n * @param client - agent get client to delegate retrieval to\n * @param options - parsed CLI options; `args[0]` must be the docid\n * @returns a `CommandResult` with serialised agent definition or an\n * error message and a non-zero exit code\n */\nexport async function runAgentGet(\n client: AgentGetClient,\n options: CliOptions,\n): Promise<CommandResult> {\n const docid = options.args[0];\n if (!docid) {\n return { error: 'docid is required', exitCode: 1 };\n }\n\n const doc = (await client.retrieveDocument(docid)) as AgentDocument;\n const metaKbid = doc.sections[0]?.kbid;\n const skillRefs = doc.sections.slice(1);\n\n const { name, description, persona } = metaKbid\n ? await readAgentMeta(client, metaKbid, doc.title)\n : { name: doc.title, description: '', persona: '' };\n\n const skills = await resolveSkills(client, skillRefs);\n\n return {\n output: JSON.stringify(\n { docid, name, description, persona, skills },\n null,\n 2,\n ),\n exitCode: 0,\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\n\n/**\n * Minimal client interface required by `runAgentDelete`.\n *\n * Decouples the CLI function from the concrete `WorkerClient`\n * implementation, making it straightforward to test with mocks.\n */\nexport interface AgentDeleteClient {\n /**\n * Removes the document grouping for the given document.\n *\n * The sections themselves are not deleted; only the grouping\n * record is removed.\n *\n * @param docid - identifier of the document grouping to remove\n */\n removeGrouping(docid: string): Promise<void>;\n}\n\n/**\n * Deletes an agent from the knowledge base.\n *\n * Removes the document grouping identified by `options.args[0]`.\n * Skill sections referenced by the agent are not deleted; only\n * the grouping record is removed.\n *\n * @param client - agent delete client to delegate removal to\n * @param options - parsed CLI options; `args[0]` must be the docid\n * @returns a `CommandResult` confirming removal or an error message\n * with a non-zero exit code\n */\nexport async function runAgentDelete(\n client: AgentDeleteClient,\n options: CliOptions,\n): Promise<CommandResult> {\n const docid = options.args[0];\n if (!docid) {\n return { error: 'docid is required', exitCode: 1 };\n }\n await client.removeGrouping(docid);\n return {\n output: JSON.stringify({ docid, removed: true }, null, 2),\n exitCode: 0,\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { ImportResult } from '../../worker-client/typings/import-result.model.ts';\n\n/**\n * Minimal client interface required by `runImport`.\n */\nexport interface ImportClient {\n /**\n * Imports an exported database from the given directory.\n *\n * @param params - source path and dry-run flag\n * @returns import report with counts and timing\n */\n import(params: {\n from: string;\n dryRun: boolean;\n }): Promise<ImportResult>;\n}\n\n/**\n * Imports an exported knowledge-base from the path specified by\n * `--from`, delegating to the worker client.\n *\n * @param client - import client to delegate to\n * @param options - parsed CLI options with `from` path\n * @returns the import result with section/document counts\n * @throws when `--from` is not provided\n */\nexport async function runImport(\n client: ImportClient,\n options: CliOptions,\n): Promise<ImportResult> {\n const from = options.from;\n if (!from) {\n throw new Error('import requires --from <path>');\n }\n return client.import({\n from,\n dryRun: options.dryRun === true,\n });\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\nimport type { PagedSearchDisplay } from '../typings/search-display.model.ts';\nimport type { LearnIO } from './run-learn.function.ts';\nimport type { SearchClient } from './run-search.function.ts';\nimport type { LearnClient } from './run-learn.function.ts';\nimport type { UnlearnClient } from './run-unlearn.function.ts';\nimport type { ContentClient } from './run-content.function.ts';\nimport type { CheckClient } from './run-check.function.ts';\nimport type { GcClient } from './run-gc.function.ts';\nimport type { RebuildClient } from './run-rebuild.function.ts';\nimport type { StatusClient } from './run-status.function.ts';\nimport type { DbMigrateClient } from './run-db-migrate.function.ts';\nimport type { SkillLearnClient } from './run-skill-learn.function.ts';\nimport type { SkillListClient } from './run-skill-list.function.ts';\nimport type { SkillGetClient } from './run-skill-get.function.ts';\nimport type { SkillDeleteClient } from './run-skill-delete.function.ts';\nimport type { AgentCreateClient } from './run-agent-create.function.ts';\nimport type { AgentListClient } from './run-agent-list.function.ts';\nimport type { AgentGetClient } from './run-agent-get.function.ts';\nimport type { AgentDeleteClient } from './run-agent-delete.function.ts';\nimport type { RecallClient } from './run-recall.function.ts';\nimport type { ExportClient } from './run-export.function.ts';\nimport type { ImportClient } from './run-import.function.ts';\nimport { runSearch } from './run-search.function.ts';\nimport { runLearn } from './run-learn.function.ts';\nimport { runUnlearn } from './run-unlearn.function.ts';\nimport { runContent } from './run-content.function.ts';\nimport { runCheck } from './run-check.function.ts';\nimport { runGc } from './run-gc.function.ts';\nimport { runRebuild } from './run-rebuild.function.ts';\nimport { runStatus } from './run-status.function.ts';\nimport { runDbInit } from './run-db-init.function.ts';\nimport { runInit } from './run-init.function.ts';\nimport { runDbMigrate } from './run-db-migrate.function.ts';\nimport { runSkillLearn } from './run-skill-learn.function.ts';\nimport { runSkillList } from './run-skill-list.function.ts';\nimport { runSkillGet } from './run-skill-get.function.ts';\nimport { runSkillDelete } from './run-skill-delete.function.ts';\nimport { runAgentCreate } from './run-agent-create.function.ts';\nimport { runAgentList } from './run-agent-list.function.ts';\nimport { runAgentGet } from './run-agent-get.function.ts';\nimport { runAgentDelete } from './run-agent-delete.function.ts';\nimport { runRecall } from './run-recall.function.ts';\nimport { runExport } from './run-export.function.ts';\nimport { runImport } from './run-import.function.ts';\nimport { formatOutput } from './format-output.function.ts';\nimport { errorToMessage } from './error-to-message.function.ts';\n\n/**\n * Intersection of all data-command client interfaces.\n *\n * Each run* function defines its own minimal interface; this\n * intersection combines them so `dispatchCommand` can route\n * to any command handler with full type safety.\n */\nexport type DispatchClient = SearchClient &\n LearnClient &\n UnlearnClient &\n ContentClient &\n CheckClient &\n GcClient &\n RebuildClient &\n StatusClient &\n DbMigrateClient &\n SkillLearnClient &\n SkillListClient &\n SkillGetClient &\n SkillDeleteClient &\n AgentCreateClient &\n AgentListClient &\n AgentGetClient &\n AgentDeleteClient &\n RecallClient &\n ExportClient &\n ImportClient;\n\n/**\n * Routes a parsed CLI command to the appropriate handler and\n * returns a `CommandResult` without touching process globals.\n *\n * @param client - worker client covering all data commands\n * @param options - parsed CLI options with command and args\n * @param io - optional injectable I/O for learn stdin\n */\nexport async function dispatchCommand(\n client: DispatchClient,\n options: CliOptions,\n io?: LearnIO,\n): Promise<CommandResult> {\n switch (options.command) {\n case 'learn':\n return handleLearn(client, options, io);\n case 'unlearn':\n return handleUnlearn(client, options);\n case 'search':\n return handleSearch(client, options);\n case 'recall':\n return handleRecall(client, options);\n case 'content':\n return handleContent(client, options);\n case 'check':\n return handleCheck(client, options);\n case 'gc':\n return handleGc(client, options);\n case 'rebuild':\n return handleRebuild(client, options);\n case 'status':\n return handleStatus(client, options);\n case 'export':\n return handleExport(client, options);\n case 'import':\n return handleImport(client, options);\n case 'db-init':\n return handleDbInit(options);\n case 'db-migrate':\n return handleDbMigrate(client, options);\n case 'skill-learn': {\n const result = await runSkillLearn(client, options);\n return result;\n }\n case 'skill-list': {\n const result = await runSkillList(client, options);\n return result;\n }\n case 'skill-get': {\n const result = await runSkillGet(client, options);\n return result;\n }\n case 'skill-delete': {\n const result = await runSkillDelete(client, options);\n return result;\n }\n case 'agent-create': {\n const result = await runAgentCreate(client, options);\n return result;\n }\n case 'agent-list': {\n const result = await runAgentList(client, options);\n return result;\n }\n case 'agent-get': {\n const result = await runAgentGet(client, options);\n return result;\n }\n case 'agent-delete': {\n const result = await runAgentDelete(client, options);\n return result;\n }\n default:\n return {\n error: `unknown command: ${options.command}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleLearn(\n client: DispatchClient,\n options: CliOptions,\n io?: LearnIO,\n): Promise<CommandResult> {\n try {\n const results = await runLearn(client, options, io);\n return {\n output: JSON.stringify(results, null, 2),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `learn failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleUnlearn(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const results = await runUnlearn(client, options);\n return {\n output: JSON.stringify(results, null, 2),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `unlearn failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleSearch(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const results = await runSearch(client, options);\n if (options.content) {\n await hydrateSearchPreviews(client, results);\n }\n return {\n output: formatOutput(results, options.format),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `search failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleRecall(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const result = await runRecall(client, options);\n if ('error' in result) {\n return {\n error: `error: ${result.error}`,\n exitCode: 1,\n };\n }\n return {\n output: JSON.stringify(result, null, 2),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `recall failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleExport(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const result = await runExport(client, options);\n return {\n output: JSON.stringify(result, null, 2),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `export failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleImport(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const result = await runImport(client, options);\n return {\n output: JSON.stringify(result, null, 2),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `import failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleContent(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const result = await runContent(client, options);\n return {\n output: JSON.stringify(result, null, 2),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `content failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleCheck(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const result = await runCheck(client, options);\n return {\n output: JSON.stringify(result, null, 2),\n exitCode: result.ok ? 0 : 1,\n };\n } catch (err) {\n return {\n error: `check failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleGc(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const result = await runGc(client, options);\n return {\n output: JSON.stringify(result, null, 2),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `gc failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleRebuild(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const result = await runRebuild(client, options);\n return {\n output: JSON.stringify(result, null, 2),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `rebuild failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleStatus(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const result = await runStatus(client, options);\n return {\n output: JSON.stringify(result, null, 2),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `status failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nfunction handleDbInit(options: CliOptions): CommandResult {\n return runDbInit(options, runInit);\n}\n\nasync function handleDbMigrate(\n client: DispatchClient,\n options: CliOptions,\n): Promise<CommandResult> {\n try {\n const result = await runDbMigrate(client, options);\n return {\n output: JSON.stringify(result, null, 2),\n exitCode: 0,\n };\n } catch (err) {\n return {\n error: `db-migrate failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\n/**\n * Hydrates each result's `preview` field with the actual section\n * content fetched from the client.\n *\n * Failures for individual results are caught and suppressed so that\n * one unavailable section does not prevent other previews from\n * being returned.\n *\n * @param client - content client used to fetch section text\n * @param results - mutable search display records to hydrate\n */\nasync function hydrateSearchPreviews(\n client: ContentClient,\n paged: PagedSearchDisplay,\n): Promise<void> {\n await Promise.all(\n paged.items.map(async (result) => {\n try {\n const contentResult = await client.content([result.kbid]);\n result.preview = contentResult.data;\n } catch {\n // Leave preview as empty string on failure.\n }\n }),\n );\n}\n", "/** Current package version, kept in sync with package.json. */\nexport const VERSION = '0.4.0';\n", "import { VERSION } from '../../version/index.ts';\n\n/**\n * The set of all recognised top-level command names,\n * including group commands (`db`, `skill`, `agent`, `worker`).\n */\nconst KNOWN_COMMANDS = new Set([\n 'learn',\n 'unlearn',\n 'search',\n 'recall',\n 'content',\n 'check',\n 'gc',\n 'rebuild',\n 'status',\n 'export',\n 'mcp',\n 'db',\n 'skill',\n 'agent',\n 'worker',\n]);\n\n/** Subcommands available under each group command. */\nconst GROUP_SUBCOMMANDS: Readonly<\n Record<string, readonly (readonly [string, string])[]>\n> = {\n db: [\n ['init', 'Initialise a new .kbdb directory'],\n ['migrate', 'Migrate database to current format'],\n ],\n skill: [\n ['learn', 'Create a new skill definition'],\n ['list', 'List all skills'],\n ['get', 'Retrieve a skill by name or kbid'],\n ['delete', 'Remove a skill'],\n ],\n agent: [\n ['create', 'Create an agent with skill refs'],\n ['list', 'List all agents'],\n ['get', 'Retrieve an agent by docid'],\n ['delete', 'Remove an agent'],\n ],\n worker: [\n ['stop', 'Stop the worker daemon'],\n ['restart', 'Restart the worker daemon'],\n ],\n};\n\n/**\n * Returns `true` when `cmd` is a recognised command name.\n *\n * Accepts both simple top-level names (`'learn'`, `'db'`)\n * and the hyphenated compound form produced by `parseArgs`\n * when a group + subcommand precedes `--help`\n * (e.g. `'db-init'`, `'skill-learn'`).\n */\nexport function isKnownCommand(cmd: string): boolean {\n if (KNOWN_COMMANDS.has(cmd)) {\n return true;\n }\n // Check hyphenated compound form: 'db-init', 'skill-learn'\n const dashIdx = cmd.indexOf('-');\n if (dashIdx < 0) {\n return false;\n }\n const group = cmd.slice(0, dashIdx);\n return group in GROUP_SUBCOMMANDS;\n}\n\n/**\n * Generates contextual help text for the `kbdb` CLI.\n *\n * Three levels of detail are produced depending on\n * how many command tokens are supplied:\n *\n * - No arguments: global help listing all commands.\n * - `command` only: command-level help. When `command`\n * is a hyphenated compound (`'db-init'`), it is split\n * into group + subcommand automatically. Group\n * commands show a subcommand listing; leaf commands\n * show detailed help; unknown commands show an error\n * prefix followed by global help.\n * - `command` + `subcommand`: detailed help for that\n * specific subcommand (falls back to group help when\n * the subcommand is not recognised).\n *\n * @param command - optional top-level command token,\n * or a hyphenated compound such as `'db-init'`\n * @param subcommand - optional subcommand token\n */\nexport function generateHelp(\n command?: string,\n subcommand?: string,\n): string {\n if (!command) {\n return generateGlobalHelp();\n }\n // Handle compound form produced by parseArgs:\n // 'db-init' -> group='db', sub='init'\n if (!subcommand && command.includes('-')) {\n const dashIdx = command.indexOf('-');\n const group = command.slice(0, dashIdx);\n const sub = command.slice(dashIdx + 1);\n if (group in GROUP_SUBCOMMANDS) {\n return generateSubcommandHelp(group, sub);\n }\n }\n if (subcommand) {\n return generateSubcommandHelp(command, subcommand);\n }\n return generateCommandHelp(command);\n}\n\n// ---------------------------------------------------------------------------\n// Level 1: Global help\n// ---------------------------------------------------------------------------\n\nfunction generateGlobalHelp(): string {\n return (\n `kbdb v${VERSION} - File-based knowledge base` +\n ` database for AI agents\\n` +\n `\\n` +\n `Usage: kbdb [options]\\n` +\n ` kbdb <command> [options] ...[parameters]\\n` +\n ` kbdb <command> <subcommand> [options]` +\n ` ...[params]\\n` +\n `\\n` +\n `Knowledge Base:\\n` +\n ` learn Import content from` +\n ` files/stdin\\n` +\n ` unlearn Remove sections by kbid\\n` +\n ` search Query the knowledge base\\n` +\n ` recall Retrieve section context` +\n ` by kbid\\n` +\n ` content Compose rendered content` +\n ` from ids\\n` +\n `\\n` +\n `Database:\\n` +\n ` db init Initialise a new .kbdb` +\n ` directory\\n` +\n ` db migrate Migrate database to current` +\n ` format\\n` +\n `\\n` +\n `Maintenance:\\n` +\n ` check Verify knowledge base` +\n ` integrity\\n` +\n ` gc Garbage collect unreferenced\\n` +\n ` sections\\n` +\n ` rebuild Reconstruct all index` +\n ` files\\n` +\n ` status Show database status\\n` +\n ` export Snapshot database for` +\n ` backup\\n` +\n `\\n` +\n `Skills:\\n` +\n ` skill learn Create a new skill` +\n ` definition\\n` +\n ` skill list List all skills\\n` +\n ` skill get Retrieve a skill by name` +\n ` or kbid\\n` +\n ` skill delete Remove a skill\\n` +\n `\\n` +\n `Agents:\\n` +\n ` agent create Create an agent with skill` +\n ` refs\\n` +\n ` agent list List all agents\\n` +\n ` agent get Retrieve an agent by docid\\n` +\n ` agent delete Remove an agent\\n` +\n `\\n` +\n `Worker:\\n` +\n ` worker stop Stop the worker daemon\\n` +\n ` worker restart Restart the worker daemon\\n` +\n `\\n` +\n `Server:\\n` +\n ` mcp Start MCP server mode` +\n ` (stdio)\\n` +\n `\\n` +\n `Global Options:\\n` +\n ` -h, --help Show this help message\\n` +\n ` -v, --version Show version information\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n ` --format <fmt> Output format` +\n ` (json|text|mcp)\\n` +\n `\\n` +\n `Run \"kbdb <command> --help\" for detailed` +\n ` information.\\n`\n );\n}\n\n// ---------------------------------------------------------------------------\n// Level 2: Command help\n// ---------------------------------------------------------------------------\n\nfunction generateCommandHelp(command: string): string {\n if (command in GROUP_SUBCOMMANDS) {\n return generateGroupHelp(command);\n }\n const leaf = LEAF_HELP[command];\n if (leaf) {\n return leaf;\n }\n return `Unknown command: ${command}\\n\\n` + generateGlobalHelp();\n}\n\nfunction generateGroupHelp(group: string): string {\n const subs = GROUP_SUBCOMMANDS[group] ?? [];\n const subLines = subs\n .map(([name, desc]) => ` ${name.padEnd(20)}${desc}`)\n .join('\\n');\n const desc = GROUP_DESCRIPTIONS[group] ?? group;\n return (\n `kbdb ${group} - ${desc}\\n` +\n `\\n` +\n `Usage: kbdb ${group} <subcommand> [options]\\n` +\n `\\n` +\n `Subcommands:\\n` +\n `${subLines}\\n` +\n `\\n` +\n `Global Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n ` -h, --help Show this help message\\n` +\n `\\n` +\n `Run \"kbdb ${group} <subcommand> --help\"` +\n ` for details.\\n`\n );\n}\n\n/** One-line description for each group command. */\nconst GROUP_DESCRIPTIONS: Readonly<Record<string, string>> = {\n db: 'Database management',\n skill: 'Skill management',\n agent: 'Agent management',\n worker: 'Worker daemon management',\n};\n\n// ---------------------------------------------------------------------------\n// Leaf command help texts\n// ---------------------------------------------------------------------------\n\nconst LEAF_HELP: Readonly<Record<string, string>> = {\n learn:\n `kbdb learn - Import content from files or stdin\\n` +\n `\\n` +\n `Usage: kbdb learn [options] <path | ->...\\n` +\n `\\n` +\n `Arguments:\\n` +\n ` <path | -> File path, directory,` +\n ` or - for stdin\\n` +\n `\\n` +\n `Options:\\n` +\n ` --title <title> Section title\\n` +\n ` --description <d> Section description\\n` +\n ` --docid <docid> Document ID to group` +\n ` under\\n` +\n ` --tags <t,...> Comma-separated tags\\n` +\n ` --replace Supersede existing section` +\n ` by source key\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON array of { kbid, path, size, skipped,\\n` +\n ` superseded, warnings,` +\n ` near_duplicates }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb learn README.md\\n` +\n ` kbdb learn ./docs/\\n` +\n ` kbdb learn --tags auth,api --replace doc.md\\n` +\n ` cat notes.txt | kbdb learn -\\n`,\n\n unlearn:\n `kbdb unlearn - Remove sections by kbid\\n` +\n `\\n` +\n `Usage: kbdb unlearn [options] <kbid>...\\n` +\n `\\n` +\n `Arguments:\\n` +\n ` <kbid> 26-character knowledge` +\n ` base identifier\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON array of { kbid, removed }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb unlearn abcdef1234567890abcdef1234\\n` +\n ` kbdb unlearn id1 id2 id3\\n`,\n\n search:\n `kbdb search - Query the knowledge base\\n` +\n `\\n` +\n `Usage: kbdb search [options] <query>...\\n` +\n `\\n` +\n `Arguments:\\n` +\n ` <query> One or more query terms\\n` +\n `\\n` +\n `Options:\\n` +\n ` --mode <mode> Result granularity` +\n ` (sections|documents|stats)\\n` +\n ` --limit <n> Max results (default: 20)\\n` +\n ` --format <fmt> Output format` +\n ` (json|text|mcp)\\n` +\n ` --content, -c Hydrate results with` +\n ` section content\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON array of { kbid, score, preview,` +\n ` matches }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb search \"machine learning\"\\n` +\n ` kbdb search --limit 5 --format text query\\n` +\n ` kbdb search --mode documents --content term\\n`,\n\n recall:\n `kbdb recall - Retrieve section context by kbid\\n` +\n `\\n` +\n `Usage: kbdb recall [options] <kbid>...\\n` +\n `\\n` +\n `Arguments:\\n` +\n ` <kbid> 26-character knowledge` +\n ` base identifier\\n` +\n `\\n` +\n `Options:\\n` +\n ` --depth <n>, -d Expansion depth (0-3,` +\n ` default: 0)\\n` +\n ` --tags <t,...> Filter by tags\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON RecallResult or RecallResult[]\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb recall abcdef1234567890abcdef1234\\n` +\n ` kbdb recall kbid1 --depth 2\\n`,\n\n content:\n `kbdb content - Compose rendered content from ids\\n` +\n `\\n` +\n `Usage: kbdb content [options] <id>...\\n` +\n `\\n` +\n `Arguments:\\n` +\n ` <id> kbid or docid identifier\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON { type, data, total }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb content abcdef1234567890abcdef1234\\n` +\n ` kbdb content id1 id2\\n`,\n\n check:\n `kbdb check - Verify knowledge base integrity\\n` +\n `\\n` +\n `Usage: kbdb check [options]\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON { ok, errors }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb check\\n` +\n ` kbdb check --db /path/to/project\\n`,\n\n gc:\n `kbdb gc - Garbage collect unreferenced sections\\n` +\n `\\n` +\n `Usage: kbdb gc [options]\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON { removed_sections, removed_bytes }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb gc\\n` +\n ` kbdb gc --db /path/to/project\\n`,\n\n rebuild:\n `kbdb rebuild - Reconstruct all index files\\n` +\n `\\n` +\n `Usage: kbdb rebuild [options]\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON { sections_reindexed, terms_indexed }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb rebuild\\n` +\n ` kbdb rebuild --db /path/to/project\\n`,\n\n status:\n `kbdb status - Show database status\\n` +\n `\\n` +\n `Usage: kbdb status [options]\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON database status object\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb status\\n` +\n ` kbdb status --db /path/to/project\\n`,\n\n export:\n `kbdb export - Snapshot database for backup\\n` +\n `\\n` +\n `Usage: kbdb export [options] [<path>]\\n` +\n `\\n` +\n `Arguments:\\n` +\n ` <path> Output directory path\\n` +\n ` (default: ./kbdb-export/)\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON { path, sections_exported,` +\n ` documents_exported }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb export\\n` +\n ` kbdb export ./my-backup\\n` +\n ` kbdb export --db /path/to/project\\n`,\n\n mcp:\n `kbdb mcp - Start MCP server mode (stdio)\\n` +\n `\\n` +\n `Usage: kbdb mcp [options]\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Environment:\\n` +\n ` KBDB_DB_DIR Fallback database path\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb mcp --db /path/to/project\\n` +\n ` KBDB_DB_DIR=/path/to/project kbdb mcp\\n`,\n};\n\n// ---------------------------------------------------------------------------\n// Level 3: Subcommand help\n// ---------------------------------------------------------------------------\n\n/**\n * Detailed help texts keyed by `\"group-subcommand\"`.\n * Falls back to group help when the key is absent.\n */\nconst SUBCOMMAND_HELP: Readonly<Record<string, string>> = {\n 'db-init':\n `kbdb db init - Initialise a new .kbdb directory\\n` +\n `\\n` +\n `Usage: kbdb db init [options]\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to create .kbdb in\\n` +\n ` (default: current directory)\\n` +\n ` -h, --help Show this help message\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON { path, created }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb db init\\n` +\n ` kbdb db init --db /path/to/project\\n`,\n\n 'db-migrate':\n `kbdb db migrate - Migrate database to current` +\n ` format\\n` +\n `\\n` +\n `Usage: kbdb db migrate [options]\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path containing .kbdb\\n` +\n ` (default: current directory)\\n` +\n ` -h, --help Show this help message\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON MigrateResult or \"already up to date\"\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb db migrate\\n` +\n ` kbdb db migrate --db /path/to/project\\n`,\n\n 'skill-learn':\n `kbdb skill learn - Create a new skill definition\\n` +\n `\\n` +\n `Usage: kbdb skill learn [options]` +\n ` --name <n> --body <file|->\\n` +\n `\\n` +\n `Options:\\n` +\n ` --name <name> Skill name (required)\\n` +\n ` --description <d> Skill description\\n` +\n ` --body <file|-> Template body file or` +\n ` stdin (required)\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON { kbid, name, arguments }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb skill learn --name summarize` +\n ` --body prompt.txt\\n` +\n ` cat body.txt | kbdb skill learn` +\n ` --name my-skill --body -\\n`,\n\n 'skill-list':\n `kbdb skill list - List all skills\\n` +\n `\\n` +\n `Usage: kbdb skill list [options]\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON array of { kbid, name, description,` +\n ` argumentCount }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb skill list\\n` +\n ` kbdb skill list --db /path/to/project\\n`,\n\n 'skill-get':\n `kbdb skill get - Retrieve a skill by name` +\n ` or kbid\\n` +\n `\\n` +\n `Usage: kbdb skill get [options] <name-or-kbid>\\n` +\n `\\n` +\n `Arguments:\\n` +\n ` <name-or-kbid> Skill name or 26-char` +\n ` kbid\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON SkillDefinition object\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb skill get summarize-document\\n` +\n ` kbdb skill get abcdef1234567890abcdef1234\\n`,\n\n 'skill-delete':\n `kbdb skill delete - Remove a skill\\n` +\n `\\n` +\n `Usage: kbdb skill delete [options] <kbid>\\n` +\n `\\n` +\n `Arguments:\\n` +\n ` <kbid> 26-character kbid of the` +\n ` skill to remove\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON { kbid, removed }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb skill delete abcdef1234567890abcdef1234\\n`,\n\n 'agent-create':\n `kbdb agent create - Create an agent with skill` +\n ` refs\\n` +\n `\\n` +\n `Usage: kbdb agent create [options] --name <n>` +\n ` --persona <file|-> --skills <kbid,...>\\n` +\n `\\n` +\n `Options:\\n` +\n ` --name <name> Agent name (required)\\n` +\n ` --description <d> Agent description\\n` +\n ` --persona <file|-> Persona file or stdin` +\n ` (required)\\n` +\n ` --skills <kbid,...> Comma-separated skill` +\n ` kbids (required)\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON { docid, name, skills }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb agent create --name code-reviewer` +\n ` --persona ./p.txt --skills abc123\\n` +\n ` cat persona.txt | kbdb agent create` +\n ` --name my-agent --persona - --skills abc123\\n`,\n\n 'agent-list':\n `kbdb agent list - List all agents\\n` +\n `\\n` +\n `Usage: kbdb agent list [options]\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON array of { docid, name, description,` +\n ` skillCount }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb agent list\\n` +\n ` kbdb agent list --db /path/to/project\\n`,\n\n 'agent-get':\n `kbdb agent get - Retrieve an agent by docid\\n` +\n `\\n` +\n `Usage: kbdb agent get [options] <docid>\\n` +\n `\\n` +\n `Arguments:\\n` +\n ` <docid> Agent document identifier\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON AgentDefinition object with resolved` +\n ` skills\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb agent get agent-code-reviewer\\n`,\n\n 'agent-delete':\n `kbdb agent delete - Remove an agent\\n` +\n `\\n` +\n `Usage: kbdb agent delete [options] <docid>\\n` +\n `\\n` +\n `Arguments:\\n` +\n ` <docid> Agent document identifier\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Output:\\n` +\n ` JSON { docid, removed }\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb agent delete agent-code-reviewer\\n`,\n\n 'worker-stop':\n `kbdb worker stop - Stop the worker daemon\\n` +\n `\\n` +\n `Usage: kbdb worker stop [options]\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb worker stop\\n` +\n ` kbdb worker stop --db /path/to/project\\n`,\n\n 'worker-restart':\n `kbdb worker restart - Restart the worker daemon\\n` +\n `\\n` +\n `Usage: kbdb worker restart [options]\\n` +\n `\\n` +\n `Options:\\n` +\n ` --db <path> Path to .kbdb directory\\n` +\n `\\n` +\n `Examples:\\n` +\n ` kbdb worker restart\\n` +\n ` kbdb worker restart --db /path/to/project\\n`,\n};\n\nfunction generateSubcommandHelp(\n command: string,\n subcommand: string,\n): string {\n const key = `${command}-${subcommand}`;\n const text = SUBCOMMAND_HELP[key];\n if (text) {\n return text;\n }\n // Fall back to group help when subcommand is unknown\n return generateCommandHelp(command);\n}\n", "import { connect } from 'node:net';\nimport type { Socket } from 'node:net';\nimport type { SearchParams } from '../typings/search-params.model.ts';\nimport type { PagedSearchResult } from '../typings/search-result.model.ts';\nimport type {\n AddSectionParams,\n Section,\n} from '../typings/section.model.ts';\nimport type { StatusResult } from '../typings/status-result.model.ts';\nimport type { AddSectionResult } from '../typings/add-section-result.model.ts';\nimport type { RemoveSectionResult } from '../typings/remove-section-result.model.ts';\nimport type { ContentResult } from '../typings/content-result.model.ts';\nimport type { IntegrityCheckResult } from '../typings/integrity-check-result.model.ts';\nimport type { GcResult } from '../typings/gc-result.model.ts';\nimport type { RebuildResult } from '../typings/rebuild-result.model.ts';\nimport type { MigrateResult } from '../typings/migrate-result.model.ts';\nimport type { VersionStatus } from '../typings/version-status.model.ts';\nimport type { SectionRecord } from '../../wasm-codec/functions/decode-section-records.function.ts';\nimport type { DocumentManifest } from '../../wasm-codec/functions/decode-document-manifest.function.ts';\nimport type {\n RecallParams,\n RecallResult,\n} from '../typings/recall-result.model.ts';\nimport type { ExportResult } from '../typings/export-result.model.ts';\nimport type { ImportResult } from '../typings/import-result.model.ts';\n\n/** Pending JSON-RPC call awaiting a response from the daemon. */\ninterface PendingCall {\n resolve: (v: unknown) => void;\n reject: (e: Error) => void;\n timer?: ReturnType<typeof setTimeout>;\n}\n\n/** Shape of a JSON-RPC 2.0 error object from the daemon. */\ninterface JsonRpcError {\n readonly code: number;\n readonly message: string;\n}\n\n/** Shape of a JSON-RPC 2.0 response from the daemon. */\ninterface JsonRpcResponse {\n readonly id: number;\n readonly result?: unknown;\n readonly error?: JsonRpcError;\n}\n\n/**\n * IPC client that communicates with the worker daemon over a Unix\n * domain socket (or Windows named pipe) using JSON-RPC 2.0 with\n * newline-delimited message framing.\n *\n * Call `connect()` before any other method and `disconnect()` when\n * done to release the underlying socket.\n */\nexport class WorkerClient {\n /** Underlying socket; `null` when not connected. */\n private socket: Socket | null = null;\n\n /** Monotonically increasing request ID counter. */\n private nextId = 1;\n\n /** Map of outstanding request IDs to their resolve/reject pairs. */\n private readonly pending = new Map<number, PendingCall>();\n\n /** Partial line buffer for split TCP/IPC frames. */\n private buffer = '';\n\n /**\n * @param socketPath - absolute path to the daemon's IPC socket\n * (or Windows named pipe path)\n * @param contextId - 16-character context identifier sent as\n * `ctx` in every JSON-RPC request\n * @param requestTimeoutMs - per-request timeout in ms\n * (0 or undefined disables the timeout)\n */\n constructor(\n private readonly socketPath: string,\n private readonly contextId: string,\n private readonly requestTimeoutMs?: number,\n ) {}\n\n /** Whether the underlying socket is connected. */\n get isConnected(): boolean {\n return this.socket !== null;\n }\n\n /**\n * Establishes the IPC connection to the worker daemon.\n *\n * Retries up to 5 times with exponential backoff on\n * transient errors (`ENOENT`, `ECONNREFUSED`).\n *\n * @throws {Error} if the connection cannot be established\n */\n async connect(): Promise<void> {\n const maxRetries = 5;\n let delay = 50;\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n await this.tryConnect();\n return;\n } catch (err: unknown) {\n const code = (err as NodeJS.ErrnoException).code;\n const retriable =\n code === 'ENOENT' || code === 'ECONNREFUSED';\n if (!retriable || attempt === maxRetries) {\n throw err;\n }\n await new Promise<void>((r) => setTimeout(r, delay));\n delay = Math.min(delay * 2, 1000);\n }\n }\n }\n\n /** Destroys the IPC socket and clears the connection state. */\n disconnect(): void {\n if (this.socket) {\n this.socket.destroy();\n this.socket = null;\n }\n }\n\n /**\n * Single connection attempt with keepalive and\n * post-connect failure handlers.\n */\n private async tryConnect(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const sock = connect(this.socketPath, () => {\n sock.removeListener('error', reject);\n sock.setKeepAlive(true, 30_000);\n sock.on('error', (err: Error) => {\n this.handleSocketFailure(err);\n });\n sock.on('close', () => {\n if (this.pending.size > 0) {\n this.handleSocketFailure(\n new Error('connection closed'),\n );\n }\n this.socket = null;\n });\n this.socket = sock;\n resolve();\n });\n sock.on('error', reject);\n sock.on('data', (chunk: Buffer) => {\n this.handleData(chunk.toString());\n });\n });\n }\n\n /**\n * Rejects all pending calls and marks the client as\n * disconnected.\n */\n private handleSocketFailure(err: Error): void {\n const sock = this.socket;\n this.socket = null;\n for (const [id, call] of this.pending) {\n this.pending.delete(id);\n if (call.timer) clearTimeout(call.timer);\n call.reject(err);\n }\n if (sock) sock.destroy();\n }\n\n /**\n * Searches the knowledge base.\n *\n * @param params - query parameters including the search string\n * @returns paginated search results with metadata\n */\n async search(params: SearchParams): Promise<PagedSearchResult> {\n return this.call('search', {\n ...params,\n algo: params.algo,\n }) as Promise<PagedSearchResult>;\n }\n\n /**\n * Retrieves full content and context for one or more sections by\n * their knowledge-base identifiers.\n *\n * @param params - section identifier(s) and optional expansion depth\n * @returns a single `RecallResult` when `kbid` is provided without\n * `kbids`, or a `RecallResult[]` when `kbids` is provided\n */\n async recall(\n params: RecallParams,\n ): Promise<RecallResult | RecallResult[]> {\n return this.call('recall', params) as Promise<\n RecallResult | RecallResult[]\n >;\n }\n\n /**\n * Adds a new section to the knowledge base.\n *\n * @param params - section content and metadata\n * @returns the result including the assigned knowledge-base\n * identifier and indexing statistics\n */\n async addSection(\n params: AddSectionParams,\n ): Promise<AddSectionResult> {\n return this.call(\n 'addSection',\n params,\n ) as Promise<AddSectionResult>;\n }\n\n /**\n * Replaces an existing section's content and metadata.\n *\n * @param kbid - identifier of the section to update\n * @param params - new content and metadata\n * @returns the knowledge-base identifier of the updated section\n */\n async updateSection(\n kbid: string,\n params: AddSectionParams,\n ): Promise<string> {\n return this.call('updateSection', {\n kbid,\n ...params,\n }) as Promise<string>;\n }\n\n /**\n * Removes a section from the knowledge base.\n *\n * @param kbid - identifier of the section to remove\n * @returns removal result with `removed` flag and elapsed time\n */\n async removeSection(kbid: string): Promise<RemoveSectionResult> {\n return this.call('removeSection', {\n kbid,\n }) as Promise<RemoveSectionResult>;\n }\n\n /**\n * Retrieves multiple sections by their identifiers.\n *\n * @param kbids - list of knowledge-base identifiers to fetch\n * @returns sections in the order their IDs were requested\n */\n async readSections(kbids: string[]): Promise<Section[]> {\n return this.call('readSections', {\n kbids,\n }) as Promise<Section[]>;\n }\n\n /**\n * Groups a set of sections under a named document.\n *\n * @param title - human-readable document title\n * @param kbids - identifiers of the sections to group\n * @param docType - application-level document type tag; omit or\n * pass an empty string for untagged documents\n * @returns the assigned document identifier\n */\n async groupSections(\n title: string,\n kbids: string[],\n docType?: string,\n ): Promise<string> {\n const result = (await this.call('groupSections', {\n title,\n kbids,\n docType: docType ?? '',\n })) as { docid: string } | string;\n return typeof result === 'string' ? result : result.docid;\n }\n\n /**\n * Removes the document grouping for the given document.\n *\n * The sections themselves are not deleted; only the grouping\n * record is removed.\n *\n * @param docid - identifier of the document grouping to remove\n */\n async removeGrouping(docid: string): Promise<void> {\n await this.call('removeGrouping', { docid });\n }\n\n /**\n * Retrieves a full document record including its sections.\n *\n * @param docid - identifier of the document to retrieve\n * @returns the document record as returned by the daemon\n */\n async retrieveDocument(docid: string): Promise<unknown> {\n return this.call('retrieveDocument', { docid });\n }\n\n /**\n * Composes a rendered Markdown document from one or more kbid\n * or docid identifiers.\n *\n * @param ids - list of kbid or docid identifiers (may be mixed)\n * @returns composed Markdown result with character count\n */\n async content(ids: string[]): Promise<ContentResult> {\n return this.call('content', { ids }) as Promise<ContentResult>;\n }\n\n /**\n * Runs an integrity check on the knowledge-base database.\n *\n * @returns a report of all issues found; `ok` is `true` when\n * no errors were detected\n */\n async integrityCheck(): Promise<IntegrityCheckResult> {\n return this.call(\n 'integrityCheck',\n {},\n ) as Promise<IntegrityCheckResult>;\n }\n\n /**\n * Removes unreferenced sections from the database.\n *\n * @returns a report of sections removed and bytes freed\n */\n async gc(): Promise<GcResult> {\n return this.call('gc', {}) as Promise<GcResult>;\n }\n\n /**\n * Reconstructs all index files from section files and document\n * manifests on disk. Text and code sections are re-tokenized;\n * image sections are skipped.\n *\n * @returns a report of sections and terms re-indexed\n */\n async rebuildIndexes(): Promise<RebuildResult> {\n return this.call('rebuildIndexes', {}) as Promise<RebuildResult>;\n }\n\n /**\n * Invalidates the in-memory cache entry for a single section.\n *\n * @param kbid - identifier of the section to evict from cache\n */\n async invalidate(kbid: string): Promise<void> {\n await this.call('invalidate', { kbid });\n }\n\n /** Clears all entries from the daemon's in-memory cache. */\n async invalidateAll(): Promise<void> {\n await this.call('invalidateAll', {});\n }\n\n /**\n * Retrieves diagnostic status information from the daemon.\n *\n * @returns current initialization state and cache statistics\n */\n async status(): Promise<StatusResult> {\n return this.call('status', {}) as Promise<StatusResult>;\n }\n\n /**\n * Returns database metadata and status from the daemon,\n * including document count, section count, index size, and\n * cache statistics.\n *\n * @returns database metadata from the daemon's cached state\n */\n async dbStatus(): Promise<StatusResult> {\n return this.call('dbStatus', {}) as Promise<StatusResult>;\n }\n\n /**\n * Initialises a new `.kbdb` database directory at the given path\n * by sending an init request to the worker daemon.\n *\n * The daemon creates all required subdirectories and seed files via\n * the `worker_init_directory` WASM export.\n *\n * @param targetPath - absolute path to the directory that will\n * contain the new `.kbdb` database\n * @throws {Error} if the `.kbdb` directory already exists or the\n * daemon cannot create the layout\n */\n async initDirectory(targetPath: string): Promise<void> {\n await this.call('initDirectory', { targetPath });\n }\n\n /**\n * Runs all pending database migrations for the `.kbdb` directory\n * at the given path.\n *\n * Delegates to the `worker_migrate` WASM export on the daemon.\n * Each migration step updates `catalog.toml` on success, so\n * retrying after a partial failure is safe.\n *\n * @param targetPath - absolute path to the `.kbdb` database root\n * @returns migration report with old version, new version, and\n * number of migration steps applied\n */\n async migrateDatabase(targetPath: string): Promise<MigrateResult> {\n return this.call('migrateDatabase', {\n targetPath,\n }) as Promise<MigrateResult>;\n }\n\n /**\n * Checks the format version of the `.kbdb` database at the given\n * path against the version required by the current WASM engine.\n *\n * This is a read-only operation: it reads `catalog.toml` and\n * returns the compatibility status without making any changes.\n *\n * @param targetPath - absolute path to the `.kbdb` database root\n * @returns version compatibility report\n */\n async checkVersion(targetPath: string): Promise<VersionStatus> {\n return this.call('checkVersion', {\n targetPath,\n }) as Promise<VersionStatus>;\n }\n\n /**\n * Retrieves all sections whose type name matches the given string.\n *\n * @param sectionType - the application-level type name to filter by\n * @returns all section records with a matching type name\n */\n async listByType(sectionType: string): Promise<SectionRecord[]> {\n return this.call('listByType', {\n sectionType,\n }) as Promise<SectionRecord[]>;\n }\n\n /**\n * Retrieves all documents whose type name matches the given string.\n *\n * @param docType - the application-level document type to filter by\n * @returns all document manifests with a matching type name\n */\n async listDocumentsByType(\n docType: string,\n ): Promise<DocumentManifest[]> {\n return this.call('listDocumentsByType', {\n docType,\n }) as Promise<DocumentManifest[]>;\n }\n\n /**\n * Exports the database to a target directory on disk.\n *\n * Copies section files, document manifests, and `catalog.toml`\n * to `params.path`. Index files are not exported because they\n * are derivable from the section and document data.\n *\n * @param params - optional export parameters\n * @param params.path - target directory path; defaults to\n * `./kbdb-export/` when not provided\n * @returns export report with the resolved path and file counts\n */\n async export(params?: {\n path?: string;\n format?: string;\n }): Promise<ExportResult> {\n return this.call('export', {\n targetPath: params?.path || undefined,\n format: params?.format,\n }) as Promise<ExportResult>;\n }\n\n /**\n * Imports an exported database from the given path.\n *\n * @param params - source path and dry-run flag\n * @returns import report with counts and timing\n */\n async import(params: {\n from: string;\n dryRun: boolean;\n }): Promise<ImportResult> {\n return this.call('importDb', {\n sourcePath: params.from,\n dryRun: params.dryRun,\n }) as Promise<ImportResult>;\n }\n\n /**\n * Sends a JSON-RPC 2.0 request and awaits the response.\n *\n * @param method - the RPC method name\n * @param params - parameters to include in the request\n * @throws {Error} if not connected\n * @throws {Error} when the daemon returns an error response\n */\n private async call(\n method: string,\n params: unknown,\n ): Promise<unknown> {\n const socket = this.socket;\n if (!socket) {\n throw new Error('not connected');\n }\n\n const id = this.nextId++;\n const request = {\n jsonrpc: '2.0',\n id,\n method,\n params: { ctx: this.contextId, ...(params as object) },\n };\n\n const timeoutMs = this.requestTimeoutMs;\n return new Promise<unknown>((resolve, reject) => {\n const call: PendingCall = { resolve, reject };\n if (timeoutMs) {\n call.timer = setTimeout(() => {\n if (!this.pending.has(id)) return;\n this.pending.delete(id);\n const err = new Error(\n `request timeout after ${String(timeoutMs)}ms`,\n );\n (err as unknown as Record<string, unknown>).code =\n 'REQUEST_TIMEOUT';\n reject(err);\n }, timeoutMs);\n }\n this.pending.set(id, call);\n socket.write(JSON.stringify(request) + '\\n');\n });\n }\n\n /**\n * Processes incoming data from the socket, splitting on newlines\n * and dispatching complete JSON-RPC response objects.\n *\n * @param data - raw string chunk received from the socket\n */\n private handleData(data: string): void {\n this.buffer += data;\n const lines = this.buffer.split('\\n');\n this.buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (!line.trim()) continue;\n try {\n const response = JSON.parse(line) as JsonRpcResponse;\n const pending = this.pending.get(response.id);\n if (pending) {\n this.pending.delete(response.id);\n if (pending.timer) clearTimeout(pending.timer);\n if (response.error) {\n const err = new Error(response.error.message);\n (err as unknown as Record<string, unknown>).code =\n response.error.code;\n pending.reject(err);\n } else {\n pending.resolve(response.result);\n }\n }\n } catch {\n // Ignore unparseable lines\n }\n }\n }\n}\n", "import { existsSync, readFileSync, unlinkSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\nimport { WorkerClient } from '../classes/worker-client.class.ts';\nimport { resolveDbPath } from './resolve-db-path.function.ts';\nimport { computeContextId } from './compute-context-id.function.ts';\nimport { discoverDaemon } from './discover-daemon.function.ts';\nimport { spawnDaemon } from './spawn-daemon.function.ts';\nimport { waitForDaemon } from './wait-for-daemon.function.ts';\nimport { detectRuntime } from '../../runtime/functions/detect-runtime.ts';\nimport { getIpcPath } from '../../platform/functions/get-ipc-path.function.ts';\nimport type { WorkerClientOptions } from '../typings/worker-client-options.interface.ts';\n\n/**\n * Creates and connects a `WorkerClient` to the worker daemon.\n *\n * Resolves the context path, derives a stable context identifier,\n * and checks whether a daemon is already running. If no daemon is\n * found and `autoSpawn` is not `false`, a new daemon process is\n * spawned and the factory waits for its PID file to appear before\n * connecting.\n *\n * @param options - optional configuration for path resolution,\n * auto-spawn behaviour, and connection timeout\n * @returns a connected `WorkerClient` ready to send requests\n * @throws {Error} if the `.kbdb` directory cannot be found\n * @throws {Error} if the socket connection cannot be established\n */\nexport async function createWorkerClient(\n options?: WorkerClientOptions,\n): Promise<WorkerClient> {\n const dbPath =\n options?.contextPath ?? resolveDbPath(options?.dbPath);\n const contextId = await computeContextId(dbPath);\n const socketPath = getIpcPath(contextId);\n\n let daemon = discoverDaemon(contextId);\n\n if (!daemon && options?.autoSpawn !== false) {\n const runtime = detectRuntime();\n spawnDaemon(dbPath, runtime, options?.workerScript);\n await waitForDaemon(contextId, options?.connectTimeoutMs);\n daemon = discoverDaemon(contextId);\n }\n\n if (!daemon) {\n throw new Error(\n `kbdb worker daemon did not start: ${readCrashReason(contextId)}`,\n );\n }\n\n const client = new WorkerClient(\n socketPath,\n contextId,\n options?.requestTimeoutMs,\n );\n await client.connect();\n return client;\n}\n\nfunction readCrashReason(contextId: string): string {\n const crashPath = join(tmpdir(), `kbdb-${contextId}.crash`);\n if (!existsSync(crashPath)) {\n return 'daemon failed to start (no details available)';\n }\n try {\n const raw = readFileSync(crashPath, 'utf-8');\n const crash = JSON.parse(raw) as { error?: string };\n unlinkSync(crashPath);\n return crash.error ?? 'unknown error (crash log empty)';\n } catch {\n return 'daemon failed to start (crash log unreadable)';\n }\n}\n", "import { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\n\n/**\n * Resolves the absolute path to the `.kbdb` database directory.\n *\n * Searches for a `.kbdb` sub-directory inside `targetDir`. When\n * `targetDir` is omitted, `process.cwd()` is used as the base.\n *\n * @param targetDir - directory to search in; defaults to cwd\n * @throws {Error} if no `.kbdb` directory exists at the resolved\n * path\n */\nexport function resolveDbPath(targetDir?: string): string {\n const base = targetDir ? resolve(targetDir) : process.cwd();\n const dbPath = join(base, '.kbdb');\n if (!existsSync(dbPath)) {\n throw new Error(`database not found: ${dbPath}`);\n }\n return dbPath;\n}\n", "/**\n * Computes the SHA-256 hash of a UTF-8 string.\n *\n * Uses the Web Crypto API (`crypto.subtle`), which is available\n * in both Deno and Node.js >= 20 without additional imports.\n *\n * @param input - the string to hash\n * @returns lowercase hex-encoded SHA-256 digest (64 characters)\n */\nexport async function computeSha256(input: string): Promise<string> {\n const data = new TextEncoder().encode(input);\n const hash = await crypto.subtle.digest('SHA-256', data);\n const bytes = new Uint8Array(hash);\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n", "import { computeSha256 } from '../../hash/functions/compute-sha256.ts';\n\n/**\n * Computes a short context identifier for an absolute path.\n *\n * Hashes the path with SHA-256 and returns the first 16 hex\n * characters. The result is stable for the same input and unique\n * enough to avoid accidental collisions across typical path sets.\n *\n * @param absolutePath - the absolute filesystem path to identify\n * @returns a 16-character lowercase hex string\n */\nexport async function computeContextId(\n absolutePath: string,\n): Promise<string> {\n const hash = await computeSha256(absolutePath);\n return hash.slice(0, 16);\n}\n", "import { existsSync, readFileSync, unlinkSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\nimport { isProcessAlive } from '../../platform/functions/is-process-alive.function.ts';\nimport type { DaemonInfo } from '../typings/daemon-info.model.ts';\n\nexport type { DaemonInfo };\n\n/**\n * Discovers a running worker daemon for the given context.\n *\n * Reads the PID file at `<tmpdir>/kbdb-<contextId>.pid`. If the\n * file exists and the process is alive, returns its PID and the\n * expected socket path. If the file is stale (process dead or PID\n * unparseable), removes the PID file and returns `null`.\n *\n * @param contextId - the 16-character context identifier\n * @returns daemon location info, or `null` if no live daemon found\n */\nexport function discoverDaemon(contextId: string): DaemonInfo | null {\n const pidPath = join(tmpdir(), `kbdb-${contextId}.pid`);\n\n if (!existsSync(pidPath)) return null;\n\n const pidStr = readFileSync(pidPath, 'utf-8').trim();\n const pid = parseInt(pidStr, 10);\n\n if (isNaN(pid) || !isProcessAlive(pid)) {\n try {\n unlinkSync(pidPath);\n } catch {\n // Stale PID file removal is best-effort\n }\n return null;\n }\n\n const socketPath = join(tmpdir(), `kbdb-${contextId}.sock`);\n\n const crashPath = join(tmpdir(), `kbdb-${contextId}.crash`);\n try {\n unlinkSync(crashPath);\n } catch {\n // stale crash file removal is best-effort\n }\n\n return { pid, socketPath };\n}\n", "/**\n * Checks whether a process with the given PID is alive.\n *\n * Sends signal `0` to the process, which performs a permission\n * check without sending an actual signal. Returns `true` if the\n * process exists and is reachable, `false` otherwise.\n *\n * @param pid - the process identifier to probe\n */\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n", "import { spawn } from 'node:child_process';\nimport type { Runtime } from '../../runtime/typings/runtime.ts';\n\n/**\n * Spawns a detached worker daemon process for the given context.\n *\n * @param contextPath - absolute path to the context directory the\n * daemon should serve\n * @param runtime - the current JavaScript runtime environment\n * @param workerScript - absolute path to the worker daemon script,\n * resolved at the entry point by `resolveWorkerScript`\n */\nexport function spawnDaemon(\n contextPath: string,\n runtime: Runtime,\n workerScript?: string,\n): void {\n if (!workerScript) {\n throw new Error(\n 'workerScript must be provided' + ' (resolve at entry point)',\n );\n }\n const execPath = runtime === 'deno' ? 'deno' : process.execPath;\n\n const args =\n runtime === 'deno'\n ? ['run', '--allow-all', workerScript, contextPath]\n : [workerScript, contextPath];\n\n const child = spawn(execPath, args, {\n detached: true,\n stdio: 'ignore',\n });\n child.unref();\n}\n", "import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\n\n/** Default maximum wait time for the daemon PID file to appear. */\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/** Polling interval in milliseconds between existence checks. */\nconst POLL_INTERVAL_MS = 100;\n\n/**\n * Waits for the worker daemon's PID file to appear on disk.\n *\n * Polls every 100 ms until the PID file at\n * `<tmpdir>/kbdb-<contextId>.pid` exists or the timeout elapses.\n *\n * @param contextId - the 16-character context identifier\n * @param timeoutMs - maximum wait time in milliseconds; defaults\n * to 10 000 ms\n * @returns `true` if the PID file appeared before the timeout,\n * `false` otherwise\n */\nexport async function waitForDaemon(\n contextId: string,\n timeoutMs: number = DEFAULT_TIMEOUT_MS,\n): Promise<boolean> {\n const pidPath = join(tmpdir(), `kbdb-${contextId}.pid`);\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n if (existsSync(pidPath)) return true;\n await new Promise<void>((r) => setTimeout(r, POLL_INTERVAL_MS));\n }\n return false;\n}\n", "import { join } from 'node:path';\nimport { getTmpdir } from './get-tmpdir.function.ts';\n\n/**\n * Returns the platform-appropriate IPC socket path for a given\n * context identifier.\n *\n * On Windows, returns a named pipe path (`\\\\.\\pipe\\kbdb-<ctx>`).\n * On POSIX systems, returns a Unix domain socket path under the\n * system temp directory (`<tmpdir>/kbdb-<ctx>.sock`).\n *\n * @param ctx - unique context identifier embedded in the path\n */\nexport function getIpcPath(ctx: string): string {\n if (process.platform === 'win32') {\n return `\\\\\\\\.\\\\pipe\\\\kbdb-${ctx}`;\n }\n return join(getTmpdir(), `kbdb-${ctx}.sock`);\n}\n", "import { tmpdir } from 'node:os';\n\n/**\n * Returns the operating system's default temporary directory path.\n */\nexport function getTmpdir(): string {\n return tmpdir();\n}\n", "import type { CommandResult } from '../typings/command-result.model.ts';\nimport {\n computeContextId,\n discoverDaemon,\n} from '../../worker-client/index.ts';\n\n/**\n * Stops the worker daemon for the resolved database path.\n *\n * Discovers the daemon via its PID file and sends `SIGTERM`.\n * Returns success when the daemon was stopped or was not running.\n *\n * @param dbDir - absolute path to the `.kbdb` directory\n * @returns command result indicating success or failure\n */\nexport async function runWorkerStop(\n dbDir: string,\n): Promise<CommandResult> {\n const contextId = await computeContextId(dbDir);\n const info = discoverDaemon(contextId);\n if (!info) {\n return { output: 'no daemon running', exitCode: 0 };\n }\n try {\n process.kill(info.pid, 'SIGTERM');\n return {\n output: `stopped daemon (pid ${info.pid.toString()})`,\n exitCode: 0,\n };\n } catch {\n return {\n error: 'error: failed to stop daemon',\n exitCode: 1,\n };\n }\n}\n", "import type { CommandResult } from '../typings/command-result.model.ts';\nimport { runWorkerStop } from './run-worker-stop.function.ts';\n\n/**\n * Restarts the worker daemon by stopping any running instance.\n *\n * The daemon auto-spawns on the next CLI command, so restart\n * only needs to stop the current instance.\n *\n * @param dbDir - absolute path to the `.kbdb` directory\n * @returns command result indicating success or failure\n */\nexport async function runWorkerRestart(\n dbDir: string,\n): Promise<CommandResult> {\n const stopResult = await runWorkerStop(dbDir);\n if (stopResult.exitCode !== 0) return stopResult;\n return {\n output: 'daemon will restart on next command',\n exitCode: 0,\n };\n}\n", "import type { CliOptions } from '../typings/cli-options.interface.ts';\n\n/**\n * Resolves the explicit database path from CLI\n * options or the `KBDB_DB_DIR` environment variable.\n *\n * Returns `undefined` when neither is set so that\n * `findDb` can fall back to upward directory\n * traversal from the current working directory.\n */\nexport function resolveRawDbPath(\n options: Pick<CliOptions, 'dbPath'>,\n): string | undefined {\n return options.dbPath ?? process.env['KBDB_DB_DIR'];\n}\n", "/**\n * Retries an operation when the daemon responds with\n * a `REQUEST_TIMEOUT` error. Each retry disconnects\n * the current client, creates a fresh one (which\n * auto-spawns the daemon), and re-runs the operation.\n *\n * @param createClient - factory that returns a connected client\n * @param operation - the work to perform with the client\n * @param maxRetries - maximum retry attempts\n * @returns the final client and result\n */\nexport async function retryOnTimeout<\n TClient extends { disconnect(): void },\n TResult,\n>(\n createClient: () => Promise<TClient>,\n operation: (client: TClient) => Promise<TResult>,\n maxRetries: number,\n): Promise<{ client: TClient; result: TResult }> {\n let lastError: Error = new Error('retryOnTimeout exhausted');\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const client = await createClient();\n try {\n const result = await operation(client);\n return { client, result };\n } catch (err: unknown) {\n const code = (err as Record<string, unknown>).code;\n if (code !== 'REQUEST_TIMEOUT' || attempt >= maxRetries) {\n client.disconnect();\n throw err;\n }\n lastError = err as Error;\n client.disconnect();\n }\n }\n throw lastError;\n}\n", "/** Default per-request timeout for daemon IPC calls (ms). */\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n", "/** Default number of retries on request timeout. */\nexport const DEFAULT_RETRY_COUNT = 5;\n", "import { VERSION } from '../../version/index.ts';\nimport type { CliOptions } from '../typings/cli-options.interface.ts';\nimport type { CommandResult } from '../typings/command-result.model.ts';\nimport type { InitResult } from './run-init.function.ts';\nimport type { VersionStatus } from '../../worker-client/typings/version-status.model.ts';\nimport type { MigrateResult } from '../../worker-client/typings/migrate-result.model.ts';\nimport { parseArgs } from './parse-args.function.ts';\nimport { errorToMessage } from './error-to-message.function.ts';\nimport { dispatchCommand } from './dispatch-command.function.ts';\nimport type { DispatchClient } from './dispatch-command.function.ts';\nimport {\n generateHelp,\n isKnownCommand,\n} from './generate-help.function.ts';\nimport { runWorkerStop } from './run-worker-stop.function.ts';\nimport { runWorkerRestart } from './run-worker-restart.function.ts';\nimport { resolveRawDbPath } from './resolve-raw-db-path.function.ts';\nimport { retryOnTimeout } from '../../worker-client/functions/retry-on-timeout.function.ts';\nimport { DEFAULT_REQUEST_TIMEOUT_MS } from '../../worker-client/constants/request-timeout.constant.ts';\nimport { DEFAULT_RETRY_COUNT } from '../../worker-client/constants/retry-defaults.constant.ts';\n\nexport interface DisconnectableClient extends DispatchClient {\n checkVersion(targetPath: string): Promise<VersionStatus>;\n migrateDatabase(targetPath: string): Promise<MigrateResult>;\n disconnect(): void;\n}\n\n/**\n * Injectable dependencies for the CLI orchestrator.\n *\n * Every external side-effect is injected so the function\n * is fully testable without touching process globals,\n * filesystem, or network.\n */\nexport interface CliDeps {\n isStdinTty: () => boolean;\n isStdoutTty: () => boolean;\n promptUser: (question: string) => Promise<string>;\n createWorkerClient: (opts: {\n contextPath: string;\n requestTimeoutMs?: number;\n }) => Promise<DisconnectableClient>;\n findDb: (basePath?: string) => string | null;\n runInit: (options: CliOptions) => InitResult;\n startMcpServer?: (\n contextPath: string,\n clientFactory?: () => Promise<DisconnectableClient>,\n maxRetries?: number,\n ) => Promise<void>;\n}\n\n/**\n * Full CLI orchestrator extracted from `src/cli.ts`.\n *\n * Parses arguments, routes to the appropriate sub-flow\n * (help, version, init, mcp, migrate, data commands), and\n * returns a `CommandResult` without touching process globals.\n *\n * @param argv - raw CLI arguments (typically `process.argv.slice(2)`)\n * @param deps - injectable dependencies\n */\nexport async function runCli(\n argv: string[],\n deps: CliDeps,\n): Promise<CommandResult> {\n const options = parseArgs(argv);\n\n if (!options.formatExplicit) {\n options.format = deps.isStdoutTty() ? 'text' : 'json';\n }\n\n if (options.command === 'help' || !options.command) {\n const helpCommand = options.args[0];\n const helpSubcommand = options.args[1];\n const helpText = generateHelp(helpCommand, helpSubcommand);\n if (helpCommand && !isKnownCommand(helpCommand)) {\n return { output: helpText, exitCode: 1 };\n }\n return { output: helpText, exitCode: 0 };\n }\n\n if (options.command === 'version') {\n return { output: VERSION, exitCode: 0 };\n }\n\n if (options.command === 'init' || options.command === 'db-init') {\n return handleInit(options, deps);\n }\n\n if (options.command === 'mcp') {\n return handleMcp(options, deps);\n }\n\n if (\n options.command === 'migrate' ||\n options.command === 'db-migrate'\n ) {\n return handleMigrate(options, deps);\n }\n\n if (options.command === 'worker-stop') {\n return handleWorkerLifecycle(options, deps, runWorkerStop);\n }\n\n if (options.command === 'worker-restart') {\n return handleWorkerLifecycle(options, deps, runWorkerRestart);\n }\n\n return handleDataCommand(options, deps);\n}\n\nfunction handleInit(options: CliOptions, deps: CliDeps): CommandResult {\n const result = deps.runInit(options);\n if (result.ok) {\n return {\n output: result.targetPath,\n exitCode: 0,\n };\n }\n return {\n error: `error: ${result.errorMessage ?? 'init failed'}`,\n exitCode: 1,\n };\n}\n\nfunction resolveTimeoutMs(options: CliOptions): number {\n return (\n options.timeoutMs ??\n (parseInt(process.env['KBDB_DAEMON_TIMEOUT'] ?? '', 10) ||\n DEFAULT_REQUEST_TIMEOUT_MS)\n );\n}\n\nfunction resolveRetryCount(options: CliOptions): number {\n return (\n options.retry ??\n (parseInt(process.env['KBDB_RETRY'] ?? '', 10) ||\n DEFAULT_RETRY_COUNT)\n );\n}\n\nasync function handleMcp(\n options: CliOptions,\n deps: CliDeps,\n): Promise<CommandResult> {\n const explicitPath = resolveRawDbPath(options);\n const dbDir = deps.findDb(explicitPath);\n if (!dbDir) {\n return {\n error:\n 'error: no .kbdb database found at ' +\n (explicitPath ?? process.cwd()),\n exitCode: 1,\n };\n }\n\n const timeoutMs = resolveTimeoutMs(options);\n const maxRetries = resolveRetryCount(options);\n let client: DisconnectableClient;\n try {\n client = await deps.createWorkerClient({\n contextPath: dbDir,\n requestTimeoutMs: timeoutMs,\n });\n } catch (err) {\n return {\n error: `error: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n\n try {\n const gateResult = await versionGate(client, dbDir);\n if (gateResult) return gateResult;\n\n if (deps.startMcpServer) {\n await deps.startMcpServer(\n dbDir,\n () =>\n deps.createWorkerClient({\n contextPath: dbDir,\n requestTimeoutMs: timeoutMs,\n }),\n maxRetries,\n );\n }\n return { exitCode: 0 };\n } catch (err) {\n return {\n error: `error: mcp failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n } finally {\n client.disconnect();\n }\n}\n\nasync function handleMigrate(\n options: CliOptions,\n deps: CliDeps,\n): Promise<CommandResult> {\n const dbDir = deps.findDb(options.dbPath);\n if (!dbDir) {\n const basePath = options.dbPath ?? process.cwd();\n return {\n error: `error: no .kbdb database found at ${basePath}`,\n exitCode: 1,\n };\n }\n\n let client: DisconnectableClient;\n try {\n client = await deps.createWorkerClient({\n contextPath: dbDir,\n });\n } catch (err) {\n return {\n error: `error: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n\n try {\n const versionStatus = await client.checkVersion(dbDir);\n\n if (versionStatus.status === 'too_new') {\n return {\n error:\n `error: database version` +\n ` ${versionStatus.currentVersion.toString()}` +\n ` is newer than kbdb version` +\n ` ${versionStatus.requiredVersion.toString()}` +\n ` -- upgrade kbdb`,\n exitCode: 1,\n };\n }\n\n if (versionStatus.status === 'needs_migration') {\n const migrateResult = await client.migrateDatabase(dbDir);\n return {\n output: JSON.stringify(migrateResult, null, 2),\n exitCode: 0,\n };\n }\n\n return { output: 'already up to date', exitCode: 0 };\n } catch (err) {\n return {\n error: `error: migrate failed: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n } finally {\n client.disconnect();\n }\n}\n\nasync function handleDataCommand(\n options: CliOptions,\n deps: CliDeps,\n): Promise<CommandResult> {\n const explicitPath = resolveRawDbPath(options);\n let dbDir = deps.findDb(explicitPath);\n\n if (!dbDir) {\n const basePath = explicitPath ?? process.cwd();\n\n if (!deps.isStdinTty()) {\n return {\n error:\n `error: no .kbdb database found at ${basePath}` +\n ' -- run `kbdb --init` to create one',\n exitCode: 1,\n };\n }\n\n const answer = await deps.promptUser(\n `No .kbdb database found. Create one in ${basePath}? [y/N] `,\n );\n\n if (answer.toLowerCase() !== 'y') {\n return {\n error: 'aborted: no database created',\n exitCode: 1,\n };\n }\n\n const initResult = deps.runInit(options);\n if (!initResult.ok) {\n return {\n error: `error: ${initResult.errorMessage ?? 'init failed'}`,\n exitCode: 1,\n };\n }\n dbDir = initResult.targetPath;\n }\n\n const timeoutMs = resolveTimeoutMs(options);\n const maxRetries = resolveRetryCount(options);\n\n try {\n const { client, result } = await retryOnTimeout(\n () =>\n deps.createWorkerClient({\n contextPath: dbDir,\n requestTimeoutMs: timeoutMs,\n }),\n async (c) => {\n const gateResult = await versionGate(c, dbDir);\n if (gateResult) return gateResult;\n return dispatchCommand(c, options);\n },\n maxRetries,\n );\n client.disconnect();\n return result;\n } catch (err) {\n return {\n error: `error: ${errorToMessage(err)}`,\n exitCode: 1,\n };\n }\n}\n\nasync function handleWorkerLifecycle(\n options: CliOptions,\n deps: CliDeps,\n action: (dbDir: string) => Promise<CommandResult>,\n): Promise<CommandResult> {\n const explicitPath = resolveRawDbPath(options);\n const dbDir = deps.findDb(explicitPath);\n if (!dbDir) {\n return {\n error:\n 'error: no .kbdb database found at ' +\n (explicitPath ?? process.cwd()),\n exitCode: 1,\n };\n }\n return action(dbDir);\n}\n\nasync function versionGate(\n client: DisconnectableClient,\n dbDir: string,\n): Promise<CommandResult | null> {\n const versionStatus = await client.checkVersion(dbDir);\n\n if (versionStatus.status === 'needs_migration') {\n return {\n error:\n 'error: database needs migration' +\n ' -- run `kbdb --migrate`',\n exitCode: 1,\n };\n }\n\n if (versionStatus.status === 'too_new') {\n return {\n error:\n `error: database version` +\n ` ${versionStatus.currentVersion.toString()}` +\n ` is newer than kbdb version` +\n ` ${versionStatus.requiredVersion.toString()}` +\n ` -- upgrade kbdb`,\n exitCode: 1,\n };\n }\n\n return null;\n}\n", "import { generateHelp } from '../functions/generate-help.function.ts';\n\n/** Global help text for the kbdb CLI. */\nexport const HELP_TEXT = generateHelp();\n", "import { createInterface } from 'node:readline';\nimport { createToolDefinitions } from '../functions/create-tool-definitions.function.ts';\nimport { createResourceTemplates } from '../functions/create-resource-templates.function.ts';\nimport { handleToolCall } from '../functions/handle-tool-call.function.ts';\nimport { handleResourceRead } from '../functions/handle-resource-read.function.ts';\nimport { createPromptDefinitions } from '../functions/create-prompt-definitions.function.ts';\nimport { handlePromptGet } from '../functions/handle-prompt-get.function.ts';\nimport { handleCompletion } from '../functions/handle-completion.function.ts';\nimport { handleRootsList } from '../functions/handle-roots-list.function.ts';\nimport { shouldEmitLog } from '../functions/should-emit-log.function.ts';\nimport { runAutoCapture } from '../functions/run-auto-capture.function.ts';\nimport { AutoCaptureController } from '../../auto-capture/classes/auto-capture-controller.class.ts';\nimport {\n PARSE_ERROR,\n METHOD_NOT_FOUND,\n RESOURCE_NOT_FOUND,\n} from '../constants/mcp-error-codes.constant.ts';\nimport type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\nimport type {\n McpRequest,\n McpResponse,\n} from '../typings/mcp-types.interface.ts';\nimport type { McpLogLevel } from '../typings/log-types.interface.ts';\nimport type {\n McpCompletionRef,\n McpCompletionArgument,\n} from '../functions/handle-completion.function.ts';\nimport type { AutoCaptureConfig } from '../../auto-capture/typings/auto-capture-config.interface.ts';\nimport { VERSION } from '../../version/index.ts';\nimport { DEFAULT_RETRY_COUNT } from '../../worker-client/constants/retry-defaults.constant.ts';\n\n/**\n * MCP server that speaks JSON-RPC 2.0 over stdio. Listens for\n * newline-delimited requests on `process.stdin`, dispatches each\n * to the appropriate knowledge-base operation via\n * `McpWorkerClient`, and writes JSON-RPC responses to\n * `process.stdout`.\n */\nexport class McpServer {\n private client: McpWorkerClient;\n private readonly contextPath: string;\n private readonly autoCaptureConfig: AutoCaptureConfig | null;\n private readonly clientFactory:\n | (() => Promise<McpWorkerClient>)\n | null;\n private readonly maxRetries: number;\n private autoCaptureController: AutoCaptureController | null = null;\n private initialized = false;\n private hostCapabilities: Record<string, unknown> | null = null;\n private logLevel: McpLogLevel | null = null;\n private readonly subscriptions = new Set<string>();\n private nextRequestId = 1;\n private readonly pendingRequests = new Map<\n number,\n {\n resolve: (value: unknown) => void;\n reject: (reason: unknown) => void;\n timer: ReturnType<typeof setTimeout>;\n }\n >();\n\n /**\n * @param client - worker client providing knowledge-base operations\n * @param contextPath - absolute path to the `.kbdb` directory\n * @param autoCaptureConfig - optional auto-capture configuration;\n * when provided the server activates auto-capture on connection\n * @param clientFactory - creates a fresh worker client (for retry)\n * @param maxRetries - max retries on REQUEST_TIMEOUT\n */\n constructor(\n client: McpWorkerClient,\n contextPath?: string,\n autoCaptureConfig?: AutoCaptureConfig,\n clientFactory?: (() => Promise<McpWorkerClient>) | null,\n maxRetries?: number,\n ) {\n this.client = client;\n this.contextPath = contextPath ?? '';\n this.autoCaptureConfig = autoCaptureConfig ?? null;\n this.clientFactory = clientFactory ?? null;\n this.maxRetries = maxRetries ?? DEFAULT_RETRY_COUNT;\n }\n\n private async reconnectClient(): Promise<void> {\n if (!this.clientFactory) {\n throw new Error('no client factory for reconnect');\n }\n this.client.disconnect();\n this.client = await this.clientFactory();\n }\n\n private async withRetry<T>(fn: () => Promise<T>): Promise<T> {\n for (let attempt = 0; ; attempt++) {\n try {\n return await fn();\n } catch (err: unknown) {\n const code = (err as Record<string, unknown>).code;\n if (\n code !== 'REQUEST_TIMEOUT' ||\n attempt >= this.maxRetries ||\n !this.clientFactory\n ) {\n throw err;\n }\n await this.reconnectClient();\n }\n }\n }\n\n async listen(): Promise<void> {\n const rl = createInterface({\n input: process.stdin,\n terminal: false,\n });\n\n let pending = Promise.resolve();\n await new Promise<void>((resolve) => {\n rl.on('line', (line) => {\n pending = pending.then(() => this.dispatchLine(line));\n });\n\n rl.on('close', () => {\n void pending.then(() => {\n this.autoCaptureController?.reset();\n this.autoCaptureController = null;\n this.client.disconnect();\n resolve();\n });\n });\n });\n }\n\n async handleLineForTest(line: string): Promise<McpResponse | null> {\n return this.processLine(line);\n }\n\n /**\n * Sends a JSON-RPC notification (no `id`, no response\n * expected) to stdout.\n */\n notify(method: string, params?: Record<string, unknown>): void {\n const notification: Record<string, unknown> = {\n jsonrpc: '2.0',\n method,\n };\n if (params !== undefined) {\n notification['params'] = params;\n }\n process.stdout.write(JSON.stringify(notification) + '\\n');\n }\n\n /**\n * Emits a log notification if the message severity meets or\n * exceeds the configured log level threshold.\n */\n log(level: McpLogLevel, message: unknown, logger?: string): void {\n if (this.logLevel === null) return;\n if (!shouldEmitLog(level, this.logLevel)) return;\n this.notify('notifications/message', {\n level,\n logger: logger ?? 'kbdb',\n data: message,\n });\n }\n\n /**\n * Sends a JSON-RPC request to the host (server-to-client)\n * and returns a Promise that resolves with the response\n * result. Times out after 30 seconds.\n */\n sendRequest(\n method: string,\n params: Record<string, unknown>,\n ): Promise<unknown> {\n const id = this.nextRequestId++;\n const request = { jsonrpc: '2.0', id, method, params };\n process.stdout.write(JSON.stringify(request) + '\\n');\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this.pendingRequests.delete(id);\n reject(new Error(`Request ${method} timed out`));\n }, 30000);\n this.pendingRequests.set(id, {\n resolve,\n reject,\n timer,\n });\n });\n }\n\n /**\n * Requests the host to generate text via the sampling\n * capability. Throws if the host did not advertise sampling\n * support during initialization.\n */\n async requestSampling(\n messages: {\n role: string;\n content: { type: string; text: string };\n }[],\n maxTokens: number,\n ): Promise<unknown> {\n if (!this.hostCapabilities?.['sampling']) {\n throw new Error('Host does not support sampling');\n }\n return this.sendRequest('sampling/createMessage', {\n messages,\n maxTokens,\n });\n }\n\n private async dispatchLine(line: string): Promise<void> {\n const response = await this.processLine(line);\n if (response !== null) {\n this.send(response);\n }\n }\n\n private async processLine(\n line: string,\n ): Promise<McpResponse | null> {\n if (!line.trim()) return null;\n\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(line) as Record<string, unknown>;\n } catch {\n return {\n jsonrpc: '2.0',\n id: 0,\n error: {\n code: PARSE_ERROR,\n message: 'Parse error',\n },\n };\n }\n\n // Incoming response to an outgoing request (sampling)\n if (\n parsed['id'] !== undefined &&\n typeof parsed['method'] !== 'string'\n ) {\n const responseId = parsed['id'] as number;\n const pending = this.pendingRequests.get(responseId);\n if (pending) {\n this.pendingRequests.delete(responseId);\n clearTimeout(pending.timer);\n if (parsed['error']) {\n const err = parsed['error'] as {\n message?: string;\n };\n pending.reject(\n new Error(err.message ?? 'Request failed'),\n );\n } else {\n pending.resolve(parsed['result']);\n }\n }\n return null;\n }\n\n const request = parsed as unknown as McpRequest;\n\n if (request.id === undefined) {\n if (\n request.method === 'notifications/initialized' ||\n request.method === 'notifications/cancelled'\n ) {\n if (\n request.method === 'notifications/initialized' &&\n !this.initialized\n ) {\n this.initialized = true;\n if (this.autoCaptureConfig !== null) {\n this.autoCaptureController =\n new AutoCaptureController(this.autoCaptureConfig);\n }\n void this.runStartupHealthCheck();\n }\n }\n return null;\n }\n\n const id = request.id;\n\n if (\n !this.initialized &&\n request.method !== 'initialize' &&\n request.method !== 'ping'\n ) {\n return {\n jsonrpc: '2.0',\n id,\n error: {\n code: RESOURCE_NOT_FOUND,\n message: 'Server not initialized',\n },\n };\n }\n\n const response = await this.handleRequest(request);\n return response;\n }\n\n private async handleRequest(\n request: McpRequest,\n ): Promise<McpResponse> {\n const id = request.id as number | string;\n\n switch (request.method) {\n case 'initialize': {\n const params = request.params ?? {};\n const caps = params['capabilities'];\n this.hostCapabilities = caps\n ? (caps as Record<string, unknown>)\n : null;\n return {\n jsonrpc: '2.0',\n id,\n result: {\n protocolVersion: '2025-11-25',\n serverInfo: {\n name: 'kbdb',\n version: VERSION,\n },\n capabilities: {\n tools: {},\n resources: { subscribe: true },\n prompts: {},\n logging: {},\n completions: {},\n },\n },\n };\n }\n\n case 'ping':\n return { jsonrpc: '2.0', id, result: {} };\n\n case 'tools/list':\n return {\n jsonrpc: '2.0',\n id,\n result: {\n tools: createToolDefinitions(),\n },\n };\n\n case 'resources/list':\n return {\n jsonrpc: '2.0',\n id,\n result: { resources: [] },\n };\n\n case 'resources/templates/list':\n return {\n jsonrpc: '2.0',\n id,\n result: {\n resourceTemplates: createResourceTemplates(),\n },\n };\n\n case 'tools/call': {\n const params = request.params ?? {};\n const rawName = params['name'];\n const name = typeof rawName === 'string' ? rawName : '';\n const args = (params['arguments'] ?? {}) as Record<\n string,\n unknown\n >;\n const result = await this.withRetry(() =>\n handleToolCall(this.client, name, args),\n );\n this.afterToolCall();\n return { jsonrpc: '2.0', id, result };\n }\n\n case 'resources/read': {\n const params = request.params ?? {};\n const rawUri = params['uri'];\n const uri = typeof rawUri === 'string' ? rawUri : '';\n try {\n const result = await this.withRetry(() =>\n handleResourceRead(this.client, uri),\n );\n return { jsonrpc: '2.0', id, result };\n } catch (err) {\n return {\n jsonrpc: '2.0',\n id,\n error: {\n code: RESOURCE_NOT_FOUND,\n message:\n err instanceof Error\n ? err.message\n : String(err),\n },\n };\n }\n }\n\n case 'prompts/list': {\n const skills = await this.client.listByType('skill');\n const agents =\n await this.client.listDocumentsByType('agent');\n const prompts = createPromptDefinitions(skills, agents);\n return {\n jsonrpc: '2.0',\n id,\n result: { prompts },\n };\n }\n\n case 'prompts/get': {\n const params = request.params ?? {};\n const name =\n typeof params['name'] === 'string' ? params['name'] : '';\n const promptArgs = (params['arguments'] ?? {}) as Record<\n string,\n string\n >;\n try {\n const messages = await handlePromptGet(\n name,\n promptArgs,\n this.client,\n );\n return {\n jsonrpc: '2.0',\n id,\n result: { messages },\n };\n } catch (err) {\n return {\n jsonrpc: '2.0',\n id,\n error: {\n code: RESOURCE_NOT_FOUND,\n message:\n err instanceof Error\n ? err.message\n : String(err),\n },\n };\n }\n }\n\n case 'completion/complete': {\n const params = request.params ?? {};\n const ref = params['ref'] as McpCompletionRef;\n const argument = (params['argument'] ?? {\n name: '',\n value: '',\n }) as McpCompletionArgument;\n const result = await handleCompletion(\n ref,\n argument,\n this.client,\n );\n return { jsonrpc: '2.0', id, result };\n }\n\n case 'roots/list': {\n const roots = handleRootsList(this.contextPath);\n return {\n jsonrpc: '2.0',\n id,\n result: { roots },\n };\n }\n\n case 'logging/setLevel': {\n const params = request.params ?? {};\n const level = params['level'] as McpLogLevel | undefined;\n this.logLevel = level ?? null;\n return { jsonrpc: '2.0', id, result: {} };\n }\n\n case 'resources/subscribe': {\n const params = request.params ?? {};\n const uri =\n typeof params['uri'] === 'string' ? params['uri'] : '';\n this.subscriptions.add(uri);\n return { jsonrpc: '2.0', id, result: {} };\n }\n\n case 'resources/unsubscribe': {\n const params = request.params ?? {};\n const uri =\n typeof params['uri'] === 'string' ? params['uri'] : '';\n this.subscriptions.delete(uri);\n return { jsonrpc: '2.0', id, result: {} };\n }\n\n default:\n return {\n jsonrpc: '2.0',\n id,\n error: {\n code: METHOD_NOT_FOUND,\n message: `Method not found: ` + request.method,\n },\n };\n }\n }\n\n private send(response: McpResponse): void {\n const json = JSON.stringify(response);\n process.stdout.write(json + '\\n');\n }\n\n /**\n * Records a tool call in the auto-capture controller and fires\n * a capture when the trigger condition is met.\n */\n private afterToolCall(): void {\n const ctrl = this.autoCaptureController;\n const cfg = this.autoCaptureConfig;\n if (ctrl === null || cfg === null) return;\n ctrl.recordToolCall();\n void runAutoCapture(\n ctrl,\n cfg,\n this.client,\n this.hostCapabilities,\n (messages, maxTokens) =>\n this.requestSampling(messages, maxTokens),\n );\n }\n\n /**\n * Runs an integrity check immediately after the MCP handshake\n * completes. Emits a `notifications/message` warning when the\n * check detects issues so the connected agent is aware before\n * making requests. The server continues operating regardless of\n * the result.\n */\n private async runStartupHealthCheck(): Promise<void> {\n try {\n const report = await this.client.integrityCheck();\n if (!report.ok) {\n const summary = report.errors\n .map((e) => `${e.type}: ${e.entity} -- ${e.detail}`)\n .join('; ');\n this.notify('notifications/message', {\n level: 'warning',\n logger: 'kbdb',\n data: `Database integrity issues detected: ${summary}`,\n });\n }\n } catch {\n // Health check failure is non-fatal -- server continues\n }\n }\n}\n", "import type { McpToolDefinition } from '../typings/mcp-types.interface.ts';\n\n/**\n * Returns the full list of MCP tool definitions exposed by the\n * knowledge-base server. Each definition includes the tool name,\n * a human-readable description, and a JSON Schema for its inputs.\n */\nexport function createToolDefinitions(): McpToolDefinition[] {\n return [\n {\n name: 'search',\n description:\n 'Query the knowledge base by keywords.' +\n ' Returns ranked results with heading,' +\n ' snippet, and matched terms. Use multiple' +\n ' short keyword queries for best coverage.' +\n ' Use recall to get full content.',\n inputSchema: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'Search query text',\n },\n mode: {\n type: 'string',\n enum: ['sections', 'documents', 'stats'],\n description: 'Search mode (default: sections)',\n },\n limit: {\n type: 'number',\n description: 'Maximum results (default: 20)',\n },\n offset: {\n type: 'number',\n description:\n 'Number of results to skip for' +\n ' pagination (default: 0)',\n },\n algo: {\n type: 'string',\n enum: ['lexical', 'vector', 'hybrid'],\n description: 'Search algorithm (default: lexical)',\n },\n relaxed: {\n type: 'boolean',\n description:\n 'Use relaxed (OR) matching when the' +\n ' strict query returns no results',\n },\n },\n required: ['query'],\n },\n annotations: {\n title: 'Search KB',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'learn',\n description:\n 'Import content into the knowledge base.' +\n ' Use for durable facts, decisions, and' +\n ' corrections. Use replace when updating' +\n ' existing knowledge. Attach tags for scoping.',\n inputSchema: {\n type: 'object',\n properties: {\n content: {\n type: 'string',\n description: 'Text content to add',\n },\n type: {\n type: 'string',\n description:\n 'MIME type (default: text/markdown).' +\n ' Use image/* for images.',\n },\n title: {\n type: 'string',\n description:\n 'Section title.' + ' Required for image/* types.',\n },\n description: {\n type: 'string',\n description: 'Optional section description',\n },\n docid: {\n type: 'string',\n description: 'Document ID to group under',\n },\n tags: {\n type: 'array',\n items: { type: 'string' },\n description: 'Tags for scoping and filtering',\n },\n replace: {\n type: 'boolean',\n description:\n 'Replace existing section with same' +\n ' source key (supersession)',\n },\n },\n required: ['content'],\n },\n annotations: {\n title: 'Import Content',\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'unlearn',\n description:\n 'Remove a section from the knowledge base' +\n ' by its kb-id.',\n inputSchema: {\n type: 'object',\n properties: {\n kbid: {\n type: 'string',\n description: 'Knowledge base ID of the section',\n },\n },\n required: ['kbid'],\n },\n annotations: {\n title: 'Remove Section',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'retrieve',\n description:\n 'Low-level fetch of a section or document' +\n ' by identifier. For AI agent workflows,' +\n ' prefer `recall` which includes metadata,' +\n ' context, and back-references.',\n inputSchema: {\n type: 'object',\n properties: {\n kbid: {\n type: 'string',\n description: 'Section kb-id',\n },\n docid: {\n type: 'string',\n description: 'Document ID',\n },\n },\n },\n annotations: {\n title: 'Fetch Content',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'recall',\n description:\n 'Retrieve full content and context for sections' +\n ' by identifier. Use after search to read relevant' +\n ' results. Returns section text, metadata,' +\n ' references, and back-references.',\n inputSchema: {\n type: 'object',\n properties: {\n kbid: {\n type: 'string',\n description: 'Single section identifier',\n },\n kbids: {\n type: 'array',\n items: { type: 'string' },\n description: 'Batch section identifiers',\n },\n depth: {\n type: 'number',\n description: 'Expansion depth (0-3, default: 0)',\n },\n },\n },\n annotations: {\n title: 'Recall Context',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'status',\n description:\n 'Get database metadata including document count,' +\n ' section count, index size, and cache statistics.',\n inputSchema: {\n type: 'object',\n properties: {},\n },\n annotations: {\n title: 'DB Status',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'content',\n description:\n 'Compose a rendered Markdown document from one or' +\n ' more kbid or docid identifiers.',\n inputSchema: {\n type: 'object',\n properties: {\n ids: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'One or more kbid or docid identifiers' +\n ' (may be mixed)',\n },\n },\n required: ['ids'],\n },\n annotations: {\n title: 'Compose Content',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'check',\n description:\n 'Verify the integrity of the knowledge base.' +\n ' Reports checksum mismatches, orphan sections,' +\n ' broken references, and circular reference chains.',\n inputSchema: {\n type: 'object',\n properties: {},\n },\n annotations: {\n title: 'Integrity Check',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'gc',\n description:\n 'Remove unreferenced sections from the knowledge' +\n ' base. A section is eligible when no document' +\n ' manifest references it.',\n inputSchema: {\n type: 'object',\n properties: {},\n },\n annotations: {\n title: 'Garbage Collect',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n },\n },\n {\n name: 'rebuild',\n description:\n 'Reconstruct all index files from section files' +\n ' and document manifests on disk. Use this to' +\n ' recover from index corruption.',\n inputSchema: {\n type: 'object',\n properties: {},\n },\n annotations: {\n title: 'Rebuild Indexes',\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n },\n {\n name: 'export',\n description:\n 'Export the database as a self-contained' +\n ' directory snapshot (sections, documents,' +\n ' catalog -- no indexes).',\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description:\n 'Export destination path' +\n ' (default: ./kbdb-export/)',\n },\n },\n },\n annotations: {\n title: 'Export Snapshot',\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'skill-learn',\n description:\n 'Create or update a skill definition.' +\n ' Skills are reusable AI agent capabilities' +\n ' with template placeholders.',\n inputSchema: {\n type: 'object',\n properties: {\n name: {\n type: 'string',\n description: 'Skill name',\n },\n description: {\n type: 'string',\n description: 'Skill description',\n },\n body: {\n type: 'string',\n description:\n 'Skill body template.' +\n ' Use {{argName}} for placeholders.',\n },\n },\n required: ['name', 'body'],\n },\n annotations: {\n title: 'Create Skill',\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'skill-list',\n description: 'List all skills in the knowledge base.',\n inputSchema: {\n type: 'object',\n properties: {},\n },\n annotations: {\n title: 'List Skills',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'skill-get',\n description: 'Get a skill definition by name or kbid.',\n inputSchema: {\n type: 'object',\n properties: {\n name: {\n type: 'string',\n description: 'Skill name',\n },\n kbid: {\n type: 'string',\n description: 'Knowledge base ID',\n },\n },\n },\n annotations: {\n title: 'Get Skill',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'skill-delete',\n description: 'Delete a skill by its kbid.',\n inputSchema: {\n type: 'object',\n properties: {\n kbid: {\n type: 'string',\n description: 'Knowledge base ID',\n },\n },\n required: ['kbid'],\n },\n annotations: {\n title: 'Delete Skill',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'agent-create',\n description:\n 'Create an AI agent with a persona and' +\n ' optional skill references.',\n inputSchema: {\n type: 'object',\n properties: {\n name: {\n type: 'string',\n description: 'Agent name',\n },\n description: {\n type: 'string',\n description: 'Agent description',\n },\n persona: {\n type: 'string',\n description: 'Agent persona prompt',\n },\n skills: {\n type: 'array',\n items: { type: 'string' },\n description: 'Skill kbid references to attach',\n },\n },\n required: ['name', 'persona'],\n },\n annotations: {\n title: 'Create Agent',\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'agent-list',\n description: 'List all agents in the knowledge base.',\n inputSchema: {\n type: 'object',\n properties: {},\n },\n annotations: {\n title: 'List Agents',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'agent-get',\n description: 'Get an agent definition by document ID.',\n inputSchema: {\n type: 'object',\n properties: {\n docid: {\n type: 'string',\n description: 'Document ID of the agent',\n },\n },\n required: ['docid'],\n },\n annotations: {\n title: 'Get Agent',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'agent-delete',\n description:\n 'Delete an agent by its document ID.' +\n ' Skill sections are not removed.',\n inputSchema: {\n type: 'object',\n properties: {\n docid: {\n type: 'string',\n description: 'Document ID of the agent',\n },\n },\n required: ['docid'],\n },\n annotations: {\n title: 'Delete Agent',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n {\n name: 'auto-capture-review',\n description:\n 'Review and approve pending auto-captured' +\n ' knowledge before storage.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['list', 'approve', 'reject'],\n description: 'Action to perform on pending captures',\n },\n },\n },\n annotations: {\n title: 'Auto-Capture Review',\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n ];\n}\n", "import type { McpResourceTemplate } from '../typings/mcp-types.interface.ts';\n\n/**\n * Returns the list of MCP resource URI templates served by the\n * knowledge-base server. Each template describes the URI pattern,\n * human-readable metadata, and the MIME type of the resource body.\n */\nexport function createResourceTemplates(): McpResourceTemplate[] {\n return [\n {\n uriTemplate: 'kbdb://section/{kb_id}',\n name: 'Section',\n description: 'A knowledge base section by its kb-id.',\n mimeType: 'text/plain',\n },\n {\n uriTemplate: 'kbdb://document/{doc_id}',\n name: 'Document',\n description: 'A document with its ordered sections.',\n mimeType: 'application/json',\n },\n ];\n}\n", "import type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\n\n/** Shape of a content item in an MCP tool call response. */\ninterface ToolContent {\n /** Content type identifier, typically `'text'`. */\n readonly type: string;\n /** The text payload. */\n readonly text: string;\n}\n\n/** Result returned by the agent-create tool handler. */\ninterface ToolCallResult {\n /** One or more content items describing the result. */\n readonly content: ToolContent[];\n /** Set to `true` when the tool encountered an error. */\n readonly isError?: boolean;\n}\n\n/**\n * Narrows an `unknown` value to a string, returning the fallback\n * when the value is not already a string.\n */\nfunction asString(value: unknown, fallback: string): string {\n return typeof value === 'string' ? value : fallback;\n}\n\n/**\n * Narrows an `unknown` value to a `string[]`, returning an empty\n * array when the value is not an array of strings.\n */\nfunction asStringArray(value: unknown): string[] {\n if (\n Array.isArray(value) &&\n value.every((item) => typeof item === 'string')\n ) {\n return value;\n }\n return [];\n}\n\n/**\n * Handles the `agent:create` MCP tool call.\n *\n * Validates required arguments, verifies that referenced skill kbids\n * exist, stores agent metadata as a JSON section, groups all sections\n * into a single document, and returns the resulting document\n * identifier.\n *\n * @param client - the worker client used to execute operations\n * @param args - tool arguments from the MCP request\n * @returns content items with optional `isError` flag\n */\nexport async function handleAgentCreate(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const name = asString(args['name'], '');\n const description = asString(args['description'], '');\n const persona = asString(args['persona'], '');\n const skills = asStringArray(args['skills']);\n\n if (!name) {\n return {\n content: [{ type: 'text', text: 'name is required' }],\n isError: true,\n };\n }\n if (!persona) {\n return {\n content: [{ type: 'text', text: 'persona is required' }],\n isError: true,\n };\n }\n\n if (skills.length > 0) {\n const sections = await client.readSections(skills);\n const found = new Set(sections.map((s) => s.kbid));\n const missing = skills.filter((k) => !found.has(k));\n if (missing.length > 0) {\n return {\n content: [\n {\n type: 'text',\n text: `skill not found: ${missing.join(', ')}`,\n },\n ],\n isError: true,\n };\n }\n }\n\n const metadata = JSON.stringify({ name, description, persona });\n\n const metaResult = await client.addSection({\n sectionType: 'text',\n content: metadata,\n title: name,\n description,\n });\n\n const allKbids = [metaResult.kbid, ...skills];\n const docid = await client.groupSections(name, allKbids, 'agent');\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n docid,\n name,\n skillCount: skills.length,\n }),\n },\n ],\n };\n}\n", "import type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\n\n/** Shape of a content item in an MCP tool call response. */\ninterface ToolContent {\n /** Content type identifier, typically `'text'`. */\n readonly type: string;\n /** The text payload. */\n readonly text: string;\n}\n\n/** Result returned by the agent-list tool handler. */\ninterface ToolCallResult {\n /** One or more content items describing the result. */\n readonly content: ToolContent[];\n /** Set to `true` when the tool encountered an error. */\n readonly isError?: boolean;\n}\n\n/**\n * Handles the `agent:list` MCP tool call.\n *\n * Retrieves all documents with `doc_type: 'agent'` and returns a\n * summary list containing each agent's document identifier, name,\n * and skill count.\n *\n * The `skillCount` is `Math.max(0, sections.length - 1)` because\n * the first section of an agent document always holds the metadata\n * JSON and does not count as a skill reference.\n *\n * @param client - the worker client used to execute operations\n * @returns content items with the serialised agent list\n */\nexport async function handleAgentList(\n client: McpWorkerClient,\n): Promise<ToolCallResult> {\n const docs = await client.listDocumentsByType('agent');\n const items = docs.map((d) => ({\n docid: d.docid,\n name: d.title,\n skillCount: Math.max(0, d.sections.length - 1),\n }));\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(items, null, 2),\n },\n ],\n };\n}\n", "import type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\nimport type { AgentDefinition } from '../typings/agent-types.interface.ts';\n\n/** Shape of a content item in an MCP tool call response. */\ninterface ToolContent {\n /** Content type identifier, typically `'text'`. */\n readonly type: string;\n /** The text payload. */\n readonly text: string;\n}\n\n/** Result returned by the agent-get tool handler. */\ninterface ToolCallResult {\n /** One or more content items describing the result. */\n readonly content: ToolContent[];\n /** Set to `true` when the tool encountered an error. */\n readonly isError?: boolean;\n}\n\n/** Parsed shape of an agent document section list entry. */\ninterface DocumentSection {\n /** Knowledge-base identifier of the section. */\n readonly kbid: string;\n /** Zero-based position of the section within the document. */\n readonly position: number;\n}\n\n/** Parsed shape of a retrieved agent document. */\ninterface AgentDocument {\n /** Document identifier. */\n readonly docid: string;\n /** Document title used as agent name fallback. */\n readonly title: string;\n /** Ordered list of sections in the document. */\n readonly sections: DocumentSection[];\n}\n\n/**\n * Reads the metadata JSON stored in the first section of an agent\n * document and extracts `name`, `description`, and `persona`.\n */\nasync function readAgentMeta(\n client: McpWorkerClient,\n metaKbid: string,\n fallbackName: string,\n): Promise<{ name: string; description: string; persona: string }> {\n const metaSections = await client.readSections([metaKbid]);\n const first = metaSections.at(0);\n if (!first) {\n return { name: fallbackName, description: '', persona: '' };\n }\n try {\n const meta = JSON.parse(first.content) as Record<string, unknown>;\n return {\n name:\n typeof meta['name'] === 'string'\n ? meta['name']\n : fallbackName,\n description:\n typeof meta['description'] === 'string'\n ? meta['description']\n : '',\n persona:\n typeof meta['persona'] === 'string' ? meta['persona'] : '',\n };\n } catch {\n return { name: fallbackName, description: '', persona: '' };\n }\n}\n\n/**\n * Resolves skill names for a list of section references by reading\n * each section's JSON content and extracting the `name` field.\n * Returns `null` for skill references where the section no longer\n * exists (dangling references).\n */\nasync function resolveSkillRefs(\n client: McpWorkerClient,\n skillRefs: DocumentSection[],\n): Promise<{ kbid: string; name: string | null; position: number }[]> {\n if (skillRefs.length === 0) {\n return [];\n }\n const skillKbids = skillRefs.map((s) => s.kbid);\n const skillSections = await client.readSections(skillKbids);\n const sectionMap = new Map(skillSections.map((s) => [s.kbid, s]));\n return skillRefs.map((ref) => {\n const sec = sectionMap.get(ref.kbid);\n if (!sec) {\n return { kbid: ref.kbid, name: null, position: ref.position };\n }\n try {\n const parsed = JSON.parse(sec.content) as Record<\n string,\n unknown\n >;\n const skillName =\n typeof parsed['name'] === 'string' ? parsed['name'] : null;\n return {\n kbid: ref.kbid,\n name: skillName,\n position: ref.position,\n };\n } catch {\n return { kbid: ref.kbid, name: null, position: ref.position };\n }\n });\n}\n\n/**\n * Handles the `agent:get` MCP tool call.\n *\n * Retrieves an agent document by its `docid`, reads the metadata\n * section and skill references, and returns a full `AgentDefinition`.\n * Dangling skill references (sections that no longer exist) appear\n * with `name: null` in the skills list.\n *\n * @param client - the worker client used to execute operations\n * @param args - tool arguments; must include a `docid` string\n * @returns content items containing the serialised `AgentDefinition`\n */\nexport async function handleAgentGet(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const docid = typeof args['docid'] === 'string' ? args['docid'] : '';\n if (!docid) {\n return {\n content: [{ type: 'text', text: 'docid is required' }],\n isError: true,\n };\n }\n\n const doc = (await client.retrieveDocument(docid)) as AgentDocument;\n const metaKbid = doc.sections[0]?.kbid;\n const skillRefs = doc.sections.slice(1);\n\n const { name, description, persona } = metaKbid\n ? await readAgentMeta(client, metaKbid, doc.title)\n : { name: doc.title, description: '', persona: '' };\n\n const skills = await resolveSkillRefs(client, skillRefs);\n\n const agent: AgentDefinition = {\n docid,\n name,\n description,\n persona,\n skills,\n };\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(agent, null, 2),\n },\n ],\n };\n}\n", "import type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\n\n/** Shape of a content item in an MCP tool call response. */\ninterface ToolContent {\n /** Content type identifier, typically `'text'`. */\n readonly type: string;\n /** The text payload. */\n readonly text: string;\n}\n\n/** Result returned by the agent-delete tool handler. */\ninterface ToolCallResult {\n /** One or more content items describing the result. */\n readonly content: ToolContent[];\n /** Set to `true` when the tool encountered an error. */\n readonly isError?: boolean;\n}\n\n/**\n * Handles the `agent:delete` MCP tool call.\n *\n * Removes the document grouping identified by `docid`. The skill\n * sections referenced by the agent are not deleted; only the grouping\n * record is removed.\n *\n * @param client - the worker client used to execute operations\n * @param args - tool arguments; must include a `docid` string\n * @returns content items confirming removal, or an error item\n */\nexport async function handleAgentDelete(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const docid = typeof args['docid'] === 'string' ? args['docid'] : '';\n if (!docid) {\n return {\n content: [{ type: 'text', text: 'docid is required' }],\n isError: true,\n };\n }\n await client.removeGrouping(docid);\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({ docid, removed: true }),\n },\n ],\n };\n}\n", "import type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\n\n/** Shape of a content item in an MCP tool call response. */\ninterface ToolContent {\n /** Content type identifier, typically `'text'`. */\n readonly type: string;\n /** The text payload. */\n readonly text: string;\n}\n\n/** Result returned by a tool call handler. */\ninterface ToolCallResult {\n /** One or more content items describing the result. */\n readonly content: ToolContent[];\n /** Set to `true` when the tool encountered an error. */\n readonly isError?: boolean;\n}\n\n/**\n * Handles the MCP `recall` tool call.\n *\n * Retrieves full content and context for one or more knowledge-base\n * sections by identifier. At least one of `kbid` or `kbids` must be\n * present in `args`; omitting both returns an error result.\n *\n * @param client - the worker client used to execute the operation\n * @param args - tool arguments from the MCP request\n * @returns content with JSON-stringified recall result, or an error\n * content item when required arguments are missing\n */\nexport async function handleRecall(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const kbid =\n typeof args['kbid'] === 'string' ? args['kbid'] : undefined;\n const kbids =\n Array.isArray(args['kbids']) &&\n args['kbids'].every((item: unknown) => typeof item === 'string')\n ? args['kbids']\n : undefined;\n\n if (!kbid && !kbids) {\n return {\n content: [\n {\n type: 'text',\n text: 'Provide kbid or kbids',\n },\n ],\n isError: true,\n };\n }\n\n const depth = typeof args['depth'] === 'number' ? args['depth'] : 0;\n\n const result = await client.recall({ kbid, kbids, depth });\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n}\n", "import type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\nimport { extractSkillArguments } from './extract-skill-arguments.function.ts';\nimport { parseSkillContent } from './parse-skill-content.function.ts';\nimport { serializeSkillContent } from './serialize-skill-content.function.ts';\nimport { handleAgentCreate } from './handle-agent-create.function.ts';\nimport { handleAgentList } from './handle-agent-list.function.ts';\nimport { handleAgentGet } from './handle-agent-get.function.ts';\nimport { handleAgentDelete } from './handle-agent-delete.function.ts';\nimport { handleRecall } from './handle-recall.function.ts';\n\n/** Shape of a content item in an MCP tool call response. */\ninterface ToolContent {\n /** Content type identifier, typically 'text'. */\n readonly type: string;\n /** The text payload. */\n readonly text: string;\n}\n\n/** Result returned by a tool call handler. */\ninterface ToolCallResult {\n /** One or more content items describing the result. */\n readonly content: ToolContent[];\n /** Set to `true` when the tool encountered an error. */\n readonly isError?: boolean;\n}\n\n/**\n * Narrows an `unknown` value to a string, returning the fallback\n * when the value is not already a string.\n */\nfunction asString(value: unknown, fallback: string): string {\n return typeof value === 'string' ? value : fallback;\n}\n\n/**\n * Narrows an `unknown` value to a boolean, returning `undefined`\n * when the value is not a boolean.\n */\nfunction asBooleanOrUndefined(value: unknown): boolean | undefined {\n return typeof value === 'boolean' ? value : undefined;\n}\n\n/**\n * Narrows an `unknown` value to a `string[]`, returning `undefined`\n * when the value is not an array of strings.\n */\nfunction asStringArrayOrUndefined(\n value: unknown,\n): string[] | undefined {\n if (\n Array.isArray(value) &&\n value.every((item) => typeof item === 'string')\n ) {\n return value;\n }\n return undefined;\n}\n\n/**\n * Narrows an `unknown` value to a `string[]`, returning an empty\n * array when the value is not an array of strings.\n */\nfunction asStringArray(value: unknown): string[] {\n if (\n Array.isArray(value) &&\n value.every((item) => typeof item === 'string')\n ) {\n return value;\n }\n return [];\n}\n\n/**\n * Dispatches an MCP tool call to the appropriate knowledge-base\n * operation and returns the result formatted as MCP content.\n *\n * @param client - the worker client used to execute operations\n * @param name - the tool name to invoke\n * @param args - tool arguments from the MCP request\n * @returns content items with optional isError flag\n */\nexport async function handleToolCall(\n client: McpWorkerClient,\n name: string,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n try {\n switch (name) {\n case 'search':\n return await handleSearch(client, args);\n case 'learn':\n return await handleLearn(client, args);\n case 'unlearn':\n return await handleUnlearn(client, args);\n case 'retrieve':\n return await handleRetrieve(client, args);\n case 'recall':\n return await handleRecall(client, args);\n case 'status':\n return await handleStatus(client);\n case 'content':\n return await handleContent(client, args);\n case 'check':\n return await handleCheck(client);\n case 'gc':\n return await handleGc(client);\n case 'rebuild':\n return await handleRebuild(client);\n case 'export':\n return await handleExport(client, args);\n case 'skill-learn':\n return await handleSkillLearn(client, args);\n case 'skill-list':\n return await handleSkillList(client);\n case 'skill-get':\n return await handleSkillGet(client, args);\n case 'skill-delete':\n return await handleSkillDelete(client, args);\n case 'agent-create':\n return await handleAgentCreate(client, args);\n case 'agent-list':\n return await handleAgentList(client);\n case 'agent-get':\n return await handleAgentGet(client, args);\n case 'agent-delete':\n return await handleAgentDelete(client, args);\n case 'auto-capture-review':\n return handleAutoCaptureReview();\n default:\n return {\n content: [\n {\n type: 'text',\n text: `Unknown tool: ${name}`,\n },\n ],\n isError: true,\n };\n }\n } catch (err) {\n return {\n content: [\n {\n type: 'text',\n text: err instanceof Error ? err.message : String(err),\n },\n ],\n isError: true,\n };\n }\n}\n\nasync function handleSearch(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const results = await client.search({\n query: asString(args['query'], ''),\n mode: args['mode'] as string | undefined,\n limit: args['limit'] as number | undefined,\n offset: args['offset'] as number | undefined,\n algo: args['algo'] as string | undefined,\n relaxed: args['relaxed'] as boolean | undefined,\n });\n\n const stripped = {\n ...results,\n items: results.items.map(\n ({\n score: _score,\n confidence: _confidence,\n ...rest\n }: (typeof results.items)[number] & {\n confidence?: number;\n }) => rest,\n ),\n };\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(stripped, null, 2),\n },\n ],\n };\n}\n\nasync function handleLearn(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const sectionType = asString(args['type'], 'text/markdown');\n const title =\n typeof args['title'] === 'string' ? args['title'] : undefined;\n const description =\n typeof args['description'] === 'string'\n ? args['description']\n : undefined;\n const docid =\n typeof args['docid'] === 'string' ? args['docid'] : undefined;\n const tags = asStringArrayOrUndefined(args['tags']);\n const replace = asBooleanOrUndefined(args['replace']);\n if (sectionType.startsWith('image/') && !title) {\n return {\n content: [\n {\n type: 'text',\n text: 'title is required for image/* types',\n },\n ],\n isError: true,\n };\n }\n const result = await client.addSection({\n sectionType,\n content: asString(args['content'], ''),\n title,\n description,\n docid,\n tags,\n replace,\n });\n const normalized = {\n kbid: result.kbid,\n indexed_terms_count: result.indexed_terms_count ?? 0,\n elapsed_ms: result.elapsed_ms ?? 0,\n superseded: result.superseded ?? null,\n warnings: result.warnings ?? [],\n near_duplicates: (result.near_duplicates ?? []).map((d) => ({\n kbid: d.kbid,\n similarity: d.similarity,\n ...(d.method !== undefined ? { method: d.method } : {}),\n })),\n };\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(normalized),\n },\n ],\n };\n}\n\nasync function handleUnlearn(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const result = await client.removeSection(\n asString(args['kbid'], ''),\n );\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(result),\n },\n ],\n };\n}\n\nasync function handleRetrieve(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n if (typeof args['kbid'] === 'string') {\n const sections = await client.readSections([args['kbid']]);\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(sections, null, 2),\n },\n ],\n };\n }\n if (typeof args['docid'] === 'string') {\n const doc = await client.retrieveDocument(args['docid']);\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(doc, null, 2),\n },\n ],\n };\n }\n return {\n content: [\n {\n type: 'text',\n text: 'Provide kbid or docid',\n },\n ],\n isError: true,\n };\n}\n\nasync function handleStatus(\n client: McpWorkerClient,\n): Promise<ToolCallResult> {\n const status = await client.dbStatus();\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(status, null, 2),\n },\n ],\n };\n}\n\nasync function handleContent(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const ids = asStringArray(args['ids']);\n const result = await client.content(ids);\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(result),\n },\n ],\n };\n}\n\nasync function handleCheck(\n client: McpWorkerClient,\n): Promise<ToolCallResult> {\n const report = await client.integrityCheck();\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(report, null, 2),\n },\n ],\n };\n}\n\nasync function handleGc(\n client: McpWorkerClient,\n): Promise<ToolCallResult> {\n const report = await client.gc();\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(report, null, 2),\n },\n ],\n };\n}\n\nasync function handleRebuild(\n client: McpWorkerClient,\n): Promise<ToolCallResult> {\n const report = await client.rebuildIndexes();\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(report, null, 2),\n },\n ],\n };\n}\n\nasync function handleSkillLearn(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const name = asString(args['name'], '');\n if (!name) {\n return {\n content: [{ type: 'text', text: 'name is required' }],\n isError: true,\n };\n }\n const body = asString(args['body'], '');\n if (!body) {\n return {\n content: [{ type: 'text', text: 'body is required' }],\n isError: true,\n };\n }\n const description =\n typeof args['description'] === 'string'\n ? args['description']\n : undefined;\n const skillArgs = extractSkillArguments(body);\n const skill = {\n name,\n description,\n arguments: skillArgs.length > 0 ? skillArgs : undefined,\n body,\n };\n const json = serializeSkillContent(skill);\n const result = await client.addSection({\n sectionType: 'skill',\n content: json,\n title: name,\n description,\n });\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({ kbid: result.kbid, name }),\n },\n ],\n };\n}\n\nasync function handleSkillList(\n client: McpWorkerClient,\n): Promise<ToolCallResult> {\n const records = await client.listByType('skill');\n const items = records.map((r) => {\n let argumentCount = 0;\n try {\n const parsed = JSON.parse(r.content) as Record<\n string,\n unknown\n >;\n if (Array.isArray(parsed['arguments'])) {\n argumentCount = parsed['arguments'].length;\n }\n } catch {\n // ignore parse errors\n }\n return {\n kbid: r.kbid,\n name: r.title,\n description: r.description,\n argumentCount,\n };\n });\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(items, null, 2),\n },\n ],\n };\n}\n\nasync function handleSkillGet(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const kbid =\n typeof args['kbid'] === 'string' ? args['kbid'] : undefined;\n const name =\n typeof args['name'] === 'string' ? args['name'] : undefined;\n if (!kbid && !name) {\n return {\n content: [\n {\n type: 'text',\n text: 'name or kbid is required',\n },\n ],\n isError: true,\n };\n }\n let content: string | undefined;\n if (kbid) {\n const sections = await client.readSections([kbid]);\n if (sections.length > 0) {\n content = sections[0]?.content;\n }\n }\n if (content === undefined && name) {\n const records = await client.listByType('skill');\n const match = records.filter((r) => r.title === name).pop();\n if (match) {\n content = match.content;\n }\n }\n if (content === undefined) {\n const identifier = kbid ?? name ?? '';\n return {\n content: [\n {\n type: 'text',\n text: `skill not found: ${identifier}`,\n },\n ],\n isError: true,\n };\n }\n const skill = parseSkillContent(content);\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(skill, null, 2),\n },\n ],\n };\n}\n\nasync function handleSkillDelete(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const kbid = asString(args['kbid'], '');\n if (!kbid) {\n return {\n content: [{ type: 'text', text: 'kbid is required' }],\n isError: true,\n };\n }\n const result = await client.removeSection(kbid);\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({ kbid, removed: result.removed }),\n },\n ],\n };\n}\n\nfunction handleAutoCaptureReview(): ToolCallResult {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n pending: [],\n message: 'No pending auto-captured knowledge entries.',\n }),\n },\n ],\n };\n}\n\nasync function handleExport(\n client: McpWorkerClient,\n args: Record<string, unknown>,\n): Promise<ToolCallResult> {\n const path =\n typeof args['path'] === 'string' ? args['path'] : undefined;\n const result = await client.export(\n path !== undefined ? { path } : {},\n );\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(result),\n },\n ],\n };\n}\n", "import type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\n\n/** A single content item in an MCP resource read response. */\ninterface ResourceContent {\n /** The resource URI that was read. */\n readonly uri: string;\n /** MIME type of the content body. */\n readonly mimeType: string;\n /** Text body of the resource. */\n readonly text: string;\n}\n\n/** Result returned by a resource read operation. */\ninterface ResourceReadResult {\n /** One or more content items for the requested URI. */\n readonly contents: ResourceContent[];\n}\n\n/**\n * Handles an MCP `resources/read` request by dispatching to the\n * appropriate knowledge-base operation based on the resource URI.\n *\n * @param client - the worker client used to fetch the resource\n * @param uri - the resource URI from the MCP request\n * @returns contents array for the MCP response\n * @throws {Error} when the URI does not match any known pattern\n */\nexport async function handleResourceRead(\n client: McpWorkerClient,\n uri: string,\n): Promise<ResourceReadResult> {\n const sectionMatch = uri.match(/^kbdb:\\/\\/section\\/(.+)$/);\n if (sectionMatch) {\n const sections = await client.readSections([sectionMatch[1]]);\n const text = sections.length > 0 ? sections[0].content : '';\n return {\n contents: [{ uri, mimeType: 'text/plain', text }],\n };\n }\n\n const docMatch = uri.match(/^kbdb:\\/\\/document\\/(.+)$/);\n if (docMatch) {\n const doc = await client.retrieveDocument(docMatch[1]);\n return {\n contents: [\n {\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(doc, null, 2),\n },\n ],\n };\n }\n\n throw new Error(`Unknown resource URI: ${uri}`);\n}\n", "import type { McpPrompt } from '../typings/prompt-types.interface.ts';\nimport type { McpPromptArgument } from '../typings/prompt-types.interface.ts';\n\n/** Minimal skill section record shape required by this function. */\ninterface SkillSectionRecord {\n /** Knowledge-base identifier of the section. */\n readonly kbid: string;\n /** Human-readable section title used as the prompt name. */\n readonly title: string | null;\n /** JSON-encoded skill definition content. */\n readonly content: string;\n /** Optional human-readable section description. */\n readonly description?: string | null;\n}\n\n/** Minimal document manifest shape required by this function. */\ninterface AgentDocumentRecord {\n /** Unique document identifier. */\n readonly docid: string;\n /** Human-readable document title used in the prompt name. */\n readonly title: string;\n /** Ordered section references belonging to the document. */\n readonly sections: readonly {\n readonly kbid: string;\n readonly position: number;\n }[];\n}\n\n/**\n * Parses the `arguments` field from a skill's JSON content string.\n *\n * Returns the array of prompt argument definitions when the content\n * is valid JSON with an `arguments` array, or `undefined` when JSON\n * parsing fails or the field is absent.\n */\nfunction parseSkillArguments(\n content: string,\n): readonly McpPromptArgument[] | undefined {\n try {\n const parsed = JSON.parse(content) as Record<string, unknown>;\n if (!Array.isArray(parsed['arguments'])) {\n return undefined;\n }\n return (parsed['arguments'] as Record<string, unknown>[]).map(\n (arg) => ({\n name: typeof arg['name'] === 'string' ? arg['name'] : '',\n description:\n typeof arg['description'] === 'string'\n ? arg['description']\n : undefined,\n required:\n typeof arg['required'] === 'boolean'\n ? arg['required']\n : undefined,\n }),\n );\n } catch {\n return undefined;\n }\n}\n\n/**\n * Builds the list of MCP prompt definitions from skill sections and\n * agent document manifests stored in the knowledge base.\n *\n * Skills are mapped first (in input order), followed by agents.\n * Each skill becomes a prompt whose name is the section title and\n * whose arguments are extracted from the JSON content. Each agent\n * becomes a prompt prefixed with `\"agent:\"` and carries an empty\n * arguments array.\n *\n * @param skills - skill section records from `listByType('skill')`\n * @param agents - agent document manifests from\n * `listDocumentsByType('agent')`\n * @returns ordered list of MCP prompt definitions\n */\nexport function createPromptDefinitions(\n skills: readonly SkillSectionRecord[],\n agents: readonly AgentDocumentRecord[],\n): McpPrompt[] {\n const skillPrompts: McpPrompt[] = skills\n .filter(\n (r): r is SkillSectionRecord & { title: string } =>\n r.title !== null,\n )\n .map((record) => {\n const args = parseSkillArguments(record.content);\n const prompt: McpPrompt = {\n name: record.title,\n description: record.description ?? undefined,\n arguments: args,\n };\n return prompt;\n });\n\n const agentPrompts: McpPrompt[] = agents.map((doc) => ({\n name: `agent:${doc.title}`,\n arguments: [],\n }));\n\n return [...skillPrompts, ...agentPrompts];\n}\n", "import type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\nimport type { McpPromptMessage } from '../typings/prompt-types.interface.ts';\n\n/** Parsed shape of an agent metadata section. */\ninterface AgentMeta {\n /** Agent persona text. */\n readonly persona: string;\n}\n\n/** Minimal section shape returned by readSections. */\ninterface ReadSection {\n /** Knowledge-base identifier. */\n readonly kbid: string;\n /** Raw text content. */\n readonly content: string;\n}\n\n/** Minimal agent document shape from listDocumentsByType. */\ninterface AgentDocument {\n /** Document title. */\n readonly title: string;\n /** Ordered section references. */\n readonly sections: readonly {\n readonly kbid: string;\n readonly position: number;\n }[];\n}\n\n/**\n * Parses agent metadata from a raw JSON content string.\n *\n * Returns default values when parsing fails or required fields are\n * absent.\n */\nfunction parseAgentMeta(content: string): AgentMeta {\n try {\n const parsed = JSON.parse(content) as Record<string, unknown>;\n return {\n persona:\n typeof parsed['persona'] === 'string'\n ? parsed['persona']\n : '',\n };\n } catch {\n return { persona: '' };\n }\n}\n\n/**\n * Builds the skills listing user message text from an array of\n * skill section content strings. Sections whose JSON is not parseable\n * or whose name cannot be determined are omitted silently.\n *\n * Returns `null` when no valid skills remain after filtering.\n */\nfunction buildSkillsText(skillSections: ReadSection[]): string | null {\n const lines: string[] = [];\n for (const sec of skillSections) {\n try {\n const parsed = JSON.parse(sec.content) as Record<\n string,\n unknown\n >;\n const name =\n typeof parsed['name'] === 'string' ? parsed['name'] : null;\n if (name === null) {\n continue;\n }\n const description =\n typeof parsed['description'] === 'string'\n ? parsed['description']\n : '';\n lines.push(`- ${name}: ${description}`);\n } catch {\n // skip unparseable sections\n }\n }\n if (lines.length === 0) {\n return null;\n }\n return `Available skills:\\n${lines.join('\\n')}`;\n}\n\n/**\n * Handles an MCP `prompts/get` request for an agent prompt.\n *\n * Looks up the agent by title via `listDocumentsByType('agent')`,\n * extracts its persona from the metadata section, then reads all\n * skill sections and composes the response. Returns an assistant\n * message with the persona and, when skills exist, a user message\n * listing them.\n */\nasync function handleAgentPrompt(\n name: string,\n client: McpWorkerClient,\n): Promise<McpPromptMessage[]> {\n const agentName = name.slice(6);\n const agents = await client.listDocumentsByType('agent');\n const doc = agents.find((a) => a.title === agentName) as\n | AgentDocument\n | undefined;\n if (!doc) {\n throw new Error('agent not found: ' + agentName);\n }\n const sections = doc.sections;\n\n const metaSection = sections.at(0);\n const skillRefs = sections.slice(1);\n\n let persona = '';\n if (metaSection !== undefined) {\n const metaSections = await client.readSections([\n metaSection.kbid,\n ]);\n const metaContent = metaSections.at(0);\n if (metaContent !== undefined) {\n persona = parseAgentMeta(metaContent.content).persona;\n }\n }\n\n const messages: McpPromptMessage[] = [\n {\n role: 'assistant',\n content: { type: 'text', text: persona },\n },\n ];\n\n if (skillRefs.length === 0) {\n return messages;\n }\n\n const skillKbids = skillRefs.map((s) => s.kbid);\n const skillSections = await client.readSections(skillKbids);\n const skillsText = buildSkillsText(skillSections);\n\n if (skillsText !== null) {\n messages.push({\n role: 'user',\n content: { type: 'text', text: skillsText },\n });\n }\n\n return messages;\n}\n\n/**\n * Handles an MCP `prompts/get` request for a skill prompt.\n *\n * Looks up the skill by name in the `listByType('skill')` results,\n * picks the most recent match (last occurrence), parses its body,\n * and substitutes `{{argName}}` placeholders from `promptArgs`.\n * Unresolved placeholders are left as-is.\n *\n * @throws {Error} when no skill with the given name is found\n */\nasync function handleSkillPrompt(\n name: string,\n promptArgs: Record<string, string>,\n client: McpWorkerClient,\n): Promise<McpPromptMessage[]> {\n const sections = await client.listByType('skill');\n let matchContent: string | undefined;\n for (const sec of sections) {\n if (sec.title === name) {\n matchContent = sec.content;\n }\n }\n if (matchContent === undefined) {\n throw new Error(`Prompt not found: ${name}`);\n }\n\n const parsed = JSON.parse(matchContent) as Record<string, unknown>;\n const body =\n typeof parsed['body'] === 'string' ? parsed['body'] : '';\n\n const rendered = body.replace(\n /\\{\\{(\\w+)\\}\\}/g,\n (_match, key: string) =>\n key in promptArgs ? (promptArgs[key] ?? _match) : _match,\n );\n\n return [\n {\n role: 'user',\n content: { type: 'text', text: rendered },\n },\n ];\n}\n\n/**\n * Handles an MCP `prompts/get` request.\n *\n * Dispatches to the agent handler when `name` starts with `\"agent:\"`,\n * otherwise treats the name as a skill prompt.\n *\n * For skill prompts: looks up by title using `listByType('skill')`,\n * substitutes `{{argName}}` placeholders in the body, and returns a\n * single user message.\n *\n * For agent prompts: looks up the agent by title via\n * `listDocumentsByType('agent')`, builds an assistant message from\n * the persona section, and (when skills exist) a user message\n * listing their names and descriptions.\n *\n * @param name - prompt name from the MCP request\n * @param promptArgs - argument key-value map from the MCP request\n * @param client - worker client used to access the knowledge base\n * @returns ordered list of prompt messages to return to the caller\n * @throws {Error} when a skill prompt name is not found in the store\n */\nexport async function handlePromptGet(\n name: string,\n promptArgs: Record<string, string>,\n client: McpWorkerClient,\n): Promise<McpPromptMessage[]> {\n if (name.startsWith('agent:')) {\n return handleAgentPrompt(name, client);\n }\n return handleSkillPrompt(name, promptArgs, client);\n}\n", "import type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\n\n/**\n * Discriminated reference used in MCP completion requests.\n * Identifies whether the completion target is a prompt or a resource.\n */\nexport interface McpCompletionRef {\n /**\n * The reference type: `'ref/prompt'` for named prompts (skills\n * and agents) or `'ref/resource'` for resource URIs.\n */\n readonly type: 'ref/prompt' | 'ref/resource';\n /** Prompt name, present when `type` is `'ref/prompt'`. */\n readonly name?: string;\n /** Resource URI, present when `type` is `'ref/resource'`. */\n readonly uri?: string;\n}\n\n/**\n * Completion argument supplied by the client, describing which\n * argument is being completed and the current partial value.\n */\nexport interface McpCompletionArgument {\n /** The argument name being completed. */\n readonly name: string;\n /** The partial value typed so far; used for prefix filtering. */\n readonly value: string;\n}\n\n/**\n * Result returned by `handleCompletion`, containing the list of\n * matching completion values and pagination metadata.\n */\nexport interface McpCompletionResult {\n /** Completion payload. */\n readonly completion: {\n /** Matching completion strings for the given prefix. */\n readonly values: string[];\n /**\n * Whether more results are available beyond what is returned.\n * Always `false` in this implementation.\n */\n readonly hasMore: boolean;\n /** Total number of values returned. */\n readonly total: number;\n };\n}\n\n/**\n * Handles an MCP `completion/complete` request.\n *\n * For `ref/prompt` references, builds a list of all skill titles and\n * agent titles (prefixed with `agent:`) and filters by the supplied\n * argument value prefix. For `ref/resource` references, returns an\n * empty result \u2014 resource completion is not implemented.\n *\n * @param ref - discriminated reference identifying the completion target\n * @param argument - current argument name and partial value\n * @param client - worker client used to fetch skills and agents\n * @returns matching completion values with pagination metadata\n */\nexport async function handleCompletion(\n ref: McpCompletionRef,\n argument: McpCompletionArgument,\n client: McpWorkerClient,\n): Promise<McpCompletionResult> {\n if (ref.type !== 'ref/prompt') {\n return { completion: { values: [], hasMore: false, total: 0 } };\n }\n\n const [skills, agents] = await Promise.all([\n client.listByType('skill'),\n client.listDocumentsByType('agent'),\n ]);\n\n const names: string[] = [];\n\n for (const skill of skills) {\n if (skill.title !== null) {\n names.push(skill.title);\n }\n }\n\n for (const agent of agents) {\n names.push(`agent:${agent.title}`);\n }\n\n const prefix = argument.value;\n\n function matchesPrefix(candidate: string): boolean {\n if (prefix.length === 0) {\n return true;\n }\n if (candidate.startsWith(prefix)) {\n return true;\n }\n // For agent-prefixed names, also match against the title portion.\n const AGENT_PREFIX = 'agent:';\n if (candidate.startsWith(AGENT_PREFIX)) {\n return candidate.slice(AGENT_PREFIX.length).startsWith(prefix);\n }\n return false;\n }\n\n const values = names.filter(matchesPrefix);\n\n return {\n completion: {\n values,\n hasMore: false,\n total: values.length,\n },\n };\n}\n", "/**\n * Represents a single file-system root entry advertised to MCP\n * clients via the `roots/list` response.\n */\nexport interface McpRoot {\n /** Absolute file URI for the root directory. */\n readonly uri: string;\n /** Human-readable label for the root. */\n readonly name: string;\n}\n\n/**\n * Returns the list of MCP roots for the given database context path.\n *\n * Produces a single root entry whose URI is `file://` concatenated\n * with the supplied `contextPath`. This tells MCP clients which\n * file-system directory the server is authoritative for.\n *\n * @param contextPath - absolute path to the kbdb database directory\n * @returns array containing a single root for the context path\n */\nexport function handleRootsList(contextPath: string): McpRoot[] {\n return [\n {\n uri: `file://${contextPath}`,\n name: 'kbdb database',\n },\n ];\n}\n", "import type { McpLogLevel } from '../typings/log-types.interface.ts';\n\n/**\n * Ordered list of MCP log severity levels, from least severe\n * (`debug`) to most severe (`emergency`). Used to compare levels\n * when filtering log output.\n */\nexport const LOG_LEVEL_ORDER: McpLogLevel[] = [\n 'debug',\n 'info',\n 'notice',\n 'warning',\n 'error',\n 'critical',\n 'alert',\n 'emergency',\n];\n\n/**\n * Determines whether a log message at `messageLevel` should be\n * emitted when the server's log threshold is `threshold`.\n *\n * Returns `true` when `messageLevel` is at the same severity as\n * `threshold` or higher. Returns `false` when the message level is\n * below the threshold.\n *\n * @param messageLevel - severity of the log message to evaluate\n * @param threshold - minimum severity level required to emit\n * @returns `true` if the message meets or exceeds the threshold\n */\nexport function shouldEmitLog(\n messageLevel: McpLogLevel,\n threshold: McpLogLevel,\n): boolean {\n const messageIndex = LOG_LEVEL_ORDER.indexOf(messageLevel);\n const thresholdIndex = LOG_LEVEL_ORDER.indexOf(threshold);\n return messageIndex >= thresholdIndex;\n}\n", "/**\n * Builds the MCP sampling prompt for knowledge extraction.\n *\n * Instructs the host LLM to identify durable factual knowledge\n * from the recent conversation context, filter out ephemeral or\n * task-specific information, and format the result for storage\n * following memory-protocol criteria.\n *\n * @param recentContext - the conversation excerpt to analyse\n */\nexport function buildCapturePrompt(recentContext: string): string {\n return (\n 'Review the following conversation context and identify' +\n ' factual knowledge worth storing in the knowledge base.\\n\\n' +\n 'Rules:\\n' +\n '- Include durable facts, decisions, preferences, and' +\n ' corrections that would be useful in future sessions.\\n' +\n '- Exclude ephemeral, task-specific, or temporary information' +\n ' that has no lasting value.\\n' +\n '- Format each piece of extracted knowledge as a concise' +\n ' statement suitable for direct storage.\\n' +\n '- If no durable knowledge is found, respond with an empty' +\n ' list.\\n\\n' +\n 'Conversation context:\\n' +\n recentContext\n );\n}\n", "/**\n * Returns `true` when the host advertised the `sampling` capability\n * during MCP initialization.\n *\n * @param hostCapabilities - capabilities object from the MCP\n * `initialize` request, or `null` when not yet set\n */\nexport function hasSamplingCapability(\n hostCapabilities: Record<string, unknown> | null,\n): boolean {\n if (hostCapabilities === null) return false;\n return Boolean(hostCapabilities['sampling']);\n}\n", "import type { AutoCaptureController } from '../../auto-capture/classes/auto-capture-controller.class.ts';\nimport type { AutoCaptureConfig } from '../../auto-capture/typings/auto-capture-config.interface.ts';\nimport { buildCapturePrompt } from '../../auto-capture/functions/build-capture-prompt.function.ts';\nimport { hasSamplingCapability } from './has-sampling-capability.function.ts';\nimport type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\n\n/** Sampling request callback matching McpServer.sendRequest. */\ntype RequestSampling = (\n messages: {\n role: string;\n content: { type: string; text: string };\n }[],\n maxTokens: number,\n) => Promise<unknown>;\n\n/** Shape of a successful sampling response. */\ninterface SamplingResponse {\n readonly content: { readonly type: string; readonly text: string };\n}\n\nfunction isSamplingResponse(v: unknown): v is SamplingResponse {\n if (typeof v !== 'object' || v === null) return false;\n const obj = v as Record<string, unknown>;\n const content = obj['content'];\n if (typeof content !== 'object' || content === null) return false;\n return (\n typeof (content as Record<string, unknown>)['text'] === 'string'\n );\n}\n\n/**\n * Evaluates the auto-capture trigger and, when it fires, sends an\n * MCP sampling request to the host and stores any returned knowledge.\n *\n * Silently ignores all errors so a capture failure never disrupts\n * the MCP server's normal operation.\n *\n * @param controller - tracks session state and evaluates the trigger\n * @param config - auto-capture configuration (provides dryRun flag)\n * @param client - worker client used to persist captured knowledge\n * @param hostCapabilities - capabilities from the MCP host\n * @param requestSampling - sends a sampling request to the host\n */\nexport async function runAutoCapture(\n controller: AutoCaptureController,\n config: AutoCaptureConfig,\n client: McpWorkerClient,\n hostCapabilities: Record<string, unknown> | null,\n requestSampling: RequestSampling,\n): Promise<void> {\n try {\n const trigger = controller.evaluate();\n if (!trigger.shouldCapture) return;\n if (!hasSamplingCapability(hostCapabilities)) return;\n\n const prompt = buildCapturePrompt('recent conversation context');\n const messages = [\n { role: 'user', content: { type: 'text', text: prompt } },\n ];\n const raw = await requestSampling(messages, 1024);\n\n if (!isSamplingResponse(raw)) return;\n const text = raw.content.text.trim();\n if (!text) return;\n if (config.dryRun) return;\n\n await client.addSection({\n sectionType: 'text/markdown',\n content: text,\n title: 'Auto-captured knowledge',\n });\n } catch {\n // Auto-capture errors are non-fatal\n }\n}\n", "import type { AutoCaptureConfig } from '../typings/auto-capture-config.interface.ts';\nimport type { AutoCaptureState } from '../typings/auto-capture-state.interface.ts';\nimport type { AutoCaptureTrigger } from '../typings/auto-capture-trigger.interface.ts';\n\n/**\n * Evaluates whether auto-capture should fire given the current\n * configuration and runtime state.\n *\n * Checks (in order): feature flag, session cap, rate limit,\n * and tool-call count threshold. Returns the first failing\n * condition as the reason.\n */\nexport function evaluateTrigger(\n config: AutoCaptureConfig,\n state: AutoCaptureState,\n): AutoCaptureTrigger {\n if (!config.enabled) {\n return {\n shouldCapture: false,\n reason: 'auto-capture is disabled',\n };\n }\n\n if (state.totalCapturesThisSession >= config.maxCapturesPerSession) {\n return {\n shouldCapture: false,\n reason: 'session capture limit reached',\n };\n }\n\n const elapsed = state.lastCaptureTimestamp\n ? Date.now() - state.lastCaptureTimestamp\n : Infinity;\n\n if (elapsed < config.minIntervalMs) {\n return {\n shouldCapture: false,\n reason: 'within minimum interval',\n };\n }\n\n if (state.toolCallsSinceLastCapture < config.triggerAfterToolCalls) {\n return {\n shouldCapture: false,\n reason: 'tool call threshold not yet reached',\n };\n }\n\n return { shouldCapture: true, reason: 'trigger threshold met' };\n}\n", "import type { AutoCaptureConfig } from '../typings/auto-capture-config.interface.ts';\nimport type { AutoCaptureState } from '../typings/auto-capture-state.interface.ts';\nimport type { AutoCaptureTrigger } from '../typings/auto-capture-trigger.interface.ts';\nimport { evaluateTrigger } from '../functions/evaluate-trigger.function.ts';\n\n/**\n * Controls the auto-capture lifecycle.\n *\n * Tracks tool call counts, evaluates trigger conditions, and\n * advances session state when a capture fires. Reset state on\n * disconnect or session end via `reset()`.\n */\nexport class AutoCaptureController {\n private toolCallsSinceLastCapture = 0;\n private lastCaptureTimestamp = 0;\n private totalCapturesThisSession = 0;\n private readonly config: AutoCaptureConfig;\n\n /** @param config - the auto-capture configuration to use */\n constructor(config: AutoCaptureConfig) {\n this.config = config;\n }\n\n /** Record one tool call for trigger counting. */\n recordToolCall(): void {\n this.toolCallsSinceLastCapture += 1;\n }\n\n /**\n * Evaluates the current state against the trigger criteria.\n *\n * When the trigger fires, advances the session counters so the\n * next evaluation respects rate limiting and the session cap.\n *\n * @returns the trigger decision with a human-readable reason\n */\n evaluate(): AutoCaptureTrigger {\n const trigger = evaluateTrigger(this.config, this.state());\n if (trigger.shouldCapture) {\n this.totalCapturesThisSession += 1;\n this.lastCaptureTimestamp = Date.now();\n this.toolCallsSinceLastCapture = 0;\n }\n return trigger;\n }\n\n /** Reset all counters, e.g. on client disconnect. */\n reset(): void {\n this.toolCallsSinceLastCapture = 0;\n this.lastCaptureTimestamp = 0;\n this.totalCapturesThisSession = 0;\n }\n\n /** Returns a snapshot of the current controller state. */\n state(): AutoCaptureState {\n return {\n toolCallsSinceLastCapture: this.toolCallsSinceLastCapture,\n lastCaptureTimestamp: this.lastCaptureTimestamp,\n totalCapturesThisSession: this.totalCapturesThisSession,\n };\n }\n}\n", "/**\n * JSON-RPC 2.0 parse error code. Returned when the\n * server receives malformed JSON.\n */\nexport const PARSE_ERROR = -32700;\n\n/**\n * JSON-RPC 2.0 method not found error code. Returned\n * when the requested method does not exist.\n */\nexport const METHOD_NOT_FOUND = -32601;\n\n/**\n * JSON-RPC 2.0 invalid params error code. Returned\n * when method parameters are invalid or missing.\n */\nexport const INVALID_PARAMS = -32602;\n\n/**\n * JSON-RPC 2.0 internal error code. Returned when an\n * unexpected server-side error occurs.\n */\nexport const INTERNAL_ERROR = -32603;\n\n/**\n * MCP-specific resource not found error code. Returned\n * when a well-formed URI does not match any resource\n * in the knowledge base.\n */\nexport const RESOURCE_NOT_FOUND = -32002;\n", "import { McpServer } from '../classes/mcp-server.class.ts';\nimport type { McpWorkerClient } from '../typings/mcp-client.interface.ts';\nimport type { AutoCaptureConfig } from '../../auto-capture/typings/auto-capture-config.interface.ts';\n\n/**\n * Factory that constructs a new `McpServer` bound to the given\n * worker client. Call `server.listen()` on the returned instance\n * to start processing stdio input.\n *\n * @param client - worker client providing knowledge-base operations\n * @param contextPath - absolute path to the `.kbdb` directory\n * @param autoCaptureConfig - optional auto-capture configuration;\n * when provided, the server activates auto-capture on client\n * connection and stops it on disconnect\n * @returns a configured `McpServer` ready to listen\n */\nexport function createMcpServer(\n client: McpWorkerClient,\n contextPath?: string,\n autoCaptureConfig?: AutoCaptureConfig,\n clientFactory?: (() => Promise<McpWorkerClient>) | null,\n maxRetries?: number,\n): McpServer {\n return new McpServer(\n client,\n contextPath,\n autoCaptureConfig,\n clientFactory,\n maxRetries,\n );\n}\n", "/** Default maximum number of items held in daemon memory. */\nexport const DEFAULT_ITEM_LIMIT = 1000;\n\n/** Default maximum number of index entries held in daemon memory. */\nexport const DEFAULT_INDEX_LIMIT = 100;\n\n/**\n * Default idle timeout in milliseconds before the daemon shuts\n * down automatically (5 minutes).\n */\nexport const DEFAULT_TIMEOUT_MS = 300_000;\n\n/**\n * Default time-to-live in milliseconds for each cached item\n * (1 minute).\n */\nexport const DEFAULT_ITEM_TTL_MS = 60_000;\n\n/** Filename of the daemon configuration file inside `.kbdb/`. */\nexport const WORKER_TOML_FILENAME = 'worker.toml';\n\n/**\n * Database format version the daemon supports.\n *\n * Read from `catalog.toml` at startup. If the catalog version\n * differs, the daemon prints a structured error to stderr and\n * exits with code 1 before loading any WASM modules.\n */\nexport const DB_FORMAT_VERSION = 1;\n", "import type { EmbeddingConfig } from '../../embedding/typings/embedding-config.interface.ts';\n\n/**\n * Parses key-value pairs from a `[embedding]` TOML section into an\n * `EmbeddingConfig`.\n *\n * Recognises: `provider`, `model`, `endpoint`, `dimensions`.\n * Unknown keys are silently ignored. Returns `undefined` when the\n * `provider` key is absent from the supplied entries.\n *\n * @param entries - key-value pairs from inside the `[embedding]`\n * section\n */\nexport function parseEmbeddingSection(\n entries: ReadonlyMap<string, string>,\n): EmbeddingConfig | undefined {\n const provider = entries.get('provider') as\n | EmbeddingConfig['provider']\n | undefined;\n\n if (!provider) {\n return undefined;\n }\n\n const model = entries.get('model');\n const endpoint = entries.get('endpoint');\n const dimensionsRaw = entries.get('dimensions');\n const dimensions = dimensionsRaw\n ? parseInt(dimensionsRaw, 10) || undefined\n : undefined;\n\n return {\n provider,\n ...(model !== undefined ? { model } : {}),\n ...(endpoint !== undefined ? { endpoint } : {}),\n ...(dimensions !== undefined ? { dimensions } : {}),\n };\n}\n", "import type { AutoCaptureConfig } from '../typings/auto-capture-config.interface.ts';\n\n/**\n * Default configuration for the auto-capture feature.\n *\n * Auto-capture is disabled by default. Enable it in\n * `worker.toml` under `[auto_capture]`.\n */\nexport const AUTO_CAPTURE_DEFAULTS: AutoCaptureConfig = {\n enabled: false,\n triggerAfterToolCalls: 5,\n minIntervalMs: 60_000,\n maxCapturesPerSession: 10,\n dryRun: false,\n};\n", "import type { AutoCaptureConfig } from '../../auto-capture/typings/auto-capture-config.interface.ts';\nimport { AUTO_CAPTURE_DEFAULTS } from '../../auto-capture/constants/auto-capture-defaults.constant.ts';\n\n/**\n * Parses key-value pairs from an `[auto_capture]` TOML section\n * into an `AutoCaptureConfig`.\n *\n * Recognised keys: `enabled`, `trigger_after_tool_calls`,\n * `min_interval_ms`, `max_captures_per_session`, `dry_run`.\n * Unknown keys are silently ignored. Falls back to\n * `AUTO_CAPTURE_DEFAULTS` for any absent key.\n *\n * @param entries - key-value pairs from inside the\n * `[auto_capture]` section\n */\nexport function parseAutoCaptureSection(\n entries: ReadonlyMap<string, string>,\n): AutoCaptureConfig {\n const enabled = entries.has('enabled')\n ? entries.get('enabled') === 'true'\n : AUTO_CAPTURE_DEFAULTS.enabled;\n\n const dryRun = entries.has('dry_run')\n ? entries.get('dry_run') === 'true'\n : AUTO_CAPTURE_DEFAULTS.dryRun;\n\n const triggerRaw = entries.get('trigger_after_tool_calls');\n const triggerAfterToolCalls = triggerRaw\n ? parseInt(triggerRaw, 10) ||\n AUTO_CAPTURE_DEFAULTS.triggerAfterToolCalls\n : AUTO_CAPTURE_DEFAULTS.triggerAfterToolCalls;\n\n const intervalRaw = entries.get('min_interval_ms');\n const minIntervalMs = intervalRaw\n ? parseInt(intervalRaw, 10) || AUTO_CAPTURE_DEFAULTS.minIntervalMs\n : AUTO_CAPTURE_DEFAULTS.minIntervalMs;\n\n const capRaw = entries.get('max_captures_per_session');\n const maxCapturesPerSession = capRaw\n ? parseInt(capRaw, 10) ||\n AUTO_CAPTURE_DEFAULTS.maxCapturesPerSession\n : AUTO_CAPTURE_DEFAULTS.maxCapturesPerSession;\n\n return {\n enabled,\n triggerAfterToolCalls,\n minIntervalMs,\n maxCapturesPerSession,\n dryRun,\n };\n}\n", "import type { DaemonConfig } from '../typings/daemon-config.interface.ts';\nimport {\n DEFAULT_ITEM_LIMIT,\n DEFAULT_INDEX_LIMIT,\n DEFAULT_TIMEOUT_MS,\n DEFAULT_ITEM_TTL_MS,\n} from '../constants/daemon-defaults.constant.ts';\nimport { parseEmbeddingSection } from './parse-embedding-section.function.ts';\nimport { parseAutoCaptureSection } from './parse-auto-capture-section.function.ts';\n\ninterface RootAccum {\n itemLimit: number;\n indexLimit: number;\n timeoutMs: number;\n itemTtlMs: number;\n}\n\nfunction applyRootKey(\n acc: RootAccum,\n key: string,\n value: string,\n): void {\n switch (key) {\n case 'item_limit':\n acc.itemLimit = parseInt(value, 10) || DEFAULT_ITEM_LIMIT;\n break;\n case 'index_limit':\n acc.indexLimit = parseInt(value, 10) || DEFAULT_INDEX_LIMIT;\n break;\n case 'timeout_ms':\n acc.timeoutMs = parseInt(value, 10) || DEFAULT_TIMEOUT_MS;\n break;\n case 'item_ttl_ms':\n acc.itemTtlMs = parseInt(value, 10) || DEFAULT_ITEM_TTL_MS;\n break;\n default:\n break;\n }\n}\n\n/**\n * Parses a `worker.toml` file body into a partial `DaemonConfig`.\n *\n * Handles `[embedding]` sub-sections and root key-value pairs.\n * Unknown keys are silently ignored.\n *\n * @param text - raw content of `worker.toml`\n * @param contextPath - daemon context directory path\n */\nexport function parseWorkerToml(\n text: string,\n contextPath: string,\n): DaemonConfig {\n let section = '';\n const embeddingEntries = new Map<string, string>();\n const autoCaptureEntries = new Map<string, string>();\n const acc: RootAccum = {\n itemLimit: DEFAULT_ITEM_LIMIT,\n indexLimit: DEFAULT_INDEX_LIMIT,\n timeoutMs: DEFAULT_TIMEOUT_MS,\n itemTtlMs: DEFAULT_ITEM_TTL_MS,\n };\n\n for (const line of text.split('\\n')) {\n const trimmed = line.trim();\n if (trimmed === '[embedding]') {\n section = 'embedding';\n continue;\n }\n if (trimmed === '[auto_capture]') {\n section = 'auto_capture';\n continue;\n }\n if (trimmed.startsWith('[')) {\n section = '';\n continue;\n }\n if (trimmed.startsWith('#') || !trimmed.includes('=')) continue;\n const eqIdx = trimmed.indexOf('=');\n const key = trimmed.slice(0, eqIdx).trim();\n const value = trimmed.slice(eqIdx + 1).trim();\n if (section === 'embedding') {\n embeddingEntries.set(key, value);\n continue;\n }\n if (section === 'auto_capture') {\n autoCaptureEntries.set(key, value);\n continue;\n }\n applyRootKey(acc, key, value);\n }\n\n const embedding = parseEmbeddingSection(embeddingEntries);\n const autoCapture =\n autoCaptureEntries.size > 0\n ? parseAutoCaptureSection(autoCaptureEntries)\n : undefined;\n return {\n contextPath,\n ...acc,\n ...(embedding !== undefined ? { embedding } : {}),\n ...(autoCapture !== undefined ? { autoCapture } : {}),\n };\n}\n"],
5
+ "mappings": ";;;;AASA,IAAAA,kBAA6B;AAC7B,IAAAC,qBAAqB;;;ACFd,SAAS,gBAAyB;AACtC,MAAI,OAAO,eAAe,eAAe,UAAU,YAAY;AAC5D,WAAO;AAAA,EACV;AACA,SAAO;AACV;;;ACLO,SAAS,UAAoB;AACjC,MAAI,cAAc,MAAM,QAAQ;AAC7B,UAAM,IAAI;AACV,UAAM,OAAO,EAAE,MAAM;AACrB,WAAO,MAAM,QAAQ,CAAC;AAAA,EACzB;AACA,SAAO,QAAQ,KAAK,MAAM,CAAC;AAC9B;;;ACfA,uBAAwB;AACxB,sBAA8B;AAIvB,SAAS,iBACb,UACA,cACO;AACP,MAAI,aAAc,QAAO;AACzB,MAAI,SAAS,WAAW,OAAO;AAC5B,eAAO,8BAAQ,+BAAc,QAAQ,CAAC;AACzC,aAAO,0BAAQ,QAAQ;AAC1B;AAEO,SAAS,eACb,UACA,cACQ;AACR,QAA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,EACA,aAAa,MAAM,QAAQ,OAAO;AAAA,EAClC;AAAA,EACA,oBAAoB,CAAC,SAClB,mBAAmB,EAAE,GAAG,MAAM,aAAa,CAAC;AAAA,EAC/C;AAAA,EACA;AAAA,EACA,gBAAgB,OAAO,aAAa,eAAe,eAAe;AAC/D,UAAM,SAAS,MAAM,mBAAmB;AAAA,MACrC;AAAA,MACA;AAAA,IACH,CAAC;AACD,QAAI;AACD,YAAM,eAAW,yBAAK,aAAa,aAAa;AAChD,UAAI;AACJ,UAAI;AACD,cAAM,eAAW,8BAAa,UAAU,OAAO;AAC/C,cAAM,eAAe,gBAAgB,UAAU,WAAW;AAC1D,4BAAoB,aAAa;AAAA,MACpC,QAAQ;AAAA,MAER;AACA,YAAM,SAAS;AAAA,QACZ;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QAGA;AAAA,MACH;AACA,YAAM,OAAO,OAAO;AAAA,IACvB,UAAE;AACC,aAAO,WAAW;AAAA,IACrB;AAAA,EACH;AACH;AAEA,eAAe,OAAsB;AAClC,QAAM,SAAS,MAAM,OAAO,QAAQ,GAAG,IAAI;AAC3C,MAAI,OAAO,QAAQ;AAEhB,YAAQ,IAAI,OAAO,MAAM;AAAA,EAC5B;AACA,MAAI,OAAO,OAAO;AAEf,YAAQ,MAAM,OAAO,KAAK;AAAA,EAC7B;AACA,MAAI,OAAO,aAAa,GAAG;AACxB,YAAQ,WAAW,OAAO;AAAA,EAC7B;AACH;AAEA,KAAK,EAAE,MAAM,CAAC,QAAiB;AAC5B,QAAM,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAE3D,UAAQ,MAAM,UAAU,GAAG,EAAE;AAC7B,UAAQ,WAAW;AACtB,CAAC;",
6
+ "names": ["import_node_fs", "import_node_path", "import_node_path", "runtime", "import_node_path", "resolve", "import_node_fs", "import_node_path", "candidate", "import_node_fs", "import_node_path", "import_node_fs", "import_node_path", "resolve", "desc", "resolve", "import_node_fs", "import_node_path", "import_node_os", "import_node_fs", "import_node_path", "import_node_fs", "import_node_path", "runtime", "workerScript", "import_node_fs", "import_node_path", "import_node_os", "import_node_path", "import_node_os", "runtime", "deps", "import_node_readline", "readAgentMeta", "handleRecall", "asString", "asStringArray", "handleSearch", "handleLearn", "handleUnlearn", "handleRecall", "handleStatus", "handleContent", "handleCheck", "handleGc", "handleRebuild", "handleExport", "resolve", "DEFAULT_TIMEOUT_MS", "DEFAULT_TIMEOUT_MS"]
7
7
  }