Skip to content

Commit 0cbbd95

Browse files
authored
fix(repair): refresh stale automerge verdicts (#699)
Bind completed verdict reuse to stable source snapshots so stale or unverifiable verdicts dispatch a fresh exact-head review.
1 parent 1b9630b commit 0cbbd95

6 files changed

Lines changed: 167 additions & 9 deletions

File tree

‎src/repair/comment-router-core.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1995,7 +1995,12 @@ export function trustedExactHeadReviewCompletionSince({
19951995
headSha: string;
19961996
trustedAuthors?: ReadonlySet<string>;
19971997
sinceMs: number;
1998-
}): { commentId: number; reviewedAt: string | null; publishedAt: string | null } | null {
1998+
}): {
1999+
commentId: number;
2000+
reviewedAt: string | null;
2001+
publishedAt: string | null;
2002+
sourceRevision: string | null;
2003+
} | null {
19992004
const normalizedHead = String(headSha ?? "")
20002005
.trim()
20012006
.toLowerCase();
@@ -2006,6 +2011,7 @@ export function trustedExactHeadReviewCompletionSince({
20062011
observedAtMs: number;
20072012
reviewedAt: string | null;
20082013
publishedAt: string | null;
2014+
sourceRevision: string | null;
20092015
} | null = null;
20102016
for (const comment of comments) {
20112017
const completed = parseTrustedAutomation(comment, { trustedAuthors });
@@ -2030,21 +2036,23 @@ export function trustedExactHeadReviewCompletionSince({
20302036
.toLowerCase() === normalizedHead,
20312037
);
20322038
const reviewedAt = String(reviewMarker?.attrs?.reviewed_at ?? "").trim() || null;
2039+
const sourceRevision = String(reviewMarker?.attrs?.source_revision ?? "").trim() || null;
20332040
const publishedAt = String(comment?.updated_at ?? comment?.created_at ?? "").trim() || null;
20342041
const observedAtMs = Math.max(
20352042
Number.isFinite(Date.parse(reviewedAt ?? "")) ? Date.parse(reviewedAt ?? "") : 0,
20362043
Number.isFinite(Date.parse(publishedAt ?? "")) ? Date.parse(publishedAt ?? "") : 0,
20372044
);
20382045
if (observedAtMs < sinceMs || observedAtMs <= 0) continue;
20392046
if (!newest || observedAtMs > newest.observedAtMs) {
2040-
newest = { commentId, observedAtMs, reviewedAt, publishedAt };
2047+
newest = { commentId, observedAtMs, reviewedAt, publishedAt, sourceRevision };
20412048
}
20422049
}
20432050
return (
20442051
newest && {
20452052
commentId: newest.commentId,
20462053
reviewedAt: newest.reviewedAt,
20472054
publishedAt: newest.publishedAt,
2055+
sourceRevision: newest.sourceRevision,
20482056
}
20492057
);
20502058
}

‎src/repair/comment-router.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3000,17 +3000,23 @@ function reviewDispatchDecisionForCommand(
30003000
activeLeaseExpiresAt: null,
30013001
completedReviewAt: null,
30023002
completedReviewCommentId: null,
3003+
completedReviewSourceRevision: null,
3004+
sourceRevisionBefore: issueSourceRevisionSha256(before, []),
3005+
sourceRevisionAfter: issueSourceRevisionSha256(before, []),
30033006
});
30043007
}
3005-
const comments = ghPaged<JsonValue>(
3008+
const commentsBefore = ghPaged<JsonValue>(
30063009
`repos/${targetRepo}/issues/${number}/comments?per_page=100`,
30073010
);
30083011
const after = fetchPullRequestView(number);
3012+
const commentsAfter = ghPaged<JsonValue>(
3013+
`repos/${targetRepo}/issues/${number}/comments?per_page=100`,
3014+
);
30093015
const headAfter = String(after.headRefOid ?? "")
30103016
.trim()
30113017
.toLowerCase();
30123018
const activeReviewLease = freshExactHeadReviewStartLease({
3013-
comments: comments as LooseRecord[],
3019+
comments: commentsAfter as LooseRecord[],
30143020
itemNumber: number,
30153021
headSha: headAfter,
30163022
trustedAuthors: trustedBots,
@@ -3022,7 +3028,7 @@ function reviewDispatchDecisionForCommand(
30223028
? 0
30233029
: Date.parse(String(command.comment_updated_at ?? command.comment_created_at ?? ""));
30243030
const completedReview = trustedExactHeadReviewCompletionSince({
3025-
comments: comments as LooseRecord[],
3031+
comments: commentsAfter as LooseRecord[],
30263032
headSha: headAfter,
30273033
trustedAuthors: trustedBots,
30283034
sinceMs: commandStartedAtMs,
@@ -3038,6 +3044,9 @@ function reviewDispatchDecisionForCommand(
30383044
completedReview?.reviewedAt ??
30393045
(completedReview ? "recently" : null),
30403046
completedReviewCommentId: completedReview?.commentId ?? null,
3047+
completedReviewSourceRevision: completedReview?.sourceRevision ?? null,
3048+
sourceRevisionBefore: issueSourceRevisionSha256(before, commentsBefore),
3049+
sourceRevisionAfter: issueSourceRevisionSha256(after, commentsAfter),
30413050
});
30423051
} catch (error) {
30433052
return {

‎src/repair/review-dispatch-coordination.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ export type ReviewDispatchCoordinationInput = {
1313
activeLeaseExpiresAt: string | null;
1414
completedReviewAt: string | null;
1515
completedReviewCommentId: number | null;
16+
completedReviewSourceRevision: string | null;
17+
sourceRevisionBefore: string;
18+
sourceRevisionAfter: string;
1619
};
1720

1821
export function decideReviewDispatchCoordination({
@@ -23,6 +26,9 @@ export function decideReviewDispatchCoordination({
2326
activeLeaseExpiresAt,
2427
completedReviewAt,
2528
completedReviewCommentId,
29+
completedReviewSourceRevision,
30+
sourceRevisionBefore,
31+
sourceRevisionAfter,
2632
}: ReviewDispatchCoordinationInput): ReviewDispatchCoordinationDecision {
2733
if (!isOpen(stateBefore) || !isOpen(stateAfter)) {
2834
return { action: "stop", reason: "target is no longer an open PR" };
@@ -33,6 +39,17 @@ export function decideReviewDispatchCoordination({
3339
reason: "PR head changed during the dispatch-time review check; next router pass will retry",
3440
};
3541
}
42+
if (
43+
!sourceRevisionBefore ||
44+
!sourceRevisionAfter ||
45+
sourceRevisionBefore !== sourceRevisionAfter
46+
) {
47+
return {
48+
action: "retry",
49+
reason:
50+
"PR source changed during the dispatch-time review check; next router pass will retry",
51+
};
52+
}
3653
// At-least-once command delivery makes an active exact-head lease a normal
3754
// coordination result. Reuse its eventual verdict instead of creating more work.
3855
if (activeLeaseExpiresAt) {
@@ -42,6 +59,17 @@ export function decideReviewDispatchCoordination({
4259
};
4360
}
4461
if (completedReviewAt && completedReviewCommentId) {
62+
const reviewedRevision = String(completedReviewSourceRevision ?? "")
63+
.trim()
64+
.toLowerCase();
65+
// Only a truly missing revision belongs to the legacy compatibility path.
66+
// Any present but unverifiable marker needs a new review.
67+
if (
68+
reviewedRevision &&
69+
(!/^[0-9a-f]{64}$/.test(reviewedRevision) || reviewedRevision !== sourceRevisionAfter)
70+
) {
71+
return { action: "dispatch" };
72+
}
4573
return {
4674
action: "reuse_completed_review",
4775
commentId: completedReviewCommentId,

‎test/e2e/automerge/run.mjs‎

Lines changed: 75 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import assert from "node:assert/strict";
22
import { execFileSync, spawn, spawnSync } from "node:child_process";
3+
import crypto from "node:crypto";
34
import fs from "node:fs";
45
import os from "node:os";
56
import path from "node:path";
@@ -15,6 +16,7 @@ const helperRoot = path.dirname(fileURLToPath(import.meta.url));
1516
export const AUTOMERGE_E2E_SCENARIOS = [
1617
"approve-intent-persistence",
1718
"completed-verdict-resume",
19+
"completed-verdict-source-drift",
1820
"dependency-setup-mutation",
1921
"happy-path",
2022
"pending-checks",
@@ -257,6 +259,7 @@ export function runAutomergeE2E({
257259
if (
258260
scenario === "approve-intent-persistence" ||
259261
scenario === "completed-verdict-resume" ||
262+
scenario === "completed-verdict-source-drift" ||
260263
scenario === "resume-intent-persistence"
261264
) {
262265
const activeJob = path.join(
@@ -313,6 +316,41 @@ export function runAutomergeE2E({
313316
attemptId: String(verdictHandoff.client_payload.attempt_id),
314317
});
315318
completedVerdictAlreadyRouted = true;
319+
} else if (scenario === "completed-verdict-source-drift") {
320+
const beforeCommand = JSON.parse(fs.readFileSync(statePath, "utf8"));
321+
const staleVerdictId = addExactHeadVerdict(
322+
statePath,
323+
repairedHead,
324+
fixtureSourceRevision(beforeCommand),
325+
);
326+
const commandId = addMaintainerAutomergeCommand(statePath);
327+
runCommentRouterExact(runtimeRoot, baseEnv, artifacts, "08-comment-router-source-drift", {
328+
commentId: commandId,
329+
});
330+
const refreshedState = JSON.parse(fs.readFileSync(statePath, "utf8"));
331+
assert.equal(
332+
refreshedState.dispatches.some(
333+
(dispatch) =>
334+
dispatch.event_type === "clawsweeper_comment" &&
335+
dispatch.client_payload?.comment_id === String(staleVerdictId),
336+
),
337+
false,
338+
"a source-stale exact-head verdict must not be replayed",
339+
);
340+
assert.equal(
341+
refreshedState.dispatches.some((dispatch) => dispatch.event_type === "clawsweeper_item"),
342+
true,
343+
"source drift must queue a fresh exact-head review",
344+
);
345+
const freshVerdictId = addExactHeadVerdict(
346+
statePath,
347+
repairedHead,
348+
fixtureSourceRevision(refreshedState),
349+
);
350+
runCommentRouterExact(runtimeRoot, baseEnv, artifacts, "10-comment-router-fresh-verdict", {
351+
commentId: freshVerdictId,
352+
});
353+
completedVerdictAlreadyRouted = true;
316354
} else if (scenario === "resume-intent-persistence") {
317355
addMaintainerAutomergeCommand(statePath);
318356
runCommentRouter(runtimeRoot, baseEnv, artifacts, "08-comment-router-resume-command");
@@ -579,12 +617,12 @@ function createCandidateRuntime(root, candidateRoot) {
579617
return runtime;
580618
}
581619

582-
function addExactHeadVerdict(statePath, headSha) {
620+
function addExactHeadVerdict(statePath, headSha, sourceRevision = null) {
583621
const state = JSON.parse(fs.readFileSync(statePath, "utf8"));
584622
const now = new Date().toISOString();
585623
state.comments.push({
586624
id: state.nextCommentId++,
587-
body: `ClawSweeper review passed.\n<!-- clawsweeper-verdict:pass item=${state.pr.number} sha=${headSha} reviewed_at=${now} -->`,
625+
body: `ClawSweeper review passed.\n<!-- clawsweeper-verdict:pass item=${state.pr.number} sha=${headSha}${sourceRevision ? ` source_revision=${sourceRevision}` : ""} reviewed_at=${now} -->`,
588626
issue_url: `https://api.github.com/repos/${state.repo}/issues/${state.pr.number}`,
589627
html_url: `https://github.com/${state.repo}/pull/${state.pr.number}#issuecomment-${state.nextCommentId - 1}`,
590628
user: { id: 1, login: "clawsweeper[bot]" },
@@ -596,6 +634,41 @@ function addExactHeadVerdict(statePath, headSha) {
596634
return state.nextCommentId - 1;
597635
}
598636

637+
function fixtureSourceRevision(state) {
638+
const snapshot = {
639+
title: state.pr.title,
640+
body: state.pr.body,
641+
labels: state.pr.labels
642+
.map((label) => String(label).trim().toLowerCase())
643+
.filter((label) => !label.startsWith("clawsweeper:"))
644+
.sort(),
645+
comments: state.comments
646+
.filter(
647+
(comment) =>
648+
![
649+
"clawsweeper",
650+
"clawsweeper[bot]",
651+
"openclaw-clawsweeper",
652+
"openclaw-clawsweeper[bot]",
653+
].includes(
654+
String(comment.user?.login ?? "")
655+
.trim()
656+
.toLowerCase(),
657+
),
658+
)
659+
.map((comment) => ({
660+
id: String(comment.id ?? ""),
661+
author: String(comment.user?.login ?? ""),
662+
body: String(comment.body ?? ""),
663+
updated_at: String(comment.updated_at ?? comment.created_at ?? ""),
664+
}))
665+
.sort((left, right) =>
666+
`${left.id}:${left.updated_at}`.localeCompare(`${right.id}:${right.updated_at}`),
667+
),
668+
};
669+
return crypto.createHash("sha256").update(JSON.stringify(snapshot)).digest("hex");
670+
}
671+
599672
function addMaintainerAutomergeCommand(statePath) {
600673
const state = JSON.parse(fs.readFileSync(statePath, "utf8"));
601674
addFixtureComment(statePath, {

‎test/repair/comment-router-core.test.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1779,12 +1779,13 @@ test("review start leases reject malformed, future, and overlong markers", () =>
17791779

17801780
test("same-head completion freshness uses durable publication time", () => {
17811781
const headSha = "0123456789abcdef0123456789abcdef01234567";
1782+
const sourceRevision = "1".repeat(64);
17821783
const comment = {
17831784
id: 1234,
17841785
user: { login: "clawsweeper[bot]" },
17851786
created_at: "2026-07-09T21:00:00.000Z",
17861787
updated_at: "2026-07-09T21:05:30.000Z",
1787-
body: `<!-- clawsweeper-verdict:pass item=103109 sha=${headSha} reviewed_at=2026-07-09T21:04:30.000Z -->`,
1788+
body: `<!-- clawsweeper-verdict:pass item=103109 sha=${headSha} source_revision=${sourceRevision} reviewed_at=2026-07-09T21:04:30.000Z -->`,
17881789
};
17891790

17901791
assert.deepEqual(
@@ -1798,6 +1799,7 @@ test("same-head completion freshness uses durable publication time", () => {
17981799
commentId: 1234,
17991800
reviewedAt: "2026-07-09T21:04:30.000Z",
18001801
publishedAt: "2026-07-09T21:05:30.000Z",
1802+
sourceRevision,
18011803
},
18021804
);
18031805
assert.equal(
@@ -1913,7 +1915,15 @@ test("review dispatch coordination guards label sweeps and maintainer mode comma
19131915
/automation_source !== "repair_loop_label_sweep"[\s\S]*?return \{ action: "dispatch" \}/,
19141916
);
19151917
assert.equal(dispatchGuard.match(/fetchPullRequestView\(number\)/g)?.length, 2);
1916-
assert.match(dispatchGuard, /issues\/\$\{number\}\/comments\?per_page=100/);
1918+
assert.equal(dispatchGuard.match(/issues\/\$\{number\}\/comments\?per_page=100/g)?.length, 2);
1919+
assert.match(
1920+
dispatchGuard,
1921+
/sourceRevisionBefore: issueSourceRevisionSha256\(before, commentsBefore\)/,
1922+
);
1923+
assert.match(
1924+
dispatchGuard,
1925+
/sourceRevisionAfter: issueSourceRevisionSha256\(after, commentsAfter\)/,
1926+
);
19171927
assert.match(dispatchGuard, /nowMs:\s*Date\.now\(\)/);
19181928
assert.match(dispatchGuard, /trustedExactHeadReviewCompletionSince\(\{/);
19191929
assert.match(dispatchGuard, /sinceMs:\s*commandStartedAtMs/);

‎test/repair/review-dispatch-coordination.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ function decision(overrides: Partial<Parameters<typeof decideReviewDispatchCoord
1414
activeLeaseExpiresAt: null,
1515
completedReviewAt: null,
1616
completedReviewCommentId: null,
17+
completedReviewSourceRevision: null,
18+
sourceRevisionBefore: "1".repeat(64),
19+
sourceRevisionAfter: "1".repeat(64),
1720
...overrides,
1821
});
1922
}
@@ -43,12 +46,39 @@ test("reuses a same-head review completed since the command", () => {
4346
const result = decision({
4447
completedReviewAt: "2026-07-17T14:10:00.000Z",
4548
completedReviewCommentId: 1234,
49+
completedReviewSourceRevision: "1".repeat(64),
4650
});
4751
assert.equal(result.action, "reuse_completed_review");
4852
assert.equal(result.commentId, 1234);
4953
assert.match(result.reason, /result will be reused/);
5054
});
5155

56+
test("dispatches a fresh review when a same-head verdict has stale source", () => {
57+
assert.deepEqual(
58+
decision({
59+
completedReviewAt: "2026-07-17T14:10:00.000Z",
60+
completedReviewCommentId: 1234,
61+
completedReviewSourceRevision: "2".repeat(64),
62+
}),
63+
{ action: "dispatch" },
64+
);
65+
});
66+
67+
test("dispatches a fresh review when a verdict source is unknown", () => {
68+
assert.deepEqual(
69+
decision({
70+
completedReviewAt: "2026-07-17T14:10:00.000Z",
71+
completedReviewCommentId: 1234,
72+
completedReviewSourceRevision: "unknown",
73+
}),
74+
{ action: "dispatch" },
75+
);
76+
});
77+
78+
test("retries when source changes during review coordination", () => {
79+
assert.equal(decision({ sourceRevisionAfter: "2".repeat(64) }).action, "retry");
80+
});
81+
5282
test("an active lease wins over a completed marker", () => {
5383
assert.equal(
5484
decision({

0 commit comments

Comments
 (0)