Prevent Claude Code from Pushing Code After Context Compaction

When Claude Code runs /compact or auto-compacts due to context limits, it loses the full conversation history. In this degraded state, it may push incomplete commits, skip tests, or push to the wrong branch — believing it has already verified the work.

The Problem

Context compaction is necessary for long sessions, but it creates a dangerous window:

Post-compaction autonomous push

After compaction, Claude Code retains a summary but loses the actual code changes it reviewed. It "remembers" that it was working on a feature and that the next step was to push. It pushes — but the code it pushes may be half-finished, untested, or targeting the wrong branch.

This is especially dangerous in autonomous/auto mode where no human is watching the session.

Why CLAUDE.md Isn't Enough

Ironically, CLAUDE.md instructions are themselves subject to compaction. The instruction "run tests before pushing" may survive compaction, but the context of which tests to run and what was changed gets lost. The model complies with the letter of the rule while missing the spirit.

The Fix: post-compact-safety Hook

post-compact-safety.sh — blocks git push entirely, requiring explicit human approval:

#!/bin/bash
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')

# Block all push operations
if echo "$COMMAND" | grep -qE 'git\s+push'; then
  echo "BLOCKED: git push requires human approval" >&2
  echo "Use: git push (outside Claude Code) after reviewing changes" >&2
  exit 2
fi

exit 0

This is the nuclear option: no pushes from Claude Code at all. For a more nuanced approach, cc-safe-setup's branch-guard allows pushes to feature branches while blocking main/master.

Install Push Protection + 7 More Safety Hooks

npx cc-safe-setup

Guards against post-compaction drift, force-push, rm -rf, secret leaks, and more. 9,200+ tests 655 examples

GitHub · npm · Getting Started

Also Prevents

Check Your Safety Score

npx cc-health-check

Free 20-point diagnostic for your Claude Code setup.

Open source, zero dependencies. View source.

Related: rm -rf · force-push · if field · autonomous · all tools

Learn more: Production Guide · All Tools