GitHub branch protection and auto-merge: stop AI from changing main directly and require passing CI before merge

Translated from the original Traditional Chinese version.

Summary

When an AI tool works through your GitHub account, GitHub treats its actions as yours. Without rules in the repo, the AI can change main directly and can merge code whose tests failed. You add one ruleset that protects main, then turn on auto-merge and automatic branch deletion. After that, main only receives pull requests whose tests pass, and GitHub does the merging and branch cleanup for you.

Table of contents

When an AI tool such as Claude Code helps with your code, you usually want it to put its changes on a branch and open a pull request for you to review. The changes should reach main only after the tests pass. But the AI uses your own GitHub account, and GitHub treats it as you. If the repo has no rules and the AI misjudges, it can change main directly, or merge code whose tests failed. To prevent that, add a ruleset that protects main on GitHub’s settings page, then turn on auto-merge and automatic branch deletion. After that, main accepts only pull requests whose tests pass.

This article uses a few terms again and again. Here is what they mean on GitHub:

Term Meaning
main The repo’s primary branch, where the production code lives
branch A line of work copied from main. Changing code on a branch does not affect main
push Upload changes from your computer to GitHub
pull request (PR) A request to merge a branch into main. GitHub lists what changed on the PR page
checks passing (green check), checks failing (red X) The result of the automated tests on the PR page. A green check means the tests passed, and a red X means they did not

Once the setup is done, a change reaches main through the flow below. Each step is labeled with the setting that handles it:

Flow after setup: edit code on a branch, open a pull request, run automated tests. When checks pass, Allow auto-merge merges the PR into main and Automatically delete head branches deletes the branch. When checks fail, Require status checks to pass blocks the merge. A direct push to main is blocked by Require a pull requestFlow after setup: edit code on a branch, open a pull request, run automated tests. When checks pass, Allow auto-merge merges the PR into main and Automatically delete head branches deletes the branch. When checks fail, Require status checks to pass blocks the merge. A direct push to main is blocked by Require a pull request

Public repos can use these settings on any plan. Private repos need GitHub Pro or a higher plan. If you have a private repo on the Free plan, you can block an agent from pushing to main with Claude Code hooks instead.

Settings to turn on

The effects you want map to six options on GitHub’s settings pages. The first four belong to one ruleset that you create on the “Rulesets” page. The last two are checkboxes on the “General” page:

Effect you want Setting Where
main cannot be deleted Restrict deletions Rulesets
main history cannot be overwritten by a force push Block force pushes Rulesets
Every change must go through a PR to reach main Require a pull request before merging Rulesets
Merge only when checks pass Require status checks to pass Rulesets
Merge automatically when checks pass Allow auto-merge General
Delete the branch after merging Automatically delete head branches General

Set up automated tests

“Merge only when checks pass” relies on GitHub Actions to run CI, the automated tests that GitHub runs every time a PR is opened. So the repo needs a test workflow first. If your repo does not have one, add a GitHub Actions workflow file named .github/workflows/ci.yml. The example below runs npm test in a Node.js project. If your project has dependencies, add - run: npm ci before npm test to install them. If your project is not Node.js, replace the last line with your own test command:

1name: CI
2on: pull_request
3jobs:
4  test:
5    runs-on: ubuntu-latest
6    steps:
7      - uses: actions/checkout@v7
8      - uses: actions/setup-node@v7
9        with:
10          node-version: 22
11      - run: npm test

The test must run on a PR once before you can find its name, test, when you create the ruleset. So add the workflow file to the repo through a PR first. You can do all of this on the GitHub website:

  1. On the repo home page, click “Add file” and choose “Create new file”.
  2. Enter .github/workflows/ci.yml as the file name, paste the workflow above as the content, then click “Commit changes…” at the top right.
  3. In the dialog, choose “Create a new branch for this commit and start a pull request”, click “Propose changes”, then click “Create pull request” on the next page. The PR page now shows test running.
  4. When test shows a green check, click “Merge pull request”.

Create the ruleset that protects main

  1. Go to the repo’s “Settings”, click “Rulesets” in the left menu, then click “New ruleset” at the top right and choose “New branch ruleset”. A new ruleset form opens.

    The repo settings page with Rulesets selected in the left menu and the New ruleset dropdown at the top right open, listing New branch ruleset, New tag ruleset, and Import a ruleset

  2. Enter a name in “Ruleset Name”, for example protect-main, and change “Enforcement status” from “Disabled” to “Active”. The ruleset takes effect only when it is Active. The “Bypass list” below it names who may ignore the ruleset. Leave it empty, so that even your own account cannot skip the rules.

    The Ruleset Name field filled with protect-main, Enforcement status set to Active, and the Bypass list showing Bypass list is empty

  3. Under “Target branches”, click “Add target” and choose “Include default branch”. When the page shows “Applies to 1 target: main”, the ruleset applies to main.

    Under Target branches, Branch targeting criteria has Default added, and the line below shows Applies to 1 target: main

  4. Under “Branch rules”, check “Require a pull request before merging” and “Require status checks to pass”. “Restrict deletions” and “Block force pushes” are already checked, so leave them as they are.

    Branch rules with Require a pull request before merging, Require status checks to pass, and Block force pushes checked

    Expand “Show additional settings” under “Require a pull request” to find “Required approvals”, which sets how many people must approve a PR. Keep the default of 0. GitHub does not let the author of a PR approve their own PR, so in a repo with one maintainer, setting it to 1 means no PR can ever be merged.

  5. Expand “Show additional settings” under “Require status checks to pass”, click “Add checks”, search for test, and select it. This name is the test under jobs in the workflow file you added earlier. After you select it, it appears in the “Required status checks” list.

    The Add Checks search box with test entered, and the list showing a test check whose source is GitHub Actions

  6. Scroll to the bottom of the page and click “Create”. GitHub then shows “Confirm access”, and you verify your identity again as prompted, for example by entering a two-factor authentication code. After that, the “Rulesets” page lists protect-main with “4 branch rules” next to it.

Once the ruleset exists, accidental pushes and accidental merges are blocked. However, an account with admin permission can still come back to this page and edit or delete the ruleset, so the ruleset cannot stop someone who deliberately changes the settings. To pause the ruleset later, open protect-main on the “Rulesets” page and set “Enforcement status” back to “Disabled”.

Turn on auto-merge and automatic branch deletion

Next, go back to “Settings”, open “General”, scroll down to the “Pull Requests” section, and check “Allow auto-merge” and “Automatically delete head branches”. A green check appears next to each option when it is saved. You do not need to click a save button.

The Pull Requests section of the General settings page with Allow auto-merge and Automatically delete head branches checked, each with a green check next to it

GitHub deletes only the branch on GitHub. The branch on your computer stays. Run git fetch --prune on your computer to remove remote-tracking branches such as origin/<branch name> that no longer exist on GitHub. To delete the local branch, run git branch -d <branch name> separately. If GitHub deletes a branch by mistake, the PR page has a “Restore branch” button that brings it back.

Check that the ruleset works

The simplest check is to edit a file on main directly on the website. After you click “Commit changes…”, the dialog says “You can’t commit to main because it is a protected branch” and offers only the option to create a new branch and open a PR. That message means the ruleset is working. Click “Cancel” to leave. You do not need to commit anything.

To confirm that a PR with a red X cannot be merged, open a PR whose test fails on purpose:

  1. On the website, open a test file, click “Edit file”, change an expected result to a wrong value, then commit it to a new branch and open a PR the same way you added the workflow file.
  2. Wait for test to finish with a red X.

The merge box on the PR page now shows “All checks have failed”, test appears as “CI / test (pull_request)” and is marked “Required”, and there is no merge button, only “Enable auto-merge”.

The merge box on a PR page showing All checks have failed, with CI / test (pull_request) marked Failing and Required, and only an Enable auto-merge button below

If you try to merge the same PR from the command line, GitHub also refuses. The 11 in the command is the PR number, shown after the title on the PR page:

1gh pr merge 11 --merge
1X Pull request OWNER/REPO#11 is not mergeable: the base branch policy prohibits the merge.

Adding --admin to force the merge with admin permission gives the same result, because the “Bypass list” is empty:

1gh pr merge 11 --merge --admin
1GraphQL: Repository rule violations found
2
3Required status check "test" is failing.

If you skip the PR and run git push origin main to push your local changes straight to main, GitHub rejects that too and lists which rules were violated:

1remote: error: GH013: Repository rule violations found for refs/heads/main.
2remote: - Changes must be made through a pull request.
3remote: - Required status check "test" is expected.
4 ! [remote rejected] main -> main (push declined due to repository rule violations)

When you have confirmed this, click “Close pull request” on the PR with the red X, then click “Delete branch” to delete the test branch.

Let GitHub merge the PR automatically

With the ruleset in place, you no longer have to wait for the tests to finish and merge by hand. On your next normal PR, while the tests are still running, click “Enable auto-merge” on the PR page. You can also run the command below on the PR’s branch, and optionally add the PR number at the end:

1gh pr merge --auto --merge

When the tests show a green check, GitHub merges the PR and then deletes the branch. If the tests fail, the PR stays where it is until you push a fix. You can add “after opening a PR, run gh pr merge --auto --merge” to your instructions for the AI. Then GitHub handles the merge and the branch cleanup for you.

The PR timeline showing enabled auto-merge, merged commit into main (1 check passed), and deleted the test/green-pr branch, with a Restore branch button next to it

Set it up with the gh command

You can also do the setup above with the GitHub CLI (gh). First sign in with gh auth login using an account that has admin permission on the repo, and make sure the repo already has the test workflow from earlier. Set the two General options with gh repo edit, and replace OWNER/REPO with your own repo:

1gh repo edit OWNER/REPO --enable-auto-merge --delete-branch-on-merge

gh has no command for creating a ruleset. Write the ruleset as ruleset.json and send it with gh api. The file below matches the ruleset you created on the website. Replace test with the name of your own test:

1{
2  "name": "protect-main",
3  "target": "branch",
4  "enforcement": "active",
5  "conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } },
6  "rules": [
7    { "type": "deletion" },
8    { "type": "non_fast_forward" },
9    {
10      "type": "pull_request",
11      "parameters": {
12        "required_approving_review_count": 0,
13        "dismiss_stale_reviews_on_push": false,
14        "require_code_owner_review": false,
15        "require_last_push_approval": false,
16        "required_review_thread_resolution": false
17      }
18    },
19    {
20      "type": "required_status_checks",
21      "parameters": {
22        "strict_required_status_checks_policy": false,
23        "required_status_checks": [{ "context": "test" }]
24      }
25    }
26  ]
27}

You must write out all five parameters under pull_request. If you give only the approval count, GitHub replies with a 422 error. After you send the ruleset, confirm it with gh ruleset check. When the output lists four rules, the setup is done:

1gh api -X POST repos/OWNER/REPO/rulesets --input ruleset.json
2gh ruleset check main -R OWNER/REPO

Test notes

I tested on a private repo under my own GitHub Pro account, with gh version 2.106.0.

Test Result
Turn on auto-merge while the tests were running The tests passed and the PR merged after about 11 seconds, and the branch was deleted 2 seconds later
Push directly to main Rejected, even when pushing as the repo owner
Force a merge with admin permission The repo owner added --admin and still could not merge

Summary

With the ruleset in place, every PR the AI opens reaches main only after its tests pass. The commands the AI can run on your computer still need to be limited separately. In my tests, even the repo owner’s account was blocked from pushing to main directly and from merging a PR with a red X.

Further reading

Ted Liou

Ted Liou

Software engineer writing about Unity and AI development.

Comments