How to Make AI Agents Work With Git Instead of Fighting Git
Learn practical strategies to stop AI agents from wrecking your git history, with concrete commands and configs you can apply today.
Before you start
You've delegated a coding task to an AI agent, and within minutes it has created a mess: a dozen commits named 'Update file', a force-pushed branch, or a merge conflict that makes no sense. Sound familiar? AI agents are powerful, but they often treat git like a scratchpad rather than a collaboration tool. This guide shows you how to set up guardrails so agents work with git, not against it.
We'll cover three practical areas: giving agents clear git instructions, restricting their permissions, and using dedicated branches and commit strategies. By the end, you'll have a copy-paste setup that keeps your history clean and your sanity intact.
- You need a terminal with git installed (version 2.30 or later).
- You should have a basic understanding of git commands like commit, branch, and merge.
- Pick an AI agent that supports custom instructions or system prompts, such as GitHub Copilot, Codex, or a custom agent you run yourself.
Step 1: Define a git policy in your agent's instructions
The first step is to tell the agent how to use git. Without explicit rules, agents tend to make a commit after every small change, use vague messages, and push directly to main. Create a policy file that you can paste into your agent's system prompt or instructions.
This policy should cover commit message style, branch naming, and the rule to never force-push. Here's a template you can adapt.
You are working in a git repository. Follow these rules:
1. Commit messages must follow Conventional Commits: type(scope): subject.
2. Make one commit per logical change, not per file.
3. Never force-push to any branch.
4. Create a new branch for each task: feature/your-task-name.
5. Before pushing, run git pull --rebase to sync with the remote.
6. If you encounter a merge conflict, stop and ask for help.- Type and scope should be lowercase, e.g., 'feat(parser): add error handling'.
- The 'stop and ask' rule prevents agents from making destructive conflict resolutions.
- Adapt the policy to your team's conventions, but keep the force-push ban.
Step 2: Restrict agent permissions with a dedicated user and config
Even with a policy, agents can still make mistakes. A stronger safeguard is to run the agent under a separate git identity and restrict its capabilities. Create a dedicated user for the agent and set up a git config that prevents it from pushing to protected branches.
You can use git's conditional includes to apply this config only in certain directories. Here's how to set it up.
# Create a git config for the agent user
mkdir -p ~/.config/git
cat > ~/.config/git/agent-config <<'EOF'
[user]
name = AI Agent
email = agent@example.com
[core]
hooksPath = ~/.git-agent-hooks
EOF
# Use conditional include in your main gitconfig
git config --global includeIf.gitdir:~/work/agent/.path ~/.config/git/agent-config- The hooksPath points to a directory where you can add a pre-push hook to block force-pushes.
- Replace ~/work/agent with the actual path where your agent works.
- This config applies only to that directory, so your personal git settings remain unchanged.
Step 3: Use a pre-push hook to block dangerous operations
A pre-push hook is a script that runs before git push. You can use it to enforce rules like blocking force-pushes or pushing to main. Here's a simple hook that blocks force-push and direct pushes to main or develop.
Create the hook file and make it executable.
cat > ~/.git-agent-hooks/pre-push <<'EOF'
#!/bin/sh
# Block force-push and pushes to main/develop
protected_branches="main develop"
current_branch=$(git symbolic-ref --short HEAD)
for branch in $protected_branches; do
if [ "$current_branch" = "$branch" ]; then
echo "Error: direct push to $branch is not allowed." >&2
exit 1
fi
done
if [ "$1" = "--force" ]; then
echo "Error: force-push is not allowed." >&2
exit 1
fi
exit 0
EOF
chmod +x ~/.git-agent-hooks/pre-push- The hook checks the current branch name and the --force flag.
- You can extend it to check the remote branch name as well.
- Test it by trying to push to main and seeing the error.
Step 4: Give the agent a clean workspace with a dedicated branch
When you start a task with an agent, always create a fresh branch for it. This isolates the agent's work and makes it easy to review or discard. Use a script that sets up the branch and prints the exact commands for the agent to follow.
Here's a bash function you can add to your shell profile.
agent_start() {
task_name="$1"
branch="agent/$task_name-$(date +%s)"
git checkout -b "$branch"
echo "Agent branch created: $branch"
echo "You are now on $branch. Make changes and commit with clear messages."
}
# Usage: agent_start fix-login-bug- The timestamp ensures the branch name is unique.
- After the agent finishes, you can merge or delete the branch.
- This also helps with parallel tasks from multiple agents.
Step 5: Automate commit message generation with a script
Agents often produce poor commit messages. Instead of relying on the agent to write them, you can use a script that generates a conventional commit message based on the diff. This script can be called by the agent or by you after the agent's work.
Here's a Python script that uses the diff to create a simple message.
#!/usr/bin/env python3
import subprocess, sys
def main():
diff = subprocess.check_output(['git', 'diff', '--cached']).decode()
if not diff:
print('No staged changes', file=sys.stderr)
sys.exit(1)
# Extract file names
files = [line[4:] for line in diff.splitlines() if line.startswith('+++ b/')]
scope = files[0].split('/')[0] if files else 'general'
msg = f'feat({scope}): update {len(files)} file(s)'
print(msg)
if __name__ == '__main__':
main()- This is a minimal example; you can extend it to analyze the diff content.
- Use it with git commit -F <(python script.py) to automate the commit.
- Make sure the script is executable and in your PATH.
Step 6: Review and merge with a pull request
Never let an agent merge its own changes directly. Always create a pull request (PR) and review the diff. This is your safety net. You can use the git command to push the branch and open a PR with a standard message.
Here's a command sequence to push the branch and create a PR using the GitHub CLI or a similar tool.
# Push the branch and create a PR
git push -u origin agent/fix-login-bug
gh pr create --title "Fix login bug" --body "Changes made by AI agent, review required."- Use gh pr create if you use GitHub; adapt for GitLab or Bitbucket.
- Review the diff carefully before merging.
- If the agent's changes are not needed, close the PR and delete the branch.
Verify it worked
After setting up the policy, hook, and branch strategy, test that the agent respects them. Run a simple task with the agent and observe its behavior. Here's a quick checklist to verify.
- The agent creates a branch with a name like agent/task-name-timestamp.
- Commit messages follow the Conventional Commits format.
- The agent does not push to main or use --force.
- The pre-push hook blocks any dangerous push attempt.
- You can review the changes in a PR without surprises.
Troubleshooting
If the agent still misbehaves, here are common issues and fixes.
The agent might be using its own git config, ignoring your settings. Check by running git config --list in the agent's working directory.
If the pre-push hook doesn't trigger, make sure the hooksPath is set correctly and the hook is executable.
If the agent creates too many commits, reinforce the 'one logical change' rule in your policy.
What I would do: Recommended setup
After running this script, any git operation in ~/work/agent uses the agent config and the pre-push hook. You still need to add the policy to your agent's instructions, but the technical guardrails are in place.
#!/bin/bash
# Setup script for AI agent git safety
# 1. Create agent config
mkdir -p ~/.config/git
cat > ~/.config/git/agent-config <<'EOF'
[user]
name = AI Agent
email = agent@example.com
[core]
hooksPath = ~/.git-agent-hooks
EOF
# 2. Add conditional include to global gitconfig
if ! grep -q 'includeIf.gitdir:~/work/agent' ~/.gitconfig; then
echo '[includeIf "gitdir:~/work/agent/"]' >> ~/.gitconfig
echo ' path = ~/.config/git/agent-config' >> ~/.gitconfig
fi
# 3. Create pre-push hook
mkdir -p ~/.git-agent-hooks
cat > ~/.git-agent-hooks/pre-push <<'EOF'
#!/bin/sh
protected_branches="main develop"
current_branch=$(git symbolic-ref --short HEAD)
for branch in $protected_branches; do
if [ "$current_branch" = "$branch" ]; then
echo "Error: direct push to $branch is not allowed." >&2
exit 1
fi
done
if [ "$1" = "--force" ]; then
echo "Error: force-push is not allowed." >&2
exit 1
fi
exit 0
EOF
chmod +x ~/.git-agent-hooks/pre-push
echo "Setup complete. Place your agent in ~/work/agent to apply the config."FAQ
Answers to the questions that come up most often on this topic.
- Q: Can I trust an AI agent to commit directly to main? A: No, even with strict instructions, agents can make mistakes. Always use branches and PRs.
- Q: What if the agent needs to modify files outside the repository? A: Limit the agent's working directory to the repo root and use environment variables to control permissions.
- Q: How do I handle an agent that keeps creating merge conflicts? A: Instruct it to pull --rebase before pushing and to avoid editing files that are likely to conflict.
- Q: Is it worth the effort to set up these guardrails? A: Yes, it saves hours of cleaning up a messy history and prevents accidental force-pushes that can break your team's work.
Next action
Your next step is to run the setup script above, then create a test branch and let your agent make a small change. Verify that the pre-push hook blocks a push to main. Once that works, you can trust your agent to collaborate on git without wrecking your repository.
Key takeaways
- Apply one concrete change from this post before collecting more reading.
- Prefer browser-side tools when the work involves secrets, tokens, or PII.
- Document the why next to the how so the next reviewer inherits context.
FAQ
- Who is this guide on ai-agents for?
- Working developers who need a practical take on how to make ai agents work with git instead of fighting git — not a marketing overview. Skim the sections, apply one tip, then come back when you hit an edge case.
- Do I need an account to use the related tools?
- No. code.live tools run in your browser with no signup. Nothing you paste is uploaded to a server for the client-side utilities linked from this post.
- How often is this article updated?
- This post was published September 12, 2026. Fundamentals stay stable; check linked tool pages and official docs when version-specific behavior matters.