The history module supports stateless history editing: build a RewritePlan in memory, inspect or dry-run it, then History::apply to move refs and align the worktree. Every operation is a method on the History handle from Repository::history:
let history = repo.history();
let plan = history.reword(commit, &RewordOptions::default().with_message("New subject\n"), &rewrite)?;
history.verify_plan(&plan)?;
history.apply(&plan, &apply, &mut NullProgress, &CancelToken::never())?;
Methods that apply a plan take a trailing CancelToken (and a ProgressSink where they report work-tree progress); a cancel rolls back partial work.
Model
- Plan —
History::plan_rewritewalks affected commits, writes replacement objects into the ODB, and records ref movements in aRewritePlan. Refs, the index, and the worktree are untouched during planning. - Apply —
History::applywrites a crash journal under.git/grit/rewrite-apply/when a worktree checkout is required, runs a compare-and-swap ref batch, then (in non-bare repos) checks out from the oldHEADtree to the new one while preserving unrelated staged and unstaged changes. On success the journal is removed. If the process dies after refs move but before checkout finishes,History::recover_interrupted_apply(also run fromstatusand beforecreate_commit) finishes the checkout when refs already match the plan, or rolls refs and the index/worktree back from the journal. Recovery holdsindex.lockfor its whole run: when grit recorded a pid sidecar for the lock (the default; seegrit_lockfile_pid_enabled) and that process has exited,LockHolder::remove_if_staleremoves the lock first; any other existing lock returnsError::LockHeldwithout touching refs. To finish, it first restores the journal's index and the transition paths it captured (a kill mid-checkout can leave files half written), then checks out the new tree again, so the partial checkout is not mistaken for local edits. Only if that checkout still fails are refs rolled back, and the call returnsRewriteApplyRecovery::RolledBackrather than the checkout error. A journal directory without itsmetafile (killed while the snapshots were written, before any ref moved) is removed.statusreports what happened inStatusModel::interrupted_rewrite, withInterruptedRewrite::Pendingwhen another process holds the index lock. While the journal remains,HistoryError::RewriteApplyIncompleteblocks new commits;grit rebase --abortcallsHistory::abort_interrupted_applyto roll back explicitly.
CommitEdit describes per-commit rewrites, drops, and insert-before commits. RewriteOptions controls scope, empty-commit policy, the committer Signature used for new objects (usually repo.identity(IdentRole::Committer, now)), and whether replacement commits are signed (RewriteOptions::sign — set false for dry-run planning so signers are not invoked).
When a rewrite replays descendant merge commits, History::plan_rewrite remaps every parent and recomputes the merge tree (first-parent transplant when side branches are unchanged, otherwise a fresh merge of the mapped parents). Dropping or reordering a merge commit itself is still rejected (HistoryError::MergeCommitInReplay).
For a message or author change, History::reword takes a RewordOptions, builds the CommitEdit and runs History::plan_rewrite after normalize_rewrite_message (stripspace, trailing newline, reject empty).
To reorder one commit on the linear first-parent chain of HEAD, History::move_commit takes a Placement (Before / After another commit), replays the affected segment in the new order, and returns a RewritePlan. Commits must sit on the same first-parent chain with no merge commits in the segment; conflicts and no-op moves surface as HistoryError variants.
For rebasing a branch tip onto a new base with fork-point detection and bounded cherry patch-id lookup, see Rebase planning (History::plan_rebase / RebaseRequest).
To assign staged hunks automatically, History::absorb blame-maps each hunk to a candidate commit between AbsorbOptions::base and HEAD, verifies commutation with later commits, builds one combined RewritePlan, and returns AbsorbPlan with HunkAssignment and UnassignedHunk detail. When --base is omitted, AbsorbPlan::excluded_refs lists other local branch tips that bound the stack (another ref at the checked-out tip is not treated as a boundary). UnassignedReason::HiddenByRef with UnassignedHunk::detail explains when a hunk’s introducing commit sits outside the stack because of one of those tips. Call History::apply_absorb so only assigned hunks are removed from the index.
Apply options and result
ApplyOptions supplies the reflog identity and message written for every ref update in the batch.
AppliedRewrite returns the ref updates that were committed and the commit OID HEAD resolves to afterward.
Undo
When ApplyOptions::record_operation is set, the apply records its ref plan in .git/grit/history-last, and History::undo_last inverts it while every recorded ref is still at its post-rewrite tip (UndoMode::DryRun checks and reports without changing anything). Undo writes the inverse as the new record, so calling it again redoes the rewrite.
History::apply_fixup, History::apply_fixup_hunks, and History::apply_absorb consume edits from the index (or selected unstaged hunks); History::staged_paths lists the staged paths a fixup or absorb consumes. A recorded apply also saves, in .git/grit/history-last-work, each consumed path's index entry and work tree file from before the command, plus a fingerprint of the same paths after it. Undo checks that those paths still match the fingerprint (otherwise LocalChangesWouldBeOverwritten), runs the inverse checkout, then puts the saved entries and files back. A restored entry takes the stat data of the file just written when that file cleans (through core.autocrlf, eol, ident and clean filters) to the restored blob, so neither Git nor grit sees a phantom unstaged change; when the file holds a real unstaged edit, the entry's stat cache stays unset so both rehash it. UndoOutcome::restored_paths lists them. A record written without saved state still moves refs, and UndoOutcome::unrestored_edits names the commit that holds the consumed edits.
Inspecting a plan
RewritePlan::ref_updates lists each ref movement as a PlannedRefUpdate (name, old, new), so callers can preview ref motion without applying.
RewritePlan::replacement maps one original commit to its rewritten OID (None when dropped), and RewritePlan::head_change reports HEAD's commit before and after the rewrite, or None when HEAD does not move. grit history builds its --json head field from it.
Change ids
History planning preserves change-id and legacy gitbutler-change-id headers on rewritten commits (signatures are stripped). When ChangeIdPolicy is enabled and the source commit has no stored id, the planner writes the Jujutsu-derived id for the original commit oid into the replacement object. Commits inserted during a rewrite (for example the parent created by History::split) receive a new random id via ChangeIdPolicy::id_for_new_commit. With grit.changeIds=false, existing headers are still copied but no derived or random ids are added. See Change ids for header format and config.
Errors
HistoryError covers planning failures (conflicts, out-of-scope commits, branch checked out elsewhere) and apply failures. There is no string catch-all variant: history operations return the umbrella Error, with history-specific failures under Error::History and repository, object, ref or revision failures under their own area variants, and structured fields carry paths, commit ids, and ref names where scripts need them.
LocalChangesWouldBeOverwritten— staged, unstaged, or untracked paths would be clobbered by the planned tree checkout.RefCasMismatch— a ref tip changed after planning; nothing is written.HeadMovedSincePlan—HEADno longer points at the ref or commit recorded when the plan was built; nothing is written.RefApply/WorktreeApply— ref batch or post-ref checkout failed (apply rolls back ref updates when checkout fails).RewriteApplyIncomplete— refs moved but the worktree checkout did not finish; run recovery orgrit rebase --abortbefore committing.ApplyRollbackIncomplete— checkout failed after refs moved and ref rollback or worktree restore also failed.EmptyMessage— reword message cleanup left an empty body.Signing—commit.gpgsignwas enabled but signing a replacement commit failed; refs are not updated.