Skip to content

chore: block direct pushes to protected branches - #31

Merged
CodeDeficient merged 12 commits into
mainfrom
chore/protect-main
Jul 27, 2026
Merged

chore: block direct pushes to protected branches#31
CodeDeficient merged 12 commits into
mainfrom
chore/protect-main

Conversation

@CodeDeficient

@CodeDeficient CodeDeficient commented Jul 27, 2026

Copy link
Copy Markdown
Owner

Why this exists

The previous ship-cycle failure exposed that this repository had no local guard against pushing directly to main. The workflow relied on process instructions alone, so reviewed work was accidentally published to the protected branch before a pull request could be opened.

Design decisions

Decision: Enforce the destination branch in the pre-push hook

Why: The unsafe operation is a push targeting refs/heads/main or refs/heads/master, regardless of which local branch supplies the commit.
Alternatives considered: Blocking only when main is checked out was rejected because explicit pushes from another local branch could still update the protected branch.
Tradeoff: Developers can still push a feature branch while checked out on main; server-side branch protection remains the final enforcement layer.

Decision: Preserve existing hooks by refusing conflicts

Why: Installing a guard must not silently disable another tool's pre-push hook.
Alternatives considered: Replacing the hook path or overwriting an existing hook was rejected because it can remove unrelated checks.
Tradeoff: Repositories with an existing pre-push hook require manual chaining.

Decision: Keep the hook source version-controlled and install a local copy

Why: The repository needs a reviewable source of truth while Git executes hooks from the local checkout's active hooks directory.
Tradeoff: A fresh checkout requires the one-time setup command, and updates require reinstalling the copied hook.

What this enables

Future commits can be reviewed and pushed through feature branches and pull requests without relying on memory to prevent direct updates to main or master.

Risks and safeguards

Risk: A developer bypasses local hooks with --no-verify.
Mitigation: Configure GitHub branch protection to require pull requests and prevent direct updates server-side.

Risk: An existing local pre-push hook is disabled during setup.
Mitigation: Setup refuses to replace any existing hook and documents manual chaining.

Validation

Automated:

  • npm test
  • npm run type-check (not defined in this repository)
  • npm run lint (not defined in this repository)
  • npm run test:e2e (not applicable)

Evidence:

  • Pushes targeting main and master are rejected locally.
  • Feature-branch pushes to feature refs remain allowed.
  • Existing hook conflicts are rejected rather than overwritten.

CodeAnt-AI Description

Prevent accidental direct pushes to protected branches

What Changed

  • Pushes targeting main or master are rejected locally with instructions to use a feature branch and pull request
  • Adds a setup command to install the shared pre-push protection after cloning
  • Existing pre-push hooks and symlinks are never overwritten; setup stops and explains how to chain the hook manually
  • Documents how to install and update the hook using Git's active hooks directory

Impact

✅ Fewer accidental direct updates to main or master
✅ Safer pull-request workflow after cloning
✅ Existing developer hooks remain intact

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

Summary by CodeRabbit

  • New Features

    • Added a shared Git hooks setup script that installs a pre-push hook.
    • Prevents accidental pushes directly to the main or master branches.
    • Preserves existing pre-push hooks and provides guidance for manual integration.
  • Documentation

    • Added setup and usage instructions for local Git hooks to the README.

@codeant-ai

codeant-ai Bot commented Jul 27, 2026

Copy link
Copy Markdown

🤖 CodeAnt AI — Review Status

Status Commit Started (UTC) Finished (UTC)
✅ Reviewed your PR 5d566bb Jul 27, 2026 · 19:56 19:59

@codeant-ai

codeant-ai Bot commented Jul 27, 2026

Copy link
Copy Markdown

Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@CodeDeficient, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 29 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 650c2d37-9a22-43bd-9581-6a2cfc9f5cf6

📥 Commits

Reviewing files that changed from the base of the PR and between 5d566bb and 6289ee4.

📒 Files selected for processing (3)
  • .githooks/pre-push
  • README.md
  • scripts/setup-git-hooks.sh
📝 Walkthrough

Walkthrough

Adds a shared Git pre-push hook that blocks direct pushes to main and master, plus an installer script and README documentation for configuring and maintaining the hook.

Changes

Local Git Hooks

Layer / File(s) Summary
Pre-push branch protection
.githooks/pre-push
The hook reads pushed refs, rejects pushes to main or master, and allows other refs.
Hook installation and instructions
scripts/setup-git-hooks.sh, README.md
The setup script installs the hook without replacing an existing one, while the README documents setup and manual updates.

Estimated code review effort: 2 (Simple) | ~10 minutes

Poem

A rabbit checks the branches bright,
“Main and master? Not tonight!”
The hook hops in with careful cheer,
Feature branches pass safely here,
And carrots guard each push just right.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: blocking direct pushes to protected branches.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/protect-main

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codeant-ai codeant-ai Bot added the size:M This PR changes 30-99 lines, ignoring generated files label Jul 27, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@scripts/setup-git-hooks.sh`:
- Around line 9-12: The existing-hook workflow is contradictory and risks
discarding unrelated hooks. In scripts/setup-git-hooks.sh lines 9-12, update the
refusal message to remove the instruction to manually chain and rerun the setup
script; in README.md line 152, distinguish an already-installed shared hook from
an unrelated existing pre-push hook and instruct users to preserve the unrelated
hook rather than discard it.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3ce83df3-0249-4f2f-817c-e36894fa70f9

📥 Commits

Reviewing files that changed from the base of the PR and between a92db39 and 5d566bb.

📒 Files selected for processing (3)
  • .githooks/pre-push
  • README.md
  • scripts/setup-git-hooks.sh

Comment thread scripts/setup-git-hooks.sh
Comment thread .githooks/pre-push
Comment on lines +5 to +6
while read -r local_ref local_oid remote_ref remote_oid; do
case "$remote_ref" in

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: This guard reads Git's pre-push ref records directly from standard input. If it is chained after an existing pre-push hook that also consumes that input, the loop receives EOF, checks no refs, and exits successfully, allowing a push to main or master. The chaining mechanism must preserve or buffer the ref stream, or ensure this guard runs before any consumer. [security]

Severity Level: Critical 🚨
- ❌ Manually chained hooks can bypass main/master protection.
- ⚠️ Direct pushes rely solely on server-side branch protection.
Steps of Reproduction ✅
1. Run `./scripts/setup-git-hooks.sh` from a checkout with an existing pre-push hook;
`scripts/setup-git-hooks.sh:9-12` refuses replacement and instructs the developer to chain
`.githooks/pre-push` manually.

2. Configure the existing hook to invoke the repository hook after reading its pre-push
stdin, which is a valid manual chaining arrangement for hooks that inspect ref updates.

3. Push to `refs/heads/main`; Git supplies the ref records on stdin, but the existing hook
consumes them before invoking `.githooks/pre-push`.

4. The loop at `.githooks/pre-push:5-12` receives EOF, never evaluates the
protected-branch case at line 7, and exits successfully at line 14, allowing the push to
proceed locally.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** .githooks/pre-push
**Line:** 5:6
**Comment:**
	*Security: This guard reads Git's pre-push ref records directly from standard input. If it is chained after an existing pre-push hook that also consumes that input, the loop receives EOF, checks no refs, and exits successfully, allowing a push to `main` or `master`. The chaining mechanism must preserve or buffer the ref stream, or ensure this guard runs before any consumer.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Comment thread scripts/setup-git-hooks.sh Outdated
Comment on lines +6 to +7
hooks_dir=$(git -C "$repo_root" rev-parse --git-path hooks)
target="$hooks_dir/pre-push"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: The --git-path hooks result can be relative, but git -C only changes Git's working directory; the shell still resolves target from the caller's current directory. Running this script from a repository subdirectory can therefore copy the hook into a nonexistent or incorrect path instead of the active hooks directory. Convert the hooks path to an absolute path or perform the copy from repo_root. [api mismatch]

Severity Level: Major ⚠️
- ❌ Setup from repository subdirectories may install incorrectly.
- ⚠️ Protected-branch checks remain absent after setup failure.
Steps of Reproduction ✅
1. Clone the repository and change into a repository subdirectory rather than the
repository root.

2. Invoke the documented setup entry point `./scripts/setup-git-hooks.sh` from that
subdirectory; the script computes the root at `scripts/setup-git-hooks.sh:5`.

3. `git -C "$repo_root" rev-parse --git-path hooks` at line 6 may return a relative Git
path, while the shell resolves `target` at line 7 relative to the caller's current
directory.

4. The `cp` at `scripts/setup-git-hooks.sh:15` then targets a path under the subdirectory
instead of the active hooks directory, causing installation to fail or placing the hook
incorrectly.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** scripts/setup-git-hooks.sh
**Line:** 6:7
**Comment:**
	*Api Mismatch: The `--git-path hooks` result can be relative, but `git -C` only changes Git's working directory; the shell still resolves `target` from the caller's current directory. Running this script from a repository subdirectory can therefore copy the hook into a nonexistent or incorrect path instead of the active hooks directory. Convert the hooks path to an absolute path or perform the copy from `repo_root`.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Comment thread scripts/setup-git-hooks.sh Outdated

if [ -e "$target" ] || [ -L "$target" ]; then
printf 'Refusing to replace existing hook: %s\n' "$target" >&2
printf 'Chain %s into that hook manually, then rerun this setup script.\n' "$repo_root/.githooks/pre-push" >&2

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: The reported recovery procedure cannot succeed as written: manually chaining the repository hook into the existing target leaves target present, so rerunning this script immediately hits the same refusal branch. The setup instructions must either install the guard as part of the existing hook without requiring a rerun, or explicitly tell the user to remove or replace the target after chaining. [incomplete implementation]

Severity Level: Major ⚠️
- ❌ Existing-hook users cannot complete documented setup.
- ⚠️ Developers must edit or remove hooks manually.
Steps of Reproduction ✅
1. Start with an existing active pre-push hook in the hooks directory resolved at
`scripts/setup-git-hooks.sh:6-7`.

2. Run `scripts/setup-git-hooks.sh`; the existence check at lines 9-13 prints the chaining
instruction at line 11 and exits.

3. Manually add a call to `.githooks/pre-push` inside the existing hook, as instructed;
the original target file remains present.

4. Rerun `scripts/setup-git-hooks.sh`; lines 9-12 detect that same target and exit again,
so the documented “then rerun” recovery procedure cannot install anything.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** scripts/setup-git-hooks.sh
**Line:** 11:11
**Comment:**
	*Incomplete Implementation: The reported recovery procedure cannot succeed as written: manually chaining the repository hook into the existing target leaves `target` present, so rerunning this script immediately hits the same refusal branch. The setup instructions must either install the guard as part of the existing hook without requiring a rerun, or explicitly tell the user to remove or replace the target after chaining.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

@CodeDeficient
CodeDeficient merged commit b833dd7 into main Jul 27, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:M This PR changes 30-99 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant