Skip to content

Commit 5d79352

Browse files
committed
Enforce repair contract before checkpointing
1 parent 25a378a commit 5d79352

2 files changed

Lines changed: 144 additions & 1 deletion

File tree

‎src/repair/execute-fix-artifact.ts‎

Lines changed: 123 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1971,11 +1971,20 @@ function editValidatePrepareMerge({
19711971
if (shouldRunCodexEdit) {
19721972
for (let attempt = 1; attempt <= maxEditAttempts; attempt += 1) {
19731973
const headBeforeAttempt = currentHead(targetDir);
1974+
const effectiveFallbackReason =
1975+
rebaseResult?.status === "conflicts"
1976+
? [
1977+
"Resolve only the current rebase conflicts before doing any feature repair.",
1978+
"Do not broaden the patch while conflict markers remain.",
1979+
"Inspect `git status --short`, remove conflict markers, preserve both intended sides where appropriate, and leave the checkout ready for `git rebase --continue`.",
1980+
"After conflicts are resolved, run the narrow validation commands from the artifact.",
1981+
].join(" ")
1982+
: fallbackReason;
19741983
const prompt = buildFixPrompt({
19751984
fixArtifact,
19761985
branch,
19771986
mode,
1978-
fallbackReason,
1987+
fallbackReason: effectiveFallbackReason,
19791988
attempt,
19801989
previousNoDiff: attempt > 1,
19811990
previousSummary,
@@ -2117,6 +2126,13 @@ function editValidatePrepareMerge({
21172126
});
21182127
}
21192128

2129+
enforceRepairContract({
2130+
fixArtifact,
2131+
targetDir,
2132+
sourceHead: repairDeltaBaseHead,
2133+
baseBranch,
2134+
});
2135+
21202136
const firstCheckpoint = commitCheckpointIfNeeded({
21212137
targetDir,
21222138
message: fixArtifact.pr_title,
@@ -2593,6 +2609,112 @@ function codexWorkspaceSandboxConfigArgs(sandbox: string, networkAccess: string)
25932609
return ["-c", `sandbox_workspace_write.network_access=${networkAccess ? "true" : "false"}`];
25942610
}
25952611

2612+
function enforceRepairContract({
2613+
fixArtifact,
2614+
targetDir,
2615+
sourceHead = null,
2616+
baseBranch = DEFAULT_BASE_BRANCH,
2617+
}: LooseRecord) {
2618+
const contract = repairContract(fixArtifact);
2619+
const changedFiles = changedFilesForRepairContract({ targetDir, sourceHead, baseBranch });
2620+
const unresolved = unmergedPaths(targetDir);
2621+
const failures: string[] = [];
2622+
2623+
if (unresolved.length > 0) {
2624+
failures.push(`rebase conflicts remain unresolved: ${unresolved.join(", ")}`);
2625+
}
2626+
2627+
if (contract.must_touch.length > 0) {
2628+
const touched = contract.must_touch.filter((file: string) => changedFiles.includes(file));
2629+
if (touched.length === 0) {
2630+
failures.push(
2631+
`repair contract must_touch not satisfied; expected one of ${contract.must_touch.join(", ")}; changed=${changedFiles.join(", ") || "none"}`,
2632+
);
2633+
}
2634+
}
2635+
2636+
const forbiddenTouched = contract.must_not_touch.filter((file: string) =>
2637+
changedFiles.includes(file),
2638+
);
2639+
if (forbiddenTouched.length > 0) {
2640+
failures.push(`repair contract must_not_touch violated: ${forbiddenTouched.join(", ")}`);
2641+
}
2642+
2643+
fs.writeFileSync(
2644+
path.join(workRoot, "repair-contract.json"),
2645+
`${JSON.stringify({ ...contract, changed_files: changedFiles, failures }, null, 2)}
2646+
`,
2647+
);
2648+
if (failures.length > 0) throw new Error(failures.join("; "));
2649+
}
2650+
2651+
function repairContract(fixArtifact: LooseRecord) {
2652+
const likelyFiles = arrayOfStrings(fixArtifact?.likely_files).filter(isSafeRelativeRepoPath);
2653+
const validationFiles = arrayOfStrings(fixArtifact?.validation_commands)
2654+
.flatMap((command: string) => command.split(/\s+/))
2655+
.filter(isSafeRelativeRepoPath);
2656+
const mustTouch = uniqueRepairStrings(
2657+
likelyFiles.length <= 4
2658+
? likelyFiles
2659+
: likelyFiles.filter((file: string) => validationFiles.includes(file)),
2660+
);
2661+
const allowedLockfiles = new Set(likelyFiles.concat(validationFiles));
2662+
const mustNotTouch = ["pnpm-lock.yaml", "package-lock.json", "yarn.lock"].filter(
2663+
(file) => !allowedLockfiles.has(file),
2664+
);
2665+
return {
2666+
must_touch: mustTouch,
2667+
must_not_touch: mustNotTouch,
2668+
must_prove: arrayOfStrings(fixArtifact?.validation_commands),
2669+
};
2670+
}
2671+
2672+
function changedFilesForRepairContract({
2673+
targetDir,
2674+
sourceHead = null,
2675+
baseBranch = DEFAULT_BASE_BRANCH,
2676+
}: LooseRecord) {
2677+
const files = new Set<string>();
2678+
for (const line of run("git", ["status", "--porcelain"], { cwd: targetDir }).split(/\r?\n/)) {
2679+
if (!line.trim()) continue;
2680+
const pathText = line.slice(3).trim();
2681+
const file = pathText.includes(" -> ") ? pathText.split(" -> ").pop() : pathText;
2682+
if (file && isSafeRelativeRepoPath(file)) files.add(file);
2683+
}
2684+
const refs = [sourceHead, sourceHead ? null : `origin/${baseBranch}`].filter(Boolean);
2685+
for (const ref of refs) {
2686+
try {
2687+
for (const file of run("git", ["diff", "--name-only", `${ref}...HEAD`], {
2688+
cwd: targetDir,
2689+
}).split(/\r?\n/)) {
2690+
const clean = file.trim();
2691+
if (clean && isSafeRelativeRepoPath(clean)) files.add(clean);
2692+
}
2693+
break;
2694+
} catch {
2695+
// Fall through to the next available reference.
2696+
}
2697+
}
2698+
return [...files].sort();
2699+
}
2700+
2701+
function arrayOfStrings(value: JsonValue): string[] {
2702+
return Array.isArray(value) ? value.map((item) => String(item ?? "").trim()).filter(Boolean) : [];
2703+
}
2704+
2705+
function uniqueRepairStrings(values: string[]) {
2706+
return [...new Set(values)];
2707+
}
2708+
2709+
function isSafeRelativeRepoPath(value: string) {
2710+
return (
2711+
Boolean(value) &&
2712+
!value.startsWith("/") &&
2713+
!value.split(/[\/]/).includes("..") &&
2714+
!/[`$;&|<>()[\]{}*?~]/.test(value)
2715+
);
2716+
}
2717+
25962718
function parseBooleanEnv(value: JsonValue, fallback: JsonValue) {
25972719
if (value == null || value === "") return fallback;
25982720
if (/^(1|true|yes|on)$/i.test(String(value))) return true;

‎test/repair/execute-fix-artifact-source.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,3 +148,24 @@ test("issue implementation rechecks opt-out labels immediately before branch pus
148148
assert.match(source.slice(helperStart, helperEnd), /repairPauseLabel\(issue\.labels\)/);
149149
assert.match(source.slice(helperStart, helperEnd), /refusing to push or open a PR/);
150150
});
151+
152+
test("repair contract enforces likely file touch before checkpointing", () => {
153+
const source = fs.readFileSync(
154+
path.join(process.cwd(), "src/repair/execute-fix-artifact.ts"),
155+
"utf8",
156+
);
157+
const callIndex = source.indexOf("enforceRepairContract({");
158+
const checkpointIndex = source.indexOf("const firstCheckpoint = commitCheckpointIfNeeded({");
159+
const helperStart = source.indexOf("function enforceRepairContract(");
160+
const helperEnd = source.indexOf("function validateAndReviewLoop(", helperStart);
161+
162+
assert.notEqual(callIndex, -1);
163+
assert.notEqual(checkpointIndex, -1);
164+
assert.ok(callIndex < checkpointIndex, "repair contract must run before checkpoint commits");
165+
assert.notEqual(helperStart, -1);
166+
assert.notEqual(helperEnd, -1);
167+
const helper = source.slice(helperStart, helperEnd);
168+
assert.match(helper, /repair contract must_touch not satisfied/);
169+
assert.match(helper, /const pathText = line\.slice\(3\)\.trim\(\);/);
170+
assert.doesNotMatch(helper, /const text = line\.trim\(\);[\s\S]*text\.slice\(3\)/);
171+
});

0 commit comments

Comments
 (0)