Skip to content

The Edge of the Cyber World See the latest

Apps

Cursor AI Code Editor Conflicts: 13 Steps, 55 Min [2026]

Every team that lets the Cursor AI code editor touch shared files eventually hits the same Friday afternoon problem. The agent finishes a ten-line change, the diff view shows sixty changed lines, and a teammate’s pull request against the same file now refuses to merge. Nothing is wrong with the logic. The edit simply moved too much text.

Cost gets most of the attention in the rewrite-versus-diff debate. Cursor’s own Composer 2.5 model, released May 18, 2026, is priced per token, and one pricing tracker lists it at $0.50 per million input tokens and $2.50 per million output tokens. A full-file rewrite sends and generates more tokens than a targeted edit, so it costs more. But the dollar gap is tiny. The real price of a noisy rewrite is the merge conflict it creates for the next human who touches the file.

Existing tutorials score how big an edit is, such as the edit risk scanner on this site. This one asks a different question: will the edit merge? It measures that second price. You will build a small lab repository with three edit shapes, write a Python script that rehearses each merge with git merge-tree without touching your working tree, and then wire the check into a pre-push hook, a Cursor rule and a CI job. The whole project is a short exercise you can run on one machine. By the end you will have a number for the question that matters: how many conflict hunks does this AI edit hand to my teammates?

One honest limit up front. Cursor does not publish a per-edit switch between rewriting a file and applying a patch, and the sources reviewed for this article describe billing by tokens, not by edit type. So the lab does not try to reverse-engineer Cursor. It tests the output that lands in your repository, which is the only thing Git and your teammates ever see.

Why the Cursor AI Code Editor Can Break a Teammate’s Branch

Git merges by comparing three versions of a file: the common ancestor, your branch and their branch. It works hunk by hunk. If your branch changed lines 40 to 45 and theirs changed lines 10 to 12, the merge is clean. If both touched the same lines, or lines that sit next to each other, Git stops and asks a human to decide.

A targeted edit leaves most of the file byte-for-byte identical to the ancestor, so the changed region is small and the chance of overlap is small. A rewrite that re-emits the whole file can change quote styles, import order, blank lines, function order and trailing whitespace on lines nobody asked it to touch. Each of those lines becomes a hunk that can overlap with someone else’s work.

The pattern is easy to miss during review. In the editor, the AI’s change looks small because you read the intent, which is one function. Git reads the bytes. When a model hands back a whole file, the intent and the bytes can drift far apart. A reviewer who only checks the logic will approve a change that rewrites the formatting of an entire module.

Teams that already audit AI edits usually do it after the fact. A risk scanner scores a change by how much it moved, and differential testing of Cursor rewrites checks that behavior survived. Both answer “is this change safe in isolation.” Neither answers “will this change collide with the branch my colleague pushed an hour ago.” That is the gap this project fills.

The practical fix is to treat the Cursor AI code editor as one more author on the team. Human authors get a code review, a branch name and a merge check. An agent that writes into the same files deserves the same treatment, and the merge check is the cheapest of the three to automate. Run git diff --stat before you accept any agent run, and you will spot most noisy edits in about five seconds, because the stat line is far larger than the task you described.

Three terms keep the rest of the article tidy. A hunk is one contiguous block of changed lines. A conflict hunk is a hunk Git could not merge on its own and wrapped in conflict markers. The target is the branch you rehearse against, usually the integration branch or a teammate’s open branch.

Prerequisites and Versions

Everything here runs on a laptop. You do not need a Cursor subscription to follow the lab, because the three edit shapes are generated by a script. You do need one if you want to repeat the experiment with real agent output in Step 10, and the Advanced Tips section explains how.

Requirement Version used Why it matters
Git Not listed git merge-tree --write-tree arrived in 2.38 and does the merge in memory
Python 3.12.3 (3.9 or newer works) Runs the lab builder and the rehearsal script, standard library only
Shell POSIX sh or bash Runs the hook and the one-command runner
Cursor Current desktop build with Composer 2.5 Optional, only for the real-agent comparison in Step 10
Disk Under 1 MB The lab repo is a one-file toy repo with a handful of branches
Time Not listed Most of it is reading the outputs, not typing

Check your Git version before anything else. Older releases print usage: git merge-tree and exit, which looks like a bug in the script but is not.

git --version
python3 --version

Expected output on the test machine was git version 2.43.0 and Python 3.12.3. If Git reports a version below 2.38, upgrade it first. The script relies on the newer merge engine and has no fallback, because the old three-argument form cannot report conflict markers the same way.

Create a working folder and keep everything inside it. The lab builder deletes and recreates its lab-repo directory on every run, so never point it at a repository you care about.

mkdir conflict-lab && cd conflict-lab

Three Edit Shapes: Diff, Faithful Rewrite and Noisy Rewrite

The lab compares three ways an AI edit can land in Git. They produce the same behavior, which is the point. Only the bytes differ.

  • Targeted diff. Only the lines the task needs change. In the lab that is 7 added and 5 removed lines.
  • Faithful rewrite. The whole file is re-emitted, but every line the task did not need comes back unchanged. Git cannot tell this from a targeted diff, because Git stores the final bytes and not the method.
  • Noisy rewrite. The whole file is re-emitted with flipped quote styles, reordered imports and alphabetized functions. In the lab that is 32 added and 30 removed lines for the same logical change.

The task given to all three is the same: make sales tax depend on a region code instead of one flat rate. It touches a constant, one function signature and one call site. A reviewer would call it a ten-line change.

What Cursor documents about its own model

Cursor describes Composer 2.5 as its own agentic model, built on Composer 2, with better effort calibration and tool selection for long tasks. Its product page says the fast variant returns edits and tool results quickly while handling file edits, terminal commands and multi-file changes inside the editor. That is a statement about speed and capability. It is not a promise about how many unrelated lines an edit will touch.

The same sources show Composer 2.5 became the default Composer model while Composer 2 stays selectable, according to the same pricing tracker. For this tutorial the model choice matters less than the habit of measuring what any model leaves behind.

What this lab actually tests

The rehearsal script looks only at Git objects. It asks three questions about each branch: how many lines changed against the common ancestor, whether it merges cleanly into the target, and how many conflict hunks appear if it does not. If you later paste in real output from an agent, the script treats it exactly like the simulated branches. You can fuzz Cursor-style edits the same way to see how often each shape misbehaves on a larger corpus.

A noise ratio falls out of the numbers for free. The noisy rewrite changed 62 lines (32 added plus 30 removed) while the targeted diff changed 12. That is a ratio of about 5 to 1 for an identical feature.

Steps 1 to 3: Create the Conflict Lab

Step 1. Write the builder. Save the following as make_lab.py. It creates a throwaway repository, commits a small checkout module as the base, and then creates five branches from it. Read the three helper functions near the middle: ai_change is the logical edit every AI branch must contain, and noisy_rewrite applies the same edit while also flipping quotes, reordering imports and sorting functions.

#!/usr/bin/env python3
"""Build a throwaway repo with three branches that simulate edit shapes."""
import pathlib, re, shutil, subprocess, sys

LAB = pathlib.Path("lab-repo")

BASE = '''import json
import os
from decimal import Decimal

TAX_RATE = Decimal('0.08')
FREE_SHIPPING_OVER = Decimal('75.00')


def load_cart(path):
    with open(path) as fh:
        return json.load(fh)


def subtotal(cart):
    return sum(Decimal(str(i['price'])) * i['qty'] for i in cart['items'])


def apply_discount(total, code):
    if code == 'SAVE10':
        return total * Decimal('0.90')
    if code == 'SAVE20':
        return total * Decimal('0.80')
    return total


def shipping_cost(total):
    if total >= FREE_SHIPPING_OVER:
        return Decimal('0.00')
    return Decimal('6.50')


def calculate_tax(total):
    return (total * TAX_RATE).quantize(Decimal('0.01'))


def format_money(value):
    return '$' + str(value.quantize(Decimal('0.01')))


def checkout(path, code=None):
    cart = load_cart(path)
    total = apply_discount(subtotal(cart), code)
    total += shipping_cost(total)
    total += calculate_tax(total)
    return format_money(total)


if __name__ == '__main__':
    print(checkout(os.environ.get('CART', 'cart.json')))
'''

def git(*args, check=True):
    return subprocess.run(["git", *args], cwd=LAB, check=check,
                          capture_output=True, text=True).stdout.strip()

def write(text):
    (LAB / "orders.py").write_text(text)

def commit(msg):
    git("add", "-A")
    git("commit", "-q", "-m", msg)

def ai_change(text):
    # The task given to the AI: make tax depend on a region.
    text = text.replace("TAX_RATE = Decimal('0.08')",
                        "TAX_RATES = {'CA': Decimal('0.0725'), 'NY': Decimal('0.04')}nDEFAULT_TAX = Decimal('0.08')")
    text = text.replace("def calculate_tax(total):n    return (total * TAX_RATE)",
                        "def calculate_tax(total, region=None):n    rate = TAX_RATES.get(region, DEFAULT_TAX)n    return (total * rate)")
    return text.replace("total += calculate_tax(total)", "total += calculate_tax(total, region)") 
               .replace("def checkout(path, code=None):", "def checkout(path, code=None, region=None):")

def noisy_rewrite(text):
    # Same logic change, but the file is re-emitted: quotes flipped,
    # functions sorted, imports re-ordered. Typical "whole file" output.
    text = ai_change(text).replace("'", '"')
    head, *funcs = re.split(r"nnn(?=def )", text)
    tail = ""
    if "if __name__" in funcs[-1]:
        funcs[-1], tail = funcs[-1].split("nnnif __name__", 1)
        tail = "nnnif __name__" + tail
    funcs.sort(key=lambda f: re.match(r"def (w+)", f).group(1))
    head = head.replace("import jsonnimport osn", "import osnimport jsonn")
    return head + "nnn" + "nnn".join(funcs) + tail

def main():
    if LAB.exists():
        shutil.rmtree(LAB)
    LAB.mkdir()
    git("init", "-q", "-b", "main")
    git("config", "user.email", "lab@example.com")
    git("config", "user.name", "Lab")
    write(BASE); commit("base: checkout module")

    # Teammate: touches shipping and discounts, far from the tax code.
    git("checkout", "-q", "-b", "teammate", "main")
    t = BASE.replace("return Decimal('6.50')", "return Decimal('5.95')") 
            .replace("if code == 'SAVE20':", "if code == 'SAVE25':") 
            .replace("Decimal('0.80')", "Decimal('0.75')")
    write(t); commit("teammate: shipping and promo tweaks")

    # Second teammate branch: edits the constant sitting right next to the tax line.
    git("checkout", "-q", "-b", "teammate-adjacent", "main")
    write(BASE.replace("FREE_SHIPPING_OVER = Decimal('75.00')", "FREE_SHIPPING_OVER = Decimal('60.00')"))
    commit("teammate: lower free-shipping threshold")

    # 1) Minimal diff edit
    git("checkout", "-q", "-b", "ai-diff", "main")
    write(ai_change(BASE)); commit("ai: regional tax (targeted edit)")

    # 2) Whole-file rewrite that preserves everything it was not asked to change
    git("checkout", "-q", "-b", "ai-rewrite-faithful", "main")
    write(ai_change(BASE)); commit("ai: regional tax (faithful rewrite)")

    # 3) Whole-file rewrite with unrequested formatting and ordering changes
    git("checkout", "-q", "-b", "ai-rewrite-noisy", "main")
    write(noisy_rewrite(BASE)); commit("ai: regional tax (noisy rewrite)")

    git("checkout", "-q", "main")
    print("lab ready:", LAB.resolve(), file=sys.stderr)

if __name__ == "__main__":
    main()

Step 2. Run it. The script prints one line to stderr when it finishes. The branches it creates are teammate, teammate-adjacent, ai-diff, ai-rewrite-faithful and ai-rewrite-noisy, plus main.

python3 make_lab.py
cd lab-repo
git branch

Expected output:

lab ready: /home/you/conflict-lab/lab-repo
  ai-diff
  ai-rewrite-faithful
  ai-rewrite-noisy
* main
  teammate
  teammate-adjacent

Step 3. Compare the diff sizes by eye. Before any merge logic, look at what each AI branch changed against main. This is the view a code reviewer sees in the editor, and it already tells the story.

git diff --stat main ai-diff
git diff --stat main ai-rewrite-noisy
 orders.py | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)

 orders.py | 62 ++++++++++++++++++++++++++++++++------------------------------
 1 file changed, 32 insertions(+), 30 deletions(-)

Same file, same feature, five times the churn. Notice that the stat view hides the real problem. It shows how much changed but not where, and conflicts depend on where.

The teammate branch edits the shipping price and the promo code table. Those lines sit well away from the tax constant. The teammate-adjacent branch edits the free-shipping threshold, which sits on the line directly under the tax constant. You will need both in Steps 9 and 10.

Steps 4 to 6: Write the Merge Rehearsal Script

Step 4. Understand the command. git merge-tree --write-tree performs a full three-way merge entirely inside Git’s object database. It never touches your index or your working directory, so it is safe to run while you have uncommitted work. It prints the OID of the resulting tree on the first line. If the merge conflicts, it exits with status 1 and the resulting tree contains the conflicted files with markers already written into them.

Step 5. Count hunks from the conflicted blobs. Git tells you which files conflicted but not how many separate collisions each file holds. The script reads each conflicted file out of the result tree with git cat-file -p TREE:path and counts the conflict-start markers, each a run of seven less-than signs. One marker means one hunk. That count is the number a human will have to resolve by hand.

Step 6. Save the script. Put the following in rehearse.py next to make_lab.py. It uses only the standard library. It computes the merge base itself, so you do not have to name an ancestor, and it exits non-zero when any branch exceeds the hunk budget, which is what lets the hook and CI job in later steps fail a push.

#!/usr/bin/env python3
"""Rehearse merging an AI branch into a moving target without touching the worktree."""
import argparse, json, subprocess, sys

def git(repo, *args):
    return subprocess.run(["git", "-C", repo, *args], capture_output=True, text=True)

def numstat(repo, base, branch):
    out = git(repo, "diff", "--numstat", base, branch).stdout
    added = removed = 0
    for line in out.splitlines():
        a, r, _ = line.split("t", 2)
        if a != "-":
            added, removed = added + int(a), removed + int(r)
    return added, removed

def rehearse(repo, target, branch):
    res = git(repo, "merge-tree", "--write-tree", "--name-only", target, branch)
    lines = res.stdout.splitlines()
    tree = lines[0] if lines else ""
    files = []
    for line in lines[1:]:
        if not line.strip():
            break
        files.append(line.strip())
    hunks = 0
    for path in files:
        blob = git(repo, "cat-file", "-p", f"{tree}:{path}").stdout
        hunks += blob.count("<<<<<<<")
    return {"clean": res.returncode == 0, "files": files, "hunks": hunks}

def main():
    p = argparse.ArgumentParser()
    p.add_argument("--repo", default=".")
    p.add_argument("--base", default=None, help="defaults to merge-base with target")
    p.add_argument("--target", default="teammate")
    p.add_argument("--max-hunks", type=int, default=0)
    p.add_argument("--json", action="store_true")
    p.add_argument("branches", nargs="+")
    a = p.parse_args()

    rows = []
    for b in a.branches:
        base = a.base or git(a.repo, "merge-base", a.target, b).stdout.strip()
        add, rem = numstat(a.repo, base, b)
        r = rehearse(a.repo, a.target, b)
        rows.append({"branch": b, "added": add, "removed": rem, **r})

    if a.json:
        print(json.dumps(rows, indent=2))
    else:
        print(f"{'branch':<22}{'+/-':<10}{'merge':<10}{'hunks':<7}files")
        for r in rows:
            state = "clean" if r["clean"] else "CONFLICT"
            print(f"{r['branch']:<22}{str(r['added'])+'/'+str(r['removed']):<10}"
                  f"{state:<10}{r['hunks']:<7}{', '.join(r['files']) or '-'}")

    worst = max(r["hunks"] for r in rows)
    sys.exit(1 if worst > a.max_hunks else 0)

if __name__ == "__main__":
    main()

Three design choices deserve a comment. First, the script runs every Git command with git -C repo so it works from any directory. Second, --max-hunks defaults to zero, because the interesting policy for shared files is “no conflicts at all,” and teams can loosen it per repository. Third, the --json flag exists for machines. A human table for the terminal and JSON for CI come from the same data.

If you want a deeper test of the same idea, add a seeded generator that mutates a file thousands of times and rehearses each mutant, as in the fuzzing walkthrough mentioned earlier. Here, three hand-built branches are enough to show the effect.

Steps 7 and 8: Run the Rehearsal and Read the Results

Step 7. Rehearse all three AI branches against the teammate. From inside lab-repo, run the script with the teammate branch as the target.

python3 ../rehearse.py --target teammate ai-diff ai-rewrite-faithful ai-rewrite-noisy
echo "exit=$?"

Output from the test run:

branch                +/-       merge     hunks  files
ai-diff               7/5       clean     0      -
ai-rewrite-faithful   7/5       clean     0      -
ai-rewrite-noisy      32/30     CONFLICT  1      orders.py
exit=1

Step 8. Read the table. The targeted diff and the faithful rewrite both merge cleanly, because their changed lines never overlap the teammate’s. The noisy rewrite fails with a conflict even though its logic never touches shipping or promo codes. The cause is the sorted function order. Alphabetizing moved apply_discount and shipping_cost relative to their neighbors, and those are exactly the functions the teammate edited, so Git saw two incompatible rewrites of the same region.

Branch Lines changed vs base Merge into teammate Conflict hunks Cause
ai-diff 12 (7 added, 5 removed) Clean 0 Edits stay near the tax constant and checkout call
ai-rewrite-faithful 12 (7 added, 5 removed) Clean 0 Identical bytes to the diff, so identical result
ai-rewrite-noisy 62 (32 added, 30 removed) Conflict 1 Sorted functions moved the code the teammate edited

The faithful rewrite row is the most useful one in the table. It proves that a full-file rewrite is not the villain. A model that re-emits a whole file and preserves every untouched byte is as safe as a patch. The villain is unrequested change, and rewriting is simply the easiest way for unrequested change to sneak in.

To see the collision itself, ask Git for the merged tree and print the file. The conflict markers show exactly which lines both sides claimed.

TREE=$(git merge-tree --write-tree teammate ai-rewrite-noisy | head -1)
git cat-file -p "$TREE:orders.py" | grep -n -A8 '<<<<<<<'

Reading the conflict markers

Here is what the command printed on the test machine. The first conflict marker sits at line 40 of the merged file:

39-
40:<<<<<<< teammate
41-def subtotal(cart):
42-    return sum(Decimal(str(i['price'])) * i['qty'] for i in cart['items'])
43-
44-
45-def apply_discount(total, code):
46-    if code == 'SAVE10':
47-        return total * Decimal('0.90')
48-    if code == 'SAVE25':
49-        return total * Decimal('0.75')
50-    return total
51-
52-
53-def shipping_cost(total):
54-    if total >= FREE_SHIPPING_OVER:

The top half of the pair is the teammate’s copy of the region. It keeps the original function order, the single-quote style and the new SAVE25 promo code. The bottom half, past the divider line, carries the AI’s alphabetized, double-quoted copy of the same code. A person resolving this has to merge two versions of functions that neither side meant to change together, and the only real edit in the whole region is the teammate’s promo code. That is wasted attention, and it is what the noise ratio measures.

You will see the teammate’s version of the shipping block on one side of the markers and the AI’s reordered version on the other. Nothing in that block has anything to do with sales tax, which is the clearest possible evidence of an edit that exceeded its mandate.

Steps 9 and 10: Trigger the Adjacent-Line Trap

Step 9. Rehearse against the adjacent teammate. A clean result in Step 7 is not proof that small edits are always safe. Run the same script against the branch that changed the line right under the tax constant.

python3 ../rehearse.py --target teammate-adjacent ai-diff ai-rewrite-noisy
echo "exit=$?"
branch                +/-       merge     hunks  files
ai-diff               7/5       CONFLICT  1      orders.py
ai-rewrite-noisy      32/30     CONFLICT  1      orders.py
exit=1

Now the minimal diff conflicts too. Git treats changes on adjacent lines as overlapping, because it cannot know whether the two edits are compatible. The teammate lowered the free-shipping threshold on line 6, and the AI replaced the tax constant on line 5. With no unchanged line between them, Git refuses to guess.

This result is worth keeping in your head, because it changes what “minimal” means. A small diff is safer on average, but a small diff in a hot spot loses to a large diff in a quiet corner. Hot spots are lines that several people change often: constants blocks, import lists, enum members, route tables and changelog files. The rehearsal catches them, and a quick look at the Git diff algorithms and how they present AI rewrites explains why the markers can look larger than the real overlap.

Step 10. Replace the simulation with real agent output. Create a branch from main, open the folder in Cursor, and give the agent the same task in plain words: make sales tax depend on a region code, defaulting to the current rate. Accept the change, commit it to a branch named ai-real, then rehearse it.

git checkout -q -b ai-real main
# ... let the Cursor agent edit orders.py, review, then:
git add -A && git commit -q -m "ai: regional tax (real agent)"
python3 ../rehearse.py --target teammate ai-real
python3 ../rehearse.py --target teammate-adjacent ai-real

Run it five or six times with different prompts and models if you can, and keep the table. The numbers will vary. A prompt that says “change only what is needed and keep the file layout” tends to land closer to the faithful rewrite than a vague one. That is a claim about prompting, not about Cursor internals, and the table will tell you whether it holds on your code.

Steps 11 and 12: Add a Pre-Push Hook and a Cursor Rule

Step 11. Install the hook. A rehearsal nobody runs is just a script. The pre-push hook makes it automatic. Git runs the hook just before a push leaves your machine, and a non-zero exit stops the push.

#!/bin/sh
# Rehearse the merge against the integration branch before pushing.
TARGET="${REHEARSE_TARGET:-origin/main}"
MAX="${REHEARSE_MAX_HUNKS:-0}"
python3 "$(git rev-parse --show-toplevel)/../rehearse.py" --repo . --target "$TARGET" --max-hunks "$MAX" HEAD || {
  echo "pre-push: merge rehearsal against $TARGET found conflicts. Ask the agent to redo the edit as a minimal diff." >&2
  exit 1
}

Install it in your real project by copying the file into .git/hooks/ and making it executable. Adjust the path to rehearse.py to wherever you keep tools in the repository. The hook reads two environment variables, so you can point it at a different branch or loosen the budget without editing the file.

cp hooks/pre-push .git/hooks/pre-push
chmod +x .git/hooks/pre-push
REHEARSE_TARGET=teammate .git/hooks/pre-push

The test run on the noisy branch printed the table followed by a plain instruction, then exited with status 1. On the targeted diff branch it printed a clean table and exited with 0.

branch                +/-       merge     hunks  files
HEAD                  32/30     CONFLICT  1      orders.py
pre-push: merge rehearsal against teammate found conflicts. Ask the agent to redo the edit as a minimal diff.
hook exit=1

Step 12. Prevent the problem at the source with a rule. A hook catches damage after the fact. A project rule asks the agent not to cause it. Cursor reads rule files from .cursor/rules, and a rule marked as always applied goes into every request. Save this as .cursor/rules/minimal-edits.mdc:

---
description: Keep edits minimal so teammates' branches still merge
alwaysApply: true
---

- Change only the lines the task requires. Do not reorder functions or imports.
- Keep the existing quote style, line endings, indentation and blank-line layout.
- Do not run a formatter over a whole file unless the task says so.
- If a file needs a full rewrite, say so first and list what will move.

Each line of the rule targets one source of noise. The first stops reordering, which caused the conflict in the lab. The second protects style choices such as quotes and indentation that a model may normalize without being asked. The third blocks a formatter pass, which is the other common way a faithful edit turns noisy. The fourth gives the agent a way out when a full rewrite really is the right call: it must announce the rewrite and list what will move, so you can warn the team before the push.

Pair the two. The rule lowers the chance of a noisy edit, and the hook guarantees that any noisy edit that slips through never reaches the remote. If you want to tune how the rule steers edit style in more detail, the Cursor rules configuration guide covers the options. Teams that prefer a size cap to a conflict check can use the GitHub diff budget gate alongside this one, since a size cap and a conflict rehearsal catch different failures.

Rules are advice, not enforcement. A model can still ignore one under a long prompt or a crowded context. That is why the hook stays in place even after the rule is working well.

Step 13: Run the Rehearsal in CI

Step 13. Add the job. The hook protects one developer’s machine. CI protects the repository. The workflow below checks out the full history, fetches the branch you want to protect and rehearses the pull request against it. It prints JSON for the log and a one-line summary at the end.

name: merge-rehearsal
on:
  pull_request:
    branches: [main]

jobs:
  rehearse:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - name: Rehearse against the release branch
        run: |
          git fetch origin release
          python3 tools/rehearse.py --target origin/release --max-hunks 0 --json HEAD | tee rehearsal.json
      - name: Summarise
        if: always()
        run: python3 -c "import json;r=json.load(open('rehearsal.json'))[0];print('clean' if r['clean'] else 'conflicts in '+', '.join(r['files']))"

Two details matter. The checkout needs fetch-depth: 0, because the merge base lives in history that a shallow clone does not have. And the rehearsal step must run before the summary, with the summary marked if: always(), so a failed rehearsal still produces a readable line in the job output.

Choose the target on purpose. Rehearsing against the main branch only repeats what the pull request check already does. The value comes from rehearsing against branches that will merge later: a release branch, a long-running feature branch, or the two or three open pull requests that touch the same directory. A small matrix over those targets turns a surprise conflict next week into a red check today.

Keep the job fast. A rehearsal against one branch finishes in well under a second on a normal repository, because it merges in memory and reads only the conflicted blobs. If your repository is large, limit the rehearsal to files the pull request changed by checking git diff --name-only first.

What a Conflict Costs in Composer 2.5 Tokens

Conflicts cost time first and tokens second. Still, the token side is easy to model, and the numbers help when someone asks whether the rule and hook are worth the setup.

Composer 2.5 lists standard rates of $0.50 per million input tokens, $0.20 per million cached-input tokens and $2.50 per million output tokens. The fast variant lists $3.00 input and $15.00 output, and Cursor’s product page says fast is the default in the product. A forum report also says Composer 2.5 uses its own token prices and should not be costed at generic fast-model rates. Cursor’s release notes add that Composer 2.5 subagents now run and bill at whichever speed you select.

The table below uses two assumptions that are mine, not Cursor’s. A line of code averages about 12 tokens, and a targeted edit touches about 30 lines. Change them to match your language and style. The arithmetic is output tokens multiplied by the output rate.

Scenario Output tokens Standard ($2.50/M) Fast ($15/M)
Targeted edit, 30 lines Not listed Not listed Not listed
Full rewrite of a whole file Not listed Not listed Not listed
Same rewrite, redone after a conflict Not listed Not listed Not listed
40 conflicted rewrites in a month Not listed Not listed Not listed

Read the last row carefully. Forty conflicted rewrites in a month cost less than $3 in standard output tokens, and less than $18 on fast. Input tokens add more, since the agent reads the file again each time, but the order of magnitude stays small. Nobody should pay for a hook to save $3.

What the hook saves is the human side. If resolving one conflict takes a developer ten minutes and a team hits forty, that is nearly seven hours a month. Trackers such as ModelPlan and DIY AI list both current and legacy Cursor plans side by side, which shows how often plan rules and usage limits change, so treat any per-token figure as a snapshot. Cursor has also said, reportedly, that included usage is counted by each model’s cost and not by raw token count, so the number of tokens a plan covers depends on the model you pick.

If you want a full break-even model for the token side, with a sweep across file sizes and edit shapes, the diff versus rewrite break-even tutorial builds one. For spending limits that stop a runaway session, see the Composer cost guardrail setup. This article’s point is narrower. Even when tokens are cheap, a conflict is expensive, so the rehearsal belongs in the workflow.

Common Pitfalls

These six mistakes account for most of the confusing results people get when they first run this project.

  1. Rehearsing against the wrong target. If you rehearse against main but your teammate’s work lives on a feature branch, the table says “clean” and the conflict arrives anyway. Name the branch that will merge next, not the branch that is easiest to type.
  2. Trusting line counts alone. A 12-line diff can conflict and a 62-line diff can merge, depending on location. Use the merge result as the verdict and the line count only as a hint.
  3. Forgetting the adjacent-line rule. Two edits one line apart conflict. If a change touches a constants block, an import list or a route table, rehearse it even when it is tiny.
  4. Running an old Git. Anything below 2.38 does not support --write-tree, and the failure message looks like a usage error. Check the version first.
  5. Letting a formatter run over the AI’s edit. Format-on-save in the editor can turn a faithful edit into a noisy one after the agent finishes. Disable format-on-save for the rehearsal, or format the whole file in a separate commit first.
  6. Treating the rule as enforcement. A rule in .cursor/rules shapes the request. It does not guarantee the result. Keep the hook and the CI job, and expect an occasional miss. When the agent’s search-and-replace edits fail outright, the failed edits and healing tutorial covers a different failure that can masquerade as a rewrite.

A seventh habit helps beyond these. Keep the lab around. When someone claims a new model “edits more precisely,” rerun the rehearsal with the new model’s output and compare the noise ratio. The claim either survives the table or it does not.

Troubleshooting

When something fails, match the symptom below.

  1. usage: git merge-tree printed and nothing else. Your Git is older than 2.38. Upgrade, then rerun.
  2. fatal: not a git repository. You ran the script outside the lab repo without --repo. Either cd lab-repo or pass --repo path.
  3. The table shows clean for every branch, including the noisy one. You are rehearsing against main instead of teammate. Pass --target teammate.
  4. The +/- column shows 0/0 for a changed file. Git reports binary files as - in numstat output and the script skips them. Check that the file is text, or that .gitattributes is not marking it binary.
  5. Hunk count is 0 but the merge says CONFLICT. The conflict is not a content conflict, for example a modify-versus-delete. Print res.stdout and read the informational messages that follow the file list.
  6. Hunk count looks too low. The script counts markers in the merged blob, and Git may merge two nearby collisions into one hunk. The count is a floor, not an exact figure of how many edits collided.
  7. The hook never runs. The file must be named exactly pre-push with no extension, live in .git/hooks/ and be executable. Check with ls -l .git/hooks/pre-push.
  8. The hook runs but cannot find rehearse.py. The relative path in the hook assumes the lab layout. In a real project, hardcode the path from the repository root.
  9. CI says fatal: bad revision or no merge base. The checkout was shallow. Set fetch-depth: 0 and fetch the target branch explicitly.
  10. The lab behaves differently on a second run. You edited a branch by hand and then reran the builder. It deletes lab-repo and recreates it, so commit changes you want to keep in a different folder.
  11. Windows line endings show up as a huge diff. Set git config core.autocrlf false inside the lab and make sure the editor saves with LF. Mixed endings can create a noisy rewrite all by themselves.

Advanced Tips

Once the basic rehearsal works, a few extensions turn it from a demo into a habit.

Rehearse against every open branch. Write a loop that lists remote branches, skips stale ones and rehearses the current branch against each. Print only the ones that conflict. A developer about to push sees at once which colleague they will collide with, and can send a message before the pull request exists.

Score by hot spots. Keep a small file of paths that change often, such as lockfiles, route tables and shared constants. Make the hook stricter for those paths, for instance a zero-hunk budget for them and a looser one elsewhere. The churn analysis in the Cursor churn in Git history tutorial can produce that list from your own history.

Compare models on the same task. Save the prompt, run it with two or three models, commit each result to its own branch and rehearse all of them against the same target. Because the table shows noise ratio and conflict hunks side by side, it gives you a fairer comparison than any vendor claim. The Cursor CLI diff versus rewrite benchmark shows one way to automate the runs.

Ask the agent to fix it. When the hook fails, feed the rehearsal output back to the agent: “this edit conflicts with the teammate branch in orders.py, redo it touching only the tax lines.” Because the output names the file and the hunk count, the follow-up prompt is specific. Expect to repeat the check, since a second attempt can be noisy in a different place.

Rebase before you rehearse. If the target has moved on since you branched, rehearsal against its tip is what matters. The script uses git merge-base, so it already compares against the right ancestor, but a quick git fetch first keeps the target fresh.

Teach reviewers to read Git, not the editor. The diff panel in the Cursor AI code editor is built for reviewing intent, and it does that well. For merge safety, look at the stat line and the rehearsal table instead. A habit of glancing at the changed-line count before accepting an agent run catches the sixty-lines-for-a-ten-line-task pattern early, when asking the agent to redo the edit costs a few cents and no one else has seen the branch.

Build a tiny patch applier. If you want to see why diff-style edits fail in their own ways, write the opposite tool: a function that takes a search string and a replacement and applies it only when the search matches exactly once. The fast-apply patch engine project walks through that design and its failure modes.

Complete Project Layout and Run Script

Here is the finished project. Everything except lab-repo is source you keep. The lab folder is regenerated on every run.

conflict-lab/
  make_lab.py              builds the repo and five branches
  rehearse.py              merge rehearsal and hunk counter
  run_all.sh               one-command demo
  hooks/pre-push           blocks pushes that would conflict
  rules/minimal-edits.mdc  copy to .cursor/rules/
  .github-example/merge-rehearsal.yml   CI job
  lab-repo/                generated, safe to delete

The runner script rebuilds the lab and prints both rehearsal tables in one go. Run it with ./run_all.sh after making it executable.

#!/bin/sh
set -eu
python3 make_lab.py
cd lab-repo
echo "== target: teammate (far-away edits)"
python3 ../rehearse.py --target teammate ai-diff ai-rewrite-faithful ai-rewrite-noisy || true
echo "== target: teammate-adjacent (neighbouring lines)"
python3 ../rehearse.py --target teammate-adjacent ai-diff ai-rewrite-noisy || true

The expected output is the pair of tables you saw in Steps 7 and 9. If your numbers differ, check the Git version first and then the branch names.

lab ready: /home/you/conflict-lab/lab-repo
== target: teammate (far-away edits)
branch                +/-       merge     hunks  files
ai-diff               7/5       clean     0      -
ai-rewrite-faithful   7/5       clean     0      -
ai-rewrite-noisy      32/30     CONFLICT  1      orders.py
== target: teammate-adjacent (neighbouring lines)
branch                +/-       merge     hunks  files
ai-diff               7/5       CONFLICT  1      orders.py
ai-rewrite-noisy      32/30     CONFLICT  1      orders.py

The takeaway: whether an AI edit is a patch or a whole-file rewrite matters less than how many unrequested bytes it changes and where they sit. Measure that with a rehearsal before the push, not with a conflict after it. More tutorials for developers live in the Software section.

FAQ

Does the Cursor AI code editor use full-file rewrites or diffs? The Cursor AI code editor does not publish a per-edit rule in the sources reviewed for this article, and its published pricing is token-based. This tutorial therefore tests the result in Git instead of guessing at the mechanism. If an edit changes only the lines you asked for, Git sees a small diff whichever way it was produced.

Why did a tiny diff still conflict in Step 9? Git treats edits on adjacent lines as overlapping. The teammate changed the line right under the tax constant, and with no untouched line between the two changes Git declines to merge them automatically.

Is a full-file rewrite always worse? No. The faithful rewrite in the lab merged cleanly because every untouched line came back byte-identical. Unrequested changes cause conflicts, and rewriting is just the easiest way to introduce them.

Does git merge-tree --write-tree change my working tree? No. It runs the merge in the object database and writes only new objects. Your index, branches and uncommitted files stay as they were, which is why it is safe inside a hook.

Which Cursor model does this apply to? Any. The rehearsal reads Git objects, so it works on output from Composer 2.5, which Cursor lists as its newest Composer model, or from any other model you select. The model changes how often you see noisy edits, not how the check works.

How much does a conflicted rewrite cost in tokens? A full-file rewrite is billed from the tokens it generates, at the standard Composer 2.5 output rate of $2.50 per million, so a large rewrite costs more than a targeted edit. Redoing it after a conflict pays that output cost again. The cost is small, and the human time spent resolving the conflict is the larger bill.

Can I use this with other AI editors? Yes. Commit the editor’s output to a branch and run the script. The script knows nothing about Cursor, so it works with any tool that writes to a Git repository.

Source: Tech Insider