Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
147 changes: 138 additions & 9 deletions src/extract-context.ts
Original file line number Diff line number Diff line change
@@ -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(
Expand Down Expand Up @@ -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}`, {
Expand All @@ -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);
}
Expand All @@ -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<string>();

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;
}
20 changes: 20 additions & 0 deletions src/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
Expand Down
19 changes: 18 additions & 1 deletion src/handle-issue.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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(),
Expand All @@ -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({
Expand Down Expand Up @@ -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) {
Expand Down
13 changes: 13 additions & 0 deletions src/handle-revision.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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) {
Expand Down
7 changes: 6 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -203,6 +206,7 @@ export function createCli(): Command {
.action(async (opts) => {
const config = getConfig();
const octokit = getOctokit();
const repoContext = extractRepoContext();
await handleIssueIntake({
octokit,
config,
Expand All @@ -213,6 +217,7 @@ export function createCli(): Command {
branchName: `githound/issue-${opts.number}`,
labels: ["githound"],
},
repoContext,
});
});

Expand Down
Loading
Loading