context-pilot-engine 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/embedder/embedder.d.ts +4 -0
  2. package/dist/embedder/embedder.d.ts.map +1 -0
  3. package/dist/embedder/embedder.js +37 -0
  4. package/dist/engine.d.ts +89 -0
  5. package/dist/engine.d.ts.map +1 -0
  6. package/dist/engine.js +314 -0
  7. package/dist/engine.test.d.ts +2 -0
  8. package/dist/engine.test.d.ts.map +1 -0
  9. package/dist/engine.test.js +9 -0
  10. package/dist/graph/graph.d.ts +46 -0
  11. package/dist/graph/graph.d.ts.map +1 -0
  12. package/dist/graph/graph.js +110 -0
  13. package/dist/index.d.ts +4 -0
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/index.js +3 -0
  16. package/dist/indexer/chunker.d.ts +12 -0
  17. package/dist/indexer/chunker.d.ts.map +1 -0
  18. package/dist/indexer/chunker.js +89 -0
  19. package/dist/indexer/indexer.d.ts +17 -0
  20. package/dist/indexer/indexer.d.ts.map +1 -0
  21. package/dist/indexer/indexer.js +247 -0
  22. package/dist/indexer/languages.d.ts +6 -0
  23. package/dist/indexer/languages.d.ts.map +1 -0
  24. package/dist/indexer/languages.js +47 -0
  25. package/dist/search/search.d.ts +12 -0
  26. package/dist/search/search.d.ts.map +1 -0
  27. package/dist/search/search.js +38 -0
  28. package/dist/storage/schema.d.ts +3 -0
  29. package/dist/storage/schema.d.ts.map +1 -0
  30. package/dist/storage/schema.js +91 -0
  31. package/dist/storage/sqlite.d.ts +63 -0
  32. package/dist/storage/sqlite.d.ts.map +1 -0
  33. package/dist/storage/sqlite.js +255 -0
  34. package/dist/types.d.ts +162 -0
  35. package/dist/types.d.ts.map +1 -0
  36. package/dist/types.js +2 -0
  37. package/package.json +31 -0
  38. package/src/embedder/embedder.ts +46 -0
  39. package/src/engine.ts +425 -0
  40. package/src/graph/graph.ts +136 -0
  41. package/src/index.ts +15 -0
  42. package/src/indexer/chunker.ts +115 -0
  43. package/src/indexer/indexer.ts +297 -0
  44. package/src/indexer/languages.ts +55 -0
  45. package/src/search/search.ts +48 -0
  46. package/src/storage/schema.ts +92 -0
  47. package/src/storage/sqlite.ts +353 -0
  48. package/src/types.ts +137 -0
  49. package/tsconfig.json +19 -0
@@ -0,0 +1,89 @@
1
+ import { randomUUID } from "crypto";
2
+ import { CHUNK_NODE_TYPES } from "./languages.js";
3
+ const MAX_CHUNK_LINES = 100;
4
+ const MIN_CHUNK_LINES = 3;
5
+ function extractName(node) {
6
+ const nameNode = node.childForFieldName("name");
7
+ return nameNode?.text ?? null;
8
+ }
9
+ function estimateTokens(text) {
10
+ return Math.ceil(text.length / 4);
11
+ }
12
+ function visitNode(node, source, fileId, chunkTypes, results) {
13
+ if (chunkTypes.includes(node.type)) {
14
+ const startLine = node.startPosition.row + 1;
15
+ const endLine = node.endPosition.row + 1;
16
+ const lineCount = endLine - startLine + 1;
17
+ if (lineCount >= MIN_CHUNK_LINES) {
18
+ const content = source.slice(node.startIndex, node.endIndex);
19
+ const chunkType = node.type.includes("class") ? "class"
20
+ : node.type === "arrow_function" || node.type === "function_expression" ? "function"
21
+ : "function";
22
+ results.push({
23
+ id: randomUUID(),
24
+ fileId,
25
+ chunkType,
26
+ name: extractName(node),
27
+ content: content.slice(0, MAX_CHUNK_LINES * 120), // cap at ~12KB
28
+ startLine,
29
+ endLine,
30
+ tokenCount: estimateTokens(content),
31
+ });
32
+ }
33
+ }
34
+ for (let i = 0; i < node.childCount; i++) {
35
+ const child = node.child(i);
36
+ if (child)
37
+ visitNode(child, source, fileId, chunkTypes, results);
38
+ }
39
+ }
40
+ export function extractChunks(source, fileId, language, tree) {
41
+ const chunkTypes = CHUNK_NODE_TYPES[language] ?? [];
42
+ const results = [];
43
+ visitNode(tree.rootNode, source, fileId, chunkTypes, results);
44
+ // If no chunks found (e.g. a config file), create a module-level chunk
45
+ if (results.length === 0) {
46
+ const lines = source.split("\n").length;
47
+ if (lines >= MIN_CHUNK_LINES) {
48
+ results.push({
49
+ id: randomUUID(),
50
+ fileId,
51
+ chunkType: "module",
52
+ name: null,
53
+ content: source.slice(0, MAX_CHUNK_LINES * 120),
54
+ startLine: 1,
55
+ endLine: lines,
56
+ tokenCount: estimateTokens(source),
57
+ });
58
+ }
59
+ }
60
+ return results;
61
+ }
62
+ /**
63
+ * Extract import/dependency edges from source for graph building.
64
+ * Returns pairs of [importerChunkName, importedModulePath].
65
+ */
66
+ export function extractImports(source, language, tree) {
67
+ const imports = [];
68
+ function visit(node) {
69
+ if (language === "python" && node.type === "import_from_statement") {
70
+ const moduleNode = node.childForFieldName("module_name");
71
+ if (moduleNode)
72
+ imports.push({ from: "module", to: moduleNode.text });
73
+ }
74
+ if ((language === "javascript" || language === "typescript" || language === "tsx") &&
75
+ node.type === "import_declaration") {
76
+ const sourceNode = node.childForFieldName("source");
77
+ if (sourceNode)
78
+ imports.push({ from: "module", to: sourceNode.text.replace(/['"]/g, "") });
79
+ }
80
+ for (let i = 0; i < node.childCount; i++) {
81
+ const child = node.child(i);
82
+ if (child)
83
+ visit(child);
84
+ }
85
+ }
86
+ visit(tree.rootNode);
87
+ return imports;
88
+ }
89
+ //# sourceMappingURL=chunker.js.map
@@ -0,0 +1,17 @@
1
+ import type { DatabaseSync } from "node:sqlite";
2
+ export declare function projectId(rootPath: string): string;
3
+ export declare function indexProject(db: DatabaseSync, projectPath: string, force: boolean): Promise<{
4
+ filesIndexed: number;
5
+ filesSkipped: number;
6
+ totalFiles: number;
7
+ }>;
8
+ /**
9
+ * Re-index only specific files (used by the file watcher).
10
+ * Does NOT rebuild graph edges — call indexProject for a full rebuild.
11
+ */
12
+ export declare function indexSpecificFiles(db: DatabaseSync, projectPath: string, absPaths: string[], force: boolean): Promise<{
13
+ filesIndexed: number;
14
+ filesSkipped: number;
15
+ totalFiles: number;
16
+ }>;
17
+ //# sourceMappingURL=indexer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"indexer.d.ts","sourceRoot":"","sources":["../../src/indexer/indexer.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AA4BhD,wBAAgB,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAElD;AAmHD,wBAAsB,YAAY,CAChC,EAAE,EAAE,YAAY,EAChB,WAAW,EAAE,MAAM,EACnB,KAAK,EAAE,OAAO,GACb,OAAO,CAAC;IAAE,YAAY,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAAC,CA8D7E;AAED;;;GAGG;AACH,wBAAsB,kBAAkB,CACtC,EAAE,EAAE,YAAY,EAChB,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,MAAM,EAAE,EAClB,KAAK,EAAE,OAAO,GACb,OAAO,CAAC;IAAE,YAAY,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAAC,CAsE7E"}
@@ -0,0 +1,247 @@
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 { randomUUID } from "crypto";
6
+ import { v5 as uuidv5 } from "uuid";
7
+ import { loadLanguage, getLanguageForFile, initTreeSitter } from "./languages.js";
8
+ import { extractChunks, extractImports } from "./chunker.js";
9
+ import { upsertFile, getFileHash, deleteFileChunks, insertChunks, getProjectFiles, upsertProject, markProjectIndexed, getFileRepresentativeChunk, deleteProjectGraphEdges, insertGraphEdges, } from "../storage/sqlite.js";
10
+ const UUID_NAMESPACE = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; // UUID v5 URL namespace
11
+ const IGNORE_DIRS = new Set([
12
+ "node_modules", ".git", "__pycache__", "dist", "build", ".context-pilot",
13
+ ".next", "coverage", ".venv", "venv", ".env",
14
+ ]);
15
+ const SUPPORTED_EXTS = new Set([".ts", ".tsx", ".js", ".jsx", ".py"]);
16
+ export function projectId(rootPath) {
17
+ return uuidv5(rootPath, UUID_NAMESPACE);
18
+ }
19
+ function hashFile(content) {
20
+ return createHash("sha256").update(content).digest("hex").slice(0, 16);
21
+ }
22
+ function collectFiles(dir) {
23
+ const files = [];
24
+ function walk(current) {
25
+ let entries;
26
+ try {
27
+ entries = readdirSync(current);
28
+ }
29
+ catch {
30
+ return;
31
+ }
32
+ for (const entry of entries) {
33
+ if (IGNORE_DIRS.has(entry))
34
+ continue;
35
+ const full = join(current, entry);
36
+ let stat;
37
+ try {
38
+ stat = statSync(full);
39
+ }
40
+ catch {
41
+ continue;
42
+ }
43
+ if (stat.isDirectory()) {
44
+ walk(full);
45
+ }
46
+ else if (SUPPORTED_EXTS.has(extname(full).toLowerCase())) {
47
+ files.push(full);
48
+ }
49
+ }
50
+ }
51
+ walk(dir);
52
+ return files;
53
+ }
54
+ /**
55
+ * Resolve a relative import path to candidate relative file paths within the project.
56
+ * Returns multiple candidates (with different extensions) for the caller to match.
57
+ */
58
+ function resolveImportCandidates(importPath, fromRelDir) {
59
+ if (!importPath.startsWith("."))
60
+ return []; // external module
61
+ const base = join(fromRelDir, importPath).replace(/\\/g, "/");
62
+ return [
63
+ base + ".ts",
64
+ base + ".tsx",
65
+ base + ".js",
66
+ base + ".jsx",
67
+ base + "/index.ts",
68
+ base + "/index.tsx",
69
+ base + "/index.js",
70
+ base,
71
+ ];
72
+ }
73
+ /**
74
+ * Second pass: extract import edges and store them in graph_edges.
75
+ * Replaces all existing graph edges for the project.
76
+ */
77
+ async function buildGraphEdges(db, pid, projectPath, allFiles) {
78
+ const projectFiles = getProjectFiles(db, pid);
79
+ const pathToFileId = new Map(projectFiles.map((f) => [f.path, f.id]));
80
+ deleteProjectGraphEdges(db, pid);
81
+ const edges = [];
82
+ for (const absPath of allFiles) {
83
+ const relPath = relative(projectPath, absPath).replace(/\\/g, "/");
84
+ const fileId = pathToFileId.get(relPath);
85
+ if (!fileId)
86
+ continue;
87
+ const fromChunkId = getFileRepresentativeChunk(db, fileId);
88
+ if (!fromChunkId)
89
+ continue;
90
+ const lang = getLanguageForFile(absPath);
91
+ if (!lang)
92
+ continue;
93
+ let source;
94
+ try {
95
+ source = readFileSync(absPath, "utf8");
96
+ }
97
+ catch {
98
+ continue;
99
+ }
100
+ try {
101
+ const language = await loadLanguage(lang);
102
+ const parser = new Parser();
103
+ parser.setLanguage(language);
104
+ const tree = parser.parse(source);
105
+ const imports = extractImports(source, lang, tree);
106
+ const fromRelDir = relPath.includes("/") ? relPath.slice(0, relPath.lastIndexOf("/")) : ".";
107
+ for (const imp of imports) {
108
+ const candidates = resolveImportCandidates(imp.to, fromRelDir);
109
+ for (const candidate of candidates) {
110
+ const targetFileId = pathToFileId.get(candidate);
111
+ if (!targetFileId)
112
+ continue;
113
+ const toChunkId = getFileRepresentativeChunk(db, targetFileId);
114
+ if (!toChunkId)
115
+ continue;
116
+ if (fromChunkId !== toChunkId) {
117
+ edges.push({ from: fromChunkId, to: toChunkId, edgeType: "imports", weight: 1.0 });
118
+ }
119
+ break; // found a match, stop trying candidates
120
+ }
121
+ }
122
+ }
123
+ catch {
124
+ // ignore parse errors in graph building
125
+ }
126
+ }
127
+ if (edges.length > 0) {
128
+ insertGraphEdges(db, pid, edges);
129
+ }
130
+ }
131
+ export async function indexProject(db, projectPath, force) {
132
+ const pid = projectId(projectPath);
133
+ upsertProject(db, pid, projectPath);
134
+ await initTreeSitter();
135
+ const allFiles = collectFiles(projectPath);
136
+ let filesIndexed = 0;
137
+ let filesSkipped = 0;
138
+ for (const absPath of allFiles) {
139
+ const relPath = relative(projectPath, absPath).replace(/\\/g, "/");
140
+ let source;
141
+ try {
142
+ source = readFileSync(absPath, "utf8");
143
+ }
144
+ catch {
145
+ filesSkipped++;
146
+ continue;
147
+ }
148
+ const hash = hashFile(source);
149
+ const existingHash = getFileHash(db, pid, relPath);
150
+ if (!force && existingHash === hash) {
151
+ filesSkipped++;
152
+ continue;
153
+ }
154
+ const lang = getLanguageForFile(absPath);
155
+ if (!lang) {
156
+ filesSkipped++;
157
+ continue;
158
+ }
159
+ try {
160
+ const language = await loadLanguage(lang);
161
+ const parser = new Parser();
162
+ parser.setLanguage(language);
163
+ const tree = parser.parse(source);
164
+ const stat = statSync(absPath);
165
+ const fileId = randomUUID();
166
+ upsertFile(db, fileId, pid, relPath, lang, hash, stat.mtimeMs);
167
+ deleteFileChunks(db, fileId);
168
+ const chunks = extractChunks(source, fileId, lang, tree);
169
+ insertChunks(db, chunks);
170
+ }
171
+ catch (err) {
172
+ process.stderr.write(`[engine] failed to index ${relPath}: ${err}\n`);
173
+ filesSkipped++;
174
+ continue;
175
+ }
176
+ filesIndexed++;
177
+ }
178
+ // Build import graph after all files are indexed
179
+ await buildGraphEdges(db, pid, projectPath, allFiles);
180
+ markProjectIndexed(db, pid);
181
+ return { filesIndexed, filesSkipped, totalFiles: allFiles.length };
182
+ }
183
+ /**
184
+ * Re-index only specific files (used by the file watcher).
185
+ * Does NOT rebuild graph edges — call indexProject for a full rebuild.
186
+ */
187
+ export async function indexSpecificFiles(db, projectPath, absPaths, force) {
188
+ const pid = projectId(projectPath);
189
+ upsertProject(db, pid, projectPath);
190
+ await initTreeSitter();
191
+ let filesIndexed = 0;
192
+ let filesSkipped = 0;
193
+ for (const absPath of absPaths) {
194
+ if (!SUPPORTED_EXTS.has(extname(absPath).toLowerCase())) {
195
+ filesSkipped++;
196
+ continue;
197
+ }
198
+ const relPath = relative(projectPath, absPath).replace(/\\/g, "/");
199
+ let source;
200
+ try {
201
+ source = readFileSync(absPath, "utf8");
202
+ }
203
+ catch {
204
+ // File deleted — remove from index
205
+ const existing = db
206
+ .prepare(`SELECT id FROM files WHERE project_id = ? AND path = ?`)
207
+ .get(pid, relPath);
208
+ if (existing) {
209
+ deleteFileChunks(db, existing.id);
210
+ db.prepare(`DELETE FROM files WHERE id = ?`).run(existing.id);
211
+ }
212
+ filesSkipped++;
213
+ continue;
214
+ }
215
+ const hash = hashFile(source);
216
+ const existingHash = getFileHash(db, pid, relPath);
217
+ if (!force && existingHash === hash) {
218
+ filesSkipped++;
219
+ continue;
220
+ }
221
+ const lang = getLanguageForFile(absPath);
222
+ if (!lang) {
223
+ filesSkipped++;
224
+ continue;
225
+ }
226
+ try {
227
+ const language = await loadLanguage(lang);
228
+ const parser = new Parser();
229
+ parser.setLanguage(language);
230
+ const tree = parser.parse(source);
231
+ const stat = statSync(absPath);
232
+ const fileId = randomUUID();
233
+ upsertFile(db, fileId, pid, relPath, lang, hash, stat.mtimeMs);
234
+ deleteFileChunks(db, fileId);
235
+ const chunks = extractChunks(source, fileId, lang, tree);
236
+ insertChunks(db, chunks);
237
+ }
238
+ catch (err) {
239
+ process.stderr.write(`[engine] failed to index ${relPath}: ${err}\n`);
240
+ filesSkipped++;
241
+ continue;
242
+ }
243
+ filesIndexed++;
244
+ }
245
+ return { filesIndexed, filesSkipped, totalFiles: absPaths.length };
246
+ }
247
+ //# sourceMappingURL=indexer.js.map
@@ -0,0 +1,6 @@
1
+ import Parser from "web-tree-sitter";
2
+ export declare function initTreeSitter(): Promise<void>;
3
+ export declare function loadLanguage(lang: "python" | "javascript" | "typescript" | "tsx"): Promise<Parser.Language>;
4
+ export declare function getLanguageForFile(filePath: string): "python" | "javascript" | "typescript" | "tsx" | null;
5
+ export declare const CHUNK_NODE_TYPES: Record<string, string[]>;
6
+ //# sourceMappingURL=languages.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"languages.d.ts","sourceRoot":"","sources":["../../src/indexer/languages.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,iBAAiB,CAAC;AAUrC,wBAAsB,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC,CAIpD;AAED,wBAAsB,YAAY,CAAC,IAAI,EAAE,QAAQ,GAAG,YAAY,GAAG,YAAY,GAAG,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,CAkBjH;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG,QAAQ,GAAG,YAAY,GAAG,YAAY,GAAG,KAAK,GAAG,IAAI,CAU1G;AAGD,eAAO,MAAM,gBAAgB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAKrD,CAAC"}
@@ -0,0 +1,47 @@
1
+ import Parser from "web-tree-sitter";
2
+ import { createRequire } from "module";
3
+ const require = createRequire(import.meta.url);
4
+ let initialized = false;
5
+ const languageCache = new Map();
6
+ export async function initTreeSitter() {
7
+ if (initialized)
8
+ return;
9
+ await Parser.init();
10
+ initialized = true;
11
+ }
12
+ export async function loadLanguage(lang) {
13
+ if (languageCache.has(lang))
14
+ return languageCache.get(lang);
15
+ await initTreeSitter();
16
+ const wasmMap = {
17
+ python: require.resolve("tree-sitter-python/tree-sitter-python.wasm"),
18
+ javascript: require.resolve("tree-sitter-javascript/tree-sitter-javascript.wasm"),
19
+ typescript: require.resolve("tree-sitter-typescript/tree-sitter-typescript.wasm"),
20
+ tsx: require.resolve("tree-sitter-typescript/tree-sitter-tsx.wasm"),
21
+ };
22
+ const wasmPath = wasmMap[lang];
23
+ if (!wasmPath)
24
+ throw new Error(`Unsupported language: ${lang}`);
25
+ const language = await Parser.Language.load(wasmPath);
26
+ languageCache.set(lang, language);
27
+ return language;
28
+ }
29
+ export function getLanguageForFile(filePath) {
30
+ const ext = filePath.slice(filePath.lastIndexOf(".")).toLowerCase();
31
+ switch (ext) {
32
+ case ".py": return "python";
33
+ case ".js":
34
+ case ".jsx": return "javascript";
35
+ case ".ts": return "typescript";
36
+ case ".tsx": return "tsx";
37
+ default: return null;
38
+ }
39
+ }
40
+ // Node types to extract per language
41
+ export const CHUNK_NODE_TYPES = {
42
+ python: ["function_definition", "class_definition"],
43
+ javascript: ["function_declaration", "function_expression", "arrow_function", "class_declaration", "method_definition"],
44
+ typescript: ["function_declaration", "function_expression", "arrow_function", "class_declaration", "method_definition"],
45
+ tsx: ["function_declaration", "function_expression", "arrow_function", "class_declaration", "method_definition"],
46
+ };
47
+ //# sourceMappingURL=languages.js.map
@@ -0,0 +1,12 @@
1
+ import type { EmbeddingCandidate, SearchResult } from "../types.js";
2
+ /**
3
+ * Cosine similarity between two Float32Arrays.
4
+ * Using typed arrays is ~5x faster than generic number[] in V8.
5
+ */
6
+ export declare function cosineSimilarity(a: Float32Array, b: Float32Array): number;
7
+ /**
8
+ * Semantic search over a list of embedding candidates.
9
+ * Returns top-k results sorted by cosine similarity descending.
10
+ */
11
+ export declare function semanticSearch(queryVector: Float32Array, candidates: EmbeddingCandidate[], k: number, filterType?: string): SearchResult[];
12
+ //# sourceMappingURL=search.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../src/search/search.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEpE;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,YAAY,GAAG,MAAM,CAWzE;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,WAAW,EAAE,YAAY,EACzB,UAAU,EAAE,kBAAkB,EAAE,EAChC,CAAC,EAAE,MAAM,EACT,UAAU,CAAC,EAAE,MAAM,GAClB,YAAY,EAAE,CAmBhB"}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Cosine similarity between two Float32Arrays.
3
+ * Using typed arrays is ~5x faster than generic number[] in V8.
4
+ */
5
+ export function cosineSimilarity(a, b) {
6
+ let dot = 0;
7
+ let na = 0;
8
+ let nb = 0;
9
+ for (let i = 0; i < a.length; i++) {
10
+ dot += a[i] * b[i];
11
+ na += a[i] * a[i];
12
+ nb += b[i] * b[i];
13
+ }
14
+ const denom = Math.sqrt(na) * Math.sqrt(nb);
15
+ return denom === 0 ? 0 : dot / denom;
16
+ }
17
+ /**
18
+ * Semantic search over a list of embedding candidates.
19
+ * Returns top-k results sorted by cosine similarity descending.
20
+ */
21
+ export function semanticSearch(queryVector, candidates, k, filterType) {
22
+ const filtered = filterType && filterType !== "any"
23
+ ? candidates.filter((c) => c.chunkType === filterType)
24
+ : candidates;
25
+ const scored = filtered.map((c) => ({
26
+ chunk_id: c.chunkId,
27
+ score: cosineSimilarity(queryVector, c.vector),
28
+ content: c.content,
29
+ chunk_type: c.chunkType,
30
+ name: c.name,
31
+ path: c.path,
32
+ start_line: c.startLine,
33
+ end_line: c.endLine,
34
+ }));
35
+ scored.sort((a, b) => b.score - a.score);
36
+ return scored.slice(0, k);
37
+ }
38
+ //# sourceMappingURL=search.js.map
@@ -0,0 +1,3 @@
1
+ import type { DatabaseSync } from "node:sqlite";
2
+ export declare function applySchema(db: DatabaseSync): void;
3
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../src/storage/schema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD,wBAAgB,WAAW,CAAC,EAAE,EAAE,YAAY,GAAG,IAAI,CAyFlD"}
@@ -0,0 +1,91 @@
1
+ export function applySchema(db) {
2
+ db.exec(`
3
+ CREATE TABLE IF NOT EXISTS projects (
4
+ id TEXT PRIMARY KEY,
5
+ name TEXT NOT NULL,
6
+ root_path TEXT NOT NULL UNIQUE,
7
+ config TEXT,
8
+ indexed_at INTEGER,
9
+ created_at INTEGER NOT NULL
10
+ );
11
+
12
+ CREATE TABLE IF NOT EXISTS files (
13
+ id TEXT PRIMARY KEY,
14
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
15
+ path TEXT NOT NULL,
16
+ language TEXT,
17
+ hash TEXT NOT NULL,
18
+ last_modified INTEGER,
19
+ UNIQUE(project_id, path)
20
+ );
21
+
22
+ CREATE TABLE IF NOT EXISTS chunks (
23
+ id TEXT PRIMARY KEY,
24
+ file_id TEXT NOT NULL REFERENCES files(id) ON DELETE CASCADE,
25
+ chunk_type TEXT NOT NULL,
26
+ name TEXT,
27
+ content TEXT NOT NULL,
28
+ start_line INTEGER NOT NULL,
29
+ end_line INTEGER NOT NULL,
30
+ token_count INTEGER NOT NULL,
31
+ metadata TEXT
32
+ );
33
+
34
+ CREATE TABLE IF NOT EXISTS embeddings (
35
+ chunk_id TEXT PRIMARY KEY REFERENCES chunks(id) ON DELETE CASCADE,
36
+ model TEXT NOT NULL,
37
+ vector BLOB NOT NULL,
38
+ dims INTEGER NOT NULL,
39
+ created_at INTEGER NOT NULL
40
+ );
41
+
42
+ CREATE TABLE IF NOT EXISTS graph_edges (
43
+ id TEXT PRIMARY KEY,
44
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
45
+ from_chunk TEXT NOT NULL REFERENCES chunks(id) ON DELETE CASCADE,
46
+ to_chunk TEXT NOT NULL REFERENCES chunks(id) ON DELETE CASCADE,
47
+ edge_type TEXT NOT NULL,
48
+ weight REAL DEFAULT 1.0
49
+ );
50
+
51
+ CREATE TABLE IF NOT EXISTS memories (
52
+ id TEXT PRIMARY KEY,
53
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
54
+ session_id TEXT,
55
+ memory_type TEXT NOT NULL,
56
+ content TEXT NOT NULL,
57
+ relevance_score REAL DEFAULT 1.0,
58
+ created_at INTEGER NOT NULL,
59
+ expires_at INTEGER
60
+ );
61
+
62
+ CREATE INDEX IF NOT EXISTS idx_chunks_file ON chunks(file_id);
63
+ CREATE INDEX IF NOT EXISTS idx_files_project ON files(project_id);
64
+ CREATE INDEX IF NOT EXISTS idx_embeddings_chunk ON embeddings(chunk_id);
65
+ CREATE INDEX IF NOT EXISTS idx_graph_from ON graph_edges(from_chunk);
66
+ CREATE INDEX IF NOT EXISTS idx_graph_project ON graph_edges(project_id);
67
+ CREATE INDEX IF NOT EXISTS idx_memories_project ON memories(project_id, created_at DESC);
68
+
69
+ CREATE TABLE IF NOT EXISTS memory_embeddings (
70
+ memory_id TEXT PRIMARY KEY REFERENCES memories(id) ON DELETE CASCADE,
71
+ model TEXT NOT NULL,
72
+ vector BLOB NOT NULL,
73
+ dims INTEGER NOT NULL,
74
+ created_at INTEGER NOT NULL
75
+ );
76
+
77
+ CREATE TABLE IF NOT EXISTS file_coedits (
78
+ id TEXT PRIMARY KEY,
79
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
80
+ file_a TEXT NOT NULL,
81
+ file_b TEXT NOT NULL,
82
+ count INTEGER NOT NULL DEFAULT 1,
83
+ last_seen INTEGER NOT NULL,
84
+ UNIQUE(project_id, file_a, file_b)
85
+ );
86
+
87
+ CREATE INDEX IF NOT EXISTS idx_coedits_a ON file_coedits(project_id, file_a);
88
+ CREATE INDEX IF NOT EXISTS idx_coedits_b ON file_coedits(project_id, file_b);
89
+ `);
90
+ }
91
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1,63 @@
1
+ import { DatabaseSync } from "node:sqlite";
2
+ import type { Chunk, EmbeddingCandidate, GraphEdge } from "../types.js";
3
+ export declare function openDatabase(dbPath: string): DatabaseSync;
4
+ export declare function vectorToBlob(vector: Float32Array): Buffer;
5
+ export declare function blobToVector(blob: Buffer | Uint8Array): Float32Array;
6
+ export declare function upsertProject(db: DatabaseSync, projectId: string, rootPath: string): void;
7
+ export declare function markProjectIndexed(db: DatabaseSync, projectId: string): void;
8
+ export declare function getProject(db: DatabaseSync, projectId: string): {
9
+ indexed_at: number | null;
10
+ root_path: string;
11
+ } | undefined;
12
+ export declare function upsertFile(db: DatabaseSync, fileId: string, projectId: string, relPath: string, language: string, hash: string, lastModified: number): void;
13
+ export declare function getFileHash(db: DatabaseSync, projectId: string, relPath: string): string | undefined;
14
+ export declare function deleteFileChunks(db: DatabaseSync, fileId: string): void;
15
+ export declare function getProjectFiles(db: DatabaseSync, projectId: string): Array<{
16
+ id: string;
17
+ path: string;
18
+ }>;
19
+ export declare function insertChunks(db: DatabaseSync, chunks: Chunk[]): void;
20
+ export declare function upsertEmbeddings(db: DatabaseSync, entries: Array<{
21
+ chunkId: string;
22
+ vector: Float32Array;
23
+ model: string;
24
+ }>): void;
25
+ export declare function getAllEmbeddings(db: DatabaseSync, projectId: string): EmbeddingCandidate[];
26
+ export declare function getProjectStats(db: DatabaseSync, projectId: string): {
27
+ files: number;
28
+ chunks: number;
29
+ };
30
+ export declare function insertGraphEdges(db: DatabaseSync, projectId: string, edges: GraphEdge[]): void;
31
+ export declare function getProjectGraphEdges(db: DatabaseSync, projectId: string): Array<{
32
+ from_chunk: string;
33
+ to_chunk: string;
34
+ edge_type: string;
35
+ weight: number;
36
+ }>;
37
+ export declare function getFileRepresentativeChunk(db: DatabaseSync, fileId: string): string | undefined;
38
+ export declare function deleteProjectGraphEdges(db: DatabaseSync, projectId: string): void;
39
+ export declare function upsertMemoryEmbedding(db: DatabaseSync, memoryId: string, vector: Float32Array, model: string): void;
40
+ export declare function getMemoryEmbeddings(db: DatabaseSync, projectId: string): Array<{
41
+ memoryId: string;
42
+ vector: Float32Array;
43
+ memoryType: string;
44
+ content: string;
45
+ createdAt: number;
46
+ }>;
47
+ /**
48
+ * Record that a set of files were edited in the same session window.
49
+ * Increments the co-edit count for every pair in the set.
50
+ */
51
+ export declare function recordCoEdits(db: DatabaseSync, projectId: string, relPaths: string[]): void;
52
+ /**
53
+ * For a given active file, return normalized co-edit scores [0,1] for candidate paths.
54
+ * Score of 1 = always edited together with activeFilePath; 0 = never.
55
+ */
56
+ export declare function getCoEditScores(db: DatabaseSync, projectId: string, activeFilePath: string, candidatePaths: string[]): Record<string, number>;
57
+ export declare function getChunksByIds(db: DatabaseSync, ids: string[]): Array<{
58
+ id: string;
59
+ chunk_type: string;
60
+ name: string | null;
61
+ path: string;
62
+ }>;
63
+ //# sourceMappingURL=sqlite.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite.d.ts","sourceRoot":"","sources":["../../src/storage/sqlite.ts"],"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