diff --git a/src/extract-context.ts b/src/extract-context.ts index 11dc3de..41caf25 100644 --- a/src/extract-context.ts +++ b/src/extract-context.ts @@ -1,5 +1,7 @@ import { Octokit } from "@octokit/rest"; import { execSync } from "node:child_process"; +import * as fs from "node:fs"; +import * as path from "node:path"; import type { ReviewContext } from "./types.js"; export async function extractReviewContext( @@ -41,9 +43,10 @@ export async function extractReviewContext( } let lineSnippet = ""; - if (filePath && line) { + let fullFileContent: string | undefined = undefined; + + if (filePath) { try { - // Pull only the surrounding lines around the comment let fileContent = ""; try { fileContent = execSync(`git show origin/${pr.head.ref}:${filePath}`, { @@ -57,13 +60,17 @@ export async function extractReviewContext( }); } - const lines = fileContent.split("\n"); - const start = Math.max(0, line - 10); - const end = Math.min(lines.length, line + 10); - lineSnippet = lines - .slice(start, end) - .map((l, idx) => `${start + idx + 1}: ${l}`) - .join("\n"); + fullFileContent = fileContent; + + if (line) { + const lines = fileContent.split("\n"); + const start = Math.max(0, line - 10); + const end = Math.min(lines.length, line + 10); + lineSnippet = lines + .slice(start, end) + .map((l, idx) => `${start + idx + 1}: ${l}`) + .join("\n"); + } } catch (err) { console.warn(`Could not extract local snippet for ${filePath}:`, err); } @@ -76,5 +83,127 @@ export async function extractReviewContext( commentPath: filePath, commentBody, lineSnippet, + fullFileContent, }; } + +const BINARY_OR_IGNORED_EXTENSIONS = new Set([ + ".png", ".jpg", ".jpeg", ".gif", ".ico", ".svg", ".webp", + ".pdf", ".zip", ".tar", ".gz", ".tgz", ".lock", ".bin", + ".exe", ".dylib", ".so", ".wasm", ".map", ".mp3", ".mp4" +]); + +const IGNORED_FILENAMES = new Set([ + "package-lock.json", "yarn.lock", "pnpm-lock.yaml", ".DS_Store" +]); + +/** + * Extracts key repository context (tracked file tree and readable source/test contents) + * to give LLMs full awareness of project structure, existing exports, and test suites. + */ +export function extractRepoContext( + cwd = process.cwd(), + options: { maxFileSize?: number; maxTotalSize?: number } = {} +): string { + const maxFileSize = options.maxFileSize ?? 50 * 1024; // 50 KB + const maxTotalSize = options.maxTotalSize ?? 200 * 1024; // 200 KB + + let files: string[] = []; + try { + files = execSync("git ls-files", { cwd, encoding: "utf-8" }) + .trim() + .split("\n") + .map((f) => f.trim()) + .filter(Boolean); + } catch { + return ""; + } + + if (files.length === 0) { + return ""; + } + + let totalBytes = 0; + const fileSections: string[] = []; + + for (const relPath of files) { + const ext = path.extname(relPath).toLowerCase(); + const basename = path.basename(relPath); + + if (BINARY_OR_IGNORED_EXTENSIONS.has(ext) || IGNORED_FILENAMES.has(basename)) { + continue; + } + + const fullPath = path.resolve(cwd, relPath); + try { + const stat = fs.statSync(fullPath); + if (!stat.isFile() || stat.size > maxFileSize) { + continue; + } + if (totalBytes + stat.size > maxTotalSize) { + break; + } + const content = fs.readFileSync(fullPath, "utf-8"); + if (content.includes("\0")) { + continue; // Skip binary files that had unexpected extensions + } + totalBytes += stat.size; + fileSections.push(`--- File: ${relPath} ---\n${content}`); + } catch { + // Ignore read errors + } + } + + const output: string[] = [ + "### Tracked Repository Files:", + ...files.map((f) => `- ${f}`), + "", + "### Existing File Contents:", + ...fileSections, + ]; + + return output.join("\n"); +} + +/** + * Inspects deterministic failure output (test logs, compiler traces) + * and retrieves the on-disk content of any mentioned repository files (e.g. failing test files). + */ +export function extractFailureRelatedFiles( + failureOutput: string, + cwd = process.cwd() +): Array<{ path: string; content: string }> { + const results: Array<{ path: string; content: string }> = []; + const visited = new Set(); + + let trackedFiles: string[] = []; + try { + trackedFiles = execSync("git ls-files", { cwd, encoding: "utf-8" }) + .trim() + .split("\n") + .map((f) => f.trim()) + .filter(Boolean); + } catch { + return results; + } + + // Look for exact matches of tracked files inside failure output + for (const relPath of trackedFiles) { + if (failureOutput.includes(relPath)) { + const fullPath = path.resolve(cwd, relPath); + if (!visited.has(relPath) && fs.existsSync(fullPath)) { + try { + const content = fs.readFileSync(fullPath, "utf-8"); + if (!content.includes("\0")) { + visited.add(relPath); + results.push({ path: relPath, content }); + } + } catch { + // Ignore read errors + } + } + } + } + + return results; +} diff --git a/src/git.ts b/src/git.ts index 05cea1f..3b33818 100644 --- a/src/git.ts +++ b/src/git.ts @@ -64,6 +64,26 @@ export class GitManager { } } + getFileContent(filePath: string): string | null { + try { + const fullPath = path.resolve(this.cwd, filePath); + if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) { + return fs.readFileSync(fullPath, "utf-8"); + } + return null; + } catch { + return null; + } + } + + listTrackedFiles(): string[] { + try { + return this.exec("git ls-files").split("\n").map((f) => f.trim()).filter(Boolean); + } catch { + return []; + } + } + getLatestCommitHash(): string { return this.exec("git rev-parse HEAD"); } diff --git a/src/handle-issue.ts b/src/handle-issue.ts index 2022fb5..12ec3c3 100644 --- a/src/handle-issue.ts +++ b/src/handle-issue.ts @@ -1,5 +1,6 @@ import { Octokit } from "@octokit/rest"; import { formatPrDescription } from "./ascii.js"; +import { extractFailureRelatedFiles, extractRepoContext } from "./extract-context.js"; import { GitManager } from "./git.js"; import { ModelClient } from "./llm.js"; import { VerificationRunner } from "./runner.js"; @@ -23,7 +24,7 @@ export async function handleIssueIntake(params: { octokit, config, issue, - repoContext, + repoContext: providedRepoContext, gitManager = new GitManager(), modelClient = new ModelClient(undefined, config.model), verificationRunner = new VerificationRunner(), @@ -36,6 +37,9 @@ export async function handleIssueIntake(params: { console.log(`Creating isolated branch: ${branchName}`); gitManager.checkoutBranch(branchName, true); + // Extract repo context if not explicitly provided + const repoContext = providedRepoContext ?? extractRepoContext(); + // 2. Initial LLM code generation console.log("Generating solution with Gemini..."); let solution = await modelClient.generateIssueSolution({ @@ -79,10 +83,23 @@ export async function handleIssueIntake(params: { if (attempts < config.maxRetries) { console.log("Feeding failure output back to Gemini for self-correction..."); + + const currentFileContents = accumulatedEdits + .map((e) => { + const content = typeof gitManager.getFileContent === "function" ? gitManager.getFileContent(e.path) : null; + return content !== null ? { path: e.path, content } : null; + }) + .filter((item): item is { path: string; content: string } => item !== null); + + const relatedFiles = extractFailureRelatedFiles(lastFailure); + const correction = await modelClient.generateCorrection({ originalGoal: `Issue #${issue.issueNumber}: ${issue.title}\n${issue.body}`, failureSummary: lastFailure, previousEdits: accumulatedEdits, + currentFileContents, + relatedFiles, + repoContext, }); if (correction.edits.length > 0) { diff --git a/src/handle-revision.ts b/src/handle-revision.ts index 8da75db..66b8e2c 100644 --- a/src/handle-revision.ts +++ b/src/handle-revision.ts @@ -1,5 +1,6 @@ import { Octokit } from "@octokit/rest"; import { formatRevisionComment } from "./ascii.js"; +import { extractFailureRelatedFiles } from "./extract-context.js"; import { GitManager } from "./git.js"; import { ModelClient } from "./llm.js"; import { VerificationRunner } from "./runner.js"; @@ -93,10 +94,22 @@ export async function handlePrRevision(params: { if (attempts < config.maxRetries) { console.log("Re-prompting model with compiler/test failure output..."); + + const currentFileContents = accumulatedEdits + .map((e) => { + const content = typeof gitManager.getFileContent === "function" ? gitManager.getFileContent(e.path) : null; + return content !== null ? { path: e.path, content } : null; + }) + .filter((item): item is { path: string; content: string } => item !== null); + + const relatedFiles = extractFailureRelatedFiles(lastFailure); + const correction = await modelClient.generateCorrection({ originalGoal: `Address PR #${ctx.prNumber} review comment: "${ctx.commentBody}"`, failureSummary: lastFailure, previousEdits: accumulatedEdits, + currentFileContents, + relatedFiles, }); if (correction.edits.length > 0) { diff --git a/src/index.ts b/src/index.ts index 0f4bd4a..0ed8bac 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,7 +5,7 @@ import { Command } from "commander"; import * as dotenv from "dotenv"; import * as fs from "node:fs"; import { HARVEY_ASCII } from "./ascii.js"; -import { extractReviewContext } from "./extract-context.js"; +import { extractRepoContext, extractReviewContext } from "./extract-context.js"; import { handleIssueIntake } from "./handle-issue.js"; import { handlePrRevision } from "./handle-revision.js"; import { VerificationRunner } from "./runner.js"; @@ -106,10 +106,13 @@ export async function runGitHubAction(options?: { labels: (event.issue.labels || []).map((l: any) => l.name), }; + const repoContext = extractRepoContext(); + await handleIssueIntake({ octokit, config, issue: issueContext, + repoContext, }); return; } @@ -203,6 +206,7 @@ export function createCli(): Command { .action(async (opts) => { const config = getConfig(); const octokit = getOctokit(); + const repoContext = extractRepoContext(); await handleIssueIntake({ octokit, config, @@ -213,6 +217,7 @@ export function createCli(): Command { branchName: `githound/issue-${opts.number}`, labels: ["githound"], }, + repoContext, }); }); diff --git a/src/llm.ts b/src/llm.ts index ad85725..11b262e 100644 --- a/src/llm.ts +++ b/src/llm.ts @@ -71,13 +71,14 @@ Title: "${params.title}" Description: ${params.body} -${params.repoContext ? `Repository Context:\n${params.repoContext}` : ""} - +${params.repoContext ? `Repository Context & Existing Files:\n${params.repoContext}\n` : ""} Instructions: 1. Provide the complete code edits needed to solve this issue. -2. Use the \`write_file\` tool to create or update files. -3. Keep changes clean, minimal, robust, and well-tested. -4. Include unit tests for any new logic where applicable. +2. Carefully inspect the existing repository files, module exports, and test expectations provided in the context. +3. Preserve existing exported functions, constants, and types required by tests and other modules, unless explicitly asked to modify them. +4. Use the \`write_file\` tool to create or update files. +5. Keep changes clean, minimal, robust, and well-tested. +6. Include or update unit tests for any new logic where applicable. `; return this.runModelLoop(prompt); @@ -90,7 +91,7 @@ The reviewer left the following feedback on pull request #${ctx.prNumber}: "${ctx.commentBody}" ${ctx.commentPath ? `Target File: ${ctx.commentPath}` : ""} -${ctx.lineSnippet ? `Code context near comment:\n\`\`\`\n${ctx.lineSnippet}\n\`\`\`` : ""} +${ctx.fullFileContent ? `Current Target File Content:\n\`\`\`\n${ctx.fullFileContent}\n\`\`\`` : (ctx.lineSnippet ? `Code context near comment:\n\`\`\`\n${ctx.lineSnippet}\n\`\`\`` : "")} Current PR Diff: \`\`\`diff @@ -100,8 +101,9 @@ ${ctx.diff} Instructions: 1. Address the review comment precisely. 2. Ensure changes are minimal and adhere strictly to project conventions. -3. Use the \`write_file\` tool to update files. -4. Update or add unit tests if the reviewer requested test coverage. +3. Preserve existing exports, imports, and architectural patterns. +4. Use the \`write_file\` tool to update files. +5. Update or add unit tests if the reviewer requested test coverage. `; return this.runModelLoop(prompt); @@ -111,7 +113,26 @@ Instructions: originalGoal: string; failureSummary: string; previousEdits: FileEdit[]; + currentFileContents?: Array<{ path: string; content: string }>; + relatedFiles?: Array<{ path: string; content: string }>; + repoContext?: string; }): Promise { + const contextSections: string[] = []; + + if (params.currentFileContents && params.currentFileContents.length > 0) { + contextSections.push("Current On-Disk Content of Modified Files:"); + for (const f of params.currentFileContents) { + contextSections.push(`--- File: ${f.path} ---\n${f.content}\n`); + } + } + + if (params.relatedFiles && params.relatedFiles.length > 0) { + contextSections.push("Failing Tests or Related Files in Repository:"); + for (const f of params.relatedFiles) { + contextSections.push(`--- File: ${f.path} ---\n${f.content}\n`); + } + } + const prompt = ` You are GitHound powered by Google Gemini. The previous code modifications triggered a failure in the deterministic verification gate. @@ -126,10 +147,13 @@ ${params.failureSummary} Previously modified files: ${params.previousEdits.map((e) => `- ${e.path} (${e.action})`).join("\n")} +${contextSections.length > 0 ? contextSections.join("\n") + "\n" : ""} Instructions: 1. Analyze the exact compiler, typechecker, or test failure above. -2. Provide corrective file updates using the \`write_file\` tool to fix the errors. -3. Do not introduce extraneous changes. +2. Inspect the current file contents and failing tests carefully to understand the exact assertion or syntax error. +3. Preserve all required module exports, function signatures, and architectural conventions tested by the test suite. +4. Provide corrective file updates using the \`write_file\` tool to fix the errors. +5. Do not introduce extraneous changes. `; return this.runModelLoop(prompt); diff --git a/src/types.ts b/src/types.ts index 1c01793..e84e9a9 100644 --- a/src/types.ts +++ b/src/types.ts @@ -5,6 +5,7 @@ export interface ReviewContext { commentPath?: string; commentBody: string; lineSnippet?: string; + fullFileContent?: string; } export interface IssueContext { diff --git a/tests/extract-context.test.ts b/tests/extract-context.test.ts index 142726a..9f014ae 100644 --- a/tests/extract-context.test.ts +++ b/tests/extract-context.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it, vi } from "vitest"; -import { extractReviewContext } from "../src/extract-context.js"; +import { + extractFailureRelatedFiles, + extractRepoContext, + extractReviewContext, +} from "../src/extract-context.js"; describe("extractReviewContext", () => { it("extracts PR branch and diff", async () => { @@ -33,3 +37,29 @@ describe("extractReviewContext", () => { expect(ctx.commentBody).toBe("/hound please optimize"); }); }); + +describe("extractRepoContext", () => { + it("extracts repository file tree and file contents", () => { + const context = extractRepoContext(); + expect(context).toContain("### Tracked Repository Files:"); + expect(context).toContain("package.json"); + expect(context).toContain("### Existing File Contents:"); + expect(context).toContain("--- File: package.json ---"); + }); +}); + +describe("extractFailureRelatedFiles", () => { + it("detects files mentioned in failure logs", () => { + const fakeFailureLog = "AssertionError: failed at src/index.ts:15:10"; + const files = extractFailureRelatedFiles(fakeFailureLog); + expect(files.some((f) => f.path === "src/index.ts")).toBe(true); + const indexFile = files.find((f) => f.path === "src/index.ts"); + expect(indexFile?.content).toContain("export function"); + }); + + it("returns empty array when no files are mentioned", () => { + const fakeFailureLog = "General error without any file references"; + const files = extractFailureRelatedFiles(fakeFailureLog); + expect(files).toEqual([]); + }); +}); diff --git a/tests/git.test.ts b/tests/git.test.ts index f8f4e14..f1bad84 100644 --- a/tests/git.test.ts +++ b/tests/git.test.ts @@ -59,4 +59,13 @@ describe("GitManager", () => { git.applyFileEdits([{ path: "temp.txt", content: "", action: "delete" }]); expect(fs.existsSync(path.join(tempDir, "temp.txt"))).toBe(false); }); + + it("reads file content and lists tracked files", () => { + git.applyFileEdits([{ path: "tracked.txt", content: "hello hound", action: "create" }]); + git.commitAll("add tracked file"); + + expect(git.getFileContent("tracked.txt")).toBe("hello hound"); + expect(git.getFileContent("nonexistent.txt")).toBeNull(); + expect(git.listTrackedFiles()).toContain("tracked.txt"); + }); }); diff --git a/tests/handlers.test.ts b/tests/handlers.test.ts index f8aaae5..8ee2b56 100644 --- a/tests/handlers.test.ts +++ b/tests/handlers.test.ts @@ -88,6 +88,7 @@ describe("Handlers: Issue Intake & PR Revision", () => { applyFileEdits: vi.fn().mockReturnValue(["src/slugify.ts"]), commitAll: vi.fn().mockReturnValue("fedcba0987654321"), pushBranch: vi.fn(), + getFileContent: vi.fn().mockReturnValue("function slugify() {}"), }; const mockModel: any = {