diff --git a/.gitattributes b/.gitattributes index 3ab406d..e3c3ab4 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,7 @@ *.patch -text *.diff -text internal/guesttools/file_sync.sh text eol=lf +internal/guesttools/drop_agent.sh text eol=lf +internal/guesttools/drop_resolve.js text eol=lf +internal/guesttools/*-Host-DNS.command text eol=lf +internal/guesttools/dns-proxy.pl text eol=lf diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 6a2a2e3..0948b9f 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -3,6 +3,6 @@ contact_links: - name: Roadmap / 开发路线图 url: https://github.com/Nwflower/Reims-Go/blob/main/docs/roadmap.md about: Check current progress and planned features before opening a duplicate / 查看当前进度与已规划功能,避免重复提问 - - name: Documentation / 使用文档(English · 简体中文) - url: https://github.com/Nwflower/Reims-Go/blob/main/README.md - about: Quick start, requirements, and troubleshooting guides / 快速开始、环境要求与常见问题排查 + - name: Documentation / 使用文档 + url: https://reims.dev/en/docs/quick-start + about: Quick start, requirements, and troubleshooting guides on reims.dev / 快速开始、环境要求与常见问题排查(中文版:https://reims.dev/docs/quick-start) diff --git a/.github/scripts/pr-review-language.mjs b/.github/scripts/pr-review-language.mjs index 46df7c4..ca1ea5d 100644 --- a/.github/scripts/pr-review-language.mjs +++ b/.github/scripts/pr-review-language.mjs @@ -9,25 +9,30 @@ export const english = { upgrade: "Upgrade compatibility", ui: "UI consistency", implementation: "Duplication and simplification", - tests: "Test evidence for this PR commit", + tests: "CI for this PR commit", ciRun: "CI run", ciPassed: "Passed", - ciFailed: "Not passed", + ciFailed: "Failed", + ciNoPass: "No passing result", + ciActionRequired: "CI needs manual action.", ciPending: "Pending", ciMissing: "No CI run found for this commit.", - pending: "Still to verify", + pending: "Required manual checks", recommendation: "Merge recommendation", merge: "Ready to merge", changes: "Revise and review again", - verify: "Verify before merging", + verify: "Verify the key scenarios first", + inspect: "Review the remaining changes", + awaitCI: "No code blockers found. Awaiting CI.", decline: "Hold this PR", conflict: "GitHub detected merge conflicts. Resolve them and request another review.", - mainMoved: "The default branch moved during review. Review against the new commit.", - ciRequired: "Wait for passing CI and evidence of key tests.", + mainMoved: "The default branch moved during this review.", + ciRequired: "This commit has no passing CI result yet.", + fixCI: "Resolve the CI failure before merging.", + fixFindings: "Address the actionable findings below before merging.", pendingRequired: "Run the key checks listed above.", incomplete: "Review the remaining changes before merging.", inline: "Inline findings", - unlocated: "Findings could not be anchored to a reviewed line.", noFindings: "No actionable issues found in the reviewed changes.", noDiff: "No text diff was available to review.", inlineFallback: "GitHub could not attach inline comments. See the findings below.", @@ -44,25 +49,30 @@ export const chinese = { upgrade: "旧版本、数据与配置升级", ui: "界面规范与风格", implementation: "实现精简与重复逻辑", - tests: "当前 PR 提交的实测记录", + tests: "当前 PR 提交的 CI", ciRun: "CI 运行记录", ciPassed: "通过", - ciFailed: "未通过", + ciFailed: "失败", + ciNoPass: "无通过结果", + ciActionRequired: "CI 需要人工处理。", ciPending: "尚未完成", ciMissing: "未找到对应提交的 CI 记录。", - pending: "待实测", + pending: "合并前必做实测", recommendation: "合并建议", merge: "可以合并", changes: "修改后再审", - verify: "待实测后再决定", + verify: "先验证关键场景", + inspect: "先审完剩余改动", + awaitCI: "代码未见阻塞,等待 CI", decline: "暂不合并", conflict: "GitHub 检测到合并冲突,解决后重新审核。", - mainMoved: "主线已更新,请对照新的主线提交重新审核。", - ciRequired: "等待对应提交的 CI 和关键测试记录。", + mainMoved: "审核期间主线有更新。", + ciRequired: "当前提交还没有 CI 通过记录。", + fixCI: "合并前处理 CI 失败项。", + fixFindings: "合并前处理下方有证据的实质问题。", pendingRequired: "完成上面列出的关键流程实测。", incomplete: "本次只覆盖部分差异,合并前补齐审查。", inline: "行内问题", - unlocated: "审核建议未能定位到已审核的改动行。", noFindings: "已审核的差异中未发现可报告的问题。", noDiff: "没有可审核的文本差异。", inlineFallback: "GitHub 未能附加行内评论,审核意见如下。", diff --git a/.github/scripts/pr-review.mjs b/.github/scripts/pr-review.mjs index 2e96d2c..551613b 100644 --- a/.github/scripts/pr-review.mjs +++ b/.github/scripts/pr-review.mjs @@ -9,11 +9,17 @@ const MAX_FILES = 300; const MAX_DIFF_LENGTH = 400_000; const MAX_FILE_LENGTH = 36_000; const CI_WAIT_MS = 240_000; -const MAX_FINDINGS = 5; +const CI_APPEAR_WAIT_MS = 60_000; +const MAX_FINDINGS = 3; 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 +400,11 @@ async function listChangedFiles(github, path) { return files.slice(0, MAX_FILES); } -async function waitForCI(github, repoPath, pull, number) { +export async function waitForCI(github, repoPath, pull, number, { skipCI = false, wait = true } = {}) { 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,14 +421,19 @@ 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 (!wait || 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)); } } +function reviewMarker(revision, mainSha, ci) { + return MARKER_PREFIX + [revision, mainSha, ci.id ?? "none", ci.attempt ?? "none", ci.conclusion ?? ci.status].join(":") + " -->"; +} + async function mainlineContext(github, repoPath, pull, files) { const branch = pull.base.repo.default_branch; const refPath = repoPath + "/git/ref/heads/" + encodeURIComponent(branch); @@ -367,37 +463,59 @@ async function mainlineContext(github, repoPath, pull, files) { }; } -function reviewSummary(copy, assessment, ci, incomplete, mainMoved, mergeable) { +export function reviewSummary(copy, assessment, ci, { incomplete, mergeable, hasFindings, locations }) { const lines = []; for (const key of REVIEW_SECTIONS) { + if (!assessment[key].trim()) continue; lines.push("- **" + copy[key] + "** " + plainMarkdown(shortText(assessment[key], 75))); } - const ciStatus = ci.status === "completed" ? (ci.conclusion === "success" ? copy.ciPassed : copy.ciFailed + " (`" + ci.conclusion + "`)") - : ci.id ? copy.ciPending : copy.ciMissing; + const ciPassed = ci.status === "completed" && ci.conclusion === "success"; + const ciFailed = ci.status === "completed" && ["failure", "timed_out"].includes(ci.conclusion); + const ciNeedsAction = ci.conclusion === "action_required" || ci.status === "action_required"; + let ciStatus = ci.id ? copy.ciPending : copy.ciMissing; + if (ciNeedsAction) ciStatus = copy.ciActionRequired; + else if (ciPassed) ciStatus = copy.ciPassed; + else if (ci.status === "completed") ciStatus = (ciFailed ? copy.ciFailed : copy.ciNoPass) + " (`" + ci.conclusion + "`)"; lines.push("\n**" + copy.tests + "** " + ciStatus + (ci.url ? " · [" + copy.ciRun + "](" + ci.url + ")" : "")); for (const step of ci.steps ?? []) { lines.push("- " + plainMarkdown(step.name) + " · " + plainMarkdown(step.conclusion ?? "—")); } - const pending = assessment.pending_checks.map((check) => check.trim()).filter(Boolean).slice(0, MAX_PENDING_CHECKS); + const pending = assessment.pending_checks.filter((check) => MANUAL_IMPACTS.has(check?.impact) + && typeof check.scenario === "string" && check.scenario.trim() + && typeof check.consequence === "string" && check.consequence.trim() + && hasChangedEvidence(locations.get(check.path), check.evidence)).slice(0, MAX_PENDING_CHECKS); if (pending.length) { lines.push("\n**" + copy.pending + "**"); - for (const check of pending) lines.push("- " + plainMarkdown(shortText(check, 75))); + for (const check of pending) { + lines.push("- " + plainMarkdown(shortText(check.scenario, 75)) + " · " + plainMarkdown(shortText(check.consequence, 60))); + } } - let decision = assessment.decision; - let reason = plainMarkdown(shortText(assessment.reason, 110)); - const hasTestEvidence = ci.conclusion === "success" && ci.steps?.some((step) => step.conclusion === "success"); + let decision = "merge"; + let reason = copy.noFindings; if (mergeable === false) { decision = "changes"; reason = copy.conflict; - } else if (decision === "merge" && (incomplete || mainMoved || !hasTestEvidence || pending.length)) { + } else if (ciFailed) { + decision = "changes"; + reason = copy.fixCI; + } else if (hasFindings) { + decision = "changes"; + reason = copy.fixFindings; + } else if (assessment.decision === "decline") { + decision = "decline"; + reason = plainMarkdown(shortText(assessment.reason, 110)); + } else if (pending.length) { decision = "verify"; - if (mainMoved) reason = copy.mainMoved; - else if (!hasTestEvidence) reason = copy.ciRequired; - else if (pending.length) reason = copy.pendingRequired; - else reason = copy.incomplete; + reason = copy.pendingRequired; + } else if (incomplete) { + decision = "inspect"; + reason = copy.incomplete; + } else if (!ciPassed) { + decision = "awaitCI"; + reason = copy.ciRequired; } lines.push("\n**" + copy.recommendation + " · " + copy[decision] + "** " + reason); return lines.join("\n"); @@ -424,12 +542,23 @@ 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 marker = reviewMarker(revision, mainline.sha, ci); + 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,23 +574,44 @@ 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, base: { branch: pull.base.ref, reportedSha: pull.base.sha, mergeable: pull.mergeable }, mainline: comparison, + goVersion: (await readFile("go.mod", "utf8")).match(/^go (\S+)/m)?.[1], 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); const coverage = copy.scope + " " + diffs.length + "/" + pull.changed_files + (partial ? " (" + partial + " " + copy.partial + ")" : ""); - const result = comments.length ? copy.inline + " · " + comments.length - : findings.length ? copy.unlocated : diffs.length ? copy.noFindings : copy.noDiff; + const result = comments.length ? copy.inline + " · " + comments.length : diffs.length ? "" : copy.noDiff; + let finalCI = ci; + if (ci.conclusion !== "success") { + try { + finalCI = await waitForCI(github, repoPath, pull, number, { wait: false }); + } catch (error) { + console.warn("Could not refresh CI: " + error.message); + } + } + const finalMarker = reviewMarker(revision, mainline.sha, finalCI); + if (finalMarker !== marker) { + const { alreadyReviewed } = await fetchReviewHistory(github, repoPath, path, pull.head.sha, finalMarker); + if (alreadyReviewed) { + console.log("This PR revision has already been reviewed with the latest CI result"); + return; + } + } const latestPR = await currentPR(); if (!latestPR) { console.log("PR changed while the model was reviewing it"); @@ -472,14 +622,19 @@ export async function run() { const mainCoverage = mainline.comparisonUnavailable ? copy.comparisonUnavailable : mainline.overlappingFiles > mainline.overlappingDiffs.length || mainline.partialOverlaps || mainline.fileListMayBeTruncated ? copy.comparisonPartial : ""; - const summary = marker + "\n## " + copy.heading + "\n\n" + copy.mainline + " `" + mainline.sha.slice(0, 12) + "` · " + coverage - + (mainCoverage ? " · " + mainCoverage : "") - + "\n\n" + reviewSummary(copy, assessment, ci, !diffs.length || diffs.length < pull.changed_files || partial > 0 - || Boolean(mainCoverage), mainMoved, latestPR.mergeable); + const scopeNotes = [mainCoverage, mainMoved ? copy.mainMoved : ""].filter(Boolean); + const assessmentSummary = reviewSummary(copy, assessment, finalCI, { + incomplete: !diffs.length || diffs.length < pull.changed_files || partial > 0, + mergeable: latestPR.mergeable, + hasFindings: comments.length > 0, + locations, + }); + const summary = finalMarker + "\n## " + copy.heading + "\n\n" + copy.mainline + " `" + mainline.sha.slice(0, 12) + "` · " + coverage + + (scopeNotes.length ? " · " + scopeNotes.join(" ") : "") + "\n\n" + assessmentSummary; const review = { event: "COMMENT", commit_id: pull.head.sha, - body: summary + "\n\n" + result, + body: result ? summary + "\n\n" + result : summary, }; if (comments.length) review.comments = comments; try { diff --git a/.github/scripts/pr-review.test.mjs b/.github/scripts/pr-review.test.mjs new file mode 100644 index 0000000..762dead --- /dev/null +++ b/.github/scripts/pr-review.test.mjs @@ -0,0 +1,213 @@ +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, + waitForCI, +} 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", impact: "correctness", trigger: "Existing configuration", + evidence: { side: "RIGHT", line: 11, text: "newLine" }, body: "Context anchor works" }, + { path: "a.go", side: "LEFT", line: 11, priority: "P2", impact: "compatibility", trigger: "Upgrading from an old release", + evidence: { side: "LEFT", line: 11, text: "oldLine" }, body: "Deleted anchor works" }, + { path: "a.go", side: "RIGHT", line: 99, priority: "P1", impact: "data", trigger: "Restoring a disk", + evidence: { side: "RIGHT", line: 11, text: "newLine" }, body: "Out of range is dropped" }, + ], + selected.locations, + ); + assert.equal(comments.length, 2); + assert.equal(comments[0].line, 10); + assert.equal(comments[1].side, "LEFT"); +}); + +test("inlineComments drops nits and unsupported evidence and limits findings to three", () => { + const patch = "@@ -1 +1,5 @@\n existing guard\n+crash first\n+crash second\n+crash third\n+crash fourth"; + const locations = new Map([["a.go", diffAnchors(patch)]]); + const finding = { + path: "a.go", side: "RIGHT", line: 2, priority: "P2", impact: "correctness", trigger: "Starting an existing VM", + evidence: { side: "RIGHT", line: 2, text: "crash first" }, body: "Starting an existing VM fails", + }; + const comments = inlineComments([ + { ...finding, priority: "P3" }, + { ...finding, impact: "style" }, + { ...finding, trigger: "" }, + { ...finding, evidence: { side: "RIGHT", line: 1, text: "existing guard" } }, + { ...finding, evidence: { side: "RIGHT", line: 2, text: "invented cause" } }, + finding, + finding, + ...["second", "third", "fourth"].map((name, index) => ({ + ...finding, line: index + 3, evidence: { side: "RIGHT", line: index + 3, text: "crash " + name }, + })), + ], locations); + assert.deepEqual(comments.map(({ line }) => line), [2, 3, 4]); +}); + +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("