Guide
How to Stop Claude Code, Cursor and Codex From Pushing to Main
Sooner or later it happens to everyone who lets an agent run for a while. You come back and find a commit on main you never reviewed. Sometimes it's harmless. Sometimes it's a force push that overwrote someone's work, or a "fix" that went straight to production because your host deploys on every push.
The fix isn't a sterner sentence in CLAUDE.md. Instructions are suggestions, and agents follow them most of the time. What you want is layers:
- The server says no. GitHub refuses direct pushes to
main, whoever sends them. - The agent's tool says no. Claude Code, Cursor or Codex blocks the
git pushcommand before it runs. - The instructions explain the workflow, so the agent goes for a branch and a draft PR first and doesn't keep trying to push.
Layer 1 is the only one that's actually guaranteed. Layers 2 and 3 save you time and noise. Every config below was checked against the official docs on 14 November 2026. These tools change fast, so check again if you're reading this much later.
Layer 1: Protect main on GitHub (the part that actually stops it)
Your agent pushes with your git credentials, so to GitHub it looks exactly like you. The only reliable block is a rule on the server that applies to you too.
Option A: A branch ruleset (recommended)
- Open your repository → Settings.
- In the sidebar under "Code, planning, and automation", click Rules → Rulesets.
- Click New ruleset → New branch ruleset.
- Name it
protect-main, set Enforcement status to Active. - Under Target branches, add the default branch.
- Enable these rules:
- Restrict deletions
- Require a pull request before merging
- Block force pushes
- Optionally Require status checks to pass (your test workflow)
- Leave the Bypass list empty. If you add yourself, your agent can bypass the rule too, because it's using your credentials.
On availability: GitHub's docs say rulesets work in public repositories on GitHub Free, and in public and private repositories on GitHub Pro, Team and Enterprise Cloud. The same goes for classic protected branches. If your repo is private on a Free plan, you'll need Pro, or you'll have to rely on layers 2 and 3.
Solo founders, note this: GitHub doesn't let you approve your own pull request. If you require one approval and you're the only person in the repo, you lock yourself out. The pull request rule allows 0 required approvals. In that case the PR still has to be opened, it just doesn't need an approval. That's exactly what a solo founder wants: no direct pushes, every change visible as a PR.
Same thing from the command line
If you'd rather script it (or apply it to many repos), the REST endpoint is POST /repos/{owner}/{repo}/rulesets:
cat > ruleset.json <<'JSON'
{
"name": "protect-main",
"target": "branch",
"enforcement": "active",
"conditions": {
"ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] }
},
"rules": [
{ "type": "deletion" },
{ "type": "non_fast_forward" },
{
"type": "pull_request",
"parameters": {
"required_approving_review_count": 0,
"dismiss_stale_reviews_on_push": false,
"require_code_owner_review": false,
"require_last_push_approval": false,
"required_review_thread_resolution": false
}
}
]
}
JSON
gh api --method POST repos/OWNER/REPO/rulesets --input ruleset.json
non_fast_forward is the API name for "Block force pushes". ~DEFAULT_BRANCH targets whatever your default branch is called.
Test it
git switch main
git commit --allow-empty -m "test: should be rejected"
git push origin main
# Expected: the push is rejected by a repository rule
git reset --hard HEAD~1 # remove the test commit locally
If that push goes through, the ruleset isn't active or you're on the bypass list.
Option B: Classic branch protection
Still supported: Settings → Branches → Add classic branch protection rule, pattern main, enable "Require a pull request before merging", and tick "Do not allow bypassing the above settings". Without that box, admins (you, and therefore your agent) can still push. Force pushes and deletions are blocked by default unless you turn on "Allow force pushes".
Layer 2a: Claude Code, with deny rules plus a hook
Claude Code has a permission system with allow, ask and deny rules in settings.json. Deny is checked first, then ask, then allow, and the first match wins. Put this in .claude/settings.json in your repo so it applies to everyone who clones it:
{
"permissions": {
"deny": [
"Bash(git push --force *)",
"Bash(git push -f *)",
"Bash(git push origin main *)",
"Bash(git push origin HEAD:main *)"
],
"ask": [
"Bash(git push *)",
"Bash(gh pr merge *)"
]
}
}
Here, force pushes and explicit pushes to main are refused, and any other push asks you first. If you want the agent never to push at all, move Bash(git push *) to deny. A trailing * also matches the bare command, so git push with no arguments is covered.
The catch, straight from the docs: Bash rules match the command text. Anthropic's permissions page says Bash(git push *) does not match git -C . push origin main or git -c push.default=current push, so a deny rule "isn't a security boundary around the program". That's why you add a hook.
A PreToolUse hook that catches the variants
Hooks run before a tool call and can deny it. Save this as .claude/hooks/block-push-main.sh and make it executable (chmod +x). It needs jq.
#!/bin/bash
# .claude/hooks/block-push-main.sh
CMD=$(jq -r '.tool_input.command // empty')
# Any git invocation that contains a push (covers "git -C . push", "git -c x=y push")
if echo "$CMD" | grep -qE '(^|[;&|[:space:]])git([[:space:]]+-[^[:space:]]+([[:space:]]+[^-[:space:]][^[:space:]]*)?)*[[:space:]]+push\b'; then
if echo "$CMD" | grep -qE '(--force|[[:space:]]-f\b|[[:space:]]\+|\bmain\b|\bmaster\b|HEAD:)'; then
jq -n '{
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: "Pushing to main or force pushing is blocked. Push a feature branch and open a draft PR instead."
}
}'
exit 0
fi
fi
exit 0 # no decision: normal permission flow continues
Register it in .claude/settings.json next to the permissions:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-push-main.sh",
"args": []
}
]
}
]
}
}
A few details from the hooks reference that matter here:
- Exit code
0with no output means "no decision", so the normal permission flow continues. The hook can deny a call, but staying silent doesn't approve it. - If you want to block with a plain exit code instead of JSON, use
exit 2. Exit code1is treated as a non-blocking error, and the command still runs. - A hook that crashes or can't be found doesn't block by default. Recent versions (v2.1.295+) support
"onFailure": "block"on the hook if you want it to fail closed. - Run
/hooksinside Claude Code to confirm the hook is loaded.
The hook deliberately looks only for force pushes and for main/master/HEAD: in the command. A bare git push while you happen to be on main gets through the hook. The ask rule above catches that, and so does the GitHub ruleset from layer 1. A branch name that contains the word main, like fix/main-menu, will be blocked too. That's a safe false positive.
One more thing about --dangerously-skip-permissions / bypass mode: Anthropic's permission-modes page says deny rules still block in every mode, including bypassPermissions, but allow rules and prompts don't apply there. So your deny list still protects you. Everything else runs without asking. Don't use it on a repo where pushes deploy to production. If you want to rule it out entirely, set permissions.disableBypassPermissionsMode to "disable" in your settings.
Layer 2b: Cursor, with approvals plus a beforeShellExecution hook
Approvals. In the Cursor IDE, open Cursor Settings → Agents → Approvals & Execution. From Cursor 3.6 you can choose Auto-review (the default), Allowlist or Run Everything. Don't use Run Everything on a repo that deploys from main, and don't add git push to your allowlist.
Hooks. Cursor supports project hooks in .cursor/hooks.json. A beforeShellExecution hook gets the command as JSON on stdin and can return "permission": "deny":
{
"version": 1,
"hooks": {
"beforeShellExecution": [
{ "command": ".cursor/hooks/block-push-main.sh", "failClosed": true }
]
}
}
#!/bin/bash
# .cursor/hooks/block-push-main.sh (chmod +x)
CMD=$(jq -r '.command // empty')
if echo "$CMD" | grep -qE '\bgit\b.*\bpush\b' && \
echo "$CMD" | grep -qE '(--force|[[:space:]]-f\b|[[:space:]]\+|\bmain\b|\bmaster\b|HEAD:)'; then
cat <<'JSON'
{
"permission": "deny",
"user_message": "Blocked: push to main / force push.",
"agent_message": "Pushing to main or force pushing is not allowed in this repo. Push a feature branch and open a draft pull request instead."
}
JSON
exit 0
fi
# Any other push: ask the human
if echo "$CMD" | grep -qE '\bgit\b.*\bpush\b'; then
echo '{ "permission": "ask", "user_message": "Agent wants to push a branch. Approve?" }'
exit 0
fi
# Everything else: same pattern as Cursor's own docs example
echo '{ "permission": "allow" }'
Points from Cursor's hooks docs:
- Project hooks run from the project root, so use
.cursor/hooks/...paths, not./hooks/.... - For permission hooks, invalid JSON blocks the action, and exit code
2also blocks. Crashes and timeouts fail open unless you set"failClosed": true. - Cloud agents pick up
.cursor/hooks.jsonfrom your repository, but not your user-level~/.cursor/hooks.json. - The final
allowmirrors the example in Cursor's docs. The docs don't say clearly whether a hook'sallowalso skips your approval mode. If you want to be strict, returnaskinstead ofallowon the last line. You'll get more prompts, but nothing runs without your approval. (Empty output isn't a safe shortcut: Cursor blocks permission hooks that return invalid JSON.)
If you use the Cursor CLI, permissions live in <project>/.cursor/cli.json (or ~/.cursor/cli-config.json) using tokens like Shell(git) in allow / deny, and deny wins over allow. Shell(git) matches every git subcommand, so deny it only if you want the CLI agent to have no git at all.
Layer 2c: Codex, with the sandbox plus a rules file
Codex's defaults already help. In the CLI and IDE extension, the default workspace-write sandbox has network access turned off, so git push can't reach GitHub without asking you to step outside the sandbox. Keep approval_policy = "on-request" for interactive work. The old "untrusted" value is no longer supported.
To make a push impossible even when Codex asks to escalate, add a rule. Rules are Starlark files in a rules/ folder, either user-level (~/.codex/rules/default.rules) or project-level (<repo>/.codex/rules/, which only loads once you trust the project):
# ~/.codex/rules/default.rules
prefix_rule(
pattern = ["git", "push"],
decision = "forbidden",
justification = "Never push from Codex. Commit to a feature branch and ask the user to push or open a draft PR.",
match = ["git push origin main", "git push --force"],
not_match = ["git status"],
)
prefix_rule(
pattern = ["gh", "pr", "merge"],
decision = "forbidden",
justification = "Merging is a human decision.",
)
decision can be allow, prompt or forbidden. When several rules match, the strictest one wins. Restart Codex after editing, then test:
codex execpolicy check --pretty \
--rules ~/.codex/rules/default.rules \
-- git push origin main
As the docs note, rules are experimental and apply to commands Codex wants to run outside the sandbox. That's why the GitHub ruleset in layer 1 still matters.
Layer 3: Tell the agent what to do instead
Blocking a push without explaining the alternative makes agents retry in creative ways. Add this to AGENTS.md (read by Codex, Cursor and others) and CLAUDE.md:
## Git workflow (mandatory)
- Never commit or push to `main` or `master`.
- Never use `git push --force`, `git reset --hard` on shared branches, or `git push origin HEAD:main`.
- For every task: create a branch `ai/<task-name>`, commit there, push that branch.
- Open a **draft** pull request and fill in `.github/pull_request_template.md`.
- Never merge pull requests. Merging is the owner's decision.
- If a push is blocked, stop and report. Do not look for another way to push.
The last line is the important one. It turns a blocked push into a status report and stops the agent from hunting for a workaround.
Quick checklist
- [ ] GitHub ruleset on default branch: PR required, force pushes blocked, deletions restricted, bypass list empty
- [ ] Tested with an empty commit: direct push rejected
- [ ] Claude Code:
deny/askrules plusPreToolUsehook in.claude/settings.json - [ ] Cursor: not on Run Everything;
beforeShellExecutionhook withfailClosed: true - [ ] Codex:
workspace-writesandbox,prefix_ruleforbiddinggit push - [ ]
AGENTS.md/CLAUDE.mddescribe the branch → draft PR workflow
Get the files ready-made
The free Founder Repo OS Community Kit has the AGENTS.md git rules, a PR template for AI changes and a DECISIONS.md log for you to copy into your repo: github.com/suppelabs/founder-repo-os-community.
If you'd rather have it fitted to your repo, Founder Repo OS scans the repository, proposes the rules and agent boundaries, and delivers everything as a draft pull request with the full diff. It follows its own advice: it never writes to main, and you decide what gets merged.