import * as fs from "node:fs"; import * as path from "node:path"; import * as crypto from "node:crypto"; import { walkWorkspaceFiles, DEFAULT_IGNORED_DIRS, type WorkspaceWalkCache } from "./workspace_walker"; import { extractFileTags, isTestPath, SymbolDef } from "./tag_extractor"; import { TreeSitterEngine } from "./tree_sitter_engine"; import { chunkHtmlFile } from "./html_chunker"; export interface CodeChunk { id: string; // e.g. "src/auth.ts:45-90#verifyToken" filePath: string; // Relative path absolutePath: string; startLine: number; endLine: number; symbolName: string; kind: string; // "function" | "class" | "method" | "interface" | "type" | "block" signature: string; breadcrumb: string; // e.g. "// [File: src/auth.ts] > [Class: AuthManager] > [Function: verifyToken]" content: string; // The full code block text textForEmbedding: string;// Search-optimized representation hash: string; // SHA-256 hash of content } export const CODE_EXTENSIONS = new Set([ ".ts", ".tsx", ".js", ".jsx", ".py", ".rs", ".go", ".c", ".cpp", ".cc", ".cxx", ".h", ".hpp", ".hh", ".hxx", ".java", ".cs", ".rb", ".php", ".swift", ".sh", ".bash", ".sql" ]); export const HTML_EXTENSIONS = new Set([ ".html", ".htm" ]); export const SUPPORTED_EXTENSIONS = new Set([ ...CODE_EXTENSIONS, ...HTML_EXTENSIONS ]); export function isHtmlPath(relPath: string): boolean { const ext = path.extname(relPath).toLowerCase(); return HTML_EXTENSIONS.has(ext); } export const IGNORED_DIRS = DEFAULT_IGNORED_DIRS; export const MAX_INDEX_FILE_BYTES = 2 * 1024 * 1024; export const MAX_INDEX_WORKSPACE_BYTES = 20 * 1024 * 1024; export const MAX_INDEX_CHUNKS = 10_000; export const MAX_INDEX_FILES = 500; /** Indexable files a walk collects for ranking; past this the walk stops in directory order. */ export const MAX_WALK_FILES = 20_000; const VENDORED_PATH = /(^|\/)(deps|third_party|thirdparty|external|extern)\//; /** Index priority when the caps cannot hold every file: 0 project source, 1 test, 2 vendored (a vendored test is vendored). */ export function fileTier(relPath: string): number { return VENDORED_PATH.test(relPath) ? 2 : isTestPath(relPath) ? 1 : 0; } /** * Compute SHA-256 hash of a string. */ export function computeHash(content: string): string { return crypto.createHash("sha256").update(content, "utf8").digest("hex").slice(0, 16); } /** * Chunk a single source file into logical AST-bounded chunks. */ export function chunkFile(rootDir: string, filePath: string, content?: string): CodeChunk[] { const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(rootDir, filePath); const ext = path.extname(absPath).toLowerCase(); if (!SUPPORTED_EXTENSIONS.has(ext)) return []; try { if (fs.statSync(absPath).size > MAX_INDEX_FILE_BYTES) return []; } catch { return []; } const relPath = path.relative(rootDir, absPath).replace(/\\/g, "/"); let fileContent = content; if (fileContent === undefined) { try { fileContent = fs.readFileSync(absPath, "utf-8"); } catch { return []; } } if (Buffer.byteLength(fileContent, "utf8") > MAX_INDEX_FILE_BYTES) return []; if (HTML_EXTENSIONS.has(ext)) { return chunkHtmlFile(rootDir, absPath, fileContent); } const lines = fileContent.split("\n"); if (lines.length === 0) return []; const chunks: CodeChunk[] = []; // 1. Extract AST symbols using extractFileTags const tags = extractFileTags(absPath, fileContent); const defs = [...tags.definitions]; // For test files (.test., .spec., /test/, /tests/), also extract top-level test blocks (describe/it/test/suite) // so test cases and assertions are indexed by code_search. if (isTestPath(relPath) && (ext === ".ts" || ext === ".tsx" || ext === ".js" || ext === ".jsx")) { const tsEngine = TreeSitterEngine.getInstance(); const parser = tsEngine.getParser(ext); if (parser) { try { const tree = parser.parse(fileContent); const root = tree.rootNode; for (let i = 0; i < root.childCount; i++) { const child = root.child(i); if (child.type === "expression_statement") { let expr = child.firstNamedChild; let callee: any = null; let argsNode: any = null; while (expr && expr.type === "call_expression") { const fn = expr.childForFieldName("function"); const args = expr.childForFieldName("arguments"); if (args && !argsNode) argsNode = args; if (fn) { callee = fn; if (fn.type === "call_expression") { expr = fn; } else { break; } } else { break; } } if (callee) { const calleeText = callee.text; const match = calleeText.match(/^(?:(?:suite|describe|context|it|test)(?:\.(?:only|skip|each|todo|concurrent|serial))?)/); if (match) { let title = ""; if (argsNode) { for (const arg of argsNode.namedChildren) { if (arg.type === "string" || arg.type === "template_string") { title = arg.text.replace(/^['"`]|['"`]$/g, ""); break; } } } const testName = title ? `${match[0]}('${title}')` : match[0]; const firstLine = fileContent.slice(child.startIndex, fileContent.indexOf("\n", child.startIndex)).trim(); defs.push({ name: testName, kind: "test", signature: firstLine.length < 120 ? firstLine : testName, line: child.startPosition.row + 1, endLine: child.endPosition.row + 1, }); } } } } } catch { // Tree-sitter parsing is best-effort fallback } } } defs.sort((a, b) => a.line - b.line); // If file has no AST definitions or is small (< 40 lines), chunk as single whole file if (defs.length === 0 || lines.length <= 40) { const wholeContent = lines.join("\n"); const breadcrumb = `// [File: ${relPath}]`; const hash = computeHash(wholeContent); chunks.push({ id: `${relPath}:1-${lines.length}`, filePath: relPath, absolutePath: absPath, startLine: 1, endLine: lines.length, symbolName: path.basename(relPath), kind: "file", signature: `File: ${relPath}`, breadcrumb, content: wholeContent, textForEmbedding: `${breadcrumb}\n${wholeContent.slice(0, 1500)}`, hash, }); return chunks; } // 2. Map symbol spans using delimiter & indentation boundaries interface SymbolSpan { def: SymbolDef; startLine: number; endLine: number; parentClass?: string; } const spans: SymbolSpan[] = []; let currentClass: string | undefined = undefined; let currentClassEndLine = -1; for (let i = 0; i < defs.length; i++) { const def = defs[i]; const startIdx = Math.max(0, def.line - 1); let endIdx = lines.length - 1; if (def.line > currentClassEndLine) { currentClass = undefined; } if (def.kind === "class") { currentClass = def.name; } if (def.endLine && def.endLine >= def.line) { // Exact AST node boundaries from Tree-sitter endIdx = Math.min(lines.length - 1, def.endLine - 1); } else if (ext === ".py") { // Python scope const defLine = lines[startIdx]; const matchIndent = defLine.match(/^(\s*)/); const baseIndent = matchIndent ? matchIndent[1].length : 0; for (let j = startIdx + 1; j < lines.length; j++) { const line = lines[j]; if (!line.trim() || line.trim().startsWith("#")) continue; const indent = line.match(/^(\s*)/)?.[1].length || 0; if (indent <= baseIndent) { endIdx = j - 1; break; } endIdx = j; } } else { // Brace based scope (fallback) let braceCount = 0; let foundOpenBrace = false; for (let j = startIdx; j < lines.length; j++) { const line = lines[j]; for (const ch of line) { if (ch === "{") { braceCount++; foundOpenBrace = true; } else if (ch === "}") { braceCount--; } } if (foundOpenBrace && braceCount <= 0) { endIdx = j; break; } } } // Bound endLine to before next top-level def if necessary // (Do not clamp test blocks, as they often contain nested type/variable definitions) if (i + 1 < defs.length && endIdx >= defs[i + 1].line - 1 && def.kind !== "class" && def.kind !== "test") { endIdx = Math.min(endIdx, defs[i + 1].line - 2); } endIdx = Math.max(startIdx, Math.min(lines.length - 1, endIdx)); if (def.kind === "class") { currentClassEndLine = endIdx + 1; } spans.push({ def, startLine: startIdx + 1, endLine: endIdx + 1, parentClass: def.kind !== "class" && def.line <= currentClassEndLine ? currentClass : undefined, }); } // 3. Construct CodeChunk objects from spans for (const span of spans) { const startIdx = span.startLine - 1; const endIdx = span.endLine - 1; const chunkLines = lines.slice(startIdx, endIdx + 1); const chunkContent = chunkLines.join("\n"); if (!chunkContent.trim()) continue; let breadcrumb = `// [File: ${relPath}]`; if (span.parentClass) { breadcrumb += ` > [Class: ${span.parentClass}]`; } breadcrumb += ` > [${span.def.kind.toUpperCase()}: ${span.def.name}]`; const textForEmbedding = `${breadcrumb}\nSignature: ${span.def.signature}\n\n${chunkContent.slice(0, 1500)}`; const hash = computeHash(chunkContent); chunks.push({ id: `${relPath}:${span.startLine}-${span.endLine}#${span.def.name}`, filePath: relPath, absolutePath: absPath, startLine: span.startLine, endLine: span.endLine, symbolName: span.def.name, kind: span.def.kind, signature: span.def.signature, breadcrumb, content: chunkContent, textForEmbedding, hash, }); } return chunks; } /** * Find supported source files in a workspace using the same traversal policy as * chunkWorkspace. The search index uses this to check live file freshness * without reparsing unchanged files. * * Returns the first `maxFiles` files in index priority order: fileTier, then * workspace-relative path in code-unit order, independent of directory order. */ export function findChunkableFiles(rootDir: string, maxFiles = MAX_INDEX_FILES, cache?: WorkspaceWalkCache): string[] { return rankChunkableFiles(rootDir, cache, Math.max(maxFiles, MAX_WALK_FILES)).slice(0, maxFiles).map((entry) => entry.file); } export interface RankedFile { readonly file: string; /** Workspace-relative path with forward slashes. */ readonly rel: string; readonly tier: number; } /** A warm search repeats an unchanged walk; ranking 20,000 paths each time would cost more than the walk check. */ const rankingMemo = new WeakMap(); /** Every walked indexable file (up to `maxWalk`) in index priority order. The result is shared: do not mutate it. */ export function rankChunkableFiles(rootDir: string, cache?: WorkspaceWalkCache, maxWalk = MAX_WALK_FILES): readonly RankedFile[] { const options = { rootDir, maxFiles: maxWalk, extensions: SUPPORTED_EXTENSIONS, includeGithub: true, }; const walked = cache ? cache.walk(options) : walkWorkspaceFiles(options); const memo = cache && rankingMemo.get(cache); if (memo && memo.rootDir === rootDir && memo.walked.length === walked.length && memo.walked.every((file, i) => file === walked[i])) { return memo.ranked; } // The walker builds every path from the resolved root, so slicing equals path.relative at a fraction of the cost. const root = path.resolve(rootDir); const prefix = root.endsWith(path.sep) ? root.length : root.length + 1; const ranked = walked .map((file) => { const rel = file.slice(prefix).replace(/\\/g, "/"); return { file, rel, tier: fileTier(rel) }; }) .sort((a, b) => a.tier - b.tier || (isHtmlPath(a.rel) !== isHtmlPath(b.rel) ? (isHtmlPath(a.rel) ? 1 : -1) : 0) || (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0)); if (cache) rankingMemo.set(cache, { rootDir, walked, ranked }); return ranked; } /** * Scan workspace and chunk all supported source files. */ export function chunkWorkspace(rootDir: string, maxFiles = 500): { chunks: CodeChunk[]; fileCount: number } { const files = findChunkableFiles(rootDir, maxFiles); const chunks: CodeChunk[] = []; for (const filePath of files) { chunks.push(...chunkFile(rootDir, filePath)); } return { chunks, fileCount: files.length }; }