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;