From e40c4751e15fa64317816313c4b94dd7fd2b407c Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 13 Dec 2024 15:20:35 -0800 Subject: [PATCH] path->uri more fixes --- core/context/providers/FileContextProvider.ts | 8 +- .../providers/FolderContextProvider.ts | 4 +- .../providers/RepoMapContextProvider.ts | 8 +- core/context/retrieval/repoMapRequest.ts | 33 +-- core/indexing/CodeSnippetsIndex.ts | 12 +- core/indexing/FullTextSearchCodebaseIndex.ts | 4 +- core/indexing/docs/article.ts | 12 +- core/indexing/docs/suggestions/index.ts | 4 +- core/indexing/walkDir.ts | 2 +- core/tools/implementations/viewRepoMap.ts | 5 +- .../tools/implementations/viewSubdirectory.ts | 12 +- core/util/generateRepoMap.test.ts | 9 +- core/util/generateRepoMap.ts | 214 +++++++----------- extensions/vscode/src/util/FileSearch.ts | 4 +- 14 files changed, 148 insertions(+), 183 deletions(-) diff --git a/core/context/providers/FileContextProvider.ts b/core/context/providers/FileContextProvider.ts index ebdc4afe6..674cc1a00 100644 --- a/core/context/providers/FileContextProvider.ts +++ b/core/context/providers/FileContextProvider.ts @@ -6,7 +6,7 @@ import { ContextSubmenuItem, LoadSubmenuItemsArgs, } from "../../"; -import { walkDirInWorkspaces } from "../../indexing/walkDir"; +import { walkDirs } from "../../indexing/walkDir"; import { getUriPathBasename, getShortestUniqueRelativeUriPaths, @@ -46,11 +46,7 @@ class FileContextProvider extends BaseContextProvider { args: LoadSubmenuItemsArgs, ): Promise { const workspaceDirs = await args.ide.getWorkspaceDirs(); - const results = await walkDirInWorkspaces( - args.ide, - undefined, - workspaceDirs, - ); + const results = await walkDirs(args.ide, undefined, workspaceDirs); const files = results.flat().slice(-MAX_SUBMENU_ITEMS); const withUniquePaths = getShortestUniqueRelativeUriPaths( files, diff --git a/core/context/providers/FolderContextProvider.ts b/core/context/providers/FolderContextProvider.ts index 260101863..dc5257568 100644 --- a/core/context/providers/FolderContextProvider.ts +++ b/core/context/providers/FolderContextProvider.ts @@ -5,7 +5,7 @@ import { ContextSubmenuItem, LoadSubmenuItemsArgs, } from "../../index.js"; -import { walkDirInWorkspaces } from "../../indexing/walkDir.js"; +import { walkDirs } from "../../indexing/walkDir.js"; import { getShortestUniqueRelativeUriPaths, getUriPathBasename, @@ -32,7 +32,7 @@ class FolderContextProvider extends BaseContextProvider { args: LoadSubmenuItemsArgs, ): Promise { const workspaceDirs = await args.ide.getWorkspaceDirs(); - const folders = await walkDirInWorkspaces( + const folders = await walkDirs( args.ide, { onlyDirs: true, diff --git a/core/context/providers/RepoMapContextProvider.ts b/core/context/providers/RepoMapContextProvider.ts index ac12d1e30..ae7d92bf9 100644 --- a/core/context/providers/RepoMapContextProvider.ts +++ b/core/context/providers/RepoMapContextProvider.ts @@ -6,7 +6,7 @@ import { ContextSubmenuItem, LoadSubmenuItemsArgs, } from "../../"; -import { walkDirInWorkspaces } from "../../indexing/walkDir"; +import { walkDirs } from "../../indexing/walkDir"; import generateRepoMap from "../../util/generateRepoMap"; import { getShortestUniqueRelativeUriPaths, @@ -36,7 +36,9 @@ class RepoMapContextProvider extends BaseContextProvider { name: "Repository Map", description: "Overview of the repository structure", content: await generateRepoMap(extras.llm, extras.ide, { - dirs: query === ENTIRE_PROJECT_ITEM.id ? undefined : [query], + dirUris: query === ENTIRE_PROJECT_ITEM.id ? undefined : [query], + outputRelativeUriPaths: true, + includeSignatures: false, }), }, ]; @@ -46,7 +48,7 @@ class RepoMapContextProvider extends BaseContextProvider { args: LoadSubmenuItemsArgs, ): Promise { const workspaceDirs = await args.ide.getWorkspaceDirs(); - const folders = await walkDirInWorkspaces( + const folders = await walkDirs( args.ide, { onlyDirs: true, diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index a6a77127a..f70f0a594 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -47,8 +47,9 @@ export async function requestFilesFromRepoMap( try { const repoMap = await generateRepoMap(llm, ide, { + dirUris: filterDirUri ? [filterDirUri] : undefined, includeSignatures: false, - dirs: filterDirUri ? [filterDirUri] : undefined, + outputRelativeUriPaths: false, }); const prompt = `${repoMap} @@ -72,26 +73,26 @@ This is the question that you should select relevant files for: "${input}"`; return []; } - const subDirPrefix = filterDirUri - ? getUriPathBasename(filterDirUri) + "/" - : ""; - const files = - content - .split("")[1] - ?.split("")[0] - ?.split("\n") - .filter(Boolean) - .map((file) => file.trim()) - .map((file) => subDirPrefix + file) ?? []; + // IMPORANT + + // const subDirPrefix = filterDirUri + // ? getUriPathBasename(filterDirUri) + "/" + // : ""; + const fileUris = content + .split("")[1] + ?.split("")[0] + ?.split("\n") + .filter(Boolean) + .map((uri) => uri.trim()); const chunks = await Promise.all( - files.map(async (file) => { - const content = await ide.readFile(file); + fileUris.map(async (uri) => { + const content = await ide.readFile(uri); const lineCount = content.split("\n").length; const chunk: Chunk = { - digest: file, + digest: uri, content, - filepath: file, + filepath: uri, endLine: lineCount - 1, startLine: 0, index: 0, diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 48d60083b..fa210ed00 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -390,7 +390,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { offset: number = 0, batchSize: number = 100, ): Promise<{ - groupedByPath: { [path: string]: string[] }; + groupedByUri: { [path: string]: string[] }; hasMore: boolean; }> { const db = await SqliteDb.get(); @@ -411,17 +411,17 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { const rows = await db.all(query, [...likePatterns, batchSize, offset]); - const groupedByPath: { [path: string]: string[] } = {}; + const groupedByUri: { [path: string]: string[] } = {}; for (const { path, signature } of rows) { - if (!groupedByPath[path]) { - groupedByPath[path] = []; + if (!groupedByUri[path]) { + groupedByUri[path] = []; } - groupedByPath[path].push(signature); + groupedByUri[path].push(signature); } const hasMore = rows.length === batchSize; - return { groupedByPath, hasMore }; + return { groupedByUri, hasMore }; } } diff --git a/core/indexing/FullTextSearchCodebaseIndex.ts b/core/indexing/FullTextSearchCodebaseIndex.ts index 82e4e822f..7ff54781c 100644 --- a/core/indexing/FullTextSearchCodebaseIndex.ts +++ b/core/indexing/FullTextSearchCodebaseIndex.ts @@ -1,6 +1,6 @@ import { BranchAndDir, Chunk, IndexTag, IndexingProgressUpdate } from "../"; -import { getBasename } from "../util/index"; import { RETRIEVAL_PARAMS } from "../util/parameters"; +import { getUriPathBasename } from "../util/uri"; import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex"; import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; @@ -79,7 +79,7 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { yield { progress: i / results.compute.length, - desc: `Indexing ${getBasename(item.path)}`, + desc: `Indexing ${getUriPathBasename(item.path)}`, status: "indexing", }; await markComplete([item], IndexResultType.Compute); diff --git a/core/indexing/docs/article.ts b/core/indexing/docs/article.ts index 2ae0e7995..8026280c9 100644 --- a/core/indexing/docs/article.ts +++ b/core/indexing/docs/article.ts @@ -31,6 +31,11 @@ function breakdownArticleComponent( let content = ""; let index = 0; + const fullUrl = new URL( + `${subpath}#${cleanFragment(article.title)}`, + url, + ).toString(); + const createChunk = ( chunkContent: string, chunkStartLine: number, @@ -44,11 +49,8 @@ function breakdownArticleComponent( title: cleanHeader(article.title), }, index: index++, - filepath: new URL( - `${subpath}#${cleanFragment(article.title)}`, - url, - ).toString(), - digest: subpath, + filepath: fullUrl, + digest: fullUrl, }); }; diff --git a/core/indexing/docs/suggestions/index.ts b/core/indexing/docs/suggestions/index.ts index d32d7c0d0..fac5091fd 100644 --- a/core/indexing/docs/suggestions/index.ts +++ b/core/indexing/docs/suggestions/index.ts @@ -7,7 +7,7 @@ import { ParsedPackageInfo, } from "../../.."; import { getUriPathBasename } from "../../../util/uri"; -import { walkDir, walkDirInWorkspaces } from "../../walkDir"; +import { walkDir, walkDirs } from "../../walkDir"; import { PythonPackageCrawler } from "./packageCrawlers/Python"; import { NodePackageCrawler } from "./packageCrawlers/TsJs"; @@ -25,7 +25,7 @@ export interface PackageCrawler { } export async function getAllSuggestedDocs(ide: IDE) { - const allFileUris = await walkDirInWorkspaces(ide); + const allFileUris = await walkDirs(ide); const allFiles = allFileUris.map((uri) => ({ path: uri, name: getUriPathBasename(uri), diff --git a/core/indexing/walkDir.ts b/core/indexing/walkDir.ts index b5e951dcb..a1ec2eba3 100644 --- a/core/indexing/walkDir.ts +++ b/core/indexing/walkDir.ts @@ -224,7 +224,7 @@ export async function* walkDirAsync( yield* new DFSWalker(path, ide, options).walk(); } -export async function walkDirInWorkspaces( +export async function walkDirs( ide: IDE, _optionOverrides?: WalkerOptions, dirs?: string[], // Can pass dirs to prevent duplicate calls diff --git a/core/tools/implementations/viewRepoMap.ts b/core/tools/implementations/viewRepoMap.ts index 56c265416..69f624feb 100644 --- a/core/tools/implementations/viewRepoMap.ts +++ b/core/tools/implementations/viewRepoMap.ts @@ -3,7 +3,10 @@ import generateRepoMap from "../../util/generateRepoMap"; import { ToolImpl } from "."; export const viewRepoMapImpl: ToolImpl = async (args, extras) => { - const repoMap = await generateRepoMap(extras.llm, extras.ide, {}); + const repoMap = await generateRepoMap(extras.llm, extras.ide, { + outputRelativeUriPaths: true, + includeSignatures: false, + }); return [ { name: "Repo map", diff --git a/core/tools/implementations/viewSubdirectory.ts b/core/tools/implementations/viewSubdirectory.ts index 9bd4583f2..c62887dc5 100644 --- a/core/tools/implementations/viewSubdirectory.ts +++ b/core/tools/implementations/viewSubdirectory.ts @@ -5,18 +5,18 @@ import { ToolImpl } from "."; export const viewSubdirectoryImpl: ToolImpl = async (args: any, extras) => { const { directory_path } = args; - const absoluteUri = await resolveRelativePathInDir( - directory_path, - extras.ide, - ); + const uri = await resolveRelativePathInDir(directory_path, extras.ide); - if (!absoluteUri) { + if (!uri) { throw new Error(`Directory path "${directory_path}" does not exist.`); } const repoMap = await generateRepoMap(extras.llm, extras.ide, { - dirs: [absoluteUri], + dirUris: [uri], + outputRelativeUriPaths: true, + includeSignatures: false, }); + return [ { name: "Repo map", diff --git a/core/util/generateRepoMap.test.ts b/core/util/generateRepoMap.test.ts index d1d130d31..536d3fcac 100644 --- a/core/util/generateRepoMap.test.ts +++ b/core/util/generateRepoMap.test.ts @@ -39,7 +39,7 @@ describe.skip("generateRepoMap", () => { .mockImplementation(async (dirs, offset, limit) => { // Return test data return { - groupedByPath: { + groupedByUri: { [path.join(TEST_DIR, "file1.js")]: [ "function foo() {}", "function bar() {}", @@ -60,6 +60,7 @@ describe.skip("generateRepoMap", () => { // Act const repoMapContent = await generateRepoMap(testLLM, testIde, { includeSignatures: true, + outputRelativeUriPaths: true, }); // Assert @@ -103,7 +104,7 @@ describe.skip("generateRepoMap", () => { .mockImplementation(async (dirs, offset, limit) => { // Return test data return { - groupedByPath: { + groupedByUri: { [path.join(TEST_DIR, "file1.js")]: [], [path.join(TEST_DIR, "subdir/file2.py")]: [], }, @@ -118,6 +119,7 @@ describe.skip("generateRepoMap", () => { // Act const repoMapContent = await generateRepoMap(testLLM, testIde, { includeSignatures: false, + outputRelativeUriPaths: true, }); // Assert @@ -155,7 +157,7 @@ describe.skip("generateRepoMap", () => { .mockImplementation(async (dirs, offset, limit) => { // Return test data return { - groupedByPath: { + groupedByUri: { [path.join(TEST_DIR, "file1.js")]: ["function foo() {}"], [path.join(TEST_DIR, "subdir/file2.py")]: ["def foo():"], }, @@ -185,6 +187,7 @@ describe.skip("generateRepoMap", () => { // Act const repoMapContent = await generateRepoMap(testLLM, testIde, { includeSignatures: true, + outputRelativeUriPaths: true, }); // Assert diff --git a/core/util/generateRepoMap.ts b/core/util/generateRepoMap.ts index 47a796b48..b0af8079a 100644 --- a/core/util/generateRepoMap.ts +++ b/core/util/generateRepoMap.ts @@ -1,16 +1,17 @@ import fs from "node:fs"; -import path from "node:path"; import { IDE, ILLM } from ".."; import { CodeSnippetsCodebaseIndex } from "../indexing/CodeSnippetsIndex"; -import { walkDirAsync } from "../indexing/walkDir"; +import { walkDirs } from "../indexing/walkDir"; import { pruneLinesFromTop } from "../llm/countTokens"; import { getRepoMapFilePath } from "./paths"; +import { findUriInDirs } from "./uri"; export interface RepoMapOptions { includeSignatures?: boolean; - dirs?: string[]; + dirUris?: string[]; + outputRelativeUriPaths: boolean; } class RepoMapGenerator { @@ -19,8 +20,8 @@ class RepoMapGenerator { private repoMapPath: string = getRepoMapFilePath(); private writeStream: fs.WriteStream = fs.createWriteStream(this.repoMapPath); private contentTokens: number = 0; - private repoMapDirs: string[] = []; - private allPathsInDirs: Set = new Set(); + private dirs: string[] = []; + private allUris: string[] = []; private pathsInDirsWithSnippets: Set = new Set(); private BATCH_SIZE = 100; @@ -40,123 +41,100 @@ class RepoMapGenerator { llm.contextLength * this.REPO_MAX_CONTEXT_LENGTH_RATIO; } - /* - Note, the repo map is usually USED as relative file paths (passed to LLM) - So for now, using URIs INPUTS to generate the map, but OUTPUTing relative paths - The exception if requestFilesFromRepoMap, which now converts the relative paths back to URIs - */ + private getUriForWrite(uri: string) { + if (this.options.outputRelativeUriPaths) { + return findUriInDirs(uri, this.dirs).relativePathOrBasename; + } + return uri; + } + async generate(): Promise { - this.repoMapDirs = this.options.dirs ?? (await this.ide.getWorkspaceDirs()); - this.allPathsInDirs = await this.getAllPathsInDirs(); + this.dirs = this.options.dirUris ?? (await this.ide.getWorkspaceDirs()); + this.allUris = await walkDirs(this.ide, undefined, this.dirs); - await this.initializeWriteStream(); - await this.processPathsAndSignatures(); - - this.writeStream.end(); - this.logRepoMapGeneration(); - - return fs.readFileSync(this.repoMapPath, "utf8"); - } - - private async initializeWriteStream(): Promise { + // Initialize await this.writeToStream(this.PREAMBLE); - this.contentTokens += this.llm.countTokens(this.PREAMBLE); - } - private async getAllPathsInDirs(): Promise> { - const paths = new Set(); + if (this.options.includeSignatures) { + // Process uris and signatures + let offset = 0; + while (true) { + const { groupedByUri, hasMore } = + await CodeSnippetsCodebaseIndex.getPathsAndSignatures( + this.allUris, + offset, + this.BATCH_SIZE, + ); + // process batch + for (const [uri, signatures] of Object.entries(groupedByUri)) { + let fileContent: string; - for (const dir of this.repoMapDirs) { - for await (const filepath of walkDirAsync(dir, this.ide)) { - paths.add(filepath.replace(dir, "").slice(1)); + try { + fileContent = await this.ide.readFile(uri); + } catch (err) { + console.error( + "Failed to read file:\n" + + ` Uri: ${uri}\n` + + ` Error: ${err instanceof Error ? err.message : String(err)}`, + ); + + continue; + } + + const filteredSignatures = signatures.filter( + (signature) => signature.trim() !== fileContent.trim(), + ); + + if (filteredSignatures.length > 0) { + this.pathsInDirsWithSnippets.add(uri); + } + + let content = `${this.getUriForWrite(uri)}:\n`; + + for (const signature of signatures.slice(0, -1)) { + content += `${this.indentMultilineString(signature)}\n\t...\n`; + } + + content += `${this.indentMultilineString( + signatures[signatures.length - 1], + )}\n\n`; + + if (content) { + await this.writeToStream(content); + } + } + if (!hasMore || this.contentTokens >= this.maxRepoMapTokens) { + break; + } + offset += this.BATCH_SIZE; } - } - return paths; - } - - private async processPathsAndSignatures(): Promise { - let offset = 0; - while (true) { - const { groupedByPath, hasMore } = - await CodeSnippetsCodebaseIndex.getPathsAndSignatures( - this.repoMapDirs, - offset, - this.BATCH_SIZE, - ); - await this.processBatch(groupedByPath); - if (!hasMore || this.contentTokens >= this.maxRepoMapTokens) { - break; - } - offset += this.BATCH_SIZE; - } - await this.writeRemainingPaths(); - } - - private async processBatch( - groupedByPath: Record, - ): Promise { - for (const [absolutePath, signatures] of Object.entries(groupedByPath)) { - const content = await this.processFile(absolutePath, signatures); - - if (content) { - await this.writeToStream(content); - } - } - } - - private async processFile( - absolutePath: string, - signatures: string[], - ): Promise { - const workspaceDir = - this.repoMapDirs.find((dir) => absolutePath.startsWith(dir)) || ""; - const relativePath = path.relative(workspaceDir, absolutePath); - - let fileContent: string; - - try { - fileContent = await fs.promises.readFile(absolutePath, "utf8"); - } catch (err) { - console.error( - "Failed to read file:\n" + - ` Path: ${absolutePath}\n` + - ` Error: ${err instanceof Error ? err.message : String(err)}`, + // Remaining Uris just so that written repo map isn't incomplete + const urisWithoutSnippets = this.allUris.filter( + (uri) => !this.pathsInDirsWithSnippets.has(uri), ); - return; + if (urisWithoutSnippets.length > 0) { + await this.writeToStream( + urisWithoutSnippets.map((uri) => this.getUriForWrite(uri)).join("\n"), + ); + } + } else { + // Only process uris + await this.writeToStream( + this.allUris.map((uri) => this.getUriForWrite(uri)).join("\n"), + ); } - const filteredSignatures = signatures.filter( - (signature) => signature.trim() !== fileContent.trim(), - ); + this.writeStream.end(); - if (filteredSignatures.length > 0) { - this.pathsInDirsWithSnippets.add(relativePath); + if (this.contentTokens >= this.maxRepoMapTokens) { + console.debug( + "Full repo map was unable to be generated due to context window limitations", + ); } - return this.generateContentForPath(relativePath, filteredSignatures); - } - - private generateContentForPath( - relativePath: string, - signatures: string[], - ): string { - if (this.options.includeSignatures === false) { - return `${relativePath}\n`; - } - - let content = `${relativePath}:\n`; - - for (const signature of signatures.slice(0, -1)) { - content += `${this.indentMultilineString(signature)}\n\t...\n`; - } - - content += `${this.indentMultilineString( - signatures[signatures.length - 1], - )}\n\n`; - - return content; + return fs.readFileSync(this.repoMapPath, "utf8"); } private async writeToStream(content: string): Promise { @@ -175,26 +153,6 @@ class RepoMapGenerator { await new Promise((resolve) => this.writeStream.write(content, resolve)); } - private async writeRemainingPaths(): Promise { - const pathsWithoutSnippets = new Set( - [...this.allPathsInDirs].filter( - (x) => !this.pathsInDirsWithSnippets.has(x), - ), - ); - - if (pathsWithoutSnippets.size > 0) { - await this.writeToStream(Array.from(pathsWithoutSnippets).join("\n")); - } - } - - private logRepoMapGeneration(): void { - if (this.contentTokens >= this.maxRepoMapTokens) { - console.debug( - "Full repo map was unable to be generated due to context window limitations", - ); - } - } - private indentMultilineString(str: string) { return str .split("\n") diff --git a/extensions/vscode/src/util/FileSearch.ts b/extensions/vscode/src/util/FileSearch.ts index fe977e4e5..c6707fa51 100644 --- a/extensions/vscode/src/util/FileSearch.ts +++ b/extensions/vscode/src/util/FileSearch.ts @@ -1,5 +1,5 @@ import { IDE } from "core"; -import { walkDirInWorkspaces } from "core/indexing/walkDir"; +import { walkDirs } from "core/indexing/walkDir"; // @ts-ignore import MiniSearch from "minisearch"; import * as vscode from "vscode"; @@ -24,7 +24,7 @@ export class FileSearch { }, }); private async initializeFileSearchState() { - const results = await walkDirInWorkspaces(this.ide); + const results = await walkDirs(this.ide); this.miniSearch.addAll( results.flat().map((uri) => ({ id: uri,