Resolve Git Merge Conflicts Safely with Claude Code
Use Claude Code to resolve Git conflicts with safe prompts, real workflows, pitfalls, tests, and team rules.
Git conflicts are not just annoying markers in a file. A real conflict usually means two people changed the same business rule, route, schema, dependency, or test expectation at the same time. Removing <<<<<<<, =======, and >>>>>>> is only the visible part. The hard part is preserving intent.
Claude Code is useful here because it can read the conflicted files, inspect nearby code, run Git commands, update tests, and explain the final diff. It is not a replacement for judgment. If you ask it to “fix all conflicts” without context, it may produce code that compiles but loses a security check, duplicates a condition, or silently chooses the wrong branch.
This guide shows the workflow I use in ClaudeCodeLab projects: give Claude Code a clear policy, let it do the mechanical work, then review the diff and tests yourself. The examples are designed to be copy-pasteable, beginner-friendly, and practical for published team projects.
Workflow Map
The safest split is simple: Claude Code owns the edit loop, while you own the policy and final approval.
changes from main or release
|
v
Git reports unmerged files
|
v
Claude Code resolves with a written policy
|
v
human reviews diff, tests, and behavior
|
v
commit the resolved state
For current CLI behavior, the official Claude Code CLI reference documents claude -p "query" for non-interactive prompts. If you automate checks, use the official Claude Code hooks reference and Claude Code settings. On the Git side, Git rerere is the official mechanism for reusing recorded resolutions.
Check State First
Before calling Claude Code, freeze the situation in your own head. This prevents unrelated local edits from being mixed into a conflict-resolution commit.
git status --short
git branch --show-current
git diff --name-only --diff-filter=U
The last command lists only unmerged files. Read that list once yourself. If it contains a file you did not expect, stop and understand why before asking Claude Code to edit.
Give Claude Code four pieces of context:
| Question | Example policy |
|---|---|
| Which side has priority? | Keep main security fixes and keep feature UI work |
| What can be edited? | Only unresolved files and directly related tests |
| How are generated files handled? | Regenerate lockfiles and generated code instead of hand-merging |
| What is done? | No conflict markers, clean diff check, passing tests, summary of decisions |
This tiny policy is the difference between “AI guessed” and “AI followed a reviewable plan.”
Use Case 1: Merge Main into a Feature Branch
This is the most common conflict: a feature branch drifted from main, and now you need to catch up before opening or updating a pull request.
git fetch origin
git merge origin/main
cat > /tmp/claude-conflict-plan.md <<'PROMPT'
Resolve the current Git merge conflicts.
Context:
- The current branch is a feature branch.
- Keep security fixes and type changes from origin/main.
- Keep the new screen, API call, and tests from the feature branch.
- Target only files reported by git diff --name-only --diff-filter=U.
Tasks:
1. Inspect why each file conflicts.
2. Remove conflict markers and integrate both intents.
3. Update only directly related tests if needed.
4. Run git diff --check.
5. Summarize decisions and commands run.
Do not:
- Perform unrelated refactors.
- Silently discard either side.
- Hand-edit package-lock.json.
PROMPT
claude -p "$(cat /tmp/claude-conflict-plan.md)"
git diff --check
npm test
The important part is not the exact wording. The important part is that priority, scope, generated-file policy, and completion criteria are explicit.
A real failure I have seen: main added a stricter authorization check while the feature branch added a new UI branch. A vague “preserve both” prompt kept the UI visible but left the API path returning 403. Since then I always tell Claude Code which security and authorization changes must survive and ask it to check UI/API consistency.
Use Case 2: Resolve Rebase Conflicts One Commit at a Time
Rebase conflicts are more delicate than merge conflicts because Git pauses at each commit. The meaning of ours and theirs can also feel inverted during rebase, so do not blindly run git checkout --ours or git checkout --theirs unless you know exactly what Git is showing.
git rebase origin/main
cat > /tmp/claude-rebase-step.md <<'PROMPT'
Resolve only the current conflict during this rebase.
Please:
- Confirm this is a rebase state with git status.
- List unresolved files with git diff --name-only --diff-filter=U.
- Infer the intent of the commit being replayed from recent git log output.
- Integrate the replayed commit with the current main branch behavior.
Constraints:
- Do not run git rebase --continue.
- Stop after resolving files and staging them with git add.
- Do not edit unrelated files.
- If a choice is ambiguous, explain the options instead of guessing.
PROMPT
claude -p "$(cat /tmp/claude-rebase-step.md)"
git diff --check
npm test
git rebase --continue
You can ask Claude Code to continue the rebase automatically, but beginners should pause after each step. Rebase rewrites the branch history, and a bad automatic resolution is harder to understand once several commits have passed.
Use Case 3: Regenerate Lockfiles and Generated Code
Lockfiles and generated code are poor candidates for manual conflict editing. Resolve the source file first, then regenerate.
git diff --name-only --diff-filter=U
cat > /tmp/claude-lockfile-policy.md <<'PROMPT'
Resolve lockfile or generated-file conflicts.
Policy:
- Resolve human-authored source files first, such as package.json.
- Do not hand-merge package-lock.json.
- After dependencies are decided, regenerate with npm install.
- For generated code, resolve the schema or OpenAPI source first, then regenerate.
- Explain why the regenerated diff is expected.
Allowed checks:
- npm install
- npm test
- npm run lint
PROMPT
claude -p "$(cat /tmp/claude-lockfile-policy.md)"
npm install
npm test
git add package.json package-lock.json
The common pitfall is keeping both dependencies in package.json but taking only one side of package-lock.json. That may work locally for one developer and fail in CI. Make “source first, generated output second” a written rule.
Use Case 4: Analyze Why the Conflict Happened
Conflict resolution is also a chance to improve team workflow. Repeated conflicts in route registries, permission maps, schemas, and dependency files usually mean the project needs a smaller ownership boundary.
cat > /tmp/claude-conflict-retro.md <<'PROMPT'
Analyze why this Git conflict happened.
Investigate:
- List unresolved files with git diff --name-only --diff-filter=U.
- Use git log --oneline --all -- <file> to inspect both branches.
- Classify whether this was shared ownership, oversized PR, generated file churn, or missing project rule.
Output:
- Three-line cause summary.
- Rules to add to CLAUDE.md.
- Whether PR splitting, owner coordination, or extra tests would help most.
PROMPT
claude -p "$(cat /tmp/claude-conflict-retro.md)"
For example, if src/routes.ts conflicts every week, the fix may be to split route registration by feature. If package.json conflicts constantly, dependency changes may need separate pull requests. Claude Code can point out those patterns because it can inspect Git history and nearby files quickly.
Copy-Paste Conflict Audit Script
After Claude Code edits files, run a mechanical audit. This Node.js script has no external dependencies.
// scripts/conflict-audit.mjs
import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
const output = execFileSync("git", ["diff", "--name-only", "--diff-filter=U"], {
encoding: "utf8",
}).trim();
const files = output ? output.split(/\r?\n/) : [];
if (files.length === 0) {
console.log("No unmerged files reported by git.");
}
let markerCount = 0;
for (const file of files) {
const body = readFileSync(file, "utf8");
const matches = body.match(/^(<<<<<<<|=======|>>>>>>>) /gm) ?? [];
if (matches.length > 0) {
markerCount += matches.length;
console.log(`${file}: ${matches.length} conflict markers`);
}
}
if (markerCount > 0) {
process.exitCode = 1;
}
Run it with the checks your project already trusts:
node scripts/conflict-audit.mjs
git diff --check
npm test
Add npm run typecheck, npm run lint, or E2E tests when the conflicted area touches contracts, routing, billing, or authorization.
Prevent Repeat Conflicts
Claude Code hooks can run deterministic checks after tool use. For a deeper setup guide, see the internal Claude Code Hooks Guide.
{
"hooks": {
"PostToolUse": [
{
"matcher": "Bash(git merge*)|Bash(git rebase*)",
"hooks": [
{
"type": "command",
"command": "git diff --check && npm test"
}
]
}
]
}
}
Also put conflict policy in CLAUDE.md, which acts as project memory for Claude Code. The internal CLAUDE.md Best Practices and Team Collaboration Guide explain how to structure those rules.
## Git conflict policy
- Preserve security fixes, authorization checks, and data-loss prevention by default.
- Check UI, API, schema, and tests together.
- Regenerate package-lock.json, pnpm-lock.yaml, and generated code instead of hand-editing.
- During rebase, humans review the diff before git rebase --continue.
- If the correct choice is unclear, present options instead of discarding one side.
Pitfalls to Watch
First, do not memorize ours and theirs as permanent labels. During rebase they can surprise you. Inspect git status and the diff before accepting a side.
Second, “keep both” is not always correct. Two validation blocks, two redirects, or two feature flags can create duplicate behavior. Ask Claude Code to merge duplicated responsibility into one clear path.
Third, tests are necessary but not sufficient. If the conflict touches authentication, billing, migrations, or destructive data operations, add manual review and scenario checks.
Fourth, keep refactoring out of the conflict commit. Reviewers need to understand the resolution, not a naming cleanup that happened at the same time.
Hands-On Result
In a TypeScript project with roughly 15 conflicted files, a vague prompt fixed syntax but missed a related test update. With the policy used in this article, Claude Code produced a smaller diff, explained the decisions, and made review faster. The lesson was clear: Claude Code is strong at the edit loop, but the final git diff, test output, and product judgment still belong to the developer.
Start with a small feature branch: list unresolved files, give Claude Code a policy, run tests, and review the diff. Once the workflow feels reliable, move the repeated rules into hooks and CLAUDE.md so conflict resolution becomes a repeatable team process instead of a stressful one-off task.
Free PDF: Claude Code Cheatsheet
Enter your email and download the one-page Claude Code cheatsheet for commands, review habits, and safe workflows.
We handle your data with care and never send spam.
Level up your Claude Code workflow
Start with the free PDF, use Gumroad guides when you need repeatable workflows, and book consultation when rollout or revenue paths need human judgment.
About the Author
Masa
Engineer focused on practical Claude Code workflows. Runs claudecode-lab.com, a 10-language technical media site.
Related Posts
Claude Code Harness Smoke Test: A 15-Minute Proof Loop Before You Trust an Agent
A practical Claude Code smoke test for scope, blocked areas, proof commands, public URLs, and revenue CTAs.
Claude Code Permission Safety Ladder: Expand Access Without Losing Control
A beginner-friendly ladder for moving Claude Code from read-only to limited edits, proof commands, and deploy checks.
Claude Code Small PR Proof Pack: Make Tiny Changes Reviewable
A practical proof pack for Claude Code PRs: diff, checks, public URL, CTA path, and rollback note.
Related Products
50 Battle-Tested Claude Code Prompt Templates
Copy, paste, ship. 50 production-ready prompts.
Use proven prompts for code review, refactoring, testing, documentation, debugging, architecture, and incident response.
The Complete Claude Code Setup & Configuration Guide
From install to team-ready workflow.
A practical guide to installation, CLAUDE.md, hooks, MCP servers, permissions, IDE setup, and CI/CD workflows.