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
package/src/engine.ts ADDED
@@ -0,0 +1,425 @@
1
+ import { join } from "path";
2
+ import { homedir } from "os";
3
+ import { randomUUID } from "crypto";
4
+ import type { DatabaseSync } from "node:sqlite";
5
+ import type { IContextEngine, IndexResult, SearchResult, StatusResult, SubgraphResult, MemorySearchResult } from "./types.js";
6
+ import {
7
+ openDatabase,
8
+ getAllEmbeddings,
9
+ getProjectStats,
10
+ getProjectGraphEdges,
11
+ getChunksByIds,
12
+ upsertProject,
13
+ upsertMemoryEmbedding,
14
+ getMemoryEmbeddings,
15
+ recordCoEdits,
16
+ getCoEditScores,
17
+ } from "./storage/sqlite.js";
18
+ import { initEmbedder, embedSingle, embedTexts } from "./embedder/embedder.js";
19
+ import { initTreeSitter } from "./indexer/languages.js";
20
+ import { indexProject, indexSpecificFiles, projectId } from "./indexer/indexer.js";
21
+ import { semanticSearch, cosineSimilarity } from "./search/search.js";
22
+ import { DiGraph } from "./graph/graph.js";
23
+ import type { EmbeddingCandidate } from "./types.js";
24
+
25
+ const MODEL = "all-MiniLM-L6-v2";
26
+ const EMBED_BATCH = 64;
27
+
28
+ export class ContextEngine implements IContextEngine {
29
+ private db: DatabaseSync;
30
+ private _initialized = false;
31
+
32
+ // Per-project caches
33
+ private embeddingsCache = new Map<string, EmbeddingCandidate[]>();
34
+ private graphCache = new Map<string, DiGraph>();
35
+
36
+ constructor(dbPath?: string) {
37
+ const path = dbPath ?? join(homedir(), ".context-pilot", "db.sqlite");
38
+ this.db = openDatabase(path);
39
+ }
40
+
41
+ async init(): Promise<void> {
42
+ if (this._initialized) return;
43
+ process.stderr.write("[engine] initializing tree-sitter...\n");
44
+ await initTreeSitter();
45
+ process.stderr.write("[engine] loading embedding model (first run may download ~90MB)...\n");
46
+ await initEmbedder();
47
+ this._initialized = true;
48
+ process.stderr.write("[engine] ready\n");
49
+ }
50
+
51
+ async index(params: { projectPath: string; force?: boolean; paths?: string[] }): Promise<IndexResult> {
52
+ if (!this._initialized) await this.init();
53
+
54
+ const pid = projectId(params.projectPath);
55
+ // Invalidate caches for this project
56
+ this.embeddingsCache.delete(pid);
57
+ this.graphCache.delete(pid);
58
+
59
+ try {
60
+ let filesIndexed: number;
61
+ let filesSkipped: number;
62
+ let totalFiles: number;
63
+
64
+ if (params.paths && params.paths.length > 0) {
65
+ // Targeted re-index of specific files (used by watcher)
66
+ ({ filesIndexed, filesSkipped, totalFiles } = await indexSpecificFiles(
67
+ this.db,
68
+ params.projectPath,
69
+ params.paths,
70
+ params.force ?? false
71
+ ));
72
+
73
+ // Record co-edit relationships for all files changed in this session window
74
+ const { relative } = await import("path");
75
+ const relPaths = params.paths.map((p) =>
76
+ relative(params.projectPath, p).replace(/\\/g, "/")
77
+ );
78
+ recordCoEdits(this.db, pid, relPaths);
79
+ } else {
80
+ // Full project index
81
+ ({ filesIndexed, filesSkipped, totalFiles } = await indexProject(
82
+ this.db,
83
+ params.projectPath,
84
+ params.force ?? false
85
+ ));
86
+ }
87
+
88
+ // Embed any chunks that don't have embeddings yet
89
+ await this._embedNewChunks(pid);
90
+
91
+ return {
92
+ success: true,
93
+ projectId: pid,
94
+ projectPath: params.projectPath,
95
+ filesIndexed,
96
+ filesSkipped,
97
+ totalFiles,
98
+ };
99
+ } catch (err) {
100
+ return {
101
+ success: false,
102
+ projectId: pid,
103
+ projectPath: params.projectPath,
104
+ filesIndexed: 0,
105
+ filesSkipped: 0,
106
+ totalFiles: 0,
107
+ error: String(err),
108
+ };
109
+ }
110
+ }
111
+
112
+ async search(params: {
113
+ query: string;
114
+ projectPath: string;
115
+ k?: number;
116
+ filterType?: string;
117
+ }): Promise<{ results: SearchResult[] }> {
118
+ if (!this._initialized) await this.init();
119
+
120
+ const pid = projectId(params.projectPath);
121
+ const candidates = await this._getEmbeddings(pid);
122
+
123
+ if (candidates.length === 0) {
124
+ return { results: [] };
125
+ }
126
+
127
+ const queryVec = await embedSingle(params.query);
128
+ const raw = semanticSearch(queryVec, candidates, params.k ?? 10, params.filterType);
129
+
130
+ // Include last_modified from the candidate data
131
+ const candidateMap = new Map(candidates.map((c) => [c.chunkId, c]));
132
+ const results: SearchResult[] = raw.map((r) => ({
133
+ ...r,
134
+ last_modified: candidateMap.get(r.chunk_id)?.lastModified,
135
+ }));
136
+
137
+ return { results };
138
+ }
139
+
140
+ async searchMemories(params: {
141
+ query: string;
142
+ projectPath: string;
143
+ k?: number;
144
+ }): Promise<{ results: MemorySearchResult[] }> {
145
+ if (!this._initialized) await this.init();
146
+
147
+ const pid = projectId(params.projectPath);
148
+ const memoryEmbeddings = getMemoryEmbeddings(this.db, pid);
149
+
150
+ if (memoryEmbeddings.length === 0) {
151
+ return { results: [] };
152
+ }
153
+
154
+ const queryVec = await embedSingle(params.query);
155
+ const k = params.k ?? 5;
156
+
157
+ const scored = memoryEmbeddings
158
+ .map((m) => ({ ...m, score: cosineSimilarity(queryVec, m.vector) }))
159
+ .sort((a, b) => b.score - a.score)
160
+ .slice(0, k);
161
+
162
+ return {
163
+ results: scored.map((m) => ({
164
+ id: m.memoryId,
165
+ memory_type: m.memoryType,
166
+ content: m.content,
167
+ score: m.score,
168
+ created_at: m.createdAt,
169
+ })),
170
+ };
171
+ }
172
+
173
+ async status(params: { projectPath: string }): Promise<StatusResult> {
174
+ const pid = projectId(params.projectPath);
175
+ const project = this.db
176
+ .prepare(`SELECT indexed_at FROM projects WHERE id = ?`)
177
+ .get(pid) as { indexed_at: number | null } | undefined;
178
+
179
+ if (!project) {
180
+ return { indexed: false, projectPath: params.projectPath };
181
+ }
182
+
183
+ const stats = getProjectStats(this.db, pid);
184
+ return {
185
+ indexed: project.indexed_at !== null,
186
+ projectId: pid,
187
+ projectPath: params.projectPath,
188
+ files: stats.files,
189
+ chunks: stats.chunks,
190
+ indexedAt: project.indexed_at ?? undefined,
191
+ };
192
+ }
193
+
194
+ async graph(params: {
195
+ target: string;
196
+ projectPath: string;
197
+ depth?: number;
198
+ direction?: string;
199
+ }): Promise<SubgraphResult> {
200
+ const pid = projectId(params.projectPath);
201
+ const g = await this._getGraph(pid);
202
+
203
+ // Find root node — match by name or path
204
+ let rootId: string | undefined;
205
+ for (const [id, attrs] of g.allNodes()) {
206
+ if (attrs.name === params.target || attrs.path.endsWith(params.target)) {
207
+ rootId = id;
208
+ break;
209
+ }
210
+ }
211
+
212
+ if (!rootId) {
213
+ return { nodes: [], edges: [], error: `Target not found: ${params.target}` };
214
+ }
215
+
216
+ const direction = (params.direction ?? "both") as "outgoing" | "incoming" | "both";
217
+ const { nodeIds, edges } = g.subgraph(rootId, params.depth ?? 2, direction);
218
+
219
+ const nodes = [...nodeIds].map((id) => {
220
+ const attrs = g.getNode(id)!;
221
+ return { id, chunkType: attrs.chunkType, name: attrs.name, path: attrs.path };
222
+ });
223
+
224
+ return {
225
+ nodes,
226
+ edges: edges.map((e) => ({
227
+ from: e.from,
228
+ to: e.to,
229
+ edgeType: e.attrs.edgeType as "calls" | "extends" | "imports",
230
+ weight: e.attrs.weight,
231
+ })),
232
+ };
233
+ }
234
+
235
+ async graphDistances(params: {
236
+ projectPath: string;
237
+ activeChunkId: string;
238
+ candidateIds: string[];
239
+ }): Promise<{ distances: Record<string, number> }> {
240
+ const pid = projectId(params.projectPath);
241
+ const g = await this._getGraph(pid);
242
+ const distances = g.shortestPathDistances(params.activeChunkId, params.candidateIds);
243
+ return { distances };
244
+ }
245
+
246
+ async remember(params: {
247
+ projectPath: string;
248
+ sessionId: string;
249
+ memoryType: "decision" | "pattern" | "todo" | "context_note";
250
+ content: string;
251
+ }): Promise<{ id: string; success: boolean }> {
252
+ if (!this._initialized) await this.init();
253
+ const pid = projectId(params.projectPath);
254
+ upsertProject(this.db, pid, params.projectPath);
255
+ const id = randomUUID();
256
+ this.db.prepare(`
257
+ INSERT INTO memories (id, project_id, session_id, memory_type, content, relevance_score, created_at)
258
+ VALUES (?, ?, ?, ?, ?, 1.0, ?)
259
+ `).run(id, pid, params.sessionId, params.memoryType, params.content, Date.now());
260
+
261
+ // Store embedding so memories are semantically searchable
262
+ try {
263
+ const vector = await embedSingle(params.content);
264
+ upsertMemoryEmbedding(this.db, id, vector, MODEL);
265
+ } catch {
266
+ // non-critical — memory is stored even without embedding
267
+ }
268
+
269
+ return { id, success: true };
270
+ }
271
+
272
+ getCoEditScores(params: {
273
+ projectPath: string;
274
+ activeFilePath: string;
275
+ candidatePaths: string[];
276
+ }): Record<string, number> {
277
+ const pid = projectId(params.projectPath);
278
+ return getCoEditScores(this.db, pid, params.activeFilePath, params.candidatePaths);
279
+ }
280
+
281
+ async getFileGraph(params: { projectPath: string }): Promise<{
282
+ nodes: Array<{ id: string; path: string; language: string; chunkCount: number }>;
283
+ edges: Array<{ from: string; to: string }>;
284
+ }> {
285
+ const pid = projectId(params.projectPath);
286
+
287
+ const files = this.db.prepare(`
288
+ SELECT f.id, f.path, COALESCE(f.language, 'unknown') as language, COUNT(c.id) as chunk_count
289
+ FROM files f
290
+ LEFT JOIN chunks c ON c.file_id = f.id
291
+ WHERE f.project_id = ?
292
+ GROUP BY f.id
293
+ ORDER BY chunk_count DESC
294
+ LIMIT 400
295
+ `).all(pid) as Array<{ id: string; path: string; language: string; chunk_count: number }>;
296
+
297
+ const edges = this.db.prepare(`
298
+ SELECT DISTINCT f1.id AS from_file, f2.id AS to_file
299
+ FROM graph_edges ge
300
+ JOIN chunks c1 ON c1.id = ge.from_chunk
301
+ JOIN files f1 ON f1.id = c1.file_id
302
+ JOIN chunks c2 ON c2.id = ge.to_chunk
303
+ JOIN files f2 ON f2.id = c2.file_id
304
+ WHERE f1.project_id = ? AND f1.id != f2.id
305
+ `).all(pid) as Array<{ from_file: string; to_file: string }>;
306
+
307
+ // Only include edges where both nodes are in our limited node set
308
+ const nodeIds = new Set(files.map((f) => f.id));
309
+ const filteredEdges = edges.filter(
310
+ (e) => nodeIds.has(e.from_file) && nodeIds.has(e.to_file)
311
+ );
312
+
313
+ return {
314
+ nodes: files.map((f) => ({
315
+ id: f.id,
316
+ path: f.path,
317
+ language: f.language,
318
+ chunkCount: f.chunk_count,
319
+ })),
320
+ edges: filteredEdges.map((e) => ({ from: e.from_file, to: e.to_file })),
321
+ };
322
+ }
323
+
324
+ async listMemories(params: { projectPath: string }): Promise<{ memories: import("./types.js").MemoryRecord[] }> {
325
+ const pid = projectId(params.projectPath);
326
+ const memories = this.db.prepare(`
327
+ SELECT id, memory_type, content, session_id, relevance_score, created_at
328
+ FROM memories
329
+ WHERE project_id = ?
330
+ ORDER BY created_at DESC
331
+ `).all(pid) as unknown as import("./types.js").MemoryRecord[];
332
+ return { memories };
333
+ }
334
+
335
+ async deleteMemory(params: { projectPath: string; memoryId: string }): Promise<{ success: boolean }> {
336
+ const pid = projectId(params.projectPath);
337
+ const result = this.db
338
+ .prepare(`DELETE FROM memories WHERE id = ? AND project_id = ?`)
339
+ .run(params.memoryId, pid) as { changes: number };
340
+ return { success: result.changes > 0 };
341
+ }
342
+
343
+ close(): void {
344
+ this.db.close();
345
+ }
346
+
347
+ // ── Private helpers ──────────────────────────────────────────────────────────
348
+
349
+ private async _getEmbeddings(projectId: string): Promise<EmbeddingCandidate[]> {
350
+ if (this.embeddingsCache.has(projectId)) return this.embeddingsCache.get(projectId)!;
351
+ const candidates = getAllEmbeddings(this.db, projectId);
352
+ this.embeddingsCache.set(projectId, candidates);
353
+ return candidates;
354
+ }
355
+
356
+ private async _getGraph(projectId: string): Promise<DiGraph> {
357
+ if (this.graphCache.has(projectId)) return this.graphCache.get(projectId)!;
358
+
359
+ const g = new DiGraph();
360
+
361
+ // Add all chunks as nodes
362
+ const chunks = this.db.prepare(`
363
+ SELECT c.id, c.chunk_type, c.name, f.path
364
+ FROM chunks c JOIN files f ON f.id = c.file_id
365
+ WHERE f.project_id = ?
366
+ `).all(projectId) as Array<{ id: string; chunk_type: string; name: string | null; path: string }>;
367
+
368
+ for (const c of chunks) {
369
+ g.addNode(c.id, { chunkType: c.chunk_type, name: c.name, path: c.path });
370
+ }
371
+
372
+ // Add edges
373
+ const edges = getProjectGraphEdges(this.db, projectId);
374
+ for (const e of edges) {
375
+ g.addEdge(e.from_chunk, e.to_chunk, { edgeType: e.edge_type, weight: e.weight });
376
+ }
377
+
378
+ this.graphCache.set(projectId, g);
379
+ return g;
380
+ }
381
+
382
+ private async _embedNewChunks(pid: string): Promise<void> {
383
+ // Find chunks without embeddings
384
+ const unembedded = this.db.prepare(`
385
+ SELECT c.id, c.content
386
+ FROM chunks c
387
+ JOIN files f ON f.id = c.file_id
388
+ WHERE f.project_id = ?
389
+ AND c.id NOT IN (SELECT chunk_id FROM embeddings)
390
+ `).all(pid) as Array<{ id: string; content: string }>;
391
+
392
+ if (unembedded.length === 0) return;
393
+
394
+ process.stderr.write(`[engine] embedding ${unembedded.length} new chunks...\n`);
395
+
396
+ const texts = unembedded.map((c) => c.content);
397
+ const vectors = await embedTexts(texts);
398
+
399
+ const stmt = this.db.prepare(`
400
+ INSERT OR REPLACE INTO embeddings (chunk_id, model, vector, dims, created_at)
401
+ VALUES (?, ?, ?, ?, ?)
402
+ `);
403
+
404
+ const { vectorToBlob } = await import("./storage/sqlite.js");
405
+ this.db.exec("BEGIN");
406
+ try {
407
+ for (let i = 0; i < unembedded.length; i++) {
408
+ stmt.run(
409
+ unembedded[i].id,
410
+ MODEL,
411
+ vectorToBlob(vectors[i]),
412
+ vectors[i].length,
413
+ Date.now()
414
+ );
415
+ }
416
+ this.db.exec("COMMIT");
417
+ } catch (err) {
418
+ this.db.exec("ROLLBACK");
419
+ throw err;
420
+ }
421
+
422
+ // Invalidate embeddings cache
423
+ this.embeddingsCache.delete(pid);
424
+ }
425
+ }
@@ -0,0 +1,136 @@
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 ADDED
@@ -0,0 +1,15 @@
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";
@@ -0,0 +1,115 @@
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
+ }