@duytransipher/gitnexus 1.4.6-sipher.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 (224) hide show
  1. package/LICENSE +73 -0
  2. package/README.md +261 -0
  3. package/dist/cli/ai-context.d.ts +23 -0
  4. package/dist/cli/ai-context.js +265 -0
  5. package/dist/cli/analyze.d.ts +12 -0
  6. package/dist/cli/analyze.js +345 -0
  7. package/dist/cli/augment.d.ts +13 -0
  8. package/dist/cli/augment.js +33 -0
  9. package/dist/cli/clean.d.ts +10 -0
  10. package/dist/cli/clean.js +60 -0
  11. package/dist/cli/eval-server.d.ts +37 -0
  12. package/dist/cli/eval-server.js +389 -0
  13. package/dist/cli/index.d.ts +2 -0
  14. package/dist/cli/index.js +137 -0
  15. package/dist/cli/lazy-action.d.ts +6 -0
  16. package/dist/cli/lazy-action.js +18 -0
  17. package/dist/cli/list.d.ts +6 -0
  18. package/dist/cli/list.js +30 -0
  19. package/dist/cli/mcp.d.ts +8 -0
  20. package/dist/cli/mcp.js +36 -0
  21. package/dist/cli/serve.d.ts +4 -0
  22. package/dist/cli/serve.js +6 -0
  23. package/dist/cli/setup.d.ts +8 -0
  24. package/dist/cli/setup.js +367 -0
  25. package/dist/cli/sipher-patched.d.ts +2 -0
  26. package/dist/cli/sipher-patched.js +77 -0
  27. package/dist/cli/skill-gen.d.ts +26 -0
  28. package/dist/cli/skill-gen.js +549 -0
  29. package/dist/cli/status.d.ts +6 -0
  30. package/dist/cli/status.js +36 -0
  31. package/dist/cli/tool.d.ts +60 -0
  32. package/dist/cli/tool.js +180 -0
  33. package/dist/cli/wiki.d.ts +15 -0
  34. package/dist/cli/wiki.js +365 -0
  35. package/dist/config/ignore-service.d.ts +26 -0
  36. package/dist/config/ignore-service.js +284 -0
  37. package/dist/config/supported-languages.d.ts +15 -0
  38. package/dist/config/supported-languages.js +16 -0
  39. package/dist/core/augmentation/engine.d.ts +26 -0
  40. package/dist/core/augmentation/engine.js +240 -0
  41. package/dist/core/embeddings/embedder.d.ts +60 -0
  42. package/dist/core/embeddings/embedder.js +251 -0
  43. package/dist/core/embeddings/embedding-pipeline.d.ts +51 -0
  44. package/dist/core/embeddings/embedding-pipeline.js +356 -0
  45. package/dist/core/embeddings/index.d.ts +9 -0
  46. package/dist/core/embeddings/index.js +9 -0
  47. package/dist/core/embeddings/text-generator.d.ts +24 -0
  48. package/dist/core/embeddings/text-generator.js +182 -0
  49. package/dist/core/embeddings/types.d.ts +87 -0
  50. package/dist/core/embeddings/types.js +32 -0
  51. package/dist/core/graph/graph.d.ts +2 -0
  52. package/dist/core/graph/graph.js +66 -0
  53. package/dist/core/graph/types.d.ts +66 -0
  54. package/dist/core/graph/types.js +1 -0
  55. package/dist/core/ingestion/ast-cache.d.ts +11 -0
  56. package/dist/core/ingestion/ast-cache.js +35 -0
  57. package/dist/core/ingestion/call-processor.d.ts +23 -0
  58. package/dist/core/ingestion/call-processor.js +793 -0
  59. package/dist/core/ingestion/call-routing.d.ts +68 -0
  60. package/dist/core/ingestion/call-routing.js +129 -0
  61. package/dist/core/ingestion/cluster-enricher.d.ts +38 -0
  62. package/dist/core/ingestion/cluster-enricher.js +170 -0
  63. package/dist/core/ingestion/community-processor.d.ts +39 -0
  64. package/dist/core/ingestion/community-processor.js +312 -0
  65. package/dist/core/ingestion/constants.d.ts +16 -0
  66. package/dist/core/ingestion/constants.js +16 -0
  67. package/dist/core/ingestion/entry-point-scoring.d.ts +40 -0
  68. package/dist/core/ingestion/entry-point-scoring.js +353 -0
  69. package/dist/core/ingestion/export-detection.d.ts +18 -0
  70. package/dist/core/ingestion/export-detection.js +231 -0
  71. package/dist/core/ingestion/filesystem-walker.d.ts +28 -0
  72. package/dist/core/ingestion/filesystem-walker.js +81 -0
  73. package/dist/core/ingestion/framework-detection.d.ts +54 -0
  74. package/dist/core/ingestion/framework-detection.js +411 -0
  75. package/dist/core/ingestion/heritage-processor.d.ts +28 -0
  76. package/dist/core/ingestion/heritage-processor.js +251 -0
  77. package/dist/core/ingestion/import-processor.d.ts +34 -0
  78. package/dist/core/ingestion/import-processor.js +398 -0
  79. package/dist/core/ingestion/language-config.d.ts +46 -0
  80. package/dist/core/ingestion/language-config.js +167 -0
  81. package/dist/core/ingestion/mro-processor.d.ts +45 -0
  82. package/dist/core/ingestion/mro-processor.js +369 -0
  83. package/dist/core/ingestion/named-binding-extraction.d.ts +61 -0
  84. package/dist/core/ingestion/named-binding-extraction.js +363 -0
  85. package/dist/core/ingestion/parsing-processor.d.ts +19 -0
  86. package/dist/core/ingestion/parsing-processor.js +315 -0
  87. package/dist/core/ingestion/pipeline.d.ts +6 -0
  88. package/dist/core/ingestion/pipeline.js +401 -0
  89. package/dist/core/ingestion/process-processor.d.ts +51 -0
  90. package/dist/core/ingestion/process-processor.js +315 -0
  91. package/dist/core/ingestion/resolution-context.d.ts +53 -0
  92. package/dist/core/ingestion/resolution-context.js +132 -0
  93. package/dist/core/ingestion/resolvers/csharp.d.ts +22 -0
  94. package/dist/core/ingestion/resolvers/csharp.js +109 -0
  95. package/dist/core/ingestion/resolvers/go.d.ts +19 -0
  96. package/dist/core/ingestion/resolvers/go.js +42 -0
  97. package/dist/core/ingestion/resolvers/index.d.ts +18 -0
  98. package/dist/core/ingestion/resolvers/index.js +13 -0
  99. package/dist/core/ingestion/resolvers/jvm.d.ts +23 -0
  100. package/dist/core/ingestion/resolvers/jvm.js +87 -0
  101. package/dist/core/ingestion/resolvers/php.d.ts +15 -0
  102. package/dist/core/ingestion/resolvers/php.js +35 -0
  103. package/dist/core/ingestion/resolvers/python.d.ts +19 -0
  104. package/dist/core/ingestion/resolvers/python.js +52 -0
  105. package/dist/core/ingestion/resolvers/ruby.d.ts +12 -0
  106. package/dist/core/ingestion/resolvers/ruby.js +15 -0
  107. package/dist/core/ingestion/resolvers/rust.d.ts +15 -0
  108. package/dist/core/ingestion/resolvers/rust.js +73 -0
  109. package/dist/core/ingestion/resolvers/standard.d.ts +28 -0
  110. package/dist/core/ingestion/resolvers/standard.js +123 -0
  111. package/dist/core/ingestion/resolvers/utils.d.ts +33 -0
  112. package/dist/core/ingestion/resolvers/utils.js +122 -0
  113. package/dist/core/ingestion/structure-processor.d.ts +2 -0
  114. package/dist/core/ingestion/structure-processor.js +36 -0
  115. package/dist/core/ingestion/symbol-table.d.ts +63 -0
  116. package/dist/core/ingestion/symbol-table.js +85 -0
  117. package/dist/core/ingestion/tree-sitter-queries.d.ts +15 -0
  118. package/dist/core/ingestion/tree-sitter-queries.js +888 -0
  119. package/dist/core/ingestion/type-env.d.ts +49 -0
  120. package/dist/core/ingestion/type-env.js +613 -0
  121. package/dist/core/ingestion/type-extractors/c-cpp.d.ts +2 -0
  122. package/dist/core/ingestion/type-extractors/c-cpp.js +385 -0
  123. package/dist/core/ingestion/type-extractors/csharp.d.ts +2 -0
  124. package/dist/core/ingestion/type-extractors/csharp.js +383 -0
  125. package/dist/core/ingestion/type-extractors/go.d.ts +2 -0
  126. package/dist/core/ingestion/type-extractors/go.js +467 -0
  127. package/dist/core/ingestion/type-extractors/index.d.ts +22 -0
  128. package/dist/core/ingestion/type-extractors/index.js +31 -0
  129. package/dist/core/ingestion/type-extractors/jvm.d.ts +3 -0
  130. package/dist/core/ingestion/type-extractors/jvm.js +681 -0
  131. package/dist/core/ingestion/type-extractors/php.d.ts +2 -0
  132. package/dist/core/ingestion/type-extractors/php.js +549 -0
  133. package/dist/core/ingestion/type-extractors/python.d.ts +2 -0
  134. package/dist/core/ingestion/type-extractors/python.js +455 -0
  135. package/dist/core/ingestion/type-extractors/ruby.d.ts +2 -0
  136. package/dist/core/ingestion/type-extractors/ruby.js +389 -0
  137. package/dist/core/ingestion/type-extractors/rust.d.ts +2 -0
  138. package/dist/core/ingestion/type-extractors/rust.js +456 -0
  139. package/dist/core/ingestion/type-extractors/shared.d.ts +145 -0
  140. package/dist/core/ingestion/type-extractors/shared.js +810 -0
  141. package/dist/core/ingestion/type-extractors/swift.d.ts +2 -0
  142. package/dist/core/ingestion/type-extractors/swift.js +137 -0
  143. package/dist/core/ingestion/type-extractors/types.d.ts +127 -0
  144. package/dist/core/ingestion/type-extractors/types.js +1 -0
  145. package/dist/core/ingestion/type-extractors/typescript.d.ts +2 -0
  146. package/dist/core/ingestion/type-extractors/typescript.js +494 -0
  147. package/dist/core/ingestion/utils.d.ts +138 -0
  148. package/dist/core/ingestion/utils.js +1290 -0
  149. package/dist/core/ingestion/workers/parse-worker.d.ts +122 -0
  150. package/dist/core/ingestion/workers/parse-worker.js +1126 -0
  151. package/dist/core/ingestion/workers/worker-pool.d.ts +16 -0
  152. package/dist/core/ingestion/workers/worker-pool.js +128 -0
  153. package/dist/core/lbug/csv-generator.d.ts +33 -0
  154. package/dist/core/lbug/csv-generator.js +366 -0
  155. package/dist/core/lbug/lbug-adapter.d.ts +103 -0
  156. package/dist/core/lbug/lbug-adapter.js +769 -0
  157. package/dist/core/lbug/schema.d.ts +53 -0
  158. package/dist/core/lbug/schema.js +430 -0
  159. package/dist/core/search/bm25-index.d.ts +23 -0
  160. package/dist/core/search/bm25-index.js +96 -0
  161. package/dist/core/search/hybrid-search.d.ts +49 -0
  162. package/dist/core/search/hybrid-search.js +118 -0
  163. package/dist/core/tree-sitter/parser-loader.d.ts +5 -0
  164. package/dist/core/tree-sitter/parser-loader.js +63 -0
  165. package/dist/core/wiki/generator.d.ts +120 -0
  166. package/dist/core/wiki/generator.js +939 -0
  167. package/dist/core/wiki/graph-queries.d.ts +80 -0
  168. package/dist/core/wiki/graph-queries.js +238 -0
  169. package/dist/core/wiki/html-viewer.d.ts +10 -0
  170. package/dist/core/wiki/html-viewer.js +297 -0
  171. package/dist/core/wiki/llm-client.d.ts +43 -0
  172. package/dist/core/wiki/llm-client.js +186 -0
  173. package/dist/core/wiki/prompts.d.ts +53 -0
  174. package/dist/core/wiki/prompts.js +174 -0
  175. package/dist/lib/utils.d.ts +1 -0
  176. package/dist/lib/utils.js +3 -0
  177. package/dist/mcp/compatible-stdio-transport.d.ts +25 -0
  178. package/dist/mcp/compatible-stdio-transport.js +200 -0
  179. package/dist/mcp/core/embedder.d.ts +27 -0
  180. package/dist/mcp/core/embedder.js +108 -0
  181. package/dist/mcp/core/lbug-adapter.d.ts +57 -0
  182. package/dist/mcp/core/lbug-adapter.js +455 -0
  183. package/dist/mcp/local/local-backend.d.ts +181 -0
  184. package/dist/mcp/local/local-backend.js +1722 -0
  185. package/dist/mcp/resources.d.ts +31 -0
  186. package/dist/mcp/resources.js +411 -0
  187. package/dist/mcp/server.d.ts +23 -0
  188. package/dist/mcp/server.js +296 -0
  189. package/dist/mcp/staleness.d.ts +15 -0
  190. package/dist/mcp/staleness.js +29 -0
  191. package/dist/mcp/tools.d.ts +24 -0
  192. package/dist/mcp/tools.js +292 -0
  193. package/dist/server/api.d.ts +10 -0
  194. package/dist/server/api.js +344 -0
  195. package/dist/server/mcp-http.d.ts +13 -0
  196. package/dist/server/mcp-http.js +100 -0
  197. package/dist/storage/git.d.ts +6 -0
  198. package/dist/storage/git.js +35 -0
  199. package/dist/storage/repo-manager.d.ts +138 -0
  200. package/dist/storage/repo-manager.js +299 -0
  201. package/dist/types/pipeline.d.ts +32 -0
  202. package/dist/types/pipeline.js +18 -0
  203. package/dist/unreal/bridge.d.ts +4 -0
  204. package/dist/unreal/bridge.js +113 -0
  205. package/dist/unreal/config.d.ts +6 -0
  206. package/dist/unreal/config.js +55 -0
  207. package/dist/unreal/types.d.ts +105 -0
  208. package/dist/unreal/types.js +1 -0
  209. package/hooks/claude/gitnexus-hook.cjs +238 -0
  210. package/hooks/claude/pre-tool-use.sh +79 -0
  211. package/hooks/claude/session-start.sh +42 -0
  212. package/package.json +100 -0
  213. package/scripts/ensure-cli-executable.cjs +21 -0
  214. package/scripts/patch-tree-sitter-swift.cjs +74 -0
  215. package/scripts/setup-unreal-gitnexus.ps1 +191 -0
  216. package/skills/gitnexus-cli.md +82 -0
  217. package/skills/gitnexus-debugging.md +89 -0
  218. package/skills/gitnexus-exploring.md +78 -0
  219. package/skills/gitnexus-guide.md +64 -0
  220. package/skills/gitnexus-impact-analysis.md +97 -0
  221. package/skills/gitnexus-pr-review.md +163 -0
  222. package/skills/gitnexus-refactoring.md +121 -0
  223. package/vendor/leiden/index.cjs +355 -0
  224. package/vendor/leiden/utils.cjs +392 -0
@@ -0,0 +1,186 @@
1
+ /**
2
+ * LLM Client for Wiki Generation
3
+ *
4
+ * OpenAI-compatible API client using native fetch.
5
+ * Supports OpenAI, Azure, LiteLLM, Ollama, and any OpenAI-compatible endpoint.
6
+ *
7
+ * Config priority: CLI flags > env vars > defaults
8
+ */
9
+ /**
10
+ * Resolve LLM configuration from env vars, saved config, and optional overrides.
11
+ * Priority: overrides (CLI flags) > env vars > ~/.gitnexus/config.json > error
12
+ *
13
+ * If no API key is found, returns config with empty apiKey (caller should handle).
14
+ */
15
+ export async function resolveLLMConfig(overrides) {
16
+ const { loadCLIConfig } = await import('../../storage/repo-manager.js');
17
+ const savedConfig = await loadCLIConfig();
18
+ const apiKey = overrides?.apiKey
19
+ || process.env.GITNEXUS_API_KEY
20
+ || process.env.OPENAI_API_KEY
21
+ || process.env.AI_GATEWAY_API_KEY
22
+ || savedConfig.apiKey
23
+ || '';
24
+ return {
25
+ apiKey,
26
+ baseUrl: overrides?.baseUrl
27
+ || process.env.GITNEXUS_LLM_BASE_URL
28
+ || savedConfig.baseUrl
29
+ || 'https://openrouter.ai/api/v1',
30
+ model: overrides?.model
31
+ || process.env.GITNEXUS_MODEL
32
+ || savedConfig.model
33
+ || 'minimax/minimax-m2.5',
34
+ maxTokens: overrides?.maxTokens ?? 16_384,
35
+ temperature: overrides?.temperature ?? 0,
36
+ gatewayApiKey: overrides?.gatewayApiKey || process.env.AI_GATEWAY_API_KEY || '',
37
+ gatewayCredential: overrides?.gatewayCredential || process.env.AI_GATEWAY_CREDENTIAL || '',
38
+ gatewayGroup: overrides?.gatewayGroup || process.env.AI_GATEWAY_GROUP || '',
39
+ };
40
+ }
41
+ /**
42
+ * Estimate token count from text (rough heuristic: ~4 chars per token).
43
+ */
44
+ export function estimateTokens(text) {
45
+ return Math.ceil(text.length / 4);
46
+ }
47
+ function isGatewayStreamStartFailure(status, errorText) {
48
+ if (status < 500)
49
+ return false;
50
+ const normalized = errorText.toLowerCase();
51
+ return normalized.includes('empty_stream')
52
+ || normalized.includes('upstream stream closed before first payload');
53
+ }
54
+ /**
55
+ * Call an OpenAI-compatible LLM API.
56
+ * Uses streaming when onChunk callback is provided for real-time progress.
57
+ * Retries up to 3 times on transient failures (429, 5xx, network errors).
58
+ */
59
+ export async function callLLM(prompt, config, systemPrompt, options) {
60
+ const messages = [];
61
+ if (systemPrompt) {
62
+ messages.push({ role: 'system', content: systemPrompt });
63
+ }
64
+ messages.push({ role: 'user', content: prompt });
65
+ const url = `${config.baseUrl.replace(/\/+$/, '')}/chat/completions`;
66
+ const useStream = !!options?.onChunk;
67
+ const baseBody = {
68
+ model: config.model,
69
+ messages,
70
+ max_tokens: config.maxTokens,
71
+ temperature: config.temperature,
72
+ };
73
+ const MAX_RETRIES = 3;
74
+ let lastError = null;
75
+ let preferStream = useStream;
76
+ let streamFallbackUsed = false;
77
+ const headers = {
78
+ 'Content-Type': 'application/json',
79
+ 'Authorization': `Bearer ${config.apiKey}`,
80
+ };
81
+ if (config.gatewayApiKey)
82
+ headers.AI_GATEWAY_API_KEY = config.gatewayApiKey;
83
+ if (config.gatewayCredential)
84
+ headers.AI_GATEWAY_CREDENTIAL = config.gatewayCredential;
85
+ if (config.gatewayGroup)
86
+ headers.AI_GATEWAY_GROUP = config.gatewayGroup;
87
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
88
+ try {
89
+ const response = await fetch(url, {
90
+ method: 'POST',
91
+ headers,
92
+ body: JSON.stringify(preferStream ? { ...baseBody, stream: true } : baseBody),
93
+ });
94
+ if (!response.ok) {
95
+ const errorText = await response.text().catch(() => 'unknown error');
96
+ if (preferStream && !streamFallbackUsed && isGatewayStreamStartFailure(response.status, errorText)) {
97
+ streamFallbackUsed = true;
98
+ preferStream = false;
99
+ attempt--;
100
+ continue;
101
+ }
102
+ // Rate limit — wait with exponential backoff and retry
103
+ if (response.status === 429 && attempt < MAX_RETRIES - 1) {
104
+ const retryAfter = parseInt(response.headers.get('retry-after') || '0', 10);
105
+ const delay = retryAfter > 0 ? retryAfter * 1000 : (2 ** attempt) * 3000;
106
+ await sleep(delay);
107
+ continue;
108
+ }
109
+ // Server error — retry with backoff
110
+ if (response.status >= 500 && attempt < MAX_RETRIES - 1) {
111
+ await sleep((attempt + 1) * 2000);
112
+ continue;
113
+ }
114
+ throw new Error(`LLM API error (${response.status}): ${errorText.slice(0, 500)}`);
115
+ }
116
+ // Streaming path
117
+ if (preferStream && response.body) {
118
+ return await readSSEStream(response.body, options.onChunk);
119
+ }
120
+ // Non-streaming path
121
+ const json = await response.json();
122
+ const choice = json.choices?.[0];
123
+ if (!choice?.message?.content) {
124
+ throw new Error('LLM returned empty response');
125
+ }
126
+ return {
127
+ content: choice.message.content,
128
+ promptTokens: json.usage?.prompt_tokens,
129
+ completionTokens: json.usage?.completion_tokens,
130
+ };
131
+ }
132
+ catch (err) {
133
+ lastError = err;
134
+ // Network error — retry with backoff
135
+ if (attempt < MAX_RETRIES - 1 && (err.code === 'ECONNREFUSED' || err.code === 'ETIMEDOUT' || err.message?.includes('fetch'))) {
136
+ await sleep((attempt + 1) * 3000);
137
+ continue;
138
+ }
139
+ throw err;
140
+ }
141
+ }
142
+ throw lastError || new Error('LLM call failed after retries');
143
+ }
144
+ /**
145
+ * Read an SSE stream from an OpenAI-compatible streaming response.
146
+ */
147
+ async function readSSEStream(body, onChunk) {
148
+ const decoder = new TextDecoder();
149
+ const reader = body.getReader();
150
+ let content = '';
151
+ let buffer = '';
152
+ while (true) {
153
+ const { done, value } = await reader.read();
154
+ if (done)
155
+ break;
156
+ buffer += decoder.decode(value, { stream: true });
157
+ const lines = buffer.split('\n');
158
+ buffer = lines.pop() || '';
159
+ for (const line of lines) {
160
+ const trimmed = line.trim();
161
+ if (!trimmed || !trimmed.startsWith('data: '))
162
+ continue;
163
+ const data = trimmed.slice(6);
164
+ if (data === '[DONE]')
165
+ continue;
166
+ try {
167
+ const parsed = JSON.parse(data);
168
+ const delta = parsed.choices?.[0]?.delta?.content;
169
+ if (delta) {
170
+ content += delta;
171
+ onChunk(content.length);
172
+ }
173
+ }
174
+ catch {
175
+ // Skip malformed SSE chunks
176
+ }
177
+ }
178
+ }
179
+ if (!content) {
180
+ throw new Error('LLM returned empty streaming response');
181
+ }
182
+ return { content };
183
+ }
184
+ function sleep(ms) {
185
+ return new Promise(resolve => setTimeout(resolve, ms));
186
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * LLM Prompt Templates for Wiki Generation
3
+ *
4
+ * All prompts produce deterministic, source-grounded documentation.
5
+ * Templates use {{PLACEHOLDER}} substitution.
6
+ */
7
+ export declare const GROUPING_SYSTEM_PROMPT = "You are a documentation architect. Given a list of source files with their exported symbols, group them into logical documentation modules.\n\nRules:\n- Each module should represent a cohesive feature, layer, or domain\n- Every file must appear in exactly one module\n- Module names should be human-readable (e.g. \"Authentication\", \"Database Layer\", \"API Routes\")\n- Aim for 5-15 modules for a typical project. Fewer for small projects, more for large ones\n- Group by functionality, not by file type or directory structure alone\n- Do NOT create modules for tests, configs, or non-source files";
8
+ export declare const GROUPING_USER_PROMPT = "Group these source files into documentation modules.\n\n**Files and their exports:**\n{{FILE_LIST}}\n\n**Directory structure:**\n{{DIRECTORY_TREE}}\n\nRespond with ONLY a JSON object mapping module names to file path arrays. No markdown, no explanation.\nExample format:\n{\n \"Authentication\": [\"src/auth/login.ts\", \"src/auth/session.ts\"],\n \"Database\": [\"src/db/connection.ts\", \"src/db/models.ts\"]\n}";
9
+ export declare const MODULE_SYSTEM_PROMPT = "You are a technical documentation writer. Write clear, developer-focused documentation for a code module.\n\nRules:\n- Reference actual function names, class names, and code patterns \u2014 do NOT invent APIs\n- Use the call graph and execution flow data for accuracy, but do NOT mechanically list every edge\n- Include Mermaid diagrams only when they genuinely help understanding. Keep them small (5-10 nodes max)\n- Structure the document however makes sense for this module \u2014 there is no mandatory format\n- Write for a developer who needs to understand and contribute to this code";
10
+ export declare const MODULE_USER_PROMPT = "Write documentation for the **{{MODULE_NAME}}** module.\n\n## Source Code\n\n{{SOURCE_CODE}}\n\n## Call Graph & Execution Flows (reference for accuracy)\n\nInternal calls: {{INTRA_CALLS}}\nOutgoing calls: {{OUTGOING_CALLS}}\nIncoming calls: {{INCOMING_CALLS}}\nExecution flows: {{PROCESSES}}\n\n---\n\nWrite comprehensive documentation for this module. Cover its purpose, how it works, its key components, and how it connects to the rest of the codebase. Use whatever structure best fits this module \u2014 you decide the sections and headings. Include a Mermaid diagram only if it genuinely clarifies the architecture.";
11
+ export declare const PARENT_SYSTEM_PROMPT = "You are a technical documentation writer. Write a summary page for a module that contains sub-modules. Synthesize the children's documentation \u2014 do not re-read source code.\n\nRules:\n- Reference actual components from the child modules\n- Focus on how the sub-modules work together, not repeating their individual docs\n- Keep it concise \u2014 the reader can click through to child pages for detail\n- Include a Mermaid diagram only if it genuinely clarifies how the sub-modules relate";
12
+ export declare const PARENT_USER_PROMPT = "Write documentation for the **{{MODULE_NAME}}** module, which contains these sub-modules:\n\n{{CHILDREN_DOCS}}\n\nCross-module calls: {{CROSS_MODULE_CALLS}}\nShared execution flows: {{CROSS_PROCESSES}}\n\n---\n\nWrite a concise overview of this module group. Explain its purpose, how the sub-modules fit together, and the key workflows that span them. Link to sub-module pages (e.g. `[Sub-module Name](sub-module-slug.md)`) rather than repeating their content. Use whatever structure fits best.";
13
+ export declare const OVERVIEW_SYSTEM_PROMPT = "You are a technical documentation writer. Write the top-level overview page for a repository wiki. This is the first page a new developer sees.\n\nRules:\n- Be clear and welcoming \u2014 this is the entry point to the entire codebase\n- Reference actual module names so readers can navigate to their docs\n- Include a high-level Mermaid architecture diagram showing only the most important modules and their relationships (max 10 nodes). A new dev should grasp it in 10 seconds\n- Do NOT create module index tables or list every module with descriptions \u2014 just link to module pages naturally within the text\n- Use the inter-module edges and execution flow data for accuracy, but do NOT dump them raw";
14
+ export declare const OVERVIEW_USER_PROMPT = "Write the overview page for this repository's wiki.\n\n## Project Info\n\n{{PROJECT_INFO}}\n\n## Module Summaries\n\n{{MODULE_SUMMARIES}}\n\n## Reference Data (for accuracy \u2014 do not reproduce verbatim)\n\nInter-module call edges: {{MODULE_EDGES}}\nKey system flows: {{TOP_PROCESSES}}\n\n---\n\nWrite a clear overview of this project: what it does, how it's architected, and the key end-to-end flows. Include a simple Mermaid architecture diagram (max 10 nodes, big-picture only). Link to module pages (e.g. `[Module Name](module-slug.md)`) naturally in the text rather than listing them in a table. If project config was provided, include brief setup instructions. Structure the page however reads best.";
15
+ /**
16
+ * Replace {{PLACEHOLDER}} tokens in a template string.
17
+ */
18
+ export declare function fillTemplate(template: string, vars: Record<string, string>): string;
19
+ /**
20
+ * Format file list with exports for the grouping prompt.
21
+ */
22
+ export declare function formatFileListForGrouping(files: Array<{
23
+ filePath: string;
24
+ symbols: Array<{
25
+ name: string;
26
+ type: string;
27
+ }>;
28
+ }>): string;
29
+ /**
30
+ * Build a directory tree string from file paths.
31
+ */
32
+ export declare function formatDirectoryTree(filePaths: string[]): string;
33
+ /**
34
+ * Format call edges as readable text.
35
+ */
36
+ export declare function formatCallEdges(edges: Array<{
37
+ fromFile: string;
38
+ fromName: string;
39
+ toFile: string;
40
+ toName: string;
41
+ }>): string;
42
+ /**
43
+ * Format process traces as readable text.
44
+ */
45
+ export declare function formatProcesses(processes: Array<{
46
+ label: string;
47
+ type: string;
48
+ steps: Array<{
49
+ step: number;
50
+ name: string;
51
+ filePath: string;
52
+ }>;
53
+ }>): string;
@@ -0,0 +1,174 @@
1
+ /**
2
+ * LLM Prompt Templates for Wiki Generation
3
+ *
4
+ * All prompts produce deterministic, source-grounded documentation.
5
+ * Templates use {{PLACEHOLDER}} substitution.
6
+ */
7
+ // ─── Grouping Prompt ──────────────────────────────────────────────────
8
+ export const GROUPING_SYSTEM_PROMPT = `You are a documentation architect. Given a list of source files with their exported symbols, group them into logical documentation modules.
9
+
10
+ Rules:
11
+ - Each module should represent a cohesive feature, layer, or domain
12
+ - Every file must appear in exactly one module
13
+ - Module names should be human-readable (e.g. "Authentication", "Database Layer", "API Routes")
14
+ - Aim for 5-15 modules for a typical project. Fewer for small projects, more for large ones
15
+ - Group by functionality, not by file type or directory structure alone
16
+ - Do NOT create modules for tests, configs, or non-source files`;
17
+ export const GROUPING_USER_PROMPT = `Group these source files into documentation modules.
18
+
19
+ **Files and their exports:**
20
+ {{FILE_LIST}}
21
+
22
+ **Directory structure:**
23
+ {{DIRECTORY_TREE}}
24
+
25
+ Respond with ONLY a JSON object mapping module names to file path arrays. No markdown, no explanation.
26
+ Example format:
27
+ {
28
+ "Authentication": ["src/auth/login.ts", "src/auth/session.ts"],
29
+ "Database": ["src/db/connection.ts", "src/db/models.ts"]
30
+ }`;
31
+ // ─── Leaf Module Prompt ───────────────────────────────────────────────
32
+ export const MODULE_SYSTEM_PROMPT = `You are a technical documentation writer. Write clear, developer-focused documentation for a code module.
33
+
34
+ Rules:
35
+ - Reference actual function names, class names, and code patterns — do NOT invent APIs
36
+ - Use the call graph and execution flow data for accuracy, but do NOT mechanically list every edge
37
+ - Include Mermaid diagrams only when they genuinely help understanding. Keep them small (5-10 nodes max)
38
+ - Structure the document however makes sense for this module — there is no mandatory format
39
+ - Write for a developer who needs to understand and contribute to this code`;
40
+ export const MODULE_USER_PROMPT = `Write documentation for the **{{MODULE_NAME}}** module.
41
+
42
+ ## Source Code
43
+
44
+ {{SOURCE_CODE}}
45
+
46
+ ## Call Graph & Execution Flows (reference for accuracy)
47
+
48
+ Internal calls: {{INTRA_CALLS}}
49
+ Outgoing calls: {{OUTGOING_CALLS}}
50
+ Incoming calls: {{INCOMING_CALLS}}
51
+ Execution flows: {{PROCESSES}}
52
+
53
+ ---
54
+
55
+ Write comprehensive documentation for this module. Cover its purpose, how it works, its key components, and how it connects to the rest of the codebase. Use whatever structure best fits this module — you decide the sections and headings. Include a Mermaid diagram only if it genuinely clarifies the architecture.`;
56
+ // ─── Parent Module Prompt ─────────────────────────────────────────────
57
+ export const PARENT_SYSTEM_PROMPT = `You are a technical documentation writer. Write a summary page for a module that contains sub-modules. Synthesize the children's documentation — do not re-read source code.
58
+
59
+ Rules:
60
+ - Reference actual components from the child modules
61
+ - Focus on how the sub-modules work together, not repeating their individual docs
62
+ - Keep it concise — the reader can click through to child pages for detail
63
+ - Include a Mermaid diagram only if it genuinely clarifies how the sub-modules relate`;
64
+ export const PARENT_USER_PROMPT = `Write documentation for the **{{MODULE_NAME}}** module, which contains these sub-modules:
65
+
66
+ {{CHILDREN_DOCS}}
67
+
68
+ Cross-module calls: {{CROSS_MODULE_CALLS}}
69
+ Shared execution flows: {{CROSS_PROCESSES}}
70
+
71
+ ---
72
+
73
+ Write a concise overview of this module group. Explain its purpose, how the sub-modules fit together, and the key workflows that span them. Link to sub-module pages (e.g. \`[Sub-module Name](sub-module-slug.md)\`) rather than repeating their content. Use whatever structure fits best.`;
74
+ // ─── Overview Prompt ──────────────────────────────────────────────────
75
+ export const OVERVIEW_SYSTEM_PROMPT = `You are a technical documentation writer. Write the top-level overview page for a repository wiki. This is the first page a new developer sees.
76
+
77
+ Rules:
78
+ - Be clear and welcoming — this is the entry point to the entire codebase
79
+ - Reference actual module names so readers can navigate to their docs
80
+ - Include a high-level Mermaid architecture diagram showing only the most important modules and their relationships (max 10 nodes). A new dev should grasp it in 10 seconds
81
+ - Do NOT create module index tables or list every module with descriptions — just link to module pages naturally within the text
82
+ - Use the inter-module edges and execution flow data for accuracy, but do NOT dump them raw`;
83
+ export const OVERVIEW_USER_PROMPT = `Write the overview page for this repository's wiki.
84
+
85
+ ## Project Info
86
+
87
+ {{PROJECT_INFO}}
88
+
89
+ ## Module Summaries
90
+
91
+ {{MODULE_SUMMARIES}}
92
+
93
+ ## Reference Data (for accuracy — do not reproduce verbatim)
94
+
95
+ Inter-module call edges: {{MODULE_EDGES}}
96
+ Key system flows: {{TOP_PROCESSES}}
97
+
98
+ ---
99
+
100
+ Write a clear overview of this project: what it does, how it's architected, and the key end-to-end flows. Include a simple Mermaid architecture diagram (max 10 nodes, big-picture only). Link to module pages (e.g. \`[Module Name](module-slug.md)\`) naturally in the text rather than listing them in a table. If project config was provided, include brief setup instructions. Structure the page however reads best.`;
101
+ // ─── Template Substitution Helper ─────────────────────────────────────
102
+ /**
103
+ * Replace {{PLACEHOLDER}} tokens in a template string.
104
+ */
105
+ export function fillTemplate(template, vars) {
106
+ let result = template;
107
+ for (const [key, value] of Object.entries(vars)) {
108
+ result = result.replaceAll(`{{${key}}}`, value);
109
+ }
110
+ return result;
111
+ }
112
+ // ─── Formatting Helpers ───────────────────────────────────────────────
113
+ /**
114
+ * Format file list with exports for the grouping prompt.
115
+ */
116
+ export function formatFileListForGrouping(files) {
117
+ return files
118
+ .map(f => {
119
+ const exports = f.symbols.length > 0
120
+ ? f.symbols.map(s => `${s.name} (${s.type})`).join(', ')
121
+ : 'no exports';
122
+ return `- ${f.filePath}: ${exports}`;
123
+ })
124
+ .join('\n');
125
+ }
126
+ /**
127
+ * Build a directory tree string from file paths.
128
+ */
129
+ export function formatDirectoryTree(filePaths) {
130
+ const dirs = new Set();
131
+ for (const fp of filePaths) {
132
+ const parts = fp.replace(/\\/g, '/').split('/');
133
+ for (let i = 1; i < parts.length; i++) {
134
+ dirs.add(parts.slice(0, i).join('/'));
135
+ }
136
+ }
137
+ const sorted = Array.from(dirs).sort();
138
+ if (sorted.length === 0)
139
+ return '(flat structure)';
140
+ return sorted.slice(0, 50).join('\n') + (sorted.length > 50 ? `\n... and ${sorted.length - 50} more directories` : '');
141
+ }
142
+ /**
143
+ * Format call edges as readable text.
144
+ */
145
+ export function formatCallEdges(edges) {
146
+ if (edges.length === 0)
147
+ return 'None';
148
+ return edges
149
+ .slice(0, 30)
150
+ .map(e => `${e.fromName} (${shortPath(e.fromFile)}) → ${e.toName} (${shortPath(e.toFile)})`)
151
+ .join('\n');
152
+ }
153
+ /**
154
+ * Format process traces as readable text.
155
+ */
156
+ export function formatProcesses(processes) {
157
+ if (processes.length === 0)
158
+ return 'No execution flows detected for this module.';
159
+ return processes
160
+ .map(p => {
161
+ const stepsText = p.steps
162
+ .map(s => ` ${s.step}. ${s.name} (${shortPath(s.filePath)})`)
163
+ .join('\n');
164
+ return `**${p.label}** (${p.type}):\n${stepsText}`;
165
+ })
166
+ .join('\n\n');
167
+ }
168
+ /**
169
+ * Shorten a file path for readability.
170
+ */
171
+ function shortPath(fp) {
172
+ const parts = fp.replace(/\\/g, '/').split('/');
173
+ return parts.length > 3 ? parts.slice(-3).join('/') : fp;
174
+ }
@@ -0,0 +1 @@
1
+ export declare const generateId: (label: string, name: string) => string;
@@ -0,0 +1,3 @@
1
+ export const generateId = (label, name) => {
2
+ return `${label}:${name}`;
3
+ };
@@ -0,0 +1,25 @@
1
+ import type { Transport, TransportSendOptions } from '@modelcontextprotocol/sdk/shared/transport.js';
2
+ import { type JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
3
+ export type StdioFraming = 'content-length' | 'newline';
4
+ export declare class CompatibleStdioServerTransport implements Transport {
5
+ private readonly _stdin;
6
+ private readonly _stdout;
7
+ private _readBuffer;
8
+ private _started;
9
+ private _framing;
10
+ onmessage?: (message: JSONRPCMessage) => void;
11
+ onerror?: (error: Error) => void;
12
+ onclose?: () => void;
13
+ constructor(_stdin?: NodeJS.ReadableStream, _stdout?: NodeJS.WritableStream);
14
+ private readonly _ondata;
15
+ private readonly _onerror;
16
+ start(): Promise<void>;
17
+ private detectFraming;
18
+ private discardBufferedInput;
19
+ private readContentLengthMessage;
20
+ private readNewlineMessage;
21
+ private readMessage;
22
+ private processReadBuffer;
23
+ close(): Promise<void>;
24
+ send(message: JSONRPCMessage, _options?: TransportSendOptions): Promise<void>;
25
+ }
@@ -0,0 +1,200 @@
1
+ import process from 'node:process';
2
+ import { JSONRPCMessageSchema } from '@modelcontextprotocol/sdk/types.js';
3
+ function deserializeMessage(raw) {
4
+ return JSONRPCMessageSchema.parse(JSON.parse(raw));
5
+ }
6
+ function serializeNewlineMessage(message) {
7
+ return `${JSON.stringify(message)}\n`;
8
+ }
9
+ function serializeContentLengthMessage(message) {
10
+ const body = JSON.stringify(message);
11
+ return `Content-Length: ${Buffer.byteLength(body, 'utf8')}\r\n\r\n${body}`;
12
+ }
13
+ function findHeaderEnd(buffer) {
14
+ const crlfEnd = buffer.indexOf('\r\n\r\n');
15
+ if (crlfEnd !== -1) {
16
+ return { index: crlfEnd, separatorLength: 4 };
17
+ }
18
+ const lfEnd = buffer.indexOf('\n\n');
19
+ if (lfEnd !== -1) {
20
+ return { index: lfEnd, separatorLength: 2 };
21
+ }
22
+ return null;
23
+ }
24
+ function looksLikeContentLength(buffer) {
25
+ if (buffer.length < 14) {
26
+ return false;
27
+ }
28
+ const probe = buffer.toString('utf8', 0, Math.min(buffer.length, 32));
29
+ return /^content-length\s*:/i.test(probe);
30
+ }
31
+ const MAX_BUFFER_SIZE = 10 * 1024 * 1024; // 10 MB — generous for JSON-RPC
32
+ export class CompatibleStdioServerTransport {
33
+ _stdin;
34
+ _stdout;
35
+ _readBuffer;
36
+ _started = false;
37
+ _framing = null;
38
+ onmessage;
39
+ onerror;
40
+ onclose;
41
+ constructor(_stdin = process.stdin, _stdout = process.stdout) {
42
+ this._stdin = _stdin;
43
+ this._stdout = _stdout;
44
+ }
45
+ _ondata = (chunk) => {
46
+ this._readBuffer = this._readBuffer ? Buffer.concat([this._readBuffer, chunk]) : chunk;
47
+ if (this._readBuffer.length > MAX_BUFFER_SIZE) {
48
+ this.onerror?.(new Error(`Read buffer exceeded maximum size (${MAX_BUFFER_SIZE} bytes)`));
49
+ this.discardBufferedInput();
50
+ return;
51
+ }
52
+ this.processReadBuffer();
53
+ };
54
+ _onerror = (error) => {
55
+ this.onerror?.(error);
56
+ };
57
+ async start() {
58
+ if (this._started) {
59
+ throw new Error('CompatibleStdioServerTransport already started!');
60
+ }
61
+ this._started = true;
62
+ this._stdin.on('data', this._ondata);
63
+ this._stdin.on('error', this._onerror);
64
+ }
65
+ detectFraming() {
66
+ if (!this._readBuffer || this._readBuffer.length === 0) {
67
+ return null;
68
+ }
69
+ const firstByte = this._readBuffer[0];
70
+ if (firstByte === 0x7b || firstByte === 0x5b) {
71
+ return 'newline';
72
+ }
73
+ if (looksLikeContentLength(this._readBuffer)) {
74
+ return 'content-length';
75
+ }
76
+ return null;
77
+ }
78
+ discardBufferedInput() {
79
+ this._readBuffer = undefined;
80
+ this._framing = null;
81
+ }
82
+ readContentLengthMessage() {
83
+ if (!this._readBuffer) {
84
+ return null;
85
+ }
86
+ const header = findHeaderEnd(this._readBuffer);
87
+ if (header === null) {
88
+ return null;
89
+ }
90
+ const headerText = this._readBuffer
91
+ .toString('utf8', 0, header.index)
92
+ .replace(/\r\n/g, '\n')
93
+ .replace(/\r/g, '\n');
94
+ const match = headerText.match(/(?:^|\n)content-length\s*:\s*(\d+)/i);
95
+ if (!match) {
96
+ this.discardBufferedInput();
97
+ throw new Error('Missing Content-Length header from MCP client');
98
+ }
99
+ const contentLength = Number.parseInt(match[1], 10);
100
+ if (!Number.isFinite(contentLength) || contentLength < 0) {
101
+ this.discardBufferedInput();
102
+ throw new Error('Invalid Content-Length header from MCP client');
103
+ }
104
+ if (contentLength > MAX_BUFFER_SIZE) {
105
+ this.discardBufferedInput();
106
+ throw new Error(`Content-Length ${contentLength} exceeds maximum allowed size (${MAX_BUFFER_SIZE} bytes)`);
107
+ }
108
+ const bodyStart = header.index + header.separatorLength;
109
+ const bodyEnd = bodyStart + contentLength;
110
+ if (this._readBuffer.length < bodyEnd) {
111
+ return null;
112
+ }
113
+ const body = this._readBuffer.toString('utf8', bodyStart, bodyEnd);
114
+ this._readBuffer = this._readBuffer.subarray(bodyEnd);
115
+ return deserializeMessage(body);
116
+ }
117
+ readNewlineMessage() {
118
+ if (!this._readBuffer) {
119
+ return null;
120
+ }
121
+ while (true) {
122
+ const newlineIndex = this._readBuffer.indexOf('\n');
123
+ if (newlineIndex === -1) {
124
+ return null;
125
+ }
126
+ const line = this._readBuffer.toString('utf8', 0, newlineIndex).replace(/\r$/, '');
127
+ this._readBuffer = this._readBuffer.subarray(newlineIndex + 1);
128
+ if (line.trim().length === 0) {
129
+ continue;
130
+ }
131
+ return deserializeMessage(line);
132
+ }
133
+ }
134
+ readMessage() {
135
+ if (!this._readBuffer || this._readBuffer.length === 0) {
136
+ return null;
137
+ }
138
+ if (this._framing === null) {
139
+ this._framing = this.detectFraming();
140
+ if (this._framing === null) {
141
+ return null;
142
+ }
143
+ }
144
+ return this._framing === 'content-length'
145
+ ? this.readContentLengthMessage()
146
+ : this.readNewlineMessage();
147
+ }
148
+ processReadBuffer() {
149
+ while (true) {
150
+ try {
151
+ const message = this.readMessage();
152
+ if (message === null) {
153
+ break;
154
+ }
155
+ this.onmessage?.(message);
156
+ }
157
+ catch (error) {
158
+ this.onerror?.(error);
159
+ break;
160
+ }
161
+ }
162
+ }
163
+ async close() {
164
+ this._stdin.off('data', this._ondata);
165
+ this._stdin.off('error', this._onerror);
166
+ const remainingDataListeners = this._stdin.listenerCount('data');
167
+ if (remainingDataListeners === 0) {
168
+ this._stdin.pause();
169
+ }
170
+ this._started = false;
171
+ this._readBuffer = undefined;
172
+ this.onclose?.();
173
+ }
174
+ send(message, _options) {
175
+ return new Promise((resolve, reject) => {
176
+ if (!this._started) {
177
+ reject(new Error('Transport is closed'));
178
+ return;
179
+ }
180
+ const payload = this._framing === 'newline'
181
+ ? serializeNewlineMessage(message)
182
+ : serializeContentLengthMessage(message);
183
+ const onError = (error) => {
184
+ this._stdout.removeListener('error', onError);
185
+ reject(error);
186
+ };
187
+ this._stdout.on('error', onError);
188
+ if (this._stdout.write(payload)) {
189
+ this._stdout.removeListener('error', onError);
190
+ resolve();
191
+ }
192
+ else {
193
+ this._stdout.once('drain', () => {
194
+ this._stdout.removeListener('error', onError);
195
+ resolve();
196
+ });
197
+ }
198
+ });
199
+ }
200
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Embedder Module (Read-Only)
3
+ *
4
+ * Singleton factory for transformers.js embedding pipeline.
5
+ * For MCP, we only need to compute query embeddings, not batch embed.
6
+ */
7
+ import { type FeatureExtractionPipeline } from '@huggingface/transformers';
8
+ /**
9
+ * Initialize the embedding model (lazy, on first search)
10
+ */
11
+ export declare const initEmbedder: () => Promise<FeatureExtractionPipeline>;
12
+ /**
13
+ * Check if embedder is ready
14
+ */
15
+ export declare const isEmbedderReady: () => boolean;
16
+ /**
17
+ * Embed a query text for semantic search
18
+ */
19
+ export declare const embedQuery: (query: string) => Promise<number[]>;
20
+ /**
21
+ * Get embedding dimensions
22
+ */
23
+ export declare const getEmbeddingDims: () => number;
24
+ /**
25
+ * Cleanup embedder
26
+ */
27
+ export declare const disposeEmbedder: () => Promise<void>;