# Conflicts during replay

> Multi-commit cherry-pick and revert sequences, on-disk sequencer state, and continue/abort.

Pick and revert ranges use [`porcelain::replay_sequence`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/replay_sequence/index.html) instead of single-commit replay. On conflict, grit writes Git-compatible `CHERRY_PICK_HEAD` or `REVERT_HEAD`, `MERGE_MSG`, `ORIG_HEAD`, and `.git/sequencer/` (todo, head, abort-safety, opts) so `git cherry-pick --continue` and `grit pick --continue` can interoperate.

[`ReplayOptions`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/replay_sequence/struct.ReplayOptions.html) controls mainline parent selection for merge commits, `-x` / `record_origin`, empty-commit policy (`Stop`, `Drop`, `Keep`), merge favor, and conflict marker style. [`Merge::start_sequence`](https://docs.rs/grit-lib/latest/grit_lib/merge/struct.Merge.html#method.start_sequence) returns [`SequenceOutcome`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/replay_sequence/enum.SequenceOutcome.html) — `Completed`, `Conflicts`, or `Empty`. Every commit created so far is a [`ReplayCreated`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/replay_sequence/struct.ReplayCreated.html) carrying its source, new oid, stored change id, and subject (also for steps committed before an earlier stop), and a stop reports the subject of the commit it stopped on, so callers can render results without re-reading commits. Resolve conflicts in the worktree, stage paths, then call [`Merge::continue_sequence`](https://docs.rs/grit-lib/latest/grit_lib/merge/struct.Merge.html#method.continue_sequence). [`Merge::skip_sequence_step`](https://docs.rs/grit-lib/latest/grit_lib/merge/struct.Merge.html#method.skip_sequence_step) and [`Merge::abort_sequence`](https://docs.rs/grit-lib/latest/grit_lib/merge/struct.Merge.html#method.abort_sequence) match Git's skip/abort semantics. Abort rewinds to `sequencer/head` when grit wrote a sequencer directory, otherwise to the current branch tip (for example a single pick or revert started by Git); a leftover `ORIG_HEAD` from an earlier reset or merge is not the restore target. Abort clears replay state without moving the branch when `HEAD` no longer matches `sequencer/abort-safety`.

Conflict markers and unmerged index stages reuse the same tree-merge path as [`porcelain::merge`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/merge/index.html) (`apply_conflict_merge_worktree`). [`status`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/status/fn.status_options_from_config.html) surfaces cherry-pick/revert operation guidance via [`state::status_operation`](https://docs.rs/grit-lib/latest/grit_lib/state/fn.status_operation.html). On the returned model, [`StatusModel::conflict_groups`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/status/struct.StatusModel.html#method.conflict_groups) groups unmerged paths by [`ConflictKind`](https://docs.rs/grit-lib/latest/grit_lib/operation/enum.ConflictKind.html), and [`StatusModel::guidance`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/status/struct.StatusModel.html#method.guidance) picks the next step `grit status` suggests: the paused operation's runnable steps, the conflict and merge fallbacks, or everyday [`StatusAction`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/status/enum.StatusAction.html)s (discard, stage, commit, pull when strictly behind).

## Sequencer and merge errors ([`MergeError`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/enum.MergeError.html))

[`Merge::start_sequence`](https://docs.rs/grit-lib/latest/grit_lib/merge/struct.Merge.html#method.start_sequence), [`Merge::continue_sequence`](https://docs.rs/grit-lib/latest/grit_lib/merge/struct.Merge.html#method.continue_sequence), skip, and abort propagate the same [`MergeError`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/enum.MergeError.html) variants as merge (wrapped in [`Error::Merge`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html#variant.Merge)). Examples: [`ReplayContinueUnmerged`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/enum.MergeError.html#variant.ReplayContinueUnmerged) when continue is attempted with unmerged index entries; [`ReplayContinueDirtyIndex`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/enum.MergeError.html#variant.ReplayContinueDirtyIndex) when the index differs from `HEAD` after the step was already committed; [`NoReplayInProgress`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/enum.MergeError.html#variant.NoReplayInProgress) for continue/skip/abort with no sequence; [`OperationInProgress`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/enum.MergeError.html#variant.OperationInProgress) when a merge (or other paused operation) blocks starting a new pick/revert. Merge commits without [`ReplayOptions::mainline`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/replay_sequence/struct.ReplayOptions.html#structfield.mainline) return [`MergeCommit`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/enum.MergeError.html#variant.MergeCommit).

## One conflict model

Every API that reports conflicts uses [`operation::Conflict`](https://docs.rs/grit-lib/latest/grit_lib/operation/struct.Conflict.html) (a path and a [`ConflictKind`](https://docs.rs/grit-lib/latest/grit_lib/operation/enum.ConflictKind.html)): [`StatusModel::conflict_details`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/status/struct.StatusModel.html#structfield.conflict_details), merge and pull outcomes, [`SequenceOutcome::Conflicts`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/replay_sequence/enum.SequenceOutcome.html#variant.Conflicts), a stopped rebase's [`RebaseStop`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/history/struct.RebaseStop.html), rebase predictions and [`HistoryError::Conflict`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/history/enum.HistoryError.html#variant.Conflict), and [`StashApplyOutcome`](https://docs.rs/grit-lib/latest/grit_lib/stash/struct.StashApplyOutcome.html). The kind is read from which unmerged index stages a path has ([`conflict_kind_from_stagemask`](https://docs.rs/grit-lib/latest/grit_lib/operation/fn.conflict_kind_from_stagemask.html), the same classification as Git's porcelain v2 `u` lines), so an operation's conflicts equal what `status` reports right after it stops, and a UI needs one renderer. Only a tree-merge result ([`conflicts_from_tree_merge`](https://docs.rs/grit-lib/latest/grit_lib/operation/fn.conflicts_from_tree_merge.html)) can add [`ConflictKind::RenameRename`](https://docs.rs/grit-lib/latest/grit_lib/operation/enum.ConflictKind.html#variant.RenameRename) and the directory rename kinds ([`DirectoryRenameMoved`](https://docs.rs/grit-lib/latest/grit_lib/operation/enum.ConflictKind.html#variant.DirectoryRenameMoved), [`DirectoryRenameSplit`](https://docs.rs/grit-lib/latest/grit_lib/operation/enum.ConflictKind.html#variant.DirectoryRenameSplit), [`DirectoryRenameBlocked`](https://docs.rs/grit-lib/latest/grit_lib/operation/enum.ConflictKind.html#variant.DirectoryRenameBlocked)), which need information the index does not keep; [`conflicts_from_index`](https://docs.rs/grit-lib/latest/grit_lib/operation/fn.conflicts_from_index.html) classifies an index alone. [`ConflictKind::as_str`](https://docs.rs/grit-lib/latest/grit_lib/operation/enum.ConflictKind.html#method.as_str) gives the snake_case name `grit` prints in `--json`, and with the `serde-models` feature a `Conflict` serializes to the same `{"path", "kind"}` object.

```rust
use grit_lib::merge::ReplayOptions;
use grit_lib::merge::{Merge, SequenceOutcome};
use grit_lib::operation::ConflictKind;
use grit_lib::progress::{CancelToken, NullProgress};

let outcome = Merge::start_sequence(&repo, &request, &ReplayOptions::default(), &mut NullProgress, &CancelToken::never())?;
let conflicts = match outcome {
    SequenceOutcome::Conflicts { conflicts, .. } => conflicts,
    _ => return Ok(()),
};
for conflict in &conflicts {
    if conflict.kind == ConflictKind::DeletedByUs {
        println!("{}: deleted here, changed on the incoming side", conflict.path);
    }
}
```

## Example

```rust
//! Cherry-pick / revert sequences that stop on conflicts (library API).
//!
//! Source for the library guide "Conflicts during replay" page.

use anyhow::Result;
use grit_lib::config::environment::RepositoryOptions;
use grit_lib::merge::{ReplayEmptyPolicy, ReplayOptions, ReplaySequenceRequest, SequenceOutcome};
use grit_lib::objects::ObjectId;
use grit_lib::porcelain::add::StageOptions;
use grit_lib::porcelain::replay::ReplayDirection;
use grit_lib::progress::NullProgress;
use grit_lib::repo::Repository;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

const IDENT: &str = "Library Guide <guide@grit-scm.com> 1735689600 +0000";

fn replay_identity() -> grit_lib::ident::Signature {
    grit_lib::ident::parse_signature(IDENT)
        .unwrap_or_else(|| panic!("guide IDENT must parse as a signature: {IDENT}"))
}

fn open_repo(root: &Path) -> Result<Repository> {
    let git_dir = if root.join(".git").is_dir() {
        root.join(".git")
    } else {
        root.to_path_buf()
    };
    let work_tree = if root.join(".git").is_dir() {
        Some(root)
    } else {
        None
    };
    let mut opts = RepositoryOptions::empty();
    if let Some(wt) = work_tree {
        opts = opts.with_work_tree(wt);
    }
    Ok(Repository::open(&git_dir, &opts)?)
}

fn git(root: &Path, args: &[&str]) -> Result<()> {
    let home = root.join(".git-home");
    fs::create_dir_all(&home)?;
    let out = Command::new("git")
        .current_dir(root)
        .args(args)
        .env("HOME", &home)
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_SYSTEM", "/dev/null")
        .output()?;
    if !out.status.success() {
        return Err(anyhow::anyhow!(format!(
            "git {:?}: {}",
            args,
            String::from_utf8_lossy(&out.stderr)
        )));
    }
    Ok(())
}

fn oid_from_rev(root: &Path, rev: &str) -> Result<ObjectId, anyhow::Error> {
    let home = root.join(".git-home");
    let out = Command::new("git")
        .current_dir(root)
        .args(["rev-parse", rev])
        .env("HOME", &home)
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_SYSTEM", "/dev/null")
        .output()?;
    if !out.status.success() {
        return Err(anyhow::anyhow!("rev-parse failed"));
    }
    let hex = String::from_utf8_lossy(&out.stdout).trim().to_owned();
    ObjectId::from_hex(&hex).map_err(|_| anyhow::anyhow!("bad oid"))
}

/// Build a tiny repo with one conflicting pick, run start → resolve → continue.
fn demo_conflict_sequence(root: &Path) -> Result<()> {
    git(root, &["init", "-q", "-b", "main", "."])?;
    git(root, &["config", "user.email", "guide@grit-scm.com"])?;
    git(root, &["config", "user.name", "Library Guide"])?;
    fs::write(root.join("f"), "base\n")?;
    git(root, &["add", "f"])?;
    git(root, &["commit", "-qm", "base"])?;

    git(root, &["switch", "-c", "topic"])?;
    fs::write(root.join("f"), "topic\n")?;
    git(root, &["commit", "-qam", "topic"])?;
    let pick = oid_from_rev(root, "HEAD")?;

    git(root, &["switch", "main"])?;
    fs::write(root.join("f"), "main\n")?;
    git(root, &["commit", "-qam", "main"])?;

    let repo = open_repo(root)?;
    let req = ReplaySequenceRequest::new(vec![pick], ReplayDirection::Pick, replay_identity())
        .with_options(ReplayOptions::default().with_empty(ReplayEmptyPolicy::Stop));

    match repo.merge().start_sequence(
        &req,
        &mut NullProgress,
        &grit_lib::progress::CancelToken::never(),
    )? {
        SequenceOutcome::Conflicts {
            conflicts,
            current,
            created_so_far,
            ..
        } => {
            println!(
                "stopped on {} conflict(s) at {}",
                conflicts.len(),
                current.to_hex()
            );
            println!("created_so_far={}", created_so_far.len());
        }
        other => {
            return Err(anyhow::anyhow!(format!(
                "expected conflicts, got {other:?}"
            )));
        }
    }

    fs::write(root.join("f"), "merged\n")?;
    repo.index().stage(
        &StageOptions::default(),
        &mut NullProgress,
        &grit_lib::progress::CancelToken::never(),
    )?;

    match repo.merge().continue_sequence(
        &replay_identity(),
        &mut NullProgress,
        &grit_lib::progress::CancelToken::never(),
    )? {
        SequenceOutcome::Completed {
            created, dropped, ..
        } => {
            println!(
                "sequence completed; created={} dropped={}",
                created.len(),
                dropped.len()
            );
            for record in created {
                println!(
                    "replay source={} new={} change_id={}",
                    record.source.to_hex(),
                    record.new_oid.to_hex(),
                    record
                        .change_id
                        .map(|c| c.to_string())
                        .unwrap_or_else(|| "-".into())
                );
            }
        }
        other => {
            return Err(anyhow::anyhow!(format!(
                "expected completed after continue, got {other:?}"
            )));
        }
    }

    Ok(())
}

fn main() -> Result<()> {
    if std::env::args().nth(1).is_none() {
        let temp = tempfile::tempdir()?;
        demo_conflict_sequence(temp.path())?;
        return Ok(());
    }

    let root = std::env::args()
        .nth(1)
        .map(PathBuf::from)
        .ok_or_else(|| anyhow::anyhow!("missing repository path"))?;
    let repo = open_repo(&root)?;

    if repo.git_dir().join("CHERRY_PICK_HEAD").exists()
        || repo.git_dir().join("REVERT_HEAD").exists()
    {
        if repo
            .index()
            .load(&grit_lib::index::IndexLoadOptions::default())?
            .has_unmerged_entries()
        {
            println!("unmerged index — resolve and stage before continue");
            return Ok(());
        }
        match repo.merge().continue_sequence(
            &replay_identity(),
            &mut NullProgress,
            &grit_lib::progress::CancelToken::never(),
        )? {
            SequenceOutcome::Completed { created, .. } => {
                println!("continued; new commits={}", created.len());
            }
            SequenceOutcome::Conflicts { conflicts, .. } => {
                println!("stopped again on {} conflict(s)", conflicts.len());
            }
            SequenceOutcome::Empty { current, .. } => {
                println!("empty step at {}", current.to_hex());
            }
            _ => println!("stopped with an outcome this example does not handle"),
        }
    } else {
        println!(
            "no replay in progress (omit path to run the built-in conflict demo, or call start_replay_sequence first)"
        );
    }

    Ok(())
}
```

The integration test `replay_sequence_git_compat` cross-checks trees, messages, and on-disk state against system `git` after `git fsck --strict`.
