Back to Resources
Branch-Switch Hygiene, Session Cache Reset, and Cross-Agent SyncLast Updated: Published November 27, 2026

Stale AI Agent Rules After Branch Switches: Preventing Context Poisoning Across Workspaces

Stale AI agent rules after a branch switch happen when Cursor, OpenAI Codex CLI, Google Antigravity, or Claude Code retain cached instructions from a previous Git branch in an open session. Prevent context poisoning by detecting rule diffs via Git post-checkout hooks, clearing active agent contexts, and decoupling portable workflows into a synced skill library.

Git Branch Switch
Rule Cache Drift
Synced Skill Library

Switched Git branches while Cursor, Codex, or Antigravity stayed open? Stop stale AI agent rules from poisoning context with hooks and synced skills.

Why Do Coding Agents Keep Applying Stale Rules After You Switch Git Branches?

Cursor, OpenAI Codex CLI, Google Antigravity, and Claude Code keep applying stale rules after a branch switch because active agent sessions retain previously injected instructions inside their conversation state even after Git swaps files on disk. Running git switch or git checkout updates working-tree files like AGENTS.md and .cursor/rules/*.mdc, yet open chat threads and untracked override files preserve the old branch's assumptions.

Context poisoning happens through two distinct mechanisms across modern coding agents:

  • In-Session Transcript Retention: In Cursor Composer, Google Antigravity IDE chats, OpenAI Codex CLI interactive runs, and Claude Code terminal sessions, instructions read at turn 1 stay embedded inside the active message history. Even when the filesystem changes underneath the workspace, prior-branch constraints continue steering token generation until the session resets.
  • Untracked & Gitignored Local Overrides: Files such as AGENTS.override.md, local .cursor/rules/draft.mdc files, or branch-specific .agents/rules/*.md drafts that are not committed to Git remain untouched during git checkout, leaking feature-branch rules onto main or hotfix branches.

Official agent configuration specs explain why startup snapshots linger. According to the official Cursor Rules documentation: “Project rules live in .cursor/rules as .mdc files and are version-controlled. They are scoped using path patterns, invoked manually, or included based on relevance.” Cursor recommends keeping each .mdc rule under 500 lines, and once a rule is attached to a Composer thread, those lines remain in that thread's prompt history.

Terminal and multi-agent runtimes introduce additional startup caches. Per the OpenAI Codex AGENTS.md guide, “Codex skips empty files and stops adding files once the combined size reaches the limit defined by project_doc_max_bytes (32 KiB by default).” Similarly, the Google Antigravity Rules documentation states: “Rules are cumulative rather than replacement-based: Antigravity combines all the rules it finds into the prompt.” Antigravity caps each rule file at 24 KB (24,000 bytes) and enforces a 20,000-token aggregate budget across global and always_on rules—so an untracked override or lingering session snapshot silently consumes budget and overrides newer branch logic.

Runtime Rule Caching Matrix: Cursor, Codex CLI, Antigravity, and Claude Code

Cursor, OpenAI Codex CLI, Google Antigravity, and Claude Code each discover repository instructions from different directories and require different reset actions after a Git checkout. Keeping an existing thread open after switching branches guarantees instruction drift in all four runtimes.

Coding AgentBranch-Tracked Rule FilesDiscovery & Budget BehaviorBranch-Switch Poisoning VectorRequired Reset Action
Cursor IDE.cursor/rules/*.mdc, AGENTS.mdChat/Composer turn start and matching file globsActive Composer threads retain prior-branch rule context in conversation historyOpen a new Composer thread after git switch and re-attach target files
OpenAI Codex CLIAGENTS.md, AGENTS.override.md, ~/.codex/skills/*/SKILL.mdSession startup (32 KiB project_doc_max_bytes cap)Long-running interactive sessions keep the initial AGENTS.md snapshot until restartedExit and restart the Codex CLI session so root-to-cwd discovery re-runs
Google AntigravityAGENTS.md, GEMINI.md, .agents/rules/*.mdWorkspace load and cumulative rule discovery (24 KB/file, 20,000-token cap)In-flight agent threads keep earlier cumulative rule snapshots across checkoutsStart a fresh Antigravity conversation and verify .agents/rules/*.md status
Anthropic Claude CodeCLAUDE.md, .claude/skills/*/SKILL.mdStartup preamble plus 1% context window skill listing budgetOld branch CLAUDE.md instructions and invoked skill bodies stay pinned in transcriptRun /clear to drop prior branch transcript and /reload-skills to re-index skills

Notice that when teams run multiple branches simultaneously instead of switching in place, linked Git worktrees avoid in-place file replacement but create their own instruction divergence—covered in our walkthrough on syncing AGENTS.md and Claude skills across Git worktrees.

How Do You Detect Stale Rule Context Poisoning Before an Agent Edits Code?

You can detect stale AI agent rules before an agent writes bad code by checking three warning signals immediately after switching branches: untracked override files in git status, rule-file diffs between branches, and tool outputs referencing removed schemas or deprecated libraries. Catching rule drift takes under five seconds when you inspect repository instruction paths directly instead of trusting the model's first response.

Watch for these four concrete symptoms of branch-switch context poisoning across Cursor, Codex CLI, Google Antigravity, and Claude Code:

  1. Phantom Framework or ORM Calls: An open Cursor Composer or Antigravity session continues importing a library or helper introduced on your feature branch after you switched back to main.
  2. Stale Test Runner Commands: OpenAI Codex CLI or Claude Code runs yesterday's feature-branch test command because its startup AGENTS.md or CLAUDE.md snapshot predated the checkout.
  3. Untracked Override Precedence Hijacks: An untracked AGENTS.override.md or gitignored .cursor/rules/local.mdc silently takes precedence over the committed branch rules in Codex CLI or Cursor.
  4. Missing Hotfix-Branch Guardrails: A branch created before a new security rule landed omits .agents/rules/security.md, causing the agent to bypass input validation checks you added earlier in the week.

Before prompting any open agent after a branch switch, run a targeted diff against your previous branch reference to see whether any instruction files changed:

# Check whether switching from the previous branch altered any AI agent rule files
git diff --name-only @{-1} HEAD --   AGENTS.md AGENTS.override.md CLAUDE.md GEMINI.md   .cursor/rules .agents/rules .claude/skills .codex/skills

# Also surface untracked or ignored local rule overrides that survive git switch
git status --ignored --short --   AGENTS.override.md .cursor/rules .agents/rules .claude/skills

If either command prints output, any long-running Cursor, Codex CLI, Google Antigravity, or Claude Code session opened prior to the checkout is operating with stale context. For related worktree commit hazards, see our guide on resolving Git detached HEAD traps in multi-agent worktrees.

Automating Branch-Switch Rule Hygiene With Git post-checkout Hooks

Installing a Git post-checkout hook gives you an automatic terminal alert whenever switching branches changes AGENTS.md, .cursor/rules, .agents/rules, CLAUDE.md, or repo-scoped skill folders. Instead of relying on memory during a fast context switch, Git compares the old and new commits on every branch checkout and surfaces exact reload instructions before you run another agent prompt.

According to the official Git Hooks documentation: “This hook is invoked when a git-checkout[1] or git-switch[1] is run after having updated the worktree. The hook is given three parameters: the ref of the previous HEAD, the ref of the new HEAD (which may or may not have changed), and a flag indicating whether the checkout was a branch checkout (changing branches, flag=1) or a file checkout (retrieving a file from the index, flag=0).”

Save the POSIX script below to .git/hooks/post-checkout and make it executable with chmod +x .git/hooks/post-checkout. Checking [ "$BRANCH_FLAG" -eq 1 ] ensures the check runs only on branch switches and ignores single-file restores:

#!/usr/bin/env bash
# .git/hooks/post-checkout — Warn when branch switches alter AI agent rules
set -euo pipefail

PREV_HEAD="${1:-}"
NEW_HEAD="${2:-}"
BRANCH_FLAG="${3:-0}"

# Only inspect full branch checkouts (flag=1); skip single-file restores (flag=0)
if [ "$BRANCH_FLAG" -ne 1 ] || [ -z "$PREV_HEAD" ] || [ -z "$NEW_HEAD" ]; then
  exit 0
fi

# Skip initial null-ref clone checkouts
if [ "$PREV_HEAD" = "0000000000000000000000000000000000000000" ]; then
  exit 0
fi

CHANGED_RULES="$(git diff --name-only "$PREV_HEAD" "$NEW_HEAD" --   AGENTS.md AGENTS.override.md CLAUDE.md GEMINI.md   .cursor/rules .agents/rules .claude/skills .codex/skills 2>/dev/null || true)"

UNTRACKED_OVERRIDES="$(git status --porcelain --untracked-files=all --   AGENTS.override.md .cursor/rules .agents/rules 2>/dev/null | grep -E '^\?\?' || true)"

if [ -n "$CHANGED_RULES" ] || [ -n "$UNTRACKED_OVERRIDES" ]; then
  echo ""
  echo "⚠️  [AI Agent Hygiene] Branch switch affected agent rule files:"
  [ -n "$CHANGED_RULES" ] && echo "$CHANGED_RULES" | sed 's/^/   changed: /'
  [ -n "$UNTRACKED_OVERRIDES" ] && echo "$UNTRACKED_OVERRIDES" | sed 's/^/   untracked: /'
  echo "   -> Cursor / Antigravity: start a new Composer or Agent thread"
  echo "   -> OpenAI Codex CLI: restart session to re-read AGENTS.md (32 KiB cap)"
  echo "   -> Claude Code: run /clear and /reload-skills"
  echo ""
fi

If your team shares client-side hooks via a repo-tracked .githooks/ directory configured with git config core.hooksPath .githooks, every developer gets the same branch-switch warning automatically across macOS and Linux workstations. When multi-agent rule conflicts arise even on a single branch, review our diagnostic guide on resolving multi-agent instruction precedence conflicts.

Which Agent Rules Belong in Git Branches vs. a Synced Global Skill Library?

Branch-tracked files like AGENTS.md and .cursor/rules/*.mdc should hold only repository invariants tied to the checked-out commit, while repeatable engineering workflows belong in a global synced skill library outside Git branches. Separating repo facts from personal and team workflows eliminates most branch-switch staleness because your review, debugging, and refactoring skills no longer vanish or mutate when you run git switch.

Instruction TypeCanonical LocationWhy It Belongs There
Database migration safety rules and ORM invariantsGit branch (AGENTS.md or .cursor/rules/*.mdc)Schema conventions change alongside feature migrations and must match the checked-out commit.
API contract schemas and endpoint deprecation noticesGit branch (.cursor/rules/api.mdc or .agents/rules/api.md)Branch-specific endpoint signatures prevent an agent from generating legacy payloads on newer branches.
Personal code review rubrics and PR risk checklistsSynced global skill library (Prompttly)Review standards stay identical across main, hotfix, and feature branches without polluting repo diffs.
Incident triage, log parsing, and release verification workflowsSynced global skill library (Prompttly)Emergency hotfix branches must never lack your diagnostic skills because edits stayed on an unmerged branch.

When NOT to store rules inside a Git branch: Do not commit personal prompt templates, cross-repository PR review rubrics, or individual formatting preferences inside branch-tracked .cursor/rules/*.mdc or CLAUDE.md files. Every uncommitted improvement you make to those instructions gets trapped on one branch, triggers noisy pull-request diffs, and disappears the moment you switch to an urgent hotfix. For deeper format separation patterns, read our comparison of Cursor Rules vs Claude Skills, CLAUDE.md, and AGENTS.md.

The Sprawl Moment: The Feature-Branch Migration Rule That Poisoned a Production Hotfix

You spend Wednesday afternoon tuning an ORM query-review rule and a multi-step migration verification checklist inside .cursor/rules/database.mdc and AGENTS.md on a long-lived feature branch—complete with new Drizzle schema helpers that do not exist on main yet. At 4:15 PM an alert pages you for a production billing bug, so you run git switch -c hotfix/webhook-idempotency main in the same workspace while Cursor Composer and an interactive OpenAI Codex CLI session stay open. Neither tool drops its earlier context; Cursor writes a hotfix patch calling the unmerged Drizzle wrapper from your feature branch, while Codex skips your production rollback verification checklist entirely because that workflow only lived on the other branch. By the time your tests fail, you have lost twenty minutes untangling code poisoned by stale branch rules and hunting down a prompt you already wrote twice.

Prompttly is a skill manager for AI agents — one library for your skills and prompts that syncs into Claude Code, Codex, ChatGPT, and Claude and is one hotkey away on your Mac, so your setup follows you across every machine, repo, and tool.

Because Prompttly syncs native SKILL.md folders directly into ~/.claude/skills and ~/.codex/skills via two-way Mac sync—and lets you invoke any workflow across Cursor, Google Antigravity, or web chats in under 200ms with a global hotkey palette—your verification checklists stay identical across every Git branch without polluting repository commits. If offline edits across laptops also cause your rules to diverge, pair branch hygiene with our guide on resolving multi-laptop prompt drift.

What Should You Reset Immediately After Switching Branches With Open Agent Sessions?

Immediately after switching Git branches, open a fresh thread in Cursor and Google Antigravity, restart active OpenAI Codex CLI processes, and run /clear plus /reload-skills in Claude Code whenever rule files differ between commits. Treating branch switches as a boundary for agent session state prevents yesterday's feature assumptions from contaminating today's hotfix.

  1. Start a Fresh Thread in Cursor and Google Antigravity: Close or archive active Composer and Antigravity agent threads after git switch so cumulative rules and .cursor/rules/*.mdc globs re-evaluate cleanly against the new branch.
  2. Restart OpenAI Codex CLI Sessions: Exit and re-launch Codex CLI so root-to-working-directory AGENTS.md discovery (within the 32 KiB project_doc_max_bytes budget) reads the checked-out commit instead of a stale session preamble.
  3. Clear and Reload Claude Code Context: Per the Anthropic Claude Code Skills documentation, “Keep SKILL.md under 500 lines. Move detailed reference material to separate files.” Run /clear to flush old-branch transcript instructions, then run /reload-skills if project skills under .claude/skills changed across branches.
  4. Promote Cross-Branch Workflows Out of Git: Move recurring review, debugging, and prompt templates out of branch-tracked markdown files using the free Claude Skill Creator or Custom Instructions Generator, or browse all workflow guides on the Prompttly resources hub.

Frequently Asked Questions: Stale AI Agent Rules After Branch Switches

Why do Cursor, OpenAI Codex CLI, and Google Antigravity ignore new rules after git checkout?

Cursor, OpenAI Codex CLI, and Google Antigravity keep previously loaded rule text inside the active conversation transcript or session startup cache after git checkout replaces files on disk. Until you start a new chat thread or restart the CLI session, the model continues conditioning on earlier branch instructions already inside its context window.

Does running /clear in Claude Code reload modified CLAUDE.md and SKILL.md files?

Running /clear in Claude Code resets the conversation transcript so stale branch instructions no longer bias the active context window. If you added or edited project skills inside .claude/skills after switching branches, also run /reload-skills so Claude Code refreshes its 1% context window skill listing.

How does a Git post-checkout hook detect stale AI agent rules automatically?

Git invokes .git/hooks/post-checkout with three positional arguments: previous HEAD ($1), new HEAD ($2), and a branch-checkout flag ($3) equal to 1 on branch switches. Comparing git diff --name-only "$1" "$2" against AGENTS.md, CLAUDE.md, .cursor/rules, .agents/rules, and skill directories immediately warns you whenever a checkout alters agent instructions.

Should reusable prompt workflows be committed to feature branches or kept in a global library?

Keep branch-specific invariants such as build commands, active schema constraints, and directory globs inside repository files like AGENTS.md or .cursor/rules/*.mdc. Store cross-branch workflows like PR review rubrics, refactoring checklists, and security audits in a synced global skill library so switching to a hotfix branch never strips your capabilities.

Can untracked .cursor/rules/*.mdc or .agents/rules/*.md files leak across Git branches?

Yes. Untracked or gitignored local override files such as AGENTS.override.md or experimental .cursor/rules/*.mdc drafts stay untouched on disk when you run git switch, causing Cursor, Codex CLI, and Google Antigravity to inject branch-specific experiments into unrelated branches.

How does Prompttly prevent stale AI agent rules across branches and workspaces?

Prompttly decouples your reusable skills and prompts from individual Git branches, syncing native skill directories into Claude Code and OpenAI Codex via two-way Mac sync while giving you a <200ms global hotkey palette to insert verified rules into Cursor, Google Antigravity, ChatGPT, and Claude.

Keep reusable skills out of volatile Git branches

Use the free Claude Skill Creator to separate branch-specific repository rules from portable workflows that should follow you cleanly across every branch, repo, and coding agent.