Git + AI Workflows in 50 Words
AI coding assistants generate code faster than you can track it manually. Git is the safety net that makes AI-generated code reviewable, reversible, and debuggable. Use atomic commits, branch-per-ask isolation, AI-generated commit messages, and automated code review. The discipline is not overhead, it is what makes AI-assisted development professional.
Why Git Matters More With AI
When you code with an AI assistant, the speed-to-commit ratio changes fundamentally. A single prompt to Cursor, Copilot, or Claude can generate hundreds of lines across multiple files. Without git discipline, that code enters your project as an unauditable blob. You cannot tell what the AI changed, why it changed it, or how to undo it without losing your own work.
The developers who skip git discipline with AI end up in one of three failure modes:
- The unrevertable mess: a bulk AI generation introduced a bug somewhere in 400 lines, and there is no way to isolate the specific change without reading every line.
- The lost history: git blame shows your name on every line, but you cannot explain what half of them do because the AI wrote them in a session you barely remember.
- The merge conflict spiral: two AI sessions edited the same files on the same branch, and the conflict resolution is harder than rewriting from scratch.
Every practice in this masterclass exists to prevent those failure modes. Git is the safety net. AI is the accelerator. Without the net, the accelerator drives you into a wall.
This class completes a three-part curriculum with the Evals and Testing AI Output masterclass (correctness) and the Security of AI-Generated Code masterclass (safety). Together they cover the three pillars of professional AI-assisted development: is the code correct (evals), is the code safe (security), and is the code traceable (git).
The Core Git + AI Workflow
The Seven-Step Loop
- Branch: create a fresh branch for the specific task you are about to ask the AI to do. Name it descriptively:
feat/add-user-auth,fix/cart-total-rounding. - Prompt: describe the task to your AI coding assistant (Cursor, Copilot, Claude, aider). Be specific about the scope.
- Review the diff: before touching git, read what the AI generated. If you cannot explain a block of code, do not commit it.
- Stage atomically: stage only the files for one logical change. If the AI generated a model, a service, and a handler, make three separate commits.
- Commit with AI: use an AI commit message tool (aicommits, OpenCommit, or your IDE) to generate a Conventional Commits message from the staged diff.
- Push and PR: push the branch. Open a pull request. Let an AI reviewer (CodeRabbit, Copilot) perform the first pass.
- Human review: review the AI reviewer's comments. Approve, request changes, or iterate. Merge only when both automated and human gates pass.
If you use aider, steps 2 through 5 happen automatically. Aider generates the code, stages it, and commits it with a descriptive message in a single operation. You still control the push and the PR (Source: aider.chat documentation).
The Rule of Atomic Commits
Every commit represents exactly one logical change. This rule exists because of git bisect: if a regression appears, bisect can only isolate the breaking commit if each commit contains a single concern. A commit that mixes a database migration, a UI change, and a config update cannot be bisected effectively. AI tools generate bulk code by default. Your job is to split it into atomic units before committing.
AI-Generated Commit Messages
The Conventional Commits Standard
Conventional Commits (conventionalcommits.org, spec v1.0.0) defines a structured format for commit messages that makes history readable by both humans and machines (Source: conventionalcommits.org):
<type>[optional scope]: <description> [optional body] [optional footer(s)]
The two mandatory types are feat (new feature, triggers a MINOR version bump) and fix (bug patch, triggers a PATCH bump). Common additional types: refactor, docs, test, ci, build, perf, style, chore. Breaking changes use a ! suffix: feat!: drop Node 18 support.
Tool Comparison
| Tool | Type | LLM Support | Key Feature |
|---|---|---|---|
| aicommits | CLI | OpenAI, configurable | Reads staged diff, returns Conventional Commits message. Widely adopted open-source tool. |
| OpenCommit | CLI | OpenAI, Anthropic, Ollama (local models) | Provider flexibility. Supports GitMoji. Direct git-hook installation for automation. |
| aider | Terminal pair programmer | OpenAI, Anthropic, local via Ollama | Auto-commits every edit with descriptive message. Git-native: every AI action is a commit. |
| Cursor | IDE | Built-in (Claude, GPT) | Context-aware messages using full codebase index. Integrated into the editor commit flow. |
| GitHub Copilot | IDE / GitHub | Built-in | Low-latency suggestions in VS Code and the GitHub PR interface. |
Best Practices for AI Commit Messages
- Stage small: AI commit tools produce better messages from small, focused diffs. A 1,000-line diff overwhelms the model and produces vague summaries.
- Enforce the standard: configure your tool to output Conventional Commits format. Most tools support this via a flag or config file.
- Review the draft: never push an AI-generated message without reading it. Verify the type is correct (
featvsfixvsrefactor), the description is accurate, and no sensitive information leaked into the message. - Add the "why": AI tools describe what changed (they read the diff). The why is your job. Add a body line if the motivation is not obvious from the description.
Some teams add a git commit trailer to mark AI-assisted commits: Co-authored-by: Claude <noreply@anthropic.com> or AI-assisted: true. This helps reviewers prioritize scrutiny on AI-generated code. The convention is emerging but not yet standardized across the industry.
Hands-On Build
Exercise 1: Generate an AI Commit Message
# Install aicommits globally npm install -g aicommits # Configure with your OpenAI key aicommits config set OPENAI_KEY=sk-your-key-here # Configure to use Conventional Commits aicommits config set type=conventional # Stage a change and generate the message git add src/auth/login.ts aicommits # Output example: # feat(auth): add JWT token validation to login endpoint # # Use aicommits? (Y/n)
Review the generated message. If the type or description is wrong, reject it and either edit manually or re-run with a smaller staged diff. The tool reads only your staged changes, not the full repository, so atomic staging produces better results.
Exercise 2: Submit an AI-Reviewed PR
# Push your branch git push origin feat/add-user-auth # Open a PR on GitHub gh pr create --title "feat(auth): add JWT token validation" \ --body "AI-generated implementation of JWT validation middleware." # If CodeRabbit is installed on your repo, it triggers automatically. # If using Copilot, request a review: # GitHub PR sidebar > Reviewers > Request from Copilot
CodeRabbit will post a summary with sequence diagrams, inline comments with severity labels, and one-click fix suggestions. Copilot provides inline comments with High/Medium/Low severity labels and groups similar comments to reduce noise (Source: GitHub Blog, 2026). Both are first-pass reviewers. Human approval is still required.
Exercise 3: Revert an AI-Generated Change
# Find the commit hash of the AI-generated change git log --oneline -5 # Revert it (creates a new commit that undoes the change) git revert abc1234 # In aider, the shortcut is: # /undo # This runs git revert on the last AI-generated commit. # Verify the reversion git diff HEAD~1
The key insight: git revert creates a new commit that undoes the change while preserving the full history. This is safer than git reset --hard, which destroys history. If the AI made multiple commits, revert them in reverse chronological order to avoid conflicts.
Exercise 4: Bisect an AI-Heavy History
# Start bisection git bisect start # Mark the current commit as bad (tests fail) git bisect bad HEAD # Mark a known-good commit (tests passed here) git bisect good v1.2.0 # Automate with your test suite git bisect run npm test # Git performs a binary search: # ~20 commits = ~5 test runs to find the exact breaking commit # When done: git bisect reset
This only works if your commits are atomic. A single bulk commit mixing 400 lines across 12 files cannot be bisected further, so the regression is somewhere in those 400 lines and you are back to reading every line. Atomic commits make bisection a 5-minute operation. Bulk commits make it a 5-hour one.
After git bisect identifies the breaking commit, feed the commit diff and test failure output into an LLM (via Ollama locally or your preferred model) for an explanation and suggested fix. The commit metadata plus the test error gives the model enough context to diagnose the root cause accurately in most cases.
AI Code Review Tools
CodeRabbit
CodeRabbit is the most-installed AI review app on the GitHub Marketplace (Source: CodeRabbit docs, July 2026). It builds a code graph mapping cross-file dependencies, which lets it catch issues that diff-based analysis misses, like a function signature change that breaks downstream callers in files not included in the PR.
- Trigger: automatic on new PRs once installed.
- Configuration:
.coderabbit.yamlin your repo root. - Interaction: comment
@coderabbitai summary,@coderabbitai help, or@coderabbitai approveon any PR. - Pricing: free for open-source. Pro at approximately 24 to 30 dollars per user per month. Enterprise custom pricing (Source: CodeRabbit pricing, July 2026).
GitHub Copilot PR Review
Copilot's PR review uses agentic analysis: it scans the diff while pulling in broader repository context, not just the changed lines. Comments include severity labels (High, Medium, Low) and one-click fix buttons (Source: GitHub Blog and GitHub Docs, 2026).
- Trigger: request Copilot as a reviewer in the PR sidebar, or use
gh pr edit --add-reviewer copilot. - Custom instructions: define team standards in
.github/copilot-instructions.md. Copilot respects these during review. - Limitation: Copilot does not count as a mandatory human approval. Use it as a pre-filter, not a replacement for human sign-off.
Graphite
Graphite is a platform for stacked pull requests, where large features are broken into smaller, sequential, dependent PRs. After its acquisition by Anysphere (creators of Cursor) in December 2025, Graphite integrated Cursor Cloud Agents for AI-driven review (Source: Graphite docs and codeant.ai, July 2026).
- Best for: teams already using or ready to adopt stacked PR workflows on GitHub.
- CLI:
gt(Graphite CLI) automates rebasing of dependent branches when a parent PR changes. - Limitation: GitHub-only. Teams on GitLab or Bitbucket need alternatives.
- Pricing: free Hobby tier (limited AI reviews). Team tier approximately 40 dollars per user per month with unlimited AI reviews (Source: Graphite pricing, July 2026).
AI Review Tool Comparison
| Feature | CodeRabbit | Copilot PR Review | Graphite |
|---|---|---|---|
| Analysis depth | Code graph (cross-file) | Agentic (repo context) | Cursor Cloud Agents |
| Platform support | GitHub, GitLab, Bitbucket, Azure DevOps | GitHub only | GitHub only |
| Free tier | Open-source projects | With Copilot subscription | Hobby (limited) |
| Stacked PRs | No | No | Native support |
| Custom rules | .coderabbit.yaml | copilot-instructions.md | Agent config |
| One-click fixes | Yes | Yes | Yes |
Branching Strategies for AI Work
Branch-Per-Ask
The branch-per-ask pattern creates a strict boundary around each AI interaction:
# One branch per AI request git checkout -b feat/add-user-auth # Ask the AI to implement auth # Review, commit, push, PR git checkout main git checkout -b fix/cart-total-rounding # Ask the AI to fix the rounding bug # Review, commit, push, PR git checkout main git checkout -b refactor/extract-db-layer # Ask the AI to refactor # Review, commit, push, PR
Each branch contains exactly one intent. If the AI's implementation is wrong, delete the branch. No other work is affected. If it is right, merge it through your standard PR flow.
Experimental Branches
For rapid prototyping or R&D, use a prefix convention:
# Experimental branch for AI-driven exploration git checkout -b exp/vector-search-approach # Let the AI try multiple approaches # When one works, cherry-pick the successful commits: git checkout main git cherry-pick abc1234 def5678 # Delete the experimental branch git branch -D exp/vector-search-approach
What Not to Do
AI on Main
Never run AI coding sessions directly on main or your primary development branch. One bad generation contaminates the branch for everyone.
Long-Lived AI Branch
A branch that accumulates dozens of AI sessions over days becomes impossible to review. Keep branches short-lived: one ask, one branch, one PR.
Reverting and Bisecting AI Changes
Reversion Strategies
| Scenario | Command | Effect |
|---|---|---|
| Undo last AI commit | git revert HEAD | Creates a new commit undoing the last change. History preserved. |
| Undo specific commit | git revert abc1234 | Creates a new commit undoing that specific change. |
| Undo in aider | /undo | Runs git revert on the last AI-generated commit. |
| Undo multiple commits | git revert abc..def | Reverts a range. Process in reverse order to avoid conflicts. |
| Selective undo | git revert --no-commit abc1234 | Stages the reversion without committing. Lets you keep some changes. |
Why git revert Beats git reset
git reset --hard destroys commit history. On a shared branch, this rewrites history and breaks every other contributor's local state. git revert preserves the original commit and creates a new one that undoes it. The full history remains intact, including the fact that the AI made the change and that you explicitly reversed it. For AI-generated code, this audit trail matters.
Effective Bisection
The binary search algorithm in git bisect tests approximately log2(N) commits. For 100 commits, that is roughly 7 test runs. Automate it:
# Fully automated bisection git bisect start git bisect bad HEAD git bisect good v1.0.0 git bisect run npm test # Git automatically checks out commits, runs the test, # and marks each as good or bad based on exit code. # Result: the exact commit that broke the build. # Clean up git bisect reset
A single commit containing 400 lines across 12 files cannot be bisected further. The regression is somewhere in those 400 lines, and bisect cannot help you. This is why the atomic commit rule is non-negotiable for AI-assisted development. Every commit must contain exactly one logical change so bisect can isolate it.
AI-Assisted Root Cause Analysis
After bisect identifies the breaking commit, feed the commit diff and test failure output into an LLM for automated root cause analysis:
# After bisect finds the bad commit (abc1234): git show abc1234 > /tmp/bad-commit.diff npm test 2>&1 > /tmp/test-error.log # Feed both to your local model via Ollama: cat /tmp/bad-commit.diff /tmp/test-error.log | \ ollama run qwen2.5-coder "Analyze this commit diff and test failure. \ Explain the root cause and suggest a fix."
.gitignore for AI Development
What to Commit (Project Conventions)
| File | Tool | Purpose |
|---|---|---|
| .cursor/rules/*.mdc | Cursor | Modular rule files defining coding standards and patterns. |
| CLAUDE.md | Claude Code / Agents | Project-wide instructions for Claude-based AI assistants. |
| AGENTS.md | Multiple | Cross-tool agent context. Read by multiple AI agents. |
| .aider.conf.yml | aider | Project-specific aider settings (model, conventions). |
| .aiderignore | aider | Files aider should skip during context loading. |
| .github/copilot-instructions.md | GitHub Copilot | Repository-wide instructions for Copilot. |
| .windsurfrules | Windsurf | Project-level rules for the Windsurf editor. |
What to Ignore (State and Artifacts)
# AI state files (session-specific, not shareable) .aider.chat.history.md .aider.input.history .aider.tags.cache.v3/ .cursor/ !.cursor/rules/ .continue/ .copilot/ # Sensitive data (never version-control secrets) .env .env.* *.pem *.key credentials.json secrets/ # Build artifacts (save tokens, improve AI performance) node_modules/ dist/ build/ .next/ *.log
A file in .gitignore is excluded from version control, but your AI coding tool may still read it locally. To prevent sensitive files from entering the AI's context window, use tool-specific ignore files: .cursorignore for Cursor, .aiderignore for aider. Treat any secret that enters an AI context window as leaked and rotate it immediately.
The .cursorignore Pattern
Cursor's .cursorignore follows .gitignore syntax but controls what the AI indexes and reads during chat:
# Sensitive files (never send to LLM provider) .env .env.* *.pem credentials.json secrets/ # Large files that waste context tokens node_modules/ dist/ package-lock.json yarn.lock *.log
Review Gates for AI-Generated Code
The Three-Gate Minimum
Automated Tests
Run your test suite (unit, integration, E2E) on every PR. If tests fail, the PR cannot merge. This catches functional regressions in AI-generated code.
AI Code Review
CodeRabbit or Copilot performs the first-pass review. Catches security vulnerabilities, performance issues, and style violations automatically.
Human Approval
A human reviewer approves the PR. Focus human review on authentication logic, database queries, API endpoints, and dependency additions.
GitHub Actions Example
name: CI Gates
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
- run: npm ci
- run: npm test
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
- run: npm ci
- run: npx eslint .
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
- run: npm audit --audit-level=high
Configure test, lint, and security as required status checks in your repository's branch protection rules. No PR merges without all three passing.
The AGENTS.md Context File
Create an AGENTS.md file in your repository root to give AI coding assistants explicit instructions about your project's architecture, coding standards, and patterns to avoid. Multiple tools (Cursor, Claude Code, Copilot) read this file to produce code that matches your existing codebase. This is the single most effective way to reduce the review burden on AI-generated PRs because the AI gets the context right the first time.
Review gates complement the security practices in the Security of AI-Generated Code masterclass. Add SAST scanning (Semgrep) and secret detection (gitleaks) as additional required status checks. See that masterclass for the full CI/CD security gate setup.
What You Learned
- Branch-per-ask isolates every AI interaction in its own branch for clean review and easy reversal.
- Atomic commits (one logical change per commit) are non-negotiable because they enable git bisect and clean reversion.
- AI commit message tools (aicommits, OpenCommit, aider) read your staged diff and produce Conventional Commits messages as first drafts.
- 3 AI review tools lead the field: CodeRabbit (code-graph analysis, multi-platform), Copilot PR Review (severity labels, custom instructions), and Graphite (stacked PRs, Cursor agents).
- git revert undoes AI changes safely by creating a new commit. git reset destroys history. Always revert, never reset on shared branches.
- git bisect run automates regression hunting across AI-heavy history in log2(N) test runs, but only if commits are atomic.
- Commit instructions, ignore state: version-control .cursor/rules/, CLAUDE.md, AGENTS.md. Ignore .aider.chat.history.md, .cursor/ session data, .env files.
- Three-gate minimum for AI PRs: automated tests, AI code review, human approval. Configure as required status checks.
Frequently Asked Questions
AI coding assistants generate code at a pace that makes manual tracking impossible. Without disciplined version control, you cannot isolate what the AI changed, revert a bad generation, or bisect a regression to its source. Git is the safety net that turns AI-generated code from an unauditable black box into a reviewable, reversible history. The developers who skip git discipline with AI end up with codebases they cannot debug.
AI-generated commit messages are structured summaries produced by an LLM that reads your staged git diff and returns a message following standards like Conventional Commits. Tools include aicommits (a CLI that reads your diff and returns a formatted message), OpenCommit (supports multiple LLM providers including local models via Ollama), and aider (an AI pair programmer that auto-commits every edit with a descriptive message). GitHub Copilot and Cursor also generate commit messages within their IDE interfaces.
Aider treats every edit as an atomic git commit. When you describe a task in natural language, aider modifies the files and immediately creates a commit with a descriptive message. If the change is wrong, you use the /undo command, which runs git revert on the last AI-generated commit. Aider also commits your uncommitted dirty changes before applying its own edits, keeping human work separate from AI work in the git history. You control the final git push manually.
Branch-per-ask means creating a fresh, short-lived git branch for every meaningful request you send to an AI coding assistant. Each branch isolates a single intent (add a CLI flag, write tests for module X, refactor the auth handler). This creates a strict boundary around each AI interaction, keeps the merge surface small, and makes it trivial to abandon or revert a specific change without affecting the rest of your work. It is the most effective branching strategy for AI-assisted development.
Apply the one-concern rule: every commit represents exactly one logical change. If an AI generates a database model, a service layer, and a handler simultaneously, split them into at least three separate commits. Stage only the files for one logical change at a time. Review the diff before committing. If you cannot explain what a block of code does, do not commit it. Atomic commits enable git bisect to pinpoint regressions to the exact AI request that introduced them.
CodeRabbit is an AI code review platform that automatically triggers on new pull requests. It builds a code graph mapping cross-file dependencies, which lets it identify systemic issues like breaking changes in downstream callers that diff-based analysis misses. It integrates 40-plus linters and SAST scanners, provides one-click fixes, and supports GitHub, GitLab, Bitbucket, and Azure DevOps. CodeRabbit offers a free tier for open-source projects and a Pro tier at approximately 24 to 30 dollars per user per month (Source: CodeRabbit pricing page, July 2026).
GitHub Copilot performs agentic PR analysis by scanning the diff while pulling in broader repository context. It provides inline comments with severity labels (High, Medium, Low), groups similar comments to reduce noise, and includes one-click fix buttons for many suggestions. Copilot respects repository-level custom instructions defined in .github/copilot-instructions.md. It is designed as a first-pass reviewer handling mechanical and security-focused checks while humans focus on architectural and domain-specific logic (Source: GitHub Blog and GitHub Docs, 2026).
Graphite is a platform for stacked pull requests, a workflow where large features are broken into smaller, sequential, dependent PRs. After its acquisition by Anysphere (the creators of Cursor) in December 2025, Graphite now includes Cursor Cloud Agents for AI-driven code review. Its CLI automates complex rebasing of dependent branches and includes a stack-aware merge queue. The stacked workflow directly addresses the challenge of managing large AI-generated changes by breaking them into reviewable units (Source: Graphite docs and codeant.ai, July 2026).
Run git bisect start, mark the current broken commit as bad and a known working commit as good. Git performs a binary search across the commit history. Automate it with git bisect run followed by your test command (for example, npm test), and git will automatically identify the exact commit that introduced the regression. This only works well if your commits are atomic: one logical change per commit. Bulk AI-generated commits that mix multiple concerns make bisection ineffective because you cannot isolate the specific change that broke the build.
Exclude AI state and session files: .aider.chat.history.md, .aider.input.history, .cursor/ (except .cursor/rules/), .continue/, .copilot/. Exclude sensitive files: .env, .env.*, *.pem, *.key, credentials.json, secrets/. Exclude build artifacts: node_modules/, dist/, build/, .next/. Commit AI configuration files that define project conventions: .cursor/rules/*.mdc, .aider.conf.yml, .aiderignore, CLAUDE.md, .github/copilot-instructions.md, AGENTS.md. The rule is: commit instructions, ignore state.
Conventional Commits is a specification for structured commit messages using a format like feat(scope): description, fix: description, or refactor: description. It matters for AI workflows because it makes commit history machine-readable for automated changelog generation and semantic versioning. Most AI commit message tools (aicommits, OpenCommit, Cursor) can be configured to enforce the Conventional Commits standard, ensuring consistency even when the AI writes the message (Source: conventionalcommits.org spec v1.0.0).
If the AI made an atomic commit, run git revert followed by the commit hash. This creates a new commit that undoes the change while preserving history. In aider, use the /undo command, which runs git revert on the last AI-generated commit. If you need to undo multiple AI commits, revert them in reverse chronological order. If the AI made a single large commit mixing multiple changes, you may need to use git revert --no-commit and then manually unstage the parts you want to keep. This is why atomic commits matter: clean reversion depends on clean separation.
This class completes the professional practices trio. Evals (Class 71) covers output correctness: measuring whether AI-generated content is accurate and faithful. Security (Class 72) covers output safety: ensuring AI-generated code does not introduce exploitable vulnerabilities. Git + AI Workflows (this class) covers output management: tracking, reviewing, and controlling AI-generated code through disciplined version control. Together, the three classes address correctness, safety, and traceability of AI-built software.
Nothing. This masterclass is 100% free. No signup, no email, no paywall, no certificate requirement. It is part of the DDS Vibe Academy, a free AI coding curriculum built by Robert McCullock at Design Delight Studio.
Start with Module 02 of this masterclass to understand the core workflow. Then jump to Module 04: the hands-on build where you install aicommits, generate your first AI commit message, set up a branch-per-ask workflow, and practice reverting an AI-generated change. The entire setup takes under 20 minutes. After that, read Module 05 on AI code review tools to add automated review to your pull requests.
