Skip to content

Commit f0dd69f

Browse files
authored
fix(review): preserve history across local reruns (#1133)
* fix(review): preserve history across local reruns * fix(review): scope exact bootstrap history * fix(review): retain completed local history on failure
1 parent a179597 commit f0dd69f

11 files changed

Lines changed: 401 additions & 13 deletions

‎README.md‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -643,7 +643,16 @@ This mode withholds GitHub token variables, points `gh` at an empty config
643643
directory inside the run artifacts, disables Codex web search, skips host-side
644644
URL/media preprocessing, and makes no GitHub reads or writes. It is not
645645
air-gapped: the Codex model invocation still uses its configured network
646-
service. Reports use a unique
646+
service. Repeated local reviews preserve the latest local result in the same
647+
bounded review-history format used by hosted review. The next run receives the
648+
previous findings and dispositions so it can verify fixes and avoid re-raising
649+
resolved findings. Exact-item history stays in the selected artifact directory.
650+
Committed-range history stays under `.git/clawsweeper/reviews/` and is reused
651+
only for the same target repository and resolved base when its reviewed commit
652+
is an ancestor of the current `HEAD`; changing the base or switching to an
653+
unrelated branch starts a fresh history.
654+
655+
Reports use a unique
647656
`.git/clawsweeper/reviews/local-range-<time>-<pid>/` directory so the default
648657
run leaves the checkout clean. `--artifact-dir` overrides that location.
649658

@@ -741,7 +750,6 @@ target repo and exact item number; ClawSweeper then runs one event job that
741750
reviews, comments, and checks immediate safe apply instead of waiting for the
742751
next hot-intake cron or bulk publish lane.
743752

744-
745753
## Checks
746754

747755
```bash

‎src/clawsweeper-context-hydration.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
filterReviewComments,
1919
latestClawSweeperReview,
2020
latestClawSweeperReviewFromHydration,
21+
previousClawSweeperReviewFromComment,
2122
timestampValueMs,
2223
} from "./clawsweeper-review-comments.js";
2324
import { truncateText } from "./clawsweeper-text.js";
@@ -231,6 +232,10 @@ export function createContextHydration(dependencies: CreateContextHydrationDepen
231232
return latestClawSweeperReview(comments, number, reviewCommentContext);
232233
}
233234

235+
function extractClawSweeperReviewCommentBody(body: string): PreviousClawSweeperReview {
236+
return previousClawSweeperReviewFromComment({ body }, reviewCommentContext);
237+
}
238+
234239
function filterReviewContextCommentsForTest(
235240
comments: readonly unknown[],
236241
number: number,
@@ -1116,6 +1121,7 @@ export function createContextHydration(dependencies: CreateContextHydrationDepen
11161121
detectBulkFiler,
11171122
detectBulkFilerForTest,
11181123
extractLatestClawSweeperReview,
1124+
extractClawSweeperReviewCommentBody,
11191125
extractLatestClawSweeperReviewForTest,
11201126
extractLatestClawSweeperReviewFromHydration,
11211127
extractLatestClawSweeperReviewFromHydrationForTest,

‎src/clawsweeper-review-command-dependencies.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ export interface CreateReviewCommandWorkflowDependencies {
108108
DEFAULT_PLAN_BATCH_SIZE: 3;
109109
defaultItemsDir: (profile?: RepositoryProfile) => string;
110110
defaultLocalRangeArtifactDir: (targetDir: string) => string;
111+
defaultLocalRangeHistoryPath: (targetDir: string, repo: string, baseSha: string) => string;
111112
defaultReviewArtifactDir: (
112113
localOnly: boolean,
113114
itemNumber: number | undefined,
@@ -127,6 +128,7 @@ export interface CreateReviewCommandWorkflowDependencies {
127128
itemNumber: number | undefined,
128129
shardIndex: number,
129130
) => UserFacingCommandError;
131+
extractClawSweeperReviewCommentBody: (body: string) => PreviousClawSweeperReview;
130132
existingReview: (item: Pick<Item, "number" | "repo">, itemsDir: string) => ExistingReview | null;
131133
extractLatestClawSweeperReview: (
132134
comments: readonly unknown[],
@@ -198,6 +200,12 @@ export interface CreateReviewCommandWorkflowDependencies {
198200
itemNumber: number | undefined,
199201
itemNumbers: number[] | undefined,
200202
) => itemNumber is number;
203+
localRangeHistoryApplies: (
204+
targetDir: string,
205+
reviewedSha: string | null,
206+
headSha: string,
207+
) => boolean;
208+
localExactReviewHistoryPath: (artifactDir: string, repo: string, itemNumber: number) => string;
201209
makeTreeReadOnly: (path: string, snapshots?: FileModeSnapshot[]) => FileModeSnapshot[];
202210
markdownFor: (options: {
203211
item: Item;
@@ -242,6 +250,11 @@ export interface CreateReviewCommandWorkflowDependencies {
242250
}) => ActionEvent | null;
243251
refreshRelatedItemsContext: (item: Item, context: ItemContext) => unknown[];
244252
replaceFrontMatterValue: (markdown: string, key: string, value: string) => string;
253+
renderReviewCommentFromReport: (
254+
markdown: string,
255+
reason: "none",
256+
options?: { previousReviewCommentBody?: string },
257+
) => string;
245258
repoFromArgs: (args: Args) => RepositoryProfile;
246259
reportFileName: (repo: string, number: number) => string;
247260
reportReviewFindings: (markdown: string) => ReviewFinding[];

‎src/clawsweeper-review-command-workflow.ts‎

Lines changed: 85 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { readFileSync, writeFileSync } from "node:fs";
1+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
22
import { join } from "node:path";
33
import { ACTION_EVENT_REASON_CODES, ACTION_EVENT_STATUSES } from "./action-ledger.js";
44
import type { Args } from "./clawsweeper-args.js";
@@ -53,6 +53,21 @@ function reviewStartLeaseCommentUpdatedAt(
5353
return undefined;
5454
}
5555

56+
export function localExactBootstrapReviewCommentBody(
57+
markdown: string,
58+
item: Pick<Item, "repo" | "number">,
59+
frontMatterValue: (markdown: string, key: string) => string | undefined,
60+
renderReviewCommentFromReport: (markdown: string, reason: "none") => string,
61+
): string {
62+
if (
63+
frontMatterValue(markdown, "repository")?.toLowerCase() !== item.repo.toLowerCase() ||
64+
frontMatterValue(markdown, "number") !== String(item.number)
65+
) {
66+
return "";
67+
}
68+
return renderReviewCommentFromReport(markdown, "none");
69+
}
70+
5671
export function restoreVerifiedMaintainerPullRequestAuthorAssociation(
5772
item: Pick<Item, "kind" | "author" | "authorAssociation" | "labels">,
5873
repositoryPermission: (author: string) => string | null,
@@ -100,6 +115,7 @@ export function createReviewCommandWorkflow(dependencies: CreateReviewCommandWor
100115
displayPath,
101116
enforceExpectedIssueSourceRevision,
102117
exactLocalReviewNoCandidateError,
118+
extractClawSweeperReviewCommentBody,
103119
existingReview,
104120
extractLatestClawSweeperReview,
105121
fetchIssueReviewComments,
@@ -115,6 +131,8 @@ export function createReviewCommandWorkflow(dependencies: CreateReviewCommandWor
115131
itemContentDigest,
116132
itemSnapshotHash,
117133
liveClawSweeperReviewDigest,
134+
localExactReviewHistoryPath,
135+
localRangeHistoryApplies,
118136
makeTreeReadOnly,
119137
markdownFor,
120138
postReviewStartStatusComment,
@@ -125,6 +143,7 @@ export function createReviewCommandWorkflow(dependencies: CreateReviewCommandWor
125143
recordReviewLogPublication,
126144
refreshRelatedItemsContext,
127145
replaceFrontMatterValue,
146+
renderReviewCommentFromReport,
128147
reportFileName,
129148
reportReviewFindings,
130149
restoreTreeModes,
@@ -163,6 +182,7 @@ export function createReviewCommandWorkflow(dependencies: CreateReviewCommandWor
163182
expectedSourceRevision,
164183
allowClosed,
165184
localRangeData,
185+
localReviewHistoryPath,
166186
coordinationHeldPath,
167187
shardIndex,
168188
shardCount,
@@ -349,6 +369,32 @@ export function createReviewCommandWorkflow(dependencies: CreateReviewCommandWor
349369
`[review] ${new Date().toISOString()} shard=${shardIndex}/${shardCount} start #${item.number} (${completed + 1}/${candidates.length})`,
350370
);
351371
}
372+
const itemLocalReviewHistoryPath = localRangeData
373+
? localReviewHistoryPath
374+
: localOnly
375+
? localExactReviewHistoryPath(artifactDir, item.repo, item.number)
376+
: null;
377+
let previousLocalReviewCommentBody =
378+
itemLocalReviewHistoryPath && existsSync(itemLocalReviewHistoryPath)
379+
? readFileSync(itemLocalReviewHistoryPath, "utf8")
380+
: "";
381+
if (
382+
!previousLocalReviewCommentBody &&
383+
localOnly &&
384+
!localRangeData &&
385+
existsSync(join(artifactDir, reportFileName(item.repo, item.number)))
386+
) {
387+
const bootstrapReport = readFileSync(
388+
join(artifactDir, reportFileName(item.repo, item.number)),
389+
"utf8",
390+
);
391+
previousLocalReviewCommentBody = localExactBootstrapReviewCommentBody(
392+
bootstrapReport,
393+
item,
394+
frontMatterValue,
395+
renderReviewCommentFromReport,
396+
);
397+
}
352398
const existingPriorReview = localRangeData ? null : existingReview(item, itemsDir);
353399
const lastFullReviewBulkFilerState = frontMatterValue(
354400
existingPriorReview?.markdown ?? "",
@@ -735,6 +781,26 @@ export function createReviewCommandWorkflow(dependencies: CreateReviewCommandWor
735781
reviewCacheDigest: true,
736782
reviewCacheGitDir: openclawDir,
737783
});
784+
if (previousLocalReviewCommentBody) {
785+
const previousLocalReview = extractClawSweeperReviewCommentBody(
786+
previousLocalReviewCommentBody,
787+
);
788+
const hasCompletedLocalReview =
789+
previousLocalReview.completedReviewCycles > 0 &&
790+
/^[0-9a-f]{40}$/iu.test(previousLocalReview.reviewedSha ?? "");
791+
const appliesToRange =
792+
!localRangeData ||
793+
localRangeHistoryApplies(
794+
openclawDir,
795+
previousLocalReview?.reviewedSha ?? null,
796+
localRangeData.headSha,
797+
);
798+
if (hasCompletedLocalReview && appliesToRange) {
799+
context.previousClawSweeperReview = previousLocalReview;
800+
} else {
801+
previousLocalReviewCommentBody = "";
802+
}
803+
}
738804
if (bulkFilerDetection.context) context.bulkFiler = bulkFilerDetection.context;
739805
const contextElapsedMs = Date.now() - contextStartedAt;
740806
const contextItemUpdatedAt = stringOrUndefined(asRecord(context.issue).updatedAt);
@@ -1383,9 +1449,7 @@ export function createReviewCommandWorkflow(dependencies: CreateReviewCommandWor
13831449
const action = reviewActionForDecision({ item, decision, git, runtime });
13841450
structuralRecord = refreshStructuralRecordForVerdict();
13851451
const reportPath = join(artifactDir, reportFileName(item.repo, item.number));
1386-
writeFileSync(
1387-
reportPath,
1388-
markdownFor({
1452+
const reportMarkdown = markdownFor({
13891453
item,
13901454
context,
13911455
decision,
@@ -1404,9 +1468,23 @@ export function createReviewCommandWorkflow(dependencies: CreateReviewCommandWor
14041468
reviewLeaseCommentId: acquiredReviewLease.commentId,
14051469
}
14061470
: {}),
1407-
}),
1408-
"utf8",
1409-
);
1471+
});
1472+
writeFileSync(reportPath, reportMarkdown, "utf8");
1473+
if (itemLocalReviewHistoryPath) {
1474+
const nextLocalReviewCommentBody =
1475+
frontMatterValue(reportMarkdown, "review_status") === "complete"
1476+
? renderReviewCommentFromReport(
1477+
reportMarkdown,
1478+
"none",
1479+
previousLocalReviewCommentBody
1480+
? { previousReviewCommentBody: previousLocalReviewCommentBody }
1481+
: undefined,
1482+
)
1483+
: previousLocalReviewCommentBody;
1484+
if (nextLocalReviewCommentBody) {
1485+
writeFileSync(itemLocalReviewHistoryPath, nextLocalReviewCommentBody, "utf8");
1486+
}
1487+
}
14101488
recordReviewLogPublication({
14111489
ledger: reviewLedger,
14121490
item,

‎src/clawsweeper-review-comments.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,8 +109,15 @@ export function latestClawSweeperReview(
109109
.filter((comment) => isDurableReviewComment(comment, number, context))
110110
.sort((left, right) => commentTimestampMs(right) - commentTimestampMs(left))[0];
111111
if (!latest) return null;
112-
const comment = asRecord(latest);
113-
const body = rawCommentBody(latest);
112+
return previousClawSweeperReviewFromComment(latest, context);
113+
}
114+
115+
export function previousClawSweeperReviewFromComment(
116+
value: unknown,
117+
context: ReviewCommentContext,
118+
): PreviousClawSweeperReview {
119+
const comment = asRecord(value);
120+
const body = rawCommentBody(value);
114121
const verdictMarker = htmlMarkerWithPrefix(body, "clawsweeper-verdict:");
115122
const actionMarker = htmlMarkerWithPrefix(body, "clawsweeper-action:");
116123
const history = parseReviewHistory(body);

‎src/clawsweeper-review-preparation.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { existsSync, readFileSync, unlinkSync } from "node:fs";
2-
import { join, resolve } from "node:path";
2+
import { dirname, join, resolve } from "node:path";
33
import { boolArg, itemNumbersArg, numberArg, stringArg } from "./clawsweeper-args.js";
44
import {
55
DEFAULT_CODEX_MODEL,
@@ -38,6 +38,7 @@ export function prepareReviewCommand(
3838
DEFAULT_PLAN_BATCH_SIZE,
3939
defaultItemsDir,
4040
defaultLocalRangeArtifactDir,
41+
defaultLocalRangeHistoryPath,
4142
defaultReviewArtifactDir,
4243
ensureDir,
4344
gitInfo,
@@ -127,6 +128,10 @@ export function prepareReviewCommand(
127128
? buildLocalRangeReview(openclawDir, targetRepo(), stringArg(args.base, ""))
128129
: undefined;
129130
ensureDir(artifactDir);
131+
const localReviewHistoryPath = localRangeData
132+
? defaultLocalRangeHistoryPath(openclawDir, targetRepo(), localRangeData.baseSha)
133+
: null;
134+
if (localReviewHistoryPath) ensureDir(dirname(localReviewHistoryPath));
130135
const coordinationHeldPath = join(artifactDir, "coordination-held.json");
131136
if (existsSync(coordinationHeldPath)) unlinkSync(coordinationHeldPath);
132137
if (localRangeData) {
@@ -197,6 +202,7 @@ export function prepareReviewCommand(
197202
additionalPrompt,
198203
allowClosed,
199204
localRangeData,
205+
localReviewHistoryPath,
200206
coordinationHeldPath,
201207
shardIndex,
202208
shardCount,

‎src/clawsweeper-review-runtime.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,42 @@ export function createReviewRuntime({
216216
return resolve(targetDir, gitArtifactRoot, `local-range-${Date.now()}-${process.pid}`);
217217
}
218218

219+
function defaultLocalRangeHistoryPath(targetDir: string, repo: string, baseSha: string): string {
220+
const gitArtifactRoot = run("git", ["rev-parse", "--git-path", "clawsweeper/reviews"], {
221+
cwd: targetDir,
222+
}).trim();
223+
return resolve(
224+
targetDir,
225+
gitArtifactRoot,
226+
`local-range-review-history-${repositoryProfileFor(repo).slug}-${baseSha}.md`,
227+
);
228+
}
229+
230+
function localExactReviewHistoryPath(
231+
artifactDir: string,
232+
repo: string,
233+
itemNumber: number,
234+
): string {
235+
return join(
236+
artifactDir,
237+
`local-review-history-${repositoryProfileFor(repo).slug}-${itemNumber}.md`,
238+
);
239+
}
240+
241+
function localRangeHistoryApplies(
242+
targetDir: string,
243+
reviewedSha: string | null,
244+
headSha: string,
245+
): boolean {
246+
if (!reviewedSha || !/^[0-9a-f]{40}$/i.test(reviewedSha)) return false;
247+
try {
248+
run("git", ["merge-base", "--is-ancestor", reviewedSha, headSha], { cwd: targetDir });
249+
return true;
250+
} catch {
251+
return false;
252+
}
253+
}
254+
219255
function resolveReviewCheckout(options: {
220256
args: Args;
221257
artifactDir: string;
@@ -355,6 +391,14 @@ export function createReviewRuntime({
355391
return defaultReviewArtifactDir(localOnly, itemNumber, itemNumbers);
356392
}
357393

394+
function localExactReviewHistoryPathForTest(
395+
artifactDir: string,
396+
repo: string,
397+
itemNumber: number,
398+
): string {
399+
return localExactReviewHistoryPath(artifactDir, repo, itemNumber);
400+
}
401+
358402
function prepareManagedLocalReviewCheckoutForTest(
359403
options: ManagedLocalReviewCheckoutOptions,
360404
): void {
@@ -1083,6 +1127,7 @@ ${extra}
10831127
codexFailureLogKindForTest,
10841128
codexReviewFailureRetryableForTest,
10851129
defaultReviewArtifactDirForTest,
1130+
localExactReviewHistoryPathForTest,
10861131
makeTreeReadOnlyForTest,
10871132
prepareManagedLocalReviewCheckoutForTest,
10881133
restoreTreeModesForTest,
@@ -1099,12 +1144,15 @@ ${extra}
10991144
codexFailureReason,
11001145
codexReviewFailureRetryable,
11011146
defaultLocalRangeArtifactDir,
1147+
defaultLocalRangeHistoryPath,
11021148
defaultReviewArtifactDir,
11031149
displayDurationMs,
11041150
displayPath,
11051151
gitInfo,
11061152
isSafeGitBranchName,
11071153
localExactReviewItem,
1154+
localExactReviewHistoryPath,
1155+
localRangeHistoryApplies,
11081156
makeTreeReadOnly,
11091157
prCloseCoverageProofPromptTemplate,
11101158
resolveReviewCheckout,

‎src/clawsweeper-runtime.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -741,6 +741,7 @@ export const {
741741
codexFailureLogKindForTest,
742742
codexReviewFailureRetryableForTest,
743743
defaultReviewArtifactDirForTest,
744+
localExactReviewHistoryPathForTest,
744745
makeTreeReadOnlyForTest,
745746
prepareManagedLocalReviewCheckoutForTest,
746747
restoreTreeModesForTest,

0 commit comments

Comments
 (0)