Elffuss BraidHub

kikocis/continue public

cfbd8cf979f7 · 5.4 KiBRawPermalink
1import { BranchAndDir, Chunk, IndexTag, IndexingProgressUpdate } from "../";
2import { RETRIEVAL_PARAMS } from "../util/parameters";
3import { getUriPathBasename } from "../util/uri";
4
5import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex";
6import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
7import {
8 IndexResultType,
9 MarkCompleteCallback,
10 RefreshIndexResults,
11 type CodebaseIndex,
12} from "./types";
13
14export interface RetrieveConfig {
15 tags: BranchAndDir[];
16 text: string;
17 n: number;
18 directory?: string;
19 filterPaths?: string[];
20 bm25Threshold?: number;
21}
22
23export class FullTextSearchCodebaseIndex implements CodebaseIndex {
24 relativeExpectedTime: number = 0.2;
25 static artifactId = "sqliteFts";
26 artifactId: string = FullTextSearchCodebaseIndex.artifactId;
27 pathWeightMultiplier = 10.0;
28
29 private async _createTables(db: DatabaseConnection) {
30 await db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5(
31 path,
32 content,
33 tokenize = 'trigram'
34 )`);
35
36 await db.exec(`CREATE TABLE IF NOT EXISTS fts_metadata (
37 id INTEGER PRIMARY KEY,
38 path TEXT NOT NULL,
39 cacheKey TEXT NOT NULL,
40 chunkId INTEGER NOT NULL,
41 FOREIGN KEY (chunkId) REFERENCES chunks (id),
42 FOREIGN KEY (id) REFERENCES fts (rowid)
43 )`);
44 }
45
46 async *update(
47 tag: IndexTag,
48 results: RefreshIndexResults,
49 markComplete: MarkCompleteCallback,
50 repoName: string | undefined,
51 ): AsyncGenerator<IndexingProgressUpdate, any, unknown> {
52 const db = await SqliteDb.get();
53 await this._createTables(db);
54
55 for (let i = 0; i < results.compute.length; i++) {
56 const item = results.compute[i];
57
58 // Insert chunks
59 const chunks = await db.all(
60 "SELECT * FROM chunks WHERE path = ? AND cacheKey = ?",
61 [item.path, item.cacheKey],
62 );
63
64 for (const chunk of chunks) {
65 const { lastID } = await db.run(
66 "INSERT INTO fts (path, content) VALUES (?, ?)",
67 [item.path, chunk.content],
68 );
69 await db.run(
70 `INSERT INTO fts_metadata (id, path, cacheKey, chunkId)
71 VALUES (?, ?, ?, ?)
72 ON CONFLICT(id) DO UPDATE SET
73 path = excluded.path,
74 cacheKey = excluded.cacheKey,
75 chunkId = excluded.chunkId`,
76 [lastID, item.path, item.cacheKey, chunk.id],
77 );
78 }
79
80 yield {
81 progress: i / results.compute.length,
82 desc: `Indexing ${getUriPathBasename(item.path)}`,
83 status: "indexing",
84 };
85 await markComplete([item], IndexResultType.Compute);
86 }
87
88 // Add tag
89 for (const item of results.addTag) {
90 await markComplete([item], IndexResultType.AddTag);
91 }
92
93 // Remove tag
94 for (const item of results.removeTag) {
95 await markComplete([item], IndexResultType.RemoveTag);
96 }
97
98 // Delete
99 for (const item of results.del) {
100 await db.run(`
101 DELETE FROM fts WHERE rowid IN (
102 SELECT id FROM fts_metadata WHERE path = ? AND cacheKey = ?
103 )
104 `,[item.path, item.cacheKey]);
105 await db.run("DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?", [
106 item.path,
107 item.cacheKey,
108 ]);
109 await markComplete([item], IndexResultType.Delete);
110 }
111 }
112
113 async retrieve(config: RetrieveConfig): Promise<Chunk[]> {
114 const db = await SqliteDb.get();
115
116 const query = this.buildRetrieveQuery(config);
117 const parameters = this.getRetrieveQueryParameters(config);
118
119 let results = await db.all(query, parameters);
120
121 results = results.filter(
122 (result) =>
123 result.rank <= (config.bm25Threshold ?? RETRIEVAL_PARAMS.bm25Threshold),
124 );
125
126 const chunks = await db.all(
127 `SELECT * FROM chunks WHERE id IN (${results.map(() => "?").join(",")})`,
128 results.map((result) => result.chunkId),
129 );
130
131 return chunks.map((chunk) => ({
132 filepath: chunk.path,
133 index: chunk.index,
134 startLine: chunk.startLine,
135 endLine: chunk.endLine,
136 content: chunk.content,
137 digest: chunk.cacheKey,
138 }));
139 }
140
141 private buildTagFilter(tags: BranchAndDir[]): string {
142 const tagStrings = this.convertTags(tags);
143
144 return `AND chunk_tags.tag IN (${tagStrings.map(() => "?").join(",")})`;
145 }
146
147 private buildPathFilter(filterPaths: string[] | undefined): string {
148 if (!filterPaths || filterPaths.length === 0) {
149 return "";
150 }
151 return `AND fts_metadata.path IN (${filterPaths.map(() => "?").join(",")})`;
152 }
153
154 private buildRetrieveQuery(config: RetrieveConfig): string {
155 return `
156 SELECT fts_metadata.chunkId, fts_metadata.path, fts.content, rank
157 FROM fts
158 JOIN fts_metadata ON fts.rowid = fts_metadata.id
159 JOIN chunk_tags ON fts_metadata.chunkId = chunk_tags.chunkId
160 WHERE fts MATCH ?
161 ${this.buildTagFilter(config.tags)}
162 ${this.buildPathFilter(config.filterPaths)}
163 ORDER BY bm25(fts, ${this.pathWeightMultiplier})
164 LIMIT ?
165 `;
166 }
167
168 private getRetrieveQueryParameters(config: RetrieveConfig) {
169 const { text, tags, filterPaths, n } = config;
170 const tagStrings = this.convertTags(tags);
171
172 return [
173 text.replace(/\?/g, ""),
174 ...tagStrings,
175 ...(filterPaths || []),
176 Math.ceil(n),
177 ];
178 }
179
180 private convertTags(tags: BranchAndDir[]): string[] {
181 // Notice that the "chunks" artifactId is used because of linking between tables
182 return tags.map((tag) =>
183 tagToString({ ...tag, artifactId: ChunkCodebaseIndex.artifactId }),
184 );
185 }
186}