mdcontext 0.0.1 → 0.1.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 (140) hide show
  1. package/.changeset/README.md +28 -0
  2. package/.changeset/config.json +11 -0
  3. package/.github/workflows/ci.yml +83 -0
  4. package/.github/workflows/release.yml +113 -0
  5. package/.tldrignore +112 -0
  6. package/AGENTS.md +46 -0
  7. package/BACKLOG.md +338 -0
  8. package/README.md +231 -11
  9. package/biome.json +36 -0
  10. package/cspell.config.yaml +14 -0
  11. package/dist/chunk-KRYIFLQR.js +92 -0
  12. package/dist/chunk-S7E6TFX6.js +742 -0
  13. package/dist/chunk-VVTGZNBT.js +1519 -0
  14. package/dist/cli/main.d.ts +1 -0
  15. package/dist/cli/main.js +2015 -0
  16. package/dist/index.d.ts +266 -0
  17. package/dist/index.js +86 -0
  18. package/dist/mcp/server.d.ts +1 -0
  19. package/dist/mcp/server.js +376 -0
  20. package/docs/019-USAGE.md +586 -0
  21. package/docs/020-current-implementation.md +364 -0
  22. package/docs/021-DOGFOODING-FINDINGS.md +175 -0
  23. package/docs/BACKLOG.md +80 -0
  24. package/docs/DESIGN.md +439 -0
  25. package/docs/PROJECT.md +88 -0
  26. package/docs/ROADMAP.md +407 -0
  27. package/docs/test-links.md +9 -0
  28. package/package.json +69 -10
  29. package/pnpm-workspace.yaml +5 -0
  30. package/research/config-analysis/01-current-implementation.md +470 -0
  31. package/research/config-analysis/02-strategy-recommendation.md +428 -0
  32. package/research/config-analysis/03-task-candidates.md +715 -0
  33. package/research/config-analysis/033-research-configuration-management.md +828 -0
  34. package/research/config-analysis/034-research-effect-cli-config.md +1504 -0
  35. package/research/config-analysis/04-consolidated-task-candidates.md +277 -0
  36. package/research/dogfood/consolidated-tool-evaluation.md +373 -0
  37. package/research/dogfood/strategy-a/a-synthesis.md +184 -0
  38. package/research/dogfood/strategy-a/a1-docs.md +226 -0
  39. package/research/dogfood/strategy-a/a2-amorphic.md +156 -0
  40. package/research/dogfood/strategy-a/a3-llm.md +164 -0
  41. package/research/dogfood/strategy-b/b-synthesis.md +228 -0
  42. package/research/dogfood/strategy-b/b1-architecture.md +207 -0
  43. package/research/dogfood/strategy-b/b2-gaps.md +258 -0
  44. package/research/dogfood/strategy-b/b3-workflows.md +250 -0
  45. package/research/dogfood/strategy-c/c-synthesis.md +451 -0
  46. package/research/dogfood/strategy-c/c1-explorer.md +192 -0
  47. package/research/dogfood/strategy-c/c2-diver-memory.md +145 -0
  48. package/research/dogfood/strategy-c/c3-diver-control.md +148 -0
  49. package/research/dogfood/strategy-c/c4-diver-failure.md +151 -0
  50. package/research/dogfood/strategy-c/c5-diver-execution.md +221 -0
  51. package/research/dogfood/strategy-c/c6-diver-org.md +221 -0
  52. package/research/effect-cli-error-handling.md +845 -0
  53. package/research/effect-errors-as-values.md +943 -0
  54. package/research/errors-task-analysis/00-consolidated-tasks.md +207 -0
  55. package/research/errors-task-analysis/cli-commands-analysis.md +909 -0
  56. package/research/errors-task-analysis/embeddings-analysis.md +709 -0
  57. package/research/errors-task-analysis/index-search-analysis.md +812 -0
  58. package/research/mdcontext-error-analysis.md +521 -0
  59. package/research/npm_publish/011-npm-workflow-research-agent2.md +792 -0
  60. package/research/npm_publish/012-npm-workflow-research-agent1.md +530 -0
  61. package/research/npm_publish/013-npm-workflow-research-agent3.md +722 -0
  62. package/research/npm_publish/014-npm-workflow-synthesis.md +556 -0
  63. package/research/npm_publish/031-npm-workflow-task-analysis.md +134 -0
  64. package/research/semantic-search/002-research-embedding-models.md +490 -0
  65. package/research/semantic-search/003-research-rag-alternatives.md +523 -0
  66. package/research/semantic-search/004-research-vector-search.md +841 -0
  67. package/research/semantic-search/032-research-semantic-search.md +427 -0
  68. package/research/task-management-2026/00-synthesis-recommendations.md +295 -0
  69. package/research/task-management-2026/01-ai-workflow-tools.md +416 -0
  70. package/research/task-management-2026/02-agent-framework-patterns.md +476 -0
  71. package/research/task-management-2026/03-lightweight-file-based.md +567 -0
  72. package/research/task-management-2026/04-established-tools-ai-features.md +541 -0
  73. package/research/task-management-2026/linear/01-core-features-workflow.md +771 -0
  74. package/research/task-management-2026/linear/02-api-integrations.md +930 -0
  75. package/research/task-management-2026/linear/03-ai-features.md +368 -0
  76. package/research/task-management-2026/linear/04-pricing-setup.md +205 -0
  77. package/research/task-management-2026/linear/05-usage-patterns-best-practices.md +605 -0
  78. package/scripts/rebuild-hnswlib.js +63 -0
  79. package/src/cli/argv-preprocessor.test.ts +210 -0
  80. package/src/cli/argv-preprocessor.ts +202 -0
  81. package/src/cli/cli.test.ts +430 -0
  82. package/src/cli/commands/backlinks.ts +54 -0
  83. package/src/cli/commands/context.ts +197 -0
  84. package/src/cli/commands/index-cmd.ts +300 -0
  85. package/src/cli/commands/index.ts +13 -0
  86. package/src/cli/commands/links.ts +52 -0
  87. package/src/cli/commands/search.ts +451 -0
  88. package/src/cli/commands/stats.ts +146 -0
  89. package/src/cli/commands/tree.ts +107 -0
  90. package/src/cli/flag-schemas.ts +275 -0
  91. package/src/cli/help.ts +386 -0
  92. package/src/cli/index.ts +9 -0
  93. package/src/cli/main.ts +145 -0
  94. package/src/cli/options.ts +31 -0
  95. package/src/cli/typo-suggester.test.ts +105 -0
  96. package/src/cli/typo-suggester.ts +130 -0
  97. package/src/cli/utils.ts +126 -0
  98. package/src/core/index.ts +1 -0
  99. package/src/core/types.ts +140 -0
  100. package/src/embeddings/index.ts +8 -0
  101. package/src/embeddings/openai-provider.ts +165 -0
  102. package/src/embeddings/semantic-search.ts +583 -0
  103. package/src/embeddings/types.ts +82 -0
  104. package/src/embeddings/vector-store.ts +299 -0
  105. package/src/index/index.ts +4 -0
  106. package/src/index/indexer.ts +446 -0
  107. package/src/index/storage.ts +196 -0
  108. package/src/index/types.ts +109 -0
  109. package/src/index/watcher.ts +131 -0
  110. package/src/index.ts +8 -0
  111. package/src/mcp/server.ts +483 -0
  112. package/src/parser/index.ts +1 -0
  113. package/src/parser/parser.test.ts +291 -0
  114. package/src/parser/parser.ts +395 -0
  115. package/src/parser/section-filter.ts +270 -0
  116. package/src/search/query-parser.test.ts +260 -0
  117. package/src/search/query-parser.ts +319 -0
  118. package/src/search/searcher.test.ts +182 -0
  119. package/src/search/searcher.ts +602 -0
  120. package/src/summarize/budget-bugs.test.ts +620 -0
  121. package/src/summarize/formatters.ts +419 -0
  122. package/src/summarize/index.ts +20 -0
  123. package/src/summarize/summarizer.test.ts +275 -0
  124. package/src/summarize/summarizer.ts +528 -0
  125. package/src/summarize/verify-bugs.test.ts +238 -0
  126. package/src/utils/index.ts +1 -0
  127. package/src/utils/tokens.test.ts +142 -0
  128. package/src/utils/tokens.ts +186 -0
  129. package/tests/fixtures/cli/.mdcontext/config.json +8 -0
  130. package/tests/fixtures/cli/.mdcontext/indexes/documents.json +33 -0
  131. package/tests/fixtures/cli/.mdcontext/indexes/links.json +12 -0
  132. package/tests/fixtures/cli/.mdcontext/indexes/sections.json +233 -0
  133. package/tests/fixtures/cli/.mdcontext/vectors.bin +0 -0
  134. package/tests/fixtures/cli/.mdcontext/vectors.meta.json +1264 -0
  135. package/tests/fixtures/cli/README.md +9 -0
  136. package/tests/fixtures/cli/api-reference.md +11 -0
  137. package/tests/fixtures/cli/getting-started.md +11 -0
  138. package/tsconfig.json +26 -0
  139. package/vitest.config.ts +21 -0
  140. package/vitest.setup.ts +12 -0
@@ -0,0 +1,1519 @@
1
+ import {
2
+ INDEX_DIR,
3
+ countTokensApprox,
4
+ createStorage,
5
+ loadDocumentIndex,
6
+ loadSectionIndex,
7
+ parseFile
8
+ } from "./chunk-S7E6TFX6.js";
9
+
10
+ // src/summarize/formatters.ts
11
+ var formatSummary = (summary, options = {}) => {
12
+ const maxTokens = options.maxTokens;
13
+ const flatSections = [];
14
+ const collectSections = (section, depth = 0, parentNumber = "", index = 0) => {
15
+ const number = parentNumber ? `${parentNumber}.${index + 1}` : `${index + 1}`;
16
+ flatSections.push({ section, depth, number });
17
+ section.children.forEach((child, i) => {
18
+ collectSections(child, depth + 1, number, i);
19
+ });
20
+ };
21
+ summary.sections.forEach((section, i) => {
22
+ collectSections(section, 0, "", i);
23
+ });
24
+ const buildOutput = (includedSectionIndices, truncationInfo, includeTopics2) => {
25
+ const lines = [];
26
+ if (truncationInfo.showWarning && truncationInfo.truncatedCount > 0 && truncationInfo.tokensTotal > 0) {
27
+ const pct = Math.round(
28
+ truncationInfo.tokensShown / truncationInfo.tokensTotal * 100
29
+ );
30
+ lines.push(
31
+ `\u26A0\uFE0F Truncated: Showing ~${truncationInfo.tokensShown}/${truncationInfo.tokensTotal} tokens (${pct}%)`
32
+ );
33
+ if (truncationInfo.includedNumbers.length > 0) {
34
+ const includedDisplay = truncationInfo.includedNumbers.length <= 6 ? truncationInfo.includedNumbers.join(", ") : truncationInfo.includedNumbers.slice(0, 5).join(", ") + `, ... (+${truncationInfo.includedNumbers.length - 5} more)`;
35
+ lines.push(`Sections included: ${includedDisplay}`);
36
+ }
37
+ if (truncationInfo.excludedNumbers.length > 0) {
38
+ const excludedDisplay = truncationInfo.excludedNumbers.length <= 6 ? truncationInfo.excludedNumbers.join(", ") : truncationInfo.excludedNumbers.slice(0, 5).join(", ") + `, ... (+${truncationInfo.excludedNumbers.length - 5} more)`;
39
+ lines.push(`Sections excluded: ${excludedDisplay}`);
40
+ }
41
+ lines.push(
42
+ "Use --full for complete content or --section to target specific sections."
43
+ );
44
+ lines.push("");
45
+ }
46
+ lines.push(`# ${summary.title}`);
47
+ lines.push(`Path: ${summary.path}`);
48
+ const tokenLineIndex = lines.length;
49
+ lines.push("PLACEHOLDER");
50
+ lines.push("");
51
+ const fullTopicsLine2 = summary.keyTopics.length > 0 ? `**Topics:** ${summary.keyTopics.join(", ")}` : "";
52
+ if (includeTopics2 && fullTopicsLine2) {
53
+ lines.push(fullTopicsLine2);
54
+ lines.push("");
55
+ }
56
+ const sectionLines = [];
57
+ for (let i = 0; i < flatSections.length; i++) {
58
+ if (!includedSectionIndices.has(i)) continue;
59
+ const { section, depth } = flatSections[i];
60
+ const indent = " ".repeat(depth);
61
+ const prefix = "#".repeat(section.level);
62
+ sectionLines.push(`${indent}${prefix} ${section.heading}`);
63
+ if (section.summary) {
64
+ sectionLines.push(`${indent}${section.summary}`);
65
+ }
66
+ }
67
+ lines.push(sectionLines.join("\n"));
68
+ const tempOutput = lines.join("\n");
69
+ const tokensWithoutLine = countTokensApprox(
70
+ tempOutput.replace("PLACEHOLDER", "")
71
+ );
72
+ let estimatedTotal = tokensWithoutLine + 8;
73
+ for (let iter = 0; iter < 3; iter++) {
74
+ const testTokenLine = `Tokens: ${estimatedTotal} (${(summary.compressionRatio * 100).toFixed(0)}% reduction from ${summary.originalTokens})`;
75
+ const testOutput = tempOutput.replace("PLACEHOLDER", testTokenLine);
76
+ const actualTotal = countTokensApprox(testOutput);
77
+ if (actualTotal === estimatedTotal) break;
78
+ estimatedTotal = actualTotal;
79
+ }
80
+ const finalTokenLine = `Tokens: ${estimatedTotal} (${(summary.compressionRatio * 100).toFixed(0)}% reduction from ${summary.originalTokens})`;
81
+ lines[tokenLineIndex] = finalTokenLine;
82
+ return lines.join("\n");
83
+ };
84
+ if (maxTokens === void 0) {
85
+ const allIndices = new Set(flatSections.map((_, i) => i));
86
+ const hasPriorTruncation = summary.truncated && summary.truncatedCount;
87
+ return buildOutput(
88
+ allIndices,
89
+ {
90
+ showWarning: !!hasPriorTruncation,
91
+ truncatedCount: summary.truncatedCount ?? 0,
92
+ includedNumbers: flatSections.map((s) => s.number),
93
+ excludedNumbers: [],
94
+ tokensShown: summary.summaryTokens,
95
+ tokensTotal: summary.originalTokens
96
+ },
97
+ true
98
+ );
99
+ }
100
+ const includedIndices = /* @__PURE__ */ new Set();
101
+ let truncatedCount = 0;
102
+ let includeTopics = true;
103
+ const SAFETY_MARGIN = 1.15;
104
+ const minHeaderTemplate = [
105
+ `# ${summary.title}`,
106
+ `Path: ${summary.path}`,
107
+ `Tokens: 9999 (${(summary.compressionRatio * 100).toFixed(0)}% reduction from ${summary.originalTokens})`,
108
+ "",
109
+ ""
110
+ ].join("\n");
111
+ const minHeaderTokens = Math.ceil(
112
+ countTokensApprox(minHeaderTemplate) * SAFETY_MARGIN
113
+ );
114
+ const fullTopicsLine = summary.keyTopics.length > 0 ? `**Topics:** ${summary.keyTopics.join(", ")}
115
+ ` : "";
116
+ const topicsTokens = fullTopicsLine ? Math.ceil(countTokensApprox(fullTopicsLine) * SAFETY_MARGIN) : 0;
117
+ const truncationWarningTokens = Math.ceil(
118
+ countTokensApprox(
119
+ `\u26A0\uFE0F Truncated: Showing ~9999/9999 tokens (99%)
120
+ Sections included: 1, 2, 3, 4, 5, ... (+99 more)
121
+ Sections excluded: 6, 7, 8, 9, 10, ... (+99 more)
122
+ Use --full for complete content or --section to target specific sections.
123
+ `
124
+ ) * SAFETY_MARGIN
125
+ );
126
+ let headerTokens = minHeaderTokens + topicsTokens;
127
+ if (headerTokens >= maxTokens) {
128
+ includeTopics = false;
129
+ headerTokens = minHeaderTokens;
130
+ }
131
+ let contentBudget = maxTokens - headerTokens - truncationWarningTokens;
132
+ let tokensUsed = 0;
133
+ for (let i = 0; i < flatSections.length; i++) {
134
+ const { section, depth } = flatSections[i];
135
+ const indent = " ".repeat(depth);
136
+ const prefix = "#".repeat(section.level);
137
+ const sectionContent = section.summary ? `${indent}${prefix} ${section.heading}
138
+ ${indent}${section.summary}` : `${indent}${prefix} ${section.heading}`;
139
+ const sectionTokens = Math.ceil(
140
+ countTokensApprox(sectionContent) * SAFETY_MARGIN
141
+ );
142
+ if (tokensUsed + sectionTokens <= contentBudget) {
143
+ includedIndices.add(i);
144
+ tokensUsed += sectionTokens;
145
+ } else {
146
+ truncatedCount++;
147
+ }
148
+ }
149
+ if (truncatedCount === 0) {
150
+ contentBudget += truncationWarningTokens;
151
+ }
152
+ const includedNumbers = [];
153
+ const excludedNumbers = [];
154
+ for (let i = 0; i < flatSections.length; i++) {
155
+ if (includedIndices.has(i)) {
156
+ includedNumbers.push(flatSections[i].number);
157
+ } else {
158
+ excludedNumbers.push(flatSections[i].number);
159
+ }
160
+ }
161
+ let tokensShown = 0;
162
+ for (const idx of includedIndices) {
163
+ tokensShown += flatSections[idx].section.summaryTokens;
164
+ }
165
+ let output = buildOutput(
166
+ includedIndices,
167
+ {
168
+ showWarning: truncatedCount > 0,
169
+ truncatedCount,
170
+ includedNumbers,
171
+ excludedNumbers,
172
+ tokensShown,
173
+ tokensTotal: summary.originalTokens
174
+ },
175
+ includeTopics
176
+ );
177
+ let actualTokens = countTokensApprox(output);
178
+ const sortedIndices = Array.from(includedIndices).sort((a, b) => b - a);
179
+ let removalIndex = 0;
180
+ while (actualTokens > maxTokens && removalIndex < sortedIndices.length) {
181
+ const indexToRemove = sortedIndices[removalIndex];
182
+ includedIndices.delete(indexToRemove);
183
+ truncatedCount++;
184
+ removalIndex++;
185
+ const removedNumber = flatSections[indexToRemove].number;
186
+ const includedIdx = includedNumbers.indexOf(removedNumber);
187
+ if (includedIdx !== -1) {
188
+ includedNumbers.splice(includedIdx, 1);
189
+ excludedNumbers.push(removedNumber);
190
+ }
191
+ tokensShown -= flatSections[indexToRemove].section.summaryTokens;
192
+ output = buildOutput(
193
+ includedIndices,
194
+ {
195
+ showWarning: true,
196
+ truncatedCount,
197
+ includedNumbers,
198
+ excludedNumbers,
199
+ tokensShown,
200
+ tokensTotal: summary.originalTokens
201
+ },
202
+ includeTopics
203
+ );
204
+ actualTokens = countTokensApprox(output);
205
+ }
206
+ if (actualTokens > maxTokens && includeTopics) {
207
+ includeTopics = false;
208
+ output = buildOutput(
209
+ includedIndices,
210
+ {
211
+ showWarning: truncatedCount > 0,
212
+ truncatedCount,
213
+ includedNumbers,
214
+ excludedNumbers,
215
+ tokensShown,
216
+ tokensTotal: summary.originalTokens
217
+ },
218
+ includeTopics
219
+ );
220
+ actualTokens = countTokensApprox(output);
221
+ }
222
+ if (actualTokens > maxTokens && truncatedCount > 0) {
223
+ output = buildOutput(
224
+ includedIndices,
225
+ {
226
+ showWarning: false,
227
+ truncatedCount,
228
+ includedNumbers,
229
+ excludedNumbers,
230
+ tokensShown,
231
+ tokensTotal: summary.originalTokens
232
+ },
233
+ includeTopics
234
+ );
235
+ actualTokens = countTokensApprox(output);
236
+ }
237
+ return output;
238
+ };
239
+ var formatAssembledContext = (context) => {
240
+ const lines = [];
241
+ lines.push("# Context Assembly");
242
+ lines.push(`Total tokens: ${context.totalTokens}/${context.budget}`);
243
+ lines.push(`Sources: ${context.sources.length}`);
244
+ lines.push("");
245
+ for (const source of context.sources) {
246
+ lines.push("---");
247
+ lines.push("");
248
+ lines.push(source.content);
249
+ }
250
+ if (context.overflow.length > 0) {
251
+ lines.push("---");
252
+ lines.push("");
253
+ lines.push("## Overflow (not included due to budget)");
254
+ for (const overflowPath of context.overflow) {
255
+ lines.push(`- ${overflowPath}`);
256
+ }
257
+ }
258
+ return lines.join("\n");
259
+ };
260
+
261
+ // src/summarize/summarizer.ts
262
+ import * as fs from "fs/promises";
263
+ import * as path from "path";
264
+ import { Effect } from "effect";
265
+ var TOKEN_BUDGETS = {
266
+ brief: 100,
267
+ summary: 500,
268
+ full: Infinity
269
+ };
270
+ var MIN_SENTENCE_LENGTH = 10;
271
+ var SENTENCE_SCORE_DEFINITION = 2;
272
+ var SENTENCE_SCORE_PROPER_START = 1;
273
+ var SENTENCE_SCORE_MEDIUM_LENGTH = 1;
274
+ var SENTENCE_SCORE_EMPHASIS = 1;
275
+ var SENTENCE_LENGTH_MIN = 50;
276
+ var SENTENCE_LENGTH_MAX = 200;
277
+ var SUMMARY_COMPRESSION_RATIO = 0.3;
278
+ var MIN_SECTION_TOKENS = 20;
279
+ var MIN_SUMMARY_SENTENCES = 2;
280
+ var TOKENS_PER_SENTENCE_ESTIMATE = 30;
281
+ var MIN_TOPIC_LENGTH = 2;
282
+ var MAX_TOPIC_LENGTH = 50;
283
+ var MAX_TOPICS = 10;
284
+ var MIN_PARTIAL_BUDGET = 50;
285
+ var extractKeyPoints = (content, maxSentences) => {
286
+ const sentences = content.replace(/\n+/g, " ").split(/(?<=[.!?])\s+/).filter((s) => s.trim().length > MIN_SENTENCE_LENGTH);
287
+ if (sentences.length <= maxSentences) {
288
+ return sentences;
289
+ }
290
+ const scored = sentences.map((s) => {
291
+ let score = 0;
292
+ if (s.includes(":")) score += SENTENCE_SCORE_DEFINITION;
293
+ if (/^[A-Z]/.test(s)) score += SENTENCE_SCORE_PROPER_START;
294
+ if (s.length > SENTENCE_LENGTH_MIN && s.length < SENTENCE_LENGTH_MAX)
295
+ score += SENTENCE_SCORE_MEDIUM_LENGTH;
296
+ if (/\*\*|`/.test(s)) score += SENTENCE_SCORE_EMPHASIS;
297
+ return { sentence: s, score };
298
+ });
299
+ scored.sort((a, b) => b.score - a.score);
300
+ return scored.slice(0, maxSentences).map((s) => s.sentence);
301
+ };
302
+ var summarizeSection = (section, level) => {
303
+ const originalTokens = section.metadata.tokenCount;
304
+ const children = section.children.map(
305
+ (child) => summarizeSection(child, level)
306
+ );
307
+ const targetTokens = Math.min(
308
+ TOKEN_BUDGETS[level],
309
+ Math.max(originalTokens * SUMMARY_COMPRESSION_RATIO, MIN_SECTION_TOKENS)
310
+ );
311
+ let summary;
312
+ if (level === "full" || originalTokens <= targetTokens) {
313
+ summary = section.plainText;
314
+ } else if (level === "brief") {
315
+ const meta = [];
316
+ if (section.metadata.hasCode) meta.push("code");
317
+ if (section.metadata.hasList) meta.push("list");
318
+ if (section.metadata.hasTable) meta.push("table");
319
+ summary = meta.length > 0 ? `[${meta.join(", ")}]` : "";
320
+ } else {
321
+ const maxSentences = Math.max(
322
+ MIN_SUMMARY_SENTENCES,
323
+ Math.floor(targetTokens / TOKENS_PER_SENTENCE_ESTIMATE)
324
+ );
325
+ const keyPoints = extractKeyPoints(section.plainText, maxSentences);
326
+ if (keyPoints.length > 0) {
327
+ summary = keyPoints.join(" ");
328
+ } else {
329
+ const words = section.plainText.split(/\s+/).slice(0, targetTokens);
330
+ summary = words.join(" ") + (words.length < section.plainText.split(/\s+/).length ? "..." : "");
331
+ }
332
+ }
333
+ const summaryTokens = countTokensApprox(summary);
334
+ return {
335
+ heading: section.heading,
336
+ level: section.level,
337
+ originalTokens,
338
+ summaryTokens,
339
+ summary,
340
+ children,
341
+ hasCode: section.metadata.hasCode,
342
+ hasList: section.metadata.hasList,
343
+ hasTable: section.metadata.hasTable
344
+ };
345
+ };
346
+ var extractTopics = (document) => {
347
+ const topics = /* @__PURE__ */ new Set();
348
+ const processSection = (section) => {
349
+ const cleanHeading = section.heading.replace(/[:#\-_]/g, " ").trim().toLowerCase();
350
+ if (cleanHeading.length > MIN_TOPIC_LENGTH && cleanHeading.length < MAX_TOPIC_LENGTH) {
351
+ topics.add(cleanHeading);
352
+ }
353
+ for (const child of section.children) {
354
+ processSection(child);
355
+ }
356
+ };
357
+ for (const section of document.sections) {
358
+ processSection(section);
359
+ }
360
+ const frontmatter = document.frontmatter;
361
+ if (frontmatter.tags && Array.isArray(frontmatter.tags)) {
362
+ for (const tag of frontmatter.tags) {
363
+ if (typeof tag === "string") {
364
+ topics.add(tag.toLowerCase());
365
+ }
366
+ }
367
+ }
368
+ return Array.from(topics).slice(0, MAX_TOPICS);
369
+ };
370
+ var summarizeDocument = (document, options = {}) => {
371
+ const level = options.level ?? "summary";
372
+ const maxTokens = options.maxTokens ?? TOKEN_BUDGETS[level];
373
+ const allSections = document.sections.map((s) => summarizeSection(s, level));
374
+ const originalTokens = document.metadata.tokenCount;
375
+ let totalSummaryTokens = 0;
376
+ const flatSections = [];
377
+ const flattenWithTokens = (section) => {
378
+ flatSections.push(section);
379
+ totalSummaryTokens += section.summaryTokens;
380
+ for (const child of section.children) {
381
+ flattenWithTokens(child);
382
+ }
383
+ };
384
+ for (const section of allSections) {
385
+ flattenWithTokens(section);
386
+ }
387
+ const topics = extractTopics(document);
388
+ const headerTemplate = `# ${document.title}
389
+ Path: ${document.path}
390
+ Tokens: 9999 (99% reduction from ${document.metadata.tokenCount})
391
+ `;
392
+ const topicsLine = topics.length > 0 ? `
393
+ **Topics:** ${topics.join(", ")}
394
+ ` : "";
395
+ const truncationWarning = "\n\u26A0\uFE0F TRUNCATED: 999 sections omitted to fit token budget";
396
+ const baseOverhead = countTokensApprox(
397
+ headerTemplate + topicsLine + truncationWarning
398
+ );
399
+ const formattingOverhead = Math.ceil(baseOverhead * 1.2) + 20;
400
+ const contentBudget = maxTokens - formattingOverhead;
401
+ let truncated = false;
402
+ let truncatedCount = 0;
403
+ let sections;
404
+ let summaryTokens;
405
+ if (totalSummaryTokens > contentBudget && contentBudget > 0) {
406
+ let tokensUsed = 0;
407
+ const truncateSections = (sectionList) => {
408
+ const result2 = [];
409
+ for (const section of sectionList) {
410
+ const sectionOwnTokens = section.summaryTokens;
411
+ const fitsInBudget = tokensUsed + sectionOwnTokens <= contentBudget;
412
+ if (fitsInBudget) {
413
+ tokensUsed += sectionOwnTokens;
414
+ const truncatedChildren = truncateSections(section.children);
415
+ result2.push({
416
+ ...section,
417
+ children: truncatedChildren
418
+ });
419
+ } else {
420
+ truncatedCount++;
421
+ const rescuedChildren = truncateSections(section.children);
422
+ result2.push(...rescuedChildren);
423
+ }
424
+ }
425
+ return result2;
426
+ };
427
+ sections = truncateSections(allSections);
428
+ summaryTokens = tokensUsed;
429
+ truncated = truncatedCount > 0;
430
+ } else {
431
+ sections = allSections;
432
+ summaryTokens = totalSummaryTokens;
433
+ }
434
+ const compressionRatio = originalTokens > 0 ? 1 - summaryTokens / originalTokens : 0;
435
+ const result = {
436
+ path: document.path,
437
+ title: document.title,
438
+ originalTokens,
439
+ summaryTokens,
440
+ compressionRatio,
441
+ sections,
442
+ keyTopics: topics
443
+ };
444
+ if (truncated) {
445
+ return {
446
+ ...result,
447
+ truncated: true,
448
+ truncatedCount
449
+ };
450
+ }
451
+ return result;
452
+ };
453
+ var summarizeFile = (filePath, options = {}) => Effect.gen(function* () {
454
+ const document = yield* parseFile(filePath).pipe(
455
+ Effect.mapError((e) => new Error(`${e._tag}: ${e.message}`))
456
+ );
457
+ return summarizeDocument(document, options);
458
+ });
459
+ var assembleContext = (rootPath, sourcePaths, options) => Effect.gen(function* () {
460
+ const budget = options.budget;
461
+ const level = options.level ?? "summary";
462
+ const sources = [];
463
+ const overflow = [];
464
+ let totalTokens = 0;
465
+ const perSourceBudget = Math.floor(budget / sourcePaths.length);
466
+ for (const sourcePath of sourcePaths) {
467
+ const resolvedPath = path.isAbsolute(sourcePath) ? sourcePath : path.join(rootPath, sourcePath);
468
+ try {
469
+ const summary = yield* summarizeFile(resolvedPath, {
470
+ level,
471
+ maxTokens: perSourceBudget
472
+ });
473
+ const content = formatSummary(summary);
474
+ const tokens = countTokensApprox(content);
475
+ if (totalTokens + tokens <= budget) {
476
+ sources.push({
477
+ path: path.relative(rootPath, resolvedPath),
478
+ title: summary.title,
479
+ tokens,
480
+ content
481
+ });
482
+ totalTokens += tokens;
483
+ } else {
484
+ const remaining = budget - totalTokens;
485
+ if (remaining > MIN_PARTIAL_BUDGET) {
486
+ const briefSummary = yield* summarizeFile(resolvedPath, {
487
+ level: "brief",
488
+ maxTokens: remaining
489
+ });
490
+ const briefContent = formatSummary(briefSummary);
491
+ const briefTokens = countTokensApprox(briefContent);
492
+ sources.push({
493
+ path: path.relative(rootPath, resolvedPath),
494
+ title: briefSummary.title,
495
+ tokens: briefTokens,
496
+ content: briefContent
497
+ });
498
+ totalTokens += briefTokens;
499
+ } else {
500
+ overflow.push(path.relative(rootPath, resolvedPath));
501
+ }
502
+ }
503
+ } catch (_e) {
504
+ overflow.push(sourcePath);
505
+ }
506
+ }
507
+ return {
508
+ sources,
509
+ totalTokens,
510
+ budget,
511
+ overflow
512
+ };
513
+ });
514
+
515
+ // src/embeddings/semantic-search.ts
516
+ import * as fs3 from "fs/promises";
517
+ import * as path3 from "path";
518
+ import { Effect as Effect4 } from "effect";
519
+
520
+ // src/embeddings/openai-provider.ts
521
+ import { Console, Effect as Effect2 } from "effect";
522
+ import OpenAI from "openai";
523
+ var PRICING = {
524
+ "text-embedding-3-small": 0.02,
525
+ "text-embedding-3-large": 0.13,
526
+ "text-embedding-ada-002": 0.1
527
+ };
528
+ var MissingApiKeyError = class extends Error {
529
+ constructor() {
530
+ super("OPENAI_API_KEY not set");
531
+ this.name = "MissingApiKeyError";
532
+ }
533
+ };
534
+ var InvalidApiKeyError = class extends Error {
535
+ constructor(message) {
536
+ super(message ?? "Invalid OPENAI_API_KEY");
537
+ this.name = "InvalidApiKeyError";
538
+ }
539
+ };
540
+ var OpenAIProvider = class {
541
+ name;
542
+ dimensions;
543
+ client;
544
+ model;
545
+ batchSize;
546
+ constructor(options = {}) {
547
+ const apiKey = options.apiKey ?? process.env.OPENAI_API_KEY;
548
+ if (!apiKey) {
549
+ throw new MissingApiKeyError();
550
+ }
551
+ this.client = new OpenAI({ apiKey });
552
+ this.model = options.model ?? "text-embedding-3-small";
553
+ this.batchSize = options.batchSize ?? 100;
554
+ this.name = `openai:${this.model}`;
555
+ this.dimensions = 512;
556
+ }
557
+ async embed(texts) {
558
+ if (texts.length === 0) {
559
+ return { embeddings: [], tokensUsed: 0, cost: 0 };
560
+ }
561
+ const allEmbeddings = [];
562
+ let totalTokens = 0;
563
+ try {
564
+ for (let i = 0; i < texts.length; i += this.batchSize) {
565
+ const batch = texts.slice(i, i + this.batchSize);
566
+ const response = await this.client.embeddings.create({
567
+ model: this.model,
568
+ input: batch,
569
+ dimensions: 512
570
+ // Ensure consistent dimensions
571
+ });
572
+ for (const item of response.data) {
573
+ allEmbeddings.push(item.embedding);
574
+ }
575
+ totalTokens += response.usage?.total_tokens ?? 0;
576
+ }
577
+ } catch (error) {
578
+ if (error instanceof OpenAI.AuthenticationError) {
579
+ throw new InvalidApiKeyError(error.message);
580
+ }
581
+ throw error;
582
+ }
583
+ const pricePerMillion = PRICING[this.model] ?? 0.02;
584
+ const cost = totalTokens / 1e6 * pricePerMillion;
585
+ return {
586
+ embeddings: allEmbeddings,
587
+ tokensUsed: totalTokens,
588
+ cost
589
+ };
590
+ }
591
+ };
592
+ var createOpenAIProvider = (options) => new OpenAIProvider(options);
593
+ var handleApiKeyError = (effect) => effect.pipe(
594
+ Effect2.catchIf(
595
+ (e) => e instanceof MissingApiKeyError,
596
+ () => Effect2.gen(function* () {
597
+ yield* Console.error("");
598
+ yield* Console.error("Error: OPENAI_API_KEY not set");
599
+ yield* Console.error("");
600
+ yield* Console.error(
601
+ "To use semantic search, set your OpenAI API key:"
602
+ );
603
+ yield* Console.error(" export OPENAI_API_KEY=sk-...");
604
+ yield* Console.error("");
605
+ yield* Console.error("Or add to .env file in project root.");
606
+ return yield* Effect2.fail(new Error("Missing API key"));
607
+ })
608
+ ),
609
+ Effect2.catchIf(
610
+ (e) => e instanceof InvalidApiKeyError,
611
+ (e) => Effect2.gen(function* () {
612
+ yield* Console.error("");
613
+ yield* Console.error("Error: Invalid OPENAI_API_KEY");
614
+ yield* Console.error("");
615
+ yield* Console.error("The provided API key was rejected by OpenAI.");
616
+ yield* Console.error("Please check your API key is correct:");
617
+ yield* Console.error(" export OPENAI_API_KEY=sk-...");
618
+ yield* Console.error("");
619
+ yield* Console.error(`Details: ${e.message}`);
620
+ return yield* Effect2.fail(new Error("Invalid API key"));
621
+ })
622
+ )
623
+ );
624
+
625
+ // src/embeddings/vector-store.ts
626
+ import * as fs2 from "fs/promises";
627
+ import * as path2 from "path";
628
+ import { Effect as Effect3 } from "effect";
629
+ import HierarchicalNSW from "hnswlib-node";
630
+ var VECTOR_INDEX_FILE = "vectors.bin";
631
+ var VECTOR_META_FILE = "vectors.meta.json";
632
+ var INDEX_VERSION = 1;
633
+ var HnswVectorStore = class {
634
+ rootPath;
635
+ dimensions;
636
+ index = null;
637
+ entries = /* @__PURE__ */ new Map();
638
+ idToIndex = /* @__PURE__ */ new Map();
639
+ nextIndex = 0;
640
+ provider = "unknown";
641
+ totalCost = 0;
642
+ totalTokens = 0;
643
+ constructor(rootPath, dimensions) {
644
+ this.rootPath = path2.resolve(rootPath);
645
+ this.dimensions = dimensions;
646
+ }
647
+ getIndexDir() {
648
+ return path2.join(this.rootPath, INDEX_DIR);
649
+ }
650
+ getVectorPath() {
651
+ return path2.join(this.getIndexDir(), VECTOR_INDEX_FILE);
652
+ }
653
+ getMetaPath() {
654
+ return path2.join(this.getIndexDir(), VECTOR_META_FILE);
655
+ }
656
+ ensureIndex() {
657
+ if (!this.index) {
658
+ this.index = new HierarchicalNSW.HierarchicalNSW(
659
+ "cosine",
660
+ this.dimensions
661
+ );
662
+ this.index.initIndex(1e4, 16, 200, 100);
663
+ }
664
+ return this.index;
665
+ }
666
+ add(entries) {
667
+ return Effect3.sync(() => {
668
+ const index = this.ensureIndex();
669
+ for (const entry of entries) {
670
+ if (this.idToIndex.has(entry.id)) {
671
+ continue;
672
+ }
673
+ const idx = this.nextIndex++;
674
+ if (idx >= index.getMaxElements()) {
675
+ index.resizeIndex(index.getMaxElements() * 2);
676
+ }
677
+ index.addPoint(entry.embedding, idx);
678
+ this.entries.set(idx, entry);
679
+ this.idToIndex.set(entry.id, idx);
680
+ }
681
+ });
682
+ }
683
+ search(vector, limit, threshold = 0) {
684
+ return Effect3.sync(() => {
685
+ if (!this.index || this.entries.size === 0) {
686
+ return [];
687
+ }
688
+ const result = this.index.searchKnn(
689
+ vector,
690
+ Math.min(limit, this.entries.size)
691
+ );
692
+ const results = [];
693
+ for (let i = 0; i < result.neighbors.length; i++) {
694
+ const idx = result.neighbors[i];
695
+ const distance = result.distances[i];
696
+ if (idx === void 0 || distance === void 0) {
697
+ continue;
698
+ }
699
+ const similarity = 1 - distance;
700
+ if (similarity < threshold) {
701
+ continue;
702
+ }
703
+ const entry = this.entries.get(idx);
704
+ if (entry) {
705
+ results.push({
706
+ id: entry.id,
707
+ sectionId: entry.sectionId,
708
+ documentPath: entry.documentPath,
709
+ heading: entry.heading,
710
+ similarity
711
+ });
712
+ }
713
+ }
714
+ return results;
715
+ });
716
+ }
717
+ save() {
718
+ return Effect3.gen(
719
+ function* () {
720
+ if (!this.index) {
721
+ return;
722
+ }
723
+ const indexDir = this.getIndexDir();
724
+ yield* Effect3.promise(() => fs2.mkdir(indexDir, { recursive: true }));
725
+ yield* Effect3.promise(
726
+ () => this.index.writeIndex(this.getVectorPath())
727
+ );
728
+ const meta = {
729
+ version: INDEX_VERSION,
730
+ provider: this.provider,
731
+ dimensions: this.dimensions,
732
+ entries: Object.fromEntries(
733
+ Array.from(this.entries.entries()).map(([idx, entry]) => [
734
+ idx.toString(),
735
+ entry
736
+ ])
737
+ ),
738
+ totalCost: this.totalCost,
739
+ totalTokens: this.totalTokens,
740
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
741
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
742
+ };
743
+ yield* Effect3.promise(
744
+ () => fs2.writeFile(this.getMetaPath(), JSON.stringify(meta, null, 2))
745
+ );
746
+ }.bind(this)
747
+ );
748
+ }
749
+ load() {
750
+ return Effect3.gen(
751
+ function* () {
752
+ const vectorPath = this.getVectorPath();
753
+ const metaPath = this.getMetaPath();
754
+ const filesExist = yield* Effect3.tryPromise({
755
+ try: async () => {
756
+ await fs2.access(vectorPath);
757
+ await fs2.access(metaPath);
758
+ return true;
759
+ },
760
+ catch: () => false
761
+ }).pipe(Effect3.catchAll(() => Effect3.succeed(false)));
762
+ if (!filesExist) {
763
+ return false;
764
+ }
765
+ const metaContent = yield* Effect3.promise(
766
+ () => fs2.readFile(metaPath, "utf-8")
767
+ );
768
+ const meta = JSON.parse(metaContent);
769
+ if (meta.dimensions !== this.dimensions) {
770
+ return false;
771
+ }
772
+ this.index = new HierarchicalNSW.HierarchicalNSW(
773
+ "cosine",
774
+ this.dimensions
775
+ );
776
+ yield* Effect3.promise(() => this.index.readIndex(vectorPath));
777
+ this.entries.clear();
778
+ this.idToIndex.clear();
779
+ this.nextIndex = 0;
780
+ for (const [idxStr, entry] of Object.entries(meta.entries)) {
781
+ const idx = parseInt(idxStr, 10);
782
+ this.entries.set(idx, entry);
783
+ this.idToIndex.set(entry.id, idx);
784
+ this.nextIndex = Math.max(this.nextIndex, idx + 1);
785
+ }
786
+ this.provider = meta.provider;
787
+ this.totalCost = meta.totalCost;
788
+ this.totalTokens = meta.totalTokens;
789
+ return true;
790
+ }.bind(this)
791
+ );
792
+ }
793
+ getStats() {
794
+ return {
795
+ count: this.entries.size,
796
+ dimensions: this.dimensions,
797
+ provider: this.provider,
798
+ totalCost: this.totalCost,
799
+ totalTokens: this.totalTokens
800
+ };
801
+ }
802
+ setProvider(name) {
803
+ this.provider = name;
804
+ }
805
+ addCost(cost, tokens) {
806
+ this.totalCost += cost;
807
+ this.totalTokens += tokens;
808
+ }
809
+ };
810
+ var createVectorStore = (rootPath, dimensions) => new HnswVectorStore(rootPath, dimensions);
811
+
812
+ // src/embeddings/semantic-search.ts
813
+ var generateEmbeddingText = (section, content, documentTitle, parentHeading) => {
814
+ const parts = [];
815
+ parts.push(`# ${section.heading}`);
816
+ if (parentHeading) {
817
+ parts.push(`Parent section: ${parentHeading}`);
818
+ }
819
+ parts.push(`Document: ${documentTitle}`);
820
+ parts.push("");
821
+ parts.push(content);
822
+ return parts.join("\n");
823
+ };
824
+ var EMBEDDING_PRICE_PER_MILLION = 0.02;
825
+ var estimateEmbeddingCost = (rootPath, options = {}) => Effect4.gen(function* () {
826
+ const resolvedRoot = path3.resolve(rootPath);
827
+ const storage = createStorage(resolvedRoot);
828
+ const docIndex = yield* loadDocumentIndex(storage);
829
+ const sectionIndex = yield* loadSectionIndex(storage);
830
+ if (!docIndex || !sectionIndex) {
831
+ return yield* Effect4.fail(
832
+ new Error("Index not found. Run 'mdcontext index' first.")
833
+ );
834
+ }
835
+ const byDir = /* @__PURE__ */ new Map();
836
+ for (const section of Object.values(sectionIndex.sections)) {
837
+ if (section.tokenCount < 10) continue;
838
+ if (options.excludePatterns?.length) {
839
+ const excluded = options.excludePatterns.some((pattern) => {
840
+ const regex = new RegExp(
841
+ `^${pattern.replace(/\*/g, ".*").replace(/\?/g, ".")}$`
842
+ );
843
+ return regex.test(section.documentPath);
844
+ });
845
+ if (excluded) continue;
846
+ }
847
+ const dir = path3.dirname(section.documentPath) || ".";
848
+ if (!byDir.has(dir)) {
849
+ byDir.set(dir, { files: /* @__PURE__ */ new Set(), sections: 0, tokens: 0 });
850
+ }
851
+ const entry = byDir.get(dir);
852
+ entry.files.add(section.documentPath);
853
+ entry.sections++;
854
+ entry.tokens += section.tokenCount;
855
+ }
856
+ const directoryEstimates = [];
857
+ let totalFiles = 0;
858
+ let totalSections = 0;
859
+ let totalTokens = 0;
860
+ for (const [dir, data] of byDir) {
861
+ directoryEstimates.push({
862
+ directory: dir,
863
+ fileCount: data.files.size,
864
+ sectionCount: data.sections,
865
+ estimatedTokens: data.tokens,
866
+ estimatedCost: data.tokens / 1e6 * EMBEDDING_PRICE_PER_MILLION
867
+ });
868
+ totalFiles += data.files.size;
869
+ totalSections += data.sections;
870
+ totalTokens += data.tokens;
871
+ }
872
+ directoryEstimates.sort((a, b) => a.directory.localeCompare(b.directory));
873
+ const estimatedTimeSeconds = Math.ceil(totalSections / 100) * 1.5;
874
+ return {
875
+ totalFiles,
876
+ totalSections,
877
+ totalTokens,
878
+ totalCost: totalTokens / 1e6 * EMBEDDING_PRICE_PER_MILLION,
879
+ estimatedTimeSeconds,
880
+ byDirectory: directoryEstimates
881
+ };
882
+ });
883
+ var buildEmbeddings = (rootPath, options = {}) => Effect4.gen(function* () {
884
+ const startTime = Date.now();
885
+ const resolvedRoot = path3.resolve(rootPath);
886
+ const storage = createStorage(resolvedRoot);
887
+ const docIndex = yield* loadDocumentIndex(storage);
888
+ const sectionIndex = yield* loadSectionIndex(storage);
889
+ if (!docIndex || !sectionIndex) {
890
+ return yield* Effect4.fail(
891
+ new Error("Index not found. Run 'mdcontext index' first.")
892
+ );
893
+ }
894
+ const provider = options.provider ?? (yield* Effect4.try({
895
+ try: () => createOpenAIProvider(),
896
+ catch: (e) => e
897
+ }));
898
+ const dimensions = provider.dimensions;
899
+ const vectorStore = createVectorStore(
900
+ resolvedRoot,
901
+ dimensions
902
+ );
903
+ vectorStore.setProvider(provider.name);
904
+ if (!options.force) {
905
+ const loaded = yield* vectorStore.load();
906
+ if (loaded) {
907
+ const stats = vectorStore.getStats();
908
+ if (stats.count > 0) {
909
+ const duration2 = Date.now() - startTime;
910
+ const estimatedSavings = stats.totalTokens / 1e6 * EMBEDDING_PRICE_PER_MILLION;
911
+ return {
912
+ sectionsEmbedded: 0,
913
+ tokensUsed: 0,
914
+ cost: 0,
915
+ duration: duration2,
916
+ filesProcessed: 0,
917
+ cacheHit: true,
918
+ existingVectors: stats.count,
919
+ estimatedSavings
920
+ };
921
+ }
922
+ }
923
+ }
924
+ const isExcluded = (docPath) => {
925
+ if (!options.excludePatterns?.length) return false;
926
+ return options.excludePatterns.some((pattern) => {
927
+ const regex = new RegExp(
928
+ `^${pattern.replace(/\*/g, ".*").replace(/\?/g, ".")}$`
929
+ );
930
+ return regex.test(docPath);
931
+ });
932
+ };
933
+ const sectionsByDoc = /* @__PURE__ */ new Map();
934
+ for (const section of Object.values(sectionIndex.sections)) {
935
+ const document = docIndex.documents[section.documentPath];
936
+ if (!document) continue;
937
+ if (section.tokenCount < 10) continue;
938
+ if (isExcluded(section.documentPath)) continue;
939
+ let parentHeading;
940
+ if (section.level > 1) {
941
+ const docSections = sectionIndex.byDocument[document.id] ?? [];
942
+ for (const sibId of docSections) {
943
+ const sib = sectionIndex.sections[sibId];
944
+ if (sib && sib.level === section.level - 1 && sib.startLine < section.startLine) {
945
+ parentHeading = sib.heading;
946
+ }
947
+ }
948
+ }
949
+ const docPath = section.documentPath;
950
+ if (!sectionsByDoc.has(docPath)) {
951
+ sectionsByDoc.set(docPath, []);
952
+ }
953
+ sectionsByDoc.get(docPath).push({ section, parentHeading });
954
+ }
955
+ if (sectionsByDoc.size === 0) {
956
+ const duration2 = Date.now() - startTime;
957
+ return {
958
+ sectionsEmbedded: 0,
959
+ tokensUsed: 0,
960
+ cost: 0,
961
+ duration: duration2,
962
+ filesProcessed: 0
963
+ };
964
+ }
965
+ const sectionsToEmbed = [];
966
+ const docPaths = Array.from(sectionsByDoc.keys());
967
+ let filesProcessed = 0;
968
+ for (let fileIndex = 0; fileIndex < docPaths.length; fileIndex++) {
969
+ const docPath = docPaths[fileIndex];
970
+ const sections = sectionsByDoc.get(docPath);
971
+ const document = docIndex.documents[docPath];
972
+ if (!document) continue;
973
+ if (options.onFileProgress) {
974
+ options.onFileProgress({
975
+ fileIndex: fileIndex + 1,
976
+ totalFiles: docPaths.length,
977
+ filePath: docPath,
978
+ sectionCount: sections.length
979
+ });
980
+ }
981
+ const filePath = path3.join(resolvedRoot, docPath);
982
+ let fileContent;
983
+ try {
984
+ fileContent = yield* Effect4.promise(
985
+ () => fs3.readFile(filePath, "utf-8")
986
+ );
987
+ } catch {
988
+ continue;
989
+ }
990
+ filesProcessed++;
991
+ const lines = fileContent.split("\n");
992
+ for (const { section, parentHeading } of sections) {
993
+ const content = lines.slice(section.startLine - 1, section.endLine).join("\n");
994
+ const text = generateEmbeddingText(
995
+ section,
996
+ content,
997
+ document.title,
998
+ parentHeading
999
+ );
1000
+ sectionsToEmbed.push({ section, text });
1001
+ }
1002
+ }
1003
+ if (sectionsToEmbed.length === 0) {
1004
+ const duration2 = Date.now() - startTime;
1005
+ return {
1006
+ sectionsEmbedded: 0,
1007
+ tokensUsed: 0,
1008
+ cost: 0,
1009
+ duration: duration2,
1010
+ filesProcessed
1011
+ };
1012
+ }
1013
+ const texts = sectionsToEmbed.map((s) => s.text);
1014
+ const result = yield* Effect4.tryPromise({
1015
+ try: () => provider.embed(texts),
1016
+ catch: (e) => {
1017
+ if (e instanceof InvalidApiKeyError) return e;
1018
+ return new Error(
1019
+ `Embedding failed: ${e instanceof Error ? e.message : String(e)}`
1020
+ );
1021
+ }
1022
+ });
1023
+ const entries = [];
1024
+ for (let i = 0; i < sectionsToEmbed.length; i++) {
1025
+ const { section } = sectionsToEmbed[i] ?? { section: null };
1026
+ const embedding = result.embeddings[i];
1027
+ if (!section || !embedding) continue;
1028
+ entries.push({
1029
+ id: section.id,
1030
+ sectionId: section.id,
1031
+ documentPath: section.documentPath,
1032
+ heading: section.heading,
1033
+ embedding
1034
+ });
1035
+ }
1036
+ yield* vectorStore.add(entries);
1037
+ vectorStore.addCost(result.cost, result.tokensUsed);
1038
+ yield* vectorStore.save();
1039
+ const duration = Date.now() - startTime;
1040
+ return {
1041
+ sectionsEmbedded: entries.length,
1042
+ tokensUsed: result.tokensUsed,
1043
+ cost: result.cost,
1044
+ duration,
1045
+ filesProcessed
1046
+ };
1047
+ });
1048
+ var semanticSearch = (rootPath, query, options = {}) => Effect4.gen(function* () {
1049
+ const resolvedRoot = path3.resolve(rootPath);
1050
+ const provider = yield* Effect4.try({
1051
+ try: () => createOpenAIProvider(),
1052
+ catch: (e) => e
1053
+ });
1054
+ const dimensions = provider.dimensions;
1055
+ const vectorStore = createVectorStore(resolvedRoot, dimensions);
1056
+ const loaded = yield* vectorStore.load();
1057
+ if (!loaded) {
1058
+ return yield* Effect4.fail(
1059
+ new Error("Embeddings not found. Run 'mdcontext embed' first.")
1060
+ );
1061
+ }
1062
+ const queryResult = yield* Effect4.tryPromise({
1063
+ try: () => provider.embed([query]),
1064
+ catch: (e) => new Error(
1065
+ `Query embedding failed: ${e instanceof Error ? e.message : String(e)}`
1066
+ )
1067
+ });
1068
+ const queryVector = queryResult.embeddings[0];
1069
+ if (!queryVector) {
1070
+ return yield* Effect4.fail(new Error("Failed to generate query embedding"));
1071
+ }
1072
+ const limit = options.limit ?? 10;
1073
+ const threshold = options.threshold ?? 0;
1074
+ const searchResults = yield* vectorStore.search(
1075
+ queryVector,
1076
+ limit * 2,
1077
+ threshold
1078
+ );
1079
+ let filteredResults = searchResults;
1080
+ if (options.pathPattern) {
1081
+ const pattern = options.pathPattern.replace(/\./g, "\\.").replace(/\*/g, ".*");
1082
+ const regex = new RegExp(`^${pattern}$`, "i");
1083
+ filteredResults = searchResults.filter((r) => regex.test(r.documentPath));
1084
+ }
1085
+ const results = filteredResults.slice(0, limit).map((r) => ({
1086
+ sectionId: r.sectionId,
1087
+ documentPath: r.documentPath,
1088
+ heading: r.heading,
1089
+ similarity: r.similarity
1090
+ }));
1091
+ return results;
1092
+ });
1093
+ var getEmbeddingStats = (rootPath) => Effect4.gen(function* () {
1094
+ const resolvedRoot = path3.resolve(rootPath);
1095
+ const vectorStore = createVectorStore(resolvedRoot, 1536);
1096
+ const loaded = yield* vectorStore.load();
1097
+ if (!loaded) {
1098
+ return {
1099
+ hasEmbeddings: false,
1100
+ count: 0,
1101
+ provider: "none",
1102
+ dimensions: 0,
1103
+ totalCost: 0,
1104
+ totalTokens: 0
1105
+ };
1106
+ }
1107
+ const stats = vectorStore.getStats();
1108
+ return {
1109
+ hasEmbeddings: true,
1110
+ count: stats.count,
1111
+ provider: stats.provider,
1112
+ dimensions: stats.dimensions,
1113
+ totalCost: stats.totalCost,
1114
+ totalTokens: stats.totalTokens
1115
+ };
1116
+ });
1117
+
1118
+ // src/search/searcher.ts
1119
+ import * as fs4 from "fs/promises";
1120
+ import * as path4 from "path";
1121
+ import { Effect as Effect5 } from "effect";
1122
+
1123
+ // src/search/query-parser.ts
1124
+ var tokenize = (query) => {
1125
+ const tokens = [];
1126
+ let i = 0;
1127
+ while (i < query.length) {
1128
+ if (/\s/.test(query[i])) {
1129
+ i++;
1130
+ continue;
1131
+ }
1132
+ if (query[i] === '"') {
1133
+ const start = i + 1;
1134
+ i++;
1135
+ while (i < query.length && query[i] !== '"') {
1136
+ i++;
1137
+ }
1138
+ const value = query.slice(start, i);
1139
+ tokens.push({ type: "PHRASE", value });
1140
+ i++;
1141
+ continue;
1142
+ }
1143
+ if (query[i] === "(") {
1144
+ tokens.push({ type: "LPAREN", value: "(" });
1145
+ i++;
1146
+ continue;
1147
+ }
1148
+ if (query[i] === ")") {
1149
+ tokens.push({ type: "RPAREN", value: ")" });
1150
+ i++;
1151
+ continue;
1152
+ }
1153
+ const wordMatch = query.slice(i).match(/^[^\s()"]+/);
1154
+ if (wordMatch) {
1155
+ const word = wordMatch[0];
1156
+ const upperWord = word.toUpperCase();
1157
+ if (upperWord === "AND") {
1158
+ tokens.push({ type: "AND", value: "AND" });
1159
+ } else if (upperWord === "OR") {
1160
+ tokens.push({ type: "OR", value: "OR" });
1161
+ } else if (upperWord === "NOT") {
1162
+ tokens.push({ type: "NOT", value: "NOT" });
1163
+ } else {
1164
+ tokens.push({ type: "TERM", value: word });
1165
+ }
1166
+ i += word.length;
1167
+ continue;
1168
+ }
1169
+ i++;
1170
+ }
1171
+ return tokens;
1172
+ };
1173
+ var Parser = class {
1174
+ tokens;
1175
+ pos = 0;
1176
+ terms = [];
1177
+ phrases = [];
1178
+ constructor(tokens) {
1179
+ this.tokens = tokens;
1180
+ }
1181
+ current() {
1182
+ return this.tokens[this.pos];
1183
+ }
1184
+ advance() {
1185
+ return this.tokens[this.pos++];
1186
+ }
1187
+ match(type) {
1188
+ if (this.current()?.type === type) {
1189
+ this.advance();
1190
+ return true;
1191
+ }
1192
+ return false;
1193
+ }
1194
+ parse() {
1195
+ if (this.tokens.length === 0) {
1196
+ return null;
1197
+ }
1198
+ return this.parseExpr();
1199
+ }
1200
+ parseExpr() {
1201
+ let left = this.parseAndExpr();
1202
+ while (this.match("OR")) {
1203
+ const right = this.parseAndExpr();
1204
+ left = { type: "or", left, right };
1205
+ }
1206
+ return left;
1207
+ }
1208
+ parseAndExpr() {
1209
+ let left = this.parseNotExpr();
1210
+ while (this.match("AND") || this.isImplicitAnd()) {
1211
+ const right = this.parseNotExpr();
1212
+ left = { type: "and", left, right };
1213
+ }
1214
+ return left;
1215
+ }
1216
+ isImplicitAnd() {
1217
+ const tok = this.current();
1218
+ return tok?.type === "TERM" || tok?.type === "PHRASE" || tok?.type === "NOT" || tok?.type === "LPAREN";
1219
+ }
1220
+ parseNotExpr() {
1221
+ if (this.match("NOT")) {
1222
+ const operand = this.parseNotExpr();
1223
+ return { type: "not", operand };
1224
+ }
1225
+ return this.parsePrimary();
1226
+ }
1227
+ parsePrimary() {
1228
+ const tok = this.current();
1229
+ if (this.match("LPAREN")) {
1230
+ const expr = this.parseExpr();
1231
+ this.match("RPAREN");
1232
+ return expr;
1233
+ }
1234
+ if (tok?.type === "PHRASE") {
1235
+ this.advance();
1236
+ this.phrases.push(tok.value);
1237
+ return { type: "phrase", value: tok.value };
1238
+ }
1239
+ if (tok?.type === "TERM") {
1240
+ this.advance();
1241
+ this.terms.push(tok.value);
1242
+ return { type: "term", value: tok.value };
1243
+ }
1244
+ return { type: "term", value: "" };
1245
+ }
1246
+ };
1247
+ var parseQuery = (query) => {
1248
+ const tokens = tokenize(query);
1249
+ if (tokens.length === 0) {
1250
+ return null;
1251
+ }
1252
+ const parser = new Parser(tokens);
1253
+ const ast = parser.parse();
1254
+ if (!ast) {
1255
+ return null;
1256
+ }
1257
+ return {
1258
+ ast,
1259
+ terms: parser.terms,
1260
+ phrases: parser.phrases
1261
+ };
1262
+ };
1263
+ var isAdvancedQuery = (query) => {
1264
+ const tokens = tokenize(query);
1265
+ return tokens.some(
1266
+ (t) => t.type === "AND" || t.type === "OR" || t.type === "NOT" || t.type === "PHRASE" || t.type === "LPAREN"
1267
+ );
1268
+ };
1269
+ var evaluateQuery = (ast, text) => {
1270
+ const lowerText = text.toLowerCase();
1271
+ const evaluate = (node) => {
1272
+ switch (node.type) {
1273
+ case "term": {
1274
+ if (!node.value) return true;
1275
+ return lowerText.includes(node.value.toLowerCase());
1276
+ }
1277
+ case "phrase": {
1278
+ return lowerText.includes(node.value.toLowerCase());
1279
+ }
1280
+ case "and": {
1281
+ return evaluate(node.left) && evaluate(node.right);
1282
+ }
1283
+ case "or": {
1284
+ return evaluate(node.left) || evaluate(node.right);
1285
+ }
1286
+ case "not": {
1287
+ return !evaluate(node.operand);
1288
+ }
1289
+ }
1290
+ };
1291
+ return evaluate(ast);
1292
+ };
1293
+ var buildHighlightPattern = (parsed) => {
1294
+ const patterns = [];
1295
+ const escapeChars = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1296
+ for (const term of parsed.terms) {
1297
+ if (term) {
1298
+ patterns.push(`\\b${escapeChars(term)}\\b`);
1299
+ }
1300
+ }
1301
+ for (const phrase of parsed.phrases) {
1302
+ if (phrase) {
1303
+ patterns.push(escapeChars(phrase));
1304
+ }
1305
+ }
1306
+ if (patterns.length === 0) {
1307
+ return /.^/;
1308
+ }
1309
+ return new RegExp(patterns.join("|"), "gi");
1310
+ };
1311
+
1312
+ // src/search/searcher.ts
1313
+ var matchPath = (filePath, pattern) => {
1314
+ const regexPattern = pattern.replace(/\./g, "\\.").replace(/\*/g, ".*").replace(/\?/g, ".");
1315
+ const regex = new RegExp(`^${regexPattern}$`, "i");
1316
+ return regex.test(filePath);
1317
+ };
1318
+ var search = (rootPath, options = {}) => Effect5.gen(function* () {
1319
+ const storage = createStorage(rootPath);
1320
+ const docIndex = yield* loadDocumentIndex(storage);
1321
+ const sectionIndex = yield* loadSectionIndex(storage);
1322
+ if (!docIndex || !sectionIndex) {
1323
+ return [];
1324
+ }
1325
+ const results = [];
1326
+ const headingRegex = options.heading ? new RegExp(options.heading, "i") : null;
1327
+ for (const section of Object.values(sectionIndex.sections)) {
1328
+ if (headingRegex && !headingRegex.test(section.heading)) {
1329
+ continue;
1330
+ }
1331
+ if (options.pathPattern && !matchPath(section.documentPath, options.pathPattern)) {
1332
+ continue;
1333
+ }
1334
+ if (options.hasCode !== void 0 && section.hasCode !== options.hasCode) {
1335
+ continue;
1336
+ }
1337
+ if (options.hasList !== void 0 && section.hasList !== options.hasList) {
1338
+ continue;
1339
+ }
1340
+ if (options.hasTable !== void 0 && section.hasTable !== options.hasTable) {
1341
+ continue;
1342
+ }
1343
+ if (options.minLevel !== void 0 && section.level < options.minLevel) {
1344
+ continue;
1345
+ }
1346
+ if (options.maxLevel !== void 0 && section.level > options.maxLevel) {
1347
+ continue;
1348
+ }
1349
+ const document = docIndex.documents[section.documentPath];
1350
+ if (document) {
1351
+ results.push({ section, document });
1352
+ }
1353
+ if (options.limit !== void 0 && results.length >= options.limit) {
1354
+ break;
1355
+ }
1356
+ }
1357
+ return results;
1358
+ });
1359
+ var searchContent = (rootPath, options = {}) => Effect5.gen(function* () {
1360
+ const storage = createStorage(rootPath);
1361
+ const docIndex = yield* loadDocumentIndex(storage);
1362
+ const sectionIndex = yield* loadSectionIndex(storage);
1363
+ if (!docIndex || !sectionIndex) {
1364
+ return [];
1365
+ }
1366
+ let parsedQuery = null;
1367
+ let contentRegex = null;
1368
+ let highlightRegex = null;
1369
+ if (options.content) {
1370
+ if (isAdvancedQuery(options.content)) {
1371
+ parsedQuery = parseQuery(options.content);
1372
+ if (parsedQuery) {
1373
+ highlightRegex = buildHighlightPattern(parsedQuery);
1374
+ }
1375
+ } else {
1376
+ contentRegex = new RegExp(options.content, "gi");
1377
+ highlightRegex = contentRegex;
1378
+ }
1379
+ }
1380
+ const headingRegex = options.heading ? new RegExp(options.heading, "i") : null;
1381
+ const results = [];
1382
+ const sectionsByDoc = {};
1383
+ for (const section of Object.values(sectionIndex.sections)) {
1384
+ const docSections = sectionsByDoc[section.documentPath];
1385
+ if (docSections) {
1386
+ docSections.push(section);
1387
+ } else {
1388
+ sectionsByDoc[section.documentPath] = [section];
1389
+ }
1390
+ }
1391
+ for (const [docPath, sections] of Object.entries(sectionsByDoc)) {
1392
+ if (options.pathPattern && !matchPath(docPath, options.pathPattern)) {
1393
+ continue;
1394
+ }
1395
+ const document = docIndex.documents[docPath];
1396
+ if (!document) continue;
1397
+ let fileContent = null;
1398
+ let fileLines = [];
1399
+ if (parsedQuery || contentRegex) {
1400
+ const filePath = path4.join(storage.rootPath, docPath);
1401
+ try {
1402
+ fileContent = yield* Effect5.promise(
1403
+ () => fs4.readFile(filePath, "utf-8")
1404
+ );
1405
+ fileLines = fileContent.split("\n");
1406
+ } catch {
1407
+ continue;
1408
+ }
1409
+ }
1410
+ for (const section of sections) {
1411
+ if (headingRegex && !headingRegex.test(section.heading)) {
1412
+ continue;
1413
+ }
1414
+ if (options.hasCode !== void 0 && section.hasCode !== options.hasCode) {
1415
+ continue;
1416
+ }
1417
+ if (options.hasList !== void 0 && section.hasList !== options.hasList) {
1418
+ continue;
1419
+ }
1420
+ if (options.hasTable !== void 0 && section.hasTable !== options.hasTable) {
1421
+ continue;
1422
+ }
1423
+ if (options.minLevel !== void 0 && section.level < options.minLevel) {
1424
+ continue;
1425
+ }
1426
+ if (options.maxLevel !== void 0 && section.level > options.maxLevel) {
1427
+ continue;
1428
+ }
1429
+ if ((parsedQuery || contentRegex) && fileContent) {
1430
+ const sectionLines = fileLines.slice(
1431
+ section.startLine - 1,
1432
+ section.endLine
1433
+ );
1434
+ const sectionContent = sectionLines.join("\n");
1435
+ if (parsedQuery) {
1436
+ if (!evaluateQuery(parsedQuery.ast, sectionContent)) {
1437
+ continue;
1438
+ }
1439
+ }
1440
+ const matches = [];
1441
+ const searchRegex = contentRegex || highlightRegex;
1442
+ const contextBefore = options.contextBefore ?? 1;
1443
+ const contextAfter = options.contextAfter ?? 1;
1444
+ if (searchRegex) {
1445
+ for (let i = 0; i < sectionLines.length; i++) {
1446
+ const line = sectionLines[i];
1447
+ if (line && searchRegex.test(line)) {
1448
+ searchRegex.lastIndex = 0;
1449
+ const absoluteLineNum = section.startLine + i;
1450
+ const snippetStart = Math.max(0, i - contextBefore);
1451
+ const snippetEnd = Math.min(
1452
+ sectionLines.length,
1453
+ i + contextAfter + 1
1454
+ );
1455
+ const snippetLines = sectionLines.slice(
1456
+ snippetStart,
1457
+ snippetEnd
1458
+ );
1459
+ const snippet = snippetLines.join("\n");
1460
+ const contextLines = [];
1461
+ for (let j = snippetStart; j < snippetEnd; j++) {
1462
+ const ctxLine = sectionLines[j];
1463
+ if (ctxLine !== void 0) {
1464
+ contextLines.push({
1465
+ lineNumber: section.startLine + j,
1466
+ line: ctxLine,
1467
+ isMatch: j === i
1468
+ });
1469
+ }
1470
+ }
1471
+ matches.push({
1472
+ lineNumber: absoluteLineNum,
1473
+ line,
1474
+ snippet,
1475
+ contextLines
1476
+ });
1477
+ }
1478
+ }
1479
+ }
1480
+ if (parsedQuery || matches.length > 0) {
1481
+ const result = {
1482
+ section,
1483
+ document,
1484
+ sectionContent
1485
+ };
1486
+ if (matches.length > 0) {
1487
+ results.push({ ...result, matches });
1488
+ } else {
1489
+ results.push(result);
1490
+ }
1491
+ if (options.limit !== void 0 && results.length >= options.limit) {
1492
+ return results;
1493
+ }
1494
+ }
1495
+ } else if (!parsedQuery && !contentRegex) {
1496
+ results.push({ section, document });
1497
+ if (options.limit !== void 0 && results.length >= options.limit) {
1498
+ return results;
1499
+ }
1500
+ }
1501
+ }
1502
+ }
1503
+ return results;
1504
+ });
1505
+
1506
+ export {
1507
+ formatSummary,
1508
+ formatAssembledContext,
1509
+ summarizeFile,
1510
+ assembleContext,
1511
+ handleApiKeyError,
1512
+ estimateEmbeddingCost,
1513
+ buildEmbeddings,
1514
+ semanticSearch,
1515
+ getEmbeddingStats,
1516
+ isAdvancedQuery,
1517
+ search,
1518
+ searchContent
1519
+ };