@zuvia-software-solutions/code-mapper 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (213) hide show
  1. package/README.md +215 -0
  2. package/dist/cli/ai-context.d.ts +19 -0
  3. package/dist/cli/ai-context.js +168 -0
  4. package/dist/cli/analyze.d.ts +7 -0
  5. package/dist/cli/analyze.js +325 -0
  6. package/dist/cli/augment.d.ts +7 -0
  7. package/dist/cli/augment.js +27 -0
  8. package/dist/cli/clean.d.ts +5 -0
  9. package/dist/cli/clean.js +56 -0
  10. package/dist/cli/eval-server.d.ts +25 -0
  11. package/dist/cli/eval-server.js +365 -0
  12. package/dist/cli/index.d.ts +6 -0
  13. package/dist/cli/index.js +102 -0
  14. package/dist/cli/lazy-action.d.ts +6 -0
  15. package/dist/cli/lazy-action.js +19 -0
  16. package/dist/cli/list.d.ts +2 -0
  17. package/dist/cli/list.js +27 -0
  18. package/dist/cli/mcp.d.ts +8 -0
  19. package/dist/cli/mcp.js +35 -0
  20. package/dist/cli/refresh.d.ts +12 -0
  21. package/dist/cli/refresh.js +165 -0
  22. package/dist/cli/serve.d.ts +5 -0
  23. package/dist/cli/serve.js +8 -0
  24. package/dist/cli/setup.d.ts +6 -0
  25. package/dist/cli/setup.js +218 -0
  26. package/dist/cli/status.d.ts +2 -0
  27. package/dist/cli/status.js +33 -0
  28. package/dist/cli/tool.d.ts +28 -0
  29. package/dist/cli/tool.js +87 -0
  30. package/dist/config/ignore-service.d.ts +32 -0
  31. package/dist/config/ignore-service.js +282 -0
  32. package/dist/config/supported-languages.d.ts +23 -0
  33. package/dist/config/supported-languages.js +52 -0
  34. package/dist/core/augmentation/engine.d.ts +22 -0
  35. package/dist/core/augmentation/engine.js +232 -0
  36. package/dist/core/embeddings/embedder.d.ts +35 -0
  37. package/dist/core/embeddings/embedder.js +171 -0
  38. package/dist/core/embeddings/embedding-pipeline.d.ts +41 -0
  39. package/dist/core/embeddings/embedding-pipeline.js +402 -0
  40. package/dist/core/embeddings/index.d.ts +5 -0
  41. package/dist/core/embeddings/index.js +6 -0
  42. package/dist/core/embeddings/text-generator.d.ts +20 -0
  43. package/dist/core/embeddings/text-generator.js +159 -0
  44. package/dist/core/embeddings/types.d.ts +60 -0
  45. package/dist/core/embeddings/types.js +23 -0
  46. package/dist/core/graph/graph.d.ts +4 -0
  47. package/dist/core/graph/graph.js +65 -0
  48. package/dist/core/graph/types.d.ts +69 -0
  49. package/dist/core/graph/types.js +3 -0
  50. package/dist/core/incremental/child-process.d.ts +8 -0
  51. package/dist/core/incremental/child-process.js +649 -0
  52. package/dist/core/incremental/refresh-coordinator.d.ts +32 -0
  53. package/dist/core/incremental/refresh-coordinator.js +147 -0
  54. package/dist/core/incremental/types.d.ts +78 -0
  55. package/dist/core/incremental/types.js +153 -0
  56. package/dist/core/incremental/watcher.d.ts +63 -0
  57. package/dist/core/incremental/watcher.js +338 -0
  58. package/dist/core/ingestion/ast-cache.d.ts +12 -0
  59. package/dist/core/ingestion/ast-cache.js +34 -0
  60. package/dist/core/ingestion/call-processor.d.ts +34 -0
  61. package/dist/core/ingestion/call-processor.js +937 -0
  62. package/dist/core/ingestion/call-routing.d.ts +40 -0
  63. package/dist/core/ingestion/call-routing.js +97 -0
  64. package/dist/core/ingestion/cluster-enricher.d.ts +30 -0
  65. package/dist/core/ingestion/cluster-enricher.js +151 -0
  66. package/dist/core/ingestion/community-processor.d.ts +26 -0
  67. package/dist/core/ingestion/community-processor.js +272 -0
  68. package/dist/core/ingestion/constants.d.ts +5 -0
  69. package/dist/core/ingestion/constants.js +8 -0
  70. package/dist/core/ingestion/entry-point-scoring.d.ts +23 -0
  71. package/dist/core/ingestion/entry-point-scoring.js +317 -0
  72. package/dist/core/ingestion/export-detection.d.ts +11 -0
  73. package/dist/core/ingestion/export-detection.js +203 -0
  74. package/dist/core/ingestion/filesystem-walker.d.ts +18 -0
  75. package/dist/core/ingestion/filesystem-walker.js +64 -0
  76. package/dist/core/ingestion/framework-detection.d.ts +42 -0
  77. package/dist/core/ingestion/framework-detection.js +405 -0
  78. package/dist/core/ingestion/heritage-processor.d.ts +15 -0
  79. package/dist/core/ingestion/heritage-processor.js +237 -0
  80. package/dist/core/ingestion/import-processor.d.ts +31 -0
  81. package/dist/core/ingestion/import-processor.js +416 -0
  82. package/dist/core/ingestion/language-config.d.ts +32 -0
  83. package/dist/core/ingestion/language-config.js +161 -0
  84. package/dist/core/ingestion/mro-processor.d.ts +32 -0
  85. package/dist/core/ingestion/mro-processor.js +343 -0
  86. package/dist/core/ingestion/named-binding-extraction.d.ts +51 -0
  87. package/dist/core/ingestion/named-binding-extraction.js +343 -0
  88. package/dist/core/ingestion/parsing-processor.d.ts +20 -0
  89. package/dist/core/ingestion/parsing-processor.js +282 -0
  90. package/dist/core/ingestion/pipeline.d.ts +3 -0
  91. package/dist/core/ingestion/pipeline.js +416 -0
  92. package/dist/core/ingestion/process-processor.d.ts +42 -0
  93. package/dist/core/ingestion/process-processor.js +357 -0
  94. package/dist/core/ingestion/resolution-context.d.ts +40 -0
  95. package/dist/core/ingestion/resolution-context.js +171 -0
  96. package/dist/core/ingestion/resolvers/csharp.d.ts +10 -0
  97. package/dist/core/ingestion/resolvers/csharp.js +101 -0
  98. package/dist/core/ingestion/resolvers/go.d.ts +8 -0
  99. package/dist/core/ingestion/resolvers/go.js +33 -0
  100. package/dist/core/ingestion/resolvers/index.d.ts +14 -0
  101. package/dist/core/ingestion/resolvers/index.js +10 -0
  102. package/dist/core/ingestion/resolvers/jvm.d.ts +9 -0
  103. package/dist/core/ingestion/resolvers/jvm.js +74 -0
  104. package/dist/core/ingestion/resolvers/php.d.ts +7 -0
  105. package/dist/core/ingestion/resolvers/php.js +30 -0
  106. package/dist/core/ingestion/resolvers/ruby.d.ts +9 -0
  107. package/dist/core/ingestion/resolvers/ruby.js +13 -0
  108. package/dist/core/ingestion/resolvers/rust.d.ts +5 -0
  109. package/dist/core/ingestion/resolvers/rust.js +62 -0
  110. package/dist/core/ingestion/resolvers/standard.d.ts +16 -0
  111. package/dist/core/ingestion/resolvers/standard.js +144 -0
  112. package/dist/core/ingestion/resolvers/utils.d.ts +18 -0
  113. package/dist/core/ingestion/resolvers/utils.js +113 -0
  114. package/dist/core/ingestion/structure-processor.d.ts +4 -0
  115. package/dist/core/ingestion/structure-processor.js +39 -0
  116. package/dist/core/ingestion/symbol-table.d.ts +34 -0
  117. package/dist/core/ingestion/symbol-table.js +48 -0
  118. package/dist/core/ingestion/tree-sitter-queries.d.ts +20 -0
  119. package/dist/core/ingestion/tree-sitter-queries.js +691 -0
  120. package/dist/core/ingestion/type-env.d.ts +52 -0
  121. package/dist/core/ingestion/type-env.js +349 -0
  122. package/dist/core/ingestion/type-extractors/c-cpp.d.ts +4 -0
  123. package/dist/core/ingestion/type-extractors/c-cpp.js +214 -0
  124. package/dist/core/ingestion/type-extractors/csharp.d.ts +4 -0
  125. package/dist/core/ingestion/type-extractors/csharp.js +224 -0
  126. package/dist/core/ingestion/type-extractors/go.d.ts +4 -0
  127. package/dist/core/ingestion/type-extractors/go.js +261 -0
  128. package/dist/core/ingestion/type-extractors/index.d.ts +20 -0
  129. package/dist/core/ingestion/type-extractors/index.js +30 -0
  130. package/dist/core/ingestion/type-extractors/jvm.d.ts +5 -0
  131. package/dist/core/ingestion/type-extractors/jvm.js +386 -0
  132. package/dist/core/ingestion/type-extractors/php.d.ts +4 -0
  133. package/dist/core/ingestion/type-extractors/php.js +280 -0
  134. package/dist/core/ingestion/type-extractors/python.d.ts +4 -0
  135. package/dist/core/ingestion/type-extractors/python.js +175 -0
  136. package/dist/core/ingestion/type-extractors/ruby.d.ts +12 -0
  137. package/dist/core/ingestion/type-extractors/ruby.js +218 -0
  138. package/dist/core/ingestion/type-extractors/rust.d.ts +4 -0
  139. package/dist/core/ingestion/type-extractors/rust.js +290 -0
  140. package/dist/core/ingestion/type-extractors/shared.d.ts +81 -0
  141. package/dist/core/ingestion/type-extractors/shared.js +322 -0
  142. package/dist/core/ingestion/type-extractors/swift.d.ts +4 -0
  143. package/dist/core/ingestion/type-extractors/swift.js +140 -0
  144. package/dist/core/ingestion/type-extractors/types.d.ts +111 -0
  145. package/dist/core/ingestion/type-extractors/types.js +4 -0
  146. package/dist/core/ingestion/type-extractors/typescript.d.ts +4 -0
  147. package/dist/core/ingestion/type-extractors/typescript.js +227 -0
  148. package/dist/core/ingestion/utils.d.ts +73 -0
  149. package/dist/core/ingestion/utils.js +992 -0
  150. package/dist/core/ingestion/workers/parse-worker.d.ts +99 -0
  151. package/dist/core/ingestion/workers/parse-worker.js +1055 -0
  152. package/dist/core/ingestion/workers/worker-pool.d.ts +15 -0
  153. package/dist/core/ingestion/workers/worker-pool.js +123 -0
  154. package/dist/core/lbug/csv-generator.d.ts +28 -0
  155. package/dist/core/lbug/csv-generator.js +355 -0
  156. package/dist/core/lbug/lbug-adapter.d.ts +96 -0
  157. package/dist/core/lbug/lbug-adapter.js +753 -0
  158. package/dist/core/lbug/schema.d.ts +46 -0
  159. package/dist/core/lbug/schema.js +402 -0
  160. package/dist/core/search/bm25-index.d.ts +20 -0
  161. package/dist/core/search/bm25-index.js +123 -0
  162. package/dist/core/search/hybrid-search.d.ts +32 -0
  163. package/dist/core/search/hybrid-search.js +131 -0
  164. package/dist/core/search/query-cache.d.ts +18 -0
  165. package/dist/core/search/query-cache.js +47 -0
  166. package/dist/core/search/query-expansion.d.ts +19 -0
  167. package/dist/core/search/query-expansion.js +75 -0
  168. package/dist/core/search/reranker.d.ts +29 -0
  169. package/dist/core/search/reranker.js +122 -0
  170. package/dist/core/search/types.d.ts +154 -0
  171. package/dist/core/search/types.js +51 -0
  172. package/dist/core/semantic/tsgo-service.d.ts +67 -0
  173. package/dist/core/semantic/tsgo-service.js +355 -0
  174. package/dist/core/tree-sitter/parser-loader.d.ts +12 -0
  175. package/dist/core/tree-sitter/parser-loader.js +71 -0
  176. package/dist/lib/memory-guard.d.ts +35 -0
  177. package/dist/lib/memory-guard.js +70 -0
  178. package/dist/lib/utils.d.ts +3 -0
  179. package/dist/lib/utils.js +6 -0
  180. package/dist/mcp/compatible-stdio-transport.d.ts +32 -0
  181. package/dist/mcp/compatible-stdio-transport.js +209 -0
  182. package/dist/mcp/core/embedder.d.ts +24 -0
  183. package/dist/mcp/core/embedder.js +168 -0
  184. package/dist/mcp/core/lbug-adapter.d.ts +29 -0
  185. package/dist/mcp/core/lbug-adapter.js +330 -0
  186. package/dist/mcp/local/local-backend.d.ts +188 -0
  187. package/dist/mcp/local/local-backend.js +2759 -0
  188. package/dist/mcp/resources.d.ts +22 -0
  189. package/dist/mcp/resources.js +379 -0
  190. package/dist/mcp/server.d.ts +10 -0
  191. package/dist/mcp/server.js +217 -0
  192. package/dist/mcp/staleness.d.ts +10 -0
  193. package/dist/mcp/staleness.js +25 -0
  194. package/dist/mcp/tools.d.ts +21 -0
  195. package/dist/mcp/tools.js +202 -0
  196. package/dist/server/api.d.ts +5 -0
  197. package/dist/server/api.js +340 -0
  198. package/dist/server/mcp-http.d.ts +7 -0
  199. package/dist/server/mcp-http.js +95 -0
  200. package/dist/storage/git.d.ts +6 -0
  201. package/dist/storage/git.js +35 -0
  202. package/dist/storage/repo-manager.d.ts +87 -0
  203. package/dist/storage/repo-manager.js +249 -0
  204. package/dist/types/pipeline.d.ts +35 -0
  205. package/dist/types/pipeline.js +20 -0
  206. package/hooks/claude/code-mapper-hook.cjs +238 -0
  207. package/hooks/claude/pre-tool-use.sh +79 -0
  208. package/hooks/claude/session-start.sh +42 -0
  209. package/models/mlx-embedder.py +185 -0
  210. package/package.json +100 -0
  211. package/scripts/patch-tree-sitter-swift.cjs +74 -0
  212. package/vendor/leiden/index.cjs +355 -0
  213. package/vendor/leiden/utils.cjs +392 -0
@@ -0,0 +1,15 @@
1
+ /** @file Generic worker thread pool with sub-batch streaming for bounded memory usage */
2
+ export interface WorkerPool {
3
+ /**
4
+ * Dispatch items across workers with sub-batch streaming
5
+ * @param items - Items to process (split into chunks, one per worker)
6
+ * @param onProgress - Optional callback for progress reporting
7
+ */
8
+ dispatch<TInput, TResult>(items: TInput[], onProgress?: (filesProcessed: number) => void): Promise<TResult[]>;
9
+ /** Terminate all workers (must be called when done) */
10
+ terminate(): Promise<void>;
11
+ /** Number of workers in the pool */
12
+ readonly size: number;
13
+ }
14
+ /** Create a pool of worker threads */
15
+ export declare const createWorkerPool: (workerUrl: URL, poolSize?: number) => WorkerPool;
@@ -0,0 +1,123 @@
1
+ // code-mapper/src/core/ingestion/workers/worker-pool.ts
2
+ /** @file Generic worker thread pool with sub-batch streaming for bounded memory usage */
3
+ import { Worker } from 'node:worker_threads';
4
+ import os from 'node:os';
5
+ import fs from 'node:fs';
6
+ import { fileURLToPath } from 'node:url';
7
+ // Max files per postMessage to keep structured-clone memory bounded
8
+ const SUB_BATCH_SIZE = 1500;
9
+ // Per sub-batch timeout (likely a pathological file if exceeded)
10
+ const SUB_BATCH_TIMEOUT_MS = 30_000;
11
+ /** Create a pool of worker threads */
12
+ export const createWorkerPool = (workerUrl, poolSize) => {
13
+ // Validate worker script exists before spawning to prevent MODULE_NOT_FOUND crashes
14
+ const workerPath = fileURLToPath(workerUrl);
15
+ if (!fs.existsSync(workerPath)) {
16
+ throw new Error(`Worker script not found: ${workerPath}`);
17
+ }
18
+ const size = poolSize ?? Math.min(8, Math.max(1, os.cpus().length - 1));
19
+ const workers = [];
20
+ for (let i = 0; i < size; i++) {
21
+ workers.push(new Worker(workerUrl));
22
+ }
23
+ const dispatch = (items, onProgress) => {
24
+ if (items.length === 0)
25
+ return Promise.resolve([]);
26
+ const chunkSize = Math.ceil(items.length / size);
27
+ const chunks = [];
28
+ for (let i = 0; i < items.length; i += chunkSize) {
29
+ chunks.push(items.slice(i, i + chunkSize));
30
+ }
31
+ const workerProgress = new Array(chunks.length).fill(0);
32
+ const promises = chunks.map((chunk, i) => {
33
+ const worker = workers[i];
34
+ return new Promise((resolve, reject) => {
35
+ let settled = false;
36
+ let subBatchTimer = null;
37
+ const cleanup = () => {
38
+ if (subBatchTimer)
39
+ clearTimeout(subBatchTimer);
40
+ worker.removeListener('message', handler);
41
+ worker.removeListener('error', errorHandler);
42
+ worker.removeListener('exit', exitHandler);
43
+ };
44
+ const resetSubBatchTimer = () => {
45
+ if (subBatchTimer)
46
+ clearTimeout(subBatchTimer);
47
+ subBatchTimer = setTimeout(() => {
48
+ if (!settled) {
49
+ settled = true;
50
+ cleanup();
51
+ reject(new Error(`Worker ${i} sub-batch timed out after ${SUB_BATCH_TIMEOUT_MS / 1000}s (chunk: ${chunk.length} items).`));
52
+ }
53
+ }, SUB_BATCH_TIMEOUT_MS);
54
+ };
55
+ let subBatchIdx = 0;
56
+ const sendNextSubBatch = () => {
57
+ const start = subBatchIdx * SUB_BATCH_SIZE;
58
+ if (start >= chunk.length) {
59
+ worker.postMessage({ type: 'flush' });
60
+ return;
61
+ }
62
+ const subBatch = chunk.slice(start, start + SUB_BATCH_SIZE);
63
+ subBatchIdx++;
64
+ resetSubBatchTimer();
65
+ worker.postMessage({ type: 'sub-batch', files: subBatch });
66
+ };
67
+ const handler = (msg) => {
68
+ if (settled)
69
+ return;
70
+ if (msg && msg.type === 'progress') {
71
+ workerProgress[i] = msg.filesProcessed;
72
+ if (onProgress) {
73
+ const total = workerProgress.reduce((a, b) => a + b, 0);
74
+ onProgress(total);
75
+ }
76
+ }
77
+ else if (msg && msg.type === 'sub-batch-done') {
78
+ sendNextSubBatch();
79
+ }
80
+ else if (msg && msg.type === 'error') {
81
+ settled = true;
82
+ cleanup();
83
+ reject(new Error(`Worker ${i} error: ${msg.error}`));
84
+ }
85
+ else if (msg && msg.type === 'result') {
86
+ settled = true;
87
+ cleanup();
88
+ resolve(msg.data);
89
+ }
90
+ else {
91
+ settled = true;
92
+ cleanup();
93
+ resolve(msg);
94
+ }
95
+ };
96
+ const errorHandler = (err) => {
97
+ if (!settled) {
98
+ settled = true;
99
+ cleanup();
100
+ reject(err);
101
+ }
102
+ };
103
+ const exitHandler = (code) => {
104
+ if (!settled) {
105
+ settled = true;
106
+ cleanup();
107
+ reject(new Error(`Worker ${i} exited with code ${code}. Likely OOM or native addon failure.`));
108
+ }
109
+ };
110
+ worker.on('message', handler);
111
+ worker.once('error', errorHandler);
112
+ worker.once('exit', exitHandler);
113
+ sendNextSubBatch();
114
+ });
115
+ });
116
+ return Promise.all(promises);
117
+ };
118
+ const terminate = async () => {
119
+ await Promise.all(workers.map(w => w.terminate()));
120
+ workers.length = 0;
121
+ };
122
+ return { dispatch, terminate, size };
123
+ };
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @file csv-generator.ts
3
+ * @description Streams RFC 4180-compliant CSV rows directly to disk in a single
4
+ * pass over graph nodes for LadybugDB bulk import
5
+ *
6
+ * File contents are lazy-read from disk with an LRU cache to avoid holding the
7
+ * entire repo in RAM. Rows are buffered (FLUSH_EVERY) to minimize Promise overhead
8
+ */
9
+ import { KnowledgeGraph } from '../graph/types.js';
10
+ import { NodeTableName } from './schema.js';
11
+ export declare const sanitizeUTF8: (str: string) => string;
12
+ export declare const escapeCSVField: (value: string | number | undefined | null) => string;
13
+ export declare const escapeCSVNumber: (value: number | undefined | null, defaultValue?: number) => string;
14
+ export declare const isBinaryContent: (content: string) => boolean;
15
+ export interface StreamedCSVResult {
16
+ nodeFiles: Map<NodeTableName, {
17
+ csvPath: string;
18
+ rows: number;
19
+ }>;
20
+ relCsvPath: string;
21
+ relRows: number;
22
+ }
23
+ /**
24
+ * Stream all CSV data directly to disk files
25
+ *
26
+ * Iterates graph nodes exactly once — routes each node to the right writer
27
+ */
28
+ export declare const streamAllCSVsToDisk: (graph: KnowledgeGraph, repoPath: string, csvDir: string) => Promise<StreamedCSVResult>;
@@ -0,0 +1,355 @@
1
+ // code-mapper/src/core/lbug/csv-generator.ts
2
+ /**
3
+ * @file csv-generator.ts
4
+ * @description Streams RFC 4180-compliant CSV rows directly to disk in a single
5
+ * pass over graph nodes for LadybugDB bulk import
6
+ *
7
+ * File contents are lazy-read from disk with an LRU cache to avoid holding the
8
+ * entire repo in RAM. Rows are buffered (FLUSH_EVERY) to minimize Promise overhead
9
+ */
10
+ import fs from 'fs/promises';
11
+ import { createWriteStream } from 'fs';
12
+ import path from 'path';
13
+ /** Flush buffered rows to disk every N rows */
14
+ const FLUSH_EVERY = 500;
15
+ // CSV escape utilities
16
+ export const sanitizeUTF8 = (str) => {
17
+ return str
18
+ .replace(/\r\n/g, '\n')
19
+ .replace(/\r/g, '\n')
20
+ .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '')
21
+ .replace(/[\uD800-\uDFFF]/g, '')
22
+ .replace(/[\uFFFE\uFFFF]/g, '');
23
+ };
24
+ export const escapeCSVField = (value) => {
25
+ if (value === undefined || value === null)
26
+ return '""';
27
+ let str = String(value);
28
+ str = sanitizeUTF8(str);
29
+ return `"${str.replace(/"/g, '""')}"`;
30
+ };
31
+ export const escapeCSVNumber = (value, defaultValue = -1) => {
32
+ if (value === undefined || value === null)
33
+ return String(defaultValue);
34
+ return String(value);
35
+ };
36
+ // Content extraction (lazy — reads from disk on demand)
37
+ export const isBinaryContent = (content) => {
38
+ if (!content || content.length === 0)
39
+ return false;
40
+ const sample = content.slice(0, 1000);
41
+ let nonPrintable = 0;
42
+ for (let i = 0; i < sample.length; i++) {
43
+ const code = sample.charCodeAt(i);
44
+ if ((code < 9) || (code > 13 && code < 32) || code === 127)
45
+ nonPrintable++;
46
+ }
47
+ return (nonPrintable / sample.length) > 0.1;
48
+ };
49
+ /**
50
+ * LRU content cache — avoids re-reading the same source file for every
51
+ * symbol defined in it
52
+ */
53
+ class FileContentCache {
54
+ cache = new Map();
55
+ accessOrder = [];
56
+ maxSize;
57
+ repoPath;
58
+ constructor(repoPath, maxSize = 3000) {
59
+ this.repoPath = repoPath;
60
+ this.maxSize = maxSize;
61
+ }
62
+ async get(relativePath) {
63
+ if (!relativePath)
64
+ return '';
65
+ const cached = this.cache.get(relativePath);
66
+ if (cached !== undefined) {
67
+ // Move to end of accessOrder (LRU promotion)
68
+ const idx = this.accessOrder.indexOf(relativePath);
69
+ if (idx !== -1) {
70
+ this.accessOrder.splice(idx, 1);
71
+ this.accessOrder.push(relativePath);
72
+ }
73
+ return cached;
74
+ }
75
+ try {
76
+ const fullPath = path.join(this.repoPath, relativePath);
77
+ const content = await fs.readFile(fullPath, 'utf-8');
78
+ this.set(relativePath, content);
79
+ return content;
80
+ }
81
+ catch {
82
+ this.set(relativePath, '');
83
+ return '';
84
+ }
85
+ }
86
+ set(key, value) {
87
+ if (this.cache.size >= this.maxSize) {
88
+ const oldest = this.accessOrder.shift();
89
+ if (oldest)
90
+ this.cache.delete(oldest);
91
+ }
92
+ this.cache.set(key, value);
93
+ this.accessOrder.push(key);
94
+ }
95
+ }
96
+ const extractContent = async (node, contentCache) => {
97
+ const filePath = node.properties.filePath;
98
+ const content = await contentCache.get(filePath);
99
+ if (!content)
100
+ return '';
101
+ if (node.label === 'Folder')
102
+ return '';
103
+ if (isBinaryContent(content))
104
+ return '[Binary file - content not stored]';
105
+ if (node.label === 'File') {
106
+ const MAX_FILE_CONTENT = 100_000;
107
+ return content.length > MAX_FILE_CONTENT
108
+ ? content.slice(0, MAX_FILE_CONTENT) + '\n... [truncated]'
109
+ : content;
110
+ }
111
+ const startLine = node.properties.startLine;
112
+ const endLine = node.properties.endLine;
113
+ if (startLine === undefined || endLine === undefined)
114
+ return '';
115
+ const lines = content.split('\n');
116
+ const start = Math.max(0, startLine - 2);
117
+ const end = Math.min(lines.length - 1, endLine + 2);
118
+ const snippet = lines.slice(start, end + 1).join('\n');
119
+ const MAX_SNIPPET = 50_000;
120
+ return snippet.length > MAX_SNIPPET
121
+ ? snippet.slice(0, MAX_SNIPPET) + '\n... [truncated]'
122
+ : snippet;
123
+ };
124
+ // Buffered CSV writer
125
+ class BufferedCSVWriter {
126
+ ws;
127
+ buffer = [];
128
+ rows = 0;
129
+ constructor(filePath, header) {
130
+ this.ws = createWriteStream(filePath, 'utf-8');
131
+ // Raise listener cap for large repos with many flushes
132
+ this.ws.setMaxListeners(50);
133
+ this.buffer.push(header);
134
+ }
135
+ addRow(row) {
136
+ this.buffer.push(row);
137
+ this.rows++;
138
+ if (this.buffer.length >= FLUSH_EVERY) {
139
+ return this.flush();
140
+ }
141
+ return Promise.resolve();
142
+ }
143
+ flush() {
144
+ if (this.buffer.length === 0)
145
+ return Promise.resolve();
146
+ const chunk = this.buffer.join('\n') + '\n';
147
+ this.buffer.length = 0;
148
+ return new Promise((resolve, reject) => {
149
+ this.ws.once('error', reject);
150
+ const ok = this.ws.write(chunk);
151
+ if (ok) {
152
+ this.ws.removeListener('error', reject);
153
+ resolve();
154
+ }
155
+ else {
156
+ this.ws.once('drain', () => {
157
+ this.ws.removeListener('error', reject);
158
+ resolve();
159
+ });
160
+ }
161
+ });
162
+ }
163
+ async finish() {
164
+ await this.flush();
165
+ return new Promise((resolve, reject) => {
166
+ this.ws.end(() => resolve());
167
+ this.ws.on('error', reject);
168
+ });
169
+ }
170
+ }
171
+ /**
172
+ * Stream all CSV data directly to disk files
173
+ *
174
+ * Iterates graph nodes exactly once — routes each node to the right writer
175
+ */
176
+ export const streamAllCSVsToDisk = async (graph, repoPath, csvDir) => {
177
+ // Remove stale CSVs from previous runs, then recreate
178
+ try {
179
+ await fs.rm(csvDir, { recursive: true, force: true });
180
+ }
181
+ catch { }
182
+ await fs.mkdir(csvDir, { recursive: true });
183
+ // Raise listener limit for ~30 concurrent write-streams (restored at end)
184
+ const prevMax = process.getMaxListeners();
185
+ process.setMaxListeners(prevMax + 40);
186
+ const contentCache = new FileContentCache(repoPath);
187
+ // Create writers for every node type
188
+ const fileWriter = new BufferedCSVWriter(path.join(csvDir, 'file.csv'), 'id,name,filePath,content');
189
+ const folderWriter = new BufferedCSVWriter(path.join(csvDir, 'folder.csv'), 'id,name,filePath');
190
+ const codeElementHeader = 'id,name,filePath,startLine,endLine,isExported,content,description';
191
+ const functionWriter = new BufferedCSVWriter(path.join(csvDir, 'function.csv'), codeElementHeader);
192
+ const classWriter = new BufferedCSVWriter(path.join(csvDir, 'class.csv'), codeElementHeader);
193
+ const interfaceWriter = new BufferedCSVWriter(path.join(csvDir, 'interface.csv'), codeElementHeader);
194
+ const methodHeader = 'id,name,filePath,startLine,endLine,isExported,content,description,parameterCount,returnType';
195
+ const methodWriter = new BufferedCSVWriter(path.join(csvDir, 'method.csv'), methodHeader);
196
+ const codeElemWriter = new BufferedCSVWriter(path.join(csvDir, 'codeelement.csv'), codeElementHeader);
197
+ const communityWriter = new BufferedCSVWriter(path.join(csvDir, 'community.csv'), 'id,label,heuristicLabel,keywords,description,enrichedBy,cohesion,symbolCount');
198
+ const processWriter = new BufferedCSVWriter(path.join(csvDir, 'process.csv'), 'id,label,heuristicLabel,processType,stepCount,communities,entryPointId,terminalId');
199
+ // Multi-language node types share the same CSV shape (no isExported column)
200
+ const multiLangHeader = 'id,name,filePath,startLine,endLine,content,description';
201
+ const MULTI_LANG_TYPES = ['Struct', 'Enum', 'Macro', 'Typedef', 'Union', 'Namespace', 'Trait', 'Impl',
202
+ 'TypeAlias', 'Const', 'Static', 'Property', 'Record', 'Delegate', 'Annotation', 'Constructor', 'Template', 'Module'];
203
+ const multiLangWriters = new Map();
204
+ for (const t of MULTI_LANG_TYPES) {
205
+ multiLangWriters.set(t, new BufferedCSVWriter(path.join(csvDir, `${t.toLowerCase()}.csv`), multiLangHeader));
206
+ }
207
+ const codeWriterMap = {
208
+ 'Function': functionWriter,
209
+ 'Class': classWriter,
210
+ 'Interface': interfaceWriter,
211
+ 'CodeElement': codeElemWriter,
212
+ };
213
+ const seenFileIds = new Set();
214
+ // Single pass over all nodes
215
+ for (const node of graph.iterNodes()) {
216
+ switch (node.label) {
217
+ case 'File': {
218
+ if (seenFileIds.has(node.id))
219
+ break;
220
+ seenFileIds.add(node.id);
221
+ const content = await extractContent(node, contentCache);
222
+ await fileWriter.addRow([
223
+ escapeCSVField(node.id),
224
+ escapeCSVField(node.properties.name || ''),
225
+ escapeCSVField(node.properties.filePath || ''),
226
+ escapeCSVField(content),
227
+ ].join(','));
228
+ break;
229
+ }
230
+ case 'Folder':
231
+ await folderWriter.addRow([
232
+ escapeCSVField(node.id),
233
+ escapeCSVField(node.properties.name || ''),
234
+ escapeCSVField(node.properties.filePath || ''),
235
+ ].join(','));
236
+ break;
237
+ case 'Community': {
238
+ const keywords = node.properties.keywords || [];
239
+ const keywordsStr = `[${keywords.map((k) => `'${k.replace(/\\/g, '\\\\').replace(/'/g, "''").replace(/,/g, '\\,')}'`).join(',')}]`;
240
+ await communityWriter.addRow([
241
+ escapeCSVField(node.id),
242
+ escapeCSVField(node.properties.name || ''),
243
+ escapeCSVField(node.properties.heuristicLabel || ''),
244
+ keywordsStr,
245
+ escapeCSVField(node.properties.description || ''),
246
+ escapeCSVField(node.properties.enrichedBy || 'heuristic'),
247
+ escapeCSVNumber(node.properties.cohesion, 0),
248
+ escapeCSVNumber(node.properties.symbolCount, 0),
249
+ ].join(','));
250
+ break;
251
+ }
252
+ case 'Process': {
253
+ const communities = node.properties.communities || [];
254
+ const communitiesStr = `[${communities.map((c) => `'${c.replace(/'/g, "''")}'`).join(',')}]`;
255
+ await processWriter.addRow([
256
+ escapeCSVField(node.id),
257
+ escapeCSVField(node.properties.name || ''),
258
+ escapeCSVField(node.properties.heuristicLabel || ''),
259
+ escapeCSVField(node.properties.processType || ''),
260
+ escapeCSVNumber(node.properties.stepCount, 0),
261
+ escapeCSVField(communitiesStr),
262
+ escapeCSVField(node.properties.entryPointId || ''),
263
+ escapeCSVField(node.properties.terminalId || ''),
264
+ ].join(','));
265
+ break;
266
+ }
267
+ case 'Method': {
268
+ const content = await extractContent(node, contentCache);
269
+ await methodWriter.addRow([
270
+ escapeCSVField(node.id),
271
+ escapeCSVField(node.properties.name || ''),
272
+ escapeCSVField(node.properties.filePath || ''),
273
+ escapeCSVNumber(node.properties.startLine, -1),
274
+ escapeCSVNumber(node.properties.endLine, -1),
275
+ node.properties.isExported ? 'true' : 'false',
276
+ escapeCSVField(content),
277
+ escapeCSVField(node.properties.description || ''),
278
+ escapeCSVNumber(node.properties.parameterCount, 0),
279
+ escapeCSVField(node.properties.returnType || ''),
280
+ ].join(','));
281
+ break;
282
+ }
283
+ default: {
284
+ // Code element nodes
285
+ const writer = codeWriterMap[node.label];
286
+ if (writer) {
287
+ const content = await extractContent(node, contentCache);
288
+ await writer.addRow([
289
+ escapeCSVField(node.id),
290
+ escapeCSVField(node.properties.name || ''),
291
+ escapeCSVField(node.properties.filePath || ''),
292
+ escapeCSVNumber(node.properties.startLine, -1),
293
+ escapeCSVNumber(node.properties.endLine, -1),
294
+ node.properties.isExported ? 'true' : 'false',
295
+ escapeCSVField(content),
296
+ escapeCSVField(node.properties.description || ''),
297
+ ].join(','));
298
+ }
299
+ else {
300
+ // Multi-language node types (Struct, Impl, Trait, Macro, etc)
301
+ const mlWriter = multiLangWriters.get(node.label);
302
+ if (mlWriter) {
303
+ const content = await extractContent(node, contentCache);
304
+ await mlWriter.addRow([
305
+ escapeCSVField(node.id),
306
+ escapeCSVField(node.properties.name || ''),
307
+ escapeCSVField(node.properties.filePath || ''),
308
+ escapeCSVNumber(node.properties.startLine, -1),
309
+ escapeCSVNumber(node.properties.endLine, -1),
310
+ escapeCSVField(content),
311
+ escapeCSVField(node.properties.description || ''),
312
+ ].join(','));
313
+ }
314
+ }
315
+ break;
316
+ }
317
+ }
318
+ }
319
+ // Flush and close all node writers
320
+ const allWriters = [fileWriter, folderWriter, functionWriter, classWriter, interfaceWriter, methodWriter, codeElemWriter, communityWriter, processWriter, ...multiLangWriters.values()];
321
+ await Promise.all(allWriters.map(w => w.finish()));
322
+ // Stream relationship CSV
323
+ const relCsvPath = path.join(csvDir, 'relations.csv');
324
+ const relWriter = new BufferedCSVWriter(relCsvPath, 'from,to,type,confidence,reason,step,callLine');
325
+ for (const rel of graph.iterRelationships()) {
326
+ await relWriter.addRow([
327
+ escapeCSVField(rel.sourceId),
328
+ escapeCSVField(rel.targetId),
329
+ escapeCSVField(rel.type),
330
+ escapeCSVNumber(rel.confidence, 1.0),
331
+ escapeCSVField(rel.reason),
332
+ escapeCSVNumber(rel.step, 0),
333
+ escapeCSVNumber(rel.callLine, 0),
334
+ ].join(','));
335
+ }
336
+ await relWriter.finish();
337
+ // Build result map (only tables with rows)
338
+ const nodeFiles = new Map();
339
+ const tableMap = [
340
+ ['File', fileWriter], ['Folder', folderWriter],
341
+ ['Function', functionWriter], ['Class', classWriter],
342
+ ['Interface', interfaceWriter], ['Method', methodWriter],
343
+ ['CodeElement', codeElemWriter],
344
+ ['Community', communityWriter], ['Process', processWriter],
345
+ ...Array.from(multiLangWriters.entries()).map(([name, w]) => [name, w]),
346
+ ];
347
+ for (const [name, writer] of tableMap) {
348
+ if (writer.rows > 0) {
349
+ nodeFiles.set(name, { csvPath: path.join(csvDir, `${name.toLowerCase()}.csv`), rows: writer.rows });
350
+ }
351
+ }
352
+ // Restore listener limit
353
+ process.setMaxListeners(prevMax);
354
+ return { nodeFiles, relCsvPath, relRows: relWriter.rows };
355
+ };
@@ -0,0 +1,96 @@
1
+ /**
2
+ * @file lbug-adapter.ts
3
+ * @description Core LadybugDB adapter — manages singleton DB connection, schema
4
+ * creation, bulk CSV import, FTS indexing, and Cypher query execution
5
+ */
6
+ import lbug from '@ladybugdb/core';
7
+ import { KnowledgeGraph } from '../graph/types.js';
8
+ export declare const initLbug: (dbPath: string) => Promise<{
9
+ db: lbug.Database;
10
+ conn: lbug.Connection;
11
+ }>;
12
+ /** Execute multiple queries against one repo DB atomically (holds session lock) */
13
+ export declare const withLbugDb: <T>(dbPath: string, operation: () => Promise<T>) => Promise<T>;
14
+ export type LbugProgressCallback = (message: string) => void;
15
+ export declare const loadGraphToLbug: (graph: KnowledgeGraph, repoPath: string, storagePath: string, onProgress?: LbugProgressCallback) => Promise<{
16
+ success: boolean;
17
+ insertedRels: number;
18
+ skippedRels: number;
19
+ warnings: string[];
20
+ }>;
21
+ /**
22
+ * Insert a single node to LadybugDB
23
+ * @param label - Node type (File, Function, Class, etc)
24
+ * @param properties - Node properties
25
+ * @param dbPath - Path to LadybugDB database (optional if already initialized)
26
+ */
27
+ export declare const insertNodeToLbug: (label: string, properties: Record<string, any>, dbPath?: string) => Promise<boolean>;
28
+ /**
29
+ * Batch insert multiple nodes using a single connection
30
+ * @param nodes - Array of {label, properties} to insert
31
+ * @param dbPath - Path to LadybugDB database
32
+ */
33
+ export declare const batchInsertNodesToLbug: (nodes: Array<{
34
+ label: string;
35
+ properties: Record<string, any>;
36
+ }>, dbPath: string) => Promise<{
37
+ inserted: number;
38
+ failed: number;
39
+ }>;
40
+ export declare const executeQuery: (cypher: string) => Promise<any[]>;
41
+ export declare const executeWithReusedStatement: (cypher: string, paramsList: Array<Record<string, any>>) => Promise<void>;
42
+ export declare const getLbugStats: () => Promise<{
43
+ nodes: number;
44
+ edges: number;
45
+ }>;
46
+ /**
47
+ * Load cached embeddings before a rebuild
48
+ *
49
+ * Returns all vectors so they can be re-inserted after the graph reloads,
50
+ * avoiding expensive re-embedding of unchanged nodes
51
+ */
52
+ export declare const loadCachedEmbeddings: () => Promise<{
53
+ embeddingNodeIds: Set<string>;
54
+ embeddings: Array<{
55
+ nodeId: string;
56
+ embedding: number[];
57
+ }>;
58
+ }>;
59
+ export declare const closeLbug: () => Promise<void>;
60
+ export declare const isLbugReady: () => boolean;
61
+ /**
62
+ * Delete all nodes (and relationships) for a specific file
63
+ * @param filePath - File path to delete nodes for
64
+ * @param dbPath - Optional path for per-query connection
65
+ */
66
+ export declare const deleteNodesForFile: (filePath: string, dbPath?: string) => Promise<{
67
+ deletedNodes: number;
68
+ }>;
69
+ export declare const getEmbeddingTableName: () => string;
70
+ /** Load the FTS extension (idempotent — tracks loaded state) */
71
+ export declare const loadFTSExtension: () => Promise<void>;
72
+ /**
73
+ * Create a full-text search index on a table
74
+ * @param tableName - Node table name (e.g. 'File', 'Function')
75
+ * @param indexName - FTS index name
76
+ * @param properties - Properties to index (e.g. ['name', 'content'])
77
+ * @param stemmer - Stemming algorithm (default: 'porter')
78
+ */
79
+ export declare const createFTSIndex: (tableName: string, indexName: string, properties: string[], stemmer?: string) => Promise<void>;
80
+ /**
81
+ * Query a full-text search index
82
+ * @param tableName - Node table name
83
+ * @param indexName - FTS index name
84
+ * @param query - Search query string
85
+ * @param limit - Max results
86
+ * @param conjunctive - If true, all terms must match (AND); false = any term (OR)
87
+ */
88
+ export declare const queryFTS: (tableName: string, indexName: string, query: string, limit?: number, conjunctive?: boolean) => Promise<Array<{
89
+ nodeId: string;
90
+ name: string;
91
+ filePath: string;
92
+ score: number;
93
+ [key: string]: any;
94
+ }>>;
95
+ /** Drop an FTS index */
96
+ export declare const dropFTSIndex: (tableName: string, indexName: string) => Promise<void>;