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,4 @@
1
+ export declare function initEmbedder(): Promise<void>;
2
+ export declare function embedTexts(texts: string[]): Promise<Float32Array[]>;
3
+ export declare function embedSingle(text: string): Promise<Float32Array>;
4
+ //# sourceMappingURL=embedder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"embedder.d.ts","sourceRoot":"","sources":["../../src/embedder/embedder.ts"],"names":[],"mappings":"AASA,wBAAsB,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC,CAYlD;AAED,wBAAsB,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC,CAiBzE;AAED,wBAAsB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC,CAGrE"}
@@ -0,0 +1,37 @@
1
+ import { pipeline, env } from "@huggingface/transformers";
2
+ import { join } from "path";
3
+ import { homedir } from "os";
4
+ const MODEL_NAME = "Xenova/all-MiniLM-L6-v2";
5
+ let embedder = null;
6
+ export async function initEmbedder() {
7
+ if (embedder)
8
+ return;
9
+ // Cache models in ~/.context-pilot/models
10
+ env.cacheDir = join(homedir(), ".context-pilot", "models");
11
+ // Disable remote model fetching in offline mode if needed
12
+ // env.allowRemoteModels = false;
13
+ embedder = await pipeline("feature-extraction", MODEL_NAME, {
14
+ dtype: "fp32",
15
+ });
16
+ }
17
+ export async function embedTexts(texts) {
18
+ if (!embedder)
19
+ await initEmbedder();
20
+ const BATCH_SIZE = 64;
21
+ const results = [];
22
+ for (let i = 0; i < texts.length; i += BATCH_SIZE) {
23
+ const batch = texts.slice(i, i + BATCH_SIZE);
24
+ const output = await embedder(batch, { pooling: "mean", normalize: true });
25
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
26
+ const list = output.tolist();
27
+ for (const vec of list) {
28
+ results.push(new Float32Array(vec));
29
+ }
30
+ }
31
+ return results;
32
+ }
33
+ export async function embedSingle(text) {
34
+ const [vec] = await embedTexts([text]);
35
+ return vec;
36
+ }
37
+ //# sourceMappingURL=embedder.js.map
@@ -0,0 +1,89 @@
1
+ import type { IContextEngine, IndexResult, SearchResult, StatusResult, SubgraphResult, MemorySearchResult } from "./types.js";
2
+ export declare class ContextEngine implements IContextEngine {
3
+ private db;
4
+ private _initialized;
5
+ private embeddingsCache;
6
+ private graphCache;
7
+ constructor(dbPath?: string);
8
+ init(): Promise<void>;
9
+ index(params: {
10
+ projectPath: string;
11
+ force?: boolean;
12
+ paths?: string[];
13
+ }): Promise<IndexResult>;
14
+ search(params: {
15
+ query: string;
16
+ projectPath: string;
17
+ k?: number;
18
+ filterType?: string;
19
+ }): Promise<{
20
+ results: SearchResult[];
21
+ }>;
22
+ searchMemories(params: {
23
+ query: string;
24
+ projectPath: string;
25
+ k?: number;
26
+ }): Promise<{
27
+ results: MemorySearchResult[];
28
+ }>;
29
+ status(params: {
30
+ projectPath: string;
31
+ }): Promise<StatusResult>;
32
+ graph(params: {
33
+ target: string;
34
+ projectPath: string;
35
+ depth?: number;
36
+ direction?: string;
37
+ }): Promise<SubgraphResult>;
38
+ graphDistances(params: {
39
+ projectPath: string;
40
+ activeChunkId: string;
41
+ candidateIds: string[];
42
+ }): Promise<{
43
+ distances: Record<string, number>;
44
+ }>;
45
+ remember(params: {
46
+ projectPath: string;
47
+ sessionId: string;
48
+ memoryType: "decision" | "pattern" | "todo" | "context_note";
49
+ content: string;
50
+ }): Promise<{
51
+ id: string;
52
+ success: boolean;
53
+ }>;
54
+ getCoEditScores(params: {
55
+ projectPath: string;
56
+ activeFilePath: string;
57
+ candidatePaths: string[];
58
+ }): Record<string, number>;
59
+ getFileGraph(params: {
60
+ projectPath: string;
61
+ }): Promise<{
62
+ nodes: Array<{
63
+ id: string;
64
+ path: string;
65
+ language: string;
66
+ chunkCount: number;
67
+ }>;
68
+ edges: Array<{
69
+ from: string;
70
+ to: string;
71
+ }>;
72
+ }>;
73
+ listMemories(params: {
74
+ projectPath: string;
75
+ }): Promise<{
76
+ memories: import("./types.js").MemoryRecord[];
77
+ }>;
78
+ deleteMemory(params: {
79
+ projectPath: string;
80
+ memoryId: string;
81
+ }): Promise<{
82
+ success: boolean;
83
+ }>;
84
+ close(): void;
85
+ private _getEmbeddings;
86
+ private _getGraph;
87
+ private _embedNewChunks;
88
+ }
89
+ //# sourceMappingURL=engine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../src/engine.ts"],"names":[],"mappings":"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"}
package/dist/engine.js ADDED
@@ -0,0 +1,314 @@
1
+ import { join } from "path";
2
+ import { homedir } from "os";
3
+ import { randomUUID } from "crypto";
4
+ import { openDatabase, getAllEmbeddings, getProjectStats, getProjectGraphEdges, upsertProject, upsertMemoryEmbedding, getMemoryEmbeddings, recordCoEdits, getCoEditScores, } from "./storage/sqlite.js";
5
+ import { initEmbedder, embedSingle, embedTexts } from "./embedder/embedder.js";
6
+ import { initTreeSitter } from "./indexer/languages.js";
7
+ import { indexProject, indexSpecificFiles, projectId } from "./indexer/indexer.js";
8
+ import { semanticSearch, cosineSimilarity } from "./search/search.js";
9
+ import { DiGraph } from "./graph/graph.js";
10
+ const MODEL = "all-MiniLM-L6-v2";
11
+ const EMBED_BATCH = 64;
12
+ export class ContextEngine {
13
+ db;
14
+ _initialized = false;
15
+ // Per-project caches
16
+ embeddingsCache = new Map();
17
+ graphCache = new Map();
18
+ constructor(dbPath) {
19
+ const path = dbPath ?? join(homedir(), ".context-pilot", "db.sqlite");
20
+ this.db = openDatabase(path);
21
+ }
22
+ async init() {
23
+ if (this._initialized)
24
+ return;
25
+ process.stderr.write("[engine] initializing tree-sitter...\n");
26
+ await initTreeSitter();
27
+ process.stderr.write("[engine] loading embedding model (first run may download ~90MB)...\n");
28
+ await initEmbedder();
29
+ this._initialized = true;
30
+ process.stderr.write("[engine] ready\n");
31
+ }
32
+ async index(params) {
33
+ if (!this._initialized)
34
+ await this.init();
35
+ const pid = projectId(params.projectPath);
36
+ // Invalidate caches for this project
37
+ this.embeddingsCache.delete(pid);
38
+ this.graphCache.delete(pid);
39
+ try {
40
+ let filesIndexed;
41
+ let filesSkipped;
42
+ let totalFiles;
43
+ if (params.paths && params.paths.length > 0) {
44
+ // Targeted re-index of specific files (used by watcher)
45
+ ({ filesIndexed, filesSkipped, totalFiles } = await indexSpecificFiles(this.db, params.projectPath, params.paths, params.force ?? false));
46
+ // Record co-edit relationships for all files changed in this session window
47
+ const { relative } = await import("path");
48
+ const relPaths = params.paths.map((p) => relative(params.projectPath, p).replace(/\\/g, "/"));
49
+ recordCoEdits(this.db, pid, relPaths);
50
+ }
51
+ else {
52
+ // Full project index
53
+ ({ filesIndexed, filesSkipped, totalFiles } = await indexProject(this.db, params.projectPath, params.force ?? false));
54
+ }
55
+ // Embed any chunks that don't have embeddings yet
56
+ await this._embedNewChunks(pid);
57
+ return {
58
+ success: true,
59
+ projectId: pid,
60
+ projectPath: params.projectPath,
61
+ filesIndexed,
62
+ filesSkipped,
63
+ totalFiles,
64
+ };
65
+ }
66
+ catch (err) {
67
+ return {
68
+ success: false,
69
+ projectId: pid,
70
+ projectPath: params.projectPath,
71
+ filesIndexed: 0,
72
+ filesSkipped: 0,
73
+ totalFiles: 0,
74
+ error: String(err),
75
+ };
76
+ }
77
+ }
78
+ async search(params) {
79
+ if (!this._initialized)
80
+ await this.init();
81
+ const pid = projectId(params.projectPath);
82
+ const candidates = await this._getEmbeddings(pid);
83
+ if (candidates.length === 0) {
84
+ return { results: [] };
85
+ }
86
+ const queryVec = await embedSingle(params.query);
87
+ const raw = semanticSearch(queryVec, candidates, params.k ?? 10, params.filterType);
88
+ // Include last_modified from the candidate data
89
+ const candidateMap = new Map(candidates.map((c) => [c.chunkId, c]));
90
+ const results = raw.map((r) => ({
91
+ ...r,
92
+ last_modified: candidateMap.get(r.chunk_id)?.lastModified,
93
+ }));
94
+ return { results };
95
+ }
96
+ async searchMemories(params) {
97
+ if (!this._initialized)
98
+ await this.init();
99
+ const pid = projectId(params.projectPath);
100
+ const memoryEmbeddings = getMemoryEmbeddings(this.db, pid);
101
+ if (memoryEmbeddings.length === 0) {
102
+ return { results: [] };
103
+ }
104
+ const queryVec = await embedSingle(params.query);
105
+ const k = params.k ?? 5;
106
+ const scored = memoryEmbeddings
107
+ .map((m) => ({ ...m, score: cosineSimilarity(queryVec, m.vector) }))
108
+ .sort((a, b) => b.score - a.score)
109
+ .slice(0, k);
110
+ return {
111
+ results: scored.map((m) => ({
112
+ id: m.memoryId,
113
+ memory_type: m.memoryType,
114
+ content: m.content,
115
+ score: m.score,
116
+ created_at: m.createdAt,
117
+ })),
118
+ };
119
+ }
120
+ async status(params) {
121
+ const pid = projectId(params.projectPath);
122
+ const project = this.db
123
+ .prepare(`SELECT indexed_at FROM projects WHERE id = ?`)
124
+ .get(pid);
125
+ if (!project) {
126
+ return { indexed: false, projectPath: params.projectPath };
127
+ }
128
+ const stats = getProjectStats(this.db, pid);
129
+ return {
130
+ indexed: project.indexed_at !== null,
131
+ projectId: pid,
132
+ projectPath: params.projectPath,
133
+ files: stats.files,
134
+ chunks: stats.chunks,
135
+ indexedAt: project.indexed_at ?? undefined,
136
+ };
137
+ }
138
+ async graph(params) {
139
+ const pid = projectId(params.projectPath);
140
+ const g = await this._getGraph(pid);
141
+ // Find root node — match by name or path
142
+ let rootId;
143
+ for (const [id, attrs] of g.allNodes()) {
144
+ if (attrs.name === params.target || attrs.path.endsWith(params.target)) {
145
+ rootId = id;
146
+ break;
147
+ }
148
+ }
149
+ if (!rootId) {
150
+ return { nodes: [], edges: [], error: `Target not found: ${params.target}` };
151
+ }
152
+ const direction = (params.direction ?? "both");
153
+ const { nodeIds, edges } = g.subgraph(rootId, params.depth ?? 2, direction);
154
+ const nodes = [...nodeIds].map((id) => {
155
+ const attrs = g.getNode(id);
156
+ return { id, chunkType: attrs.chunkType, name: attrs.name, path: attrs.path };
157
+ });
158
+ return {
159
+ nodes,
160
+ edges: edges.map((e) => ({
161
+ from: e.from,
162
+ to: e.to,
163
+ edgeType: e.attrs.edgeType,
164
+ weight: e.attrs.weight,
165
+ })),
166
+ };
167
+ }
168
+ async graphDistances(params) {
169
+ const pid = projectId(params.projectPath);
170
+ const g = await this._getGraph(pid);
171
+ const distances = g.shortestPathDistances(params.activeChunkId, params.candidateIds);
172
+ return { distances };
173
+ }
174
+ async remember(params) {
175
+ if (!this._initialized)
176
+ await this.init();
177
+ const pid = projectId(params.projectPath);
178
+ upsertProject(this.db, pid, params.projectPath);
179
+ const id = randomUUID();
180
+ this.db.prepare(`
181
+ INSERT INTO memories (id, project_id, session_id, memory_type, content, relevance_score, created_at)
182
+ VALUES (?, ?, ?, ?, ?, 1.0, ?)
183
+ `).run(id, pid, params.sessionId, params.memoryType, params.content, Date.now());
184
+ // Store embedding so memories are semantically searchable
185
+ try {
186
+ const vector = await embedSingle(params.content);
187
+ upsertMemoryEmbedding(this.db, id, vector, MODEL);
188
+ }
189
+ catch {
190
+ // non-critical — memory is stored even without embedding
191
+ }
192
+ return { id, success: true };
193
+ }
194
+ getCoEditScores(params) {
195
+ const pid = projectId(params.projectPath);
196
+ return getCoEditScores(this.db, pid, params.activeFilePath, params.candidatePaths);
197
+ }
198
+ async getFileGraph(params) {
199
+ const pid = projectId(params.projectPath);
200
+ const files = this.db.prepare(`
201
+ SELECT f.id, f.path, COALESCE(f.language, 'unknown') as language, COUNT(c.id) as chunk_count
202
+ FROM files f
203
+ LEFT JOIN chunks c ON c.file_id = f.id
204
+ WHERE f.project_id = ?
205
+ GROUP BY f.id
206
+ ORDER BY chunk_count DESC
207
+ LIMIT 400
208
+ `).all(pid);
209
+ const edges = this.db.prepare(`
210
+ SELECT DISTINCT f1.id AS from_file, f2.id AS to_file
211
+ FROM graph_edges ge
212
+ JOIN chunks c1 ON c1.id = ge.from_chunk
213
+ JOIN files f1 ON f1.id = c1.file_id
214
+ JOIN chunks c2 ON c2.id = ge.to_chunk
215
+ JOIN files f2 ON f2.id = c2.file_id
216
+ WHERE f1.project_id = ? AND f1.id != f2.id
217
+ `).all(pid);
218
+ // Only include edges where both nodes are in our limited node set
219
+ const nodeIds = new Set(files.map((f) => f.id));
220
+ const filteredEdges = edges.filter((e) => nodeIds.has(e.from_file) && nodeIds.has(e.to_file));
221
+ return {
222
+ nodes: files.map((f) => ({
223
+ id: f.id,
224
+ path: f.path,
225
+ language: f.language,
226
+ chunkCount: f.chunk_count,
227
+ })),
228
+ edges: filteredEdges.map((e) => ({ from: e.from_file, to: e.to_file })),
229
+ };
230
+ }
231
+ async listMemories(params) {
232
+ const pid = projectId(params.projectPath);
233
+ const memories = this.db.prepare(`
234
+ SELECT id, memory_type, content, session_id, relevance_score, created_at
235
+ FROM memories
236
+ WHERE project_id = ?
237
+ ORDER BY created_at DESC
238
+ `).all(pid);
239
+ return { memories };
240
+ }
241
+ async deleteMemory(params) {
242
+ const pid = projectId(params.projectPath);
243
+ const result = this.db
244
+ .prepare(`DELETE FROM memories WHERE id = ? AND project_id = ?`)
245
+ .run(params.memoryId, pid);
246
+ return { success: result.changes > 0 };
247
+ }
248
+ close() {
249
+ this.db.close();
250
+ }
251
+ // ── Private helpers ──────────────────────────────────────────────────────────
252
+ async _getEmbeddings(projectId) {
253
+ if (this.embeddingsCache.has(projectId))
254
+ return this.embeddingsCache.get(projectId);
255
+ const candidates = getAllEmbeddings(this.db, projectId);
256
+ this.embeddingsCache.set(projectId, candidates);
257
+ return candidates;
258
+ }
259
+ async _getGraph(projectId) {
260
+ if (this.graphCache.has(projectId))
261
+ return this.graphCache.get(projectId);
262
+ const g = new DiGraph();
263
+ // Add all chunks as nodes
264
+ const chunks = this.db.prepare(`
265
+ SELECT c.id, c.chunk_type, c.name, f.path
266
+ FROM chunks c JOIN files f ON f.id = c.file_id
267
+ WHERE f.project_id = ?
268
+ `).all(projectId);
269
+ for (const c of chunks) {
270
+ g.addNode(c.id, { chunkType: c.chunk_type, name: c.name, path: c.path });
271
+ }
272
+ // Add edges
273
+ const edges = getProjectGraphEdges(this.db, projectId);
274
+ for (const e of edges) {
275
+ g.addEdge(e.from_chunk, e.to_chunk, { edgeType: e.edge_type, weight: e.weight });
276
+ }
277
+ this.graphCache.set(projectId, g);
278
+ return g;
279
+ }
280
+ async _embedNewChunks(pid) {
281
+ // Find chunks without embeddings
282
+ const unembedded = this.db.prepare(`
283
+ SELECT c.id, c.content
284
+ FROM chunks c
285
+ JOIN files f ON f.id = c.file_id
286
+ WHERE f.project_id = ?
287
+ AND c.id NOT IN (SELECT chunk_id FROM embeddings)
288
+ `).all(pid);
289
+ if (unembedded.length === 0)
290
+ return;
291
+ process.stderr.write(`[engine] embedding ${unembedded.length} new chunks...\n`);
292
+ const texts = unembedded.map((c) => c.content);
293
+ const vectors = await embedTexts(texts);
294
+ const stmt = this.db.prepare(`
295
+ INSERT OR REPLACE INTO embeddings (chunk_id, model, vector, dims, created_at)
296
+ VALUES (?, ?, ?, ?, ?)
297
+ `);
298
+ const { vectorToBlob } = await import("./storage/sqlite.js");
299
+ this.db.exec("BEGIN");
300
+ try {
301
+ for (let i = 0; i < unembedded.length; i++) {
302
+ stmt.run(unembedded[i].id, MODEL, vectorToBlob(vectors[i]), vectors[i].length, Date.now());
303
+ }
304
+ this.db.exec("COMMIT");
305
+ }
306
+ catch (err) {
307
+ this.db.exec("ROLLBACK");
308
+ throw err;
309
+ }
310
+ // Invalidate embeddings cache
311
+ this.embeddingsCache.delete(pid);
312
+ }
313
+ }
314
+ //# sourceMappingURL=engine.js.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=engine.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine.test.d.ts","sourceRoot":"","sources":["../src/engine.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,9 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { ContextEngine } from "../src/engine";
3
+ describe("ContextEngine", () => {
4
+ it("should instantiate without errors", () => {
5
+ const engine = new ContextEngine();
6
+ expect(engine).toBeDefined();
7
+ });
8
+ });
9
+ //# sourceMappingURL=engine.test.js.map
@@ -0,0 +1,46 @@
1
+ export interface NodeAttrs {
2
+ chunkType: string;
3
+ name: string | null;
4
+ path: string;
5
+ }
6
+ export interface EdgeAttrs {
7
+ edgeType: string;
8
+ weight: number;
9
+ }
10
+ export declare class DiGraph {
11
+ private nodes;
12
+ private outEdges;
13
+ private inEdges;
14
+ addNode(id: string, attrs: NodeAttrs): void;
15
+ addEdge(from: string, to: string, attrs: EdgeAttrs): void;
16
+ has(id: string): boolean;
17
+ getNode(id: string): NodeAttrs | undefined;
18
+ successors(id: string): string[];
19
+ predecessors(id: string): string[];
20
+ getEdge(from: string, to: string): EdgeAttrs | undefined;
21
+ allNodes(): Array<[string, NodeAttrs]>;
22
+ allEdges(): Array<{
23
+ from: string;
24
+ to: string;
25
+ attrs: EdgeAttrs;
26
+ }>;
27
+ nodeCount(): number;
28
+ /**
29
+ * BFS subgraph starting from `rootId`, up to `depth` hops.
30
+ * direction: "outgoing" | "incoming" | "both"
31
+ */
32
+ subgraph(rootId: string, depth: number, direction: "outgoing" | "incoming" | "both"): {
33
+ nodeIds: Set<string>;
34
+ edges: Array<{
35
+ from: string;
36
+ to: string;
37
+ attrs: EdgeAttrs;
38
+ }>;
39
+ };
40
+ /**
41
+ * Compute normalized shortest-path distances from `sourceId` to each candidate.
42
+ * Uses BFS on undirected version. Returns 0–1 where 0 = same node, 1 = unreachable.
43
+ */
44
+ shortestPathDistances(sourceId: string, targetIds: string[]): Record<string, number>;
45
+ }
46
+ //# sourceMappingURL=graph.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph.d.ts","sourceRoot":"","sources":["../../src/graph/graph.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,SAAS;IACxB,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,SAAS;IACxB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,qBAAa,OAAO;IAClB,OAAO,CAAC,KAAK,CAAgC;IAC7C,OAAO,CAAC,QAAQ,CAA6C;IAC7D,OAAO,CAAC,OAAO,CAAkC;IAEjD,OAAO,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,GAAG,IAAI;IAM3C,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,GAAG,IAAI;IAOzD,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO;IAIxB,OAAO,CAAC,EAAE,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS;IAI1C,UAAU,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,EAAE;IAIhC,YAAY,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,EAAE;IAIlC,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS;IAIxD,QAAQ,IAAI,KAAK,CAAC,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;IAItC,QAAQ,IAAI,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,SAAS,CAAA;KAAE,CAAC;IAUjE,SAAS,IAAI,MAAM;IAInB;;;OAGG;IACH,QAAQ,CACN,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,UAAU,GAAG,UAAU,GAAG,MAAM,GAC1C;QAAE,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;QAAC,KAAK,EAAE,KAAK,CAAC;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,EAAE,EAAE,MAAM,CAAC;YAAC,KAAK,EAAE,SAAS,CAAA;SAAE,CAAC,CAAA;KAAE;IA8BzF;;;OAGG;IACH,qBAAqB,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;CA0BrF"}
@@ -0,0 +1,110 @@
1
+ export class DiGraph {
2
+ nodes = new Map();
3
+ outEdges = new Map();
4
+ inEdges = new Map();
5
+ addNode(id, attrs) {
6
+ this.nodes.set(id, attrs);
7
+ if (!this.outEdges.has(id))
8
+ this.outEdges.set(id, new Map());
9
+ if (!this.inEdges.has(id))
10
+ this.inEdges.set(id, new Set());
11
+ }
12
+ addEdge(from, to, attrs) {
13
+ if (!this.outEdges.has(from))
14
+ this.outEdges.set(from, new Map());
15
+ if (!this.inEdges.has(to))
16
+ this.inEdges.set(to, new Set());
17
+ this.outEdges.get(from).set(to, attrs);
18
+ this.inEdges.get(to).add(from);
19
+ }
20
+ has(id) {
21
+ return this.nodes.has(id);
22
+ }
23
+ getNode(id) {
24
+ return this.nodes.get(id);
25
+ }
26
+ successors(id) {
27
+ return [...(this.outEdges.get(id)?.keys() ?? [])];
28
+ }
29
+ predecessors(id) {
30
+ return [...(this.inEdges.get(id) ?? [])];
31
+ }
32
+ getEdge(from, to) {
33
+ return this.outEdges.get(from)?.get(to);
34
+ }
35
+ allNodes() {
36
+ return [...this.nodes.entries()];
37
+ }
38
+ allEdges() {
39
+ const result = [];
40
+ for (const [from, tos] of this.outEdges) {
41
+ for (const [to, attrs] of tos) {
42
+ result.push({ from, to, attrs });
43
+ }
44
+ }
45
+ return result;
46
+ }
47
+ nodeCount() {
48
+ return this.nodes.size;
49
+ }
50
+ /**
51
+ * BFS subgraph starting from `rootId`, up to `depth` hops.
52
+ * direction: "outgoing" | "incoming" | "both"
53
+ */
54
+ subgraph(rootId, depth, direction) {
55
+ const visited = new Set([rootId]);
56
+ const queue = [{ id: rootId, d: 0 }];
57
+ const edges = [];
58
+ while (queue.length > 0) {
59
+ const { id, d } = queue.shift();
60
+ if (d >= depth)
61
+ continue;
62
+ const neighbors = [];
63
+ if (direction === "outgoing" || direction === "both")
64
+ neighbors.push(...this.successors(id));
65
+ if (direction === "incoming" || direction === "both")
66
+ neighbors.push(...this.predecessors(id));
67
+ for (const neighbor of neighbors) {
68
+ if (!visited.has(neighbor)) {
69
+ visited.add(neighbor);
70
+ queue.push({ id: neighbor, d: d + 1 });
71
+ }
72
+ // collect edges in original direction
73
+ if (this.outEdges.get(id)?.has(neighbor)) {
74
+ edges.push({ from: id, to: neighbor, attrs: this.getEdge(id, neighbor) });
75
+ }
76
+ else if (this.outEdges.get(neighbor)?.has(id)) {
77
+ edges.push({ from: neighbor, to: id, attrs: this.getEdge(neighbor, id) });
78
+ }
79
+ }
80
+ }
81
+ return { nodeIds: visited, edges };
82
+ }
83
+ /**
84
+ * Compute normalized shortest-path distances from `sourceId` to each candidate.
85
+ * Uses BFS on undirected version. Returns 0–1 where 0 = same node, 1 = unreachable.
86
+ */
87
+ shortestPathDistances(sourceId, targetIds) {
88
+ const dist = new Map();
89
+ const queue = [{ id: sourceId, d: 0 }];
90
+ dist.set(sourceId, 0);
91
+ while (queue.length > 0) {
92
+ const { id, d } = queue.shift();
93
+ const neighbors = [...this.successors(id), ...this.predecessors(id)];
94
+ for (const n of neighbors) {
95
+ if (!dist.has(n)) {
96
+ dist.set(n, d + 1);
97
+ queue.push({ id: n, d: d + 1 });
98
+ }
99
+ }
100
+ }
101
+ const maxDist = Math.max(1, ...dist.values());
102
+ const result = {};
103
+ for (const targetId of targetIds) {
104
+ const d = dist.get(targetId);
105
+ result[targetId] = d === undefined ? 1.0 : Math.min(1.0, d / maxDist);
106
+ }
107
+ return result;
108
+ }
109
+ }
110
+ //# sourceMappingURL=graph.js.map
@@ -0,0 +1,4 @@
1
+ export { ContextEngine } from "./engine.js";
2
+ export { openDatabase } from "./storage/sqlite.js";
3
+ export type { IContextEngine, IndexResult, SearchResult, StatusResult, SubgraphResult, Chunk, EmbeddingCandidate, GraphNode, GraphEdge, MemorySearchResult, MemoryRecord, } from "./types.js";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,YAAY,EACV,cAAc,EACd,WAAW,EACX,YAAY,EACZ,YAAY,EACZ,cAAc,EACd,KAAK,EACL,kBAAkB,EAClB,SAAS,EACT,SAAS,EACT,kBAAkB,EAClB,YAAY,GACb,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { ContextEngine } from "./engine.js";
2
+ export { openDatabase } from "./storage/sqlite.js";
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,12 @@
1
+ import Parser from "web-tree-sitter";
2
+ import type { Chunk } from "../types.js";
3
+ export declare function extractChunks(source: string, fileId: string, language: string, tree: Parser.Tree): Chunk[];
4
+ /**
5
+ * Extract import/dependency edges from source for graph building.
6
+ * Returns pairs of [importerChunkName, importedModulePath].
7
+ */
8
+ export declare function extractImports(source: string, language: string, tree: Parser.Tree): Array<{
9
+ from: string;
10
+ to: string;
11
+ }>;
12
+ //# sourceMappingURL=chunker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chunker.d.ts","sourceRoot":"","sources":["../../src/indexer/chunker.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,iBAAiB,CAAC;AAErC,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAqDzC,wBAAgB,aAAa,CAC3B,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,MAAM,CAAC,IAAI,GAChB,KAAK,EAAE,CAuBT;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,MAAM,CAAC,IAAI,GAChB,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAAC,CAqBrC"}