diff --git a/.github/scripts/pr-review.mjs b/.github/scripts/pr-review.mjs index 2e96d2c..507e0e0 100644 --- a/.github/scripts/pr-review.mjs +++ b/.github/scripts/pr-review.mjs @@ -9,8 +9,12 @@ const MAX_FILES = 300; const MAX_DIFF_LENGTH = 400_000; const MAX_FILE_LENGTH = 36_000; const CI_WAIT_MS = 240_000; +const CI_APPEAR_WAIT_MS = 60_000; const MAX_FINDINGS = 5; const MAX_PENDING_CHECKS = 3; +const MAX_PREVIOUS_COMMENTS = 8; +const MARKER_PREFIX = "\r?\n?/, "").trim(); + const result = { + commit: latest.commit_id || null, + summary: shortText(body, 1200), + inlineFindings: reviewComments.slice(0, MAX_PREVIOUS_COMMENTS).map((comment) => ({ + path: comment.path, + side: comment.side ?? "RIGHT", + line: comment.line ?? comment.original_line ?? null, + body: shortText(comment.body ?? "", 160), + })), + }; + if (Array.isArray(changedFilesSince)) { + result.changedFilesSincePreviousReview = changedFilesSince.slice(0, 60); + } + return result; +} + +async function fetchReviewHistory(github, repoPath, path, headSha, marker) { + const botReviews = []; + let reviewed = false; for (let page = 1; ; page++) { const { data, link } = await github(path + "/reviews?per_page=100&page=" + page); - if (data.some((review) => review.user?.login === "github-actions[bot]" - && review.state === "COMMENTED" && review.body?.startsWith(marker + "\n"))) return true; - if (!link?.includes('rel="next"')) return false; + for (const review of data) { + if (review.user?.login !== "github-actions[bot]" || review.state !== "COMMENTED") continue; + if (review.body?.startsWith(marker + "\n")) reviewed = true; + if (review.body?.startsWith(MARKER_PREFIX)) botReviews.push(review); + } + if (reviewed || !link?.includes('rel="next"')) break; + } + if (reviewed) return { alreadyReviewed: true, previousReview: null }; + const latest = botReviews.at(-1); + if (!latest) return { alreadyReviewed: false, previousReview: null }; + let comments = []; + try { + ({ data: comments } = await github(path + "/reviews/" + latest.id + "/comments?per_page=100")); + } catch { + comments = []; + } + let changedSince = null; + if (latest.commit_id && latest.commit_id !== headSha) { + try { + const { data: comparison } = await github(repoPath + "/compare/" + latest.commit_id + "..." + headSha + "?per_page=1"); + changedSince = (comparison.files ?? []).map((file) => file.filename); + } catch { + changedSince = null; + } + } + return { + alreadyReviewed: false, + previousReview: extractPreviousReview(botReviews, comments, changedSince), + }; +} + +async function fetchHeadCommitMessage(github, repoPath, sha) { + try { + const { data } = await github(repoPath + "/commits/" + sha); + return data?.commit?.message ?? ""; + } catch { + return ""; } } @@ -311,9 +388,11 @@ async function listChangedFiles(github, path) { return files.slice(0, MAX_FILES); } -async function waitForCI(github, repoPath, pull, number) { +async function waitForCI(github, repoPath, pull, number, { skipCI = false } = {}) { if (pull.base.ref !== pull.base.repo.default_branch || !pull.head.repo) return { status: "unavailable" }; - const deadline = Date.now() + CI_WAIT_MS; + const startedAt = Date.now(); + const deadline = startedAt + CI_WAIT_MS; + const appearDeadline = startedAt + CI_APPEAR_WAIT_MS; const path = repoPath + "/actions/workflows/ci.yml/runs?event=pull_request&per_page=20&head_sha=" + pull.head.sha; for (;;) { const { data } = await github(path); @@ -330,8 +409,9 @@ async function waitForCI(github, repoPath, pull, number) { steps: (steps ?? []).map(({ name, conclusion }) => ({ name, conclusion })), }; } - const remaining = deadline - Date.now(); - if (remaining <= 0 || pull.mergeable === false) { + const now = Date.now(); + const remaining = deadline - now; + if (remaining <= 0 || pull.mergeable === false || (!run && (skipCI || now >= appearDeadline))) { return { status: run?.status ?? "unavailable", id: run?.id, attempt: run?.run_attempt, url: run?.html_url }; } await delay(Math.min(20_000, remaining)); @@ -367,7 +447,7 @@ async function mainlineContext(github, repoPath, pull, files) { }; } -function reviewSummary(copy, assessment, ci, incomplete, mainMoved, mergeable) { +export function reviewSummary(copy, assessment, ci, incomplete, mainMoved, mergeable) { const lines = []; for (const key of REVIEW_SECTIONS) { lines.push("- **" + copy[key] + "** " + plainMarkdown(shortText(assessment[key], 75))); @@ -424,12 +504,24 @@ export async function run() { return; } + const isManual = !event.pull_request; + const headCommitMessage = !isManual && pull.draft ? "" : await fetchHeadCommitMessage(github, repoPath, pull.head.sha); + const skipReason = shouldSkipAutoReview({ isManual, draft: Boolean(pull.draft), commitMessage: headCommitMessage }); + if (skipReason) { + console.log("PR review skipped: " + skipReason); + return; + } + const revision = snapshot(pull).join(":"); - const [files, ci] = await Promise.all([listChangedFiles(github, path), waitForCI(github, repoPath, pull, number)]); + const [files, ci] = await Promise.all([ + listChangedFiles(github, path), + waitForCI(github, repoPath, pull, number, { skipCI: hasSkipCIToken(headCommitMessage) }), + ]); const mainline = await mainlineContext(github, repoPath, pull, files); - const marker = ""; - if (await alreadyReviewed(github, path, marker)) { + const history = await fetchReviewHistory(github, repoPath, path, pull.head.sha, marker); + if (history.alreadyReviewed) { console.log("This PR revision has already been reviewed"); return; } @@ -445,7 +537,7 @@ export async function run() { } const { refPath, ...comparison } = mainline; - const assessment = await reviewDiffs({ + const reviewInput = { title: pull.title.slice(0, 300), description: (pull.body ?? "").slice(0, 3500), head: pull.head.sha, @@ -454,7 +546,12 @@ export async function run() { coverage: { reviewedFiles: diffs.length, changedFiles: pull.changed_files, partialFiles: partial }, ci: { ...ci, changesCIWorkflow: files.some((file) => file.filename === ".github/workflows/ci.yml") }, diffs, - }, files.some((file) => file.filename.startsWith("frontend/") || file.previous_filename?.startsWith("frontend/"))); + }; + if (history.previousReview) reviewInput.previousReview = history.previousReview; + const assessment = await reviewDiffs( + reviewInput, + files.some((file) => file.filename.startsWith("frontend/") || file.previous_filename?.startsWith("frontend/")), + ); const { findings } = assessment; const copy = localizedCopy(assessment); const comments = inlineComments(findings, locations); diff --git a/.github/scripts/pr-review.test.mjs b/.github/scripts/pr-review.test.mjs new file mode 100644 index 0000000..b444eab --- /dev/null +++ b/.github/scripts/pr-review.test.mjs @@ -0,0 +1,117 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { chinese } from "./pr-review-language.mjs"; +import { + diffAnchors, + extractPreviousReview, + hasSkipCIToken, + inlineComments, + reviewSummary, + selectDiffs, + shouldSkipAutoReview, +} from "./pr-review.mjs"; + +test("hasSkipCIToken recognizes standard skip tokens case-insensitively", () => { + assert.equal(hasSkipCIToken("ui: tweak layout\n\n[skip ci]"), true); + assert.equal(hasSkipCIToken("[CI SKIP] docs update"), true); + assert.equal(hasSkipCIToken("chore: update [no ci]"), true); + assert.equal(hasSkipCIToken("chore: [skip actions]"), true); + assert.equal(hasSkipCIToken("chore: [actions skip]"), true); + assert.equal(hasSkipCIToken("feat: normal commit"), false); + assert.equal(hasSkipCIToken(""), false); +}); + +test("shouldSkipAutoReview skips drafts and skip-ci commits only for automatic triggers", () => { + assert.equal(shouldSkipAutoReview({ isManual: false, draft: true, commitMessage: "feat: wip" }), "PR is a draft"); + assert.equal( + shouldSkipAutoReview({ isManual: false, draft: false, commitMessage: "fix: typo\n\n[skip ci]" }), + "head commit requested [skip ci]", + ); + assert.equal(shouldSkipAutoReview({ isManual: false, draft: false, commitMessage: "fix: typo" }), null); + assert.equal(shouldSkipAutoReview({ isManual: true, draft: true, commitMessage: "[skip ci]" }), null); +}); + +test("diffAnchors includes added, deleted, and context lines while selectDiffs tracks partial hunks", () => { + const patch = [ + "@@ -10,4 +10,4 @@", + " keep1", + "-oldLine", + "+newLine", + " keep2", + ].join("\n"); + const anchors = diffAnchors(patch); + assert.equal(anchors.has("RIGHT:10"), true); + assert.equal(anchors.has("LEFT:11"), true); + assert.equal(anchors.has("RIGHT:11"), true); + assert.equal(anchors.has("RIGHT:12"), true); + assert.equal(anchors.has("LEFT:10"), false); + + const selected = selectDiffs([{ filename: "a.go", patch, changes: 2 }]); + assert.equal(selected.diffs.length, 1); + assert.equal(selected.partial, 0); + + const comments = inlineComments( + [ + { path: "a.go", side: "RIGHT", line: 10, priority: "P2", body: "context anchor works" }, + { path: "a.go", side: "LEFT", line: 11, priority: "P3", body: "deleted anchor works" }, + { path: "a.go", side: "RIGHT", line: 99, priority: "P1", body: "out of range dropped" }, + ], + selected.locations, + ); + assert.equal(comments.length, 2); + assert.equal(comments[0].line, 10); + assert.equal(comments[1].side, "LEFT"); +}); + +test("extractPreviousReview returns latest bot review with stripped marker and changed files", () => { + const reviews = [ + { + id: 1, + commit_id: "aaaa111", + user: { login: "github-actions[bot]" }, + state: "COMMENTED", + body: "\n## 自动代码审核\n\nold summary", + }, + { + id: 2, + commit_id: "bbbb222", + user: { login: "human-reviewer" }, + state: "CHANGES_REQUESTED", + body: "human comment", + }, + { + id: 3, + commit_id: "cccc333", + user: { login: "github-actions[bot]" }, + state: "COMMENTED", + body: "\n## 自动代码审核\n\nlatest summary", + }, + ]; + const prev = extractPreviousReview( + reviews, + [{ path: "internal/app/a.go", side: "RIGHT", line: 42, body: "**[P2]** keep ForegroundPID check" }], + ["internal/app/a.go"], + ); + assert.ok(prev); + assert.equal(prev.commit, "cccc333"); + assert.equal(prev.summary.includes("