@dirgha/code 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (360) hide show
  1. package/LICENSE +101 -0
  2. package/README.md +674 -0
  3. package/dist/dirgha.mjs +2185 -0
  4. package/dist_v2/acp/index.d.ts +1 -0
  5. package/dist_v2/acp/index.js +2 -0
  6. package/dist_v2/acp/server.d.ts +31 -0
  7. package/dist_v2/acp/server.js +137 -0
  8. package/dist_v2/cli/auth-cmd.d.ts +10 -0
  9. package/dist_v2/cli/auth-cmd.js +69 -0
  10. package/dist_v2/cli/config.d.ts +46 -0
  11. package/dist_v2/cli/config.js +70 -0
  12. package/dist_v2/cli/flags.d.ts +10 -0
  13. package/dist_v2/cli/flags.js +49 -0
  14. package/dist_v2/cli/flows/full-cycle.d.ts +30 -0
  15. package/dist_v2/cli/flows/full-cycle.js +39 -0
  16. package/dist_v2/cli/flows/index.d.ts +2 -0
  17. package/dist_v2/cli/flows/index.js +3 -0
  18. package/dist_v2/cli/flows/tarball.d.ts +10 -0
  19. package/dist_v2/cli/flows/tarball.js +47 -0
  20. package/dist_v2/cli/index.d.ts +4 -0
  21. package/dist_v2/cli/index.js +5 -0
  22. package/dist_v2/cli/interactive.d.ts +21 -0
  23. package/dist_v2/cli/interactive.js +207 -0
  24. package/dist_v2/cli/main.d.ts +10 -0
  25. package/dist_v2/cli/main.js +173 -0
  26. package/dist_v2/cli/models-cmd.d.ts +6 -0
  27. package/dist_v2/cli/models-cmd.js +50 -0
  28. package/dist_v2/cli/setup.d.ts +13 -0
  29. package/dist_v2/cli/setup.js +128 -0
  30. package/dist_v2/cli/slash/account.d.ts +10 -0
  31. package/dist_v2/cli/slash/account.js +59 -0
  32. package/dist_v2/cli/slash/clear.d.ts +8 -0
  33. package/dist_v2/cli/slash/clear.js +15 -0
  34. package/dist_v2/cli/slash/compact.d.ts +7 -0
  35. package/dist_v2/cli/slash/compact.js +13 -0
  36. package/dist_v2/cli/slash/config.d.ts +8 -0
  37. package/dist_v2/cli/slash/config.js +49 -0
  38. package/dist_v2/cli/slash/exit.d.ts +7 -0
  39. package/dist_v2/cli/slash/exit.js +16 -0
  40. package/dist_v2/cli/slash/fleet.d.ts +7 -0
  41. package/dist_v2/cli/slash/fleet.js +22 -0
  42. package/dist_v2/cli/slash/help.d.ts +9 -0
  43. package/dist_v2/cli/slash/help.js +31 -0
  44. package/dist_v2/cli/slash/history.d.ts +7 -0
  45. package/dist_v2/cli/slash/history.js +42 -0
  46. package/dist_v2/cli/slash/index.d.ts +30 -0
  47. package/dist_v2/cli/slash/index.js +52 -0
  48. package/dist_v2/cli/slash/init.d.ts +8 -0
  49. package/dist_v2/cli/slash/init.js +57 -0
  50. package/dist_v2/cli/slash/keys.d.ts +8 -0
  51. package/dist_v2/cli/slash/keys.js +101 -0
  52. package/dist_v2/cli/slash/login.d.ts +10 -0
  53. package/dist_v2/cli/slash/login.js +47 -0
  54. package/dist_v2/cli/slash/memory.d.ts +8 -0
  55. package/dist_v2/cli/slash/memory.js +101 -0
  56. package/dist_v2/cli/slash/mode.d.ts +8 -0
  57. package/dist_v2/cli/slash/mode.js +30 -0
  58. package/dist_v2/cli/slash/models.d.ts +8 -0
  59. package/dist_v2/cli/slash/models.js +73 -0
  60. package/dist_v2/cli/slash/resume.d.ts +8 -0
  61. package/dist_v2/cli/slash/resume.js +24 -0
  62. package/dist_v2/cli/slash/session.d.ts +8 -0
  63. package/dist_v2/cli/slash/session.js +74 -0
  64. package/dist_v2/cli/slash/setup.d.ts +8 -0
  65. package/dist_v2/cli/slash/setup.js +50 -0
  66. package/dist_v2/cli/slash/status.d.ts +7 -0
  67. package/dist_v2/cli/slash/status.js +37 -0
  68. package/dist_v2/cli/slash/theme.d.ts +9 -0
  69. package/dist_v2/cli/slash/theme.js +53 -0
  70. package/dist_v2/cli/slash/types.d.ts +14 -0
  71. package/dist_v2/cli/slash/types.js +9 -0
  72. package/dist_v2/cli/slash/upgrade.d.ts +9 -0
  73. package/dist_v2/cli/slash/upgrade.js +66 -0
  74. package/dist_v2/cli/slash.d.ts +72 -0
  75. package/dist_v2/cli/slash.js +77 -0
  76. package/dist_v2/cli/subcommands/ask.d.ts +17 -0
  77. package/dist_v2/cli/subcommands/ask.js +76 -0
  78. package/dist_v2/cli/subcommands/audit.d.ts +15 -0
  79. package/dist_v2/cli/subcommands/audit.js +128 -0
  80. package/dist_v2/cli/subcommands/chat.d.ts +13 -0
  81. package/dist_v2/cli/subcommands/chat.js +72 -0
  82. package/dist_v2/cli/subcommands/compact.d.ts +14 -0
  83. package/dist_v2/cli/subcommands/compact.js +114 -0
  84. package/dist_v2/cli/subcommands/doctor.d.ts +11 -0
  85. package/dist_v2/cli/subcommands/doctor.js +103 -0
  86. package/dist_v2/cli/subcommands/export-session.d.ts +10 -0
  87. package/dist_v2/cli/subcommands/export-session.js +60 -0
  88. package/dist_v2/cli/subcommands/import-session.d.ts +11 -0
  89. package/dist_v2/cli/subcommands/import-session.js +77 -0
  90. package/dist_v2/cli/subcommands/index.d.ts +40 -0
  91. package/dist_v2/cli/subcommands/index.js +38 -0
  92. package/dist_v2/cli/subcommands/init.d.ts +10 -0
  93. package/dist_v2/cli/subcommands/init.js +74 -0
  94. package/dist_v2/cli/subcommands/keys.d.ts +12 -0
  95. package/dist_v2/cli/subcommands/keys.js +136 -0
  96. package/dist_v2/cli/subcommands/login.d.ts +10 -0
  97. package/dist_v2/cli/subcommands/login.js +60 -0
  98. package/dist_v2/cli/subcommands/logout.d.ts +10 -0
  99. package/dist_v2/cli/subcommands/logout.js +21 -0
  100. package/dist_v2/cli/subcommands/models.d.ts +14 -0
  101. package/dist_v2/cli/subcommands/models.js +144 -0
  102. package/dist_v2/cli/subcommands/setup.d.ts +11 -0
  103. package/dist_v2/cli/subcommands/setup.js +107 -0
  104. package/dist_v2/cli/subcommands/stats.d.ts +13 -0
  105. package/dist_v2/cli/subcommands/stats.js +148 -0
  106. package/dist_v2/cli/subcommands/status.d.ts +14 -0
  107. package/dist_v2/cli/subcommands/status.js +91 -0
  108. package/dist_v2/cli/submit-paper.d.ts +15 -0
  109. package/dist_v2/cli/submit-paper.js +68 -0
  110. package/dist_v2/context/_fts.d.ts +62 -0
  111. package/dist_v2/context/_fts.js +195 -0
  112. package/dist_v2/context/branch.d.ts +18 -0
  113. package/dist_v2/context/branch.js +66 -0
  114. package/dist_v2/context/compaction.d.ts +26 -0
  115. package/dist_v2/context/compaction.js +120 -0
  116. package/dist_v2/context/index.d.ts +5 -0
  117. package/dist_v2/context/index.js +6 -0
  118. package/dist_v2/context/knowledge.d.ts +38 -0
  119. package/dist_v2/context/knowledge.js +146 -0
  120. package/dist_v2/context/memory.d.ts +80 -0
  121. package/dist_v2/context/memory.js +276 -0
  122. package/dist_v2/context/mode.d.ts +25 -0
  123. package/dist_v2/context/mode.js +81 -0
  124. package/dist_v2/context/session.d.ts +56 -0
  125. package/dist_v2/context/session.js +108 -0
  126. package/dist_v2/daemon/index.d.ts +2 -0
  127. package/dist_v2/daemon/index.js +3 -0
  128. package/dist_v2/daemon/protocol.d.ts +73 -0
  129. package/dist_v2/daemon/protocol.js +6 -0
  130. package/dist_v2/daemon/server.d.ts +35 -0
  131. package/dist_v2/daemon/server.js +191 -0
  132. package/dist_v2/eval/index.d.ts +5 -0
  133. package/dist_v2/eval/index.js +6 -0
  134. package/dist_v2/eval/regression.d.ts +14 -0
  135. package/dist_v2/eval/regression.js +106 -0
  136. package/dist_v2/eval/reporter.d.ts +7 -0
  137. package/dist_v2/eval/reporter.js +34 -0
  138. package/dist_v2/eval/swe-bench.d.ts +18 -0
  139. package/dist_v2/eval/swe-bench.js +23 -0
  140. package/dist_v2/eval/terminal-bench.d.ts +13 -0
  141. package/dist_v2/eval/terminal-bench.js +19 -0
  142. package/dist_v2/eval/types.d.ts +36 -0
  143. package/dist_v2/eval/types.js +5 -0
  144. package/dist_v2/fleet/apply-back.d.ts +27 -0
  145. package/dist_v2/fleet/apply-back.js +191 -0
  146. package/dist_v2/fleet/cli-command.d.ts +61 -0
  147. package/dist_v2/fleet/cli-command.js +329 -0
  148. package/dist_v2/fleet/index.d.ts +21 -0
  149. package/dist_v2/fleet/index.js +21 -0
  150. package/dist_v2/fleet/runner.d.ts +28 -0
  151. package/dist_v2/fleet/runner.js +347 -0
  152. package/dist_v2/fleet/tripleshot.d.ts +21 -0
  153. package/dist_v2/fleet/tripleshot.js +222 -0
  154. package/dist_v2/fleet/types.d.ts +193 -0
  155. package/dist_v2/fleet/types.js +24 -0
  156. package/dist_v2/fleet/worktree.d.ts +51 -0
  157. package/dist_v2/fleet/worktree.js +176 -0
  158. package/dist_v2/hooks/index.d.ts +1 -0
  159. package/dist_v2/hooks/index.js +2 -0
  160. package/dist_v2/hooks/registry.d.ts +21 -0
  161. package/dist_v2/hooks/registry.js +40 -0
  162. package/dist_v2/index.d.ts +12 -0
  163. package/dist_v2/index.js +11 -0
  164. package/dist_v2/integrations/arniko-client.d.ts +42 -0
  165. package/dist_v2/integrations/arniko-client.js +86 -0
  166. package/dist_v2/integrations/auth.d.ts +45 -0
  167. package/dist_v2/integrations/auth.js +54 -0
  168. package/dist_v2/integrations/billing.d.ts +71 -0
  169. package/dist_v2/integrations/billing.js +107 -0
  170. package/dist_v2/integrations/bucky-client.d.ts +105 -0
  171. package/dist_v2/integrations/bucky-client.js +76 -0
  172. package/dist_v2/integrations/deploy-client.d.ts +60 -0
  173. package/dist_v2/integrations/deploy-client.js +87 -0
  174. package/dist_v2/integrations/device-auth.d.ts +48 -0
  175. package/dist_v2/integrations/device-auth.js +192 -0
  176. package/dist_v2/integrations/entitlements.d.ts +34 -0
  177. package/dist_v2/integrations/entitlements.js +43 -0
  178. package/dist_v2/integrations/http.d.ts +22 -0
  179. package/dist_v2/integrations/http.js +114 -0
  180. package/dist_v2/integrations/index.d.ts +8 -0
  181. package/dist_v2/integrations/index.js +15 -0
  182. package/dist_v2/intelligence/cost.d.ts +28 -0
  183. package/dist_v2/intelligence/cost.js +58 -0
  184. package/dist_v2/intelligence/error-classifier.d.ts +8 -0
  185. package/dist_v2/intelligence/error-classifier.js +71 -0
  186. package/dist_v2/intelligence/index.d.ts +5 -0
  187. package/dist_v2/intelligence/index.js +6 -0
  188. package/dist_v2/intelligence/prices.d.ts +13 -0
  189. package/dist_v2/intelligence/prices.js +26 -0
  190. package/dist_v2/intelligence/smart-router.d.ts +21 -0
  191. package/dist_v2/intelligence/smart-router.js +59 -0
  192. package/dist_v2/intelligence/telemetry.d.ts +22 -0
  193. package/dist_v2/intelligence/telemetry.js +31 -0
  194. package/dist_v2/kernel/agent-loop.d.ts +32 -0
  195. package/dist_v2/kernel/agent-loop.js +151 -0
  196. package/dist_v2/kernel/event-stream.d.ts +18 -0
  197. package/dist_v2/kernel/event-stream.js +102 -0
  198. package/dist_v2/kernel/index.d.ts +4 -0
  199. package/dist_v2/kernel/index.js +5 -0
  200. package/dist_v2/kernel/message.d.ts +29 -0
  201. package/dist_v2/kernel/message.js +118 -0
  202. package/dist_v2/kernel/types.d.ts +206 -0
  203. package/dist_v2/kernel/types.js +9 -0
  204. package/dist_v2/mcp/client.d.ts +44 -0
  205. package/dist_v2/mcp/client.js +63 -0
  206. package/dist_v2/mcp/index.d.ts +3 -0
  207. package/dist_v2/mcp/index.js +4 -0
  208. package/dist_v2/mcp/tool-bridge.d.ts +11 -0
  209. package/dist_v2/mcp/tool-bridge.js +33 -0
  210. package/dist_v2/mcp/transport.d.ts +29 -0
  211. package/dist_v2/mcp/transport.js +73 -0
  212. package/dist_v2/parity/index.d.ts +3 -0
  213. package/dist_v2/parity/index.js +4 -0
  214. package/dist_v2/parity/mock-openai-compat.d.ts +15 -0
  215. package/dist_v2/parity/mock-openai-compat.js +35 -0
  216. package/dist_v2/parity/runner.d.ts +21 -0
  217. package/dist_v2/parity/runner.js +76 -0
  218. package/dist_v2/parity/scenarios.d.ts +20 -0
  219. package/dist_v2/parity/scenarios.js +70 -0
  220. package/dist_v2/providers/anthropic.d.ts +21 -0
  221. package/dist_v2/providers/anthropic.js +191 -0
  222. package/dist_v2/providers/dispatch.d.ts +11 -0
  223. package/dist_v2/providers/dispatch.js +45 -0
  224. package/dist_v2/providers/fireworks.d.ts +18 -0
  225. package/dist_v2/providers/fireworks.js +44 -0
  226. package/dist_v2/providers/gemini.d.ts +19 -0
  227. package/dist_v2/providers/gemini.js +188 -0
  228. package/dist_v2/providers/http.d.ts +41 -0
  229. package/dist_v2/providers/http.js +188 -0
  230. package/dist_v2/providers/iface.d.ts +18 -0
  231. package/dist_v2/providers/iface.js +18 -0
  232. package/dist_v2/providers/index.d.ts +39 -0
  233. package/dist_v2/providers/index.js +51 -0
  234. package/dist_v2/providers/nvidia.d.ts +27 -0
  235. package/dist_v2/providers/nvidia.js +142 -0
  236. package/dist_v2/providers/ollama.d.ts +15 -0
  237. package/dist_v2/providers/ollama.js +37 -0
  238. package/dist_v2/providers/openai-compat.d.ts +29 -0
  239. package/dist_v2/providers/openai-compat.js +239 -0
  240. package/dist_v2/providers/openai.d.ts +20 -0
  241. package/dist_v2/providers/openai.js +107 -0
  242. package/dist_v2/providers/openrouter.d.ts +24 -0
  243. package/dist_v2/providers/openrouter.js +69 -0
  244. package/dist_v2/safety/approval-bus.d.ts +26 -0
  245. package/dist_v2/safety/approval-bus.js +48 -0
  246. package/dist_v2/safety/audit-log.d.ts +27 -0
  247. package/dist_v2/safety/audit-log.js +71 -0
  248. package/dist_v2/safety/index.d.ts +4 -0
  249. package/dist_v2/safety/index.js +5 -0
  250. package/dist_v2/safety/policy.d.ts +32 -0
  251. package/dist_v2/safety/policy.js +131 -0
  252. package/dist_v2/safety/sandbox/bwrap.d.ts +11 -0
  253. package/dist_v2/safety/sandbox/bwrap.js +52 -0
  254. package/dist_v2/safety/sandbox/iface.d.ts +29 -0
  255. package/dist_v2/safety/sandbox/iface.js +8 -0
  256. package/dist_v2/safety/sandbox/index.d.ts +7 -0
  257. package/dist_v2/safety/sandbox/index.js +8 -0
  258. package/dist_v2/safety/sandbox/landlock.d.ts +17 -0
  259. package/dist_v2/safety/sandbox/landlock.js +26 -0
  260. package/dist_v2/safety/sandbox/noop.d.ts +12 -0
  261. package/dist_v2/safety/sandbox/noop.js +52 -0
  262. package/dist_v2/safety/sandbox/seatbelt.d.ts +11 -0
  263. package/dist_v2/safety/sandbox/seatbelt.js +49 -0
  264. package/dist_v2/safety/sandbox/select.d.ts +6 -0
  265. package/dist_v2/safety/sandbox/select.js +42 -0
  266. package/dist_v2/safety/sandbox/windows.d.ts +13 -0
  267. package/dist_v2/safety/sandbox/windows.js +22 -0
  268. package/dist_v2/skills/index.d.ts +3 -0
  269. package/dist_v2/skills/index.js +4 -0
  270. package/dist_v2/skills/loader.d.ts +38 -0
  271. package/dist_v2/skills/loader.js +102 -0
  272. package/dist_v2/skills/matcher.d.ts +14 -0
  273. package/dist_v2/skills/matcher.js +72 -0
  274. package/dist_v2/skills/runtime.d.ts +13 -0
  275. package/dist_v2/skills/runtime.js +40 -0
  276. package/dist_v2/subagents/delegator.d.ts +36 -0
  277. package/dist_v2/subagents/delegator.js +82 -0
  278. package/dist_v2/subagents/index.d.ts +2 -0
  279. package/dist_v2/subagents/index.js +3 -0
  280. package/dist_v2/subagents/pool.d.ts +18 -0
  281. package/dist_v2/subagents/pool.js +31 -0
  282. package/dist_v2/tools/browser.d.ts +27 -0
  283. package/dist_v2/tools/browser.js +179 -0
  284. package/dist_v2/tools/checkpoint.d.ts +25 -0
  285. package/dist_v2/tools/checkpoint.js +222 -0
  286. package/dist_v2/tools/cron.d.ts +32 -0
  287. package/dist_v2/tools/cron.js +160 -0
  288. package/dist_v2/tools/diff.d.ts +18 -0
  289. package/dist_v2/tools/diff.js +117 -0
  290. package/dist_v2/tools/exec.d.ts +19 -0
  291. package/dist_v2/tools/exec.js +49 -0
  292. package/dist_v2/tools/fs-edit.d.ts +11 -0
  293. package/dist_v2/tools/fs-edit.js +81 -0
  294. package/dist_v2/tools/fs-ls.d.ts +7 -0
  295. package/dist_v2/tools/fs-ls.js +57 -0
  296. package/dist_v2/tools/fs-read.d.ts +7 -0
  297. package/dist_v2/tools/fs-read.js +60 -0
  298. package/dist_v2/tools/fs-write.d.ts +8 -0
  299. package/dist_v2/tools/fs-write.js +46 -0
  300. package/dist_v2/tools/git.d.ts +8 -0
  301. package/dist_v2/tools/git.js +57 -0
  302. package/dist_v2/tools/index.d.ts +25 -0
  303. package/dist_v2/tools/index.js +39 -0
  304. package/dist_v2/tools/multimodal.d.ts +41 -0
  305. package/dist_v2/tools/multimodal.js +381 -0
  306. package/dist_v2/tools/permission.d.ts +27 -0
  307. package/dist_v2/tools/permission.js +43 -0
  308. package/dist_v2/tools/registry.d.ts +44 -0
  309. package/dist_v2/tools/registry.js +62 -0
  310. package/dist_v2/tools/search-glob.d.ts +7 -0
  311. package/dist_v2/tools/search-glob.js +98 -0
  312. package/dist_v2/tools/search-grep.d.ts +7 -0
  313. package/dist_v2/tools/search-grep.js +109 -0
  314. package/dist_v2/tools/shell.d.ts +10 -0
  315. package/dist_v2/tools/shell.js +76 -0
  316. package/dist_v2/tools/task.d.ts +8 -0
  317. package/dist_v2/tools/task.js +37 -0
  318. package/dist_v2/tui/approval.d.ts +7 -0
  319. package/dist_v2/tui/approval.js +55 -0
  320. package/dist_v2/tui/index.d.ts +4 -0
  321. package/dist_v2/tui/index.js +5 -0
  322. package/dist_v2/tui/ink/App.d.ts +39 -0
  323. package/dist_v2/tui/ink/App.js +206 -0
  324. package/dist_v2/tui/ink/components/AtFileComplete.d.ts +25 -0
  325. package/dist_v2/tui/ink/components/AtFileComplete.js +158 -0
  326. package/dist_v2/tui/ink/components/HelpOverlay.d.ts +24 -0
  327. package/dist_v2/tui/ink/components/HelpOverlay.js +130 -0
  328. package/dist_v2/tui/ink/components/InputBox.d.ts +35 -0
  329. package/dist_v2/tui/ink/components/InputBox.js +153 -0
  330. package/dist_v2/tui/ink/components/Logo.d.ts +12 -0
  331. package/dist_v2/tui/ink/components/Logo.js +27 -0
  332. package/dist_v2/tui/ink/components/ModelPicker.d.ts +26 -0
  333. package/dist_v2/tui/ink/components/ModelPicker.js +80 -0
  334. package/dist_v2/tui/ink/components/PasteCollapse.d.ts +36 -0
  335. package/dist_v2/tui/ink/components/PasteCollapse.js +59 -0
  336. package/dist_v2/tui/ink/components/StatusBar.d.ts +18 -0
  337. package/dist_v2/tui/ink/components/StatusBar.js +41 -0
  338. package/dist_v2/tui/ink/components/StreamingText.d.ts +14 -0
  339. package/dist_v2/tui/ink/components/StreamingText.js +11 -0
  340. package/dist_v2/tui/ink/components/ThinkingBlock.d.ts +13 -0
  341. package/dist_v2/tui/ink/components/ThinkingBlock.js +13 -0
  342. package/dist_v2/tui/ink/components/ToolBox.d.ts +20 -0
  343. package/dist_v2/tui/ink/components/ToolBox.js +63 -0
  344. package/dist_v2/tui/ink/components/vim-bindings.d.ts +43 -0
  345. package/dist_v2/tui/ink/components/vim-bindings.js +135 -0
  346. package/dist_v2/tui/ink/index.d.ts +39 -0
  347. package/dist_v2/tui/ink/index.js +47 -0
  348. package/dist_v2/tui/ink/use-event-projection.d.ts +51 -0
  349. package/dist_v2/tui/ink/use-event-projection.js +126 -0
  350. package/dist_v2/tui/ink/use-overlays.d.ts +24 -0
  351. package/dist_v2/tui/ink/use-overlays.js +50 -0
  352. package/dist_v2/tui/renderer.d.ts +19 -0
  353. package/dist_v2/tui/renderer.js +64 -0
  354. package/dist_v2/tui/status-bar.d.ts +12 -0
  355. package/dist_v2/tui/status-bar.js +16 -0
  356. package/dist_v2/tui/theme.d.ts +27 -0
  357. package/dist_v2/tui/theme.js +56 -0
  358. package/dist_v2/utils/json-repair.d.ts +7 -0
  359. package/dist_v2/utils/json-repair.js +45 -0
  360. package/package.json +113 -0
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Optional SQLite FTS5 index, shared by memory and knowledge stores.
3
+ *
4
+ * This module is a thin best-effort wrapper around better-sqlite3's FTS5
5
+ * virtual table. It never throws on the happy path: if the native binary
6
+ * or FTS5 extension is unavailable, `openFtsIndex` returns `null` and
7
+ * callers fall back to their naive substring scan.
8
+ *
9
+ * Keeping FTS logic in one place lets `memory.ts` and `knowledge.ts`
10
+ * stay focused on their file-backed record contracts without each
11
+ * growing its own sqlite boilerplate.
12
+ */
13
+ export interface FtsDoc {
14
+ /** Primary key in the docs table. */
15
+ id: string;
16
+ /** Short title / headline. Indexed and returned in hits. */
17
+ title: string;
18
+ /** Main searchable body. Indexed but only snippets returned. */
19
+ body: string;
20
+ /** Optional comma-joined tag list. Indexed. */
21
+ tags?: string;
22
+ }
23
+ export interface FtsHit {
24
+ id: string;
25
+ title: string;
26
+ snippet: string;
27
+ score: number;
28
+ }
29
+ export interface FtsIndex {
30
+ upsert(doc: FtsDoc): void;
31
+ remove(id: string): void;
32
+ search(query: string, limit: number): FtsHit[];
33
+ close(): void;
34
+ }
35
+ export interface OpenFtsOptions {
36
+ /** Absolute path to the sqlite file. Parent directory is auto-created. */
37
+ dbPath: string;
38
+ /** Table name prefix. Two tables are created: `${ns}_docs`, `${ns}_fts`. */
39
+ namespace: string;
40
+ }
41
+ /**
42
+ * Try to open (or create) an FTS5 index. Returns `null` if the native
43
+ * binary or FTS5 virtual table cannot be initialised; callers should
44
+ * treat `null` as "no index available, use naive search".
45
+ */
46
+ export declare function openFtsIndex(opts: OpenFtsOptions): Promise<FtsIndex | null>;
47
+ /**
48
+ * FTS5 MATCH queries reject most punctuation and raw apostrophes. We
49
+ * strip everything that isn't a letter/digit/space and quote remaining
50
+ * tokens. Empty output means "no useful query"; callers should bail.
51
+ */
52
+ export declare function sanitizeFtsQuery(input: string): string;
53
+ /**
54
+ * Naive fallback: case-insensitive substring search with a coarse score.
55
+ * Used when the FTS index cannot be opened.
56
+ */
57
+ export declare function fallbackSearch<T extends {
58
+ id: string;
59
+ title: string;
60
+ body: string;
61
+ tags?: string;
62
+ }>(docs: T[], query: string, limit: number): FtsHit[];
@@ -0,0 +1,195 @@
1
+ /**
2
+ * Optional SQLite FTS5 index, shared by memory and knowledge stores.
3
+ *
4
+ * This module is a thin best-effort wrapper around better-sqlite3's FTS5
5
+ * virtual table. It never throws on the happy path: if the native binary
6
+ * or FTS5 extension is unavailable, `openFtsIndex` returns `null` and
7
+ * callers fall back to their naive substring scan.
8
+ *
9
+ * Keeping FTS logic in one place lets `memory.ts` and `knowledge.ts`
10
+ * stay focused on their file-backed record contracts without each
11
+ * growing its own sqlite boilerplate.
12
+ */
13
+ import { mkdir, stat } from 'node:fs/promises';
14
+ import { dirname } from 'node:path';
15
+ import { createRequire } from 'node:module';
16
+ /**
17
+ * Try to open (or create) an FTS5 index. Returns `null` if the native
18
+ * binary or FTS5 virtual table cannot be initialised; callers should
19
+ * treat `null` as "no index available, use naive search".
20
+ */
21
+ export async function openFtsIndex(opts) {
22
+ const Ctor = loadBetterSqlite3();
23
+ if (!Ctor)
24
+ return null;
25
+ await ensureDir(dirname(opts.dbPath));
26
+ let db;
27
+ try {
28
+ db = new Ctor(opts.dbPath);
29
+ db.pragma('journal_mode = WAL');
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ const docsTable = `${opts.namespace}_docs`;
35
+ const ftsTable = `${opts.namespace}_fts`;
36
+ try {
37
+ db.exec(`
38
+ CREATE TABLE IF NOT EXISTS ${docsTable} (
39
+ id TEXT PRIMARY KEY,
40
+ title TEXT NOT NULL,
41
+ body TEXT NOT NULL,
42
+ tags TEXT NOT NULL DEFAULT '',
43
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
44
+ );
45
+ CREATE VIRTUAL TABLE IF NOT EXISTS ${ftsTable}
46
+ USING fts5(id UNINDEXED, title, body, tags, tokenize='porter unicode61');
47
+ `);
48
+ }
49
+ catch {
50
+ try {
51
+ db.close();
52
+ }
53
+ catch { /* ignore */ }
54
+ return null;
55
+ }
56
+ const stmts = {
57
+ deleteDoc: db.prepare(`DELETE FROM ${docsTable} WHERE id = ?`),
58
+ deleteFts: db.prepare(`DELETE FROM ${ftsTable} WHERE id = ?`),
59
+ insertDoc: db.prepare(`INSERT INTO ${docsTable}(id, title, body, tags, updated_at)
60
+ VALUES (?, ?, ?, ?, datetime('now'))
61
+ ON CONFLICT(id) DO UPDATE SET
62
+ title = excluded.title,
63
+ body = excluded.body,
64
+ tags = excluded.tags,
65
+ updated_at = excluded.updated_at`),
66
+ insertFts: db.prepare(`INSERT INTO ${ftsTable}(id, title, body, tags) VALUES (?, ?, ?, ?)`),
67
+ search: db.prepare(`SELECT id, title,
68
+ snippet(${ftsTable}, 2, '[', ']', '…', 12) AS snippet,
69
+ bm25(${ftsTable}) AS score
70
+ FROM ${ftsTable}
71
+ WHERE ${ftsTable} MATCH ?
72
+ ORDER BY score
73
+ LIMIT ?`),
74
+ };
75
+ const index = {
76
+ upsert(doc) {
77
+ const tags = doc.tags ?? '';
78
+ try {
79
+ stmts.deleteFts.run(doc.id);
80
+ stmts.insertDoc.run(doc.id, doc.title, doc.body, tags);
81
+ stmts.insertFts.run(doc.id, doc.title, doc.body, tags);
82
+ }
83
+ catch { /* swallow — index is best-effort */ }
84
+ },
85
+ remove(id) {
86
+ try {
87
+ stmts.deleteDoc.run(id);
88
+ stmts.deleteFts.run(id);
89
+ }
90
+ catch { /* swallow */ }
91
+ },
92
+ search(query, limit) {
93
+ const safe = sanitizeFtsQuery(query);
94
+ if (!safe)
95
+ return [];
96
+ let rows;
97
+ try {
98
+ rows = stmts.search.all(safe, Math.max(1, limit));
99
+ }
100
+ catch {
101
+ return [];
102
+ }
103
+ const hits = [];
104
+ for (const row of rows) {
105
+ const r = row;
106
+ if (typeof r.id !== 'string' || typeof r.title !== 'string')
107
+ continue;
108
+ hits.push({
109
+ id: r.id,
110
+ title: r.title,
111
+ snippet: typeof r.snippet === 'string' ? r.snippet : '',
112
+ score: typeof r.score === 'number' ? r.score : 0,
113
+ });
114
+ }
115
+ return hits;
116
+ },
117
+ close() {
118
+ try {
119
+ db.close();
120
+ }
121
+ catch { /* ignore */ }
122
+ },
123
+ };
124
+ return index;
125
+ }
126
+ /**
127
+ * Lazily resolve the better-sqlite3 constructor. Returns `null` when
128
+ * the module is missing or the native binary fails to load (e.g. wrong
129
+ * ABI) so callers can degrade gracefully instead of crashing.
130
+ */
131
+ function loadBetterSqlite3() {
132
+ try {
133
+ const req = createRequire(import.meta.url);
134
+ const mod = req('better-sqlite3');
135
+ // CJS default export: module.exports = Database
136
+ if (typeof mod === 'function')
137
+ return mod;
138
+ if (mod && typeof mod.default === 'function') {
139
+ return mod.default;
140
+ }
141
+ return null;
142
+ }
143
+ catch {
144
+ return null;
145
+ }
146
+ }
147
+ async function ensureDir(path) {
148
+ const info = await stat(path).catch(() => undefined);
149
+ if (!info)
150
+ await mkdir(path, { recursive: true });
151
+ }
152
+ /**
153
+ * FTS5 MATCH queries reject most punctuation and raw apostrophes. We
154
+ * strip everything that isn't a letter/digit/space and quote remaining
155
+ * tokens. Empty output means "no useful query"; callers should bail.
156
+ */
157
+ export function sanitizeFtsQuery(input) {
158
+ const cleaned = input
159
+ .replace(/[^\p{L}\p{N}\s]+/gu, ' ')
160
+ .split(/\s+/)
161
+ .map(s => s.trim())
162
+ .filter(s => s.length >= 2);
163
+ if (cleaned.length === 0)
164
+ return '';
165
+ return cleaned.map(t => `"${t}"`).join(' OR ');
166
+ }
167
+ /**
168
+ * Naive fallback: case-insensitive substring search with a coarse score.
169
+ * Used when the FTS index cannot be opened.
170
+ */
171
+ export function fallbackSearch(docs, query, limit) {
172
+ const needle = query.toLowerCase().trim();
173
+ if (!needle)
174
+ return [];
175
+ const hits = [];
176
+ for (const doc of docs) {
177
+ const hay = `${doc.title}\n${doc.tags ?? ''}\n${doc.body}`.toLowerCase();
178
+ const idx = hay.indexOf(needle);
179
+ if (idx < 0)
180
+ continue;
181
+ const start = Math.max(0, idx - 24);
182
+ const end = Math.min(hay.length, idx + needle.length + 24);
183
+ // Scoring: earlier hits rank higher; title hits beat body hits.
184
+ const score = (doc.title.toLowerCase().includes(needle) ? -10 : 0) + idx;
185
+ hits.push({
186
+ id: doc.id,
187
+ title: doc.title,
188
+ snippet: `${idx > 0 ? '…' : ''}${doc.body.slice(start, end)}…`,
189
+ score,
190
+ });
191
+ }
192
+ hits.sort((a, b) => a.score - b.score);
193
+ return hits.slice(0, Math.max(1, limit));
194
+ }
195
+ //# sourceMappingURL=_fts.js.map
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Session branching: create a new session whose first message is a
3
+ * summary of the parent, so the child inherits context without dragging
4
+ * the full parent transcript. Branch metadata is logged to both parent
5
+ * and child.
6
+ */
7
+ import type { Provider } from '../kernel/types.js';
8
+ import type { Session, SessionStore } from './session.js';
9
+ export interface BranchOptions {
10
+ name: string;
11
+ summarizer: Provider;
12
+ summaryModel: string;
13
+ }
14
+ export interface BranchResult {
15
+ child: Session;
16
+ summary: string;
17
+ }
18
+ export declare function branchSession(parent: Session, store: SessionStore, opts: BranchOptions): Promise<BranchResult>;
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Session branching: create a new session whose first message is a
3
+ * summary of the parent, so the child inherits context without dragging
4
+ * the full parent transcript. Branch metadata is logged to both parent
5
+ * and child.
6
+ */
7
+ import { randomUUID } from 'node:crypto';
8
+ export async function branchSession(parent, store, opts) {
9
+ const parentMessages = await parent.messages();
10
+ const summary = await summariseParent(opts.summarizer, opts.summaryModel, parentMessages);
11
+ const childId = `${parent.id}-${opts.name}-${randomUUID().slice(0, 8)}`;
12
+ const child = await store.create(childId);
13
+ const ts = new Date().toISOString();
14
+ await child.append({ type: 'branch', ts, parentId: parent.id, name: opts.name });
15
+ await child.append({
16
+ type: 'message',
17
+ ts,
18
+ message: {
19
+ role: 'user',
20
+ content: [
21
+ {
22
+ type: 'text',
23
+ text: `[Branched from session ${parent.id} (${opts.name})]\n${summary}\n[End parent summary]`,
24
+ },
25
+ ],
26
+ },
27
+ });
28
+ await parent.append({ type: 'branch', ts, parentId: parent.id, name: opts.name });
29
+ return { child, summary };
30
+ }
31
+ async function summariseParent(provider, model, messages) {
32
+ if (messages.length === 0)
33
+ return '[Empty parent session]';
34
+ const transcript = messages.map(renderMessage).join('\n\n');
35
+ const prompt = [
36
+ {
37
+ role: 'system',
38
+ content: 'Summarise this conversation so that a resuming agent has enough context to continue. Keep decisions, file paths, tool outcomes, and open questions. Omit pleasantries.',
39
+ },
40
+ {
41
+ role: 'user',
42
+ content: `Summarise below in plain text under ~600 tokens.\n\n${transcript}`,
43
+ },
44
+ ];
45
+ let out = '';
46
+ for await (const ev of provider.stream({ model, messages: prompt })) {
47
+ if (ev.type === 'text_delta')
48
+ out += ev.delta;
49
+ }
50
+ return out.trim() || '[Empty summary]';
51
+ }
52
+ function renderMessage(msg) {
53
+ const text = typeof msg.content === 'string'
54
+ ? msg.content
55
+ : msg.content.map(p => {
56
+ if (p.type === 'text' || p.type === 'thinking')
57
+ return p.text;
58
+ if (p.type === 'tool_use')
59
+ return `(tool ${p.name})`;
60
+ if (p.type === 'tool_result')
61
+ return `(result)`;
62
+ return '';
63
+ }).join(' ');
64
+ return `${msg.role}: ${text}`;
65
+ }
66
+ //# sourceMappingURL=branch.js.map
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Context compaction.
3
+ *
4
+ * When the total token estimate of the running history crosses a
5
+ * threshold, summarise the older portion via a provider call and return
6
+ * a trimmed history that contains the system prompt, a synthetic user
7
+ * summary, and the last N preserved turns. A compaction log entry is
8
+ * written to the session so the operation is auditable.
9
+ */
10
+ import type { Provider, Message } from '../kernel/types.js';
11
+ import type { Session } from './session.js';
12
+ export interface CompactionConfig {
13
+ triggerTokens: number;
14
+ preserveLastTurns: number;
15
+ summarizer: Provider;
16
+ summaryModel: string;
17
+ maxSummaryTokens?: number;
18
+ }
19
+ export interface CompactionResult {
20
+ messages: Message[];
21
+ compacted: boolean;
22
+ summary?: string;
23
+ tokensBefore: number;
24
+ tokensAfter: number;
25
+ }
26
+ export declare function maybeCompact(messages: Message[], cfg: CompactionConfig, session?: Session): Promise<CompactionResult>;
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Context compaction.
3
+ *
4
+ * When the total token estimate of the running history crosses a
5
+ * threshold, summarise the older portion via a provider call and return
6
+ * a trimmed history that contains the system prompt, a synthetic user
7
+ * summary, and the last N preserved turns. A compaction log entry is
8
+ * written to the session so the operation is auditable.
9
+ */
10
+ import { estimateTokens, normaliseContent } from '../kernel/message.js';
11
+ export async function maybeCompact(messages, cfg, session) {
12
+ const tokensBefore = messages.reduce((acc, m) => acc + estimateTokens(flatten(m)), 0);
13
+ if (tokensBefore < cfg.triggerTokens) {
14
+ return { messages, compacted: false, tokensBefore, tokensAfter: tokensBefore };
15
+ }
16
+ const { systems, rest } = splitSystems(messages);
17
+ const preserveCount = countPreservedMessages(rest, cfg.preserveLastTurns);
18
+ const historical = rest.slice(0, rest.length - preserveCount);
19
+ const preserved = rest.slice(rest.length - preserveCount);
20
+ if (historical.length === 0) {
21
+ return { messages, compacted: false, tokensBefore, tokensAfter: tokensBefore };
22
+ }
23
+ const summary = await summarise(cfg, historical);
24
+ const trimmed = [
25
+ ...systems,
26
+ {
27
+ role: 'user',
28
+ content: [
29
+ { type: 'text', text: `[Compacted summary of earlier turns]\n${summary}\n[End compacted summary]` },
30
+ ],
31
+ },
32
+ ...preserved,
33
+ ];
34
+ const tokensAfter = trimmed.reduce((acc, m) => acc + estimateTokens(flatten(m)), 0);
35
+ if (session) {
36
+ await session.append({
37
+ type: 'compaction',
38
+ ts: new Date().toISOString(),
39
+ keptFrom: `last-${preserveCount}-messages`,
40
+ summary,
41
+ });
42
+ }
43
+ return { messages: trimmed, compacted: true, summary, tokensBefore, tokensAfter };
44
+ }
45
+ async function summarise(cfg, historical) {
46
+ const transcript = historical.map(renderForSummary).join('\n\n');
47
+ const prompt = [
48
+ {
49
+ role: 'system',
50
+ content: 'You summarise a coding agent conversation. Keep the summary terse, information-dense, ordered by topic. Retain every decision, file path, tool outcome, and open question. Omit greetings and pleasantries. Do not invent facts.',
51
+ },
52
+ {
53
+ role: 'user',
54
+ content: `Summarise the following transcript. Produce a single plain-text summary under ${cfg.maxSummaryTokens ?? 800} tokens.\n\n${transcript}`,
55
+ },
56
+ ];
57
+ let summary = '';
58
+ for await (const ev of cfg.summarizer.stream({ model: cfg.summaryModel, messages: prompt })) {
59
+ if (ev.type === 'text_delta')
60
+ summary += ev.delta;
61
+ }
62
+ return summary.trim() || '[Empty summary]';
63
+ }
64
+ function renderForSummary(msg) {
65
+ const body = normaliseContent(msg).map(p => {
66
+ switch (p.type) {
67
+ case 'text': return p.text;
68
+ case 'thinking': return `(thinking) ${p.text}`;
69
+ case 'tool_use': return `(tool_use ${p.name}: ${truncate(JSON.stringify(p.input), 240)})`;
70
+ case 'tool_result': return `(tool_result ${p.toolUseId}${p.isError ? ' ERROR' : ''}: ${truncate(p.content, 360)})`;
71
+ }
72
+ }).join('\n');
73
+ return `### ${msg.role}\n${body}`;
74
+ }
75
+ function flatten(msg) {
76
+ if (typeof msg.content === 'string')
77
+ return msg.content;
78
+ return msg.content.map(p => {
79
+ if (p.type === 'text')
80
+ return p.text;
81
+ if (p.type === 'thinking')
82
+ return p.text;
83
+ if (p.type === 'tool_use')
84
+ return JSON.stringify(p.input);
85
+ if (p.type === 'tool_result')
86
+ return p.content;
87
+ return '';
88
+ }).join(' ');
89
+ }
90
+ function splitSystems(messages) {
91
+ const systems = [];
92
+ const rest = [];
93
+ for (const m of messages) {
94
+ if (m.role === 'system')
95
+ systems.push(m);
96
+ else
97
+ rest.push(m);
98
+ }
99
+ return { systems, rest };
100
+ }
101
+ function countPreservedMessages(rest, preserveLastTurns) {
102
+ if (preserveLastTurns <= 0)
103
+ return 0;
104
+ let turns = 0;
105
+ let count = 0;
106
+ for (let i = rest.length - 1; i >= 0; i--) {
107
+ count++;
108
+ if (rest[i].role === 'user') {
109
+ turns++;
110
+ if (turns >= preserveLastTurns)
111
+ break;
112
+ }
113
+ }
114
+ return count;
115
+ }
116
+ function truncate(s, max) {
117
+ return s.length <= max ? s : `${s.slice(0, max - 1)}…`;
118
+ }
119
+ void undefined;
120
+ //# sourceMappingURL=compaction.js.map
@@ -0,0 +1,5 @@
1
+ export * from './memory.js';
2
+ export * from './session.js';
3
+ export * from './compaction.js';
4
+ export * from './branch.js';
5
+ export * from './knowledge.js';
@@ -0,0 +1,6 @@
1
+ export * from './memory.js';
2
+ export * from './session.js';
3
+ export * from './compaction.js';
4
+ export * from './branch.js';
5
+ export * from './knowledge.js';
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Wiki-style knowledge base. Read-forward, navigation-first.
3
+ *
4
+ * Articles live as plain Markdown at `~/.dirgha/knowledge/{slug}.md`,
5
+ * optionally indexed by SQLite FTS5 for full-text search. The design
6
+ * is deliberately simpler than v1's multi-stage raw/compile/summary
7
+ * pipeline — a knowledge base is just a folder of markdown files; a
8
+ * compiler agent can write to it the same way a human can.
9
+ *
10
+ * Slugs are derived from the filename (minus `.md`). The first markdown
11
+ * heading, if present, becomes the article's title; the first non-heading
12
+ * paragraph becomes the summary.
13
+ */
14
+ export interface Article {
15
+ slug: string;
16
+ title: string;
17
+ summary: string;
18
+ body: string;
19
+ updatedAt: string;
20
+ }
21
+ export interface ArticleHit {
22
+ slug: string;
23
+ title: string;
24
+ snippet: string;
25
+ score: number;
26
+ }
27
+ export interface KnowledgeStore {
28
+ listArticles(): Promise<string[]>;
29
+ getArticle(slug: string): Promise<Article | null>;
30
+ putArticle(slug: string, body: string): Promise<void>;
31
+ deleteArticle(slug: string): Promise<void>;
32
+ searchArticles(query: string, limit?: number): Promise<ArticleHit[]>;
33
+ }
34
+ export interface KnowledgeStoreOptions {
35
+ directory?: string;
36
+ useFtsIndex?: boolean;
37
+ }
38
+ export declare function createKnowledgeStore(opts?: KnowledgeStoreOptions): KnowledgeStore;
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Wiki-style knowledge base. Read-forward, navigation-first.
3
+ *
4
+ * Articles live as plain Markdown at `~/.dirgha/knowledge/{slug}.md`,
5
+ * optionally indexed by SQLite FTS5 for full-text search. The design
6
+ * is deliberately simpler than v1's multi-stage raw/compile/summary
7
+ * pipeline — a knowledge base is just a folder of markdown files; a
8
+ * compiler agent can write to it the same way a human can.
9
+ *
10
+ * Slugs are derived from the filename (minus `.md`). The first markdown
11
+ * heading, if present, becomes the article's title; the first non-heading
12
+ * paragraph becomes the summary.
13
+ */
14
+ import { readFile, readdir, stat, writeFile, mkdir, unlink } from 'node:fs/promises';
15
+ import { join } from 'node:path';
16
+ import { homedir } from 'node:os';
17
+ import { openFtsIndex, fallbackSearch } from './_fts.js';
18
+ export function createKnowledgeStore(opts = {}) {
19
+ const dir = opts.directory ?? join(homedir(), '.dirgha', 'knowledge');
20
+ return new FileKnowledgeStore(dir, opts.useFtsIndex !== false);
21
+ }
22
+ class FileKnowledgeStore {
23
+ dir;
24
+ ftsEnabled;
25
+ ftsPromise = null;
26
+ constructor(dir, ftsEnabled) {
27
+ this.dir = dir;
28
+ this.ftsEnabled = ftsEnabled;
29
+ }
30
+ async listArticles() {
31
+ await this.ensure();
32
+ const names = await readdir(this.dir).catch(() => []);
33
+ return names
34
+ .filter(n => n.endsWith('.md') && n !== 'INDEX.md')
35
+ .map(n => n.replace(/\.md$/, ''))
36
+ .sort();
37
+ }
38
+ async getArticle(slug) {
39
+ assertValidSlug(slug);
40
+ const abs = this.pathFor(slug);
41
+ const info = await stat(abs).catch(() => undefined);
42
+ if (!info)
43
+ return null;
44
+ const text = await readFile(abs, 'utf8').catch(() => null);
45
+ if (text === null)
46
+ return null;
47
+ return parseArticle(slug, text, info.mtime.toISOString());
48
+ }
49
+ async putArticle(slug, body) {
50
+ assertValidSlug(slug);
51
+ await this.ensure();
52
+ await writeFile(this.pathFor(slug), body, 'utf8');
53
+ const article = parseArticle(slug, body, new Date().toISOString());
54
+ await this.rebuildIndex();
55
+ const fts = await this.fts();
56
+ fts?.upsert({
57
+ id: article.slug,
58
+ title: article.title,
59
+ body: article.body,
60
+ tags: '',
61
+ });
62
+ }
63
+ async deleteArticle(slug) {
64
+ assertValidSlug(slug);
65
+ await unlink(this.pathFor(slug)).catch(() => undefined);
66
+ await this.rebuildIndex();
67
+ const fts = await this.fts();
68
+ fts?.remove(slug);
69
+ }
70
+ async searchArticles(query, limit = 8) {
71
+ const fts = await this.fts();
72
+ if (fts) {
73
+ const hits = fts.search(query, limit);
74
+ if (hits.length > 0) {
75
+ return hits.map(h => ({ slug: h.id, title: h.title, snippet: h.snippet, score: h.score }));
76
+ }
77
+ }
78
+ const slugs = await this.listArticles();
79
+ const docs = [];
80
+ for (const slug of slugs) {
81
+ const article = await this.getArticle(slug);
82
+ if (!article)
83
+ continue;
84
+ docs.push({ id: article.slug, title: article.title, body: article.body });
85
+ }
86
+ return fallbackSearch(docs, query, limit).map(h => ({
87
+ slug: h.id, title: h.title, snippet: h.snippet, score: h.score,
88
+ }));
89
+ }
90
+ pathFor(slug) {
91
+ return join(this.dir, `${slug}.md`);
92
+ }
93
+ async ensure() {
94
+ const info = await stat(this.dir).catch(() => undefined);
95
+ if (!info)
96
+ await mkdir(this.dir, { recursive: true });
97
+ }
98
+ async rebuildIndex() {
99
+ const slugs = await this.listArticles();
100
+ const lines = ['# Knowledge Base', ''];
101
+ for (const slug of slugs) {
102
+ const article = await this.getArticle(slug);
103
+ if (!article)
104
+ continue;
105
+ lines.push(`- [${article.title}](${slug}.md) — ${article.summary.slice(0, 120)}`);
106
+ }
107
+ await writeFile(join(this.dir, 'INDEX.md'), `${lines.join('\n')}\n`, 'utf8');
108
+ }
109
+ fts() {
110
+ if (!this.ftsEnabled)
111
+ return Promise.resolve(null);
112
+ if (!this.ftsPromise) {
113
+ this.ftsPromise = openFtsIndex({
114
+ dbPath: join(this.dir, 'index.db'),
115
+ namespace: 'knowledge',
116
+ });
117
+ }
118
+ return this.ftsPromise;
119
+ }
120
+ }
121
+ function parseArticle(slug, body, updatedAt) {
122
+ const title = firstHeading(body) ?? slug;
123
+ const summary = firstParagraph(body) ?? '';
124
+ return { slug, title, summary, body, updatedAt };
125
+ }
126
+ function firstHeading(text) {
127
+ const m = text.match(/^\s*#+\s+(.+?)\s*$/m);
128
+ return m ? m[1] : null;
129
+ }
130
+ function firstParagraph(text) {
131
+ for (const block of text.split(/\n\s*\n/)) {
132
+ const line = block.trim();
133
+ if (!line)
134
+ continue;
135
+ if (line.startsWith('#'))
136
+ continue;
137
+ return line.replace(/\s+/g, ' ');
138
+ }
139
+ return null;
140
+ }
141
+ function assertValidSlug(slug) {
142
+ if (!slug || !/^[a-zA-Z0-9][a-zA-Z0-9_\-\.]*$/.test(slug)) {
143
+ throw new Error(`Invalid knowledge slug "${slug}". Use alphanumeric, dash, dot, underscore.`);
144
+ }
145
+ }
146
+ //# sourceMappingURL=knowledge.js.map