From 434e4ee44b513db15d502c6a9d52ceb17fa805c3 Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 26 Aug 2024 14:00:26 -0700 Subject: [PATCH 01/10] fix: update imports in CodeSnippetsIndex.ts --- core/indexing/CodeSnippetsIndex.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index dc55f9cc3..65f42cb11 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -5,21 +5,21 @@ import type { IDE, IndexTag, IndexingProgressUpdate, -} from "../index.js"; -import { getBasename, getLastNPathParts } from "../util/index.js"; -import { migrate } from "../util/paths.js"; +} from "../"; +import { getBasename, getLastNPathParts } from "../util/"; +import { migrate } from "../util/paths"; import { TSQueryType, getParserForFile, getQueryForFile, -} from "../util/treeSitter.js"; -import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; +} from "../util/treeSitter"; +import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; import { IndexResultType, MarkCompleteCallback, RefreshIndexResults, type CodebaseIndex, -} from "./types.js"; +} from "./types"; export class CodeSnippetsCodebaseIndex implements CodebaseIndex { relativeExpectedTime: number = 1; From a535e9e15fb3041fec732574636221e0a83dccfa Mon Sep 17 00:00:00 2001 From: "Test (aider)" Date: Mon, 26 Aug 2024 14:00:28 -0700 Subject: [PATCH 02/10] feat: Add signature column to code_snippets table --- core/indexing/CodeSnippetsIndex.ts | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 65f42cb11..38706efe7 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -34,6 +34,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { cacheKey TEXT NOT NULL, content TEXT NOT NULL, title TEXT NOT NULL, + signature TEXT, startLine INTEGER NOT NULL, endLine INTEGER NOT NULL )`); @@ -45,6 +46,13 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { FOREIGN KEY (snippetId) REFERENCES code_snippets (id) )`); + migrate("add_signature_column", async () => { + await db.exec(` + ALTER TABLE code_snippets + ADD COLUMN signature TEXT; + `); + }); + migrate("delete_duplicate_code_snippets", async () => { // Delete duplicate entries in code_snippets await db.exec(` @@ -98,7 +106,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { async getSnippetsInFile( filepath: string, contents: string, - ): Promise<(ChunkWithoutID & { title: string })[]> { + ): Promise<(ChunkWithoutID & { title: string; signature: string })[]> { const parser = await getParserForFile(filepath); if (!parser) { @@ -116,9 +124,12 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { return matches.flatMap((match) => { const node = match.captures[0].node; const title = match.captures[1].node.text; + const signatureNode = node.child(0); // Assuming the first child is the signature + const signature = signatureNode ? signatureNode.text : ''; const results = { title, content: node.text, + signature, startLine: node.startPosition.row, endLine: node.endPosition.row, }; @@ -154,12 +165,13 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { // Add snippets to sqlite for (const snippet of snippets) { const { lastID } = await db.run( - "REPLACE INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)", + "REPLACE INTO code_snippets (path, cacheKey, content, title, signature, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?, ?)", [ compute.path, compute.cacheKey, snippet.content, snippet.title, + snippet.signature, snippet.startLine, snippet.endLine, ], @@ -217,12 +229,13 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { for (const snippet of snippets) { const { lastID } = await db.run( - "REPLACE INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)", + "REPLACE INTO code_snippets (path, cacheKey, content, title, signature, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?, ?)", [ addTag.path, addTag.cacheKey, snippet.content, snippet.title, + snippet.signature, snippet.startLine, snippet.endLine, ], @@ -270,7 +283,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { return { name: row.title, description: getLastNPathParts(row.path, 2), - content: `\`\`\`${getBasename(row.path)}\n${row.content}\n\`\`\``, + content: `\`\`\`${getBasename(row.path)}\n${row.signature}\n${row.content}\n\`\`\``, }; } From bf426d5e2147248c06ab51cab31ac5cd9e834b1d Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 26 Aug 2024 17:55:39 -0700 Subject: [PATCH 03/10] feat: get return_type and parameters from snippets --- .gitignore | 3 +- core/index.d.ts | 1 + core/indexing/CodeSnippetsIndex.ts | 83 +++++++++++++------ core/indexing/chunk/markdown.ts | 6 +- .../code-snippet-queries/javascript.scm | 8 +- .../code-snippet-queries/typescript.scm | 10 ++- 6 files changed, 78 insertions(+), 33 deletions(-) diff --git a/.gitignore b/.gitignore index 3fa43ae1a..5d0457b0c 100644 --- a/.gitignore +++ b/.gitignore @@ -166,4 +166,5 @@ Icon? .continue -.prompts/ \ No newline at end of file +.prompts/ +.aider* diff --git a/core/index.d.ts b/core/index.d.ts index ab06f27fd..b9260c3fe 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -25,6 +25,7 @@ export interface ChunkWithoutID { content: string; startLine: number; endLine: number; + signature?: string; otherMetadata?: { [key: string]: any }; } diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 38706efe7..2c6a56041 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -1,3 +1,4 @@ +import Parser from "web-tree-sitter"; import type { ChunkWithoutID, ContextItem, @@ -21,6 +22,8 @@ import { type CodebaseIndex, } from "./types"; +type SnippetChunk = ChunkWithoutID & { title: string; signature: string }; + export class CodeSnippetsCodebaseIndex implements CodebaseIndex { relativeExpectedTime: number = 1; artifactId = "codeSnippets"; @@ -34,7 +37,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { cacheKey TEXT NOT NULL, content TEXT NOT NULL, title TEXT NOT NULL, - signature TEXT, + signature TEXT NOT NULL, startLine INTEGER NOT NULL, endLine INTEGER NOT NULL )`); @@ -103,10 +106,55 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { }); } + private getSnippetsFromMatch(match: Parser.QueryMatch): SnippetChunk { + let title = "", + content = "", + signature = "", + parameters = "", + returnType = "", + startLine = 0, + endLine = 0; + + const nodeTypesToTreatAsSignatures = ["interface_declaration"]; + + for (const { name, node } of match.captures) { + const nodeText = node.text; + const nodeType = node.type; + + switch (name) { + case "name": + title = nodeText; + break; + case "body": + if (nodeTypesToTreatAsSignatures.includes(nodeType)) { + signature = nodeText; + } + + content = nodeText; + startLine = node.startPosition.row; + endLine = node.endPosition.row; + + break; + case "parameters": + parameters = nodeText; + break; + case "return_type": + returnType = nodeText; + break; + } + } + + if (signature === "") { + signature = `${title}${parameters}${returnType}`; + } + + return { title, content, signature, startLine, endLine }; + } + async getSnippetsInFile( filepath: string, contents: string, - ): Promise<(ChunkWithoutID & { title: string; signature: string })[]> { + ): Promise { const parser = await getParserForFile(filepath); if (!parser) { @@ -121,20 +169,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { return []; } - return matches.flatMap((match) => { - const node = match.captures[0].node; - const title = match.captures[1].node.text; - const signatureNode = node.child(0); // Assuming the first child is the signature - const signature = signatureNode ? signatureNode.text : ''; - const results = { - title, - content: node.text, - signature, - startLine: node.startPosition.row, - endLine: node.endPosition.row, - }; - return results; - }); + return matches.map(this.getSnippetsFromMatch); } async *update( @@ -151,7 +186,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { for (let i = 0; i < results.compute.length; i++) { const compute = results.compute[i]; - let snippets: (ChunkWithoutID & { title: string })[] = []; + let snippets: SnippetChunk[] = []; try { snippets = await this.getSnippetsInFile( compute.path, @@ -216,7 +251,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { // Add tag for (let i = 0; i < results.addTag.length; i++) { const addTag = results.addTag[i]; - let snippets: (ChunkWithoutID & { title: string })[] = []; + let snippets: SnippetChunk[] = []; try { snippets = await this.getSnippetsInFile( addTag.path, @@ -253,22 +288,20 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { for (let i = 0; i < results.removeTag.length; i++) { const removeTag = results.removeTag[i]; - const snippets = await db.get( + const snippet = await db.get( `SELECT id FROM code_snippets WHERE cacheKey = ? AND path = ?`, [removeTag.cacheKey, removeTag.path], ); - if (snippets) { - const snippetIds = snippets.map((row: any) => row.id).join(","); - + if (snippet) { await db.run( ` DELETE FROM code_snippets_tags WHERE tag = ? - AND snippetId IN (${snippetIds}) + AND snippetId = ? `, - [tagString], + [tagString, snippet.id], ); } @@ -283,7 +316,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { return { name: row.title, description: getLastNPathParts(row.path, 2), - content: `\`\`\`${getBasename(row.path)}\n${row.signature}\n${row.content}\n\`\`\``, + content: `\`\`\`${getBasename(row.path)}\n${row.content}\n\`\`\``, }; } diff --git a/core/indexing/chunk/markdown.ts b/core/indexing/chunk/markdown.ts index b79ccec8c..a4edaed77 100644 --- a/core/indexing/chunk/markdown.ts +++ b/core/indexing/chunk/markdown.ts @@ -1,6 +1,6 @@ -import { ChunkWithoutID } from "../../index.js"; -import { countTokens } from "../../llm/countTokens.js"; -import { basicChunker } from "./basic.js"; +import { ChunkWithoutID } from "../../"; +import { countTokens } from "../../llm/countTokens"; +import { basicChunker } from "./basic"; export function cleanFragment( fragment: string | undefined, diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/javascript.scm b/extensions/vscode/tree-sitter/code-snippet-queries/javascript.scm index 7be9458f4..36be2f491 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/javascript.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/javascript.scm @@ -2,7 +2,11 @@ name: (_) @name) @body (function_declaration - name: (_) @name) @body + name: (_) @name + parameters: (_) @parameters +) @body (method_definition - name: (_) @name) @body \ No newline at end of file + name: (_) @name + parameters: (_) @parameters +) @body \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/typescript.scm b/extensions/vscode/tree-sitter/code-snippet-queries/typescript.scm index c56cf4fba..02269b9ee 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/typescript.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/typescript.scm @@ -2,10 +2,16 @@ name: (_) @name) @body (function_declaration - name: (_) @name) @body + name: (_) @name + parameters: (_) @parameters + return_type: (_)? @return_type +) @body (method_definition - name: (_) @name) @body + name: (_) @name + parameters: (_) @parameters + return_type: (_)? @return_type +) @body (interface_declaration name: (_) @name) @body \ No newline at end of file From 48c442d1c687b15d5612786e87a09b016714abd6 Mon Sep 17 00:00:00 2001 From: "Test (aider)" Date: Mon, 26 Aug 2024 18:12:58 -0700 Subject: [PATCH 04/10] fix: Implement RepoMapContextProvider --- RepoMapContextProvider.ts | 64 +++++++++++++++++++ core/context/providers/CodeContextProvider.ts | 20 +++++- core/indexing/CodeSnippetsIndex.ts | 37 +++++++++++ core/util/paths.ts | 4 ++ 4 files changed, 124 insertions(+), 1 deletion(-) create mode 100644 RepoMapContextProvider.ts diff --git a/RepoMapContextProvider.ts b/RepoMapContextProvider.ts new file mode 100644 index 000000000..e177d10ad --- /dev/null +++ b/RepoMapContextProvider.ts @@ -0,0 +1,64 @@ +import * as fs from "fs"; +import { + ContextItem, + ContextProviderDescription, + ContextProviderExtras, + ContextSubmenuItem, + LoadSubmenuItemsArgs, +} from "../../index.js"; +import { CodeSnippetsCodebaseIndex } from "../../indexing/CodeSnippetsIndex.js"; +import { BaseContextProvider } from "../index.js"; +import { getRepoMapFilePath } from "../../util/paths.js"; + +class RepoMapContextProvider extends BaseContextProvider { + static description: ContextProviderDescription = { + title: "repo_map", + displayTitle: "Repository Map", + description: "Overview of the repository structure", + type: "default", + }; + + async getContextItems( + query: string, + extras: ContextProviderExtras, + ): Promise { + const repoMapPath = getRepoMapFilePath(); + + if (!fs.existsSync(repoMapPath)) { + await this.generateRepoMap(); + } + + const content = fs.readFileSync(repoMapPath, "utf8"); + return [ + { + name: "Repository Map", + description: "Overview of the repository structure", + content, + }, + ]; + } + + private async generateRepoMap(): Promise { + const repoMapPath = getRepoMapFilePath(); + + if (fs.existsSync(repoMapPath)) { + console.log(`Overwriting existing repo map at ${repoMapPath}`); + } + + const writeStream = fs.createWriteStream(repoMapPath); + writeStream.write("Repository Map:\n\n"); + + for await (const { path, signatures } of CodeSnippetsCodebaseIndex.getAllPathsAndSignatures()) { + writeStream.write(`${path}:\n`); + for (const signature of signatures) { + writeStream.write(` ${signature}\n`); + } + writeStream.write("\n"); + } + + writeStream.end(); + console.log(`Generated repo map at ${repoMapPath}`); + } +} + +export default RepoMapContextProvider; diff --git a/core/context/providers/CodeContextProvider.ts b/core/context/providers/CodeContextProvider.ts index be82c511a..60d07c905 100644 --- a/core/context/providers/CodeContextProvider.ts +++ b/core/context/providers/CodeContextProvider.ts @@ -7,6 +7,7 @@ import { } from "../../index.js"; import { CodeSnippetsCodebaseIndex } from "../../indexing/CodeSnippetsIndex.js"; import { BaseContextProvider } from "../index.js"; +import RepoMapContextProvider from "./RepoMapContextProvider.js"; const MAX_SUBMENU_ITEMS = 10_000; @@ -18,10 +19,20 @@ class CodeContextProvider extends BaseContextProvider { type: "submenu", }; + private repoMapProvider: RepoMapContextProvider; + + constructor() { + super(); + this.repoMapProvider = new RepoMapContextProvider(); + } + async getContextItems( query: string, extras: ContextProviderExtras, ): Promise { + if (query === "repo_map") { + return this.repoMapProvider.getContextItems(query, extras); + } // Assume the query is the id as returned by loadSubmenuItems return [ await CodeSnippetsCodebaseIndex.getForId(Number.parseInt(query, 10)), @@ -38,7 +49,14 @@ class CodeContextProvider extends BaseContextProvider { tags.map((tag) => CodeSnippetsCodebaseIndex.getAll(tag)), ); - const submenuItems: ContextSubmenuItem[] = []; + const submenuItems: ContextSubmenuItem[] = [ + { + title: "Repository Map", + description: "Overview of the repository structure", + id: "repo_map", + }, + ]; + for (const snippetList of snippets.slice(-MAX_SUBMENU_ITEMS)) { submenuItems.push(...snippetList); } diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 2c6a56041..c516b7451 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -343,4 +343,41 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { return []; } } + + static async getAllPathsAndSignatures(batchSize: number = 1000): AsyncGenerator<{ path: string; signatures: string[] }> { + const db = await SqliteDb.get(); + await CodeSnippetsCodebaseIndex._createTables(db); + + let offset = 0; + let hasMore = true; + + while (hasMore) { + const rows = await db.all( + `SELECT path, signature + FROM code_snippets + ORDER BY path + LIMIT ? OFFSET ?`, + [batchSize, offset] + ); + + if (rows.length === 0) { + hasMore = false; + continue; + } + + const groupedByPath: { [path: string]: string[] } = {}; + for (const row of rows) { + if (!groupedByPath[row.path]) { + groupedByPath[row.path] = []; + } + groupedByPath[row.path].push(row.signature); + } + + for (const [path, signatures] of Object.entries(groupedByPath)) { + yield { path, signatures }; + } + + offset += batchSize; + } + } } diff --git a/core/util/paths.ts b/core/util/paths.ts index 5bc7fc26b..28216d8af 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -341,3 +341,7 @@ export function readAllGlobalPromptFiles( return promptFiles; } + +export function getRepoMapFilePath(): string { + return path.join(getContinueUtilsPath(), "repo_map.txt"); +} From 4e5276dde9aeb2e303da82e9de0cd85f7465c84f Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 26 Aug 2024 18:44:08 -0700 Subject: [PATCH 05/10] add repomapcontextprovider --- core/context/providers/CodeContextProvider.ts | 19 +------- .../providers/RepoMapContextProvider.ts | 42 ++++++++++------ core/context/providers/index.ts | 48 ++++++++++--------- core/indexing/CodeSnippetsIndex.ts | 9 +++- 4 files changed, 60 insertions(+), 58 deletions(-) rename RepoMapContextProvider.ts => core/context/providers/RepoMapContextProvider.ts (58%) diff --git a/core/context/providers/CodeContextProvider.ts b/core/context/providers/CodeContextProvider.ts index 60d07c905..3f84c6fed 100644 --- a/core/context/providers/CodeContextProvider.ts +++ b/core/context/providers/CodeContextProvider.ts @@ -7,7 +7,6 @@ import { } from "../../index.js"; import { CodeSnippetsCodebaseIndex } from "../../indexing/CodeSnippetsIndex.js"; import { BaseContextProvider } from "../index.js"; -import RepoMapContextProvider from "./RepoMapContextProvider.js"; const MAX_SUBMENU_ITEMS = 10_000; @@ -19,20 +18,10 @@ class CodeContextProvider extends BaseContextProvider { type: "submenu", }; - private repoMapProvider: RepoMapContextProvider; - - constructor() { - super(); - this.repoMapProvider = new RepoMapContextProvider(); - } - async getContextItems( query: string, extras: ContextProviderExtras, ): Promise { - if (query === "repo_map") { - return this.repoMapProvider.getContextItems(query, extras); - } // Assume the query is the id as returned by loadSubmenuItems return [ await CodeSnippetsCodebaseIndex.getForId(Number.parseInt(query, 10)), @@ -49,13 +38,7 @@ class CodeContextProvider extends BaseContextProvider { tags.map((tag) => CodeSnippetsCodebaseIndex.getAll(tag)), ); - const submenuItems: ContextSubmenuItem[] = [ - { - title: "Repository Map", - description: "Overview of the repository structure", - id: "repo_map", - }, - ]; + const submenuItems: ContextSubmenuItem[] = []; for (const snippetList of snippets.slice(-MAX_SUBMENU_ITEMS)) { submenuItems.push(...snippetList); diff --git a/RepoMapContextProvider.ts b/core/context/providers/RepoMapContextProvider.ts similarity index 58% rename from RepoMapContextProvider.ts rename to core/context/providers/RepoMapContextProvider.ts index e177d10ad..514839292 100644 --- a/RepoMapContextProvider.ts +++ b/core/context/providers/RepoMapContextProvider.ts @@ -1,21 +1,26 @@ import * as fs from "fs"; +import * as path from "path"; import { ContextItem, ContextProviderDescription, ContextProviderExtras, - ContextSubmenuItem, - LoadSubmenuItemsArgs, -} from "../../index.js"; +} from "../../"; import { CodeSnippetsCodebaseIndex } from "../../indexing/CodeSnippetsIndex.js"; -import { BaseContextProvider } from "../index.js"; -import { getRepoMapFilePath } from "../../util/paths.js"; +import { getRepoMapFilePath } from "../../util/paths"; +import { BaseContextProvider } from ".."; class RepoMapContextProvider extends BaseContextProvider { + repoMapPreamble = + "Below is a repository map. \n" + + "For each file in the codebase, " + + "this map contains the name of the file, and the signature for any " + + "classes, methods, or functions in the file.\n\n"; + static description: ContextProviderDescription = { title: "repo_map", displayTitle: "Repository Map", description: "Overview of the repository structure", - type: "default", + type: "normal", }; async getContextItems( @@ -23,12 +28,11 @@ class RepoMapContextProvider extends BaseContextProvider { extras: ContextProviderExtras, ): Promise { const repoMapPath = getRepoMapFilePath(); - - if (!fs.existsSync(repoMapPath)) { - await this.generateRepoMap(); - } + + await this.generateRepoMap(extras); const content = fs.readFileSync(repoMapPath, "utf8"); + return [ { name: "Repository Map", @@ -38,21 +42,29 @@ class RepoMapContextProvider extends BaseContextProvider { ]; } - private async generateRepoMap(): Promise { + private async generateRepoMap(extras: ContextProviderExtras): Promise { const repoMapPath = getRepoMapFilePath(); - + const [workspaceDir] = await extras.ide.getWorkspaceDirs(); + if (fs.existsSync(repoMapPath)) { console.log(`Overwriting existing repo map at ${repoMapPath}`); } const writeStream = fs.createWriteStream(repoMapPath); - writeStream.write("Repository Map:\n\n"); + writeStream.write(this.repoMapPreamble); + + for await (const { + path: absolutePath, + signatures, + } of CodeSnippetsCodebaseIndex.getAllPathsAndSignatures(workspaceDir)) { + const relativePath = path.relative(workspaceDir, absolutePath); + + writeStream.write(`${relativePath}:\n`); - for await (const { path, signatures } of CodeSnippetsCodebaseIndex.getAllPathsAndSignatures()) { - writeStream.write(`${path}:\n`); for (const signature of signatures) { writeStream.write(` ${signature}\n`); } + writeStream.write("\n"); } diff --git a/core/context/providers/index.ts b/core/context/providers/index.ts index c388fb6dc..92cabb222 100644 --- a/core/context/providers/index.ts +++ b/core/context/providers/index.ts @@ -1,26 +1,27 @@ -import { ContextProviderName } from "../../index.js"; -import { BaseContextProvider } from "../index.js"; -import CodeContextProvider from "./CodeContextProvider.js"; -import ContinueProxyContextProvider from "./ContinueProxyContextProvider.js"; -import CurrentFileContextProvider from "./CurrentFileContextProvider.js"; -import DatabaseContextProvider from "./DatabaseContextProvider.js"; -import DiffContextProvider from "./DiffContextProvider.js"; -import DocsContextProvider from "./DocsContextProvider.js"; -import FileTreeContextProvider from "./FileTreeContextProvider.js"; -import FolderContextProvider from "./FolderContextProvider.js"; -import GitHubIssuesContextProvider from "./GitHubIssuesContextProvider.js"; -import GitLabMergeRequestContextProvider from "./GitLabMergeRequestContextProvider.js"; -import GoogleContextProvider from "./GoogleContextProvider.js"; -import HttpContextProvider from "./HttpContextProvider.js"; -import JiraIssuesContextProvider from "./JiraIssuesContextProvider/index.js"; -import LocalsProvider from "./LocalsProvider.js"; -import OSContextProvider from "./OSContextProvider.js"; -import OpenFilesContextProvider from "./OpenFilesContextProvider.js"; -import PostgresContextProvider from "./PostgresContextProvider.js"; -import ProblemsContextProvider from "./ProblemsContextProvider.js"; -import SearchContextProvider from "./SearchContextProvider.js"; -import TerminalContextProvider from "./TerminalContextProvider.js"; -import URLContextProvider from "./URLContextProvider.js"; +import { ContextProviderName } from "../../"; +import { BaseContextProvider } from "../"; +import CodeContextProvider from "./CodeContextProvider"; +import ContinueProxyContextProvider from "./ContinueProxyContextProvider"; +import CurrentFileContextProvider from "./CurrentFileContextProvider"; +import DatabaseContextProvider from "./DatabaseContextProvider"; +import DiffContextProvider from "./DiffContextProvider"; +import DocsContextProvider from "./DocsContextProvider"; +import FileTreeContextProvider from "./FileTreeContextProvider"; +import FolderContextProvider from "./FolderContextProvider"; +import GitHubIssuesContextProvider from "./GitHubIssuesContextProvider"; +import GitLabMergeRequestContextProvider from "./GitLabMergeRequestContextProvider"; +import GoogleContextProvider from "./GoogleContextProvider"; +import HttpContextProvider from "./HttpContextProvider"; +import JiraIssuesContextProvider from "./JiraIssuesContextProvider/"; +import LocalsProvider from "./LocalsProvider"; +import OSContextProvider from "./OSContextProvider"; +import OpenFilesContextProvider from "./OpenFilesContextProvider"; +import PostgresContextProvider from "./PostgresContextProvider"; +import ProblemsContextProvider from "./ProblemsContextProvider"; +import SearchContextProvider from "./SearchContextProvider"; +import TerminalContextProvider from "./TerminalContextProvider"; +import URLContextProvider from "./URLContextProvider"; +import RepoMapContextProvider from "./RepoMapContextProvider"; /** * Note: We are currently omitting the following providers due to bugs: @@ -51,6 +52,7 @@ const Providers: (typeof BaseContextProvider)[] = [ CurrentFileContextProvider, URLContextProvider, ContinueProxyContextProvider, + RepoMapContextProvider, ]; export function contextProviderClassFromName( diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index c516b7451..34e065b50 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -344,7 +344,10 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { } } - static async getAllPathsAndSignatures(batchSize: number = 1000): AsyncGenerator<{ path: string; signatures: string[] }> { + static async *getAllPathsAndSignatures( + workspaceDir: string, + batchSize: number = 1000, + ): AsyncGenerator<{ path: string; signatures: string[] }> { const db = await SqliteDb.get(); await CodeSnippetsCodebaseIndex._createTables(db); @@ -355,9 +358,10 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { const rows = await db.all( `SELECT path, signature FROM code_snippets + WHERE path LIKE ? ORDER BY path LIMIT ? OFFSET ?`, - [batchSize, offset] + [`${workspaceDir}%`, batchSize, offset], ); if (rows.length === 0) { @@ -366,6 +370,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { } const groupedByPath: { [path: string]: string[] } = {}; + for (const row of rows) { if (!groupedByPath[row.path]) { groupedByPath[row.path] = []; From bb4dd228f3db020ae188d3447132074a9280cf65 Mon Sep 17 00:00:00 2001 From: Test Date: Tue, 27 Aug 2024 14:04:35 -0700 Subject: [PATCH 06/10] update tree-sitter queries --- .../providers/RepoMapContextProvider.ts | 75 +++++++++++++------ core/indexing/CodeSnippetsIndex.ts | 73 ++++++++++-------- .../tree-sitter/code-snippet-queries/c.scm | 2 +- .../tree-sitter/code-snippet-queries/go.scm | 23 ++++-- .../tree-sitter/code-snippet-queries/java.scm | 13 +++- .../code-snippet-queries/javascript.scm | 30 +++++--- .../code-snippet-queries/ocaml.scm | 6 +- .../tree-sitter/code-snippet-queries/php.scm | 6 +- .../code-snippet-queries/python.scm | 6 +- .../tree-sitter/code-snippet-queries/rust.scm | 9 ++- .../code-snippet-queries/typescript.scm | 39 ++++++---- 11 files changed, 182 insertions(+), 100 deletions(-) diff --git a/core/context/providers/RepoMapContextProvider.ts b/core/context/providers/RepoMapContextProvider.ts index 514839292..1d629e9f5 100644 --- a/core/context/providers/RepoMapContextProvider.ts +++ b/core/context/providers/RepoMapContextProvider.ts @@ -16,10 +16,13 @@ class RepoMapContextProvider extends BaseContextProvider { "this map contains the name of the file, and the signature for any " + "classes, methods, or functions in the file.\n\n"; + // The max percent of the context window we will take + REPO_MAX_CONTEXT_LENGTH_RATIO = 0.5; + static description: ContextProviderDescription = { title: "repo_map", displayTitle: "Repository Map", - description: "Overview of the repository structure", + description: "List of files and signatures", type: "normal", }; @@ -27,49 +30,79 @@ class RepoMapContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { - const repoMapPath = getRepoMapFilePath(); - - await this.generateRepoMap(extras); - - const content = fs.readFileSync(repoMapPath, "utf8"); - return [ { name: "Repository Map", description: "Overview of the repository structure", - content, + content: await this.generateRepoMap(extras), }, ]; } - private async generateRepoMap(extras: ContextProviderExtras): Promise { + private indentMultilineString(str: string) { + return str + .split("\n") + .map((line: any) => "\t" + line) + .join("\n"); + } + + private async generateRepoMap({ llm, ide }: ContextProviderExtras) { const repoMapPath = getRepoMapFilePath(); - const [workspaceDir] = await extras.ide.getWorkspaceDirs(); + const [workspaceDir] = await ide.getWorkspaceDirs(); + const maxRepoMapTokens = + llm.contextLength * this.REPO_MAX_CONTEXT_LENGTH_RATIO; if (fs.existsSync(repoMapPath)) { - console.log(`Overwriting existing repo map at ${repoMapPath}`); + console.debug(`Overwriting existing repo map at ${repoMapPath}`); } const writeStream = fs.createWriteStream(repoMapPath); writeStream.write(this.repoMapPreamble); - for await (const { - path: absolutePath, - signatures, - } of CodeSnippetsCodebaseIndex.getAllPathsAndSignatures(workspaceDir)) { - const relativePath = path.relative(workspaceDir, absolutePath); + let curTokens = llm.countTokens(this.repoMapPreamble); - writeStream.write(`${relativePath}:\n`); + for await (const pathsAndSignatures of CodeSnippetsCodebaseIndex.getAllPathsAndSignatures( + workspaceDir, + )) { + let content = ""; - for (const signature of signatures) { - writeStream.write(` ${signature}\n`); + for (const [absolutePath, signatures] of Object.entries( + pathsAndSignatures, + )) { + const relativePath = path.relative(workspaceDir, absolutePath); + content += `${relativePath}:\n`; + + for (const signature of signatures.slice(0, -1)) { + content += `${this.indentMultilineString(signature)}\n\t...\n`; + } + + // Don't add the trailing elipsis for the last entry + content += `${this.indentMultilineString( + signatures[signatures.length - 1], + )}\n\n`; } - writeStream.write("\n"); + curTokens += llm.countTokens(content); + + if (curTokens >= maxRepoMapTokens) { + break; + } + + writeStream.write(content); } writeStream.end(); - console.log(`Generated repo map at ${repoMapPath}`); + console.debug(`Generated repo map at ${repoMapPath}`); + + if (curTokens >= maxRepoMapTokens) { + console.debug( + "Full repo map was unable to be genereated due to context window limitations", + ); + } + + const repoMap = fs.readFileSync(repoMapPath, "utf8"); + + return repoMap; } } diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 34e065b50..fff4ceba9 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -37,7 +37,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { cacheKey TEXT NOT NULL, content TEXT NOT NULL, title TEXT NOT NULL, - signature TEXT NOT NULL, + signature TEXT, startLine INTEGER NOT NULL, endLine INTEGER NOT NULL )`); @@ -107,47 +107,58 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { } private getSnippetsFromMatch(match: Parser.QueryMatch): SnippetChunk { + const bodyTypesToTreatAsSignatures = [ + "interface_declaration", // TypeScript, Java + "struct_item", // Rust + "type_spec", // Go + ]; + + const bodyCaptureGroupPrefixes = ["definition", "reference"]; + let title = "", content = "", signature = "", - parameters = "", - returnType = "", startLine = 0, - endLine = 0; - - const nodeTypesToTreatAsSignatures = ["interface_declaration"]; + endLine = 0, + hasSeenBody = false; + // This loop assumes that the ordering of the capture groups is represenatative + // of the structure of the language, e.g. for a TypeScript match on a function, + // `function myFunc(param: string): string`, the first capture would be the `myFunc` + // the second capture would be the `(param: string)`, etc for (const { name, node } of match.captures) { + // Assume we are capturing groups using a dot syntax for more precise groupings + // However, for this case, we only care about the first substring + const trimmedCaptureName = name.split(".")[0]; + const nodeText = node.text; const nodeType = node.type; - switch (name) { - case "name": + if (bodyCaptureGroupPrefixes.includes(trimmedCaptureName)) { + if (bodyTypesToTreatAsSignatures.includes(nodeType)) { + // Note we override whatever existing value there is here + signature = nodeText; + hasSeenBody = true; + } + + content = nodeText; + startLine = node.startPosition.row; + endLine = node.endPosition.row; + } else { + if (trimmedCaptureName === "name") { title = nodeText; - break; - case "body": - if (nodeTypesToTreatAsSignatures.includes(nodeType)) { - signature = nodeText; + } + + if (!hasSeenBody) { + signature += nodeText + " "; + + if (trimmedCaptureName === "comment") { + signature += "\n"; } - - content = nodeText; - startLine = node.startPosition.row; - endLine = node.endPosition.row; - - break; - case "parameters": - parameters = nodeText; - break; - case "return_type": - returnType = nodeText; - break; + } } } - if (signature === "") { - signature = `${title}${parameters}${returnType}`; - } - return { title, content, signature, startLine, endLine }; } @@ -347,7 +358,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { static async *getAllPathsAndSignatures( workspaceDir: string, batchSize: number = 1000, - ): AsyncGenerator<{ path: string; signatures: string[] }> { + ): AsyncGenerator<{ [path: string]: string[] }> { const db = await SqliteDb.get(); await CodeSnippetsCodebaseIndex._createTables(db); @@ -378,9 +389,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { groupedByPath[row.path].push(row.signature); } - for (const [path, signatures] of Object.entries(groupedByPath)) { - yield { path, signatures }; - } + yield groupedByPath; offset += batchSize; } diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/c.scm b/extensions/vscode/tree-sitter/code-snippet-queries/c.scm index bb343911e..ff3cb6dc2 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/c.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/c.scm @@ -4,6 +4,6 @@ (declaration type: (union_specifier name: (type_identifier) @name.definition.class)) @definition.class -(type_definition declarator: (type_identifier) @name ) @body +(type_definition declarator: (type_identifier) @name ) @definition (enum_specifier name: (type_identifier) @name.definition.type) @definition.type diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/go.scm b/extensions/vscode/tree-sitter/code-snippet-queries/go.scm index 9d2af874d..bac626605 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/go.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/go.scm @@ -1,19 +1,26 @@ ( - (comment)* @doc + (comment)* @comment . (function_declaration - name: (identifier) @name.definition.function) @definition.function - (#strip! @doc "^//\\s*") - (#set-adjacent! @doc @definition.function) + name: (identifier) @name.definition.function + parameters: (_) @parameters + result: (_)? @return_type + ) @definition.function + (#strip! @comment "^//\\s*") + (#set-adjacent! @comment @definition.function) ) ( - (comment)* @doc + (comment)* @comment . (method_declaration - name: (field_identifier) @name.definition.method) @definition.method - (#strip! @doc "^//\\s*") - (#set-adjacent! @doc @definition.method) + receiver: (_) @receiver + name: (field_identifier) @name.definition.method + parameters: (_) @parameters + result: (_)? @return_type + ) @definition.method + (#strip! @comment "^//\\s*") + (#set-adjacent! @comment @definition.method) ) (type_spec diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/java.scm b/extensions/vscode/tree-sitter/code-snippet-queries/java.scm index 593a75fc6..0aeccc319 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/java.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/java.scm @@ -1,8 +1,15 @@ (class_declaration - name: (identifier) @name.definition.class) @definition.class + name: (_) @name.definition.class + interfaces: (_) @interfaces +) @definition.class + (method_declaration - name: (identifier) @name.definition.method) @definition.method + type: (_) @return_type + name: (_) @name.definition.method + parameters: (_) @parameters +) @definition.method (interface_declaration - name: (identifier) @name.definition.interface) @definition.interface \ No newline at end of file + name: (_) @name.definition.interface +) @definition.interface \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/javascript.scm b/extensions/vscode/tree-sitter/code-snippet-queries/javascript.scm index 36be2f491..3b6153c90 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/javascript.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/javascript.scm @@ -1,12 +1,22 @@ -(class_declaration - name: (_) @name) @body +( + (comment)? @comment + (class_declaration + name: (_) @name + ) @definition +) -(function_declaration - name: (_) @name - parameters: (_) @parameters -) @body +( + (comment)? @comment + (function_declaration + name: (_) @name + parameters: (_) @parameters + ) @definition +) -(method_definition - name: (_) @name - parameters: (_) @parameters -) @body \ No newline at end of file +( + (comment)? @comment + (method_definition + name: (_) @name + parameters: (_) @parameters + ) @definition +) \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/ocaml.scm b/extensions/vscode/tree-sitter/code-snippet-queries/ocaml.scm index 9bc034d8e..9040cad33 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/ocaml.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/ocaml.scm @@ -1,12 +1,12 @@ (value_definition (let_binding pattern: (_) @name) -) @body +) @definition (module_type_definition - name: (_) @name) @body + name: (_) @name) @definition (class_definition (class_binding name: (_) @name) -) @body \ No newline at end of file +) @definition \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/php.scm b/extensions/vscode/tree-sitter/code-snippet-queries/php.scm index c95663f3c..124de18ea 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/php.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/php.scm @@ -1,8 +1,8 @@ (class_declaration - name: (name) @name) @body + name: (name) @name) @definition (function_definition - name: (name) @name) @body + name: (name) @name) @definition (method_declaration - name: (name) @name) @body \ No newline at end of file + name: (name) @name) @definition \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/python.scm b/extensions/vscode/tree-sitter/code-snippet-queries/python.scm index 04289704f..586d738c7 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/python.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/python.scm @@ -1,5 +1,7 @@ (class_definition - name: (_) @name) @body + name: (_) @name) @definition (function_definition - name: (_) @name) @body \ No newline at end of file + name: (_) @name + parameters: (_) @parameters +) @definition \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/rust.scm b/extensions/vscode/tree-sitter/code-snippet-queries/rust.scm index e4125cabf..4b10e7c34 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/rust.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/rust.scm @@ -1,8 +1,11 @@ (function_item - name: (_) @name) @body + name: (_) @name + parameters: (_) @parameters + return_type: (_)? @return_type +) @definition (struct_item - name: (_) @name) @body + name: (_) @name) @definition (impl_item - type: (_) @name) @body \ No newline at end of file + type: (_) @name) @definition \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/typescript.scm b/extensions/vscode/tree-sitter/code-snippet-queries/typescript.scm index 02269b9ee..d564f406a 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/typescript.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/typescript.scm @@ -1,17 +1,28 @@ -(class_declaration - name: (_) @name) @body +( + (comment)? @comment + (class_declaration + name: (_) @name + ) @definition +) -(function_declaration - name: (_) @name - parameters: (_) @parameters - return_type: (_)? @return_type -) @body +( + (comment)? @comment + (function_declaration + name: (_) @name + parameters: (_) @parameters + ) @definition +) -(method_definition - name: (_) @name - parameters: (_) @parameters - return_type: (_)? @return_type -) @body +( + (comment)? @comment + (method_definition + name: (_) @name + parameters: (_) @parameters + ) @definition +) -(interface_declaration - name: (_) @name) @body \ No newline at end of file +( + (comment)? @comment + (interface_declaration + name: (_) @name) @definition +) \ No newline at end of file From d1a451ccf47ef2480972e66c5bb3747e0e982a32 Mon Sep 17 00:00:00 2001 From: Test Date: Tue, 27 Aug 2024 14:15:56 -0700 Subject: [PATCH 07/10] add docs --- core/context/providers/RepoMapContextProvider.ts | 2 +- core/indexing/CodeSnippetsIndex.ts | 15 +++++++++++---- docs/docs/customization/context-providers.md | 12 ++++++++++++ 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/core/context/providers/RepoMapContextProvider.ts b/core/context/providers/RepoMapContextProvider.ts index 1d629e9f5..90eadb964 100644 --- a/core/context/providers/RepoMapContextProvider.ts +++ b/core/context/providers/RepoMapContextProvider.ts @@ -20,7 +20,7 @@ class RepoMapContextProvider extends BaseContextProvider { REPO_MAX_CONTEXT_LENGTH_RATIO = 0.5; static description: ContextProviderDescription = { - title: "repo_map", + title: "repo-map", displayTitle: "Repository Map", description: "List of files and signatures", type: "normal", diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index c4b0cd18c..27a7e90cb 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -299,23 +299,30 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { for (let i = 0; i < results.removeTag.length; i++) { const removeTag = results.removeTag[i]; - const snippet = await db.get( + let snippets = await db.get( `SELECT id FROM code_snippets WHERE cacheKey = ? AND path = ?`, [removeTag.cacheKey, removeTag.path], ); + if (!Array.isArray(snippets)) { snippets = [snippets]; } - if (snippet) { + if (snippets) { + if (!Array.isArray(snippets)) { + snippets = [snippets]; + } + + const snippetIds = snippets.map((row: any) => row.id).join(","); + await db.run( ` DELETE FROM code_snippets_tags WHERE tag = ? - AND snippetId = ? + AND snippetId IN (${snippetIds}) `, - [tagString, snippet.id], + [tagString], ); } diff --git a/docs/docs/customization/context-providers.md b/docs/docs/customization/context-providers.md index 610e272a9..7dfe6190c 100644 --- a/docs/docs/customization/context-providers.md +++ b/docs/docs/customization/context-providers.md @@ -301,6 +301,18 @@ Type `@locals` to reference the contents of the local variables with top n level } ``` +### Repository map + +Provides an overview of all files and the call signatures of top-level classes, functions, and methods. This helps the model better understand how a particular piece of code relates to the rest of the codebase. + +This context provider is inpsired by [Aider's repository map](https://aider.chat/2023/10/22/repomap.html). + +```json +{ + "name": "repo-map" +} +``` + ### Operating System Type `@os` to reference the architecture and platform of your current operating system. From b4e9af97991609b16427fab374789420df63f8a5 Mon Sep 17 00:00:00 2001 From: Test Date: Tue, 27 Aug 2024 14:32:41 -0700 Subject: [PATCH 08/10] Update CodeSnippetsIndex.ts --- core/indexing/CodeSnippetsIndex.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 27a7e90cb..cfc180bb2 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -367,7 +367,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { static async *getAllPathsAndSignatures( workspaceDir: string, - batchSize: number = 1000, + batchSize: number = 100, ): AsyncGenerator<{ [path: string]: string[] }> { const db = await SqliteDb.get(); await CodeSnippetsCodebaseIndex._createTables(db); From aec9b63facb69350b1f254fc8169e999f5533186 Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 28 Aug 2024 09:57:59 -0700 Subject: [PATCH 09/10] Update CodeSnippetsIndex.test.ts --- core/indexing/CodeSnippetsIndex.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/indexing/CodeSnippetsIndex.test.ts b/core/indexing/CodeSnippetsIndex.test.ts index a80ffe7bd..4731fad8f 100644 --- a/core/indexing/CodeSnippetsIndex.test.ts +++ b/core/indexing/CodeSnippetsIndex.test.ts @@ -34,6 +34,7 @@ describe("CodeSnippetsCodebaseIndex", () => { const mockSnippet = { title: "", content: "", + signature: "", startLine: 0, endLine: 1, }; From cbd341dd2da132d726467de3b1c2f318e4705301 Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 28 Aug 2024 11:42:06 -0700 Subject: [PATCH 10/10] support for multi-workspace dirs and pagination --- .../providers/RepoMapContextProvider.ts | 38 ++++++++---- core/indexing/CodeSnippetsIndex.ts | 60 +++++++++---------- 2 files changed, 57 insertions(+), 41 deletions(-) diff --git a/core/context/providers/RepoMapContextProvider.ts b/core/context/providers/RepoMapContextProvider.ts index 90eadb964..f8c3dc684 100644 --- a/core/context/providers/RepoMapContextProvider.ts +++ b/core/context/providers/RepoMapContextProvider.ts @@ -48,7 +48,7 @@ class RepoMapContextProvider extends BaseContextProvider { private async generateRepoMap({ llm, ide }: ContextProviderExtras) { const repoMapPath = getRepoMapFilePath(); - const [workspaceDir] = await ide.getWorkspaceDirs(); + const workspaceDirs = await ide.getWorkspaceDirs(); const maxRepoMapTokens = llm.contextLength * this.REPO_MAX_CONTEXT_LENGTH_RATIO; @@ -60,15 +60,23 @@ class RepoMapContextProvider extends BaseContextProvider { writeStream.write(this.repoMapPreamble); let curTokens = llm.countTokens(this.repoMapPreamble); + let offset = 0; + const batchSize = 100; + + while (true) { + const { groupedByPath, hasMore } = + await CodeSnippetsCodebaseIndex.getPathsAndSignatures( + workspaceDirs, + offset, + batchSize, + ); - for await (const pathsAndSignatures of CodeSnippetsCodebaseIndex.getAllPathsAndSignatures( - workspaceDir, - )) { let content = ""; - for (const [absolutePath, signatures] of Object.entries( - pathsAndSignatures, - )) { + for (const [absolutePath, signatures] of Object.entries(groupedByPath)) { + const workspaceDir = + workspaceDirs.find((dir) => absolutePath.startsWith(dir)) || ""; + const relativePath = path.relative(workspaceDir, absolutePath); content += `${relativePath}:\n`; @@ -76,10 +84,12 @@ class RepoMapContextProvider extends BaseContextProvider { content += `${this.indentMultilineString(signature)}\n\t...\n`; } - // Don't add the trailing elipsis for the last entry - content += `${this.indentMultilineString( - signatures[signatures.length - 1], - )}\n\n`; + if (signatures.length > 0) { + // Don't add the trailing ellipsis for the last entry + content += `${this.indentMultilineString( + signatures[signatures.length - 1], + )}\n\n`; + } } curTokens += llm.countTokens(content); @@ -89,6 +99,12 @@ class RepoMapContextProvider extends BaseContextProvider { } writeStream.write(content); + + if (!hasMore) { + break; + } + + offset += batchSize; } writeStream.end(); diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index cfc180bb2..56cc7d126 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -365,43 +365,43 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { } } - static async *getAllPathsAndSignatures( - workspaceDir: string, + static async getPathsAndSignatures( + workspaceDirs: string[], + offset: number = 0, batchSize: number = 100, - ): AsyncGenerator<{ [path: string]: string[] }> { + ): Promise<{ + groupedByPath: { [path: string]: string[] }; + hasMore: boolean; + }> { const db = await SqliteDb.get(); await CodeSnippetsCodebaseIndex._createTables(db); - let offset = 0; - let hasMore = true; + const likePatterns = workspaceDirs.map((dir) => `${dir}%`); + const placeholders = likePatterns.map(() => "?").join(" OR path LIKE "); - while (hasMore) { - const rows = await db.all( - `SELECT path, signature - FROM code_snippets - WHERE path LIKE ? - ORDER BY path - LIMIT ? OFFSET ?`, - [`${workspaceDir}%`, batchSize, offset], - ); + const query = ` + SELECT path, signature + FROM code_snippets + WHERE path LIKE ${placeholders} + ORDER BY path + LIMIT ? OFFSET ? +`; - if (rows.length === 0) { - hasMore = false; - continue; + const rows = await db.all(query, [...likePatterns, batchSize, offset]); + + const validRows = rows.filter((row) => row.path && row.signature !== null); + + const groupedByPath: { [path: string]: string[] } = {}; + + for (const { path, signature } of validRows) { + if (!groupedByPath[path]) { + groupedByPath[path] = []; } - - const groupedByPath: { [path: string]: string[] } = {}; - - for (const row of rows) { - if (!groupedByPath[row.path]) { - groupedByPath[row.path] = []; - } - groupedByPath[row.path].push(row.signature); - } - - yield groupedByPath; - - offset += batchSize; + groupedByPath[path].push(signature); } + + const hasMore = rows.length === batchSize; + + return { groupedByPath, hasMore }; } }