context-pilot-engine 0.2.0 → 0.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 (81) hide show
  1. package/LICENSE +21 -0
  2. package/dist/engine.d.ts +11 -64
  3. package/dist/engine.d.ts.map +1 -1
  4. package/dist/engine.js +110 -204
  5. package/dist/engine.js.map +1 -0
  6. package/dist/graph/graph.js.map +1 -0
  7. package/dist/history/backtest.d.ts +127 -0
  8. package/dist/history/backtest.d.ts.map +1 -0
  9. package/dist/history/backtest.js +290 -0
  10. package/dist/history/backtest.js.map +1 -0
  11. package/dist/history/cochange.d.ts +91 -0
  12. package/dist/history/cochange.d.ts.map +1 -0
  13. package/dist/history/cochange.js +149 -0
  14. package/dist/history/cochange.js.map +1 -0
  15. package/dist/history/diff.d.ts +21 -0
  16. package/dist/history/diff.d.ts.map +1 -0
  17. package/dist/history/diff.js +57 -0
  18. package/dist/history/diff.js.map +1 -0
  19. package/dist/history/git.d.ts +34 -0
  20. package/dist/history/git.d.ts.map +1 -0
  21. package/dist/history/git.js +92 -0
  22. package/dist/history/git.js.map +1 -0
  23. package/dist/history/miner.d.ts +9 -0
  24. package/dist/history/miner.d.ts.map +1 -0
  25. package/dist/history/miner.js +70 -0
  26. package/dist/history/miner.js.map +1 -0
  27. package/dist/impact/impact.d.ts +55 -0
  28. package/dist/impact/impact.d.ts.map +1 -0
  29. package/dist/impact/impact.js +139 -0
  30. package/dist/impact/impact.js.map +1 -0
  31. package/dist/index.d.ts +11 -2
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +7 -1
  34. package/dist/index.js.map +1 -0
  35. package/dist/indexer/chunker.d.ts +9 -6
  36. package/dist/indexer/chunker.d.ts.map +1 -1
  37. package/dist/indexer/chunker.js +46 -11
  38. package/dist/indexer/chunker.js.map +1 -0
  39. package/dist/indexer/imports.d.ts +24 -0
  40. package/dist/indexer/imports.d.ts.map +1 -0
  41. package/dist/indexer/imports.js +138 -0
  42. package/dist/indexer/imports.js.map +1 -0
  43. package/dist/indexer/indexer.d.ts +15 -0
  44. package/dist/indexer/indexer.d.ts.map +1 -1
  45. package/dist/indexer/indexer.js +55 -59
  46. package/dist/indexer/indexer.js.map +1 -0
  47. package/dist/indexer/languages.d.ts +2 -2
  48. package/dist/indexer/languages.d.ts.map +1 -1
  49. package/dist/indexer/languages.js +10 -0
  50. package/dist/indexer/languages.js.map +1 -0
  51. package/dist/storage/schema.js +87 -87
  52. package/dist/storage/schema.js.map +1 -0
  53. package/dist/storage/sqlite.d.ts +34 -27
  54. package/dist/storage/sqlite.d.ts.map +1 -1
  55. package/dist/storage/sqlite.js +126 -153
  56. package/dist/storage/sqlite.js.map +1 -0
  57. package/dist/types.d.ts +86 -97
  58. package/dist/types.d.ts.map +1 -1
  59. package/dist/types.js.map +1 -0
  60. package/package.json +24 -10
  61. package/dist/embedder/embedder.d.ts +0 -4
  62. package/dist/embedder/embedder.d.ts.map +0 -1
  63. package/dist/embedder/embedder.js +0 -37
  64. package/dist/engine.test.d.ts +0 -2
  65. package/dist/engine.test.d.ts.map +0 -1
  66. package/dist/engine.test.js +0 -9
  67. package/dist/search/search.d.ts +0 -12
  68. package/dist/search/search.d.ts.map +0 -1
  69. package/dist/search/search.js +0 -38
  70. package/src/embedder/embedder.ts +0 -46
  71. package/src/engine.ts +0 -425
  72. package/src/graph/graph.ts +0 -136
  73. package/src/index.ts +0 -15
  74. package/src/indexer/chunker.ts +0 -115
  75. package/src/indexer/indexer.ts +0 -297
  76. package/src/indexer/languages.ts +0 -55
  77. package/src/search/search.ts +0 -48
  78. package/src/storage/schema.ts +0 -92
  79. package/src/storage/sqlite.ts +0 -353
  80. package/src/types.ts +0 -137
  81. package/tsconfig.json +0 -19
@@ -1,136 +0,0 @@
1
- export interface NodeAttrs {
2
- chunkType: string;
3
- name: string | null;
4
- path: string;
5
- }
6
-
7
- export interface EdgeAttrs {
8
- edgeType: string;
9
- weight: number;
10
- }
11
-
12
- export class DiGraph {
13
- private nodes = new Map<string, NodeAttrs>();
14
- private outEdges = new Map<string, Map<string, EdgeAttrs>>();
15
- private inEdges = new Map<string, Set<string>>();
16
-
17
- addNode(id: string, attrs: NodeAttrs): void {
18
- this.nodes.set(id, attrs);
19
- if (!this.outEdges.has(id)) this.outEdges.set(id, new Map());
20
- if (!this.inEdges.has(id)) this.inEdges.set(id, new Set());
21
- }
22
-
23
- addEdge(from: string, to: string, attrs: EdgeAttrs): void {
24
- if (!this.outEdges.has(from)) this.outEdges.set(from, new Map());
25
- if (!this.inEdges.has(to)) this.inEdges.set(to, new Set());
26
- this.outEdges.get(from)!.set(to, attrs);
27
- this.inEdges.get(to)!.add(from);
28
- }
29
-
30
- has(id: string): boolean {
31
- return this.nodes.has(id);
32
- }
33
-
34
- getNode(id: string): NodeAttrs | undefined {
35
- return this.nodes.get(id);
36
- }
37
-
38
- successors(id: string): string[] {
39
- return [...(this.outEdges.get(id)?.keys() ?? [])];
40
- }
41
-
42
- predecessors(id: string): string[] {
43
- return [...(this.inEdges.get(id) ?? [])];
44
- }
45
-
46
- getEdge(from: string, to: string): EdgeAttrs | undefined {
47
- return this.outEdges.get(from)?.get(to);
48
- }
49
-
50
- allNodes(): Array<[string, NodeAttrs]> {
51
- return [...this.nodes.entries()];
52
- }
53
-
54
- allEdges(): Array<{ from: string; to: string; attrs: EdgeAttrs }> {
55
- const result: Array<{ from: string; to: string; attrs: EdgeAttrs }> = [];
56
- for (const [from, tos] of this.outEdges) {
57
- for (const [to, attrs] of tos) {
58
- result.push({ from, to, attrs });
59
- }
60
- }
61
- return result;
62
- }
63
-
64
- nodeCount(): number {
65
- return this.nodes.size;
66
- }
67
-
68
- /**
69
- * BFS subgraph starting from `rootId`, up to `depth` hops.
70
- * direction: "outgoing" | "incoming" | "both"
71
- */
72
- subgraph(
73
- rootId: string,
74
- depth: number,
75
- direction: "outgoing" | "incoming" | "both"
76
- ): { nodeIds: Set<string>; edges: Array<{ from: string; to: string; attrs: EdgeAttrs }> } {
77
- const visited = new Set<string>([rootId]);
78
- const queue: Array<{ id: string; d: number }> = [{ id: rootId, d: 0 }];
79
- const edges: Array<{ from: string; to: string; attrs: EdgeAttrs }> = [];
80
-
81
- while (queue.length > 0) {
82
- const { id, d } = queue.shift()!;
83
- if (d >= depth) continue;
84
-
85
- const neighbors: string[] = [];
86
- if (direction === "outgoing" || direction === "both") neighbors.push(...this.successors(id));
87
- if (direction === "incoming" || direction === "both") neighbors.push(...this.predecessors(id));
88
-
89
- for (const neighbor of neighbors) {
90
- if (!visited.has(neighbor)) {
91
- visited.add(neighbor);
92
- queue.push({ id: neighbor, d: d + 1 });
93
- }
94
- // collect edges in original direction
95
- if (this.outEdges.get(id)?.has(neighbor)) {
96
- edges.push({ from: id, to: neighbor, attrs: this.getEdge(id, neighbor)! });
97
- } else if (this.outEdges.get(neighbor)?.has(id)) {
98
- edges.push({ from: neighbor, to: id, attrs: this.getEdge(neighbor, id)! });
99
- }
100
- }
101
- }
102
-
103
- return { nodeIds: visited, edges };
104
- }
105
-
106
- /**
107
- * Compute normalized shortest-path distances from `sourceId` to each candidate.
108
- * Uses BFS on undirected version. Returns 0–1 where 0 = same node, 1 = unreachable.
109
- */
110
- shortestPathDistances(sourceId: string, targetIds: string[]): Record<string, number> {
111
- const dist = new Map<string, number>();
112
- const queue: Array<{ id: string; d: number }> = [{ id: sourceId, d: 0 }];
113
- dist.set(sourceId, 0);
114
-
115
- while (queue.length > 0) {
116
- const { id, d } = queue.shift()!;
117
- const neighbors = [...this.successors(id), ...this.predecessors(id)];
118
- for (const n of neighbors) {
119
- if (!dist.has(n)) {
120
- dist.set(n, d + 1);
121
- queue.push({ id: n, d: d + 1 });
122
- }
123
- }
124
- }
125
-
126
- const maxDist = Math.max(1, ...dist.values());
127
- const result: Record<string, number> = {};
128
-
129
- for (const targetId of targetIds) {
130
- const d = dist.get(targetId);
131
- result[targetId] = d === undefined ? 1.0 : Math.min(1.0, d / maxDist);
132
- }
133
-
134
- return result;
135
- }
136
- }
package/src/index.ts DELETED
@@ -1,15 +0,0 @@
1
- export { ContextEngine } from "./engine.js";
2
- export { openDatabase } from "./storage/sqlite.js";
3
- export type {
4
- IContextEngine,
5
- IndexResult,
6
- SearchResult,
7
- StatusResult,
8
- SubgraphResult,
9
- Chunk,
10
- EmbeddingCandidate,
11
- GraphNode,
12
- GraphEdge,
13
- MemorySearchResult,
14
- MemoryRecord,
15
- } from "./types.js";
@@ -1,115 +0,0 @@
1
- import Parser from "web-tree-sitter";
2
- import { randomUUID } from "crypto";
3
- import type { Chunk } from "../types.js";
4
- import { CHUNK_NODE_TYPES } from "./languages.js";
5
-
6
- const MAX_CHUNK_LINES = 100;
7
- const MIN_CHUNK_LINES = 3;
8
-
9
- function extractName(node: Parser.SyntaxNode): string | null {
10
- const nameNode = node.childForFieldName("name");
11
- return nameNode?.text ?? null;
12
- }
13
-
14
- function estimateTokens(text: string): number {
15
- return Math.ceil(text.length / 4);
16
- }
17
-
18
- function visitNode(
19
- node: Parser.SyntaxNode,
20
- source: string,
21
- fileId: string,
22
- chunkTypes: string[],
23
- results: Chunk[]
24
- ): void {
25
- if (chunkTypes.includes(node.type)) {
26
- const startLine = node.startPosition.row + 1;
27
- const endLine = node.endPosition.row + 1;
28
- const lineCount = endLine - startLine + 1;
29
-
30
- if (lineCount >= MIN_CHUNK_LINES) {
31
- const content = source.slice(node.startIndex, node.endIndex);
32
- const chunkType =
33
- node.type.includes("class") ? "class"
34
- : node.type === "arrow_function" || node.type === "function_expression" ? "function"
35
- : "function";
36
-
37
- results.push({
38
- id: randomUUID(),
39
- fileId,
40
- chunkType,
41
- name: extractName(node),
42
- content: content.slice(0, MAX_CHUNK_LINES * 120), // cap at ~12KB
43
- startLine,
44
- endLine,
45
- tokenCount: estimateTokens(content),
46
- });
47
- }
48
- }
49
-
50
- for (let i = 0; i < node.childCount; i++) {
51
- const child = node.child(i);
52
- if (child) visitNode(child, source, fileId, chunkTypes, results);
53
- }
54
- }
55
-
56
- export function extractChunks(
57
- source: string,
58
- fileId: string,
59
- language: string,
60
- tree: Parser.Tree
61
- ): Chunk[] {
62
- const chunkTypes = CHUNK_NODE_TYPES[language] ?? [];
63
- const results: Chunk[] = [];
64
- visitNode(tree.rootNode, source, fileId, chunkTypes, results);
65
-
66
- // If no chunks found (e.g. a config file), create a module-level chunk
67
- if (results.length === 0) {
68
- const lines = source.split("\n").length;
69
- if (lines >= MIN_CHUNK_LINES) {
70
- results.push({
71
- id: randomUUID(),
72
- fileId,
73
- chunkType: "module",
74
- name: null,
75
- content: source.slice(0, MAX_CHUNK_LINES * 120),
76
- startLine: 1,
77
- endLine: lines,
78
- tokenCount: estimateTokens(source),
79
- });
80
- }
81
- }
82
-
83
- return results;
84
- }
85
-
86
- /**
87
- * Extract import/dependency edges from source for graph building.
88
- * Returns pairs of [importerChunkName, importedModulePath].
89
- */
90
- export function extractImports(
91
- source: string,
92
- language: string,
93
- tree: Parser.Tree
94
- ): Array<{ from: string; to: string }> {
95
- const imports: Array<{ from: string; to: string }> = [];
96
-
97
- function visit(node: Parser.SyntaxNode): void {
98
- if (language === "python" && node.type === "import_from_statement") {
99
- const moduleNode = node.childForFieldName("module_name");
100
- if (moduleNode) imports.push({ from: "module", to: moduleNode.text });
101
- }
102
- if ((language === "javascript" || language === "typescript" || language === "tsx") &&
103
- node.type === "import_declaration") {
104
- const sourceNode = node.childForFieldName("source");
105
- if (sourceNode) imports.push({ from: "module", to: sourceNode.text.replace(/['"]/g, "") });
106
- }
107
- for (let i = 0; i < node.childCount; i++) {
108
- const child = node.child(i);
109
- if (child) visit(child);
110
- }
111
- }
112
-
113
- visit(tree.rootNode);
114
- return imports;
115
- }
@@ -1,297 +0,0 @@
1
- import { readdirSync, readFileSync, statSync } from "fs";
2
- import { createHash } from "crypto";
3
- import { join, relative, extname } from "path";
4
- import Parser from "web-tree-sitter";
5
- import type { DatabaseSync } from "node:sqlite";
6
- import { randomUUID } from "crypto";
7
- import { v5 as uuidv5 } from "uuid";
8
- import type { Chunk } from "../types.js";
9
- import { loadLanguage, getLanguageForFile, initTreeSitter } from "./languages.js";
10
- import { extractChunks, extractImports } from "./chunker.js";
11
- import {
12
- upsertFile,
13
- getFileHash,
14
- deleteFileChunks,
15
- insertChunks,
16
- getProjectFiles,
17
- upsertProject,
18
- markProjectIndexed,
19
- getFileRepresentativeChunk,
20
- deleteProjectGraphEdges,
21
- insertGraphEdges,
22
- } from "../storage/sqlite.js";
23
-
24
- const UUID_NAMESPACE = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; // UUID v5 URL namespace
25
-
26
- const IGNORE_DIRS = new Set([
27
- "node_modules", ".git", "__pycache__", "dist", "build", ".context-pilot",
28
- ".next", "coverage", ".venv", "venv", ".env",
29
- ]);
30
-
31
- const SUPPORTED_EXTS = new Set([".ts", ".tsx", ".js", ".jsx", ".py"]);
32
-
33
- export function projectId(rootPath: string): string {
34
- return uuidv5(rootPath, UUID_NAMESPACE);
35
- }
36
-
37
- function hashFile(content: string): string {
38
- return createHash("sha256").update(content).digest("hex").slice(0, 16);
39
- }
40
-
41
- function collectFiles(dir: string): string[] {
42
- const files: string[] = [];
43
-
44
- function walk(current: string): void {
45
- let entries: string[];
46
- try {
47
- entries = readdirSync(current);
48
- } catch {
49
- return;
50
- }
51
- for (const entry of entries) {
52
- if (IGNORE_DIRS.has(entry)) continue;
53
- const full = join(current, entry);
54
- let stat;
55
- try { stat = statSync(full); } catch { continue; }
56
- if (stat.isDirectory()) {
57
- walk(full);
58
- } else if (SUPPORTED_EXTS.has(extname(full).toLowerCase())) {
59
- files.push(full);
60
- }
61
- }
62
- }
63
-
64
- walk(dir);
65
- return files;
66
- }
67
-
68
- /**
69
- * Resolve a relative import path to candidate relative file paths within the project.
70
- * Returns multiple candidates (with different extensions) for the caller to match.
71
- */
72
- function resolveImportCandidates(importPath: string, fromRelDir: string): string[] {
73
- if (!importPath.startsWith(".")) return []; // external module
74
-
75
- const base = join(fromRelDir, importPath).replace(/\\/g, "/");
76
- return [
77
- base + ".ts",
78
- base + ".tsx",
79
- base + ".js",
80
- base + ".jsx",
81
- base + "/index.ts",
82
- base + "/index.tsx",
83
- base + "/index.js",
84
- base,
85
- ];
86
- }
87
-
88
- /**
89
- * Second pass: extract import edges and store them in graph_edges.
90
- * Replaces all existing graph edges for the project.
91
- */
92
- async function buildGraphEdges(
93
- db: DatabaseSync,
94
- pid: string,
95
- projectPath: string,
96
- allFiles: string[]
97
- ): Promise<void> {
98
- const projectFiles = getProjectFiles(db, pid);
99
- const pathToFileId = new Map(projectFiles.map((f) => [f.path, f.id]));
100
-
101
- deleteProjectGraphEdges(db, pid);
102
-
103
- const edges: Array<{ from: string; to: string; edgeType: "calls" | "extends" | "imports"; weight: number }> = [];
104
-
105
- for (const absPath of allFiles) {
106
- const relPath = relative(projectPath, absPath).replace(/\\/g, "/");
107
- const fileId = pathToFileId.get(relPath);
108
- if (!fileId) continue;
109
-
110
- const fromChunkId = getFileRepresentativeChunk(db, fileId);
111
- if (!fromChunkId) continue;
112
-
113
- const lang = getLanguageForFile(absPath);
114
- if (!lang) continue;
115
-
116
- let source: string;
117
- try { source = readFileSync(absPath, "utf8"); } catch { continue; }
118
-
119
- try {
120
- const language = await loadLanguage(lang);
121
- const parser = new Parser();
122
- parser.setLanguage(language);
123
- const tree = parser.parse(source);
124
- const imports = extractImports(source, lang, tree);
125
- const fromRelDir = relPath.includes("/") ? relPath.slice(0, relPath.lastIndexOf("/")) : ".";
126
-
127
- for (const imp of imports) {
128
- const candidates = resolveImportCandidates(imp.to, fromRelDir);
129
- for (const candidate of candidates) {
130
- const targetFileId = pathToFileId.get(candidate);
131
- if (!targetFileId) continue;
132
- const toChunkId = getFileRepresentativeChunk(db, targetFileId);
133
- if (!toChunkId) continue;
134
- if (fromChunkId !== toChunkId) {
135
- edges.push({ from: fromChunkId, to: toChunkId, edgeType: "imports", weight: 1.0 });
136
- }
137
- break; // found a match, stop trying candidates
138
- }
139
- }
140
- } catch {
141
- // ignore parse errors in graph building
142
- }
143
- }
144
-
145
- if (edges.length > 0) {
146
- insertGraphEdges(db, pid, edges);
147
- }
148
- }
149
-
150
- export async function indexProject(
151
- db: DatabaseSync,
152
- projectPath: string,
153
- force: boolean
154
- ): Promise<{ filesIndexed: number; filesSkipped: number; totalFiles: number }> {
155
- const pid = projectId(projectPath);
156
- upsertProject(db, pid, projectPath);
157
-
158
- await initTreeSitter();
159
-
160
- const allFiles = collectFiles(projectPath);
161
- let filesIndexed = 0;
162
- let filesSkipped = 0;
163
-
164
- for (const absPath of allFiles) {
165
- const relPath = relative(projectPath, absPath).replace(/\\/g, "/");
166
- let source: string;
167
- try {
168
- source = readFileSync(absPath, "utf8");
169
- } catch {
170
- filesSkipped++;
171
- continue;
172
- }
173
-
174
- const hash = hashFile(source);
175
- const existingHash = getFileHash(db, pid, relPath);
176
-
177
- if (!force && existingHash === hash) {
178
- filesSkipped++;
179
- continue;
180
- }
181
-
182
- const lang = getLanguageForFile(absPath);
183
- if (!lang) {
184
- filesSkipped++;
185
- continue;
186
- }
187
-
188
- try {
189
- const language = await loadLanguage(lang);
190
- const parser = new Parser();
191
- parser.setLanguage(language);
192
- const tree = parser.parse(source);
193
-
194
- const stat = statSync(absPath);
195
- const fileId = randomUUID();
196
-
197
- upsertFile(db, fileId, pid, relPath, lang, hash, stat.mtimeMs);
198
- deleteFileChunks(db, fileId);
199
-
200
- const chunks = extractChunks(source, fileId, lang, tree);
201
- insertChunks(db, chunks);
202
- } catch (err) {
203
- process.stderr.write(`[engine] failed to index ${relPath}: ${err}\n`);
204
- filesSkipped++;
205
- continue;
206
- }
207
-
208
- filesIndexed++;
209
- }
210
-
211
- // Build import graph after all files are indexed
212
- await buildGraphEdges(db, pid, projectPath, allFiles);
213
-
214
- markProjectIndexed(db, pid);
215
- return { filesIndexed, filesSkipped, totalFiles: allFiles.length };
216
- }
217
-
218
- /**
219
- * Re-index only specific files (used by the file watcher).
220
- * Does NOT rebuild graph edges — call indexProject for a full rebuild.
221
- */
222
- export async function indexSpecificFiles(
223
- db: DatabaseSync,
224
- projectPath: string,
225
- absPaths: string[],
226
- force: boolean
227
- ): Promise<{ filesIndexed: number; filesSkipped: number; totalFiles: number }> {
228
- const pid = projectId(projectPath);
229
- upsertProject(db, pid, projectPath);
230
-
231
- await initTreeSitter();
232
-
233
- let filesIndexed = 0;
234
- let filesSkipped = 0;
235
-
236
- for (const absPath of absPaths) {
237
- if (!SUPPORTED_EXTS.has(extname(absPath).toLowerCase())) {
238
- filesSkipped++;
239
- continue;
240
- }
241
-
242
- const relPath = relative(projectPath, absPath).replace(/\\/g, "/");
243
- let source: string;
244
- try {
245
- source = readFileSync(absPath, "utf8");
246
- } catch {
247
- // File deleted — remove from index
248
- const existing = db
249
- .prepare(`SELECT id FROM files WHERE project_id = ? AND path = ?`)
250
- .get(pid, relPath) as { id: string } | undefined;
251
- if (existing) {
252
- deleteFileChunks(db, existing.id);
253
- db.prepare(`DELETE FROM files WHERE id = ?`).run(existing.id);
254
- }
255
- filesSkipped++;
256
- continue;
257
- }
258
-
259
- const hash = hashFile(source);
260
- const existingHash = getFileHash(db, pid, relPath);
261
-
262
- if (!force && existingHash === hash) {
263
- filesSkipped++;
264
- continue;
265
- }
266
-
267
- const lang = getLanguageForFile(absPath);
268
- if (!lang) {
269
- filesSkipped++;
270
- continue;
271
- }
272
-
273
- try {
274
- const language = await loadLanguage(lang);
275
- const parser = new Parser();
276
- parser.setLanguage(language);
277
- const tree = parser.parse(source);
278
-
279
- const stat = statSync(absPath);
280
- const fileId = randomUUID();
281
-
282
- upsertFile(db, fileId, pid, relPath, lang, hash, stat.mtimeMs);
283
- deleteFileChunks(db, fileId);
284
-
285
- const chunks = extractChunks(source, fileId, lang, tree);
286
- insertChunks(db, chunks);
287
- } catch (err) {
288
- process.stderr.write(`[engine] failed to index ${relPath}: ${err}\n`);
289
- filesSkipped++;
290
- continue;
291
- }
292
-
293
- filesIndexed++;
294
- }
295
-
296
- return { filesIndexed, filesSkipped, totalFiles: absPaths.length };
297
- }
@@ -1,55 +0,0 @@
1
- import Parser from "web-tree-sitter";
2
- import { createRequire } from "module";
3
- import { fileURLToPath } from "url";
4
- import { dirname, join } from "path";
5
-
6
- const require = createRequire(import.meta.url);
7
-
8
- let initialized = false;
9
- const languageCache = new Map<string, Parser.Language>();
10
-
11
- export async function initTreeSitter(): Promise<void> {
12
- if (initialized) return;
13
- await Parser.init();
14
- initialized = true;
15
- }
16
-
17
- export async function loadLanguage(lang: "python" | "javascript" | "typescript" | "tsx"): Promise<Parser.Language> {
18
- if (languageCache.has(lang)) return languageCache.get(lang)!;
19
-
20
- await initTreeSitter();
21
-
22
- const wasmMap: Record<string, string> = {
23
- python: require.resolve("tree-sitter-python/tree-sitter-python.wasm"),
24
- javascript: require.resolve("tree-sitter-javascript/tree-sitter-javascript.wasm"),
25
- typescript: require.resolve("tree-sitter-typescript/tree-sitter-typescript.wasm"),
26
- tsx: require.resolve("tree-sitter-typescript/tree-sitter-tsx.wasm"),
27
- };
28
-
29
- const wasmPath = wasmMap[lang];
30
- if (!wasmPath) throw new Error(`Unsupported language: ${lang}`);
31
-
32
- const language = await Parser.Language.load(wasmPath);
33
- languageCache.set(lang, language);
34
- return language;
35
- }
36
-
37
- export function getLanguageForFile(filePath: string): "python" | "javascript" | "typescript" | "tsx" | null {
38
- const ext = filePath.slice(filePath.lastIndexOf(".")).toLowerCase();
39
- switch (ext) {
40
- case ".py": return "python";
41
- case ".js":
42
- case ".jsx": return "javascript";
43
- case ".ts": return "typescript";
44
- case ".tsx": return "tsx";
45
- default: return null;
46
- }
47
- }
48
-
49
- // Node types to extract per language
50
- export const CHUNK_NODE_TYPES: Record<string, string[]> = {
51
- python: ["function_definition", "class_definition"],
52
- javascript: ["function_declaration", "function_expression", "arrow_function", "class_declaration", "method_definition"],
53
- typescript: ["function_declaration", "function_expression", "arrow_function", "class_declaration", "method_definition"],
54
- tsx: ["function_declaration", "function_expression", "arrow_function", "class_declaration", "method_definition"],
55
- };
@@ -1,48 +0,0 @@
1
- import type { EmbeddingCandidate, SearchResult } from "../types.js";
2
-
3
- /**
4
- * Cosine similarity between two Float32Arrays.
5
- * Using typed arrays is ~5x faster than generic number[] in V8.
6
- */
7
- export function cosineSimilarity(a: Float32Array, b: Float32Array): number {
8
- let dot = 0;
9
- let na = 0;
10
- let nb = 0;
11
- for (let i = 0; i < a.length; i++) {
12
- dot += a[i] * b[i];
13
- na += a[i] * a[i];
14
- nb += b[i] * b[i];
15
- }
16
- const denom = Math.sqrt(na) * Math.sqrt(nb);
17
- return denom === 0 ? 0 : dot / denom;
18
- }
19
-
20
- /**
21
- * Semantic search over a list of embedding candidates.
22
- * Returns top-k results sorted by cosine similarity descending.
23
- */
24
- export function semanticSearch(
25
- queryVector: Float32Array,
26
- candidates: EmbeddingCandidate[],
27
- k: number,
28
- filterType?: string
29
- ): SearchResult[] {
30
- const filtered =
31
- filterType && filterType !== "any"
32
- ? candidates.filter((c) => c.chunkType === filterType)
33
- : candidates;
34
-
35
- const scored = filtered.map((c) => ({
36
- chunk_id: c.chunkId,
37
- score: cosineSimilarity(queryVector, c.vector),
38
- content: c.content,
39
- chunk_type: c.chunkType,
40
- name: c.name,
41
- path: c.path,
42
- start_line: c.startLine,
43
- end_line: c.endLine,
44
- }));
45
-
46
- scored.sort((a, b) => b.score - a.score);
47
- return scored.slice(0, k);
48
- }