mdcontext 0.0.1 → 0.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 (337) hide show
  1. package/.changeset/README.md +28 -0
  2. package/.changeset/config.json +11 -0
  3. package/.claude/settings.local.json +25 -0
  4. package/.github/workflows/ci.yml +83 -0
  5. package/.github/workflows/claude-code-review.yml +44 -0
  6. package/.github/workflows/claude.yml +85 -0
  7. package/.github/workflows/release.yml +113 -0
  8. package/.tldrignore +112 -0
  9. package/BACKLOG.md +338 -0
  10. package/CONTRIBUTING.md +186 -0
  11. package/NOTES/NOTES +44 -0
  12. package/README.md +434 -11
  13. package/biome.json +36 -0
  14. package/cspell.config.yaml +14 -0
  15. package/dist/chunk-23UPXDNL.js +3044 -0
  16. package/dist/chunk-2W7MO2DL.js +1366 -0
  17. package/dist/chunk-3NUAZGMA.js +1689 -0
  18. package/dist/chunk-7TOWB2XB.js +366 -0
  19. package/dist/chunk-7XOTOADQ.js +3065 -0
  20. package/dist/chunk-AH2PDM2K.js +3042 -0
  21. package/dist/chunk-BNXWSZ63.js +3742 -0
  22. package/dist/chunk-BTL5DJVU.js +3222 -0
  23. package/dist/chunk-HDHYG7E4.js +104 -0
  24. package/dist/chunk-HLR4KZBP.js +3234 -0
  25. package/dist/chunk-IP3FRFEB.js +1045 -0
  26. package/dist/chunk-KHU56VDO.js +3042 -0
  27. package/dist/chunk-KRYIFLQR.js +88 -0
  28. package/dist/chunk-LBSDNLEM.js +287 -0
  29. package/dist/chunk-MNTQ7HCP.js +2643 -0
  30. package/dist/chunk-MUJELQQ6.js +1387 -0
  31. package/dist/chunk-MXJGMSLV.js +2199 -0
  32. package/dist/chunk-N6QJGC3Z.js +2636 -0
  33. package/dist/chunk-OBELGBPM.js +1713 -0
  34. package/dist/chunk-OT7R5XTA.js +3192 -0
  35. package/dist/chunk-P7X4RA2T.js +106 -0
  36. package/dist/chunk-PIDUQNC2.js +3185 -0
  37. package/dist/chunk-POGCDIH4.js +3187 -0
  38. package/dist/chunk-PSIEOQGZ.js +3043 -0
  39. package/dist/chunk-PVRT3IHA.js +3238 -0
  40. package/dist/chunk-QNN4TT23.js +1430 -0
  41. package/dist/chunk-RE3R45RJ.js +3042 -0
  42. package/dist/chunk-S7E6TFX6.js +803 -0
  43. package/dist/chunk-SG6GLU4U.js +1378 -0
  44. package/dist/chunk-SJCDV2ST.js +274 -0
  45. package/dist/chunk-SYE5XLF3.js +104 -0
  46. package/dist/chunk-T5VLYBZD.js +103 -0
  47. package/dist/chunk-TOQB7VWU.js +3238 -0
  48. package/dist/chunk-VFNMZ4ZQ.js +3228 -0
  49. package/dist/chunk-VVTGZNBT.js +1629 -0
  50. package/dist/chunk-W7Q4RFEV.js +104 -0
  51. package/dist/chunk-XTYYVRLO.js +3190 -0
  52. package/dist/chunk-Y6MDYVJD.js +3063 -0
  53. package/dist/cli/main.d.ts +1 -0
  54. package/dist/cli/main.js +5458 -0
  55. package/dist/index.d.ts +653 -0
  56. package/dist/index.js +79 -0
  57. package/dist/mcp/server.d.ts +1 -0
  58. package/dist/mcp/server.js +472 -0
  59. package/dist/schema-BAWSG7KY.js +22 -0
  60. package/dist/schema-E3QUPL26.js +20 -0
  61. package/dist/schema-EHL7WUT6.js +20 -0
  62. package/docs/019-USAGE.md +625 -0
  63. package/docs/020-current-implementation.md +364 -0
  64. package/docs/021-DOGFOODING-FINDINGS.md +175 -0
  65. package/docs/BACKLOG.md +80 -0
  66. package/docs/CONFIG.md +1123 -0
  67. package/docs/DESIGN.md +439 -0
  68. package/docs/ERRORS.md +383 -0
  69. package/docs/PROJECT.md +88 -0
  70. package/docs/ROADMAP.md +407 -0
  71. package/docs/summarization.md +320 -0
  72. package/docs/test-links.md +9 -0
  73. package/justfile +40 -0
  74. package/package.json +74 -9
  75. package/pnpm-workspace.yaml +5 -0
  76. package/research/INDEX.md +315 -0
  77. package/research/code-review/README.md +90 -0
  78. package/research/code-review/cli-error-handling-review.md +979 -0
  79. package/research/code-review/code-review-validation-report.md +464 -0
  80. package/research/code-review/main-ts-review.md +1128 -0
  81. package/research/config-analysis/01-current-implementation.md +470 -0
  82. package/research/config-analysis/02-strategy-recommendation.md +428 -0
  83. package/research/config-analysis/03-task-candidates.md +715 -0
  84. package/research/config-analysis/033-research-configuration-management.md +828 -0
  85. package/research/config-analysis/034-research-effect-cli-config.md +1504 -0
  86. package/research/config-analysis/04-consolidated-task-candidates.md +277 -0
  87. package/research/config-docs/SUMMARY.md +357 -0
  88. package/research/config-docs/TEST-RESULTS.md +776 -0
  89. package/research/config-docs/TODO.md +542 -0
  90. package/research/config-docs/analysis.md +744 -0
  91. package/research/config-docs/fix-validation.md +502 -0
  92. package/research/config-docs/help-audit.md +264 -0
  93. package/research/config-docs/help-system-analysis.md +890 -0
  94. package/research/dogfood/consolidated-tool-evaluation.md +373 -0
  95. package/research/dogfood/strategy-a/a-synthesis.md +184 -0
  96. package/research/dogfood/strategy-a/a1-docs.md +226 -0
  97. package/research/dogfood/strategy-a/a2-amorphic.md +156 -0
  98. package/research/dogfood/strategy-a/a3-llm.md +164 -0
  99. package/research/dogfood/strategy-b/b-synthesis.md +228 -0
  100. package/research/dogfood/strategy-b/b1-architecture.md +207 -0
  101. package/research/dogfood/strategy-b/b2-gaps.md +258 -0
  102. package/research/dogfood/strategy-b/b3-workflows.md +250 -0
  103. package/research/dogfood/strategy-c/c-synthesis.md +451 -0
  104. package/research/dogfood/strategy-c/c1-explorer.md +192 -0
  105. package/research/dogfood/strategy-c/c2-diver-memory.md +145 -0
  106. package/research/dogfood/strategy-c/c3-diver-control.md +148 -0
  107. package/research/dogfood/strategy-c/c4-diver-failure.md +151 -0
  108. package/research/dogfood/strategy-c/c5-diver-execution.md +221 -0
  109. package/research/dogfood/strategy-c/c6-diver-org.md +221 -0
  110. package/research/effect-cli-error-handling.md +845 -0
  111. package/research/effect-errors-as-values.md +943 -0
  112. package/research/errors-task-analysis/00-consolidated-tasks.md +207 -0
  113. package/research/errors-task-analysis/cli-commands-analysis.md +909 -0
  114. package/research/errors-task-analysis/embeddings-analysis.md +709 -0
  115. package/research/errors-task-analysis/index-search-analysis.md +812 -0
  116. package/research/frontmatter/COMMENTS-ARE-SKIPPED.md +149 -0
  117. package/research/frontmatter/LLM-CODE-NAVIGATION.md +276 -0
  118. package/research/issue-review.md +603 -0
  119. package/research/llm-summarization/agent-cli-tools-2026.md +1082 -0
  120. package/research/llm-summarization/alternative-providers-2026.md +1428 -0
  121. package/research/llm-summarization/anthropic-2026.md +367 -0
  122. package/research/llm-summarization/claude-cli-integration.md +1706 -0
  123. package/research/llm-summarization/cli-integration-patterns.md +3155 -0
  124. package/research/llm-summarization/openai-2026.md +473 -0
  125. package/research/llm-summarization/openai-compatible-providers-2026.md +1022 -0
  126. package/research/llm-summarization/opencode-cli-integration.md +1552 -0
  127. package/research/llm-summarization/prompt-engineering-2026.md +1426 -0
  128. package/research/llm-summarization/prototype-results.md +56 -0
  129. package/research/llm-summarization/provider-switching-patterns-2026.md +2153 -0
  130. package/research/llm-summarization/typescript-llm-libraries-2026.md +2436 -0
  131. package/research/mdcontext-error-analysis.md +521 -0
  132. package/research/mdcontext-pudding/00-EXECUTIVE-SUMMARY.md +282 -0
  133. package/research/mdcontext-pudding/01-index-embed.md +956 -0
  134. package/research/mdcontext-pudding/02-search-COMMANDS.md +142 -0
  135. package/research/mdcontext-pudding/02-search-SUMMARY.md +146 -0
  136. package/research/mdcontext-pudding/02-search.md +970 -0
  137. package/research/mdcontext-pudding/03-context.md +779 -0
  138. package/research/mdcontext-pudding/04-navigation-and-analytics.md +803 -0
  139. package/research/mdcontext-pudding/04-tree.md +704 -0
  140. package/research/mdcontext-pudding/05-config.md +1038 -0
  141. package/research/mdcontext-pudding/06-links-summary.txt +87 -0
  142. package/research/mdcontext-pudding/06-links.md +679 -0
  143. package/research/mdcontext-pudding/07-stats.md +693 -0
  144. package/research/mdcontext-pudding/BUG-FIX-PLAN.md +388 -0
  145. package/research/mdcontext-pudding/P0-BUG-VALIDATION.md +167 -0
  146. package/research/mdcontext-pudding/README.md +168 -0
  147. package/research/mdcontext-pudding/TESTING-SUMMARY.md +128 -0
  148. package/research/npm_publish/011-npm-workflow-research-agent2.md +792 -0
  149. package/research/npm_publish/012-npm-workflow-research-agent1.md +530 -0
  150. package/research/npm_publish/013-npm-workflow-research-agent3.md +722 -0
  151. package/research/npm_publish/014-npm-workflow-synthesis.md +556 -0
  152. package/research/npm_publish/031-npm-workflow-task-analysis.md +134 -0
  153. package/research/research-quality-review.md +834 -0
  154. package/research/semantic-search/002-research-embedding-models.md +490 -0
  155. package/research/semantic-search/003-research-rag-alternatives.md +523 -0
  156. package/research/semantic-search/004-research-vector-search.md +841 -0
  157. package/research/semantic-search/032-research-semantic-search.md +427 -0
  158. package/research/semantic-search/embedding-text-analysis.md +156 -0
  159. package/research/semantic-search/multi-word-failure-reproduction.md +171 -0
  160. package/research/semantic-search/query-processing-analysis.md +207 -0
  161. package/research/semantic-search/root-cause-and-solution.md +114 -0
  162. package/research/semantic-search/threshold-validation-report.md +69 -0
  163. package/research/semantic-search/vector-search-analysis.md +63 -0
  164. package/research/task-management-2026/00-synthesis-recommendations.md +295 -0
  165. package/research/task-management-2026/01-ai-workflow-tools.md +416 -0
  166. package/research/task-management-2026/02-agent-framework-patterns.md +476 -0
  167. package/research/task-management-2026/03-lightweight-file-based.md +567 -0
  168. package/research/task-management-2026/04-established-tools-ai-features.md +541 -0
  169. package/research/task-management-2026/linear/01-core-features-workflow.md +771 -0
  170. package/research/task-management-2026/linear/02-api-integrations.md +930 -0
  171. package/research/task-management-2026/linear/03-ai-features.md +368 -0
  172. package/research/task-management-2026/linear/04-pricing-setup.md +205 -0
  173. package/research/task-management-2026/linear/05-usage-patterns-best-practices.md +605 -0
  174. package/research/test-path-issues.md +276 -0
  175. package/review/ALP-76/1-error-type-design.md +962 -0
  176. package/review/ALP-76/2-error-handling-patterns.md +906 -0
  177. package/review/ALP-76/3-error-presentation.md +624 -0
  178. package/review/ALP-76/4-test-coverage.md +625 -0
  179. package/review/ALP-76/5-migration-completeness.md +440 -0
  180. package/review/ALP-76/6-effect-best-practices.md +755 -0
  181. package/scripts/apply-branch-protection.sh +47 -0
  182. package/scripts/branch-protection-templates.json +79 -0
  183. package/scripts/prototype-summarization.ts +346 -0
  184. package/scripts/rebuild-hnswlib.js +58 -0
  185. package/scripts/setup-branch-protection.sh +64 -0
  186. package/src/__tests__/fixtures/semantic-search/multi-word-corpus/.mdcontext/active-provider.json +7 -0
  187. package/src/__tests__/fixtures/semantic-search/multi-word-corpus/.mdcontext/bm25.json +541 -0
  188. package/src/__tests__/fixtures/semantic-search/multi-word-corpus/.mdcontext/bm25.meta.json +5 -0
  189. package/src/__tests__/fixtures/semantic-search/multi-word-corpus/.mdcontext/config.json +8 -0
  190. package/src/__tests__/fixtures/semantic-search/multi-word-corpus/.mdcontext/embeddings/openai_text-embedding-3-small_512/vectors.bin +0 -0
  191. package/src/__tests__/fixtures/semantic-search/multi-word-corpus/.mdcontext/embeddings/openai_text-embedding-3-small_512/vectors.meta.bin +0 -0
  192. package/src/__tests__/fixtures/semantic-search/multi-word-corpus/.mdcontext/indexes/documents.json +60 -0
  193. package/src/__tests__/fixtures/semantic-search/multi-word-corpus/.mdcontext/indexes/links.json +13 -0
  194. package/src/__tests__/fixtures/semantic-search/multi-word-corpus/.mdcontext/indexes/sections.json +1197 -0
  195. package/src/__tests__/fixtures/semantic-search/multi-word-corpus/configuration-management.md +99 -0
  196. package/src/__tests__/fixtures/semantic-search/multi-word-corpus/distributed-systems.md +92 -0
  197. package/src/__tests__/fixtures/semantic-search/multi-word-corpus/error-handling.md +78 -0
  198. package/src/__tests__/fixtures/semantic-search/multi-word-corpus/failure-automation.md +55 -0
  199. package/src/__tests__/fixtures/semantic-search/multi-word-corpus/job-context.md +69 -0
  200. package/src/__tests__/fixtures/semantic-search/multi-word-corpus/process-orchestration.md +99 -0
  201. package/src/cli/argv-preprocessor.test.ts +210 -0
  202. package/src/cli/argv-preprocessor.ts +202 -0
  203. package/src/cli/cli.test.ts +627 -0
  204. package/src/cli/commands/backlinks.ts +54 -0
  205. package/src/cli/commands/config-cmd.ts +642 -0
  206. package/src/cli/commands/context.ts +285 -0
  207. package/src/cli/commands/duplicates.ts +122 -0
  208. package/src/cli/commands/embeddings.ts +529 -0
  209. package/src/cli/commands/index-cmd.ts +480 -0
  210. package/src/cli/commands/index.ts +16 -0
  211. package/src/cli/commands/links.ts +52 -0
  212. package/src/cli/commands/search.ts +1281 -0
  213. package/src/cli/commands/stats.ts +149 -0
  214. package/src/cli/commands/tree.ts +128 -0
  215. package/src/cli/config-layer.ts +176 -0
  216. package/src/cli/error-handler.test.ts +235 -0
  217. package/src/cli/error-handler.ts +655 -0
  218. package/src/cli/flag-schemas.ts +341 -0
  219. package/src/cli/help.ts +588 -0
  220. package/src/cli/index.ts +9 -0
  221. package/src/cli/main.ts +435 -0
  222. package/src/cli/options.ts +41 -0
  223. package/src/cli/shared-error-handling.ts +199 -0
  224. package/src/cli/typo-suggester.test.ts +105 -0
  225. package/src/cli/typo-suggester.ts +130 -0
  226. package/src/cli/utils.ts +259 -0
  227. package/src/config/file-provider.test.ts +320 -0
  228. package/src/config/file-provider.ts +273 -0
  229. package/src/config/index.ts +72 -0
  230. package/src/config/integration.test.ts +667 -0
  231. package/src/config/precedence.test.ts +277 -0
  232. package/src/config/precedence.ts +451 -0
  233. package/src/config/schema.test.ts +414 -0
  234. package/src/config/schema.ts +603 -0
  235. package/src/config/service.test.ts +320 -0
  236. package/src/config/service.ts +243 -0
  237. package/src/config/testing.test.ts +264 -0
  238. package/src/config/testing.ts +110 -0
  239. package/src/core/index.ts +1 -0
  240. package/src/core/types.ts +113 -0
  241. package/src/duplicates/detector.test.ts +183 -0
  242. package/src/duplicates/detector.ts +414 -0
  243. package/src/duplicates/index.ts +18 -0
  244. package/src/embeddings/embedding-namespace.test.ts +300 -0
  245. package/src/embeddings/embedding-namespace.ts +947 -0
  246. package/src/embeddings/heading-boost.test.ts +222 -0
  247. package/src/embeddings/hnsw-build-options.test.ts +198 -0
  248. package/src/embeddings/hyde.test.ts +272 -0
  249. package/src/embeddings/hyde.ts +264 -0
  250. package/src/embeddings/index.ts +10 -0
  251. package/src/embeddings/openai-provider.ts +414 -0
  252. package/src/embeddings/pricing.json +22 -0
  253. package/src/embeddings/provider-constants.ts +204 -0
  254. package/src/embeddings/provider-errors.test.ts +967 -0
  255. package/src/embeddings/provider-errors.ts +565 -0
  256. package/src/embeddings/provider-factory.test.ts +240 -0
  257. package/src/embeddings/provider-factory.ts +225 -0
  258. package/src/embeddings/provider-integration.test.ts +788 -0
  259. package/src/embeddings/query-preprocessing.test.ts +187 -0
  260. package/src/embeddings/semantic-search-threshold.test.ts +508 -0
  261. package/src/embeddings/semantic-search.ts +1270 -0
  262. package/src/embeddings/types.ts +359 -0
  263. package/src/embeddings/vector-store.ts +708 -0
  264. package/src/embeddings/voyage-provider.ts +313 -0
  265. package/src/errors/errors.test.ts +845 -0
  266. package/src/errors/index.ts +533 -0
  267. package/src/index/ignore-patterns.test.ts +354 -0
  268. package/src/index/ignore-patterns.ts +305 -0
  269. package/src/index/index.ts +4 -0
  270. package/src/index/indexer.ts +684 -0
  271. package/src/index/storage.ts +260 -0
  272. package/src/index/types.ts +147 -0
  273. package/src/index/watcher.ts +189 -0
  274. package/src/index.ts +30 -0
  275. package/src/integration/search-keyword.test.ts +678 -0
  276. package/src/mcp/server.ts +612 -0
  277. package/src/parser/index.ts +1 -0
  278. package/src/parser/parser.test.ts +291 -0
  279. package/src/parser/parser.ts +394 -0
  280. package/src/parser/section-filter.test.ts +277 -0
  281. package/src/parser/section-filter.ts +392 -0
  282. package/src/search/__tests__/hybrid-search.test.ts +650 -0
  283. package/src/search/bm25-store.ts +366 -0
  284. package/src/search/cross-encoder.test.ts +253 -0
  285. package/src/search/cross-encoder.ts +406 -0
  286. package/src/search/fuzzy-search.test.ts +419 -0
  287. package/src/search/fuzzy-search.ts +273 -0
  288. package/src/search/hybrid-search.ts +448 -0
  289. package/src/search/path-matcher.test.ts +276 -0
  290. package/src/search/path-matcher.ts +33 -0
  291. package/src/search/query-parser.test.ts +260 -0
  292. package/src/search/query-parser.ts +319 -0
  293. package/src/search/searcher.test.ts +280 -0
  294. package/src/search/searcher.ts +724 -0
  295. package/src/search/wink-bm25.d.ts +30 -0
  296. package/src/summarization/cli-providers/claude.ts +202 -0
  297. package/src/summarization/cli-providers/detection.test.ts +273 -0
  298. package/src/summarization/cli-providers/detection.ts +118 -0
  299. package/src/summarization/cli-providers/index.ts +8 -0
  300. package/src/summarization/cost.test.ts +139 -0
  301. package/src/summarization/cost.ts +102 -0
  302. package/src/summarization/error-handler.test.ts +127 -0
  303. package/src/summarization/error-handler.ts +111 -0
  304. package/src/summarization/index.ts +102 -0
  305. package/src/summarization/pipeline.test.ts +498 -0
  306. package/src/summarization/pipeline.ts +231 -0
  307. package/src/summarization/prompts.test.ts +269 -0
  308. package/src/summarization/prompts.ts +133 -0
  309. package/src/summarization/provider-factory.test.ts +396 -0
  310. package/src/summarization/provider-factory.ts +178 -0
  311. package/src/summarization/types.ts +184 -0
  312. package/src/summarize/budget-bugs.test.ts +620 -0
  313. package/src/summarize/formatters.ts +419 -0
  314. package/src/summarize/index.ts +20 -0
  315. package/src/summarize/summarizer.test.ts +275 -0
  316. package/src/summarize/summarizer.ts +597 -0
  317. package/src/summarize/verify-bugs.test.ts +238 -0
  318. package/src/types/huggingface-transformers.d.ts +66 -0
  319. package/src/utils/index.ts +1 -0
  320. package/src/utils/tokens.test.ts +142 -0
  321. package/src/utils/tokens.ts +186 -0
  322. package/tests/fixtures/cli/.mdcontext/active-provider.json +7 -0
  323. package/tests/fixtures/cli/.mdcontext/config.json +8 -0
  324. package/tests/fixtures/cli/.mdcontext/embeddings/openai_text-embedding-3-small_512/vectors.bin +0 -0
  325. package/tests/fixtures/cli/.mdcontext/embeddings/openai_text-embedding-3-small_512/vectors.meta.bin +0 -0
  326. package/tests/fixtures/cli/.mdcontext/indexes/documents.json +33 -0
  327. package/tests/fixtures/cli/.mdcontext/indexes/links.json +12 -0
  328. package/tests/fixtures/cli/.mdcontext/indexes/sections.json +247 -0
  329. package/tests/fixtures/cli/README.md +9 -0
  330. package/tests/fixtures/cli/api-reference.md +11 -0
  331. package/tests/fixtures/cli/getting-started.md +11 -0
  332. package/tests/integration/embed-index.test.ts +712 -0
  333. package/tests/integration/search-context.test.ts +469 -0
  334. package/tests/integration/search-semantic.test.ts +522 -0
  335. package/tsconfig.json +26 -0
  336. package/vitest.config.ts +16 -0
  337. package/vitest.setup.ts +12 -0
@@ -0,0 +1,2199 @@
1
+ // src/config/precedence.ts
2
+ import {
3
+ ConfigProvider,
4
+ ConfigProvider as ConfigProvider2,
5
+ Effect,
6
+ Effect as Effect2,
7
+ } from "effect";
8
+ // src/config/file-provider.ts
9
+ import * as fs from "fs";
10
+ import * as path from "path";
11
+ import { defaultConfig, MdContextConfig } from "./chunk-LBSDNLEM.js";
12
+ import {
13
+ ApiKeyInvalidError,
14
+ ApiKeyMissingError,
15
+ ConfigError,
16
+ countTokensApprox,
17
+ createStorage,
18
+ EmbeddingError,
19
+ EmbeddingsNotFoundError,
20
+ INDEX_DIR,
21
+ IndexNotFoundError,
22
+ loadDocumentIndex,
23
+ loadSectionIndex,
24
+ parseFile,
25
+ VectorStoreError,
26
+ } from "./chunk-QNN4TT23.js";
27
+
28
+ var CONFIG_FILE_NAMES = [
29
+ "mdcontext.config.ts",
30
+ "mdcontext.config.js",
31
+ "mdcontext.config.mjs",
32
+ "mdcontext.config.json",
33
+ ".mdcontextrc",
34
+ ".mdcontextrc.json",
35
+ ];
36
+ var findConfigFile = (startDir) => {
37
+ let currentDir = path.resolve(startDir);
38
+ const root = path.parse(currentDir).root;
39
+ while (currentDir !== root) {
40
+ for (const fileName of CONFIG_FILE_NAMES) {
41
+ const configPath = path.join(currentDir, fileName);
42
+ if (fs.existsSync(configPath)) {
43
+ const format = getConfigFormat(fileName);
44
+ return { path: configPath, format };
45
+ }
46
+ }
47
+ const parentDir = path.dirname(currentDir);
48
+ if (parentDir === currentDir) break;
49
+ currentDir = parentDir;
50
+ }
51
+ return null;
52
+ };
53
+ var getConfigFormat = (fileName) => {
54
+ if (fileName.endsWith(".ts")) return "ts";
55
+ if (fileName.endsWith(".js") || fileName.endsWith(".mjs")) return "js";
56
+ return "json";
57
+ };
58
+ var loadJsonConfig = (filePath) =>
59
+ Effect.try({
60
+ try: () => {
61
+ const content = fs.readFileSync(filePath, "utf-8");
62
+ return JSON.parse(content);
63
+ },
64
+ catch: (error) =>
65
+ new ConfigError({
66
+ field: "configFile",
67
+ message: `Failed to load config from ${filePath}: ${error instanceof Error ? error.message : String(error)}`,
68
+ cause: error,
69
+ }),
70
+ });
71
+ var loadJsConfig = (filePath) =>
72
+ Effect.tryPromise({
73
+ try: async () => {
74
+ const fileUrl = `file://${filePath}`;
75
+ const module = await import(fileUrl);
76
+ const config = module.default ?? module.config;
77
+ if (!config || typeof config !== "object") {
78
+ throw new Error(
79
+ 'Config file must export a default object or named "config" export',
80
+ );
81
+ }
82
+ return config;
83
+ },
84
+ catch: (error) =>
85
+ new ConfigError({
86
+ field: "configFile",
87
+ message: `Failed to load config from ${filePath}: ${error instanceof Error ? error.message : String(error)}`,
88
+ cause: error,
89
+ }),
90
+ });
91
+ var loadConfigFromFile = (filePath, format) => {
92
+ switch (format) {
93
+ case "json":
94
+ return loadJsonConfig(filePath);
95
+ case "ts":
96
+ case "js":
97
+ return loadJsConfig(filePath);
98
+ }
99
+ };
100
+ var loadConfigFile = (startDir) =>
101
+ Effect.gen(function* () {
102
+ const found = findConfigFile(startDir);
103
+ if (!found) {
104
+ return {
105
+ found: false,
106
+ searched: CONFIG_FILE_NAMES.map((name) => path.join(startDir, name)),
107
+ };
108
+ }
109
+ const config = yield* loadConfigFromFile(found.path, found.format);
110
+ return {
111
+ found: true,
112
+ path: found.path,
113
+ config,
114
+ };
115
+ });
116
+ var loadConfigFromPath = (configPath) =>
117
+ Effect.gen(function* () {
118
+ const resolvedPath = path.resolve(configPath);
119
+ if (!fs.existsSync(resolvedPath)) {
120
+ return yield* Effect.fail(
121
+ new ConfigError({
122
+ field: "configFile",
123
+ message: `Config file not found: ${resolvedPath}`,
124
+ }),
125
+ );
126
+ }
127
+ const format = getConfigFormat(path.basename(configPath));
128
+ return yield* loadConfigFromFile(resolvedPath, format);
129
+ });
130
+
131
+ // src/config/precedence.ts
132
+ var flattenConfig = (config, prefix = "") => {
133
+ const result = /* @__PURE__ */ new Map();
134
+ const flatten = (obj, currentPrefix) => {
135
+ if (obj === null || obj === void 0) {
136
+ return;
137
+ }
138
+ if (Array.isArray(obj)) {
139
+ result.set(currentPrefix, obj.join(","));
140
+ return;
141
+ }
142
+ if (typeof obj === "object") {
143
+ for (const [key, value] of Object.entries(obj)) {
144
+ const newKey = currentPrefix ? `${currentPrefix}.${key}` : key;
145
+ flatten(value, newKey);
146
+ }
147
+ return;
148
+ }
149
+ result.set(currentPrefix, String(obj));
150
+ };
151
+ flatten(config, prefix);
152
+ return result;
153
+ };
154
+ var ENV_SEQ_DELIM = ",";
155
+ var CONFIG_SCHEMA_KEYS = {
156
+ index: [
157
+ "maxDepth",
158
+ "excludePatterns",
159
+ "fileExtensions",
160
+ "followSymlinks",
161
+ "indexDir",
162
+ ],
163
+ search: [
164
+ "defaultLimit",
165
+ "maxLimit",
166
+ "minSimilarity",
167
+ "includeSnippets",
168
+ "snippetLength",
169
+ "autoIndexThreshold",
170
+ ],
171
+ embeddings: [
172
+ "provider",
173
+ "baseURL",
174
+ "model",
175
+ "dimensions",
176
+ "batchSize",
177
+ "maxRetries",
178
+ "retryDelayMs",
179
+ "timeoutMs",
180
+ "apiKey",
181
+ ],
182
+ summarization: [
183
+ "briefTokenBudget",
184
+ "summaryTokenBudget",
185
+ "compressionRatio",
186
+ "minSectionTokens",
187
+ "maxTopics",
188
+ "minPartialBudget",
189
+ ],
190
+ output: ["format", "color", "prettyJson", "verbose", "debug"],
191
+ paths: ["root", "configFile", "cacheDir"],
192
+ };
193
+ var generateEnvKeyMapping = () => {
194
+ const mapping = {};
195
+ for (const [section, keys] of Object.entries(CONFIG_SCHEMA_KEYS)) {
196
+ for (const key of keys) {
197
+ const envKey = `${section}_${key}`.toLowerCase();
198
+ const configKey = `${section}.${key}`;
199
+ mapping[envKey] = configKey;
200
+ }
201
+ }
202
+ return mapping;
203
+ };
204
+ var ENV_KEY_MAPPING = generateEnvKeyMapping();
205
+ var readEnvConfig = (prefix = "MDCONTEXT") => {
206
+ const result = /* @__PURE__ */ new Map();
207
+ const prefixWithUnderscore = `${prefix}_`;
208
+ for (const [key, value] of Object.entries(process.env)) {
209
+ if (key.startsWith(prefixWithUnderscore) && value !== void 0) {
210
+ const envKey = key.slice(prefixWithUnderscore.length).toLowerCase();
211
+ const configKey = ENV_KEY_MAPPING[envKey];
212
+ if (configKey) {
213
+ result.set(configKey, value);
214
+ }
215
+ }
216
+ }
217
+ return result;
218
+ };
219
+ var createConfigProvider = (options = {}) =>
220
+ Effect2.gen(function* () {
221
+ const {
222
+ cliOverrides,
223
+ configPath,
224
+ workingDir = process.cwd(),
225
+ envPrefix = "MDCONTEXT",
226
+ skipConfigFile = false,
227
+ skipEnv = false,
228
+ } = options;
229
+ const mergedMap = /* @__PURE__ */ new Map();
230
+ if (!skipConfigFile) {
231
+ let fileConfig;
232
+ if (configPath) {
233
+ fileConfig = yield* loadConfigFromPath(configPath);
234
+ } else {
235
+ const result = yield* loadConfigFile(workingDir);
236
+ if (result.found) {
237
+ fileConfig = result.config;
238
+ }
239
+ }
240
+ if (fileConfig) {
241
+ const flattened = flattenConfig(fileConfig);
242
+ for (const [k, v] of flattened) {
243
+ mergedMap.set(k, v);
244
+ }
245
+ }
246
+ }
247
+ if (!skipEnv) {
248
+ const envConfig = readEnvConfig(envPrefix);
249
+ for (const [k, v] of envConfig) {
250
+ mergedMap.set(k, v);
251
+ }
252
+ }
253
+ if (cliOverrides && Object.keys(cliOverrides).length > 0) {
254
+ const flattened = flattenConfig(cliOverrides);
255
+ for (const [k, v] of flattened) {
256
+ mergedMap.set(k, v);
257
+ }
258
+ }
259
+ return ConfigProvider2.fromMap(mergedMap, {
260
+ pathDelim: ".",
261
+ seqDelim: ENV_SEQ_DELIM,
262
+ });
263
+ });
264
+ var createConfigProviderSync = (options = {}) => {
265
+ const {
266
+ cliOverrides,
267
+ fileConfig,
268
+ envPrefix = "MDCONTEXT",
269
+ skipConfigFile = false,
270
+ skipEnv = false,
271
+ } = options;
272
+ const mergedMap = /* @__PURE__ */ new Map();
273
+ if (!skipConfigFile && fileConfig) {
274
+ const flattened = flattenConfig(fileConfig);
275
+ for (const [k, v] of flattened) {
276
+ mergedMap.set(k, v);
277
+ }
278
+ }
279
+ if (!skipEnv) {
280
+ const envConfig = readEnvConfig(envPrefix);
281
+ for (const [k, v] of envConfig) {
282
+ mergedMap.set(k, v);
283
+ }
284
+ }
285
+ if (cliOverrides && Object.keys(cliOverrides).length > 0) {
286
+ const flattened = flattenConfig(cliOverrides);
287
+ for (const [k, v] of flattened) {
288
+ mergedMap.set(k, v);
289
+ }
290
+ }
291
+ return ConfigProvider2.fromMap(mergedMap, {
292
+ pathDelim: ".",
293
+ seqDelim: ENV_SEQ_DELIM,
294
+ });
295
+ };
296
+
297
+ // src/config/service.ts
298
+ import { Context, Effect as Effect3, Layer } from "effect";
299
+
300
+ var ConfigService = class extends Context.Tag("ConfigService")() {};
301
+ var ConfigServiceLive = Layer.effect(ConfigService, MdContextConfig);
302
+ var makeConfigLayer = (config) => Layer.succeed(ConfigService, config);
303
+ var ConfigServiceDefault = makeConfigLayer(defaultConfig);
304
+
305
+ // src/config/testing.ts
306
+ import { Effect as Effect4, Layer as Layer2 } from "effect";
307
+
308
+ var TestConfigLayer = Layer2.succeed(ConfigService, defaultConfig);
309
+
310
+ // src/summarize/formatters.ts
311
+ var formatSummary = (summary, options = {}) => {
312
+ const maxTokens = options.maxTokens;
313
+ const flatSections = [];
314
+ const collectSections = (
315
+ section,
316
+ depth = 0,
317
+ parentNumber = "",
318
+ index = 0,
319
+ ) => {
320
+ const number = parentNumber
321
+ ? `${parentNumber}.${index + 1}`
322
+ : `${index + 1}`;
323
+ flatSections.push({ section, depth, number });
324
+ section.children.forEach((child, i) => {
325
+ collectSections(child, depth + 1, number, i);
326
+ });
327
+ };
328
+ summary.sections.forEach((section, i) => {
329
+ collectSections(section, 0, "", i);
330
+ });
331
+ const buildOutput = (
332
+ includedSectionIndices,
333
+ truncationInfo,
334
+ includeTopics2,
335
+ ) => {
336
+ const lines = [];
337
+ if (
338
+ truncationInfo.showWarning &&
339
+ truncationInfo.truncatedCount > 0 &&
340
+ truncationInfo.tokensTotal > 0
341
+ ) {
342
+ const pct = Math.round(
343
+ (truncationInfo.tokensShown / truncationInfo.tokensTotal) * 100,
344
+ );
345
+ lines.push(
346
+ `\u26A0\uFE0F Truncated: Showing ~${truncationInfo.tokensShown}/${truncationInfo.tokensTotal} tokens (${pct}%)`,
347
+ );
348
+ if (truncationInfo.includedNumbers.length > 0) {
349
+ const includedDisplay =
350
+ truncationInfo.includedNumbers.length <= 6
351
+ ? truncationInfo.includedNumbers.join(", ")
352
+ : truncationInfo.includedNumbers.slice(0, 5).join(", ") +
353
+ `, ... (+${truncationInfo.includedNumbers.length - 5} more)`;
354
+ lines.push(`Sections included: ${includedDisplay}`);
355
+ }
356
+ if (truncationInfo.excludedNumbers.length > 0) {
357
+ const excludedDisplay =
358
+ truncationInfo.excludedNumbers.length <= 6
359
+ ? truncationInfo.excludedNumbers.join(", ")
360
+ : truncationInfo.excludedNumbers.slice(0, 5).join(", ") +
361
+ `, ... (+${truncationInfo.excludedNumbers.length - 5} more)`;
362
+ lines.push(`Sections excluded: ${excludedDisplay}`);
363
+ }
364
+ lines.push(
365
+ "Use --full for complete content or --section to target specific sections.",
366
+ );
367
+ lines.push("");
368
+ }
369
+ lines.push(`# ${summary.title}`);
370
+ lines.push(`Path: ${summary.path}`);
371
+ const tokenLineIndex = lines.length;
372
+ lines.push("PLACEHOLDER");
373
+ lines.push("");
374
+ const fullTopicsLine2 =
375
+ summary.keyTopics.length > 0
376
+ ? `**Topics:** ${summary.keyTopics.join(", ")}`
377
+ : "";
378
+ if (includeTopics2 && fullTopicsLine2) {
379
+ lines.push(fullTopicsLine2);
380
+ lines.push("");
381
+ }
382
+ const sectionLines = [];
383
+ for (let i = 0; i < flatSections.length; i++) {
384
+ if (!includedSectionIndices.has(i)) continue;
385
+ const { section, depth } = flatSections[i];
386
+ const indent = " ".repeat(depth);
387
+ const prefix = "#".repeat(section.level);
388
+ sectionLines.push(`${indent}${prefix} ${section.heading}`);
389
+ if (section.summary) {
390
+ sectionLines.push(`${indent}${section.summary}`);
391
+ }
392
+ }
393
+ lines.push(sectionLines.join("\n"));
394
+ const tempOutput = lines.join("\n");
395
+ const tokensWithoutLine = countTokensApprox(
396
+ tempOutput.replace("PLACEHOLDER", ""),
397
+ );
398
+ let estimatedTotal = tokensWithoutLine + 8;
399
+ for (let iter = 0; iter < 3; iter++) {
400
+ const testTokenLine = `Tokens: ${estimatedTotal} (${(summary.compressionRatio * 100).toFixed(0)}% reduction from ${summary.originalTokens})`;
401
+ const testOutput = tempOutput.replace("PLACEHOLDER", testTokenLine);
402
+ const actualTotal = countTokensApprox(testOutput);
403
+ if (actualTotal === estimatedTotal) break;
404
+ estimatedTotal = actualTotal;
405
+ }
406
+ const finalTokenLine = `Tokens: ${estimatedTotal} (${(summary.compressionRatio * 100).toFixed(0)}% reduction from ${summary.originalTokens})`;
407
+ lines[tokenLineIndex] = finalTokenLine;
408
+ return lines.join("\n");
409
+ };
410
+ if (maxTokens === void 0) {
411
+ const allIndices = new Set(flatSections.map((_, i) => i));
412
+ const hasPriorTruncation = summary.truncated && summary.truncatedCount;
413
+ return buildOutput(
414
+ allIndices,
415
+ {
416
+ showWarning: !!hasPriorTruncation,
417
+ truncatedCount: summary.truncatedCount ?? 0,
418
+ includedNumbers: flatSections.map((s) => s.number),
419
+ excludedNumbers: [],
420
+ tokensShown: summary.summaryTokens,
421
+ tokensTotal: summary.originalTokens,
422
+ },
423
+ true,
424
+ );
425
+ }
426
+ const includedIndices = /* @__PURE__ */ new Set();
427
+ let truncatedCount = 0;
428
+ let includeTopics = true;
429
+ const SAFETY_MARGIN = 1.15;
430
+ const minHeaderTemplate = [
431
+ `# ${summary.title}`,
432
+ `Path: ${summary.path}`,
433
+ `Tokens: 9999 (${(summary.compressionRatio * 100).toFixed(0)}% reduction from ${summary.originalTokens})`,
434
+ "",
435
+ "",
436
+ ].join("\n");
437
+ const minHeaderTokens = Math.ceil(
438
+ countTokensApprox(minHeaderTemplate) * SAFETY_MARGIN,
439
+ );
440
+ const fullTopicsLine =
441
+ summary.keyTopics.length > 0
442
+ ? `**Topics:** ${summary.keyTopics.join(", ")}
443
+ `
444
+ : "";
445
+ const topicsTokens = fullTopicsLine
446
+ ? Math.ceil(countTokensApprox(fullTopicsLine) * SAFETY_MARGIN)
447
+ : 0;
448
+ const truncationWarningTokens = Math.ceil(
449
+ countTokensApprox(
450
+ `\u26A0\uFE0F Truncated: Showing ~9999/9999 tokens (99%)
451
+ Sections included: 1, 2, 3, 4, 5, ... (+99 more)
452
+ Sections excluded: 6, 7, 8, 9, 10, ... (+99 more)
453
+ Use --full for complete content or --section to target specific sections.
454
+ `,
455
+ ) * SAFETY_MARGIN,
456
+ );
457
+ let headerTokens = minHeaderTokens + topicsTokens;
458
+ if (headerTokens >= maxTokens) {
459
+ includeTopics = false;
460
+ headerTokens = minHeaderTokens;
461
+ }
462
+ let contentBudget = maxTokens - headerTokens - truncationWarningTokens;
463
+ let tokensUsed = 0;
464
+ for (let i = 0; i < flatSections.length; i++) {
465
+ const { section, depth } = flatSections[i];
466
+ const indent = " ".repeat(depth);
467
+ const prefix = "#".repeat(section.level);
468
+ const sectionContent = section.summary
469
+ ? `${indent}${prefix} ${section.heading}
470
+ ${indent}${section.summary}`
471
+ : `${indent}${prefix} ${section.heading}`;
472
+ const sectionTokens = Math.ceil(
473
+ countTokensApprox(sectionContent) * SAFETY_MARGIN,
474
+ );
475
+ if (tokensUsed + sectionTokens <= contentBudget) {
476
+ includedIndices.add(i);
477
+ tokensUsed += sectionTokens;
478
+ } else {
479
+ truncatedCount++;
480
+ }
481
+ }
482
+ if (truncatedCount === 0) {
483
+ contentBudget += truncationWarningTokens;
484
+ }
485
+ const includedNumbers = [];
486
+ const excludedNumbers = [];
487
+ for (let i = 0; i < flatSections.length; i++) {
488
+ if (includedIndices.has(i)) {
489
+ includedNumbers.push(flatSections[i].number);
490
+ } else {
491
+ excludedNumbers.push(flatSections[i].number);
492
+ }
493
+ }
494
+ let tokensShown = 0;
495
+ for (const idx of includedIndices) {
496
+ tokensShown += flatSections[idx].section.summaryTokens;
497
+ }
498
+ let output = buildOutput(
499
+ includedIndices,
500
+ {
501
+ showWarning: truncatedCount > 0,
502
+ truncatedCount,
503
+ includedNumbers,
504
+ excludedNumbers,
505
+ tokensShown,
506
+ tokensTotal: summary.originalTokens,
507
+ },
508
+ includeTopics,
509
+ );
510
+ let actualTokens = countTokensApprox(output);
511
+ const sortedIndices = Array.from(includedIndices).sort((a, b) => b - a);
512
+ let removalIndex = 0;
513
+ while (actualTokens > maxTokens && removalIndex < sortedIndices.length) {
514
+ const indexToRemove = sortedIndices[removalIndex];
515
+ includedIndices.delete(indexToRemove);
516
+ truncatedCount++;
517
+ removalIndex++;
518
+ const removedNumber = flatSections[indexToRemove].number;
519
+ const includedIdx = includedNumbers.indexOf(removedNumber);
520
+ if (includedIdx !== -1) {
521
+ includedNumbers.splice(includedIdx, 1);
522
+ excludedNumbers.push(removedNumber);
523
+ }
524
+ tokensShown -= flatSections[indexToRemove].section.summaryTokens;
525
+ output = buildOutput(
526
+ includedIndices,
527
+ {
528
+ showWarning: true,
529
+ truncatedCount,
530
+ includedNumbers,
531
+ excludedNumbers,
532
+ tokensShown,
533
+ tokensTotal: summary.originalTokens,
534
+ },
535
+ includeTopics,
536
+ );
537
+ actualTokens = countTokensApprox(output);
538
+ }
539
+ if (actualTokens > maxTokens && includeTopics) {
540
+ includeTopics = false;
541
+ output = buildOutput(
542
+ includedIndices,
543
+ {
544
+ showWarning: truncatedCount > 0,
545
+ truncatedCount,
546
+ includedNumbers,
547
+ excludedNumbers,
548
+ tokensShown,
549
+ tokensTotal: summary.originalTokens,
550
+ },
551
+ includeTopics,
552
+ );
553
+ actualTokens = countTokensApprox(output);
554
+ }
555
+ if (actualTokens > maxTokens && truncatedCount > 0) {
556
+ output = buildOutput(
557
+ includedIndices,
558
+ {
559
+ showWarning: false,
560
+ truncatedCount,
561
+ includedNumbers,
562
+ excludedNumbers,
563
+ tokensShown,
564
+ tokensTotal: summary.originalTokens,
565
+ },
566
+ includeTopics,
567
+ );
568
+ actualTokens = countTokensApprox(output);
569
+ }
570
+ return output;
571
+ };
572
+ var formatAssembledContext = (context) => {
573
+ const lines = [];
574
+ lines.push("# Context Assembly");
575
+ lines.push(`Total tokens: ${context.totalTokens}/${context.budget}`);
576
+ lines.push(`Sources: ${context.sources.length}`);
577
+ lines.push("");
578
+ for (const source of context.sources) {
579
+ lines.push("---");
580
+ lines.push("");
581
+ lines.push(source.content);
582
+ }
583
+ if (context.overflow.length > 0) {
584
+ lines.push("---");
585
+ lines.push("");
586
+ lines.push("## Overflow (not included due to budget)");
587
+ for (const overflowPath of context.overflow) {
588
+ lines.push(`- ${overflowPath}`);
589
+ }
590
+ }
591
+ return lines.join("\n");
592
+ };
593
+
594
+ import { Effect as Effect5 } from "effect";
595
+ // src/summarize/summarizer.ts
596
+ import * as fs2 from "fs/promises";
597
+ import * as path2 from "path";
598
+
599
+ var TOKEN_BUDGETS = {
600
+ brief: 100,
601
+ summary: 500,
602
+ full: Infinity,
603
+ };
604
+ var MIN_SENTENCE_LENGTH = 10;
605
+ var SENTENCE_SCORE_DEFINITION = 2;
606
+ var SENTENCE_SCORE_PROPER_START = 1;
607
+ var SENTENCE_SCORE_MEDIUM_LENGTH = 1;
608
+ var SENTENCE_SCORE_EMPHASIS = 1;
609
+ var SENTENCE_LENGTH_MIN = 50;
610
+ var SENTENCE_LENGTH_MAX = 200;
611
+ var SUMMARY_COMPRESSION_RATIO = 0.3;
612
+ var MIN_SECTION_TOKENS = 20;
613
+ var MIN_SUMMARY_SENTENCES = 2;
614
+ var TOKENS_PER_SENTENCE_ESTIMATE = 30;
615
+ var MIN_TOPIC_LENGTH = 2;
616
+ var MAX_TOPIC_LENGTH = 50;
617
+ var MAX_TOPICS = 10;
618
+ var MIN_PARTIAL_BUDGET = 50;
619
+ var extractKeyPoints = (content, maxSentences) => {
620
+ const sentences = content
621
+ .replace(/\n+/g, " ")
622
+ .split(/(?<=[.!?])\s+/)
623
+ .filter((s) => s.trim().length > MIN_SENTENCE_LENGTH);
624
+ if (sentences.length <= maxSentences) {
625
+ return sentences;
626
+ }
627
+ const scored = sentences.map((s) => {
628
+ let score = 0;
629
+ if (s.includes(":")) score += SENTENCE_SCORE_DEFINITION;
630
+ if (/^[A-Z]/.test(s)) score += SENTENCE_SCORE_PROPER_START;
631
+ if (s.length > SENTENCE_LENGTH_MIN && s.length < SENTENCE_LENGTH_MAX)
632
+ score += SENTENCE_SCORE_MEDIUM_LENGTH;
633
+ if (/\*\*|`/.test(s)) score += SENTENCE_SCORE_EMPHASIS;
634
+ return { sentence: s, score };
635
+ });
636
+ scored.sort((a, b) => b.score - a.score);
637
+ return scored.slice(0, maxSentences).map((s) => s.sentence);
638
+ };
639
+ var summarizeSection = (section, level) => {
640
+ const originalTokens = section.metadata.tokenCount;
641
+ const children = section.children.map((child) =>
642
+ summarizeSection(child, level),
643
+ );
644
+ const targetTokens = Math.min(
645
+ TOKEN_BUDGETS[level],
646
+ Math.max(originalTokens * SUMMARY_COMPRESSION_RATIO, MIN_SECTION_TOKENS),
647
+ );
648
+ let summary;
649
+ if (level === "full" || originalTokens <= targetTokens) {
650
+ summary = section.plainText;
651
+ } else if (level === "brief") {
652
+ const meta = [];
653
+ if (section.metadata.hasCode) meta.push("code");
654
+ if (section.metadata.hasList) meta.push("list");
655
+ if (section.metadata.hasTable) meta.push("table");
656
+ summary = meta.length > 0 ? `[${meta.join(", ")}]` : "";
657
+ } else {
658
+ const maxSentences = Math.max(
659
+ MIN_SUMMARY_SENTENCES,
660
+ Math.floor(targetTokens / TOKENS_PER_SENTENCE_ESTIMATE),
661
+ );
662
+ const keyPoints = extractKeyPoints(section.plainText, maxSentences);
663
+ if (keyPoints.length > 0) {
664
+ summary = keyPoints.join(" ");
665
+ } else {
666
+ const words = section.plainText.split(/\s+/).slice(0, targetTokens);
667
+ summary =
668
+ words.join(" ") +
669
+ (words.length < section.plainText.split(/\s+/).length ? "..." : "");
670
+ }
671
+ }
672
+ const summaryTokens = countTokensApprox(summary);
673
+ return {
674
+ heading: section.heading,
675
+ level: section.level,
676
+ originalTokens,
677
+ summaryTokens,
678
+ summary,
679
+ children,
680
+ hasCode: section.metadata.hasCode,
681
+ hasList: section.metadata.hasList,
682
+ hasTable: section.metadata.hasTable,
683
+ };
684
+ };
685
+ var extractTopics = (document) => {
686
+ const topics = /* @__PURE__ */ new Set();
687
+ const processSection = (section) => {
688
+ const cleanHeading = section.heading
689
+ .replace(/[:#\-_]/g, " ")
690
+ .trim()
691
+ .toLowerCase();
692
+ if (
693
+ cleanHeading.length > MIN_TOPIC_LENGTH &&
694
+ cleanHeading.length < MAX_TOPIC_LENGTH
695
+ ) {
696
+ topics.add(cleanHeading);
697
+ }
698
+ for (const child of section.children) {
699
+ processSection(child);
700
+ }
701
+ };
702
+ for (const section of document.sections) {
703
+ processSection(section);
704
+ }
705
+ const frontmatter = document.frontmatter;
706
+ if (frontmatter.tags && Array.isArray(frontmatter.tags)) {
707
+ for (const tag of frontmatter.tags) {
708
+ if (typeof tag === "string") {
709
+ topics.add(tag.toLowerCase());
710
+ }
711
+ }
712
+ }
713
+ return Array.from(topics).slice(0, MAX_TOPICS);
714
+ };
715
+ var summarizeDocument = (document, options = {}) => {
716
+ const level = options.level ?? "summary";
717
+ const maxTokens = options.maxTokens ?? TOKEN_BUDGETS[level];
718
+ const allSections = document.sections.map((s) => summarizeSection(s, level));
719
+ const originalTokens = document.metadata.tokenCount;
720
+ let totalSummaryTokens = 0;
721
+ const flatSections = [];
722
+ const flattenWithTokens = (section) => {
723
+ flatSections.push(section);
724
+ totalSummaryTokens += section.summaryTokens;
725
+ for (const child of section.children) {
726
+ flattenWithTokens(child);
727
+ }
728
+ };
729
+ for (const section of allSections) {
730
+ flattenWithTokens(section);
731
+ }
732
+ const topics = extractTopics(document);
733
+ const headerTemplate = `# ${document.title}
734
+ Path: ${document.path}
735
+ Tokens: 9999 (99% reduction from ${document.metadata.tokenCount})
736
+ `;
737
+ const topicsLine =
738
+ topics.length > 0
739
+ ? `
740
+ **Topics:** ${topics.join(", ")}
741
+ `
742
+ : "";
743
+ const truncationWarning =
744
+ "\n\u26A0\uFE0F TRUNCATED: 999 sections omitted to fit token budget";
745
+ const baseOverhead = countTokensApprox(
746
+ headerTemplate + topicsLine + truncationWarning,
747
+ );
748
+ const formattingOverhead = Math.ceil(baseOverhead * 1.2) + 20;
749
+ const contentBudget = maxTokens - formattingOverhead;
750
+ let truncated = false;
751
+ let truncatedCount = 0;
752
+ let sections;
753
+ let summaryTokens;
754
+ if (totalSummaryTokens > contentBudget && contentBudget > 0) {
755
+ let tokensUsed = 0;
756
+ const truncateSections = (sectionList) => {
757
+ const result2 = [];
758
+ for (const section of sectionList) {
759
+ const sectionOwnTokens = section.summaryTokens;
760
+ const fitsInBudget = tokensUsed + sectionOwnTokens <= contentBudget;
761
+ if (fitsInBudget) {
762
+ tokensUsed += sectionOwnTokens;
763
+ const truncatedChildren = truncateSections(section.children);
764
+ result2.push({
765
+ ...section,
766
+ children: truncatedChildren,
767
+ });
768
+ } else {
769
+ truncatedCount++;
770
+ const rescuedChildren = truncateSections(section.children);
771
+ result2.push(...rescuedChildren);
772
+ }
773
+ }
774
+ return result2;
775
+ };
776
+ sections = truncateSections(allSections);
777
+ summaryTokens = tokensUsed;
778
+ truncated = truncatedCount > 0;
779
+ } else {
780
+ sections = allSections;
781
+ summaryTokens = totalSummaryTokens;
782
+ }
783
+ const compressionRatio =
784
+ originalTokens > 0 ? 1 - summaryTokens / originalTokens : 0;
785
+ const result = {
786
+ path: document.path,
787
+ title: document.title,
788
+ originalTokens,
789
+ summaryTokens,
790
+ compressionRatio,
791
+ sections,
792
+ keyTopics: topics,
793
+ };
794
+ if (truncated) {
795
+ return {
796
+ ...result,
797
+ truncated: true,
798
+ truncatedCount,
799
+ };
800
+ }
801
+ return result;
802
+ };
803
+ var summarizeFile = (filePath, options = {}) =>
804
+ Effect5.gen(function* () {
805
+ const document = yield* parseFile(filePath);
806
+ return summarizeDocument(document, options);
807
+ });
808
+ var assembleContext = (rootPath, sourcePaths, options) =>
809
+ Effect5.gen(function* () {
810
+ const budget = options.budget;
811
+ const level = options.level ?? "summary";
812
+ const sources = [];
813
+ const overflow = [];
814
+ let totalTokens = 0;
815
+ const perSourceBudget = Math.floor(budget / sourcePaths.length);
816
+ for (const sourcePath of sourcePaths) {
817
+ const resolvedPath = path2.isAbsolute(sourcePath)
818
+ ? sourcePath
819
+ : path2.join(rootPath, sourcePath);
820
+ const summaryResult = yield* summarizeFile(resolvedPath, {
821
+ level,
822
+ maxTokens: perSourceBudget,
823
+ }).pipe(
824
+ Effect5.map((s) => s),
825
+ // Log error for observability before gracefully degrading
826
+ Effect5.tapError((error) =>
827
+ Effect5.logError(`Failed to summarize ${sourcePath}`, error),
828
+ ),
829
+ // Note: catchAll intentional for batch processing - individual file
830
+ // failures add to overflow instead of stopping assembly
831
+ Effect5.catchAll(() => Effect5.succeed(null)),
832
+ );
833
+ if (!summaryResult) {
834
+ overflow.push(sourcePath);
835
+ continue;
836
+ }
837
+ const summary = summaryResult;
838
+ const content = formatSummary(summary);
839
+ const tokens = countTokensApprox(content);
840
+ if (totalTokens + tokens <= budget) {
841
+ sources.push({
842
+ path: path2.relative(rootPath, resolvedPath),
843
+ title: summary.title,
844
+ tokens,
845
+ content,
846
+ });
847
+ totalTokens += tokens;
848
+ } else {
849
+ const remaining = budget - totalTokens;
850
+ if (remaining > MIN_PARTIAL_BUDGET) {
851
+ const briefSummary = yield* summarizeFile(resolvedPath, {
852
+ level: "brief",
853
+ maxTokens: remaining,
854
+ }).pipe(
855
+ Effect5.map((s) => s),
856
+ // Log error for observability before gracefully degrading
857
+ Effect5.tapError((error) =>
858
+ Effect5.logError(
859
+ `Failed to create brief summary for ${sourcePath}`,
860
+ error,
861
+ ),
862
+ ),
863
+ Effect5.catchAll(() => Effect5.succeed(null)),
864
+ );
865
+ if (briefSummary) {
866
+ const briefContent = formatSummary(briefSummary);
867
+ const briefTokens = countTokensApprox(briefContent);
868
+ sources.push({
869
+ path: path2.relative(rootPath, resolvedPath),
870
+ title: briefSummary.title,
871
+ tokens: briefTokens,
872
+ content: briefContent,
873
+ });
874
+ totalTokens += briefTokens;
875
+ } else {
876
+ overflow.push(path2.relative(rootPath, resolvedPath));
877
+ }
878
+ } else {
879
+ overflow.push(path2.relative(rootPath, resolvedPath));
880
+ }
881
+ }
882
+ }
883
+ return {
884
+ sources,
885
+ totalTokens,
886
+ budget,
887
+ overflow,
888
+ };
889
+ });
890
+
891
+ // src/embeddings/openai-provider.ts
892
+ import { Effect as Effect6, Effect as Effect9 } from "effect";
893
+ // src/embeddings/semantic-search.ts
894
+ import * as fs4 from "fs/promises";
895
+ import OpenAI from "openai";
896
+ import * as path4 from "path";
897
+
898
+ var PRICING_DATA = {
899
+ /** Last update date in YYYY-MM format */
900
+ lastUpdated: "2024-09",
901
+ /** Source URL for verification */
902
+ source: "https://platform.openai.com/docs/pricing",
903
+ /** Prices per 1M tokens by model */
904
+ prices: {
905
+ "text-embedding-3-small": 0.02,
906
+ "text-embedding-3-large": 0.13,
907
+ "text-embedding-ada-002": 0.1,
908
+ },
909
+ };
910
+ var checkPricingFreshness = () => {
911
+ const [year, month] = PRICING_DATA.lastUpdated.split("-").map(Number);
912
+ if (!year || !month) return null;
913
+ const lastUpdated = new Date(year, month - 1, 1);
914
+ const now = /* @__PURE__ */ new Date();
915
+ const daysSince = Math.floor(
916
+ (now.getTime() - lastUpdated.getTime()) / (1e3 * 60 * 60 * 24),
917
+ );
918
+ if (daysSince > 90) {
919
+ return `Pricing data is ${daysSince} days old. May not reflect current rates.`;
920
+ }
921
+ return null;
922
+ };
923
+ var getPricingDate = () => PRICING_DATA.lastUpdated;
924
+ var OpenAIProvider = class _OpenAIProvider {
925
+ name;
926
+ dimensions;
927
+ /** Provider name for error context */
928
+ providerName;
929
+ /** Model name */
930
+ model;
931
+ /** Base URL for API requests */
932
+ baseURL;
933
+ client;
934
+ batchSize;
935
+ constructor(apiKey, options = {}) {
936
+ this.baseURL = options.baseURL;
937
+ this.client = new OpenAI({
938
+ apiKey,
939
+ baseURL: options.baseURL,
940
+ // If undefined, SDK uses default https://api.openai.com/v1
941
+ });
942
+ this.model = options.model ?? "text-embedding-3-small";
943
+ this.batchSize = options.batchSize ?? 100;
944
+ this.providerName =
945
+ options.providerName ?? this.inferProviderName(options.baseURL);
946
+ this.name = `${this.providerName}:${this.model}`;
947
+ this.dimensions = 512;
948
+ }
949
+ /**
950
+ * Infer the provider name from the baseURL
951
+ */
952
+ inferProviderName(baseURL) {
953
+ if (!baseURL) return "openai";
954
+ if (baseURL.includes("11434")) return "ollama";
955
+ if (baseURL.includes("1234")) return "lm-studio";
956
+ if (baseURL.includes("openrouter")) return "openrouter";
957
+ return "openai";
958
+ }
959
+ /**
960
+ * Create an OpenAI provider instance.
961
+ * Returns an Effect that fails with ApiKeyMissingError if no API key is available.
962
+ */
963
+ static create(options = {}) {
964
+ const isOpenRouter =
965
+ options.baseURL?.includes("openrouter") ||
966
+ options.providerName === "openrouter";
967
+ const apiKey =
968
+ options.apiKey ??
969
+ (isOpenRouter ? process.env.OPENROUTER_API_KEY : void 0) ??
970
+ process.env.OPENAI_API_KEY;
971
+ if (!apiKey) {
972
+ return Effect6.fail(
973
+ new ApiKeyMissingError({
974
+ provider: isOpenRouter ? "OpenRouter" : "OpenAI",
975
+ envVar: isOpenRouter ? "OPENROUTER_API_KEY" : "OPENAI_API_KEY",
976
+ }),
977
+ );
978
+ }
979
+ const shouldWarn =
980
+ isOpenRouter && apiKey.startsWith("sk-") && !apiKey.startsWith("sk-or-");
981
+ return Effect6.succeed(new _OpenAIProvider(apiKey, options)).pipe(
982
+ shouldWarn
983
+ ? Effect6.tap(() =>
984
+ Effect6.logWarning(
985
+ '\u26A0\uFE0F Using OpenAI key format with OpenRouter. Consider setting OPENROUTER_API_KEY with a key starting with "sk-or-"',
986
+ ),
987
+ )
988
+ : (self) => self,
989
+ );
990
+ }
991
+ async embed(texts) {
992
+ if (texts.length === 0) {
993
+ return { embeddings: [], tokensUsed: 0, cost: 0 };
994
+ }
995
+ const allEmbeddings = [];
996
+ let totalTokens = 0;
997
+ try {
998
+ for (let i = 0; i < texts.length; i += this.batchSize) {
999
+ const batch = texts.slice(i, i + this.batchSize);
1000
+ const response = await this.client.embeddings.create({
1001
+ model: this.model,
1002
+ input: batch,
1003
+ dimensions: 512,
1004
+ // Ensure consistent dimensions
1005
+ });
1006
+ for (const item of response.data) {
1007
+ allEmbeddings.push(item.embedding);
1008
+ }
1009
+ totalTokens += response.usage?.total_tokens ?? 0;
1010
+ }
1011
+ } catch (error) {
1012
+ if (error instanceof OpenAI.AuthenticationError) {
1013
+ throw new ApiKeyInvalidError({
1014
+ provider: this.providerName,
1015
+ details: error.message,
1016
+ });
1017
+ }
1018
+ throw new EmbeddingError({
1019
+ reason: this.classifyError(error),
1020
+ message: error instanceof Error ? error.message : String(error),
1021
+ provider: this.providerName,
1022
+ cause: error,
1023
+ });
1024
+ }
1025
+ const pricePerMillion =
1026
+ this.providerName === "openai" || this.providerName === "openrouter"
1027
+ ? (PRICING_DATA.prices[this.model] ?? 0.02)
1028
+ : 0;
1029
+ const cost = (totalTokens / 1e6) * pricePerMillion;
1030
+ return {
1031
+ embeddings: allEmbeddings,
1032
+ tokensUsed: totalTokens,
1033
+ cost,
1034
+ };
1035
+ }
1036
+ /**
1037
+ * Classify an error into a known category for better error handling
1038
+ */
1039
+ classifyError(error) {
1040
+ if (!(error instanceof Error)) return "Unknown";
1041
+ const msg = error.message.toLowerCase();
1042
+ if (
1043
+ msg.includes("429") ||
1044
+ msg.includes("rate limit") ||
1045
+ msg.includes("too many requests")
1046
+ ) {
1047
+ return "RateLimit";
1048
+ }
1049
+ if (
1050
+ msg.includes("quota") ||
1051
+ msg.includes("insufficient") ||
1052
+ msg.includes("billing")
1053
+ ) {
1054
+ return "QuotaExceeded";
1055
+ }
1056
+ if (
1057
+ msg.includes("econnrefused") ||
1058
+ msg.includes("timeout") ||
1059
+ msg.includes("network") ||
1060
+ msg.includes("enotfound") ||
1061
+ msg.includes("connection")
1062
+ ) {
1063
+ return "Network";
1064
+ }
1065
+ if (
1066
+ msg.includes("model") &&
1067
+ (msg.includes("not found") ||
1068
+ msg.includes("not exist") ||
1069
+ msg.includes("invalid"))
1070
+ ) {
1071
+ return "ModelError";
1072
+ }
1073
+ return "Unknown";
1074
+ }
1075
+ };
1076
+ var createOpenAIProvider = (options) => OpenAIProvider.create(options);
1077
+ var wrapEmbedding = (embedPromise) =>
1078
+ Effect6.tryPromise({
1079
+ try: () => embedPromise,
1080
+ catch: (e) => {
1081
+ if (e instanceof ApiKeyInvalidError) {
1082
+ return e;
1083
+ }
1084
+ return new EmbeddingError({
1085
+ reason: "Unknown",
1086
+ message: e instanceof Error ? e.message : String(e),
1087
+ provider: "OpenAI",
1088
+ cause: e,
1089
+ });
1090
+ },
1091
+ });
1092
+
1093
+ // src/embeddings/provider-factory.ts
1094
+ import { Effect as Effect7, Option } from "effect";
1095
+
1096
+ var PROVIDER_BASE_URLS = {
1097
+ openai: void 0,
1098
+ // Use OpenAI SDK default
1099
+ ollama: "http://localhost:11434/v1",
1100
+ "lm-studio": "http://localhost:1234/v1",
1101
+ openrouter: "https://openrouter.ai/api/v1",
1102
+ };
1103
+ var getProviderBaseURL = (provider, configBaseURL) => {
1104
+ if (Option.isSome(configBaseURL)) {
1105
+ return configBaseURL.value;
1106
+ }
1107
+ return PROVIDER_BASE_URLS[provider];
1108
+ };
1109
+ var normalizeBaseURL = (baseURL) => {
1110
+ if (baseURL === void 0) {
1111
+ return Option.none();
1112
+ }
1113
+ if (typeof baseURL === "string") {
1114
+ return Option.some(baseURL);
1115
+ }
1116
+ return baseURL;
1117
+ };
1118
+ var normalizeApiKey = (apiKey) => {
1119
+ if (apiKey === void 0) {
1120
+ return void 0;
1121
+ }
1122
+ if (typeof apiKey === "string") {
1123
+ return apiKey;
1124
+ }
1125
+ return Option.isSome(apiKey) ? apiKey.value : void 0;
1126
+ };
1127
+ var createEmbeddingProviderDirect = (config) =>
1128
+ Effect7.gen(function* () {
1129
+ const provider = config.provider;
1130
+ const baseURL = getProviderBaseURL(
1131
+ provider,
1132
+ normalizeBaseURL(config.baseURL),
1133
+ );
1134
+ return yield* createOpenAIProvider({
1135
+ model: config.model,
1136
+ batchSize: config.batchSize,
1137
+ baseURL,
1138
+ apiKey: normalizeApiKey(config.apiKey),
1139
+ });
1140
+ });
1141
+
1142
+ import { Effect as Effect8 } from "effect";
1143
+ // src/embeddings/vector-store.ts
1144
+ import * as fs3 from "fs/promises";
1145
+ import HierarchicalNSW from "hnswlib-node";
1146
+ import * as path3 from "path";
1147
+
1148
+ var VECTOR_INDEX_FILE = "vectors.bin";
1149
+ var VECTOR_META_FILE = "vectors.meta.json";
1150
+ var INDEX_VERSION = 1;
1151
+ var HnswVectorStore = class {
1152
+ rootPath;
1153
+ dimensions;
1154
+ index = null;
1155
+ entries = /* @__PURE__ */ new Map();
1156
+ idToIndex = /* @__PURE__ */ new Map();
1157
+ nextIndex = 0;
1158
+ provider = "unknown";
1159
+ providerModel = void 0;
1160
+ providerBaseURL = void 0;
1161
+ totalCost = 0;
1162
+ totalTokens = 0;
1163
+ constructor(rootPath, dimensions) {
1164
+ this.rootPath = path3.resolve(rootPath);
1165
+ this.dimensions = dimensions;
1166
+ }
1167
+ getIndexDir() {
1168
+ return path3.join(this.rootPath, INDEX_DIR);
1169
+ }
1170
+ getVectorPath() {
1171
+ return path3.join(this.getIndexDir(), VECTOR_INDEX_FILE);
1172
+ }
1173
+ getMetaPath() {
1174
+ return path3.join(this.getIndexDir(), VECTOR_META_FILE);
1175
+ }
1176
+ ensureIndex() {
1177
+ if (!this.index) {
1178
+ this.index = new HierarchicalNSW.HierarchicalNSW(
1179
+ "cosine",
1180
+ this.dimensions,
1181
+ );
1182
+ this.index.initIndex(1e4, 16, 200, 100);
1183
+ }
1184
+ return this.index;
1185
+ }
1186
+ add(entries) {
1187
+ return Effect8.try({
1188
+ try: () => {
1189
+ const index = this.ensureIndex();
1190
+ for (const entry of entries) {
1191
+ if (this.idToIndex.has(entry.id)) {
1192
+ continue;
1193
+ }
1194
+ const idx = this.nextIndex++;
1195
+ if (idx >= index.getMaxElements()) {
1196
+ index.resizeIndex(index.getMaxElements() * 2);
1197
+ }
1198
+ index.addPoint(entry.embedding, idx);
1199
+ this.entries.set(idx, entry);
1200
+ this.idToIndex.set(entry.id, idx);
1201
+ }
1202
+ },
1203
+ catch: (e) =>
1204
+ new VectorStoreError({
1205
+ operation: "add",
1206
+ message: e instanceof Error ? e.message : String(e),
1207
+ cause: e,
1208
+ }),
1209
+ });
1210
+ }
1211
+ search(vector, limit, threshold = 0) {
1212
+ return Effect8.try({
1213
+ try: () => {
1214
+ if (!this.index || this.entries.size === 0) {
1215
+ return [];
1216
+ }
1217
+ const result = this.index.searchKnn(
1218
+ vector,
1219
+ Math.min(limit, this.entries.size),
1220
+ );
1221
+ const results = [];
1222
+ for (let i = 0; i < result.neighbors.length; i++) {
1223
+ const idx = result.neighbors[i];
1224
+ const distance = result.distances[i];
1225
+ if (idx === void 0 || distance === void 0) {
1226
+ continue;
1227
+ }
1228
+ const similarity = 1 - distance;
1229
+ if (similarity < threshold) {
1230
+ continue;
1231
+ }
1232
+ const entry = this.entries.get(idx);
1233
+ if (entry) {
1234
+ results.push({
1235
+ id: entry.id,
1236
+ sectionId: entry.sectionId,
1237
+ documentPath: entry.documentPath,
1238
+ heading: entry.heading,
1239
+ similarity,
1240
+ });
1241
+ }
1242
+ }
1243
+ return results;
1244
+ },
1245
+ catch: (e) =>
1246
+ new VectorStoreError({
1247
+ operation: "search",
1248
+ message: e instanceof Error ? e.message : String(e),
1249
+ cause: e,
1250
+ }),
1251
+ });
1252
+ }
1253
+ save() {
1254
+ return Effect8.gen(
1255
+ function* () {
1256
+ if (!this.index) {
1257
+ return;
1258
+ }
1259
+ const indexDir = this.getIndexDir();
1260
+ yield* Effect8.tryPromise({
1261
+ try: () => fs3.mkdir(indexDir, { recursive: true }),
1262
+ catch: (e) =>
1263
+ new VectorStoreError({
1264
+ operation: "save",
1265
+ message: `Failed to create directory: ${e instanceof Error ? e.message : String(e)}`,
1266
+ cause: e,
1267
+ }),
1268
+ });
1269
+ yield* Effect8.tryPromise({
1270
+ try: () => this.index.writeIndex(this.getVectorPath()),
1271
+ catch: (e) =>
1272
+ new VectorStoreError({
1273
+ operation: "save",
1274
+ message: `Failed to write index: ${e instanceof Error ? e.message : String(e)}`,
1275
+ cause: e,
1276
+ }),
1277
+ });
1278
+ const meta = {
1279
+ version: INDEX_VERSION,
1280
+ provider: this.provider,
1281
+ providerModel: this.providerModel,
1282
+ providerBaseURL: this.providerBaseURL,
1283
+ dimensions: this.dimensions,
1284
+ entries: Object.fromEntries(
1285
+ Array.from(this.entries.entries()).map(([idx, entry]) => [
1286
+ idx.toString(),
1287
+ entry,
1288
+ ]),
1289
+ ),
1290
+ totalCost: this.totalCost,
1291
+ totalTokens: this.totalTokens,
1292
+ createdAt: /* @__PURE__ */ new Date().toISOString(),
1293
+ updatedAt: /* @__PURE__ */ new Date().toISOString(),
1294
+ };
1295
+ yield* Effect8.tryPromise({
1296
+ try: () =>
1297
+ fs3.writeFile(this.getMetaPath(), JSON.stringify(meta, null, 2)),
1298
+ catch: (e) =>
1299
+ new VectorStoreError({
1300
+ operation: "save",
1301
+ message: `Failed to write metadata: ${e instanceof Error ? e.message : String(e)}`,
1302
+ cause: e,
1303
+ }),
1304
+ });
1305
+ }.bind(this),
1306
+ );
1307
+ }
1308
+ load() {
1309
+ return Effect8.gen(
1310
+ function* () {
1311
+ const vectorPath = this.getVectorPath();
1312
+ const metaPath = this.getMetaPath();
1313
+ const filesExist = yield* Effect8.tryPromise({
1314
+ try: async () => {
1315
+ await fs3.access(vectorPath);
1316
+ await fs3.access(metaPath);
1317
+ return true;
1318
+ },
1319
+ catch: () =>
1320
+ new VectorStoreError({
1321
+ operation: "load",
1322
+ message: "Files not found",
1323
+ }),
1324
+ }).pipe(
1325
+ Effect8.catchTag("VectorStoreError", () => Effect8.succeed(false)),
1326
+ );
1327
+ if (!filesExist) {
1328
+ return false;
1329
+ }
1330
+ const metaContent = yield* Effect8.tryPromise({
1331
+ try: () => fs3.readFile(metaPath, "utf-8"),
1332
+ catch: (e) =>
1333
+ new VectorStoreError({
1334
+ operation: "load",
1335
+ message: `Failed to read metadata: ${e instanceof Error ? e.message : String(e)}`,
1336
+ cause: e,
1337
+ }),
1338
+ });
1339
+ const loadedMeta = yield* Effect8.try({
1340
+ try: () => JSON.parse(metaContent),
1341
+ catch: (e) =>
1342
+ new VectorStoreError({
1343
+ operation: "load",
1344
+ message: `Failed to parse metadata: ${e instanceof Error ? e.message : String(e)}`,
1345
+ cause: e,
1346
+ }),
1347
+ });
1348
+ const meta = {
1349
+ ...loadedMeta,
1350
+ provider: loadedMeta.provider || "openai",
1351
+ };
1352
+ if (meta.dimensions !== this.dimensions) {
1353
+ return false;
1354
+ }
1355
+ this.index = new HierarchicalNSW.HierarchicalNSW(
1356
+ "cosine",
1357
+ this.dimensions,
1358
+ );
1359
+ yield* Effect8.tryPromise({
1360
+ try: () => this.index.readIndex(vectorPath),
1361
+ catch: (e) =>
1362
+ new VectorStoreError({
1363
+ operation: "load",
1364
+ message: `Failed to read index: ${e instanceof Error ? e.message : String(e)}`,
1365
+ cause: e,
1366
+ }),
1367
+ });
1368
+ this.entries.clear();
1369
+ this.idToIndex.clear();
1370
+ this.nextIndex = 0;
1371
+ for (const [idxStr, entry] of Object.entries(meta.entries)) {
1372
+ const idx = parseInt(idxStr, 10);
1373
+ this.entries.set(idx, entry);
1374
+ this.idToIndex.set(entry.id, idx);
1375
+ this.nextIndex = Math.max(this.nextIndex, idx + 1);
1376
+ }
1377
+ this.provider = meta.provider;
1378
+ this.providerModel = meta.providerModel;
1379
+ this.providerBaseURL = meta.providerBaseURL;
1380
+ this.totalCost = meta.totalCost;
1381
+ this.totalTokens = meta.totalTokens;
1382
+ return true;
1383
+ }.bind(this),
1384
+ );
1385
+ }
1386
+ getStats() {
1387
+ return {
1388
+ count: this.entries.size,
1389
+ dimensions: this.dimensions,
1390
+ provider: this.provider,
1391
+ providerModel: this.providerModel,
1392
+ totalCost: this.totalCost,
1393
+ totalTokens: this.totalTokens,
1394
+ };
1395
+ }
1396
+ setProvider(name, model, baseURL) {
1397
+ this.provider = name;
1398
+ this.providerModel = model;
1399
+ this.providerBaseURL = baseURL;
1400
+ }
1401
+ addCost(cost, tokens) {
1402
+ this.totalCost += cost;
1403
+ this.totalTokens += tokens;
1404
+ }
1405
+ };
1406
+ var createVectorStore = (rootPath, dimensions) =>
1407
+ new HnswVectorStore(rootPath, dimensions);
1408
+
1409
+ // src/embeddings/semantic-search.ts
1410
+ var generateEmbeddingText = (
1411
+ section,
1412
+ content,
1413
+ documentTitle,
1414
+ parentHeading,
1415
+ ) => {
1416
+ const parts = [];
1417
+ parts.push(`# ${section.heading}`);
1418
+ if (parentHeading) {
1419
+ parts.push(`Parent section: ${parentHeading}`);
1420
+ }
1421
+ parts.push(`Document: ${documentTitle}`);
1422
+ parts.push("");
1423
+ parts.push(content);
1424
+ return parts.join("\n");
1425
+ };
1426
+ var EMBEDDING_PRICE_PER_MILLION =
1427
+ PRICING_DATA.prices["text-embedding-3-small"] ?? 0.02;
1428
+ var estimateEmbeddingCost = (rootPath, options = {}) =>
1429
+ Effect9.gen(function* () {
1430
+ const resolvedRoot = path4.resolve(rootPath);
1431
+ const storage = createStorage(resolvedRoot);
1432
+ const docIndex = yield* loadDocumentIndex(storage);
1433
+ const sectionIndex = yield* loadSectionIndex(storage);
1434
+ if (!docIndex || !sectionIndex) {
1435
+ return yield* Effect9.fail(
1436
+ new IndexNotFoundError({ path: resolvedRoot }),
1437
+ );
1438
+ }
1439
+ const byDir = /* @__PURE__ */ new Map();
1440
+ for (const section of Object.values(sectionIndex.sections)) {
1441
+ if (section.tokenCount < 10) continue;
1442
+ if (options.excludePatterns?.length) {
1443
+ const excluded = options.excludePatterns.some((pattern) => {
1444
+ const regex = new RegExp(
1445
+ `^${pattern.replace(/\*/g, ".*").replace(/\?/g, ".")}$`,
1446
+ );
1447
+ return regex.test(section.documentPath);
1448
+ });
1449
+ if (excluded) continue;
1450
+ }
1451
+ const dir = path4.dirname(section.documentPath) || ".";
1452
+ if (!byDir.has(dir)) {
1453
+ byDir.set(dir, {
1454
+ files: /* @__PURE__ */ new Set(),
1455
+ sections: 0,
1456
+ tokens: 0,
1457
+ });
1458
+ }
1459
+ const entry = byDir.get(dir);
1460
+ entry.files.add(section.documentPath);
1461
+ entry.sections++;
1462
+ entry.tokens += section.tokenCount;
1463
+ }
1464
+ const directoryEstimates = [];
1465
+ let totalFiles = 0;
1466
+ let totalSections = 0;
1467
+ let totalTokens = 0;
1468
+ for (const [dir, data] of byDir) {
1469
+ directoryEstimates.push({
1470
+ directory: dir,
1471
+ fileCount: data.files.size,
1472
+ sectionCount: data.sections,
1473
+ estimatedTokens: data.tokens,
1474
+ estimatedCost: (data.tokens / 1e6) * EMBEDDING_PRICE_PER_MILLION,
1475
+ });
1476
+ totalFiles += data.files.size;
1477
+ totalSections += data.sections;
1478
+ totalTokens += data.tokens;
1479
+ }
1480
+ directoryEstimates.sort((a, b) => a.directory.localeCompare(b.directory));
1481
+ const estimatedTimeSeconds = Math.ceil(totalSections / 100) * 1.5;
1482
+ return {
1483
+ totalFiles,
1484
+ totalSections,
1485
+ totalTokens,
1486
+ totalCost: (totalTokens / 1e6) * EMBEDDING_PRICE_PER_MILLION,
1487
+ estimatedTimeSeconds,
1488
+ byDirectory: directoryEstimates,
1489
+ };
1490
+ });
1491
+ var buildEmbeddings = (rootPath, options = {}) =>
1492
+ Effect9.gen(function* () {
1493
+ const startTime = Date.now();
1494
+ const resolvedRoot = path4.resolve(rootPath);
1495
+ const storage = createStorage(resolvedRoot);
1496
+ const docIndex = yield* loadDocumentIndex(storage);
1497
+ const sectionIndex = yield* loadSectionIndex(storage);
1498
+ if (!docIndex || !sectionIndex) {
1499
+ return yield* Effect9.fail(
1500
+ new IndexNotFoundError({ path: resolvedRoot }),
1501
+ );
1502
+ }
1503
+ const providerConfig = options.providerConfig ?? { provider: "openai" };
1504
+ const provider =
1505
+ options.provider ??
1506
+ (yield* createEmbeddingProviderDirect(providerConfig));
1507
+ const dimensions = provider.dimensions;
1508
+ const vectorStore = createVectorStore(resolvedRoot, dimensions);
1509
+ const providerMeta = provider;
1510
+ const model =
1511
+ typeof providerMeta.model === "string" ? providerMeta.model : void 0;
1512
+ const baseURL =
1513
+ typeof providerMeta.baseURL === "string" ? providerMeta.baseURL : void 0;
1514
+ vectorStore.setProvider(provider.name, model, baseURL);
1515
+ if (!options.force) {
1516
+ const loaded = yield* vectorStore.load();
1517
+ if (loaded) {
1518
+ const stats = vectorStore.getStats();
1519
+ if (stats.count > 0) {
1520
+ const duration2 = Date.now() - startTime;
1521
+ const estimatedSavings =
1522
+ (stats.totalTokens / 1e6) * EMBEDDING_PRICE_PER_MILLION;
1523
+ return {
1524
+ sectionsEmbedded: 0,
1525
+ tokensUsed: 0,
1526
+ cost: 0,
1527
+ duration: duration2,
1528
+ filesProcessed: 0,
1529
+ cacheHit: true,
1530
+ existingVectors: stats.count,
1531
+ estimatedSavings,
1532
+ };
1533
+ }
1534
+ }
1535
+ }
1536
+ const isExcluded = (docPath) => {
1537
+ if (!options.excludePatterns?.length) return false;
1538
+ return options.excludePatterns.some((pattern) => {
1539
+ const regex = new RegExp(
1540
+ `^${pattern.replace(/\*/g, ".*").replace(/\?/g, ".")}$`,
1541
+ );
1542
+ return regex.test(docPath);
1543
+ });
1544
+ };
1545
+ const sectionsByDoc = /* @__PURE__ */ new Map();
1546
+ for (const section of Object.values(sectionIndex.sections)) {
1547
+ const document = docIndex.documents[section.documentPath];
1548
+ if (!document) continue;
1549
+ if (section.tokenCount < 10) continue;
1550
+ if (isExcluded(section.documentPath)) continue;
1551
+ let parentHeading;
1552
+ if (section.level > 1) {
1553
+ const docSections = sectionIndex.byDocument[document.id] ?? [];
1554
+ for (const sibId of docSections) {
1555
+ const sib = sectionIndex.sections[sibId];
1556
+ if (
1557
+ sib &&
1558
+ sib.level === section.level - 1 &&
1559
+ sib.startLine < section.startLine
1560
+ ) {
1561
+ parentHeading = sib.heading;
1562
+ }
1563
+ }
1564
+ }
1565
+ const docPath = section.documentPath;
1566
+ if (!sectionsByDoc.has(docPath)) {
1567
+ sectionsByDoc.set(docPath, []);
1568
+ }
1569
+ sectionsByDoc.get(docPath).push({ section, parentHeading });
1570
+ }
1571
+ if (sectionsByDoc.size === 0) {
1572
+ const duration2 = Date.now() - startTime;
1573
+ return {
1574
+ sectionsEmbedded: 0,
1575
+ tokensUsed: 0,
1576
+ cost: 0,
1577
+ duration: duration2,
1578
+ filesProcessed: 0,
1579
+ };
1580
+ }
1581
+ const sectionsToEmbed = [];
1582
+ const docPaths = Array.from(sectionsByDoc.keys());
1583
+ let filesProcessed = 0;
1584
+ for (let fileIndex = 0; fileIndex < docPaths.length; fileIndex++) {
1585
+ const docPath = docPaths[fileIndex];
1586
+ const sections = sectionsByDoc.get(docPath);
1587
+ const document = docIndex.documents[docPath];
1588
+ if (!document) continue;
1589
+ if (options.onFileProgress) {
1590
+ options.onFileProgress({
1591
+ fileIndex: fileIndex + 1,
1592
+ totalFiles: docPaths.length,
1593
+ filePath: docPath,
1594
+ sectionCount: sections.length,
1595
+ });
1596
+ }
1597
+ const filePath = path4.join(resolvedRoot, docPath);
1598
+ const fileContentResult = yield* Effect9.promise(() =>
1599
+ fs4.readFile(filePath, "utf-8"),
1600
+ ).pipe(
1601
+ Effect9.map((content) => ({ ok: true, content })),
1602
+ Effect9.catchAll(() => Effect9.succeed({ ok: false, content: "" })),
1603
+ );
1604
+ if (!fileContentResult.ok) {
1605
+ yield* Effect9.logWarning(`Skipping file (cannot read): ${docPath}`);
1606
+ continue;
1607
+ }
1608
+ filesProcessed++;
1609
+ const lines = fileContentResult.content.split("\n");
1610
+ for (const { section, parentHeading } of sections) {
1611
+ const content = lines
1612
+ .slice(section.startLine - 1, section.endLine)
1613
+ .join("\n");
1614
+ const text = generateEmbeddingText(
1615
+ section,
1616
+ content,
1617
+ document.title,
1618
+ parentHeading,
1619
+ );
1620
+ sectionsToEmbed.push({ section, text });
1621
+ }
1622
+ }
1623
+ if (sectionsToEmbed.length === 0) {
1624
+ const duration2 = Date.now() - startTime;
1625
+ return {
1626
+ sectionsEmbedded: 0,
1627
+ tokensUsed: 0,
1628
+ cost: 0,
1629
+ duration: duration2,
1630
+ filesProcessed,
1631
+ };
1632
+ }
1633
+ const texts = sectionsToEmbed.map((s) => s.text);
1634
+ const result = yield* wrapEmbedding(provider.embed(texts));
1635
+ const entries = [];
1636
+ for (let i = 0; i < sectionsToEmbed.length; i++) {
1637
+ const { section } = sectionsToEmbed[i] ?? { section: null };
1638
+ const embedding = result.embeddings[i];
1639
+ if (!section || !embedding) continue;
1640
+ entries.push({
1641
+ id: section.id,
1642
+ sectionId: section.id,
1643
+ documentPath: section.documentPath,
1644
+ heading: section.heading,
1645
+ embedding,
1646
+ });
1647
+ }
1648
+ yield* vectorStore.add(entries);
1649
+ vectorStore.addCost(result.cost, result.tokensUsed);
1650
+ yield* vectorStore.save();
1651
+ const duration = Date.now() - startTime;
1652
+ return {
1653
+ sectionsEmbedded: entries.length,
1654
+ tokensUsed: result.tokensUsed,
1655
+ cost: result.cost,
1656
+ duration,
1657
+ filesProcessed,
1658
+ };
1659
+ });
1660
+ var semanticSearch = (rootPath, query, options = {}) =>
1661
+ Effect9.gen(function* () {
1662
+ const resolvedRoot = path4.resolve(rootPath);
1663
+ const provider = yield* createEmbeddingProviderDirect(
1664
+ options.providerConfig ?? { provider: "openai" },
1665
+ );
1666
+ const dimensions = provider.dimensions;
1667
+ const vectorStore = createVectorStore(resolvedRoot, dimensions);
1668
+ const loaded = yield* vectorStore.load();
1669
+ if (!loaded) {
1670
+ return yield* Effect9.fail(
1671
+ new EmbeddingsNotFoundError({ path: resolvedRoot }),
1672
+ );
1673
+ }
1674
+ const stats = vectorStore.getStats();
1675
+ const currentProviderModel =
1676
+ options.providerConfig?.model ?? "text-embedding-3-small";
1677
+ const currentProvider = options.providerConfig?.provider ?? "openai";
1678
+ if (stats.providerModel && stats.providerModel !== currentProviderModel) {
1679
+ console.warn(
1680
+ `\u26A0\uFE0F Index was created with ${stats.provider}/${stats.providerModel}`,
1681
+ );
1682
+ console.warn(
1683
+ ` but querying with ${currentProvider}/${currentProviderModel}`,
1684
+ );
1685
+ console.warn(" Results may be inconsistent. Consider re-indexing.");
1686
+ } else if (!stats.providerModel) {
1687
+ const indexProviderParts = stats.provider.split(":");
1688
+ if (
1689
+ indexProviderParts.length === 2 &&
1690
+ indexProviderParts[1] !== currentProviderModel
1691
+ ) {
1692
+ console.warn(
1693
+ `\u26A0\uFE0F Index was created with ${indexProviderParts[0]}/${indexProviderParts[1]}`,
1694
+ );
1695
+ console.warn(
1696
+ ` but querying with ${currentProvider}/${currentProviderModel}`,
1697
+ );
1698
+ console.warn(" Results may be inconsistent. Consider re-indexing.");
1699
+ }
1700
+ }
1701
+ const queryResult = yield* wrapEmbedding(provider.embed([query]));
1702
+ const queryVector = queryResult.embeddings[0];
1703
+ if (!queryVector) {
1704
+ return yield* Effect9.fail(
1705
+ new EmbeddingError({
1706
+ reason: "Unknown",
1707
+ message: "Failed to generate query embedding",
1708
+ provider: "OpenAI",
1709
+ }),
1710
+ );
1711
+ }
1712
+ const limit = options.limit ?? 10;
1713
+ const threshold = options.threshold ?? 0;
1714
+ const searchResults = yield* vectorStore.search(
1715
+ queryVector,
1716
+ limit * 2,
1717
+ threshold,
1718
+ );
1719
+ let filteredResults = searchResults;
1720
+ if (options.pathPattern) {
1721
+ const pattern = options.pathPattern
1722
+ .replace(/\./g, "\\.")
1723
+ .replace(/\*/g, ".*");
1724
+ const regex = new RegExp(`^${pattern}$`, "i");
1725
+ filteredResults = searchResults.filter((r) => regex.test(r.documentPath));
1726
+ }
1727
+ const results = filteredResults.slice(0, limit).map((r) => ({
1728
+ sectionId: r.sectionId,
1729
+ documentPath: r.documentPath,
1730
+ heading: r.heading,
1731
+ similarity: r.similarity,
1732
+ }));
1733
+ return results;
1734
+ });
1735
+ var getEmbeddingStats = (rootPath) =>
1736
+ Effect9.gen(function* () {
1737
+ const resolvedRoot = path4.resolve(rootPath);
1738
+ const vectorStore = createVectorStore(resolvedRoot, 1536);
1739
+ const loaded = yield* vectorStore.load();
1740
+ if (!loaded) {
1741
+ return {
1742
+ hasEmbeddings: false,
1743
+ count: 0,
1744
+ provider: "none",
1745
+ dimensions: 0,
1746
+ totalCost: 0,
1747
+ totalTokens: 0,
1748
+ };
1749
+ }
1750
+ const stats = vectorStore.getStats();
1751
+ return {
1752
+ hasEmbeddings: true,
1753
+ count: stats.count,
1754
+ provider: stats.provider,
1755
+ dimensions: stats.dimensions,
1756
+ totalCost: stats.totalCost,
1757
+ totalTokens: stats.totalTokens,
1758
+ };
1759
+ });
1760
+
1761
+ import { Effect as Effect10 } from "effect";
1762
+ // src/search/searcher.ts
1763
+ import * as fs5 from "fs/promises";
1764
+ import * as path5 from "path";
1765
+
1766
+ // src/search/query-parser.ts
1767
+ var tokenize = (query) => {
1768
+ const tokens = [];
1769
+ let i = 0;
1770
+ while (i < query.length) {
1771
+ if (/\s/.test(query[i])) {
1772
+ i++;
1773
+ continue;
1774
+ }
1775
+ if (query[i] === '"') {
1776
+ const start = i + 1;
1777
+ i++;
1778
+ while (i < query.length && query[i] !== '"') {
1779
+ i++;
1780
+ }
1781
+ const value = query.slice(start, i);
1782
+ tokens.push({ type: "PHRASE", value });
1783
+ i++;
1784
+ continue;
1785
+ }
1786
+ if (query[i] === "(") {
1787
+ tokens.push({ type: "LPAREN", value: "(" });
1788
+ i++;
1789
+ continue;
1790
+ }
1791
+ if (query[i] === ")") {
1792
+ tokens.push({ type: "RPAREN", value: ")" });
1793
+ i++;
1794
+ continue;
1795
+ }
1796
+ const wordMatch = query.slice(i).match(/^[^\s()"]+/);
1797
+ if (wordMatch) {
1798
+ const word = wordMatch[0];
1799
+ const upperWord = word.toUpperCase();
1800
+ if (upperWord === "AND") {
1801
+ tokens.push({ type: "AND", value: "AND" });
1802
+ } else if (upperWord === "OR") {
1803
+ tokens.push({ type: "OR", value: "OR" });
1804
+ } else if (upperWord === "NOT") {
1805
+ tokens.push({ type: "NOT", value: "NOT" });
1806
+ } else {
1807
+ tokens.push({ type: "TERM", value: word });
1808
+ }
1809
+ i += word.length;
1810
+ continue;
1811
+ }
1812
+ i++;
1813
+ }
1814
+ return tokens;
1815
+ };
1816
+ var Parser = class {
1817
+ tokens;
1818
+ pos = 0;
1819
+ terms = [];
1820
+ phrases = [];
1821
+ constructor(tokens) {
1822
+ this.tokens = tokens;
1823
+ }
1824
+ current() {
1825
+ return this.tokens[this.pos];
1826
+ }
1827
+ advance() {
1828
+ return this.tokens[this.pos++];
1829
+ }
1830
+ match(type) {
1831
+ if (this.current()?.type === type) {
1832
+ this.advance();
1833
+ return true;
1834
+ }
1835
+ return false;
1836
+ }
1837
+ parse() {
1838
+ if (this.tokens.length === 0) {
1839
+ return null;
1840
+ }
1841
+ return this.parseExpr();
1842
+ }
1843
+ parseExpr() {
1844
+ let left = this.parseAndExpr();
1845
+ while (this.match("OR")) {
1846
+ const right = this.parseAndExpr();
1847
+ left = { type: "or", left, right };
1848
+ }
1849
+ return left;
1850
+ }
1851
+ parseAndExpr() {
1852
+ let left = this.parseNotExpr();
1853
+ while (this.match("AND") || this.isImplicitAnd()) {
1854
+ const right = this.parseNotExpr();
1855
+ left = { type: "and", left, right };
1856
+ }
1857
+ return left;
1858
+ }
1859
+ isImplicitAnd() {
1860
+ const tok = this.current();
1861
+ return (
1862
+ tok?.type === "TERM" ||
1863
+ tok?.type === "PHRASE" ||
1864
+ tok?.type === "NOT" ||
1865
+ tok?.type === "LPAREN"
1866
+ );
1867
+ }
1868
+ parseNotExpr() {
1869
+ if (this.match("NOT")) {
1870
+ const operand = this.parseNotExpr();
1871
+ return { type: "not", operand };
1872
+ }
1873
+ return this.parsePrimary();
1874
+ }
1875
+ parsePrimary() {
1876
+ const tok = this.current();
1877
+ if (this.match("LPAREN")) {
1878
+ const expr = this.parseExpr();
1879
+ this.match("RPAREN");
1880
+ return expr;
1881
+ }
1882
+ if (tok?.type === "PHRASE") {
1883
+ this.advance();
1884
+ this.phrases.push(tok.value);
1885
+ return { type: "phrase", value: tok.value };
1886
+ }
1887
+ if (tok?.type === "TERM") {
1888
+ this.advance();
1889
+ this.terms.push(tok.value);
1890
+ return { type: "term", value: tok.value };
1891
+ }
1892
+ return { type: "term", value: "" };
1893
+ }
1894
+ };
1895
+ var parseQuery = (query) => {
1896
+ const tokens = tokenize(query);
1897
+ if (tokens.length === 0) {
1898
+ return null;
1899
+ }
1900
+ const parser = new Parser(tokens);
1901
+ const ast = parser.parse();
1902
+ if (!ast) {
1903
+ return null;
1904
+ }
1905
+ return {
1906
+ ast,
1907
+ terms: parser.terms,
1908
+ phrases: parser.phrases,
1909
+ };
1910
+ };
1911
+ var isAdvancedQuery = (query) => {
1912
+ const tokens = tokenize(query);
1913
+ return tokens.some(
1914
+ (t) =>
1915
+ t.type === "AND" ||
1916
+ t.type === "OR" ||
1917
+ t.type === "NOT" ||
1918
+ t.type === "PHRASE" ||
1919
+ t.type === "LPAREN",
1920
+ );
1921
+ };
1922
+ var evaluateQuery = (ast, text) => {
1923
+ const lowerText = text.toLowerCase();
1924
+ const evaluate = (node) => {
1925
+ switch (node.type) {
1926
+ case "term": {
1927
+ if (!node.value) return true;
1928
+ return lowerText.includes(node.value.toLowerCase());
1929
+ }
1930
+ case "phrase": {
1931
+ return lowerText.includes(node.value.toLowerCase());
1932
+ }
1933
+ case "and": {
1934
+ return evaluate(node.left) && evaluate(node.right);
1935
+ }
1936
+ case "or": {
1937
+ return evaluate(node.left) || evaluate(node.right);
1938
+ }
1939
+ case "not": {
1940
+ return !evaluate(node.operand);
1941
+ }
1942
+ }
1943
+ };
1944
+ return evaluate(ast);
1945
+ };
1946
+ var buildHighlightPattern = (parsed) => {
1947
+ const patterns = [];
1948
+ const escapeChars = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1949
+ for (const term of parsed.terms) {
1950
+ if (term) {
1951
+ patterns.push(`\\b${escapeChars(term)}\\b`);
1952
+ }
1953
+ }
1954
+ for (const phrase of parsed.phrases) {
1955
+ if (phrase) {
1956
+ patterns.push(escapeChars(phrase));
1957
+ }
1958
+ }
1959
+ if (patterns.length === 0) {
1960
+ return /.^/;
1961
+ }
1962
+ return new RegExp(patterns.join("|"), "gi");
1963
+ };
1964
+
1965
+ // src/search/searcher.ts
1966
+ var matchPath = (filePath, pattern) => {
1967
+ const regexPattern = pattern
1968
+ .replace(/\./g, "\\.")
1969
+ .replace(/\*/g, ".*")
1970
+ .replace(/\?/g, ".");
1971
+ const regex = new RegExp(`^${regexPattern}$`, "i");
1972
+ return regex.test(filePath);
1973
+ };
1974
+ var search = (rootPath, options = {}) =>
1975
+ Effect10.gen(function* () {
1976
+ const storage = createStorage(rootPath);
1977
+ const docIndex = yield* loadDocumentIndex(storage);
1978
+ const sectionIndex = yield* loadSectionIndex(storage);
1979
+ if (!docIndex || !sectionIndex) {
1980
+ return [];
1981
+ }
1982
+ const results = [];
1983
+ const headingRegex = options.heading
1984
+ ? new RegExp(options.heading, "i")
1985
+ : null;
1986
+ for (const section of Object.values(sectionIndex.sections)) {
1987
+ if (headingRegex && !headingRegex.test(section.heading)) {
1988
+ continue;
1989
+ }
1990
+ if (
1991
+ options.pathPattern &&
1992
+ !matchPath(section.documentPath, options.pathPattern)
1993
+ ) {
1994
+ continue;
1995
+ }
1996
+ if (options.hasCode !== void 0 && section.hasCode !== options.hasCode) {
1997
+ continue;
1998
+ }
1999
+ if (options.hasList !== void 0 && section.hasList !== options.hasList) {
2000
+ continue;
2001
+ }
2002
+ if (
2003
+ options.hasTable !== void 0 &&
2004
+ section.hasTable !== options.hasTable
2005
+ ) {
2006
+ continue;
2007
+ }
2008
+ if (options.minLevel !== void 0 && section.level < options.minLevel) {
2009
+ continue;
2010
+ }
2011
+ if (options.maxLevel !== void 0 && section.level > options.maxLevel) {
2012
+ continue;
2013
+ }
2014
+ const document = docIndex.documents[section.documentPath];
2015
+ if (document) {
2016
+ results.push({ section, document });
2017
+ }
2018
+ if (options.limit !== void 0 && results.length >= options.limit) {
2019
+ break;
2020
+ }
2021
+ }
2022
+ return results;
2023
+ });
2024
+ var searchContent = (rootPath, options = {}) =>
2025
+ Effect10.gen(function* () {
2026
+ const storage = createStorage(rootPath);
2027
+ const docIndex = yield* loadDocumentIndex(storage);
2028
+ const sectionIndex = yield* loadSectionIndex(storage);
2029
+ if (!docIndex || !sectionIndex) {
2030
+ return [];
2031
+ }
2032
+ let parsedQuery = null;
2033
+ let contentRegex = null;
2034
+ let highlightRegex = null;
2035
+ if (options.content) {
2036
+ if (isAdvancedQuery(options.content)) {
2037
+ parsedQuery = parseQuery(options.content);
2038
+ if (parsedQuery) {
2039
+ highlightRegex = buildHighlightPattern(parsedQuery);
2040
+ }
2041
+ } else {
2042
+ contentRegex = new RegExp(options.content, "gi");
2043
+ highlightRegex = contentRegex;
2044
+ }
2045
+ }
2046
+ const headingRegex = options.heading
2047
+ ? new RegExp(options.heading, "i")
2048
+ : null;
2049
+ const results = [];
2050
+ const sectionsByDoc = {};
2051
+ for (const section of Object.values(sectionIndex.sections)) {
2052
+ const docSections = sectionsByDoc[section.documentPath];
2053
+ if (docSections) {
2054
+ docSections.push(section);
2055
+ } else {
2056
+ sectionsByDoc[section.documentPath] = [section];
2057
+ }
2058
+ }
2059
+ for (const [docPath, sections] of Object.entries(sectionsByDoc)) {
2060
+ if (options.pathPattern && !matchPath(docPath, options.pathPattern)) {
2061
+ continue;
2062
+ }
2063
+ const document = docIndex.documents[docPath];
2064
+ if (!document) continue;
2065
+ let fileContent = null;
2066
+ let fileLines = [];
2067
+ if (parsedQuery || contentRegex) {
2068
+ const filePath = path5.join(storage.rootPath, docPath);
2069
+ try {
2070
+ fileContent = yield* Effect10.promise(() =>
2071
+ fs5.readFile(filePath, "utf-8"),
2072
+ );
2073
+ fileLines = fileContent.split("\n");
2074
+ } catch {
2075
+ continue;
2076
+ }
2077
+ }
2078
+ for (const section of sections) {
2079
+ if (headingRegex && !headingRegex.test(section.heading)) {
2080
+ continue;
2081
+ }
2082
+ if (options.hasCode !== void 0 && section.hasCode !== options.hasCode) {
2083
+ continue;
2084
+ }
2085
+ if (options.hasList !== void 0 && section.hasList !== options.hasList) {
2086
+ continue;
2087
+ }
2088
+ if (
2089
+ options.hasTable !== void 0 &&
2090
+ section.hasTable !== options.hasTable
2091
+ ) {
2092
+ continue;
2093
+ }
2094
+ if (options.minLevel !== void 0 && section.level < options.minLevel) {
2095
+ continue;
2096
+ }
2097
+ if (options.maxLevel !== void 0 && section.level > options.maxLevel) {
2098
+ continue;
2099
+ }
2100
+ if ((parsedQuery || contentRegex) && fileContent) {
2101
+ const sectionLines = fileLines.slice(
2102
+ section.startLine - 1,
2103
+ section.endLine,
2104
+ );
2105
+ const sectionContent = sectionLines.join("\n");
2106
+ if (parsedQuery) {
2107
+ if (!evaluateQuery(parsedQuery.ast, sectionContent)) {
2108
+ continue;
2109
+ }
2110
+ }
2111
+ const matches = [];
2112
+ const searchRegex = contentRegex || highlightRegex;
2113
+ const contextBefore = options.contextBefore ?? 1;
2114
+ const contextAfter = options.contextAfter ?? 1;
2115
+ if (searchRegex) {
2116
+ for (let i = 0; i < sectionLines.length; i++) {
2117
+ const line = sectionLines[i];
2118
+ if (line && searchRegex.test(line)) {
2119
+ searchRegex.lastIndex = 0;
2120
+ const absoluteLineNum = section.startLine + i;
2121
+ const snippetStart = Math.max(0, i - contextBefore);
2122
+ const snippetEnd = Math.min(
2123
+ sectionLines.length,
2124
+ i + contextAfter + 1,
2125
+ );
2126
+ const snippetLines = sectionLines.slice(
2127
+ snippetStart,
2128
+ snippetEnd,
2129
+ );
2130
+ const snippet = snippetLines.join("\n");
2131
+ const contextLines = [];
2132
+ for (let j = snippetStart; j < snippetEnd; j++) {
2133
+ const ctxLine = sectionLines[j];
2134
+ if (ctxLine !== void 0) {
2135
+ contextLines.push({
2136
+ lineNumber: section.startLine + j,
2137
+ line: ctxLine,
2138
+ isMatch: j === i,
2139
+ });
2140
+ }
2141
+ }
2142
+ matches.push({
2143
+ lineNumber: absoluteLineNum,
2144
+ line,
2145
+ snippet,
2146
+ contextLines,
2147
+ });
2148
+ }
2149
+ }
2150
+ }
2151
+ if (parsedQuery || matches.length > 0) {
2152
+ const result = {
2153
+ section,
2154
+ document,
2155
+ sectionContent,
2156
+ };
2157
+ if (matches.length > 0) {
2158
+ results.push({ ...result, matches });
2159
+ } else {
2160
+ results.push(result);
2161
+ }
2162
+ if (options.limit !== void 0 && results.length >= options.limit) {
2163
+ return results;
2164
+ }
2165
+ }
2166
+ } else if (!parsedQuery && !contentRegex) {
2167
+ results.push({ section, document });
2168
+ if (options.limit !== void 0 && results.length >= options.limit) {
2169
+ return results;
2170
+ }
2171
+ }
2172
+ }
2173
+ }
2174
+ return results;
2175
+ });
2176
+
2177
+ export {
2178
+ CONFIG_FILE_NAMES,
2179
+ findConfigFile,
2180
+ loadConfigFile,
2181
+ readEnvConfig,
2182
+ createConfigProvider,
2183
+ createConfigProviderSync,
2184
+ ConfigService,
2185
+ ConfigServiceDefault,
2186
+ formatSummary,
2187
+ formatAssembledContext,
2188
+ summarizeFile,
2189
+ assembleContext,
2190
+ checkPricingFreshness,
2191
+ getPricingDate,
2192
+ estimateEmbeddingCost,
2193
+ buildEmbeddings,
2194
+ semanticSearch,
2195
+ getEmbeddingStats,
2196
+ isAdvancedQuery,
2197
+ search,
2198
+ searchContent,
2199
+ };