From 8bf35b8f4204206ea6fd9590df84ee6e5af0491e Mon Sep 17 00:00:00 2001 From: lezi-fun <177434121+lezi-fun@users.noreply.github.com> Date: Sun, 17 May 2026 20:57:39 +0800 Subject: [PATCH 1/6] Add app comment test file --- app-comment-test.txt | 1 + 1 file changed, 1 insertion(+) create mode 100644 app-comment-test.txt diff --git a/app-comment-test.txt b/app-comment-test.txt new file mode 100644 index 0000000..62caf9c --- /dev/null +++ b/app-comment-test.txt @@ -0,0 +1 @@ +app comment test From 0d8ac00189b6ea6405308ecf942b6dcb49ca0753 Mon Sep 17 00:00:00 2001 From: lezi-fun Date: Sun, 17 May 2026 21:09:38 +0800 Subject: [PATCH 2/6] Add app comment test file (#17) Co-authored-by: lezi-fun <177434121+lezi-fun@users.noreply.github.com> --- app-comment-test.txt | 1 + 1 file changed, 1 insertion(+) create mode 100644 app-comment-test.txt diff --git a/app-comment-test.txt b/app-comment-test.txt new file mode 100644 index 0000000..62caf9c --- /dev/null +++ b/app-comment-test.txt @@ -0,0 +1 @@ +app comment test From 548f63f2514aa57f17658ee00eb6cbc7e4979fb5 Mon Sep 17 00:00:00 2001 From: lezi-fun Date: Sun, 17 May 2026 21:10:52 +0800 Subject: [PATCH 3/6] Delete app-comment-test.txt --- app-comment-test.txt | 1 - 1 file changed, 1 deletion(-) delete mode 100644 app-comment-test.txt diff --git a/app-comment-test.txt b/app-comment-test.txt deleted file mode 100644 index 62caf9c..0000000 --- a/app-comment-test.txt +++ /dev/null @@ -1 +0,0 @@ -app comment test From 8b0aeac3e111db307474f10a44f978ec37adbd34 Mon Sep 17 00:00:00 2001 From: lezi-fun <177434121+lezi-fun@users.noreply.github.com> Date: Tue, 19 May 2026 16:55:45 +0800 Subject: [PATCH 4/6] Add scheduled branch cleanup --- README.md | 1 + src/actions/runReview.ts | 16 +++++++ src/review/processor.ts | 95 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 112 insertions(+) diff --git a/README.md b/README.md index cb4441b..6c0137b 100644 --- a/README.md +++ b/README.md @@ -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`. - 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. +- 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. - 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: diff --git a/src/actions/runReview.ts b/src/actions/runReview.ts index 5eb2cc5..1d05e2f 100644 --- a/src/actions/runReview.ts +++ b/src/actions/runReview.ts @@ -7,6 +7,7 @@ import { processLenientCheckComment, processPullRequest, processScheduledLenientMerges, + processScheduledBranchCleanup, processPullRequestReviewApproval } from "../review/processor.js"; @@ -144,6 +145,21 @@ async function main(): Promise { if (eventName === "schedule") { 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, { owner: scheduledPayload.repository.owner.login, repo: scheduledPayload.repository.name diff --git a/src/review/processor.ts b/src/review/processor.ts index 84a4c4c..7e44956 100644 --- a/src/review/processor.ts +++ b/src/review/processor.ts @@ -13,6 +13,7 @@ const reviewer = new CodexCliReviewer(); const CHECK_RUN_NAME = "ghbot review"; export const LENIENT_COMMENT_COMMAND = "/lenient-check"; 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 { const { owner, repo, pullNumber } = ref; @@ -153,6 +154,55 @@ export async function processScheduledLenientMerges( } } +export async function processScheduledBranchCleanup( + octokit: Octokit, + params: { + owner: string; + repo: string; + } +): Promise { + 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 (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( octokit: Octokit, params: { @@ -818,6 +868,51 @@ async function dismissExistingBotReviews( } } +async function deleteBranchIfPresent( + octokit: Octokit, + params: { + owner: string; + repo: string; + branch: string; + reason: string; + } +): Promise { + 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 shouldFallbackToCommentReview(error: unknown, event: "APPROVE" | "REQUEST_CHANGES"): boolean { if (event !== "APPROVE") { return false; From af332a5d1cd05fbd5039e3db3fc53a33a6d5b5ed Mon Sep 17 00:00:00 2001 From: lezi-fun <177434121+lezi-fun@users.noreply.github.com> Date: Tue, 19 May 2026 17:03:54 +0800 Subject: [PATCH 5/6] Avoid deleting reused PR branches --- src/review/processor.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/review/processor.ts b/src/review/processor.ts index 7e44956..84c93b7 100644 --- a/src/review/processor.ts +++ b/src/review/processor.ts @@ -175,6 +175,28 @@ export async function processScheduledBranchCleanup( 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; + } + if (pullRequest.merged_at) { await deleteBranchIfPresent(octokit, { owner: params.owner, From c400b78989cc51626c4a4c840bac5a6d4fc4d3b7 Mon Sep 17 00:00:00 2001 From: lezi-fun <177434121+lezi-fun@users.noreply.github.com> Date: Tue, 19 May 2026 17:20:44 +0800 Subject: [PATCH 6/6] Skip configured cleanup branches --- .env.example | 1 + .github/workflows/review-reusable.yml | 6 ++ .github/workflows/review.yml | 2 + README.md | 5 ++ src/config.ts | 13 +++++ src/review/codexCliReviewer.ts | 2 + src/review/processor.ts | 84 +++++++++++++++++++++++++++ 7 files changed, 113 insertions(+) diff --git a/.env.example b/.env.example index c25405e..2ac9782 100644 --- a/.env.example +++ b/.env.example @@ -9,6 +9,7 @@ CODEX_API_KEY=sk-... CODEX_BASE_URL=https://api.openai.com/v1 CODEX_MODEL=gpt-5.4 CODEX_REASONING_EFFORT=high +BRANCH_CLEANUP_SKIP_BRANCHES=main,develop,release/* # Optional controls BOT_NAME=github-actions[bot] diff --git a/.github/workflows/review-reusable.yml b/.github/workflows/review-reusable.yml index 179f400..37ff927 100644 --- a/.github/workflows/review-reusable.yml +++ b/.github/workflows/review-reusable.yml @@ -70,6 +70,10 @@ on: required: false type: string default: "120000" + branch_cleanup_skip_branches: + required: false + type: string + default: "" log_level: required: false type: string @@ -142,6 +146,7 @@ jobs: MERGE_METHOD: ${{ inputs.merge_method }} REQUIRE_CHECKS: ${{ inputs.require_checks }} MAX_PATCH_CHARS: ${{ inputs.max_patch_chars }} + BRANCH_CLEANUP_SKIP_BRANCHES: ${{ inputs.branch_cleanup_skip_branches }} LOG_LEVEL: ${{ inputs.log_level }} GHBOT_EVENT_NAME: ${{ inputs.event_name }} GHBOT_EVENT_ACTION: ${{ inputs.event_action }} @@ -193,6 +198,7 @@ jobs: MERGE_METHOD: ${{ inputs.merge_method }} REQUIRE_CHECKS: ${{ inputs.require_checks }} MAX_PATCH_CHARS: ${{ inputs.max_patch_chars }} + BRANCH_CLEANUP_SKIP_BRANCHES: ${{ inputs.branch_cleanup_skip_branches }} LOG_LEVEL: ${{ inputs.log_level }} GHBOT_EVENT_NAME: schedule GHBOT_EVENT_ACTION: schedule diff --git a/.github/workflows/review.yml b/.github/workflows/review.yml index e6ca2d0..82a2a0d 100644 --- a/.github/workflows/review.yml +++ b/.github/workflows/review.yml @@ -54,6 +54,7 @@ jobs: merge_method: ${{ vars.MERGE_METHOD || 'squash' }} require_checks: ${{ vars.REQUIRE_CHECKS || 'true' }} max_patch_chars: ${{ vars.MAX_PATCH_CHARS || '120000' }} + branch_cleanup_skip_branches: ${{ vars.BRANCH_CLEANUP_SKIP_BRANCHES || '' }} log_level: info review-schedule-recheck: if: github.event_name == 'schedule' @@ -77,5 +78,6 @@ jobs: merge_method: ${{ vars.MERGE_METHOD || 'squash' }} require_checks: ${{ vars.REQUIRE_CHECKS || 'true' }} max_patch_chars: ${{ vars.MAX_PATCH_CHARS || '120000' }} + branch_cleanup_skip_branches: ${{ vars.BRANCH_CLEANUP_SKIP_BRANCHES || '' }} log_level: info run_schedule_recheck: "true" diff --git a/README.md b/README.md index 6c0137b..811478d 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ Optional repository variables: - `MERGE_METHOD`: `merge`, `squash`, or `rebase`, defaults to `squash` - `REQUIRE_CHECKS`: defaults to `true` - `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`. If you do nothing else, ghbot uses that workflow token for comments, reviews, checks, and merges. @@ -85,6 +86,7 @@ Notes: - `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. - 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 @@ -145,6 +147,7 @@ jobs: merge_method: ${{ vars.MERGE_METHOD || 'squash' }} require_checks: ${{ vars.REQUIRE_CHECKS || 'true' }} max_patch_chars: ${{ vars.MAX_PATCH_CHARS || '120000' }} + branch_cleanup_skip_branches: ${{ vars.BRANCH_CLEANUP_SKIP_BRANCHES || '' }} log_level: info ``` @@ -153,6 +156,7 @@ The caller repository still needs to configure: - `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 - `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 @@ -225,6 +229,7 @@ Important variables: - `MERGE_METHOD`: defaults to `squash` - `REQUIRE_CHECKS`: defaults to `true` - `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: diff --git a/src/config.ts b/src/config.ts index 9bb33ac..0e59b7b 100644 --- a/src/config.ts +++ b/src/config.ts @@ -5,6 +5,17 @@ const optionalString = z.preprocess((value) => { return value === "" ? undefined : value; }, 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) => { if (typeof value !== "string") { return value; @@ -49,6 +60,7 @@ const configSchema = z.object({ mergeMethod: z.enum(["merge", "squash", "rebase"]).default("squash"), requireChecks: envBoolean.default(true), maxPatchChars: z.coerce.number().int().positive().default(120_000), + branchCleanupSkipBranches: csvList, logLevel: z.string().min(1).default("info") }); @@ -67,5 +79,6 @@ export const config = configSchema.parse({ mergeMethod: process.env.MERGE_METHOD, requireChecks: process.env.REQUIRE_CHECKS, maxPatchChars: process.env.MAX_PATCH_CHARS, + branchCleanupSkipBranches: process.env.BRANCH_CLEANUP_SKIP_BRANCHES, logLevel: process.env.LOG_LEVEL }); diff --git a/src/review/codexCliReviewer.ts b/src/review/codexCliReviewer.ts index 2b56c33..4467602 100644 --- a/src/review/codexCliReviewer.ts +++ b/src/review/codexCliReviewer.ts @@ -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.", "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.", + "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.", "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.", diff --git a/src/review/processor.ts b/src/review/processor.ts index 84c93b7..3631937 100644 --- a/src/review/processor.ts +++ b/src/review/processor.ts @@ -161,6 +161,11 @@ export async function processScheduledBranchCleanup( repo: string; } ): Promise { + 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, @@ -175,6 +180,20 @@ export async function processScheduledBranchCleanup( 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 && @@ -197,6 +216,25 @@ export async function processScheduledBranchCleanup( 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, @@ -935,6 +973,52 @@ async function deleteBranchIfPresent( } } +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 { + 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 { if (event !== "APPROVE") { return false;