Handle outside approvals and scheduled fallback

This commit is contained in:
lezi-fun committed 2026-05-17 10:38:27 +08:00
1 parent 6d14749626
commit 22ee162cbf
5 files changed
+212 -28

No files matched your search

+39
View File
@@ -74,6 +74,10 @@ on:
required: false required: false
type: string type: string
default: info default: info
run_schedule_recheck:
required: false
type: string
default: "false"
secrets: secrets:
CODEX_API_KEY: CODEX_API_KEY:
required: true required: true
@@ -88,6 +92,7 @@ permissions:
jobs: jobs:
review: review:
name: bot-review name: bot-review
if: ${{ inputs.run_schedule_recheck != 'true' }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
@@ -124,3 +129,37 @@ jobs:
GHBOT_REVIEWER_LOGIN: ${{ inputs.reviewer_login }} GHBOT_REVIEWER_LOGIN: ${{ inputs.reviewer_login }}
GHBOT_REVIEW_STATE: ${{ inputs.review_state }} GHBOT_REVIEW_STATE: ${{ inputs.review_state }}
GHBOT_REVIEW_COMMIT_ID: ${{ inputs.review_commit_id }} GHBOT_REVIEW_COMMIT_ID: ${{ inputs.review_commit_id }}
schedule-recheck:
name: bot-schedule-recheck
if: ${{ inputs.run_schedule_recheck == 'true' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
cache: npm
- name: Install Codex CLI
run: npm install -g @openai/codex
- run: npm ci
- run: npm run build
- name: Remove stale review result
run: rm -f .review-result.json
- run: node dist/src/actions/runReview.js
env:
GITHUB_TOKEN: ${{ github.token }}
CODEX_API_KEY: ${{ secrets.CODEX_API_KEY }}
CODEX_BASE_URL: ${{ inputs.codex_base_url }}
CODEX_MODEL: ${{ inputs.codex_model }}
CODEX_REASONING_EFFORT: ${{ inputs.codex_reasoning_effort }}
BOT_NAME: ${{ inputs.bot_name }}
AUTO_MERGE: ${{ inputs.auto_merge }}
MERGE_METHOD: ${{ inputs.merge_method }}
REQUIRE_CHECKS: ${{ inputs.require_checks }}
MAX_PATCH_CHARS: ${{ inputs.max_patch_chars }}
LOG_LEVEL: ${{ inputs.log_level }}
GHBOT_EVENT_NAME: schedule
GHBOT_EVENT_ACTION: schedule
GHBOT_REPOSITORY_OWNER: ${{ inputs.repository_owner }}
GHBOT_REPOSITORY_NAME: ${{ inputs.repository_name }}
GHBOT_PULL_NUMBER: "1"
+23
View File
@@ -13,6 +13,8 @@ on:
pull_request_review: pull_request_review:
types: types:
- submitted - submitted
schedule:
- cron: "17 * * * *"
permissions: permissions:
contents: write contents: write
@@ -50,3 +52,24 @@ jobs:
require_checks: ${{ vars.REQUIRE_CHECKS || 'true' }} require_checks: ${{ vars.REQUIRE_CHECKS || 'true' }}
max_patch_chars: ${{ vars.MAX_PATCH_CHARS || '120000' }} max_patch_chars: ${{ vars.MAX_PATCH_CHARS || '120000' }}
log_level: info log_level: info
review-schedule-recheck:
if: github.event_name == 'schedule'
uses: ./.github/workflows/review-reusable.yml
secrets:
CODEX_API_KEY: ${{ secrets.CODEX_API_KEY }}
with:
event_name: schedule
event_action: schedule
repository_owner: ${{ github.repository_owner }}
repository_name: ${{ github.event.repository.name }}
pull_number: "1"
bot_name: github-actions[bot]
codex_base_url: ${{ vars.CODEX_BASE_URL || 'https://api.openai.com/v1' }}
codex_model: ${{ vars.CODEX_MODEL || 'gpt-5.4' }}
codex_reasoning_effort: ${{ vars.CODEX_REASONING_EFFORT || 'high' }}
auto_merge: ${{ vars.AUTO_MERGE || 'false' }}
merge_method: ${{ vars.MERGE_METHOD || 'squash' }}
require_checks: ${{ vars.REQUIRE_CHECKS || 'true' }}
max_patch_chars: ${{ vars.MAX_PATCH_CHARS || '120000' }}
log_level: info
run_schedule_recheck: "true"
+2
View File
@@ -13,6 +13,7 @@ GitHub Actions bot that reviews pull requests by calling Codex CLI, leaves inlin
- `suggestion` findings are included as non-blocking suggestions. - `suggestion` findings are included as non-blocking suggestions.
- Supports a lenient pass when a repository administrator comments `/lenient-check`. - Supports a lenient pass when a repository administrator comments `/lenient-check`.
- If no repository administrator has commented or reviewed within the last 24 hours, the lenient trigger automatically broadens to users with `write`, `maintain`, or `admin` permission. - If no repository administrator has commented or reviewed within the last 24 hours, the lenient trigger automatically broadens to users with `write`, `maintain`, or `admin` permission.
- A scheduled recheck runs hourly so the 24-hour fallback can take effect even if no new PR event arrives after the window expires.
- In lenient mode, only blocks dangerous changes, runtime-impacting issues, errors, crashes, broken builds, data-loss risks, and security risks. - In lenient mode, only blocks dangerous changes, runtime-impacting issues, errors, crashes, broken builds, data-loss risks, and security risks.
- A PR that passes lenient mode is not auto-merged until an eligible reviewer approves the current head commit. - A PR that passes lenient mode is not auto-merged until an eligible reviewer approves the current head commit.
- Eligible reviewers for lenient merge approval are: - Eligible reviewers for lenient merge approval are:
@@ -141,6 +142,7 @@ Approval eligibility follows the same rule as lenient triggering:
- if a repository administrator has commented or reviewed on that PR within the last 24 hours, only an administrator approval can unlock merge - if a repository administrator has commented or reviewed on that PR within the last 24 hours, only an administrator approval can unlock merge
- otherwise any user with `write`, `maintain`, or `admin` permission can unlock merge - otherwise any user with `write`, `maintain`, or `admin` permission can unlock merge
- an hourly scheduled recheck reevaluates this fallback window for already-approved PRs
## Local development ## Local development
+23 -3
View File
@@ -6,6 +6,7 @@ import { withRetry } from "../retry.js";
import { import {
processLenientCheckComment, processLenientCheckComment,
processPullRequest, processPullRequest,
processScheduledLenientMerges,
processPullRequestReviewApproval processPullRequestReviewApproval
} from "../review/processor.js"; } from "../review/processor.js";
@@ -58,6 +59,10 @@ type PullRequestReviewPayload = {
repository: GitHubRepository; repository: GitHubRepository;
}; };
type ScheduledPayload = {
repository: GitHubRepository;
};
async function main(): Promise<void> { async function main(): Promise<void> {
const workflowCallEventName = process.env.GHBOT_EVENT_NAME; const workflowCallEventName = process.env.GHBOT_EVENT_NAME;
const payload = workflowCallEventName const payload = workflowCallEventName
@@ -133,19 +138,28 @@ async function main(): Promise<void> {
return; return;
} }
if (eventName === "schedule") {
const scheduledPayload = payload as ScheduledPayload;
await processScheduledLenientMerges(octokit, {
owner: scheduledPayload.repository.owner.login,
repo: scheduledPayload.repository.name
});
return;
}
logger.warn({ eventName }, "Unhandled GitHub Actions event."); logger.warn({ eventName }, "Unhandled GitHub Actions event.");
} }
function readPayloadFromGitHubEventPath(): PullRequestPayload | IssueCommentPayload | PullRequestReviewPayload { function readPayloadFromGitHubEventPath(): PullRequestPayload | IssueCommentPayload | PullRequestReviewPayload | ScheduledPayload {
const eventPath = process.env.GITHUB_EVENT_PATH; const eventPath = process.env.GITHUB_EVENT_PATH;
if (!eventPath) { if (!eventPath) {
throw new Error("GITHUB_EVENT_PATH is required when workflow_call inputs are not provided."); throw new Error("GITHUB_EVENT_PATH is required when workflow_call inputs are not provided.");
} }
return JSON.parse(fs.readFileSync(eventPath, "utf8")) as PullRequestPayload | IssueCommentPayload | PullRequestReviewPayload; return JSON.parse(fs.readFileSync(eventPath, "utf8")) as PullRequestPayload | IssueCommentPayload | PullRequestReviewPayload | ScheduledPayload;
} }
function buildPayloadFromWorkflowCallEnv(eventName: string): PullRequestPayload | IssueCommentPayload | PullRequestReviewPayload { function buildPayloadFromWorkflowCallEnv(eventName: string): PullRequestPayload | IssueCommentPayload | PullRequestReviewPayload | ScheduledPayload {
const action = process.env.GHBOT_EVENT_ACTION; const action = process.env.GHBOT_EVENT_ACTION;
const owner = process.env.GHBOT_REPOSITORY_OWNER; const owner = process.env.GHBOT_REPOSITORY_OWNER;
const repo = process.env.GHBOT_REPOSITORY_NAME; const repo = process.env.GHBOT_REPOSITORY_NAME;
@@ -210,6 +224,12 @@ function buildPayloadFromWorkflowCallEnv(eventName: string): PullRequestPayload
}; };
} }
if (eventName === "schedule") {
return {
repository
};
}
throw new Error(`Unsupported GHBOT_EVENT_NAME: ${eventName}`); throw new Error(`Unsupported GHBOT_EVENT_NAME: ${eventName}`);
} }
+125 -25
View File
@@ -83,10 +83,76 @@ export async function processPullRequest(octokit: Octokit, ref: PullRequestRef,
pullNumber, pullNumber,
title: pullRequest.title, title: pullRequest.title,
headSha: pullRequest.head.sha, headSha: pullRequest.head.sha,
mode mode,
emitStatusComments: true
}); });
} }
export async function processScheduledLenientMerges(
octokit: Octokit,
params: {
owner: string;
repo: string;
}
): Promise<void> {
if (!config.autoMerge) {
logger.info({ owner: params.owner, repo: params.repo }, "Skipping scheduled lenient recheck because AUTO_MERGE is disabled.");
return;
}
const pullRequests = await octokit.paginate(octokit.rest.pulls.list, {
owner: params.owner,
repo: params.repo,
state: "open",
per_page: 100
});
for (const pullRequest of pullRequests) {
if (pullRequest.draft) {
continue;
}
const hasSuccessfulLenientReview = await hasSuccessfulLenientReviewForHead(octokit, {
owner: params.owner,
repo: params.repo,
pullNumber: pullRequest.number,
headSha: pullRequest.head.sha
});
if (!hasSuccessfulLenientReview) {
continue;
}
const adminRecentlyResponded = await hasRecentAdminResponse(octokit, {
owner: params.owner,
repo: params.repo,
pullNumber: pullRequest.number
});
const approvedByEligibleReviewer = await hasCurrentHeadApprovalFrom(octokit, {
owner: params.owner,
repo: params.repo,
pullNumber: pullRequest.number,
headSha: pullRequest.head.sha,
requireAdmin: adminRecentlyResponded
});
if (!approvedByEligibleReviewer) {
continue;
}
await maybeMergePullRequest(octokit, {
owner: params.owner,
repo: params.repo,
pullNumber: pullRequest.number,
title: pullRequest.title,
headSha: pullRequest.head.sha,
mode: "lenient",
emitStatusComments: false
});
}
}
export async function processPullRequestReviewApproval( export async function processPullRequestReviewApproval(
octokit: Octokit, octokit: Octokit,
params: { params: {
@@ -153,13 +219,19 @@ export async function processPullRequestReviewApproval(
owner: params.owner, owner: params.owner,
repo: params.repo, repo: params.repo,
username: params.reviewerLogin username: params.reviewerLogin
}).catch((error: unknown) => {
if (isNotFoundError(error)) {
return { data: { permission: null } };
}
throw error;
}); });
const allowedPermissions = adminRecentlyResponded const allowedPermissions = adminRecentlyResponded
? new Set(["admin"]) ? new Set(["admin"])
: new Set(["admin", "maintain", "write"]); : new Set(["admin", "maintain", "write"]);
if (!allowedPermissions.has(permission.permission)) { if (!permission.permission || !allowedPermissions.has(permission.permission)) {
logger.info( logger.info(
{ {
owner: params.owner, owner: params.owner,
@@ -180,7 +252,8 @@ export async function processPullRequestReviewApproval(
pullNumber: params.pullNumber, pullNumber: params.pullNumber,
title: pullRequest.title, title: pullRequest.title,
headSha: pullRequest.head.sha, headSha: pullRequest.head.sha,
mode: "lenient" mode: "lenient",
emitStatusComments: true
}); });
} }
@@ -208,13 +281,19 @@ export async function processLenientCheckComment(
owner: params.owner, owner: params.owner,
repo: params.repo, repo: params.repo,
username: params.commenterLogin username: params.commenterLogin
}).catch((error: unknown) => {
if (isNotFoundError(error)) {
return { data: { permission: null } };
}
throw error;
}); });
const allowedPermissions = adminRecentlyResponded const allowedPermissions = adminRecentlyResponded
? new Set(["admin"]) ? new Set(["admin"])
: new Set(["admin", "maintain", "write"]); : new Set(["admin", "maintain", "write"]);
if (!allowedPermissions.has(permission.permission)) { if (!permission.permission || !allowedPermissions.has(permission.permission)) {
logger.info( logger.info(
{ {
owner: params.owner, owner: params.owner,
@@ -270,6 +349,7 @@ async function maybeMergePullRequest(
title: string; title: string;
headSha: string; headSha: string;
mode: ReviewMode; mode: ReviewMode;
emitStatusComments: boolean;
} }
): Promise<void> { ): Promise<void> {
const { owner, repo, pullNumber } = params; const { owner, repo, pullNumber } = params;
@@ -299,14 +379,16 @@ async function maybeMergePullRequest(
}); });
if (!approvedByEligibleReviewer) { if (!approvedByEligibleReviewer) {
await withRetry("github.issues.createComment.awaitLenientApproval", async () => { if (params.emitStatusComments) {
return octokit.rest.issues.createComment({ await withRetry("github.issues.createComment.awaitLenientApproval", async () => {
owner, return octokit.rest.issues.createComment({
repo, owner,
issue_number: pullNumber, repo,
body: `Lenient check passed, but this PR will not be merged until ${approvalRequirement} approves the current head commit.` issue_number: pullNumber,
body: `Lenient check passed, but this PR will not be merged until ${approvalRequirement} approves the current head commit.`
});
}); });
}); }
logger.info({ owner, repo, pullNumber, adminRecentlyResponded }, "Waiting for eligible lenient approval before merging."); logger.info({ owner, repo, pullNumber, adminRecentlyResponded }, "Waiting for eligible lenient approval before merging.");
return; return;
} }
@@ -314,14 +396,16 @@ async function maybeMergePullRequest(
const mergeablePullRequest = await waitForMergeable(octokit, owner, repo, pullNumber); const mergeablePullRequest = await waitForMergeable(octokit, owner, repo, pullNumber);
if (mergeablePullRequest.mergeable !== true || mergeablePullRequest.mergeable_state === "dirty") { if (mergeablePullRequest.mergeable !== true || mergeablePullRequest.mergeable_state === "dirty") {
await withRetry("github.issues.createComment.notMergeable", async () => { if (params.emitStatusComments) {
return octokit.rest.issues.createComment({ await withRetry("github.issues.createComment.notMergeable", async () => {
owner, return octokit.rest.issues.createComment({
repo, owner,
issue_number: pullNumber, repo,
body: `Automated review approved this PR, but it was not merged because GitHub reports mergeable=${mergeablePullRequest.mergeable} and mergeable_state=${mergeablePullRequest.mergeable_state}.` issue_number: pullNumber,
body: `Automated review approved this PR, but it was not merged because GitHub reports mergeable=${mergeablePullRequest.mergeable} and mergeable_state=${mergeablePullRequest.mergeable_state}.`
});
}); });
}); }
return; return;
} }
@@ -332,14 +416,16 @@ async function maybeMergePullRequest(
ref: params.headSha ref: params.headSha
}); });
if (!checks.ok) { if (!checks.ok) {
await withRetry("github.issues.createComment.requiredChecks", async () => { if (params.emitStatusComments) {
return octokit.rest.issues.createComment({ await withRetry("github.issues.createComment.requiredChecks", async () => {
owner, return octokit.rest.issues.createComment({
repo, owner,
issue_number: pullNumber, repo,
body: `Automated review approved this PR, but it was not merged because required checks are not green. ${checks.reason ?? ""}`.trim() issue_number: pullNumber,
body: `Automated review approved this PR, but it was not merged because required checks are not green. ${checks.reason ?? ""}`.trim()
});
}); });
}); }
return; return;
} }
} }
@@ -383,8 +469,18 @@ async function hasCurrentHeadApprovalFrom(
owner: params.owner, owner: params.owner,
repo: params.repo, repo: params.repo,
username: login username: login
}).catch((error: unknown) => {
if (isNotFoundError(error)) {
return { data: { permission: null } };
}
throw error;
}); });
if (!permission.permission) {
continue;
}
if (params.requireAdmin) { if (params.requireAdmin) {
if (permission.permission === "admin") { if (permission.permission === "admin") {
return true; return true;
@@ -412,6 +508,10 @@ async function hasCurrentHeadApprovalFrom(
return false; return false;
} }
function isNotFoundError(error: unknown): boolean {
return typeof error === "object" && error !== null && "status" in error && error.status === 404;
}
async function hasSuccessfulLenientReviewForHead( async function hasSuccessfulLenientReviewForHead(
octokit: Octokit, octokit: Octokit,
params: { params: {