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,353 @@
1
+ import { DatabaseSync } from "node:sqlite";
2
+ import { mkdirSync } from "fs";
3
+ import { dirname } from "path";
4
+ import { applySchema } from "./schema.js";
5
+ import type { Chunk, EmbeddingCandidate, GraphEdge } from "../types.js";
6
+
7
+ export function openDatabase(dbPath: string): DatabaseSync {
8
+ mkdirSync(dirname(dbPath), { recursive: true });
9
+ const db = new DatabaseSync(dbPath);
10
+ db.exec("PRAGMA journal_mode = WAL");
11
+ db.exec("PRAGMA foreign_keys = ON");
12
+ applySchema(db);
13
+ return db;
14
+ }
15
+
16
+ // ── Vector serialization ──────────────────────────────────────────────────────
17
+ // Bit-compatible with Python's struct.pack(f"{n}f", *vector) — little-endian f32
18
+
19
+ export function vectorToBlob(vector: Float32Array): Buffer {
20
+ return Buffer.from(vector.buffer, vector.byteOffset, vector.byteLength);
21
+ }
22
+
23
+ export function blobToVector(blob: Buffer | Uint8Array): Float32Array {
24
+ const buf = Buffer.isBuffer(blob) ? blob : Buffer.from(blob);
25
+ const copy = Buffer.allocUnsafe(buf.length);
26
+ buf.copy(copy);
27
+ return new Float32Array(copy.buffer);
28
+ }
29
+
30
+ function tx(db: DatabaseSync, fn: () => void): void {
31
+ db.exec("BEGIN");
32
+ try {
33
+ fn();
34
+ db.exec("COMMIT");
35
+ } catch (err) {
36
+ db.exec("ROLLBACK");
37
+ throw err;
38
+ }
39
+ }
40
+
41
+ // ── Project ───────────────────────────────────────────────────────────────────
42
+
43
+ export function upsertProject(db: DatabaseSync, projectId: string, rootPath: string): void {
44
+ db.prepare(`
45
+ INSERT INTO projects (id, name, root_path, created_at)
46
+ VALUES (?, ?, ?, ?)
47
+ ON CONFLICT(id) DO UPDATE SET root_path = excluded.root_path
48
+ `).run(projectId, rootPath, rootPath, Date.now());
49
+ }
50
+
51
+ export function markProjectIndexed(db: DatabaseSync, projectId: string): void {
52
+ db.prepare(`UPDATE projects SET indexed_at = ? WHERE id = ?`).run(Date.now(), projectId);
53
+ }
54
+
55
+ export function getProject(
56
+ db: DatabaseSync,
57
+ projectId: string
58
+ ): { indexed_at: number | null; root_path: string } | undefined {
59
+ return db
60
+ .prepare(`SELECT root_path, indexed_at FROM projects WHERE id = ?`)
61
+ .get(projectId) as { root_path: string; indexed_at: number | null } | undefined;
62
+ }
63
+
64
+ // ── Files ─────────────────────────────────────────────────────────────────────
65
+
66
+ export function upsertFile(
67
+ db: DatabaseSync,
68
+ fileId: string,
69
+ projectId: string,
70
+ relPath: string,
71
+ language: string,
72
+ hash: string,
73
+ lastModified: number
74
+ ): void {
75
+ db.prepare(`
76
+ INSERT INTO files (id, project_id, path, language, hash, last_modified)
77
+ VALUES (?, ?, ?, ?, ?, ?)
78
+ ON CONFLICT(project_id, path) DO UPDATE SET
79
+ id = excluded.id,
80
+ language = excluded.language,
81
+ hash = excluded.hash,
82
+ last_modified = excluded.last_modified
83
+ `).run(fileId, projectId, relPath, language, hash, lastModified);
84
+ }
85
+
86
+ export function getFileHash(
87
+ db: DatabaseSync,
88
+ projectId: string,
89
+ relPath: string
90
+ ): string | undefined {
91
+ const row = db
92
+ .prepare(`SELECT hash FROM files WHERE project_id = ? AND path = ?`)
93
+ .get(projectId, relPath) as { hash: string } | undefined;
94
+ return row?.hash;
95
+ }
96
+
97
+ export function deleteFileChunks(db: DatabaseSync, fileId: string): void {
98
+ db.prepare(`DELETE FROM chunks WHERE file_id = ?`).run(fileId);
99
+ }
100
+
101
+ export function getProjectFiles(
102
+ db: DatabaseSync,
103
+ projectId: string
104
+ ): Array<{ id: string; path: string }> {
105
+ return db
106
+ .prepare(`SELECT id, path FROM files WHERE project_id = ?`)
107
+ .all(projectId) as Array<{ id: string; path: string }>;
108
+ }
109
+
110
+ // ── Chunks ────────────────────────────────────────────────────────────────────
111
+
112
+ export function insertChunks(db: DatabaseSync, chunks: Chunk[]): void {
113
+ const stmt = db.prepare(`
114
+ INSERT OR REPLACE INTO chunks
115
+ (id, file_id, chunk_type, name, content, start_line, end_line, token_count)
116
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
117
+ `);
118
+ tx(db, () => {
119
+ for (const c of chunks) {
120
+ stmt.run(c.id, c.fileId, c.chunkType, c.name ?? null, c.content, c.startLine, c.endLine, c.tokenCount);
121
+ }
122
+ });
123
+ }
124
+
125
+ // ── Embeddings ────────────────────────────────────────────────────────────────
126
+
127
+ export function upsertEmbeddings(
128
+ db: DatabaseSync,
129
+ entries: Array<{ chunkId: string; vector: Float32Array; model: string }>
130
+ ): void {
131
+ const stmt = db.prepare(`
132
+ INSERT OR REPLACE INTO embeddings (chunk_id, model, vector, dims, created_at)
133
+ VALUES (?, ?, ?, ?, ?)
134
+ `);
135
+ tx(db, () => {
136
+ for (const item of entries) {
137
+ stmt.run(item.chunkId, item.model, vectorToBlob(item.vector), item.vector.length, Date.now());
138
+ }
139
+ });
140
+ }
141
+
142
+ export function getAllEmbeddings(db: DatabaseSync, projectId: string): EmbeddingCandidate[] {
143
+ const rows = db.prepare(`
144
+ SELECT
145
+ e.chunk_id,
146
+ e.vector,
147
+ c.content,
148
+ c.chunk_type,
149
+ c.name,
150
+ c.start_line,
151
+ c.end_line,
152
+ f.path,
153
+ f.last_modified
154
+ FROM embeddings e
155
+ JOIN chunks c ON c.id = e.chunk_id
156
+ JOIN files f ON f.id = c.file_id
157
+ WHERE f.project_id = ?
158
+ `).all(projectId) as Array<{
159
+ chunk_id: string;
160
+ vector: Buffer;
161
+ content: string;
162
+ chunk_type: string;
163
+ name: string | null;
164
+ start_line: number;
165
+ end_line: number;
166
+ path: string;
167
+ last_modified: number | null;
168
+ }>;
169
+
170
+ return rows.map((r) => ({
171
+ chunkId: r.chunk_id,
172
+ vector: blobToVector(r.vector),
173
+ content: r.content,
174
+ chunkType: r.chunk_type,
175
+ name: r.name,
176
+ startLine: r.start_line,
177
+ endLine: r.end_line,
178
+ path: r.path,
179
+ lastModified: r.last_modified ?? undefined,
180
+ }));
181
+ }
182
+
183
+ export function getProjectStats(db: DatabaseSync, projectId: string): { files: number; chunks: number } {
184
+ const files = (db
185
+ .prepare(`SELECT COUNT(*) as n FROM files WHERE project_id = ?`)
186
+ .get(projectId) as { n: number }).n;
187
+ const chunks = (db
188
+ .prepare(`
189
+ SELECT COUNT(*) as n FROM chunks c
190
+ JOIN files f ON f.id = c.file_id
191
+ WHERE f.project_id = ?
192
+ `)
193
+ .get(projectId) as { n: number }).n;
194
+ return { files, chunks };
195
+ }
196
+
197
+ // ── Graph edges ───────────────────────────────────────────────────────────────
198
+
199
+ export function insertGraphEdges(db: DatabaseSync, projectId: string, edges: GraphEdge[]): void {
200
+ const stmt = db.prepare(`
201
+ INSERT OR REPLACE INTO graph_edges (id, project_id, from_chunk, to_chunk, edge_type, weight)
202
+ VALUES (?, ?, ?, ?, ?, ?)
203
+ `);
204
+ tx(db, () => {
205
+ for (const e of edges) {
206
+ stmt.run(`${e.from}:${e.to}:${e.edgeType}`, projectId, e.from, e.to, e.edgeType, e.weight);
207
+ }
208
+ });
209
+ }
210
+
211
+ export function getProjectGraphEdges(
212
+ db: DatabaseSync,
213
+ projectId: string
214
+ ): Array<{ from_chunk: string; to_chunk: string; edge_type: string; weight: number }> {
215
+ return db
216
+ .prepare(`SELECT from_chunk, to_chunk, edge_type, weight FROM graph_edges WHERE project_id = ?`)
217
+ .all(projectId) as Array<{
218
+ from_chunk: string;
219
+ to_chunk: string;
220
+ edge_type: string;
221
+ weight: number;
222
+ }>;
223
+ }
224
+
225
+ export function getFileRepresentativeChunk(db: DatabaseSync, fileId: string): string | undefined {
226
+ const row = db
227
+ .prepare(`SELECT id FROM chunks WHERE file_id = ? ORDER BY start_line LIMIT 1`)
228
+ .get(fileId) as { id: string } | undefined;
229
+ return row?.id;
230
+ }
231
+
232
+ export function deleteProjectGraphEdges(db: DatabaseSync, projectId: string): void {
233
+ db.prepare(`DELETE FROM graph_edges WHERE project_id = ?`).run(projectId);
234
+ }
235
+
236
+ export function upsertMemoryEmbedding(
237
+ db: DatabaseSync,
238
+ memoryId: string,
239
+ vector: Float32Array,
240
+ model: string
241
+ ): void {
242
+ db.prepare(`
243
+ INSERT OR REPLACE INTO memory_embeddings (memory_id, model, vector, dims, created_at)
244
+ VALUES (?, ?, ?, ?, ?)
245
+ `).run(memoryId, model, vectorToBlob(vector), vector.length, Date.now());
246
+ }
247
+
248
+ export function getMemoryEmbeddings(
249
+ db: DatabaseSync,
250
+ projectId: string
251
+ ): Array<{ memoryId: string; vector: Float32Array; memoryType: string; content: string; createdAt: number }> {
252
+ const rows = db.prepare(`
253
+ SELECT me.memory_id, me.vector, m.memory_type, m.content, m.created_at
254
+ FROM memory_embeddings me
255
+ JOIN memories m ON m.id = me.memory_id
256
+ WHERE m.project_id = ?
257
+ ORDER BY m.created_at DESC
258
+ `).all(projectId) as Array<{
259
+ memory_id: string;
260
+ vector: Buffer;
261
+ memory_type: string;
262
+ content: string;
263
+ created_at: number;
264
+ }>;
265
+
266
+ return rows.map((r) => ({
267
+ memoryId: r.memory_id,
268
+ vector: blobToVector(r.vector),
269
+ memoryType: r.memory_type,
270
+ content: r.content,
271
+ createdAt: r.created_at,
272
+ }));
273
+ }
274
+
275
+ // ── Co-edit tracking ──────────────────────────────────────────────────────────
276
+
277
+ /**
278
+ * Record that a set of files were edited in the same session window.
279
+ * Increments the co-edit count for every pair in the set.
280
+ */
281
+ export function recordCoEdits(db: DatabaseSync, projectId: string, relPaths: string[]): void {
282
+ if (relPaths.length < 2) return;
283
+
284
+ const stmt = db.prepare(`
285
+ INSERT INTO file_coedits (id, project_id, file_a, file_b, count, last_seen)
286
+ VALUES (?, ?, ?, ?, 1, ?)
287
+ ON CONFLICT(project_id, file_a, file_b) DO UPDATE SET
288
+ count = count + 1,
289
+ last_seen = excluded.last_seen
290
+ `);
291
+
292
+ const now = Date.now();
293
+ tx(db, () => {
294
+ for (let i = 0; i < relPaths.length; i++) {
295
+ for (let j = i + 1; j < relPaths.length; j++) {
296
+ // Store canonically sorted to avoid (A,B) and (B,A) duplicates
297
+ const [a, b] = [relPaths[i], relPaths[j]].sort();
298
+ stmt.run(`${projectId}:${a}:${b}`, projectId, a, b, now);
299
+ }
300
+ }
301
+ });
302
+ }
303
+
304
+ /**
305
+ * For a given active file, return normalized co-edit scores [0,1] for candidate paths.
306
+ * Score of 1 = always edited together with activeFilePath; 0 = never.
307
+ */
308
+ export function getCoEditScores(
309
+ db: DatabaseSync,
310
+ projectId: string,
311
+ activeFilePath: string,
312
+ candidatePaths: string[]
313
+ ): Record<string, number> {
314
+ if (candidatePaths.length === 0) return {};
315
+
316
+ const rows = db.prepare(`
317
+ SELECT
318
+ CASE WHEN file_a = ? THEN file_b ELSE file_a END AS other_file,
319
+ count
320
+ FROM file_coedits
321
+ WHERE project_id = ? AND (file_a = ? OR file_b = ?)
322
+ `).all(activeFilePath, projectId, activeFilePath, activeFilePath) as Array<{
323
+ other_file: string;
324
+ count: number;
325
+ }>;
326
+
327
+ if (rows.length === 0) return {};
328
+
329
+ const maxCount = Math.max(...rows.map((r) => r.count));
330
+ const scoreMap = new Map(rows.map((r) => [r.other_file, r.count / maxCount]));
331
+
332
+ const result: Record<string, number> = {};
333
+ for (const path of candidatePaths) {
334
+ result[path] = scoreMap.get(path) ?? 0;
335
+ }
336
+ return result;
337
+ }
338
+
339
+ export function getChunksByIds(
340
+ db: DatabaseSync,
341
+ ids: string[]
342
+ ): Array<{ id: string; chunk_type: string; name: string | null; path: string }> {
343
+ if (ids.length === 0) return [];
344
+ const placeholders = ids.map(() => "?").join(",");
345
+ return db
346
+ .prepare(`
347
+ SELECT c.id, c.chunk_type, c.name, f.path
348
+ FROM chunks c
349
+ JOIN files f ON f.id = c.file_id
350
+ WHERE c.id IN (${placeholders})
351
+ `)
352
+ .all(...ids) as Array<{ id: string; chunk_type: string; name: string | null; path: string }>;
353
+ }
package/src/types.ts ADDED
@@ -0,0 +1,137 @@
1
+ export interface Chunk {
2
+ id: string;
3
+ fileId: string;
4
+ chunkType: "function" | "class" | "module";
5
+ name: string | null;
6
+ content: string;
7
+ startLine: number;
8
+ endLine: number;
9
+ tokenCount: number;
10
+ metadata?: Record<string, unknown>;
11
+ }
12
+
13
+ export interface EmbeddingCandidate {
14
+ chunkId: string;
15
+ vector: Float32Array;
16
+ content: string;
17
+ chunkType: string;
18
+ name: string | null;
19
+ path: string;
20
+ startLine: number;
21
+ endLine: number;
22
+ lastModified?: number;
23
+ }
24
+
25
+ export interface SearchResult {
26
+ chunk_id: string;
27
+ score: number;
28
+ content: string;
29
+ chunk_type: string;
30
+ name: string | null;
31
+ path: string;
32
+ start_line: number;
33
+ end_line: number;
34
+ last_modified?: number;
35
+ }
36
+
37
+ export interface MemorySearchResult {
38
+ id: string;
39
+ memory_type: string;
40
+ content: string;
41
+ score: number;
42
+ created_at: number;
43
+ }
44
+
45
+ export interface MemoryRecord {
46
+ id: string;
47
+ memory_type: string;
48
+ content: string;
49
+ session_id: string | null;
50
+ relevance_score: number;
51
+ created_at: number;
52
+ }
53
+
54
+ export interface GraphNode {
55
+ id: string;
56
+ chunkType: string;
57
+ name: string | null;
58
+ path: string;
59
+ }
60
+
61
+ export interface GraphEdge {
62
+ from: string;
63
+ to: string;
64
+ edgeType: "calls" | "extends" | "imports";
65
+ weight: number;
66
+ }
67
+
68
+ export interface SubgraphResult {
69
+ nodes: GraphNode[];
70
+ edges: GraphEdge[];
71
+ error?: string;
72
+ }
73
+
74
+ export interface IndexResult {
75
+ success: boolean;
76
+ projectId: string;
77
+ projectPath: string;
78
+ filesIndexed: number;
79
+ filesSkipped: number;
80
+ totalFiles: number;
81
+ error?: string;
82
+ }
83
+
84
+ export interface StatusResult {
85
+ indexed: boolean;
86
+ projectId?: string;
87
+ projectPath: string;
88
+ files?: number;
89
+ chunks?: number;
90
+ indexedAt?: number;
91
+ }
92
+
93
+ export interface IContextEngine {
94
+ init(): Promise<void>;
95
+ index(params: { projectPath: string; force?: boolean; paths?: string[] }): Promise<IndexResult>;
96
+ search(params: {
97
+ query: string;
98
+ projectPath: string;
99
+ k?: number;
100
+ filterType?: string;
101
+ }): Promise<{ results: SearchResult[] }>;
102
+ status(params: { projectPath: string }): Promise<StatusResult>;
103
+ graph(params: {
104
+ target: string;
105
+ projectPath: string;
106
+ depth?: number;
107
+ direction?: string;
108
+ }): Promise<SubgraphResult>;
109
+ graphDistances(params: {
110
+ projectPath: string;
111
+ activeChunkId: string;
112
+ candidateIds: string[];
113
+ }): Promise<{ distances: Record<string, number> }>;
114
+ remember(params: {
115
+ projectPath: string;
116
+ sessionId: string;
117
+ memoryType: "decision" | "pattern" | "todo" | "context_note";
118
+ content: string;
119
+ }): Promise<{ id: string; success: boolean }>;
120
+ searchMemories(params: {
121
+ query: string;
122
+ projectPath: string;
123
+ k?: number;
124
+ }): Promise<{ results: MemorySearchResult[] }>;
125
+ getCoEditScores(params: {
126
+ projectPath: string;
127
+ activeFilePath: string;
128
+ candidatePaths: string[];
129
+ }): Record<string, number>;
130
+ getFileGraph(params: { projectPath: string }): Promise<{
131
+ nodes: Array<{ id: string; path: string; language: string; chunkCount: number }>;
132
+ edges: Array<{ from: string; to: string }>;
133
+ }>;
134
+ listMemories(params: { projectPath: string }): Promise<{ memories: MemoryRecord[] }>;
135
+ deleteMemory(params: { projectPath: string; memoryId: string }): Promise<{ success: boolean }>;
136
+ close(): void;
137
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "lib": ["ES2022"],
7
+ "outDir": "dist",
8
+ "rootDir": "src",
9
+ "declaration": true,
10
+ "declarationMap": true,
11
+ "sourceMap": true,
12
+ "strict": true,
13
+ "esModuleInterop": true,
14
+ "skipLibCheck": true,
15
+ "resolveJsonModule": true
16
+ },
17
+ "include": ["src"],
18
+ "exclude": ["node_modules", "dist"]
19
+ }