Merge pull request #2116 from continuedev/pe/repo-map

feat: add `repo-map` context provider
This commit is contained in:
Patrick Erichsen 2024-08-28 13:47:44 -07:00 • committed by GitHub
commit 25b9b8d7f0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
19 changed files with 383 additions and 86 deletions

3
.gitignore vendored
View file

@ -166,4 +166,5 @@ Icon?
.continue
.prompts/
.prompts/
.aider*

View file

@ -39,6 +39,7 @@ class CodeContextProvider extends BaseContextProvider {
);
const submenuItems: ContextSubmenuItem[] = [];
for (const snippetList of snippets.slice(-MAX_SUBMENU_ITEMS)) {
submenuItems.push(...snippetList);
}

View file

@ -0,0 +1,125 @@
import * as fs from "fs";
import * as path from "path";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
} from "../../";
import { CodeSnippetsCodebaseIndex } from "../../indexing/CodeSnippetsIndex.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";
// 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: "List of files and signatures",
type: "normal",
};
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
return [
{
name: "Repository Map",
description: "Overview of the repository structure",
content: await this.generateRepoMap(extras),
},
];
}
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 workspaceDirs = await ide.getWorkspaceDirs();
const maxRepoMapTokens =
llm.contextLength * this.REPO_MAX_CONTEXT_LENGTH_RATIO;
if (fs.existsSync(repoMapPath)) {
console.debug(`Overwriting existing repo map at ${repoMapPath}`);
}
const writeStream = fs.createWriteStream(repoMapPath);
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,
);
let content = "";
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`;
for (const signature of signatures.slice(0, -1)) {
content += `${this.indentMultilineString(signature)}\n\t...\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);
if (curTokens >= maxRepoMapTokens) {
break;
}
writeStream.write(content);
if (!hasMore) {
break;
}
offset += batchSize;
}
writeStream.end();
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;
}
}
export default RepoMapContextProvider;

View file

@ -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(

1
core/index.d.ts vendored
View file

@ -25,6 +25,7 @@ export interface ChunkWithoutID {
content: string;
startLine: number;
endLine: number;
signature?: string;
otherMetadata?: { [key: string]: any };
}

View file

@ -34,6 +34,7 @@ describe("CodeSnippetsCodebaseIndex", () => {
const mockSnippet = {
title: "",
content: "",
signature: "",
startLine: 0,
endLine: 1,
};

View file

@ -1,3 +1,4 @@
import Parser from "web-tree-sitter";
import type {
ChunkWithoutID,
ContextItem,
@ -5,21 +6,23 @@ 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";
type SnippetChunk = ChunkWithoutID & { title: string; signature: string };
export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
relativeExpectedTime: number = 1;
@ -34,6 +37,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 +49,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(`
@ -95,10 +106,66 @@ 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 = "",
startLine = 0,
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;
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;
}
if (!hasSeenBody) {
signature += nodeText + " ";
if (trimmedCaptureName === "comment") {
signature += "\n";
}
}
}
}
return { title, content, signature, startLine, endLine };
}
async getSnippetsInFile(
filepath: string,
contents: string,
): Promise<(ChunkWithoutID & { title: string })[]> {
): Promise<SnippetChunk[]> {
const parser = await getParserForFile(filepath);
if (!parser) {
@ -113,17 +180,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 results = {
title,
content: node.text,
startLine: node.startPosition.row,
endLine: node.endPosition.row,
};
return results;
});
return matches.map(this.getSnippetsFromMatch);
}
async *update(
@ -140,7 +197,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,
@ -154,12 +211,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,
],
@ -204,7 +262,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,
@ -217,12 +275,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,
],
@ -245,6 +304,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
WHERE cacheKey = ? AND path = ?`,
[removeTag.cacheKey, removeTag.path],
);
if (!Array.isArray(snippets)) {
snippets = [snippets];
}
@ -304,4 +364,44 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
return [];
}
}
static async getPathsAndSignatures(
workspaceDirs: string[],
offset: number = 0,
batchSize: number = 100,
): Promise<{
groupedByPath: { [path: string]: string[] };
hasMore: boolean;
}> {
const db = await SqliteDb.get();
await CodeSnippetsCodebaseIndex._createTables(db);
const likePatterns = workspaceDirs.map((dir) => `${dir}%`);
const placeholders = likePatterns.map(() => "?").join(" OR path LIKE ");
const query = `
SELECT path, signature
FROM code_snippets
WHERE path LIKE ${placeholders}
ORDER BY path
LIMIT ? OFFSET ?
`;
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] = [];
}
groupedByPath[path].push(signature);
}
const hasMore = rows.length === batchSize;
return { groupedByPath, hasMore };
}
}

View file

@ -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,

View file

@ -341,3 +341,7 @@ export function readAllGlobalPromptFiles(
return promptFiles;
}
export function getRepoMapFilePath(): string {
return path.join(getContinueUtilsPath(), "repo_map.txt");
}

View file

@ -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.

View file

@ -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

View file

@ -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

View file

@ -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
name: (_) @name.definition.interface
) @definition.interface

View file

@ -1,8 +1,22 @@
(class_declaration
name: (_) @name) @body
(
(comment)? @comment
(class_declaration
name: (_) @name
) @definition
)
(function_declaration
name: (_) @name) @body
(
(comment)? @comment
(function_declaration
name: (_) @name
parameters: (_) @parameters
) @definition
)
(method_definition
name: (_) @name) @body
(
(comment)? @comment
(method_definition
name: (_) @name
parameters: (_) @parameters
) @definition
)

View file

@ -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
) @definition

View file

@ -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
name: (name) @name) @definition

View file

@ -1,5 +1,7 @@
(class_definition
name: (_) @name) @body
name: (_) @name) @definition
(function_definition
name: (_) @name) @body
name: (_) @name
parameters: (_) @parameters
) @definition

View file

@ -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
type: (_) @name) @definition

View file

@ -1,11 +1,28 @@
(class_declaration
name: (_) @name) @body
(
(comment)? @comment
(class_declaration
name: (_) @name
) @definition
)
(function_declaration
name: (_) @name) @body
(
(comment)? @comment
(function_declaration
name: (_) @name
parameters: (_) @parameters
) @definition
)
(method_definition
name: (_) @name) @body
(
(comment)? @comment
(method_definition
name: (_) @name
parameters: (_) @parameters
) @definition
)
(interface_declaration
name: (_) @name) @body
(
(comment)? @comment
(interface_declaration
name: (_) @name) @definition
)