Merge pull request #18 from lezi-fun/codex/branch-cleanup

[feature] scheduled branch cleanup for merged and stale closed PRs
This commit is contained in:
lezi-fun authored and GitHub committed 2026-05-19 17:22:06 +08:00
commit ad5a0d5363
8 files changed
+247

No files matched your search

+1
View File
@@ -9,6 +9,7 @@ CODEX_API_KEY=sk-...
CODEX_BASE_URL=https://api.openai.com/v1 CODEX_BASE_URL=https://api.openai.com/v1
CODEX_MODEL=gpt-5.4 CODEX_MODEL=gpt-5.4
CODEX_REASONING_EFFORT=high CODEX_REASONING_EFFORT=high
BRANCH_CLEANUP_SKIP_BRANCHES=main,develop,release/*
# Optional controls # Optional controls
BOT_NAME=github-actions[bot] BOT_NAME=github-actions[bot]
+6
View File
@@ -70,6 +70,10 @@ on:
required: false required: false
type: string type: string
default: "120000" default: "120000"
branch_cleanup_skip_branches:
required: false
type: string
default: ""
log_level: log_level:
required: false required: false
type: string type: string
@@ -142,6 +146,7 @@ jobs:
MERGE_METHOD: ${{ inputs.merge_method }} MERGE_METHOD: ${{ inputs.merge_method }}
REQUIRE_CHECKS: ${{ inputs.require_checks }} REQUIRE_CHECKS: ${{ inputs.require_checks }}
MAX_PATCH_CHARS: ${{ inputs.max_patch_chars }} MAX_PATCH_CHARS: ${{ inputs.max_patch_chars }}
BRANCH_CLEANUP_SKIP_BRANCHES: ${{ inputs.branch_cleanup_skip_branches }}
LOG_LEVEL: ${{ inputs.log_level }} LOG_LEVEL: ${{ inputs.log_level }}
GHBOT_EVENT_NAME: ${{ inputs.event_name }} GHBOT_EVENT_NAME: ${{ inputs.event_name }}
GHBOT_EVENT_ACTION: ${{ inputs.event_action }} GHBOT_EVENT_ACTION: ${{ inputs.event_action }}
@@ -193,6 +198,7 @@ jobs:
MERGE_METHOD: ${{ inputs.merge_method }} MERGE_METHOD: ${{ inputs.merge_method }}
REQUIRE_CHECKS: ${{ inputs.require_checks }} REQUIRE_CHECKS: ${{ inputs.require_checks }}
MAX_PATCH_CHARS: ${{ inputs.max_patch_chars }} MAX_PATCH_CHARS: ${{ inputs.max_patch_chars }}
BRANCH_CLEANUP_SKIP_BRANCHES: ${{ inputs.branch_cleanup_skip_branches }}
LOG_LEVEL: ${{ inputs.log_level }} LOG_LEVEL: ${{ inputs.log_level }}
GHBOT_EVENT_NAME: schedule GHBOT_EVENT_NAME: schedule
GHBOT_EVENT_ACTION: schedule GHBOT_EVENT_ACTION: schedule
+2
View File
@@ -54,6 +54,7 @@ jobs:
merge_method: ${{ vars.MERGE_METHOD || 'squash' }} merge_method: ${{ vars.MERGE_METHOD || 'squash' }}
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' }}
branch_cleanup_skip_branches: ${{ vars.BRANCH_CLEANUP_SKIP_BRANCHES || '' }}
log_level: info log_level: info
review-schedule-recheck: review-schedule-recheck:
if: github.event_name == 'schedule' if: github.event_name == 'schedule'
@@ -77,5 +78,6 @@ jobs:
merge_method: ${{ vars.MERGE_METHOD || 'squash' }} merge_method: ${{ vars.MERGE_METHOD || 'squash' }}
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' }}
branch_cleanup_skip_branches: ${{ vars.BRANCH_CLEANUP_SKIP_BRANCHES || '' }}
log_level: info log_level: info
run_schedule_recheck: "true" run_schedule_recheck: "true"
+6
View File
@@ -14,6 +14,7 @@ GitHub Actions bot that reviews pull requests by calling Codex CLI, leaves inlin
- 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. - A scheduled recheck runs hourly so the 24-hour fallback can take effect even if no new PR event arrives after the window expires.
- The hourly scheduled run also deletes merged branches immediately and deletes branches for closed PRs after 3 days.
- 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:
@@ -48,6 +49,7 @@ Optional repository variables:
- `MERGE_METHOD`: `merge`, `squash`, or `rebase`, defaults to `squash` - `MERGE_METHOD`: `merge`, `squash`, or `rebase`, defaults to `squash`
- `REQUIRE_CHECKS`: defaults to `true` - `REQUIRE_CHECKS`: defaults to `true`
- `MAX_PATCH_CHARS`: defaults to `120000` - `MAX_PATCH_CHARS`: defaults to `120000`
- `BRANCH_CLEANUP_SKIP_BRANCHES`: comma-separated branch patterns to keep, for example `main,develop,release/*`
The workflow automatically receives `github.token` from GitHub Actions, so you do not need to create a repository secret named `GITHUB_TOKEN`. The workflow automatically receives `github.token` from GitHub Actions, so you do not need to create a repository secret named `GITHUB_TOKEN`.
If you do nothing else, ghbot uses that workflow token for comments, reviews, checks, and merges. If you do nothing else, ghbot uses that workflow token for comments, reviews, checks, and merges.
@@ -84,6 +86,7 @@ Notes:
- `GH_APP_INSTALLATION_ID` is optional. ghbot can resolve it automatically from the repository if the App is installed there. - `GH_APP_INSTALLATION_ID` is optional. ghbot can resolve it automatically from the repository if the App is installed there.
- Keep `CODEX_API_KEY` as a separate secret. The App only replaces GitHub write identity; it does not replace Codex authentication. - Keep `CODEX_API_KEY` as a separate secret. The App only replaces GitHub write identity; it does not replace Codex authentication.
- The repository still gets `github.token` automatically from GitHub Actions, and ghbot uses it as a fallback if App authentication is unavailable or broken. - The repository still gets `github.token` automatically from GitHub Actions, and ghbot uses it as a fallback if App authentication is unavailable or broken.
- The scheduled branch cleanup skips the repository default branch and any branches matched by `BRANCH_CLEANUP_SKIP_BRANCHES`. It also skips protected branches automatically.
## Reuse from another repository ## Reuse from another repository
@@ -144,6 +147,7 @@ jobs:
merge_method: ${{ vars.MERGE_METHOD || 'squash' }} merge_method: ${{ vars.MERGE_METHOD || 'squash' }}
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' }}
branch_cleanup_skip_branches: ${{ vars.BRANCH_CLEANUP_SKIP_BRANCHES || '' }}
log_level: info log_level: info
``` ```
@@ -152,6 +156,7 @@ The caller repository still needs to configure:
- `CODEX_API_KEY` as a secret - `CODEX_API_KEY` as a secret
- optional `GH_APP_ID`, `GH_APP_PRIVATE_KEY`, and `GH_APP_INSTALLATION_ID` secrets if you want GitHub App identity - optional `GH_APP_ID`, `GH_APP_PRIVATE_KEY`, and `GH_APP_INSTALLATION_ID` secrets if you want GitHub App identity
- `CODEX_BASE_URL`, `CODEX_MODEL`, `CODEX_REASONING_EFFORT`, `AUTO_MERGE`, `MERGE_METHOD`, `REQUIRE_CHECKS`, and `MAX_PATCH_CHARS` as repository variables as needed - `CODEX_BASE_URL`, `CODEX_MODEL`, `CODEX_REASONING_EFFORT`, `AUTO_MERGE`, `MERGE_METHOD`, `REQUIRE_CHECKS`, and `MAX_PATCH_CHARS` as repository variables as needed
- `BRANCH_CLEANUP_SKIP_BRANCHES` as a repository variable if you want to keep long-lived or shared branches out of scheduled cleanup
## Required workflow permissions ## Required workflow permissions
@@ -224,6 +229,7 @@ Important variables:
- `MERGE_METHOD`: defaults to `squash` - `MERGE_METHOD`: defaults to `squash`
- `REQUIRE_CHECKS`: defaults to `true` - `REQUIRE_CHECKS`: defaults to `true`
- `MAX_PATCH_CHARS`: defaults to `120000` - `MAX_PATCH_CHARS`: defaults to `120000`
- `BRANCH_CLEANUP_SKIP_BRANCHES`: optional comma-separated list of branch patterns skipped by scheduled cleanup
The generated Codex CLI config is intentionally close to a working local setup: The generated Codex CLI config is intentionally close to a working local setup:
+16
View File
@@ -7,6 +7,7 @@ import {
processLenientCheckComment, processLenientCheckComment,
processPullRequest, processPullRequest,
processScheduledLenientMerges, processScheduledLenientMerges,
processScheduledBranchCleanup,
processPullRequestReviewApproval processPullRequestReviewApproval
} from "../review/processor.js"; } from "../review/processor.js";
@@ -144,6 +145,21 @@ async function main(): Promise<void> {
if (eventName === "schedule") { if (eventName === "schedule") {
const scheduledPayload = payload as ScheduledPayload; const scheduledPayload = payload as ScheduledPayload;
try {
await processScheduledBranchCleanup(octokit, {
owner: scheduledPayload.repository.owner.login,
repo: scheduledPayload.repository.name
});
} catch (error) {
logger.warn(
{
error,
owner: scheduledPayload.repository.owner.login,
repo: scheduledPayload.repository.name
},
"Scheduled branch cleanup failed."
);
}
await processScheduledLenientMerges(octokit, { await processScheduledLenientMerges(octokit, {
owner: scheduledPayload.repository.owner.login, owner: scheduledPayload.repository.owner.login,
repo: scheduledPayload.repository.name repo: scheduledPayload.repository.name
+13
View File
@@ -5,6 +5,17 @@ const optionalString = z.preprocess((value) => {
return value === "" ? undefined : value; return value === "" ? undefined : value;
}, z.string().optional()); }, z.string().optional());
const csvList = z.preprocess((value) => {
if (typeof value !== "string") {
return [];
}
return value
.split(",")
.map((part) => part.trim())
.filter(Boolean);
}, z.array(z.string()));
const envBoolean = z.preprocess((value) => { const envBoolean = z.preprocess((value) => {
if (typeof value !== "string") { if (typeof value !== "string") {
return value; return value;
@@ -49,6 +60,7 @@ const configSchema = z.object({
mergeMethod: z.enum(["merge", "squash", "rebase"]).default("squash"), mergeMethod: z.enum(["merge", "squash", "rebase"]).default("squash"),
requireChecks: envBoolean.default(true), requireChecks: envBoolean.default(true),
maxPatchChars: z.coerce.number().int().positive().default(120_000), maxPatchChars: z.coerce.number().int().positive().default(120_000),
branchCleanupSkipBranches: csvList,
logLevel: z.string().min(1).default("info") logLevel: z.string().min(1).default("info")
}); });
@@ -67,5 +79,6 @@ export const config = configSchema.parse({
mergeMethod: process.env.MERGE_METHOD, mergeMethod: process.env.MERGE_METHOD,
requireChecks: process.env.REQUIRE_CHECKS, requireChecks: process.env.REQUIRE_CHECKS,
maxPatchChars: process.env.MAX_PATCH_CHARS, maxPatchChars: process.env.MAX_PATCH_CHARS,
branchCleanupSkipBranches: process.env.BRANCH_CLEANUP_SKIP_BRANCHES,
logLevel: process.env.LOG_LEVEL logLevel: process.env.LOG_LEVEL
}); });
+2
View File
@@ -339,6 +339,8 @@ function buildSystemPrompt(mode: ReviewMode): string {
"When you identify a bug, also check nearby code paths and obvious related regressions, but stay close to what the diff actually makes plausible.", "When you identify a bug, also check nearby code paths and obvious related regressions, but stay close to what the diff actually makes plausible.",
"Prefer false negatives over false positives. Do not report a finding unless you can explain a concrete failure mode, misuse case, or broken behavior from the diff itself.", "Prefer false negatives over false positives. Do not report a finding unless you can explain a concrete failure mode, misuse case, or broken behavior from the diff itself.",
"Do not report hypothetical, speculative, low-probability, style-only, architecture-preference, or vague maintainability concerns.", "Do not report hypothetical, speculative, low-probability, style-only, architecture-preference, or vague maintainability concerns.",
"When reviewing branch cleanup logic, judge the ordinary feature-branch case first. Do not block the change by bringing in extreme repository-specific examples such as shared long-lived branches or unusual protected branch workflows unless the diff is explicitly about those cases.",
"If a concern is really about a repository-specific exception, prefer a configurable skip list or existing branch protection instead of rejecting the feature for the common case.",
"Set shouldClosePullRequest=true only for clearly malicious code: backdoors, credential theft, token exfiltration, destructive commands, malware, hidden persistence, privilege escalation, supply-chain compromise, or intentionally abusive behavior.", "Set shouldClosePullRequest=true only for clearly malicious code: backdoors, credential theft, token exfiltration, destructive commands, malware, hidden persistence, privilege escalation, supply-chain compromise, or intentionally abusive behavior.",
"Do not set shouldClosePullRequest=true for ordinary bugs, crashes, failing tests, incomplete code, suspicious-but-unproven code, or low-quality changes.", "Do not set shouldClosePullRequest=true for ordinary bugs, crashes, failing tests, incomplete code, suspicious-but-unproven code, or low-quality changes.",
"When shouldClosePullRequest=true, explain the evidence in closeReason. Otherwise closeReason must be an empty string.", "When shouldClosePullRequest=true, explain the evidence in closeReason. Otherwise closeReason must be an empty string.",
+201
View File
@@ -13,6 +13,7 @@ const reviewer = new CodexCliReviewer();
const CHECK_RUN_NAME = "ghbot review"; const CHECK_RUN_NAME = "ghbot review";
export const LENIENT_COMMENT_COMMAND = "/lenient-check"; export const LENIENT_COMMENT_COMMAND = "/lenient-check";
const ADMIN_RESPONSE_WINDOW_MS = 24 * 60 * 60 * 1000; const ADMIN_RESPONSE_WINDOW_MS = 24 * 60 * 60 * 1000;
const CLOSED_BRANCH_DELETE_AFTER_MS = 3 * 24 * 60 * 60 * 1000;
export async function processPullRequest(octokit: Octokit, ref: PullRequestRef, mode: ReviewMode = "strict"): Promise<void> { export async function processPullRequest(octokit: Octokit, ref: PullRequestRef, mode: ReviewMode = "strict"): Promise<void> {
const { owner, repo, pullNumber } = ref; const { owner, repo, pullNumber } = ref;
@@ -153,6 +154,115 @@ export async function processScheduledLenientMerges(
} }
} }
export async function processScheduledBranchCleanup(
octokit: Octokit,
params: {
owner: string;
repo: string;
}
): Promise<void> {
const { data: repository } = await octokit.rest.repos.get({
owner: params.owner,
repo: params.repo
});
const pullRequests = await octokit.paginate(octokit.rest.pulls.list, {
owner: params.owner,
repo: params.repo,
state: "all",
per_page: 100
});
const now = Date.now();
for (const pullRequest of pullRequests) {
if (!pullRequest.head?.ref || pullRequest.head.repo?.full_name !== `${params.owner}/${params.repo}`) {
continue;
}
if (shouldSkipBranchCleanup(pullRequest.head.ref, repository.default_branch)) {
logger.info(
{
owner: params.owner,
repo: params.repo,
branch: pullRequest.head.ref,
pullNumber: pullRequest.number,
defaultBranch: repository.default_branch
},
"Skipping branch cleanup because the branch is configured or considered a common shared branch."
);
continue;
}
const hasOtherOpenPullRequestWithSameRef = pullRequests.some((candidate) => {
return (
candidate.number !== pullRequest.number &&
candidate.state === "open" &&
candidate.head?.ref === pullRequest.head.ref &&
candidate.head.repo?.full_name === `${params.owner}/${params.repo}`
);
});
if (hasOtherOpenPullRequestWithSameRef) {
logger.info(
{
owner: params.owner,
repo: params.repo,
branch: pullRequest.head.ref,
pullNumber: pullRequest.number
},
"Skipping branch cleanup because another open pull request still uses the same head ref."
);
continue;
}
const branchProtected = await isProtectedBranch(octokit, {
owner: params.owner,
repo: params.repo,
branch: pullRequest.head.ref
});
if (branchProtected) {
logger.info(
{
owner: params.owner,
repo: params.repo,
branch: pullRequest.head.ref,
pullNumber: pullRequest.number
},
"Skipping branch cleanup because the branch is protected."
);
continue;
}
if (pullRequest.merged_at) {
await deleteBranchIfPresent(octokit, {
owner: params.owner,
repo: params.repo,
branch: pullRequest.head.ref,
reason: `merged PR #${pullRequest.number}`
});
continue;
}
if (pullRequest.state !== "closed" || !pullRequest.closed_at) {
continue;
}
const closedAt = Date.parse(pullRequest.closed_at);
if (Number.isNaN(closedAt) || now - closedAt < CLOSED_BRANCH_DELETE_AFTER_MS) {
continue;
}
await deleteBranchIfPresent(octokit, {
owner: params.owner,
repo: params.repo,
branch: pullRequest.head.ref,
reason: `closed PR #${pullRequest.number} older than 3 days`
});
}
}
export async function processPullRequestReviewApproval( export async function processPullRequestReviewApproval(
octokit: Octokit, octokit: Octokit,
params: { params: {
@@ -818,6 +928,97 @@ async function dismissExistingBotReviews(
} }
} }
async function deleteBranchIfPresent(
octokit: Octokit,
params: {
owner: string;
repo: string;
branch: string;
reason: string;
}
): Promise<void> {
try {
await withRetry("github.git.deleteRef", async () => {
return octokit.rest.git.deleteRef({
owner: params.owner,
repo: params.repo,
ref: `heads/${params.branch}`
});
});
logger.info(
{
owner: params.owner,
repo: params.repo,
branch: params.branch,
reason: params.reason
},
"Deleted branch after PR cleanup."
);
} catch (error) {
if (isNotFoundError(error)) {
return;
}
logger.warn(
{
error,
owner: params.owner,
repo: params.repo,
branch: params.branch,
reason: params.reason
},
"Failed to delete branch during PR cleanup."
);
}
}
function shouldSkipBranchCleanup(branch: string, defaultBranch: string): boolean {
if (branch === defaultBranch) {
return true;
}
return config.branchCleanupSkipBranches.some((pattern) => branchMatchesPattern(branch, pattern));
}
function branchMatchesPattern(branch: string, pattern: string): boolean {
if (!pattern) {
return false;
}
const escaped = pattern
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
.replace(/\*/g, ".*")
.replace(/\?/g, ".");
return new RegExp(`^${escaped}$`).test(branch);
}
async function isProtectedBranch(
octokit: Octokit,
params: {
owner: string;
repo: string;
branch: string;
}
): Promise<boolean> {
try {
const { data } = await octokit.rest.repos.getBranch({
owner: params.owner,
repo: params.repo,
branch: params.branch
});
return Boolean(data.protected);
} catch (error) {
if (isNotFoundError(error)) {
return false;
}
throw error;
}
}
function shouldFallbackToCommentReview(error: unknown, event: "APPROVE" | "REQUEST_CHANGES"): boolean { function shouldFallbackToCommentReview(error: unknown, event: "APPROVE" | "REQUEST_CHANGES"): boolean {
if (event !== "APPROVE") { if (event !== "APPROVE") {
return false; return false;