context-pilot-engine 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/engine.d.ts +11 -64
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +110 -204
- package/dist/engine.js.map +1 -0
- package/dist/graph/graph.js.map +1 -0
- package/dist/history/backtest.d.ts +127 -0
- package/dist/history/backtest.d.ts.map +1 -0
- package/dist/history/backtest.js +290 -0
- package/dist/history/backtest.js.map +1 -0
- package/dist/history/cochange.d.ts +91 -0
- package/dist/history/cochange.d.ts.map +1 -0
- package/dist/history/cochange.js +149 -0
- package/dist/history/cochange.js.map +1 -0
- package/dist/history/diff.d.ts +21 -0
- package/dist/history/diff.d.ts.map +1 -0
- package/dist/history/diff.js +57 -0
- package/dist/history/diff.js.map +1 -0
- package/dist/history/git.d.ts +34 -0
- package/dist/history/git.d.ts.map +1 -0
- package/dist/history/git.js +92 -0
- package/dist/history/git.js.map +1 -0
- package/dist/history/miner.d.ts +9 -0
- package/dist/history/miner.d.ts.map +1 -0
- package/dist/history/miner.js +70 -0
- package/dist/history/miner.js.map +1 -0
- package/dist/impact/impact.d.ts +55 -0
- package/dist/impact/impact.d.ts.map +1 -0
- package/dist/impact/impact.js +139 -0
- package/dist/impact/impact.js.map +1 -0
- package/dist/index.d.ts +11 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -1
- package/dist/index.js.map +1 -0
- package/dist/indexer/chunker.d.ts +9 -6
- package/dist/indexer/chunker.d.ts.map +1 -1
- package/dist/indexer/chunker.js +46 -11
- package/dist/indexer/chunker.js.map +1 -0
- package/dist/indexer/imports.d.ts +24 -0
- package/dist/indexer/imports.d.ts.map +1 -0
- package/dist/indexer/imports.js +138 -0
- package/dist/indexer/imports.js.map +1 -0
- package/dist/indexer/indexer.d.ts +15 -0
- package/dist/indexer/indexer.d.ts.map +1 -1
- package/dist/indexer/indexer.js +55 -59
- package/dist/indexer/indexer.js.map +1 -0
- package/dist/indexer/languages.d.ts +2 -2
- package/dist/indexer/languages.d.ts.map +1 -1
- package/dist/indexer/languages.js +10 -0
- package/dist/indexer/languages.js.map +1 -0
- package/dist/storage/schema.js +87 -87
- package/dist/storage/schema.js.map +1 -0
- package/dist/storage/sqlite.d.ts +34 -27
- package/dist/storage/sqlite.d.ts.map +1 -1
- package/dist/storage/sqlite.js +126 -153
- package/dist/storage/sqlite.js.map +1 -0
- package/dist/types.d.ts +86 -97
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -0
- package/package.json +24 -10
- package/dist/embedder/embedder.d.ts +0 -4
- package/dist/embedder/embedder.d.ts.map +0 -1
- package/dist/embedder/embedder.js +0 -37
- package/dist/engine.test.d.ts +0 -2
- package/dist/engine.test.d.ts.map +0 -1
- package/dist/engine.test.js +0 -9
- package/dist/search/search.d.ts +0 -12
- package/dist/search/search.d.ts.map +0 -1
- package/dist/search/search.js +0 -38
- package/src/embedder/embedder.ts +0 -46
- package/src/engine.ts +0 -425
- package/src/graph/graph.ts +0 -136
- package/src/index.ts +0 -15
- package/src/indexer/chunker.ts +0 -115
- package/src/indexer/indexer.ts +0 -297
- package/src/indexer/languages.ts +0 -55
- package/src/search/search.ts +0 -48
- package/src/storage/schema.ts +0 -92
- package/src/storage/sqlite.ts +0 -353
- package/src/types.ts +0 -137
- package/tsconfig.json +0 -19
|
@@ -1,37 +0,0 @@
|
|
|
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
|
package/dist/engine.test.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"engine.test.d.ts","sourceRoot":"","sources":["../src/engine.test.ts"],"names":[],"mappings":""}
|
package/dist/engine.test.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
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
|
package/dist/search/search.d.ts
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
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
|
|
@@ -1 +0,0 @@
|
|
|
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"}
|
package/dist/search/search.js
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
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
|
package/src/embedder/embedder.ts
DELETED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
import { pipeline, env } from "@huggingface/transformers";
|
|
2
|
-
import { join } from "path";
|
|
3
|
-
import { homedir } from "os";
|
|
4
|
-
|
|
5
|
-
const MODEL_NAME = "Xenova/all-MiniLM-L6-v2";
|
|
6
|
-
|
|
7
|
-
type FeatureExtractionPipeline = Awaited<ReturnType<typeof pipeline>>;
|
|
8
|
-
let embedder: FeatureExtractionPipeline | null = null;
|
|
9
|
-
|
|
10
|
-
export async function initEmbedder(): Promise<void> {
|
|
11
|
-
if (embedder) return;
|
|
12
|
-
|
|
13
|
-
// Cache models in ~/.context-pilot/models
|
|
14
|
-
env.cacheDir = join(homedir(), ".context-pilot", "models");
|
|
15
|
-
|
|
16
|
-
// Disable remote model fetching in offline mode if needed
|
|
17
|
-
// env.allowRemoteModels = false;
|
|
18
|
-
|
|
19
|
-
embedder = await pipeline("feature-extraction", MODEL_NAME, {
|
|
20
|
-
dtype: "fp32",
|
|
21
|
-
});
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
export async function embedTexts(texts: string[]): Promise<Float32Array[]> {
|
|
25
|
-
if (!embedder) await initEmbedder();
|
|
26
|
-
|
|
27
|
-
const BATCH_SIZE = 64;
|
|
28
|
-
const results: Float32Array[] = [];
|
|
29
|
-
|
|
30
|
-
for (let i = 0; i < texts.length; i += BATCH_SIZE) {
|
|
31
|
-
const batch = texts.slice(i, i + BATCH_SIZE);
|
|
32
|
-
const output = await (embedder as Function)(batch, { pooling: "mean", normalize: true });
|
|
33
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
34
|
-
const list: number[][] = (output as any).tolist();
|
|
35
|
-
for (const vec of list) {
|
|
36
|
-
results.push(new Float32Array(vec));
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
return results;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export async function embedSingle(text: string): Promise<Float32Array> {
|
|
44
|
-
const [vec] = await embedTexts([text]);
|
|
45
|
-
return vec;
|
|
46
|
-
}
|
package/src/engine.ts
DELETED
|
@@ -1,425 +0,0 @@
|
|
|
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
|
-
}
|