Skip to content

Commit d3ad07b

Browse files
fix(repair): validate final repair contract (#341)
Validate final-tree repair contracts only after review fixes and base sync, and keep the strict Codex output schema compatible with explicit null contracts. Co-authored-by: Joao Carreiro <[email protected]> Co-authored-by: Vincent Koc <[email protected]>
1 parent 19ca145 commit d3ad07b

12 files changed

Lines changed: 405 additions & 6 deletions

‎schema/repair/codex-result.schema.json‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,8 @@
285285
"source_prs",
286286
"repair_strategy",
287287
"allow_no_pr",
288-
"branch_update_blockers"
288+
"branch_update_blockers",
289+
"repair_contract"
289290
],
290291
"additionalProperties": false,
291292
"properties": {
@@ -356,6 +357,31 @@
356357
"items": {
357358
"type": "string"
358359
}
360+
},
361+
"repair_contract": {
362+
"anyOf": [
363+
{
364+
"type": "null"
365+
},
366+
{
367+
"type": "object",
368+
"required": ["must_touch", "match"],
369+
"additionalProperties": false,
370+
"properties": {
371+
"must_touch": {
372+
"type": "array",
373+
"minItems": 1,
374+
"items": {
375+
"type": "string"
376+
}
377+
},
378+
"match": {
379+
"type": "string",
380+
"enum": ["any", "all"]
381+
}
382+
}
383+
}
384+
]
359385
}
360386
}
361387
}

‎src/repair/commit-finding-intake.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,7 @@ function writeSyntheticRun(context: LooseRecord) {
342342
repair_strategy: "new_fix_pr",
343343
allow_no_pr: true,
344344
branch_update_blockers: [],
345+
repair_contract: null,
345346
},
346347
};
347348
fs.writeFileSync(

‎src/repair/deterministic-automerge-result.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ export function deterministicAutomergeResult({
7878
repair_strategy: "repair_contributor_branch",
7979
allow_no_pr: false,
8080
branch_update_blockers: [],
81+
repair_contract: null,
8182
};
8283

8384
return {

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

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,11 @@ import {
114114
type TargetValidationOptions,
115115
} from "./target-validation.js";
116116
import { uniqueStrings } from "./validation-command-utils.js";
117+
import {
118+
changedFilesFromNameOnlyZ,
119+
enforceRepairContract,
120+
repairContract,
121+
} from "./repair-contract.js";
117122
import {
118123
rebaseConflictEditDecision,
119124
unresolvedRebaseConflictReason,
@@ -1996,6 +2001,8 @@ function editValidatePrepareMerge({
19962001
let producedChanges = allowExistingChanges;
19972002
let previousSummary = "";
19982003
const checkpointCommits: JsonValue[] = [];
2004+
const hasRepairContract = repairContract(fixArtifact) !== null;
2005+
const pushIntermediateCheckpoint = hasRepairContract ? null : pushCheckpoint;
19992006
if (
20002007
!producedChanges &&
20012008
canTreatRebaseAsCompleteRepair({
@@ -2210,7 +2217,7 @@ function editValidatePrepareMerge({
22102217
});
22112218
if (firstCheckpoint) {
22122219
checkpointCommits.push(firstCheckpoint);
2213-
pushCheckpoint?.();
2220+
pushIntermediateCheckpoint?.();
22142221
}
22152222

22162223
let codexReview = null;
@@ -2241,7 +2248,7 @@ function editValidatePrepareMerge({
22412248
});
22422249
if (checkpoint) {
22432250
checkpointCommits.push(checkpoint);
2244-
pushCheckpoint?.();
2251+
pushIntermediateCheckpoint?.();
22452252
}
22462253
},
22472254
});
@@ -2272,7 +2279,7 @@ function editValidatePrepareMerge({
22722279
});
22732280
if (checkpoint) {
22742281
checkpointCommits.push(checkpoint);
2275-
pushCheckpoint?.();
2282+
pushIntermediateCheckpoint?.();
22762283
}
22772284
if (attempt === maxFinalBaseSyncAttempts) {
22782285
codexReview.final_base_sync = {
@@ -2292,7 +2299,7 @@ function editValidatePrepareMerge({
22922299
});
22932300
if (finalCheckpoint) {
22942301
checkpointCommits.push(finalCheckpoint);
2295-
pushCheckpoint?.();
2302+
pushIntermediateCheckpoint?.();
22962303
}
22972304
const historyCompaction =
22982305
mode === "replacement"
@@ -2304,7 +2311,8 @@ function editValidatePrepareMerge({
23042311
checkpointCommits,
23052312
})
23062313
: null;
2307-
if (historyCompaction?.status === "compacted") {
2314+
enforceFinalRepairContract({ fixArtifact, targetDir, baseBranch });
2315+
if (hasRepairContract || historyCompaction?.status === "compacted") {
23082316
pushCheckpoint?.();
23092317
}
23102318
const commit = run("git", ["rev-parse", "HEAD"], { cwd: targetDir }).trim();
@@ -3367,6 +3375,15 @@ function commitCheckpointIfNeeded({ targetDir, message, trailers = [] }: LooseRe
33673375
return run("git", ["rev-parse", "HEAD"], { cwd: targetDir }).trim();
33683376
}
33693377

3378+
function enforceFinalRepairContract({ fixArtifact, targetDir, baseBranch }: LooseRecord) {
3379+
if (!repairContract(fixArtifact)) return;
3380+
const baseRef = `origin/${baseBranch}`;
3381+
const changedFiles = changedFilesFromNameOnlyZ(
3382+
run("git", ["diff", "--name-only", "-z", `${baseRef}..HEAD`], { cwd: targetDir }),
3383+
);
3384+
enforceRepairContract({ fixArtifact, changedFiles });
3385+
}
3386+
33703387
function pushRecoverableBranch({ targetDir, branch }: LooseRecord) {
33713388
assertIssueImplementationNotPaused();
33723389
const remoteSha = remoteBranchSha({ targetDir, branch });

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import fs from "node:fs";
22
import path from "node:path";
33

44
import type { JsonValue, LooseRecord } from "./json-types.js";
5+
import { validateRepairContractShape } from "./repair-contract.js";
56
import { GITHUB_PR_TITLE_MAX_LENGTH } from "./pr-title.js";
67
import { slug } from "./text-utils.js";
78

@@ -51,6 +52,8 @@ export function validateFixArtifact(fixArtifact: LooseRecord): LooseRecord {
5152
if (typeof fixArtifact.changelog_required !== "boolean") {
5253
throw new Error("fix_artifact.changelog_required must be boolean");
5354
}
55+
const contractErrors = validateRepairContractShape(fixArtifact);
56+
if (contractErrors.length > 0) throw new Error(contractErrors.join("; "));
5457
if (!REPAIR_STRATEGIES.has(fixArtifact.repair_strategy)) {
5558
throw new Error("fix_artifact.repair_strategy is not executable");
5659
}

‎src/repair/lib.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,7 @@ export function renderPrompt(
290290
parts.push(
291291
"## Required final output",
292292
"Return JSON matching `schema/repair/codex-result.schema.json` and nothing else.",
293+
"If the fix has explicit files that must differ from the latest base in the final repaired tree, set `fix_artifact.repair_contract` to an object with `must_touch` and `match` (`any` or `all`). The executor checks this once against the final branch delta after review fixes and base sync. Set `repair_contract` to null when the expected edit surface is uncertain, only represented by incomplete `likely_files`, or the work is a pure deterministic rebase.",
293294
);
294295

295296
return parts.join("\n\n");

‎src/repair/repair-contract.ts‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
import type { JsonValue, LooseRecord } from "./json-types.js";
2+
3+
export interface RepairContract {
4+
mustTouch: string[];
5+
match: "any" | "all";
6+
}
7+
8+
export function repairContract(fixArtifact: LooseRecord): RepairContract | null {
9+
const raw = fixArtifact.repair_contract;
10+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
11+
if (validateRepairContractShape(fixArtifact).length > 0) return null;
12+
const mustTouch = uniqueStrings(raw.must_touch.map(normalizeRepairContractPath));
13+
return {
14+
mustTouch,
15+
match: raw.match,
16+
};
17+
}
18+
19+
export function enforceRepairContract({
20+
fixArtifact,
21+
changedFiles: rawChangedFiles,
22+
}: {
23+
fixArtifact: LooseRecord;
24+
changedFiles: readonly string[];
25+
}): void {
26+
const contract = repairContract(fixArtifact);
27+
if (!contract) return;
28+
29+
const changedFiles = uniqueStrings(
30+
rawChangedFiles.map(normalizeRepairContractPath).filter(Boolean),
31+
);
32+
const matched = contract.mustTouch.filter((expected) =>
33+
changedFiles.some((file) => changedFileMatchesContract(file, expected)),
34+
);
35+
const ok =
36+
contract.match === "all" ? matched.length === contract.mustTouch.length : matched.length > 0;
37+
if (ok) return;
38+
39+
const missing = contract.mustTouch.filter((expected) => !matched.includes(expected));
40+
throw new Error(
41+
[
42+
"repair contract rejected final repair tree: required paths are missing from the final branch delta",
43+
`match=${contract.match}`,
44+
`must_touch=${contract.mustTouch.join(", ")}`,
45+
`matched=${matched.join(", ") || "none"}`,
46+
`missing=${missing.join(", ") || "none"}`,
47+
`changed_files=${changedFiles.join(", ") || "none"}`,
48+
].join("; "),
49+
);
50+
}
51+
52+
export function changedFilesFromNameOnlyZ(diff: string): string[] {
53+
return uniqueStrings(diff.split("\0").map(normalizeRepairContractPath).filter(Boolean));
54+
}
55+
56+
export function validateRepairContractShape(fixArtifact: LooseRecord): string[] {
57+
const raw = fixArtifact.repair_contract;
58+
if (raw === undefined || raw === null) return [];
59+
if (typeof raw !== "object" || Array.isArray(raw)) {
60+
return ["fix_artifact.repair_contract must be an object when present"];
61+
}
62+
63+
const errors: string[] = [];
64+
const allowedKeys = new Set(["must_touch", "match"]);
65+
for (const key of Object.keys(raw)) {
66+
if (!allowedKeys.has(key)) {
67+
errors.push(`fix_artifact.repair_contract.${key} is not allowed`);
68+
}
69+
}
70+
if (!Array.isArray(raw.must_touch) || raw.must_touch.length === 0) {
71+
errors.push("fix_artifact.repair_contract.must_touch must be a non-empty list");
72+
}
73+
for (const value of Array.isArray(raw.must_touch) ? raw.must_touch : []) {
74+
if (typeof value !== "string") {
75+
errors.push("fix_artifact.repair_contract.must_touch entries must be strings");
76+
continue;
77+
}
78+
if (!normalizeRepairContractPath(value)) {
79+
errors.push(
80+
`fix_artifact.repair_contract.must_touch contains an unsafe path: ${String(value)}`,
81+
);
82+
}
83+
}
84+
if (raw.match !== "any" && raw.match !== "all") {
85+
errors.push("fix_artifact.repair_contract.match must be any or all");
86+
}
87+
if (fixArtifact.deterministic_rebase_only === true) {
88+
errors.push(
89+
"fix_artifact.repair_contract is incompatible with deterministic_rebase_only because a pure base sync has no repair delta",
90+
);
91+
}
92+
return errors;
93+
}
94+
95+
function changedFileMatchesContract(changedFile: string, expected: string): boolean {
96+
const prefix = expected.replace(/\/$/, "");
97+
return changedFile === expected || changedFile.startsWith(`${prefix}/`);
98+
}
99+
100+
function normalizeRepairContractPath(value: JsonValue): string {
101+
const pathValue = String(value ?? "").trim();
102+
if (!pathValue || pathValue.startsWith("/") || pathValue.includes("\0")) return "";
103+
if (/[`$;&|<>()[\]{}*?~]/.test(pathValue)) return "";
104+
if (pathValue.split(/[\\/]/).includes("..")) return "";
105+
return pathValue.replace(/^\.\//, "");
106+
}
107+
108+
function uniqueStrings(values: readonly string[]): string[] {
109+
return [...new Set(values)];
110+
}

‎src/repair/review-results.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#!/usr/bin/env node
22
import type { JsonValue, LooseRecord } from "./json-types.js";
3+
import { validateRepairContractShape } from "./repair-contract.js";
34
import fs from "node:fs";
45
import path from "node:path";
56
import { parseArgs, parseJob, repoRoot } from "./lib.js";
@@ -526,6 +527,7 @@ function validateFixArtifact(fixArtifact: LooseRecord, failures: LooseRecord[])
526527
if (typeof fixArtifact.changelog_required !== "boolean") {
527528
failures.push("fix_artifact.changelog_required must be boolean");
528529
}
530+
failures.push(...validateRepairContractShape(fixArtifact));
529531
if (!FIX_REPAIR_STRATEGIES.has(fixArtifact.repair_strategy)) {
530532
failures.push("fix_artifact.repair_strategy is required");
531533
}

‎test/repair/deterministic-automerge-result.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ test("deterministic automerge result emits generic direct-Codex repair artifact"
8888
]);
8989
assert.deepEqual(result?.fix_artifact.affected_surfaces, ["extensions/memory-core"]);
9090
assert.equal(result?.fix_artifact.changelog_required, false);
91+
assert.equal(result?.fix_artifact.repair_contract, null);
9192
assert.deepEqual(result?.fix_artifact.source_prs, [
9293
"https://github.com/openclaw/openclaw/pull/71898",
9394
]);

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

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,3 +176,38 @@ test("issue implementation rechecks opt-out labels immediately before branch pus
176176
assert.match(source.slice(helperStart, helperEnd), /repairPauseLabel\(issue\.labels\)/);
177177
assert.match(source.slice(helperStart, helperEnd), /refusing to push or open a PR/);
178178
});
179+
180+
test("repair contract gates the final cumulative tree, not individual checkpoints", () => {
181+
const source = readText(path.join(process.cwd(), "src/repair/execute-fix-artifact.ts"));
182+
assert.equal(
183+
[...source.matchAll(/commitCheckpointIfNeeded\(/g)].length,
184+
5,
185+
"four checkpoint call sites plus the ordinary commit helper should remain",
186+
);
187+
assert.doesNotMatch(source, /commitRepairCheckpointIfNeeded|checkpointBaseHead/);
188+
assert.match(source, /enforceFinalRepairContract\(\{ fixArtifact, targetDir, baseBranch \}\)/);
189+
assert.equal(
190+
[...source.matchAll(/pushIntermediateCheckpoint\?\.\(\)/g)].length,
191+
4,
192+
"contract jobs must defer all four recovery pushes until final validation",
193+
);
194+
assert.match(source, /if \(hasRepairContract \|\| historyCompaction\?\.status === "compacted"\)/);
195+
196+
const compact = source.indexOf("const historyCompaction =");
197+
const enforce = source.indexOf("enforceFinalRepairContract(", compact);
198+
const publish = source.indexOf("if (hasRepairContract", enforce);
199+
const commit = source.indexOf('const commit = run("git", ["rev-parse", "HEAD"]', publish);
200+
assert.ok(compact < enforce && enforce < publish && publish < commit);
201+
});
202+
203+
test("final repair contract compares the repaired tree with the latest base", () => {
204+
const source = readText(path.join(process.cwd(), "src/repair/execute-fix-artifact.ts"));
205+
const start = source.indexOf("function enforceFinalRepairContract(");
206+
const end = source.indexOf("function pushRecoverableBranch(", start);
207+
const helper = source.slice(start, end);
208+
assert.match(source, /\.\/repair-contract\.js/);
209+
assert.match(helper, /const baseRef = `origin\/\$\{baseBranch\}`/);
210+
assert.match(helper, /"diff", "--name-only", "-z", `\$\{baseRef\}\.\.HEAD`/);
211+
assert.match(helper, /enforceRepairContract\(\{ fixArtifact, changedFiles \}\)/);
212+
assert.doesNotMatch(helper, /--porcelain=v1|phase|checkpoint/);
213+
});

0 commit comments

Comments
 (0)