Elffuss BraidHub

kikocis/continue public

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