Skip to content

Commit 710819a

Browse files
committed
fix(review): distinguish PR changes from main-only drift
1 parent 0bd84d4 commit 710819a

17 files changed

Lines changed: 849 additions & 42 deletions

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ checkpoint, and status-only commits are intentionally omitted.
1919

2020
### Changed
2121

22+
- PR reviews now separate introduced changes from main-only drift, verify test-merge parents, and avoid stored-data warnings for ordinary Markdown prose beside source.
23+
- Review and repair fetches preserve the target branch ref when Git pruning is enabled.
2224
- Default close-mode apply runs now requeue up to five exact re-reviews for records whose close was blocked by source drift or an unverified-checkout review, so stale backlog records converge to closeable instead of being skipped by every cursor sweep.
2325
- Live verification now publishes a sanitized, capped dev-server log tail when browser startup fails, and detects a start command that exits before its URL becomes reachable without waiting for the readiness timeout.
2426
- Live verification now installs a missing target package manager on demand after execution is approved, publishes installer failures as verification results, and guides plans toward stable assertions the run can satisfy.

‎docs/pr-review-comments.md‎

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -108,11 +108,44 @@ merge-risk options, full review comments, labels, evidence, optional rank-up
108108
moves, the rank legend, workflow notes, and review history.
109109

110110
For OpenClaw PRs, stored-data warnings flag possible persistence changes in
111-
production source or semantic documentation changes, not setup in test,
112-
fixture, or example source paths. Renames retain evidence from either production
113-
path. Missing, empty, or truncated patches on likely production persistence paths,
114-
and truncated file lists, still produce conservative unknown warnings. The
115-
warning requests review; it does not prove a persisted contract changed.
111+
production source or documented storage contracts, not setup in test, fixture,
112+
or example source paths. Markdown beside source is still documentation: ordinary
113+
prose mentioning sessions or metadata is not a stored-format change. Explicit
114+
storage formats, SQL DDL, and structured storage keys (including frontmatter)
115+
remain evidence. Renames retain evidence from either production path. Missing,
116+
empty, or truncated patches on likely production persistence paths or hook
117+
descriptors, and truncated file lists, still produce conservative unknown
118+
warnings. The warning requests review; it does not prove a persisted contract
119+
changed. This classification does not change the separate `docs/` exemption for
120+
contributor behavior proof.
121+
122+
## PR Introduction Evidence
123+
124+
Before model execution, the host assembles bounded local Git evidence for the
125+
pinned PR base and head. The reviewer receives the actual checkout SHA separately
126+
from fetched main, the unique merge base, introduced files and patch from
127+
merge-base to head, base-branch changes, and a separately labeled base-to-head
128+
endpoint comparison. A file that differs only because main advanced is not
129+
automatically a PR edit. Findings in untouched files remain valid when an
130+
introduced hunk elsewhere causes the failure; risks, labels, scores, and fixups
131+
must use that same ownership boundary.
132+
133+
The existing PR hydration path may fetch up to 256 commits of ancestry per tip
134+
and the pinned open-PR test merge before restricted review. The evidence reader
135+
itself cannot fetch objects or run external diff drivers. It bounds each Git read
136+
to 1 MiB and five seconds, lists to 80 paths, and the introduced patch to 24,000
137+
characters. Missing blobs, incomplete shallow ancestry, multiple merge bases,
138+
and truncated evidence are explicit limitations, never inferred ownership or an
139+
automatic pass.
140+
141+
Test-merge evidence is accepted only for an open, unmerged PR and a local commit
142+
with exactly the pinned base then head as its two parents. Its result is compared
143+
with that base parent, which may differ from newly fetched main. Stale test
144+
merges and final merge commits cannot establish what this merge would change.
145+
A clean merge does not rule out semantic regressions.
146+
147+
This is reviewer input, not a new persistent decision or repair contract.
148+
OpenClaw Bay is unaffected: no observer fields, routes, or controls change.
116149

117150
Security defaults to `None.` when there are no concerns. Do not spend public
118151
space explaining why an uneventful security pass is uneventful.

‎prompts/review-item.md‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,30 @@ The checkout must remain byte-for-byte clean. Use read-only inspection commands
6969

7070
Review deeply before closing. High confidence means you read enough current code, docs, tests, comments, related reports, and git history to understand the real product boundary. Do not decide from the issue title, one exact `rg` hit, or one nearby file. Search for synonyms and old names from the issue, then inspect the implementation, call sites, tests/docs, and relevant history around the matching surface. Prefer several independent checks over a single brittle match. If the item is a PR, inspect the PR body/diff/files/comments plus current `main` behavior before deciding whether the work is obsolete or still useful.
7171

72+
For PR ownership, start with the host-computed `PR Introduction Evidence`.
73+
`introduced` is the pinned merge-base..head delta; `endpointDrift` is base..head
74+
and is not introduction evidence. `baseChanges` and `baseOnlyFiles` identify
75+
base-branch work, not edits by this PR. `checkoutSha` records the actual local
76+
revision; `fetchedMainSha` is behavioral context and may differ from both the
77+
checkout and the pinned PR base. GitHub `pullFiles` supplies bounded PR patches,
78+
not an endpoint comparison; check truncation and pinned identities before use.
79+
When host evidence is unavailable, ambiguous, or incomplete, say what is missing
80+
and use only independently verified introduced hunks. Never guess ownership from
81+
an older head's contents or a current-main comparison.
82+
83+
Every finding must identify an actual introduced trigger and its causal link to
84+
the failure. An untouched affected file is a valid finding location when another
85+
introduced hunk causes the regression; this is not a changed-file allowlist.
86+
Current main versus an older head cannot establish a revert or downgrade. For
87+
a claim about what merging would remove, verify the test merge has exactly the
88+
pinned main/base parent followed by the exact head parent, then compare its
89+
result against that main parent. Do not substitute a final merge commit, stale
90+
test merge, or `mergeable` metadata. A clean merge does not rule out semantic
91+
regressions. Apply this ownership check to all derivative risks, labels, scores,
92+
compatibility warnings, and recommended fixups, not only `reviewFindings`.
93+
Before returning the decision, remove or correct claims whose introduced trigger
94+
was disproved; unavailable evidence is not an automatic pass or a contributor defect.
95+
7296
Every review must answer whether the item is still necessary. For both issues
7397
and PRs, check whether current `main` already solves the central user problem,
7498
whether the fix is in the latest release or main-only, and whether a merged or
@@ -667,7 +691,10 @@ Durable Object or hosted storage schemas, serialized JSON state written to disk
667691
or a database, vector or embedding row identity/query-compatibility metadata,
668692
and doctor, repair, migration, or backfill code that rewrites persisted state.
669693
Do not treat pure query-only changes or non-semantic docs wording as data-model
670-
breakage by default. When a PR materially changes a stored data model, require
694+
breakage by default. Markdown beside source is not automatically runtime code:
695+
distinguish prose from changed machine-consumed frontmatter, configuration, or
696+
persisted-format contracts; unchanged frontmatter is not an introduced trigger.
697+
When a PR materially changes a stored data model, require
671698
maintainer-visible migration or upgrade compatibility proof before any pass,
672699
automerge, or autofix verdict.
673700

‎src/clawsweeper-change-detection.ts‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ export function dataModelChangeFromContext(repo: string, context: ItemContext):
100100
}
101101

102102
for (const candidate of candidates) {
103-
if (isDocsPath(candidate)) {
103+
if (isDataModelDocumentationPath(candidate)) {
104104
if (patch !== null && !configSurfacePatchIsTruncated(patch)) {
105105
dataModelSurfacesFromPatch(candidate, lines, { docsOnly: true }).forEach((surface) =>
106106
surfaces.add(surface),
@@ -458,7 +458,7 @@ function dataModelSurfacesFromPatch(
458458
add("persistent cache schema");
459459
}
460460
if (
461-
/\b(?:embedding|vector|collection|dimension|metadata|row[_-]?id|document[_-]?id|chunk[_-]?id|similarity[_-]?index)\b/i.test(
461+
/\b(?:embedding(?:[_-]?dimension)?|vector(?:[_-]?dimension)?|collection|dimension|metadata|row[_-]?id|document[_-]?id|chunk[_-]?id|similarity[_-]?index)\b/i.test(
462462
text,
463463
)
464464
) {
@@ -471,16 +471,31 @@ function dataModelLineLooksSemantic(line: string, options: { docsOnly: boolean }
471471
const trimmed = line.trim();
472472
if (!trimmed || /^\/\/|^\/\*|^\*|^<!--/.test(trimmed)) return false;
473473
if (!options.docsOnly) return true;
474-
return /\b(?:schema|migration|migrate|upgrade|backfill|database|sqlite|postgres|durable object|storage|cache|serialized|json state|embedding|vector|metadata|doctor|repair)\b/i.test(
475-
trimmed,
474+
// Markdown lives beside runtime code too. Words such as "session" or
475+
// "metadata" describe behavior, not necessarily a changed stored contract.
476+
return (
477+
/\b(?:CREATE|ALTER|DROP)\s+(?:TABLE|INDEX|VIEW|COLUMN)\b|\bPRAGMA\s+user_version\b/i.test(
478+
trimmed,
479+
) ||
480+
/^["'`]?(?:schema[_-]?version|cache[_-]?(?:key|version|schema|namespace)|embedding[_-]?dimension|vector[_-]?dimension|row[_-]?id|document[_-]?id|chunk[_-]?id)["'`]?\s*:/i.test(
481+
trimmed,
482+
) ||
483+
/\b(?:serialized|persisted|storage|database|cache|vector|embedding)\s+(?:data\s+)?(?:format|schema|layout|identity|namespace)\b/i.test(
484+
trimmed,
485+
)
476486
);
477487
}
478488

479489
function isLikelyOpenClawDataModelPath(path: string): boolean {
480490
if (!path || isDocsPath(path)) return false;
491+
if (isMarkdownConfigSurfacePath(path)) return /(?:^|\/)HOOK\.md$/.test(path);
481492
return Boolean(dataModelPathHint(path)) || /\.(?:sql|sqlite|db|prisma)$/.test(path);
482493
}
483494

495+
function isDataModelDocumentationPath(path: string): boolean {
496+
return isDocsPath(path) || isMarkdownConfigSurfacePath(path);
497+
}
498+
484499
function dataModelPathHint(path: string): string {
485500
if (
486501
/(^|\/)(?:durable-?objects?|workers?|storage)(?:\/|[-_.])|durable-?object|state-storage/i.test(

‎src/clawsweeper-context-hydration.ts‎

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
ensureReviewTreeCommit,
1616
githubReviewBlobSizes,
1717
hydratePullRequestReviewBlobs,
18+
hydratePullRequestReviewHistory,
1819
materializePullRequestReviewTree,
1920
removePullRequestReviewTree,
2021
} from "./clawsweeper-review-blobs.js";
@@ -1002,20 +1003,33 @@ export function createContextHydration(dependencies: CreateContextHydrationDepen
10021003
});
10031004

10041005
if (commitsAvailable) {
1005-
const hydration = hydratePullRequestReviewBlobs({
1006+
const testMergeSha =
1007+
pull.merged === false && pull.state === "open"
1008+
? stringOrUndefined(pull.merge_commit_sha)
1009+
: undefined;
1010+
const mergeBaseSha = hydratePullRequestReviewHistory({
10061011
targetDir: options.targetDir,
10071012
baseSha,
10081013
headSha,
1009-
files: options.files,
1010-
resolveBlobSizes: (objectIds) =>
1011-
githubReviewBlobSizes({
1012-
repository: targetRepo(),
1013-
objectIds,
1014-
request: (query) => ghJson(["api", "graphql", "-f", `query=${query}`]),
1015-
}),
1014+
itemNumber: options.itemNumber,
1015+
...(testMergeSha ? { testMergeSha } : {}),
10161016
});
1017-
if (!hydration.hydrated) {
1018-
console.warn("pull-request review blobs could not be hydrated before restricted review");
1017+
for (const revision of new Set([mergeBaseSha ?? baseSha, baseSha])) {
1018+
const hydration = hydratePullRequestReviewBlobs({
1019+
targetDir: options.targetDir,
1020+
baseSha: revision,
1021+
headSha,
1022+
files: options.files,
1023+
resolveBlobSizes: (objectIds) =>
1024+
githubReviewBlobSizes({
1025+
repository: targetRepo(),
1026+
objectIds,
1027+
request: (query) => ghJson(["api", "graphql", "-f", `query=${query}`]),
1028+
}),
1029+
});
1030+
if (!hydration.hydrated) {
1031+
console.warn("pull-request review blobs could not be hydrated before restricted review");
1032+
}
10191033
}
10201034
}
10211035

‎src/clawsweeper-review-blobs.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { spawnSync } from "node:child_process";
22
import { existsSync } from "node:fs";
3+
import { reviewMergeBase } from "./pr-review-evidence.js";
34

45
const MAX_REVIEW_FILES = 80;
56
const MAX_GIT_OUTPUT_BYTES = 4 * 1024 * 1024;
@@ -57,6 +58,7 @@ export function ensureReviewTreeCommit({
5758
cwd: targetDir,
5859
env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
5960
stdio: "ignore",
61+
timeout: 30_000,
6062
},
6163
);
6264
return !fetched.error && fetched.status === 0 && gitCommitExists(targetDir, sha);
@@ -91,6 +93,56 @@ export function ensurePullRequestReviewHead({
9193
);
9294
}
9395

96+
export function hydratePullRequestReviewHistory(options: {
97+
targetDir: string;
98+
baseSha: string;
99+
headSha: string;
100+
itemNumber: number;
101+
testMergeSha?: string;
102+
}): string | null {
103+
const { targetDir, baseSha, headSha, itemNumber, testMergeSha } = options;
104+
if (
105+
!GIT_OBJECT_ID.test(baseSha) ||
106+
!GIT_OBJECT_ID.test(headSha) ||
107+
!Number.isSafeInteger(itemNumber) ||
108+
itemNumber <= 0
109+
)
110+
return null;
111+
if (reviewMergeBase(targetDir, baseSha, headSha).status === "unavailable") {
112+
// Existing tree hydration may have fetched only the PR tip. Bound history, not
113+
// the reviewed identity; failure remains explicit in the local evidence reader.
114+
spawnSync(
115+
"git",
116+
[
117+
"fetch",
118+
"--filter=blob:none",
119+
"--no-tags",
120+
"--no-write-fetch-head",
121+
"--recurse-submodules=no",
122+
"--depth=256",
123+
"origin",
124+
baseSha,
125+
headSha,
126+
],
127+
{
128+
cwd: targetDir,
129+
env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
130+
stdio: "ignore",
131+
timeout: 30_000,
132+
},
133+
);
134+
}
135+
if (testMergeSha && GIT_OBJECT_ID.test(testMergeSha)) {
136+
ensureReviewTreeCommit({
137+
targetDir,
138+
sha: testMergeSha,
139+
sourceRef: `refs/pull/${itemNumber}/merge`,
140+
destinationRef: `refs/clawsweeper/review-cache/merge-${itemNumber}`,
141+
});
142+
}
143+
return reviewMergeBase(targetDir, baseSha, headSha).sha;
144+
}
145+
94146
function reviewTreeMatchesCommit({ targetDir, sha }: { targetDir: string; sha: string }): boolean {
95147
const head = spawnSync("git", ["rev-parse", "HEAD"], {
96148
cwd: targetDir,

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1490,7 +1490,7 @@ export function createReviewCommandWorkflow(dependencies: CreateReviewCommandWor
14901490
context,
14911491
git,
14921492
additionalPrompt,
1493-
mediaProofRuntimeHints(proofScratchDir, preparedMediaProof),
1493+
{ ...mediaProofRuntimeHints(proofScratchDir, preparedMediaProof), targetDir: reviewOpenclawDir },
14941494
);
14951495
const snapshotHash = itemSnapshotHash(item, context);
14961496
let decision: Decision;

‎src/clawsweeper-review-runtime.ts‎

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
} from "./clawsweeper-media-proof.js";
1919
import { DEFAULT_CODEX_FALLBACK_MIN_BUDGET_MS } from "./clawsweeper-policy.js";
2020
import { safeOutputTail, trimMiddle } from "./clawsweeper-text.js";
21+
import { buildPullRequestReviewEvidence } from "./pr-review-evidence.js";
2122
import type {
2223
Decision,
2324
DecisionNormalizationItem,
@@ -100,7 +101,12 @@ export function createReviewRuntime({
100101
requireSafeGitBranchName(targetBranch, "target branch");
101102
run(
102103
"git",
103-
["fetch", "origin", `${targetBranch}:refs/remotes/origin/${targetBranch}`, "--depth=50"],
104+
[
105+
"fetch",
106+
"origin",
107+
`refs/heads/${targetBranch}:refs/remotes/origin/${targetBranch}`,
108+
"--depth=50",
109+
],
104110
{
105111
cwd: openclawDir,
106112
},
@@ -442,6 +448,18 @@ export function createReviewRuntime({
442448
): ReviewPromptBuild {
443449
const prompt = reviewPromptTemplate();
444450
const contextJson = contextJsonForPrompt(context);
451+
const introductionEvidence =
452+
item.kind === "pull_request"
453+
? `\n\n## PR Introduction Evidence\n\n\`\`\`json\n${JSON.stringify(
454+
buildPullRequestReviewEvidence({
455+
...(runtimeHints.targetDir ? { targetDir: runtimeHints.targetDir } : {}),
456+
context,
457+
mainSha: git.mainSha,
458+
}),
459+
null,
460+
2,
461+
)}\n\`\`\`\n`
462+
: "";
445463
const schema = reviewDecisionSchemaText();
446464
const proofScratchDir = runtimeHints.proofScratchDir?.trim();
447465
const maturityHelperPath = proofScratchDir
@@ -473,7 +491,7 @@ ${additionalPrompt.trim()}
473491
- Author association: ${item.authorAssociation}
474492
- Created at: ${item.createdAt}
475493
- Updated at: ${item.updatedAt}
476-
- Current main SHA: ${git.mainSha}
494+
- Fetched target branch SHA (not necessarily the checkout revision): ${git.mainSha}
477495
- Latest release: ${git.latestRelease?.tagName ?? "unknown"} (${git.latestRelease?.sha ?? "unknown sha"})
478496
479497
## Runtime Capabilities
@@ -483,6 +501,7 @@ ${additionalPrompt.trim()}
483501
- The target checkout is read-only for review. Do not modify repository files; use the scratch directory or /tmp for downloaded evidence and generated video stills/contact sheets.
484502
- A token-light maturity helper is available at ${maturityHelperPath}. For issue maturity labels, first run \`node "$CLAWSWEEPER_PROOF_SCRATCH_DIR/maturity-stable-shortlist.mjs"\` from the target checkout and compare the issue against that shortlist; read the full scorecard or taxonomy only if the shortlist is ambiguous.
485503
${mediaProofPrompt}
504+
${introductionEvidence}
486505
487506
## GitHub Context
488507
@@ -496,7 +515,7 @@ ${extra}
496515
telemetry: {
497516
promptChars: text.length,
498517
staticPromptChars: prompt.length,
499-
contextChars: contextJson.length,
518+
contextChars: contextJson.length + introductionEvidence.length,
500519
schemaChars: schema.length,
501520
additionalPromptChars: additionalPrompt.trim().length,
502521
},
@@ -985,13 +1004,10 @@ ${extra}
9851004
const outputPath = join(options.workDir, `${options.item.number}.json`);
9861005
const prompt =
9871006
options.prompt ??
988-
buildReviewPrompt(
989-
options.item,
990-
options.context,
991-
options.git,
992-
options.additionalPrompt,
993-
mediaProofRuntimeHints(proofScratchDir, preparedMediaProof),
994-
).text;
1007+
buildReviewPrompt(options.item, options.context, options.git, options.additionalPrompt, {
1008+
...mediaProofRuntimeHints(proofScratchDir, preparedMediaProof),
1009+
targetDir: options.openclawDir,
1010+
}).text;
9951011
writeFileSync(promptPath, prompt, "utf8");
9961012
const codexEnv = untrustedCodexEnv({
9971013
ghToken: process.env.CLAWSWEEPER_PROOF_INSPECTION_TOKEN,

‎src/clawsweeper-types.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -760,6 +760,7 @@ export interface ReviewContextLedgerEntry {
760760
}
761761

762762
export interface ReviewPromptRuntimeHints {
763+
targetDir?: string;
763764
proofScratchDir?: string;
764765
mediaProofManifestPath?: string;
765766
mediaProofSummary?: string;

0 commit comments

Comments
 (0)