fix: avoid slow conflict whitespace retries

This commit is contained in:
lezi-fun committed 2026-08-14 13:40:58 +08:00
1 parent 785cddedd9
commit 135bc060e2
2 files changed
+176 -9

No files matched your search

+141 -8
View File
@@ -41,6 +41,12 @@ type SnapshotFile = {
size: number;
};
type DiffCheckWhitespaceDiagnostic = {
file: string;
line: number;
kind: "trailing-whitespace" | "space-before-tab";
};
export function canAutoResolveConflicts(input: ConflictResolutionEligibility): boolean {
return (
input.enabled &&
@@ -187,15 +193,54 @@ export async function resolvePullRequestConflicts(
}
let diffCheck = await runCommandAllowFailure(
"git",
["diff", "--check", "--cached"],
buildConflictDiffCheckArgs(agentChanges),
worktree,
gitEnv
);
if (diffCheck.code !== 0) {
const deterministicRepairFiles = await repairDiffCheckWhitespace(
snapshot,
commandFailureOutput(diffCheck)
);
if (deterministicRepairFiles.length > 0) {
const afterDeterministicRepair = await inventorySnapshot(snapshot);
await applySnapshotChanges(
snapshot,
worktree,
deterministicRepairFiles,
afterDeterministicRepair
);
await runCommand("git", ["add", "-A"], worktree, gitEnv);
afterAgent = afterDeterministicRepair;
agentChanges = diffSnapshotInventories(beforeAgent, afterAgent);
diffCheck = await runCommandAllowFailure(
"git",
buildConflictDiffCheckArgs(agentChanges),
worktree,
gitEnv
);
logger.info(
{
pullNumber: params.pullNumber,
files: deterministicRepairFiles,
remainingErrors: diffCheck.code !== 0
},
"Applied deterministic Git diff-check whitespace repairs."
);
}
}
if (diffCheck.code !== 0) {
const previousAgent = afterAgent;
await runGooseAgent(buildDiffCheckRepairPrompt(commandFailureOutput(diffCheck)), snapshot, {
timeoutMs: remainingConflictTime(resolutionStartedAt, CONFLICT_AGENT_TIMEOUT_MS)
});
try {
await runGooseAgent(buildDiffCheckRepairPrompt(commandFailureOutput(diffCheck)), snapshot, {
timeoutMs: remainingConflictTime(resolutionStartedAt, CONFLICT_AGENT_TIMEOUT_MS)
});
} catch (error) {
if (error instanceof Error && error.message.toLowerCase().includes("timed out")) {
throw new Error("git diff --check goose correction timed out.", { cause: error });
}
throw error;
}
afterAgent = await inventorySnapshot(snapshot);
const correctionChanges = diffSnapshotInventories(previousAgent, afterAgent);
if (correctionChanges.length === 0) {
@@ -214,9 +259,10 @@ export async function resolvePullRequestConflicts(
`goose reintroduced unresolved conflicts while correcting diff issues: ${remainingAfterCorrection.join(", ")}`
);
}
agentChanges = diffSnapshotInventories(beforeAgent, afterAgent);
diffCheck = await runCommandAllowFailure(
"git",
["diff", "--check", "--cached"],
buildConflictDiffCheckArgs(agentChanges),
worktree,
gitEnv
);
@@ -260,9 +306,10 @@ export async function resolvePullRequestConflicts(
`goose reintroduced unresolved conflicts while correcting validation failures: ${remainingAfterValidationRepair.join(", ")}`
);
}
agentChanges = diffSnapshotInventories(beforeAgent, afterAgent);
const repairedDiffCheck = await runCommandAllowFailure(
"git",
["diff", "--check", "--cached"],
buildConflictDiffCheckArgs(agentChanges),
worktree,
gitEnv
);
@@ -271,8 +318,6 @@ export async function resolvePullRequestConflicts(
`git diff --check failed after goose validation correction: ${commandFailureOutput(repairedDiffCheck)}`
);
}
agentChanges = diffSnapshotInventories(beforeAgent, afterAgent);
validation = await runIsolatedWorkspaceCommand(
config.conflictTestCommand,
snapshot,
@@ -421,6 +466,16 @@ export function buildConflictReviewDiffArgs(changedFiles: string[]): string[] {
return ["diff", "--cached", "--no-ext-diff", "--unified=24", "--", ...changedFiles];
}
export function buildConflictDiffCheckArgs(changedFiles: string[]): string[] {
if (changedFiles.length === 0) {
throw new Error("Conflict diff check requires at least one agent-changed file.");
}
for (const file of changedFiles) {
validateAgentChangePath(file);
}
return ["diff", "--check", "--cached", "--", ...changedFiles];
}
export function describeConflictResolutionFailure(error: unknown): string {
const message = error instanceof Error ? error.message.toLowerCase() : "";
if (message.includes("refusing to merge unrelated histories") || message.includes("shallow")) {
@@ -451,6 +506,9 @@ export function describeConflictResolutionFailure(error: unknown): string {
if (message.includes("conflict resolution timed out")) {
return "Conflict repair exceeded its 12-minute total time budget and stopped safely. No commit was pushed.";
}
if (message.includes("git diff --check goose correction timed out")) {
return "The whitespace or conflict-marker correction pass exceeded its 4-minute limit. No commit was pushed.";
}
if (message.includes("git diff --check failed")) {
return "The candidate resolution still contained Git whitespace or conflict-marker errors after one automatic correction pass. No commit was pushed.";
}
@@ -533,6 +591,81 @@ function buildDiffCheckRepairPrompt(checkOutput: string): string {
].join("\n");
}
export function parseDiffCheckWhitespaceDiagnostics(
output: string
): DiffCheckWhitespaceDiagnostic[] {
const diagnostics: DiffCheckWhitespaceDiagnostic[] = [];
for (const line of output.split(/\r?\n/)) {
const match = /^(.*):(\d+): (trailing whitespace|space before tab in indent)\.$/.exec(line);
if (!match) {
continue;
}
const [, file, lineNumber, message] = match;
if (!file || file.startsWith('"') || !lineNumber) {
continue;
}
diagnostics.push({
file,
line: Number(lineNumber),
kind: message === "trailing whitespace" ? "trailing-whitespace" : "space-before-tab"
});
}
return diagnostics;
}
export function repairDiffCheckContent(
content: string,
diagnostics: DiffCheckWhitespaceDiagnostic[]
): string {
const lines = content.split("\n");
for (const diagnostic of diagnostics) {
const index = diagnostic.line - 1;
const line = lines[index];
if (line === undefined) {
continue;
}
if (diagnostic.kind === "trailing-whitespace") {
lines[index] = line.replace(/[ \t]+(?=\r?$)/, "");
continue;
}
const indentation = /^[ \t]*/.exec(line)?.[0] ?? "";
const repairedIndentation = indentation.replace(/ +(?=\t)/g, "");
lines[index] = repairedIndentation + line.slice(indentation.length);
}
return lines.join("\n");
}
async function repairDiffCheckWhitespace(snapshot: string, output: string): Promise<string[]> {
const byFile = new Map<string, DiffCheckWhitespaceDiagnostic[]>();
for (const diagnostic of parseDiffCheckWhitespaceDiagnostics(output)) {
validateAgentChangePath(diagnostic.file);
const fileDiagnostics = byFile.get(diagnostic.file) ?? [];
fileDiagnostics.push(diagnostic);
byFile.set(diagnostic.file, fileDiagnostics);
}
const changedFiles: string[] = [];
for (const [relativePath, diagnostics] of byFile) {
const absolutePath = safeFilePath(snapshot, relativePath);
const content = await fs.readFile(absolutePath, "utf8").catch((error: unknown) => {
if (isFileNotFoundError(error)) {
return undefined;
}
throw error;
});
if (content === undefined) {
continue;
}
const repaired = repairDiffCheckContent(content, diagnostics);
if (repaired === content) {
continue;
}
await fs.writeFile(absolutePath, repaired);
changedFiles.push(relativePath);
}
return changedFiles.sort();
}
async function confirmFinalResolution(input: {
pullNumber: number;
baseBranch: string;
+35 -1
View File
@@ -1,13 +1,16 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
buildConflictDiffCheckArgs,
buildValidationRepairPrompt,
buildConflictPushArgs,
buildConflictReviewDiffArgs,
canAutoResolveConflicts,
describeConflictResolutionFailure,
diffSnapshotInventories,
parseFinalConfirmation
parseDiffCheckWhitespaceDiagnostics,
parseFinalConfirmation,
repairDiffCheckContent
} from "../src/review/conflictResolver.js";
const eligible = {
@@ -48,6 +51,15 @@ test("conflict final review scopes the diff to agent-changed files", () => {
]);
assert.throws(() => buildConflictReviewDiffArgs([]), /at least one agent-changed file/);
assert.throws(() => buildConflictReviewDiffArgs([".env"]), /protected path/);
assert.deepEqual(buildConflictDiffCheckArgs(["server.js", "public/js/app.js"]), [
"diff",
"--check",
"--cached",
"--",
"server.js",
"public/js/app.js"
]);
assert.throws(() => buildConflictDiffCheckArgs([]), /at least one agent-changed file/);
});
test("conflict failures are actionable without exposing raw command output", () => {
@@ -67,6 +79,10 @@ test("conflict failures are actionable without exposing raw command output", ()
describeConflictResolutionFailure(new Error("git diff --check failed after goose correction")),
/automatic correction pass/
);
assert.match(
describeConflictResolutionFailure(new Error("git diff --check goose correction timed out")),
/4-minute limit/
);
assert.match(
describeConflictResolutionFailure(new Error("rejected: stale info")),
/Run \/conflict again/
@@ -77,6 +93,24 @@ test("conflict failures are actionable without exposing raw command output", ()
);
});
test("diff-check whitespace diagnostics are repaired without another agent run", () => {
const diagnostics = parseDiffCheckWhitespaceDiagnostics([
"src/app.js:2: trailing whitespace.",
"+const value = true; ",
"src/app.js:3: space before tab in indent.",
"+ \treturn value;",
"src/app.js:4: leftover conflict marker."
].join("\n"));
assert.deepEqual(diagnostics, [
{ file: "src/app.js", line: 2, kind: "trailing-whitespace" },
{ file: "src/app.js", line: 3, kind: "space-before-tab" }
]);
assert.equal(
repairDiffCheckContent("function check() {\nconst value = true; \n \treturn value;\n}\n", diagnostics),
"function check() {\nconst value = true;\n\treturn value;\n}\n"
);
});
test("external fork conflict pushes use a head-SHA force lease", () => {
assert.deepEqual(buildConflictPushArgs({
baseRepository: "forumlify/public",