fix: refresh reviews after new commits

This commit is contained in:
lezi-fun committed 2026-08-14 09:16:07 +08:00
1 parent ed3e1bd72c
commit 4d73d1f30c
12 files changed
+565 -29

No files matched your search

+6 -1
View File
@@ -22,6 +22,10 @@ on:
pull_number:
required: true
type: string
pull_head_repository:
required: false
type: string
default: ""
comment_id:
required: false
type: string
@@ -203,7 +207,7 @@ jobs:
ref: main
path: ghbot-runtime
- name: Check out current PR source for agent tasks
if: ${{ inputs.event_name == 'issue_comment' || (inputs.event_name == 'pull_request_target' && inputs.event_action != 'closed' && inputs.auto_resolve_conflicts == 'true') }}
if: ${{ inputs.event_name == 'issue_comment' || (inputs.event_name == 'pull_request_target' && inputs.event_action != 'closed' && inputs.auto_resolve_conflicts == 'true' && inputs.pull_head_repository == format('{0}/{1}', inputs.repository_owner, inputs.repository_name)) }}
uses: actions/checkout@v4
with:
repository: ${{ inputs.repository_owner }}/${{ inputs.repository_name }}
@@ -267,6 +271,7 @@ jobs:
GHBOT_REPOSITORY_NAME: ${{ inputs.repository_name }}
GHBOT_REPOSITORY_ID: ${{ inputs.repository_id }}
GHBOT_PULL_NUMBER: ${{ inputs.pull_number }}
GHBOT_PULL_HEAD_REPOSITORY: ${{ inputs.pull_head_repository }}
GHBOT_COMMENT_ID: ${{ inputs.comment_id }}
GHBOT_COMMENTER_LOGIN: ${{ inputs.commenter_login }}
GHBOT_COMMENT_BODY: ${{ inputs.comment_body }}
+1
View File
@@ -52,6 +52,7 @@ jobs:
repository_name: ${{ github.event.repository.name }}
repository_id: ${{ github.repository_id }}
pull_number: ${{ github.event.pull_request.number || github.event.issue.number }}
pull_head_repository: ${{ github.event.pull_request.head.repo.full_name || '' }}
comment_id: ${{ github.event.comment.id || '' }}
commenter_login: ${{ github.event.comment.user.login || '' }}
comment_body: ${{ github.event.comment.body || '' }}
+4
View File
@@ -46,6 +46,8 @@ goose 的审核结果固定包含四个顶层字段:
新 commit 触发 `synchronize` 后,workflow 会恢复该 PR 最新的缓存。goose 同时收到旧审核结果和当前完整 PR diff,重新验证所有旧问题、移除已经修复的问题,并检查新 commit 引入的回归。旧的合并结论不会在没有新审核的情况下直接复用。
每次 `synchronize` 都会先发布一条绑定当前 commit 的“开始审核”进度评论;审核完成、失败,或因为 PR 再次变化而过期时,会更新同一条评论。新审核成功发布后,ghbot 会删除旧机器人审核中的逐行 `review` 和 `change` 意见,dismiss 仍然生效的旧审核结论,并把旧审核正文压缩为 superseded 占位说明。GitHub 不允许删除已经提交的 review 记录本身,因此最终只有最新审核保留完整正文和有效状态。
PR 标题、描述或 base branch 变化触发 `edited` 时也会重新审核。对象按仓库 ID 和 PR 编号隔离;`latest.json` 用于加速下一次审核,`reviews/<head-sha>.json` 留存每个成功审核过的 head。关闭或合并 PR 不会主动删除这些对象。缓存不保存 API key、完整 diff 或 prompt。
需要同时配置:
@@ -97,6 +99,8 @@ Agent 只能编辑临时快照中的 `.ghbot/repository-knowledge.md` 草稿。g
因为它可以执行任意命令,只有具有 `write`、`maintain` 或 `admin` 仓库权限的评论者可以触发。该限制只影响 `@bot` 命令 Agent,不影响外部贡献者的自动 PR 审核。如果外部贡献者需要深入排查,maintainer 可以在对方的 PR 中提到 `@bot`,Agent 会分析该贡献者当前的 PR head,并把回答发布到同一个 conversation。
没有上述权限的用户尝试 `@bot`、`/recheck` 或 `/conflict` 时,机器人会公开回复所需权限并提示联系 maintainer,不再静默失败。回复按源评论 ID 去重,workflow 重跑不会重复发送。
Agent 在一次性 Docker 容器中运行:
- PR head checkout 不保存 GitHub credentials。
+4
View File
@@ -44,6 +44,8 @@ When Cloudflare R2 is configured, each successful review stores this metadata in
When a new commit triggers `synchronize`, or PR metadata/base changes trigger `edited`, the latest cache for that PR is restored. goose receives an earlier-head result plus the current complete PR patch, revalidates old findings, removes fixed findings, and checks the newest content. The previous merge decision is never reused without a fresh review. An `edited` event on the same head still runs a fresh complete review so title, description, and base-branch changes are respected.
For every `synchronize` event, ghbot posts a commit-scoped progress comment when review starts and updates that same comment when the run completes, fails, or becomes stale because the PR changed again. After the new review is published successfully, ghbot removes inline `review` and `change` comments from earlier bot reviews, dismisses any earlier active bot decision, and reduces its old summary to a superseded marker. GitHub does not allow a submitted review record itself to be deleted, so the newest review is the only full and active automated result.
Objects are isolated by repository ID and PR number. `latest.json` accelerates the next review, while `reviews/<head-sha>.json` preserves each successful head result. Closing or merging a PR does not proactively delete these objects. Cache data contains no API keys, full diff, or prompt.
Configure all of these together:
@@ -88,6 +90,8 @@ Missing configured labels are created automatically.
Mention `@bot` in a pull request conversation to ask about the current PR. The configured `BOT_NAME` is also accepted as a mention; for example, `BOT_NAME=github-actions[bot]` accepts both `@github-actions` and `@github-actions[bot]`. Because this agent can execute commands, only repository collaborators with `write`, `maintain`, or `admin` permission may invoke it.
When someone without that permission tries `@bot`, `/recheck`, or `/conflict`, ghbot posts a visible reply explaining the required permission and asks them to contact a maintainer. The response is keyed to the source comment so rerunning the workflow does not duplicate it.
This restriction does not affect automatic review. Pull requests from forks and contributors without repository access still receive the normal `review/change/comment/result` review on every configured PR event. When an external contributor needs repository-agent investigation, a maintainer can mention `@bot` on that contributor's PR; the agent then analyzes the contributor's current PR head in isolation and posts the answer to the same conversation.
ghbot checks out the current PR head without persisted GitHub credentials and gives goose a sanitized temporary snapshot plus the PR title, description, branches, and bounded complete diff. goose runs in a dedicated disposable Docker container with the built-in Developer extension enabled in automatic mode. It can execute commands and tests, edit the temporary workspace, install dependencies, and use the network, but the container mounts only the sanitized PR snapshot and receives no GitHub token, GitHub App credentials, or real goose API key. A short-lived local proxy exchanges the container's one-run token for the real provider credential and closes with the container. The agent cannot commit or push, and resource/time limits still apply. The named container is forcibly removed on success, failure, or timeout.
+27 -6
View File
@@ -8,6 +8,8 @@ import { processIssueTriage, processPullRequestTriage } from "../triage/processo
import { deleteLocalReviewCache } from "../review/cache.js";
import { loadRepositoryKnowledge } from "../repository/knowledge.js";
import {
beginCommitReviewProgress,
finishCommitReviewProgress,
processConflictComment,
processRecheckComment,
processPullRequest,
@@ -159,12 +161,29 @@ async function main(): Promise<void> {
});
}
await processPullRequest(
octokit,
ref,
config.reviewStrictness === "strict" ? "strict" : "normal",
github.token
);
const progress = prPayload.action === "synchronize"
? await beginCommitReviewProgress(octokit, ref)
: undefined;
try {
await processPullRequest(
octokit,
ref,
config.reviewStrictness === "strict" ? "strict" : "normal",
github.token
);
if (progress) {
await finishCommitReviewProgress(octokit, { ...ref, ...progress });
}
} catch (error) {
if (progress) {
await finishCommitReviewProgress(octokit, { ...ref, ...progress, failed: true }).catch(
(progressError: unknown) => {
logger.warn({ error: progressError, ...ref }, "Failed to publish review failure progress.");
}
);
}
throw error;
}
return;
}
@@ -191,6 +210,7 @@ async function main(): Promise<void> {
owner: commentPayload.repository.owner.login,
repo: commentPayload.repository.name,
pullNumber: commentPayload.issue.number,
commentId: commentPayload.comment.id,
commenterLogin: commentPayload.comment.user.login,
commentBody: commentPayload.comment.body,
gitToken: github.token
@@ -199,6 +219,7 @@ async function main(): Promise<void> {
owner: commentPayload.repository.owner.login,
repo: commentPayload.repository.name,
pullNumber: commentPayload.issue.number,
commentId: commentPayload.comment.id,
commenterLogin: commentPayload.comment.user.login,
commentBody: commentPayload.comment.body,
gitToken: github.token
+8 -7
View File
@@ -3,6 +3,7 @@ import path from "node:path";
import type { Octokit } from "@octokit/rest";
import { runGooseAgent } from "../ai/gooseCli.js";
import { config } from "../config.js";
import { postPermissionDeniedComment } from "../github/commandFeedback.js";
import { logger } from "../logger.js";
import { withRetry } from "../retry.js";
import { compactFilesForReview } from "../review/prompt.js";
@@ -56,13 +57,13 @@ export async function processPullRequestChat(
throw error;
});
if (!isTrustedChatPermission(permission.permission)) {
await withRetry("github.issues.createComment.prChatPermissionDenied", async () => {
return octokit.rest.issues.createComment({
owner: params.owner,
repo: params.repo,
issue_number: params.pullNumber,
body: `${marker}\n@${params.commenterLogin}, repository-agent replies can run commands, so only collaborators with write, maintain, or admin permission can invoke them.`
});
await postPermissionDeniedComment(octokit, {
owner: params.owner,
repo: params.repo,
pullNumber: params.pullNumber,
sourceCommentId: params.commentId,
commenterLogin: params.commenterLogin,
command: "@bot"
});
return;
}
+47
View File
@@ -0,0 +1,47 @@
import type { Octokit } from "@octokit/rest";
import { withRetry } from "../retry.js";
export type RepositoryCommand = "/recheck" | "/conflict" | "@bot";
export function formatPermissionDeniedMessage(
commenterLogin: string,
command: RepositoryCommand
): string {
return [
`Hi! @${commenterLogin}, we're sorry that you don't have permission to run \`${command}\`.`,
"Only repository collaborators with **write**, **maintain**, or **admin** permission can run this command.",
"Please ask a repository maintainer to run it for you."
].join(" ");
}
export async function postPermissionDeniedComment(
octokit: Octokit,
params: {
owner: string;
repo: string;
pullNumber: number;
sourceCommentId: number;
commenterLogin: string;
command: RepositoryCommand;
}
): Promise<void> {
const marker = `<!-- ghbot-permission-denied:v1 comment=${params.sourceCommentId} command=${encodeURIComponent(params.command)} -->`;
const comments = await octokit.paginate(octokit.rest.issues.listComments, {
owner: params.owner,
repo: params.repo,
issue_number: params.pullNumber,
per_page: 100
});
if (comments.some((comment) => comment.body?.includes(marker))) {
return;
}
await withRetry("github.issues.createComment.permissionDenied", async () => {
return octokit.rest.issues.createComment({
owner: params.owner,
repo: params.repo,
issue_number: params.pullNumber,
body: `${marker}\n${formatPermissionDeniedMessage(params.commenterLogin, params.command)}`
});
});
}
+197 -15
View File
@@ -1,6 +1,7 @@
import type { Octokit } from "@octokit/rest";
import { config } from "../config.js";
import { requiredChecksAreGreen } from "../github/checks.js";
import { postPermissionDeniedComment } from "../github/commandFeedback.js";
import { collectValidNewLines, toDiffPosition } from "../github/diff.js";
import { logger } from "../logger.js";
import { withRetry } from "../retry.js";
@@ -28,6 +29,7 @@ const reviewer = new GooseReviewer();
const CHECK_RUN_NAME = "ghbot review";
export const RECHECK_COMMENT_COMMAND = "/recheck";
export const CONFLICT_COMMENT_COMMAND = "/conflict";
const REVIEW_PROGRESS_MARKER_PREFIX = "<!-- ghbot-review-progress:v1";
export async function processPullRequest(
octokit: Octokit,
@@ -318,6 +320,86 @@ export async function shouldReviewPullRequest(
return isReviewBranchEnabled(pullRequest.base.ref);
}
export async function beginCommitReviewProgress(
octokit: Octokit,
params: { owner: string; repo: string; pullNumber: number }
): Promise<{ commentId: number; headSha: string } | undefined> {
const { data: pullRequest } = await octokit.rest.pulls.get({
owner: params.owner,
repo: params.repo,
pull_number: params.pullNumber
});
if (pullRequest.state !== "open" || pullRequest.draft) {
return undefined;
}
const marker = reviewProgressMarker(pullRequest.head.sha);
const body = [
marker,
`New commit \`${shortSha(pullRequest.head.sha)}\` detected. Automated review has started for this commit.`
].join("\n");
const existing = await findIssueCommentByMarker(octokit, params, marker);
const response = existing
? await withRetry("github.issues.updateComment.reviewProgressStarted", async () => {
return octokit.rest.issues.updateComment({
owner: params.owner,
repo: params.repo,
comment_id: existing.id,
body
});
})
: await withRetry("github.issues.createComment.reviewProgressStarted", async () => {
return octokit.rest.issues.createComment({
owner: params.owner,
repo: params.repo,
issue_number: params.pullNumber,
body
});
});
return { commentId: response.data.id, headSha: pullRequest.head.sha };
}
export async function finishCommitReviewProgress(
octokit: Octokit,
params: {
owner: string;
repo: string;
pullNumber: number;
commentId: number;
headSha: string;
failed?: boolean;
}
): Promise<void> {
const marker = reviewProgressMarker(params.headSha);
let message: string;
if (params.failed) {
message = `Automated review could not complete for commit \`${shortSha(params.headSha)}\`. A maintainer can inspect the failed Actions run or comment \`/recheck\` after the problem is corrected.`;
} else {
const reviews = await octokit.paginate(octokit.rest.pulls.listReviews, {
owner: params.owner,
repo: params.repo,
pull_number: params.pullNumber,
per_page: 100
});
const published = reviews.some(
(review) => review.commit_id === params.headSha && Boolean(parseReviewStateMarker(review.body))
);
message = published
? `Automated review completed for commit \`${shortSha(params.headSha)}\`. The latest review result and \`${CHECK_RUN_NAME}\` check now reflect this commit.`
: `The review run ended without publishing a result for commit \`${shortSha(params.headSha)}\`, usually because the PR changed again while it was running. The newest commit will be reviewed separately.`;
}
await withRetry("github.issues.updateComment.reviewProgressFinished", async () => {
return octokit.rest.issues.updateComment({
owner: params.owner,
repo: params.repo,
comment_id: params.commentId,
body: [marker, message].join("\n")
});
});
}
export async function processPullRequestReviewApproval(
octokit: Octokit,
params: {
@@ -435,6 +517,7 @@ export async function processRecheckComment(
owner: string;
repo: string;
pullNumber: number;
commentId: number;
commenterLogin: string;
commentBody: string;
gitToken?: string;
@@ -483,6 +566,14 @@ export async function processRecheckComment(
},
"Ignoring recheck comment because commenter does not have write permission."
);
await postPermissionDeniedComment(octokit, {
owner: params.owner,
repo: params.repo,
pullNumber: params.pullNumber,
sourceCommentId: params.commentId,
commenterLogin: params.commenterLogin,
command: "/recheck"
});
return;
}
@@ -524,6 +615,7 @@ export async function processConflictComment(
owner: string;
repo: string;
pullNumber: number;
commentId: number;
commenterLogin: string;
commentBody: string;
gitToken?: string;
@@ -548,6 +640,14 @@ export async function processConflictComment(
{ ...params, commentBody: undefined, permission: permission.permission },
"Ignoring conflict command because commenter does not have write permission."
);
await postPermissionDeniedComment(octokit, {
owner: params.owner,
repo: params.repo,
pullNumber: params.pullNumber,
sourceCommentId: params.commentId,
commenterLogin: params.commenterLogin,
command: "/conflict"
});
return;
}
@@ -810,6 +910,28 @@ function isNotFoundError(error: unknown): boolean {
return typeof error === "object" && error !== null && "status" in error && error.status === 404;
}
function reviewProgressMarker(headSha: string): string {
return `${REVIEW_PROGRESS_MARKER_PREFIX} head=${headSha} -->`;
}
function shortSha(headSha: string): string {
return headSha.slice(0, 12);
}
async function findIssueCommentByMarker(
octokit: Octokit,
params: { owner: string; repo: string; pullNumber: number },
marker: string
) {
const comments = await octokit.paginate(octokit.rest.issues.listComments, {
owner: params.owner,
repo: params.repo,
issue_number: params.pullNumber,
per_page: 100
});
return comments.find((comment) => comment.body?.includes(marker));
}
async function getLatestBotReviewOutcomeForHead(
octokit: Octokit,
params: {
@@ -879,13 +1001,6 @@ async function submitReview(
mode: ReviewMode;
}
): Promise<void> {
await dismissExistingBotReviews(octokit, {
owner: params.owner,
repo: params.repo,
pullNumber: params.pullNumber,
commitId: params.commitId
});
const validLines = collectValidNewLines(params.files);
const filesByPath = new Map(params.files.map((file) => [file.filename, file]));
const unpostedFindings: CategorizedFinding[] = [];
@@ -921,8 +1036,9 @@ async function submitReview(
const event = disposition.event;
const body = formatReviewBody(params.decision, unpostedFindings, params.mode, disposition);
let currentReviewId: number;
try {
await withRetry("github.pulls.createReview", async () => {
const response = await withRetry("github.pulls.createReview", async () => {
return octokit.rest.pulls.createReview({
owner: params.owner,
repo: params.repo,
@@ -933,6 +1049,7 @@ async function submitReview(
comments
});
});
currentReviewId = response.data.id;
} catch (error) {
if (!shouldFallbackToCommentReview(error, event)) {
throw error;
@@ -949,7 +1066,7 @@ async function submitReview(
"Falling back to COMMENT review because the current token is not allowed to approve pull requests."
);
await withRetry("github.pulls.createReview.commentFallback", async () => {
const response = await withRetry("github.pulls.createReview.commentFallback", async () => {
return octokit.rest.pulls.createReview({
owner: params.owner,
repo: params.repo,
@@ -960,7 +1077,16 @@ async function submitReview(
comments
});
});
currentReviewId = response.data.id;
}
await supersedePreviousBotReviews(octokit, {
owner: params.owner,
repo: params.repo,
pullNumber: params.pullNumber,
currentReviewId,
currentCommitId: params.commitId
});
}
async function upsertReviewCheckRun(
@@ -1103,13 +1229,14 @@ async function waitForMergeable(
return data;
}
async function dismissExistingBotReviews(
export async function supersedePreviousBotReviews(
octokit: Octokit,
params: {
owner: string;
repo: string;
pullNumber: number;
commitId: string;
currentReviewId: number;
currentCommitId: string;
}
): Promise<void> {
const reviews = await octokit.paginate(octokit.rest.pulls.listReviews, {
@@ -1124,18 +1251,54 @@ async function dismissExistingBotReviews(
continue;
}
if (!review.id || review.state === "DISMISSED") {
if (!review.id || review.id === params.currentReviewId) {
continue;
}
const oldCommitId = review.commit_id ?? "unknown";
try {
await octokit.rest.pulls.dismissReview({
const comments = await octokit.paginate(octokit.rest.pulls.listCommentsForReview, {
owner: params.owner,
repo: params.repo,
pull_number: params.pullNumber,
review_id: review.id,
message: "Superseded by a newer automated review run."
per_page: 100
});
for (const comment of comments) {
await withRetry("github.pulls.deleteReviewComment.superseded", async () => {
return octokit.rest.pulls.deleteReviewComment({
owner: params.owner,
repo: params.repo,
comment_id: comment.id
});
});
}
await withRetry("github.pulls.updateReview.superseded", async () => {
return octokit.rest.pulls.updateReview({
owner: params.owner,
repo: params.repo,
pull_number: params.pullNumber,
review_id: review.id,
body: formatSupersededReviewBody({
originalMarker: extractReviewStateMarker(review.body),
oldCommitId,
currentCommitId: params.currentCommitId
})
});
});
if (review.state !== "DISMISSED") {
await withRetry("github.pulls.dismissReview.superseded", async () => {
return octokit.rest.pulls.dismissReview({
owner: params.owner,
repo: params.repo,
pull_number: params.pullNumber,
review_id: review.id,
message: `Superseded by the automated review for commit ${shortSha(params.currentCommitId)}.`
});
});
}
} catch (error) {
logger.warn(
{
@@ -1145,12 +1308,31 @@ async function dismissExistingBotReviews(
pullNumber: params.pullNumber,
reviewId: review.id
},
"Failed to dismiss existing bot review."
"Failed to fully remove a superseded bot review."
);
}
}
}
export function formatSupersededReviewBody(params: {
originalMarker: string;
oldCommitId: string;
currentCommitId: string;
}): string {
return [
params.originalMarker,
"## Superseded automated review",
"",
`The review for commit \`${shortSha(params.oldCommitId)}\` has been replaced by the automated review for commit \`${shortSha(params.currentCommitId)}\`.`,
"",
"Its previous inline `review` and `change` comments were removed. Refer to the latest commit review for the current result."
].join("\n");
}
function extractReviewStateMarker(body: string | null | undefined): string {
return body?.match(/<!-- ghbot-review:v1[^>]*-->/)?.[0] ?? "<!-- ghbot-review:v1 superseded=true -->";
}
function shouldFallbackToCommentReview(error: unknown, event: "APPROVE" | "COMMENT" | "REQUEST_CHANGES"): boolean {
if (event !== "APPROVE") {
return false;
+48
View File
@@ -0,0 +1,48 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { Octokit } from "@octokit/rest";
import {
formatPermissionDeniedMessage,
postPermissionDeniedComment
} from "../src/github/commandFeedback.js";
test("permission denied feedback is friendly and actionable", () => {
const body = formatPermissionDeniedMessage("contributor", "/recheck");
assert.match(body, /^Hi! @contributor, we're sorry/);
assert.match(body, /permission to run `\/recheck`/);
assert.match(body, /write.*maintain.*admin/i);
assert.match(body, /ask a repository maintainer/i);
});
test("permission denied feedback is deduplicated by source comment", async () => {
const created: string[] = [];
const comments: Array<{ body: string }> = [];
const octokit = {
paginate: async () => comments,
rest: {
issues: {
listComments: async () => ({ data: comments }),
createComment: async ({ body }: { body: string }) => {
created.push(body);
comments.push({ body });
return { data: { id: 1, body } };
}
}
}
} as unknown as Octokit;
const params = {
owner: "forumlify",
repo: "public",
pullNumber: 17,
sourceCommentId: 123,
commenterLogin: "contributor",
command: "/conflict" as const
};
await postPermissionDeniedComment(octokit, params);
await postPermissionDeniedComment(octokit, params);
assert.equal(created.length, 1);
assert.match(created[0]!, /comment=123/);
assert.match(created[0]!, /permission to run `\/conflict`/);
});
+126
View File
@@ -0,0 +1,126 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { Octokit } from "@octokit/rest";
import {
beginCommitReviewProgress,
finishCommitReviewProgress
} from "../src/review/processor.js";
const headSha = "1234567890abcdef1234567890abcdef12345678";
const reviewMarker = "<!-- ghbot-review:v1 mode=normal outcome=pass requires-admin=false review=0 change=0 -->";
test("new commit progress is created once and reused for the same head", async () => {
const comments: Array<{ id: number; body: string }> = [];
const created: string[] = [];
const updated: Array<{ comment_id: number; body: string }> = [];
const pullsGet = async () => ({
data: {
state: "open",
draft: false,
head: { sha: headSha }
}
});
const issuesListComments = async () => ({ data: comments });
const octokit = {
paginate: async (method: unknown) => {
assert.equal(method, issuesListComments);
return comments;
},
rest: {
pulls: { get: pullsGet },
issues: {
listComments: issuesListComments,
createComment: async ({ body }: { body: string }) => {
created.push(body);
const comment = { id: 77, body };
comments.push(comment);
return { data: comment };
},
updateComment: async ({ comment_id, body }: { comment_id: number; body: string }) => {
updated.push({ comment_id, body });
const comment = comments.find((item) => item.id === comment_id);
if (comment) {
comment.body = body;
}
return { data: { id: comment_id, body } };
}
}
}
} as unknown as Octokit;
const params = { owner: "forumlify", repo: "public", pullNumber: 17 };
const first = await beginCommitReviewProgress(octokit, params);
const second = await beginCommitReviewProgress(octokit, params);
assert.deepEqual(first, { commentId: 77, headSha });
assert.deepEqual(second, first);
assert.equal(created.length, 1);
assert.equal(updated.length, 1);
assert.match(created[0]!, /ghbot-review-progress:v1 head=1234567890abcdef/);
assert.match(created[0]!, /New commit `1234567890ab` detected/);
});
test("completed progress updates the same comment after a review is published for the head", async () => {
const updated: Array<{ comment_id: number; body: string }> = [];
const reviews = [
{ commit_id: "f".repeat(40), body: reviewMarker },
{ commit_id: headSha, body: reviewMarker }
];
const pullsListReviews = async () => ({ data: reviews });
const octokit = {
paginate: async (method: unknown) => {
assert.equal(method, pullsListReviews);
return reviews;
},
rest: {
pulls: { listReviews: pullsListReviews },
issues: {
updateComment: async ({ comment_id, body }: { comment_id: number; body: string }) => {
updated.push({ comment_id, body });
return { data: { id: comment_id, body } };
}
}
}
} as unknown as Octokit;
await finishCommitReviewProgress(octokit, {
owner: "forumlify",
repo: "public",
pullNumber: 17,
commentId: 77,
headSha
});
assert.equal(updated.length, 1);
assert.equal(updated[0]!.comment_id, 77);
assert.match(updated[0]!.body, /Automated review completed/);
assert.match(updated[0]!.body, /`ghbot review` check now reflect this commit/);
});
test("completed progress reports a stale run when the reviewed head was not published", async () => {
const updated: string[] = [];
const pullsListReviews = async () => ({ data: [] });
const octokit = {
paginate: async () => [],
rest: {
pulls: { listReviews: pullsListReviews },
issues: {
updateComment: async ({ body }: { body: string }) => {
updated.push(body);
return { data: { id: 77, body } };
}
}
}
} as unknown as Octokit;
await finishCommitReviewProgress(octokit, {
owner: "forumlify",
repo: "public",
pullNumber: 17,
commentId: 77,
headSha
});
assert.match(updated[0]!, /ended without publishing a result/);
assert.match(updated[0]!, /newest commit will be reviewed separately/);
});
+86
View File
@@ -0,0 +1,86 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { Octokit } from "@octokit/rest";
import {
formatSupersededReviewBody,
supersedePreviousBotReviews
} from "../src/review/processor.js";
const marker = "<!-- ghbot-review:v1 mode=normal outcome=block requires-admin=false review=1 change=1 -->";
test("superseded review body removes old findings and points to the current commit", () => {
const body = formatSupersededReviewBody({
originalMarker: marker,
oldCommitId: "a".repeat(40),
currentCommitId: "b".repeat(40)
});
assert.match(body, /Superseded automated review/);
assert.match(body, /`aaaaaaaaaaaa`/);
assert.match(body, /`bbbbbbbbbbbb`/);
assert.doesNotMatch(body, /Required changes:/);
assert.match(body, /inline `review` and `change` comments were removed/);
});
test("old bot reviews are cleaned only while the current review is preserved", async () => {
const deletedComments: number[] = [];
const updatedReviews: Array<{ review_id: number; body: string }> = [];
const dismissedReviews: number[] = [];
const reviews = [
{ id: 10, user: { type: "Bot" }, body: marker, state: "CHANGES_REQUESTED", commit_id: "a".repeat(40) },
{ id: 20, user: { type: "Bot" }, body: marker, state: "APPROVED", commit_id: "b".repeat(40) },
{ id: 30, user: { type: "User" }, body: marker, state: "COMMENTED", commit_id: "c".repeat(40) },
{ id: 40, user: { type: "Bot" }, body: marker, state: "DISMISSED", commit_id: "d".repeat(40) },
{ id: 50, user: { type: "Bot" }, body: "Unrelated automation", state: "COMMENTED", commit_id: "e".repeat(40) },
{ id: 60, user: { type: "Bot" }, body: marker, state: "CHANGES_REQUESTED", commit_id: "b".repeat(40) }
];
const octokit = {
paginate: async (method: unknown, params: { review_id?: number }) => {
if (method === pulls.listReviews) {
return reviews;
}
if (params.review_id === 10) {
return [{ id: 101 }, { id: 102 }];
}
if (params.review_id === 40) {
return [{ id: 401 }];
}
if (params.review_id === 60) {
return [{ id: 601 }];
}
return [];
},
rest: {
pulls: {
listReviews: async () => ({ data: reviews }),
listCommentsForReview: async () => ({ data: [] }),
deleteReviewComment: async ({ comment_id }: { comment_id: number }) => {
deletedComments.push(comment_id);
return { data: undefined };
},
updateReview: async ({ review_id, body }: { review_id: number; body: string }) => {
updatedReviews.push({ review_id, body });
return { data: {} };
},
dismissReview: async ({ review_id }: { review_id: number }) => {
dismissedReviews.push(review_id);
return { data: {} };
}
}
}
} as unknown as Octokit;
const pulls = (octokit.rest as unknown as { pulls: { listReviews: unknown } }).pulls;
await supersedePreviousBotReviews(octokit, {
owner: "forumlify",
repo: "public",
pullNumber: 17,
currentReviewId: 20,
currentCommitId: "b".repeat(40)
});
assert.deepEqual(deletedComments, [101, 102, 401, 601]);
assert.deepEqual(updatedReviews.map((item) => item.review_id), [10, 40, 60]);
assert.match(updatedReviews[0]!.body, /bbbbbbbbbbbb/);
assert.deepEqual(dismissedReviews, [10, 60]);
assert.ok(pulls.listReviews);
});
+11
View File
@@ -0,0 +1,11 @@
import assert from "node:assert/strict";
import fs from "node:fs/promises";
import test from "node:test";
test("pull_request_target checks out a PR worktree only for same-repository heads", async () => {
const workflow = await fs.readFile(".github/workflows/review-reusable.yml", "utf8");
const caller = await fs.readFile(".github/workflows/review.yml", "utf8");
assert.match(workflow, /pull_head_repository == format\('\{0\}\/\{1\}'/);
assert.doesNotMatch(workflow, /allow-unsafe-pr-checkout:\s*true/);
assert.match(caller, /pull_head_repository:\s*\$\{\{ github\.event\.pull_request\.head\.repo\.full_name \|\| '' \}\}/);
});