Skip to main content

gitpoulpi_core/
backend.rs

1use std::path::{Path, PathBuf};
2
3use crate::domain::rewrite::{Recipe, RewriteOutcome, RewritePlan, RewriteProgressSink, RunId};
4use crate::domain::{
5    AmOutcome, Blame, Blob, BlobSource, CheckoutTarget, CherryPickOptions, CherryPickOutcome,
6    CloneOptions, CloneProgressSink, CommitAmend, CommitGraph, CommitMessages, CommitMessagesQuery,
7    CommitOptions, CommitStat, ConflictEntry, ConflictResolution, ConflictSet, DiffFileList,
8    DiffTarget, DiscardTarget, DiscoveredRepo, FastForwardOutcome, FetchOptions, FetchOutcome,
9    FileDiff, FileHistoryPage, IndexLock, InitOptions, InteractiveRebase, LfsFetchOptions, LfsFile,
10    LfsInstallScope, LfsLock, LfsPattern, LfsProgressSink, LfsPushOptions, LfsRepoStatus,
11    LfsTrackOptions, LogOptions, LostCommitOptions, LostCommitsPage, MergeDocument, MergeOptions,
12    MergeOutcome, NetworkAuth, Oid, OperationState, PatchApplied, PatchCreated, PatchSource,
13    PathHash, PullOptions, PullOutcome, PushOptions, PushOutcome, RebaseOptions, RebaseOutcome,
14    RebasePlanDraft, RebaseState, Ref, RefScope, RefSnapshot, RefUpdate, ReflogPage, Remote,
15    RemoteAccessOptions, RemoteAccessReport, RepoRef, ResetMode, ResolveOptions, RevertOutcome,
16    RewordOutcome, Snapshot, SparseState, SplitCommit, SplitOutcome, SplitSource, StageTarget,
17    Stash, StashId, Submodule, SubmoduleUpdateOptions, WorkingTree, Worktree, WorktreeAddOptions,
18    WorktreeChange, WorktreeRemoveOptions, WorktreeRemoved,
19};
20use crate::Result;
21
22/// A config section's name and its `(key, value)` pairs.
23pub type ConfigSection = (String, Vec<(String, String)>);
24
25/// The port every frontend (TUI/CLI/MCP, via the daemon) and every backend
26/// adapter (git2, system git) implements against.
27#[async_trait::async_trait]
28pub trait GitBackend: Send + Sync {
29    /// Short implementation name (`"git2"` or `"system"`), for diagnostics.
30    fn name(&self) -> &'static str;
31
32    // -- read --
33    /// Finds the repository enclosing `path` and describes it.
34    ///
35    /// Behind the seam so both backends agree on what "the repository at
36    /// this path" means, including a linked worktree (`.git` is a *file*),
37    /// a bare repository and an external `$GIT_DIR`.
38    ///
39    /// `path` may be the root, any subdirectory, or a file inside it. Both
40    /// fields of the returned [`RepoRef`] come from the root.
41    ///
42    /// A path that does not exist, and one inside no repository, are both
43    /// [`crate::Error::RepoNotFound`] (also the answer for a recent entry
44    /// whose directory has been deleted).
45    fn discover(&self, path: &Path) -> Result<DiscoveredRepo>;
46
47    /// Creates a new repository at `path` and returns the `RepoRef` every
48    /// later request for it will be keyed on.
49    ///
50    /// Pinned by the contract suite:
51    ///
52    /// - **A missing directory is created**, parents included, like
53    ///   `git init <path>`.
54    /// - **The returned `RepoRef` is what `discover` would return** for the
55    ///   same path.
56    /// - **An existing repository root is an error**, not a silent
57    ///   re-initialisation. A directory that merely contains files, or sits
58    ///   inside another repository, is fine (a legitimate nested
59    ///   repository).
60    ///
61    /// Synchronous: no network, and no repository to target yet.
62    fn init(&self, path: &Path, opts: &InitOptions) -> Result<RepoRef>;
63
64    fn status(&self, repo: &RepoRef) -> Result<WorkingTree>;
65    /// The commit graph. With `all_refs`, `opts.hidden` drops refs from the
66    /// walk (the commits only they reach go with them; `HEAD` always stays
67    /// while a filter is active); both backends take the tips from
68    /// `domain::visible_tips` and page that one walk with `skip`/`limit`.
69    fn log(&self, repo: &RepoRef, opts: &LogOptions) -> Result<CommitGraph>;
70    /// How many commits [`log`](Self::log) would return for `opts` if it
71    /// were not paged: the same refs (`all_refs`, `start_ref`, HEAD) and
72    /// path filter and `hidden` filter, `skip` and `limit` ignored. Counts without loading any
73    /// commit's text, so it stays cheap on a very large history. An unborn
74    /// repository is `0`. Read-only; nothing to journal.
75    fn count_commits(&self, repo: &RepoRef, opts: &LogOptions) -> Result<u64>;
76    fn diff(&self, repo: &RepoRef, target: DiffTarget) -> Result<Vec<FileDiff>>;
77    /// The files [`diff`](Self::diff) lists for the same `target` - same
78    /// paths, same statuses, same order - as cheaply as the backend can
79    /// produce them.
80    ///
81    /// The commit-detail pane shows the list from this and fills the hunks
82    /// in from `diff` a moment later.
83    ///
84    /// A backend for which the list costs what the whole diff costs
85    /// (system git: one `git diff` process either way) answers with the
86    /// whole diff and says so in [`DiffFileList::hunks_included`], so the
87    /// caller never pays twice.
88    fn diff_files(&self, repo: &RepoRef, target: DiffTarget) -> Result<DiffFileList>;
89    /// [`CommitStat`] for each of `ids`, in the order given, for the Log's
90    /// "Changes" column. Each is the commit against its first parent (a
91    /// root commit against nothing) without rename detection, so
92    /// `files` equals the length of `diff(CommitVsParent(id))`. A batch
93    /// so the system backend can answer it with one process instead of
94    /// one per commit. An empty `ids` is an empty answer; an unknown id
95    /// is an error.
96    fn commit_stats(&self, repo: &RepoRef, ids: &[Oid]) -> Result<Vec<CommitStat>>;
97    /// [`diff`](Self::diff) restricted to `paths`: the hunks of just those
98    /// files, so the Diff view can load one file's hunks when it is opened.
99    ///
100    /// Paths are literal (no globbing, no pathspec magic), repo-relative.
101    /// The answer holds the files of `diff(target)` whose path is in
102    /// `paths`, in the same order, with identical statuses and identical
103    /// hunks and hunk ids (ids number the hunks within one file, so
104    /// restricting never renumbers them). An empty `paths` is an empty
105    /// answer, not "everything". Untracked files are not part of any
106    /// `diff` target and are not here either.
107    fn diff_paths(
108        &self,
109        repo: &RepoRef,
110        target: DiffTarget,
111        paths: &[PathBuf],
112    ) -> Result<Vec<FileDiff>>;
113    fn refs(&self, repo: &RepoRef) -> Result<Vec<Ref>>;
114    /// Raw ref values (tag objects not peeled) under `scope`, plus HEAD
115    /// (symbolic, possibly unborn, or detached). A read; the undo
116    /// journal's source of truth for "what did this operation change".
117    /// The hidden `refs/gitpoulpi/` namespace is never listed.
118    fn ref_snapshot(&self, repo: &RepoRef, scope: &RefScope) -> Result<RefSnapshot>;
119    /// An atomic compare-and-swap ref transaction: every update applies
120    /// or none does. A ref that does not hold the expected value is
121    /// `Error::UndoRefused(UndoRefusal::RefMoved)`; a HEAD that is not
122    /// where `SetHead` expects is `HeadMoved`. `SetHead` re-points HEAD
123    /// without touching the index or any file. `reflog_message` is
124    /// written for every ref that moves.
125    fn update_refs(
126        &self,
127        repo: &RepoRef,
128        updates: &[RefUpdate],
129        reflog_message: &str,
130    ) -> Result<()>;
131    /// Moves the branch `branch` from `from` to `to` **and** carries the
132    /// index and working tree along, with `git reset --keep` semantics:
133    /// local changes survive unless the move would overwrite them, in
134    /// which case it is `UndoRefusal::WouldOverwrite` and nothing changed.
135    /// `branch` must be the checked-out branch (else `HeadMoved`) and must
136    /// hold `from` (else `RefMoved`). The undo journal's primitive for
137    /// fast-forwards of the checked-out branch.
138    fn move_head_keep(&self, repo: &RepoRef, branch: &str, from: Oid, to: Oid) -> Result<()>;
139    /// The `key = value` pairs of one repository-local config section,
140    /// full keys (`branch.x.remote`), in file order. Only the sections
141    /// `branch.<name>` and `remote.<name>` are accepted (an undo helper, not a
142    /// general config reader).
143    fn config_section(&self, repo: &RepoRef, section: &str) -> Result<Vec<(String, String)>>;
144    /// [`GitBackend::config_section`] for several sections at once, in the
145    /// order asked. The system-git backend answers with one process
146    /// instead of one per section (the undo journal reads a remote's
147    /// section and every dependent branch's together).
148    fn config_sections(&self, repo: &RepoRef, sections: &[String]) -> Result<Vec<ConfigSection>> {
149        sections
150            .iter()
151            .map(|s| Ok((s.clone(), self.config_section(repo, s)?)))
152            .collect()
153    }
154    /// The `branch.<name>` sections whose `remote` is `remote`, sorted:
155    /// what `git remote remove` deletes and `git remote rename` rewrites
156    /// besides the remote's own section.
157    fn remote_dependents(&self, repo: &RepoRef, remote: &str) -> Result<Vec<String>>;
158    /// Replaces the whole section with `entries` (empty removes it). Same
159    /// restriction as [`GitBackend::config_section`].
160    fn set_config_section(
161        &self,
162        repo: &RepoRef,
163        section: &str,
164        entries: &[(String, String)],
165    ) -> Result<()>;
166    /// The tree id of the index as it is right now (`git write-tree`):
167    /// what a staging operation's undo records before and after. Writes
168    /// tree objects (never the working tree); an index with unresolved
169    /// conflicts has no tree and is an error.
170    fn index_tree(&self, repo: &RepoRef) -> Result<Oid>;
171    /// Makes the index equal `tree` exactly (`git read-tree`). Never
172    /// touches the working tree. The undo journal's primitive for
173    /// stage/unstage; the caller has verified, under the repository's
174    /// write lock, that the index is what it expects.
175    fn index_restore(&self, repo: &RepoRef, tree: Oid) -> Result<()>;
176    /// A safety snapshot of every file under `paths` (repo-relative, `/`
177    /// separated; a directory means everything below it): the index entry
178    /// and the working-tree file, **including untracked files**, as raw
179    /// bytes (no clean filter), with the executable bit and symlinks. It
180    /// writes objects only: neither the index nor the working tree is
181    /// touched. Take it before a destructive operation and keep `tree`
182    /// reachable with a pin ref. Snapshot only what the operation will
183    /// touch, never the whole tree.
184    fn snapshot_create(&self, repo: &RepoRef, paths: &[String]) -> Result<Snapshot>;
185    /// Writes a snapshot's index and working-tree sides back for `paths`,
186    /// exactly: a file the snapshot holds is rewritten (content, mode,
187    /// symlink), and a file under `paths` that the snapshot does *not*
188    /// hold is removed from the index and the disk. Index and working
189    /// tree are restored independently of each other.
190    fn snapshot_restore(&self, repo: &RepoRef, snapshot: Oid, paths: &[String]) -> Result<()>;
191    /// The current [`PathHash`] of every file under `paths` that exists in
192    /// the index or the working tree, sorted by path. Equal to
193    /// `snapshot_create(paths).hashes` taken at the same instant. A read:
194    /// the undo preconditions.
195    fn path_hashes(&self, repo: &RepoRef, paths: &[String]) -> Result<Vec<PathHash>>;
196    /// The raw bytes of the blob `oid` (no filter, no decoding): what a
197    /// snapshot's [`FileHash`] names. "Restore only this" writes them next
198    /// to a file that changed since. A missing object is an error.
199    fn blob_bytes(&self, repo: &RepoRef, oid: Oid) -> Result<Vec<u8>>;
200    /// One page of a reflog, newest entry first. `refname` is `HEAD` or a
201    /// ref (`refs/heads/main`; a bare name is a local branch, see
202    /// [`crate::domain::reflog_refname`]). `old`/`new` are the values
203    /// git stored, `old` being all zeros for the first entry. A ref with
204    /// no reflog (a deleted branch, a tag, `core.logAllRefUpdates` off)
205    /// is an empty page, not an error. A read; shows moves made outside
206    /// GitPoulpi too.
207    fn reflog(
208        &self,
209        repo: &RepoRef,
210        refname: &str,
211        skip: usize,
212        limit: usize,
213    ) -> Result<ReflogPage>;
214    /// Commits no branch, tag, remote-tracking ref or stash reaches (the
215    /// reflogs and GitPoulpi's undo pins do not count as reaching), newest
216    /// first: what a deleted branch left behind (named by a reflog or only
217    /// by an undo pin), and with `opts.deep` the dangling commits of the
218    /// whole object database (what `git fsck --unreachable --no-reflogs`
219    /// lists). A read, bounded by `opts.budget_ms`.
220    fn lost_commits(&self, repo: &RepoRef, opts: &LostCommitOptions) -> Result<LostCommitsPage>;
221    /// Every commit's author, time, subject and body, for the workspace
222    /// search index: the commits reachable from the branches, remote
223    /// branches, tags and HEAD (not stashes, not GitPoulpi's own refs),
224    /// newest first, minus those reachable from `query.known_tips` (so an
225    /// index is brought up to date by asking for what is new). See
226    /// [`CommitMessages`] for `tips`, `replace` and `truncated`. A read.
227    fn commit_messages(
228        &self,
229        repo: &RepoRef,
230        query: &CommitMessagesQuery,
231    ) -> Result<CommitMessages>;
232    /// Deletes `paths` (files, or directories with everything below) from
233    /// the working tree; the index is not touched, so a tracked file shows
234    /// up as a deleted change, as with `rm`. A path that does not exist is
235    /// ignored; a path outside the repository or inside `.git` is an error. The daemon-side home of the
236    /// TUI's "Delete file", so it can be journaled and undone.
237    fn delete_files(&self, repo: &RepoRef, paths: &[String]) -> Result<()>;
238    /// Rewrites the bytes of the files `paths` (working tree only; the index
239    /// is not touched) as `op` says: another encoding, other line breaks or
240    /// other indentation (`textconv::convert_bytes`, the editor's own
241    /// functions). A binary file, a missing one, one the target encoding
242    /// cannot hold, is left alone and reported, never damaged; a path
243    /// outside the repository or inside `.git` is an error. The daemon-side
244    /// home of the right pane's "Convert" menu, so one call is one journal
245    /// entry.
246    fn convert_files(
247        &self,
248        repo: &RepoRef,
249        paths: &[String],
250        op: crate::textconv::ConvertOp,
251    ) -> Result<crate::textconv::ConvertReport>;
252    /// Appends `pattern` as its own line to the `.gitignore` named by
253    /// `file` (repo-relative, default `.gitignore`; its file name must be
254    /// `.gitignore`), creating the file and keeping an existing last line
255    /// intact. `Ok(false)` when the pattern is already a line of the file
256    /// (nothing written). The daemon-side home of the TUI's "Ignore" menu,
257    /// so it can be journaled and undone.
258    fn gitignore_add(&self, repo: &RepoRef, pattern: &str, file: Option<&str>) -> Result<bool>;
259    /// Writes the `.gitattributes` rule that makes git diff `paths` as
260    /// `treat` says (see [`crate::domain::Treat::attributes`]): one pattern
261    /// per path (`scope`: the file itself or its extension; `Folder`: the
262    /// path is a folder and the rule covers everything below), relative to
263    /// `file`'s folder. `file` is repo-relative: `None` is the root
264    /// `.gitattributes`, `Some(".git/info/attributes")` the per-clone file,
265    /// else a `.gitattributes` inside the repository (created when
266    /// missing). A rule already naming the same pattern is rewritten rather
267    /// than contradicted. The answer says what was written and whether git
268    /// now really treats `paths` that way (a rule closer to the file, or
269    /// in `.git/info/attributes`, can still override a root one). The
270    /// daemon-side home of "Treat as Binary/Text", journaled like
271    /// [`GitBackend::gitignore_add`], except for the per-clone file, which
272    /// lives outside the working tree.
273    fn gitattributes_treat(
274        &self,
275        repo: &RepoRef,
276        paths: &[String],
277        scope: crate::domain::RuleScope,
278        file: Option<&str>,
279        treat: crate::domain::Treat,
280    ) -> Result<crate::domain::AttributesWrite>;
281    /// Each of `idents` as the repository's `.mailmap` (and `mailmap.file`)
282    /// shows it, in the same order: the canonical name and email, or the
283    /// identity itself when nothing maps it. The system backend asks `git
284    /// check-mailmap`, `Git2Backend` libgit2's `Mailmap`; the contract suite
285    /// pins that they agree. A read.
286    fn mailmap_resolve(
287        &self,
288        repo: &RepoRef,
289        idents: &[crate::domain::rewrite::Ident],
290    ) -> Result<Vec<crate::domain::rewrite::Ident>>;
291    /// Every name and email that authored or committed a commit of `scope`,
292    /// with the counts, most commits first, and what the `.mailmap` already
293    /// maps each to. The Identities list of the history workbench. A read;
294    /// one `git log`, whatever the size of the history.
295    fn mailmap_identities(
296        &self,
297        repo: &RepoRef,
298        scope: &crate::domain::rewrite::Scope,
299        options: &crate::domain::rewrite::ScopeOptions,
300    ) -> Result<crate::domain::rewrite::IdentityList>;
301    /// Appends the lines that map each of `from` to `canonical` to the
302    /// `.mailmap` (`file`: repo-relative, default `.mailmap`; created when
303    /// missing), once each. Nothing is committed. Journaled like
304    /// [`GitBackend::gitignore_add`]: undo puts the previous file back.
305    fn mailmap_add(
306        &self,
307        repo: &RepoRef,
308        canonical: &crate::domain::rewrite::Ident,
309        from: &[crate::domain::rewrite::Ident],
310        file: Option<&str>,
311    ) -> Result<crate::domain::rewrite::MailmapAdded>;
312    /// For each of `paths`, in order: does `git diff` treat it as binary?
313    /// The `diff` attribute decides when a rule sets or unsets it (`binary`
314    /// unsets it); otherwise the content does, with git's own sniff (a NUL
315    /// in the first 8000 bytes of the working-tree file). A read.
316    fn binary_paths(&self, repo: &RepoRef, paths: &[String]) -> Result<Vec<bool>>;
317    /// The repo-relative paths a patch file would touch (every side of a
318    /// rename), without applying it: what to snapshot before
319    /// [`GitBackend::patch_apply`].
320    fn patch_files(&self, repo: &RepoRef, patch: &Path) -> Result<Vec<String>>;
321    fn stashes(&self, repo: &RepoRef) -> Result<Vec<Stash>>;
322    fn remotes(&self, repo: &RepoRef) -> Result<Vec<Remote>>;
323    /// The remote-tracking namespaces no remote is configured for: refs
324    /// under `refs/remotes/<name>/` (or a tag mirror under
325    /// [`crate::domain::REMOTE_TAG_MIRROR_PREFIX`]) whose `<name>` is not in
326    /// [`GitBackend::remotes`] - what a repository keeps after its remote
327    /// went (a fork that is not one any more). Names split like
328    /// [`crate::domain::split_remote_ref`] does (a configured `grp/sub`
329    /// owns its refs; the rest of `grp/` is the leftover `grp`), sorted.
330    /// [`GitBackend::remote_remove`] on such a name deletes those refs.
331    fn leftover_remotes(&self, repo: &RepoRef) -> Result<Vec<String>>;
332    /// Every worktree of `repo`, main one first (see [`Worktree`]).
333    fn worktrees(&self, repo: &RepoRef) -> Result<Vec<Worktree>>;
334    /// Every submodule `.gitmodules` declares, sorted by path, with its
335    /// state against what the superproject records. Top level only: a
336    /// submodule's own submodules are listed by that repository. An
337    /// uninitialized submodule is listed (state `Uninitialized`, no
338    /// `head`); a repository without `.gitmodules` answers an empty list
339    /// without spawning anything.
340    fn submodules(&self, repo: &RepoRef) -> Result<Vec<Submodule>>;
341    /// Registers submodules in `.git/config` (`git submodule init`), without
342    /// cloning anything. Empty `paths` is every submodule; an unknown path is
343    /// an error.
344    fn submodule_init(&self, repo: &RepoRef, paths: &[String]) -> Result<()>;
345    /// `git submodule update [--init] [--recursive] [-- paths]`: checks each
346    /// submodule out at the commit the superproject records, cloning it first
347    /// with `init`. May reach the network (the submodule's remote), so a
348    /// caller that cares about prompts applies `credentials.https_mode`
349    /// first, as the daemon does.
350    fn submodule_update(&self, repo: &RepoRef, opts: &SubmoduleUpdateOptions) -> Result<()>;
351    /// Turns any revision spelling git accepts (`HEAD`, `HEAD~2`, a
352    /// branch or tag name, a full or abbreviated sha) into the [`Oid`] of
353    /// the *commit* it names, peeling annotated tags on the way.
354    ///
355    /// The only sanctioned bridge from the strings CLI/MCP callers type to
356    /// the `Oid`s every mutating operation takes, so no frontend runs
357    /// `git rev-parse` outside the seam.
358    ///
359    /// An unresolvable revision is an `Err`, never a fallback to HEAD.
360    fn resolve(&self, repo: &RepoRef, rev: &str) -> Result<Oid>;
361
362    /// The best common ancestor of two commits (`git merge-base a b`), or
363    /// `None` when their histories share nothing. A read; the code review
364    /// view diffs `merge_base(base, head)..head`, which is what a host shows.
365    fn merge_base(&self, repo: &RepoRef, a: Oid, b: Oid) -> Result<Option<Oid>>;
366
367    /// `(ahead, behind)` of `tip` against `base`: the commits reachable from
368    /// `tip` but not from `base`, and the reverse (`rev-list --left-right
369    /// --count tip...base`). A read; the branching workflow's "behind its
370    /// parent by n".
371    fn ahead_behind(&self, repo: &RepoRef, tip: Oid, base: Oid) -> Result<(u32, u32)>;
372
373    /// Like [`Self::ahead_behind`] but patch-equivalent commits do not
374    /// count (`rev-list --cherry-pick --left-right --count local...remote`):
375    /// `(local_unmatched, remote_unmatched)`. A remote that only holds
376    /// older copies of rebased local commits reads `(n, 0)` here while
377    /// `ahead_behind` says it diverged. A read.
378    fn cherry_counts(&self, repo: &RepoRef, local: Oid, remote: Oid) -> Result<(u32, u32)>;
379
380    /// The paths a merge of `theirs` into `ours` would leave conflicted,
381    /// sorted and without duplicates, computed **without touching the work
382    /// tree, the index, HEAD or any ref** (proactive conflict detection).
383    /// Empty when the merge would go through, including when one commit
384    /// contains the other.
385    ///
386    /// `SystemGitBackend` runs `git merge-tree --write-tree --name-only -z`
387    /// (git 2.38 or later; an older git is `Error::Unsupported`) and
388    /// `Git2Backend` merges the two commits in memory. Both detect renames,
389    /// so rename/modify merges cleanly on both and the sets agree; a merge
390    /// can write the merged blobs and trees into the object database as
391    /// unreferenced objects, which `git gc` collects.
392    fn predict_merge_conflicts(
393        &self,
394        repo: &RepoRef,
395        ours: Oid,
396        theirs: Oid,
397    ) -> Result<Vec<String>>;
398
399    /// A file's *content* - as opposed to a diff of it - at a commit,
400    /// at the index, or on disk (see [`BlobSource`]).
401    ///
402    /// `path` is always relative to the repository root, with `/`
403    /// separators, matching every other path in the domain.
404    ///
405    /// A binary or oversized file is a successful [`Blob`] whose
406    /// [`crate::domain::BlobContent`] says so, not an `Err`: "this is a
407    /// 4 GiB PNG" is something a file viewer renders. Both backends learn
408    /// the size before reading anything, so an oversized file is never
409    /// pulled into memory just to be rejected. A path that does not
410    /// exist at `source` *is* an `Err`.
411    fn read_blob(&self, repo: &RepoRef, path: &Path, source: &BlobSource) -> Result<Blob>;
412
413    /// A file's **exact bytes** at `source` (same sources and path rules as
414    /// [`GitBackend::read_blob`]): no smudge filter, no decoding. What an
415    /// image viewer needs, since `read_blob` drops the bytes of a binary
416    /// file.
417    ///
418    /// The size is learned first; above `max` bytes the answer is
419    /// [`crate::domain::BlobBody::TooLarge`] and nothing is read. An LFS
420    /// pointer comes back as `BlobBody::Lfs`, carrying the real object when
421    /// it is in the local LFS store and within `max`. A path that does not
422    /// exist at `source` is an `Err`.
423    fn read_blob_bytes(
424        &self,
425        repo: &RepoRef,
426        path: &Path,
427        source: &BlobSource,
428        max: u64,
429    ) -> Result<crate::domain::BlobBytes>;
430
431    /// Every path present in the repository **at** `at`, sorted, with
432    /// `/` separators - the whole tree, not the subset a commit changed
433    /// (what the `View all files` toggle needs).
434    ///
435    /// Directories are not listed; a caller wanting a folder view derives
436    /// it from the path list.
437    fn list_tree(&self, repo: &RepoRef, at: Oid) -> Result<Vec<PathBuf>>;
438
439    /// The lines of the files **at** `at` that contain any of `terms`
440    /// (plain strings, case-sensitive), at most `max_hits` for each term,
441    /// sorted by path then line. A read: nothing is journaled.
442    ///
443    /// Binary files, LFS pointers and files over
444    /// [`crate::domain::MAX_GREP_FILE_BYTES`] are skipped; blank terms are
445    /// ignored (see [`crate::domain::grep_bytes`] for the rules both
446    /// backends share). An unknown revision is an `Err`.
447    fn grep_tree(
448        &self,
449        repo: &RepoRef,
450        at: Oid,
451        terms: &[String],
452        max_hits: usize,
453    ) -> Result<Vec<crate::domain::GrepHit>>;
454
455    /// Per-line attribution for `path` as of the commit `at`.
456    ///
457    /// Always a committed revision: blaming a dirty working tree would
458    /// attribute half the lines to git's "Not Committed Yet" pseudo-commit,
459    /// whose zero oid nothing downstream can click through to. Callers
460    /// that want "blame what I'm looking at" resolve a commit first.
461    ///
462    /// The returned lines are the same lines [`GitBackend::read_blob`]
463    /// would produce for `BlobSource::Commit(at)`, in the same order --
464    /// they share [`crate::domain::BlobContent::from_bytes`] - so a
465    /// blame gutter can be drawn beside file content without the two
466    /// disagreeing about where a line is.
467    ///
468    /// Whole-file renames are followed (blame's default): a line born
469    /// under an old name carries that name in `BlameLine::orig_path`.
470    /// Lines are not chased across files (no `-M`/`-C` line movement).
471    fn blame(&self, repo: &RepoRef, path: &Path, at: Oid) -> Result<Blame>;
472
473    /// The commits that changed `path`, newest first, **following renames**
474    /// (`git log --follow`), starting from `start` and returning at most
475    /// `limit` entries after skipping `skip`.
476    ///
477    /// - History is the default simplified history, not first-parent: a
478    ///   merge appears only when the file differs from every parent (a
479    ///   conflict resolution), and both sides of a kept merge are walked.
480    ///   A kept merge reports its change and line counts against its
481    ///   **first** parent.
482    /// - A file deleted then re-added shows the re-adding commit as
483    ///   `Added`, the deleting one as `Deleted`, and keeps going back.
484    /// - Lazy: the walk stops once `skip + limit + 1` entries are known
485    ///   (the extra one sets `FileHistoryPage::more`), so the first page
486    ///   of a huge history is cheap; deep pages cost their depth.
487    /// - A path that never existed at or before `start` is an empty page.
488    fn file_history(
489        &self,
490        repo: &RepoRef,
491        path: &Path,
492        start: Oid,
493        skip: usize,
494        limit: usize,
495    ) -> Result<FileHistoryPage>;
496
497    // -- staging (every granularity funnels through StageTarget) --
498    fn stage(&self, repo: &RepoRef, target: &StageTarget) -> Result<()>;
499    fn unstage(&self, repo: &RepoRef, target: &StageTarget) -> Result<()>;
500
501    // -- history mutation --
502    fn commit(&self, repo: &RepoRef, message: &str, opts: &CommitOptions) -> Result<Oid>;
503    fn checkout(&self, repo: &RepoRef, target: &CheckoutTarget) -> Result<()>;
504    /// Discards every uncommitted change to each of `paths` (relative to
505    /// the repository root, `/`-separated): a tracked path's index entry
506    /// and working-tree copy are both reset back to `HEAD`, and a path with
507    /// no `HEAD` entry (untracked, or staged but never committed) is
508    /// removed from the index if present and deleted from the working tree.
509    ///
510    /// Unlike [`CheckoutTarget::File`] (one already-tracked path from a
511    /// caller-supplied commit), this takes several paths and handles
512    /// untracked ones, which are not a `checkout` source at all.
513    ///
514    /// Empty `paths` is a no-op success. A missing path, or one with
515    /// nothing to discard, is not an error: discarding is idempotent, so a
516    /// caller racing another client's discard sees success.
517    fn discard(&self, repo: &RepoRef, paths: &[String]) -> Result<()>;
518    /// Reverts one hunk, or some changed lines of one hunk, of a file's
519    /// **unstaged** changes in the working tree - the
520    /// working-tree half of what [`GitBackend::unstage`] does to the index
521    /// with the same selection, and the "Discard Hunk" / "Discard
522    /// this line" actions.
523    ///
524    /// The target is resolved against a working-tree-vs-index diff the
525    /// backend computes itself, numbered as [`StageTarget::Hunk`] /
526    /// [`StageTarget::Line`] are when staging. The index is never touched:
527    /// a line that is staged *and* then edited again goes back to its
528    /// staged content, not to `HEAD`'s. Only the named lines change on
529    /// disk; every other change in the file, in that hunk or another,
530    /// survives.
531    ///
532    /// Selecting an added line removes it from the file; selecting a
533    /// removed line puts it back. An unknown hunk, or a selection whose
534    /// patch no longer applies (the file moved underneath the caller), is
535    /// an error and leaves the file exactly as it was.
536    fn discard_part(&self, repo: &RepoRef, target: &DiscardTarget) -> Result<()>;
537    fn branch_create(&self, repo: &RepoRef, name: &str, at: Oid) -> Result<()>;
538    /// Create the local branch `local_name` tracking the remote-tracking
539    /// branch `upstream` (spelled the way `RefKind::RemoteBranch` spells
540    /// it, `origin/feature/login`) and check it out - what
541    /// `git checkout -b <local_name> --track <upstream>` does, in one
542    /// operation.
543    ///
544    /// One call because the three steps are only ever wanted together, and
545    /// separate daemon round trips can interleave with another client's
546    /// mutation, leaving a branch created but not checked out.
547    ///
548    /// An existing `local_name` is an **error**, never a silent checkout of
549    /// that branch; callers wanting that call [`GitBackend::checkout`].
550    fn branch_create_tracking(
551        &self,
552        repo: &RepoRef,
553        local_name: &str,
554        upstream: &str,
555    ) -> Result<()>;
556    fn branch_delete(&self, repo: &RepoRef, name: &str) -> Result<()>;
557    fn branch_rename(&self, repo: &RepoRef, old_name: &str, new_name: &str) -> Result<()>;
558    /// Sets the local branch `branch`'s upstream to the remote-tracking
559    /// branch `upstream` (spelled `origin/feature`, as
560    /// `RefKind::RemoteBranch` joins it), or removes it with `None` --
561    /// `git branch --set-upstream-to` / `--unset-upstream`.
562    ///
563    /// The upstream must exist: pointing a branch at a remote branch
564    /// nobody has fetched is an error rather than config that silently
565    /// names nothing. Unsetting an upstream that is not set is a
566    /// success - the state asked for is the state reached.
567    fn branch_set_upstream(
568        &self,
569        repo: &RepoRef,
570        branch: &str,
571        upstream: Option<&str>,
572    ) -> Result<()>;
573
574    /// Moves the local branch `branch` forward to the commit `target`,
575    /// **only** when that is a fast-forward - the
576    /// `Fast-forward <branch> to <other>` action.
577    ///
578    /// - `branch`'s tip an ancestor of `target`: the branch moves there.
579    ///   If it is the branch checked out in *this* worktree, the index and
580    ///   working tree follow, as `git merge --ff-only` does; local changes
581    ///   that the move would overwrite refuse it, with nothing changed.
582    ///   Any other branch just has its ref moved (`git fetch . a:b`'s
583    ///   semantics) and no file is touched.
584    /// - `target` already contained in `branch` (the same commit, or
585    ///   behind it): [`FastForwardOutcome::UpToDate`], nothing moves.
586    /// - The two diverged: [`crate::Error::NotFastForward`], nothing moves.
587    ///
588    /// A branch checked out in *another* linked worktree is refused:
589    /// moving it would leave that worktree's files describing the old
590    /// commit, which is what `git fetch . a:b` refuses too.
591    fn fast_forward(&self, repo: &RepoRef, branch: &str, target: Oid)
592        -> Result<FastForwardOutcome>;
593
594    /// Adds a linked worktree at `path` (`git worktree add`), on the
595    /// branch or commit [`WorktreeAddOptions`] names, optionally on a
596    /// new branch created there, and returns its entry as
597    /// [`GitBackend::worktrees`] would list it.
598    ///
599    /// `path` must not exist, or be an empty directory - git's own rule.
600    /// Missing parent directories are created. A branch already checked
601    /// out in another worktree, a `new_branch` name already taken, and a
602    /// `WorktreeStart::Branch` that is not a local branch are errors, and
603    /// leave no worktree behind.
604    fn worktree_add(
605        &self,
606        repo: &RepoRef,
607        path: &Path,
608        opts: &WorktreeAddOptions,
609    ) -> Result<Worktree>;
610
611    /// The uncommitted changes of the worktree at `path` (tracked and
612    /// untracked, not ignored), in path order. Empty when it is clean.
613    fn worktree_changes(&self, repo: &RepoRef, path: &Path) -> Result<Vec<WorktreeChange>>;
614
615    /// Removes the linked worktree at `path` (`git worktree remove`).
616    ///
617    /// The main worktree is refused. A worktree with uncommitted changes
618    /// is refused unless `opts.force`, or unless `opts.commit` / `opts.stash`
619    /// first saves them (commit on the worktree's branch, or a
620    /// `stash push -u`); a refusal leaves the worktree untouched. A
621    /// locked worktree is refused. Not journaled: removing the folder
622    /// cannot be undone, but a commit or stash made first stays.
623    fn worktree_remove(
624        &self,
625        repo: &RepoRef,
626        path: &Path,
627        opts: &WorktreeRemoveOptions,
628    ) -> Result<WorktreeRemoved>;
629
630    /// Writes `source` out as a patch file at `dest` (`git format-patch`
631    /// for commits/ranges, `git diff HEAD --binary` for the working
632    /// tree).
633    ///
634    /// Refuses, writing nothing, when: `dest` already exists; `dest`'s
635    /// parent directory does not exist; the resulting patch would be
636    /// empty; a [`PatchSource::Commits`] entry is a merge commit or
637    /// names an unknown commit; or the working tree's `HEAD` is unborn
638    /// (`PatchSource::WorkingTree` on a repository with no commits).
639    fn patch_create(
640        &self,
641        repo: &RepoRef,
642        source: &PatchSource,
643        dest: &Path,
644    ) -> Result<PatchCreated>;
645
646    /// Applies `patch` (a file on disk, in `git apply`'s format) to the
647    /// working tree only - never the index - via `git apply`.
648    ///
649    /// Atomic: a patch that does not apply cleanly changes nothing.
650    fn patch_apply(&self, repo: &RepoRef, patch: &Path) -> Result<PatchApplied>;
651
652    /// Replays the changes `commit` made (its diff against its parent, or
653    /// against the empty tree for a root commit) onto the working tree
654    /// only - never the index, never HEAD. Binary files and line endings
655    /// come out as in the commit.
656    ///
657    /// All or nothing: when any file does not apply cleanly, nothing is
658    /// changed and the error says why. A merge commit is refused with
659    /// [`crate::Error::ApplyRefused`]. Returns the touched paths.
660    fn apply_commit_to_worktree(&self, repo: &RepoRef, commit: Oid) -> Result<PatchApplied>;
661
662    fn tag_create(
663        &self,
664        repo: &RepoRef,
665        name: &str,
666        at: Oid,
667        annotated_message: Option<&str>,
668    ) -> Result<()>;
669    fn tag_delete(&self, repo: &RepoRef, name: &str) -> Result<()>;
670
671    /// Replaces the existing tag `name` with an *annotated* tag carrying
672    /// `message`, at the same commit.
673    ///
674    /// Separate from `tag_create(.., force: true)` because it must *keep*
675    /// the tag where it is: both backends read the tag's own peeled commit
676    /// and put it back there (pinned by the contract). Annotating a tag
677    /// that does not exist is an error; annotating an already-annotated
678    /// one replaces its message.
679    fn tag_annotate(&self, repo: &RepoRef, name: &str, message: &str) -> Result<()>;
680
681    /// Sends tags to `remote` - one named tag, several, or every tag no
682    /// remote is known to have (see [`crate::domain::TagSelection`]).
683    ///
684    /// One operation so the frontends get one result, one broadcast and one
685    /// credential prompt for what the user did as one gesture.
686    ///
687    /// Both backends must also **record the push locally**, by writing the
688    /// mirror refs described at
689    /// [`crate::domain::REMOTE_TAG_MIRROR_PREFIX`]; otherwise the tag keeps
690    /// its "unpushed" marker until the next fetch.
691    ///
692    /// The returned [`PushOutcome::pushed_refs`] holds the tag names
693    /// actually sent, in the order they were sent. Pushing an empty
694    /// selection is a success reporting nothing.
695    async fn tag_push(
696        &self,
697        repo: &RepoRef,
698        remote: &str,
699        selection: &crate::domain::TagSelection,
700    ) -> Result<PushOutcome>;
701
702    /// Deletes tag `name` from `remote` (`git push --delete`), leaving
703    /// the local tag alone.
704    ///
705    /// [`GitBackend::tag_delete`] is the other half and must not touch the
706    /// remote either.
707    ///
708    /// Drops the tag's mirror ref on success, as `tag_push` writes one.
709    async fn tag_delete_remote(&self, repo: &RepoRef, remote: &str, name: &str) -> Result<()>;
710
711    /// Fetches the single tag `name` from `remote` into `refs/tags/` - the
712    /// "Fetch this tag" of a remote-only tag. Never overwrites: a local
713    /// tag of that name at another commit is an error, not a silent loss.
714    /// Network. The remote tag mirror already knows the tag, so it is
715    /// not rewritten.
716    async fn tag_fetch(&self, repo: &RepoRef, remote: &str, name: &str) -> Result<()>;
717
718    /// Deletes branch `name` from `remote` (`push --delete`), leaving
719    /// any local branch of that name alone; the remote-tracking ref goes
720    /// with it. The remote twin of [`GitBackend::branch_delete`], which
721    /// must not touch the remote.
722    async fn branch_delete_remote(&self, repo: &RepoRef, remote: &str, name: &str) -> Result<()>;
723
724    /// What `remote` holds at the fully qualified `full_ref` (`refs/heads/x`
725    /// or `refs/tags/v1`) right now, asked of the server (`ls-remote`);
726    /// `None` when it has no such ref. For an annotated tag, the tag object.
727    /// A network read, never answered from local tracking refs. It is the
728    /// value an undo of a remote deletion records and later checks.
729    async fn remote_ref_value(
730        &self,
731        repo: &RepoRef,
732        remote: &str,
733        full_ref: &str,
734    ) -> Result<Option<Oid>>;
735
736    /// Moves the branch or tag `full_ref` on `remote` from `expect` to `new`,
737    /// never forced: `Some(oid)` pushes that object there (it re-creates a
738    /// deleted ref when `expect` is `None`), `None` deletes the ref. The
739    /// remote must hold `expect` at that moment (a lease); if it moved on,
740    /// [`crate::Error::PushRejected`] with `StaleLease` comes back and
741    /// nothing changed. An object this repository no longer has is
742    /// [`crate::Error::UndoRefused`] with `RemoteObjectMissing`. Network.
743    /// The remote-tracking ref (branch) or remote-tag mirror (tag) follows.
744    async fn remote_ref_update(
745        &self,
746        repo: &RepoRef,
747        remote: &str,
748        full_ref: &str,
749        new: Option<Oid>,
750        expect: Option<Oid>,
751    ) -> Result<()>;
752    fn merge(&self, repo: &RepoRef, from: &Ref, opts: &MergeOptions) -> Result<MergeOutcome>;
753    fn rebase(&self, repo: &RepoRef, onto: &Ref, opts: &RebaseOptions) -> Result<RebaseOutcome>;
754
755    /// The range an interactive rebase from `upstream` would replay,
756    /// oldest first - what a frontend builds an [`InteractiveRebase`]
757    /// plan's `steps` from. `upstream: None` means the whole history
758    /// (`--root`). A read.
759    fn rebase_plan(&self, repo: &RepoRef, upstream: Option<Oid>) -> Result<RebasePlanDraft>;
760
761    /// Runs an interactive rebase from an explicit, pre-decided todo list
762    /// rather than an interactively edited one - the plan a frontend
763    /// built (possibly from [`GitBackend::rebase_plan`]), validated
764    /// again here regardless.
765    ///
766    /// Refuses (leaving the repository untouched) with
767    /// [`crate::Error::RebaseRefused`] when: another operation is in
768    /// progress, the working tree is dirty, `req.upstream` is not an
769    /// ancestor of HEAD, the range contains a merge commit, `req.steps`
770    /// is not exactly a permutation of the range, a `Squash`/`Fixup` step
771    /// is first, or a `Reword` step has no message.
772    ///
773    /// Never consults the user's `sequence.editor`/`core.editor`/
774    /// `rebase.autoSquash` config - the plan given here is authoritative.
775    fn rebase_interactive(&self, repo: &RepoRef, req: &InteractiveRebase) -> Result<RebaseOutcome>;
776
777    /// The state of a rebase (interactive or plain) currently in
778    /// progress, or `None` if none is. A read.
779    fn rebase_state(&self, repo: &RepoRef) -> Result<Option<RebaseState>>;
780
781    /// Resumes a rebase stopped by a conflict or an `edit` step
782    /// (`git rebase --continue`). [`crate::Error::RebaseRefused`] with
783    /// [`crate::domain::RebaseRefusal::NoRebaseInProgress`] if none is
784    /// running.
785    fn rebase_continue(&self, repo: &RepoRef) -> Result<RebaseOutcome>;
786
787    /// Skips the commit a rebase is stopped at (`git rebase --skip`).
788    fn rebase_skip(&self, repo: &RepoRef) -> Result<RebaseOutcome>;
789
790    /// Aborts a rebase in progress, restoring the branch and HEAD to
791    /// where they were before it started (`git rebase --abort`).
792    fn rebase_abort(&self, repo: &RepoRef) -> Result<()>;
793
794    fn cherry_pick(
795        &self,
796        repo: &RepoRef,
797        commits: &[Oid],
798        opts: &CherryPickOptions,
799    ) -> Result<CherryPickOutcome>;
800    /// Reverts `commit` with a new commit. A merge commit needs
801    /// `mainline`: the 1-based number of the parent whose side is kept
802    /// (`git revert -m`); `None` on a merge commit is an error.
803    fn revert(&self, repo: &RepoRef, commit: Oid, mainline: Option<u32>) -> Result<RevertOutcome>;
804    fn reset(&self, repo: &RepoRef, target: Oid, mode: ResetMode) -> Result<()>;
805
806    /// Gives `commit` the message `message`, keeping everything else.
807    ///
808    /// `commit` must be HEAD or an ancestor of HEAD. The commit is
809    /// re-created with the same tree, parents and author (name, email
810    /// *and date*); every commit between it and HEAD - the descendants
811    /// that are ancestors of HEAD - is then re-created on top of it,
812    /// again with its own tree, author and message, so merges among them
813    /// are kept as merges with their other parents untouched. Committer
814    /// is the current identity at the current time, as with `git rebase`
815    /// or `git commit --amend`. Finally the checked-out branch (or a
816    /// detached HEAD) moves to the new tip, with `ORIG_HEAD` and a reflog
817    /// entry recording the old one.
818    ///
819    /// Only messages change, so the rewrite cannot conflict and **the index
820    /// and working tree are never touched**: on HEAD this is an amend of
821    /// the message alone (staged changes stay staged, *not* folded in as
822    /// `git commit --amend` would), and a dirty working tree is no reason
823    /// to refuse. No rebase runs, so the repository is never left
824    /// mid-operation: either the branch moved or nothing did.
825    ///
826    /// The message is stored as [`crate::domain::normalize_reword_message`]
827    /// leaves it. Refusals are [`crate::Error::RewordRefused`]: the
828    /// commit is not on the current branch, a merge/rebase/... is in
829    /// progress, or the message is empty. Other branches or tags pointing
830    /// into the rewritten range are left where they are, as `git rebase`
831    /// leaves them.
832    fn reword(&self, repo: &RepoRef, commit: Oid, message: &str) -> Result<RewordOutcome>;
833
834    /// [`GitBackend::reword`] generalised to the commit's other
835    /// properties: whichever of `amend`'s message, author name/email/date
836    /// and committer name/email/date are `Some` replace the commit's; the
837    /// rest (tree, parents, every `None`) is kept. Same walk, same
838    /// descendants re-created on top (their own authors kept), same
839    /// guarantees (index and working tree untouched, no rebase) and the
840    /// same typed refusals, plus `InvalidIdentity` and `InvalidDate`;
841    /// [`crate::domain::CommitAmend::resolve`] runs first. Unless a
842    /// committer field says otherwise the committer is the current
843    /// identity, now. The reflog entry reads `amend: <oid> <summary>`.
844    fn amend_commit(
845        &self,
846        repo: &RepoRef,
847        commit: Oid,
848        amend: &CommitAmend,
849    ) -> Result<RewordOutcome>;
850
851    /// The pieces `commit` can be split into, numbered with `--no-renames`
852    /// (never from `diff(CommitVsParent)`, which honours `diff.renames`).
853    /// Text-modified files list hunks; binary, mode-only, added, deleted,
854    /// submodule and LFS files are whole-only. A read.
855    fn split_source(&self, repo: &RepoRef, commit: Oid) -> Result<SplitSource>;
856
857    /// Breaks `req.commit` into `req.parts` (oldest first) by plumbing, as
858    /// `reword` does: the last part carries the original tree, the
859    /// descendants are re-created on top, the index and working tree are
860    /// never touched. Refusals are [`crate::Error::SplitRefused`] and
861    /// [`crate::domain::validate_split`] runs first.
862    fn split_commit(&self, repo: &RepoRef, req: &SplitCommit) -> Result<SplitOutcome>;
863
864    // -- history rewrite (the history-rewrite design) --
865    /// Computes `recipe` into a temporary pack under the repository's
866    /// `gitpoulpi/rewrite/<run>/` directory and describes the result; no ref
867    /// and no object store moves. A read. The preview is the real run:
868    /// [`GitBackend::rewrite_apply`] indexes exactly that pack. `progress`
869    /// returning `Break` cancels and leaves nothing behind. Refusals are
870    /// [`crate::Error::RewriteRefused`];
871    /// [`crate::domain::rewrite::validate_recipe`] runs first.
872    fn rewrite_preview(
873        &self,
874        repo: &RepoRef,
875        recipe: &Recipe,
876        progress: RewriteProgressSink<'_>,
877    ) -> Result<RewritePlan>;
878
879    /// Indexes the previewed pack and moves every ref in one transaction with
880    /// compare-and-swap on the old values (a moved ref fails the whole run,
881    /// `RewriteRefusal::Stale`). Journaled by the daemon as one entry.
882    fn rewrite_apply(&self, repo: &RepoRef, plan: &RewritePlan) -> Result<RewriteOutcome>;
883
884    /// Applies a preview whose recipe extracts a subdirectory as a new
885    /// repository (`ExtractMode::Clone` or `Submodule`) instead of moving
886    /// this repository's refs: a `git clone --no-local` of this repository
887    /// into `target` (a folder that does not exist or is empty) is rewritten
888    /// there with the recipe, then cleaned of the old history. `Clone` leaves
889    /// this repository untouched and the outcome moves no ref here;
890    /// `Submodule` also adds one commit to the current branch that replaces
891    /// the folder by a submodule of `target` (the outcome's one ref change),
892    /// the old history stays. Journaled by the daemon (a submodule commit is
893    /// undone by moving the branch back). `Error::RewriteRefused` otherwise.
894    fn rewrite_extract(
895        &self,
896        _repo: &RepoRef,
897        _plan: &RewritePlan,
898        _target: &Path,
899    ) -> Result<RewriteOutcome> {
900        Err(crate::Error::Unsupported {
901            operation: "rewrite extract",
902        })
903    }
904
905    /// Deletes a preview's temporary objects. Idempotent.
906    fn rewrite_discard(&self, repo: &RepoRef, run: &RunId) -> Result<()>;
907
908    /// A previewed plan, without its rows, rebuilt from the run directory
909    /// the preview left (so a preview outlives its daemon). `None` when the
910    /// run is gone or its stored plan does not hash to its digest.
911    fn rewrite_load(&self, _repo: &RepoRef, _run: &RunId) -> Result<Option<RewritePlan>> {
912        Ok(None)
913    }
914
915    /// What an applied run moved, from the record its apply left in the run
916    /// directory (`moved.json`), with the directory the maps are in. This is
917    /// what the collaborator note and the push are built from; it outlives
918    /// the daemon. `RewriteRefusal::Stale` when the run was not applied here
919    /// or its directory was swept.
920    fn rewrite_record(
921        &self,
922        _repo: &RepoRef,
923        _run: &RunId,
924    ) -> Result<crate::domain::rewrite::RewriteRecord> {
925        Err(crate::Error::Unsupported {
926            operation: "rewrite record",
927        })
928    }
929
930    /// The run's `commit-map` and `ref-map` (git-filter-repo's format),
931    /// copied to `out` when given. A read.
932    fn rewrite_maps(
933        &self,
934        _repo: &RepoRef,
935        _run: &RunId,
936        _out: Option<&Path>,
937    ) -> Result<crate::domain::rewrite::RewriteMaps> {
938        Err(crate::Error::Unsupported {
939            operation: "rewrite maps",
940        })
941    }
942
943    /// Pushes the refs an applied run moved that were on a remote, each with
944    /// `--force-with-lease=<ref>:<the remote's id when the preview ran>`
945    /// (never a plain force), one `--atomic` push per remote where the
946    /// server allows it. Protected refs are left out unless asked for. A
947    /// rejection is a per-ref status in the answer, not an error. Not
948    /// journaled and not undoable; the record of what was pushed lets a later
949    /// undo of the rewrite warn.
950    async fn push_rewritten(
951        &self,
952        _repo: &RepoRef,
953        _req: &crate::domain::rewrite::PushRewritten,
954    ) -> Result<crate::domain::rewrite::PushRewrittenOutcome> {
955        Err(crate::Error::Unsupported {
956            operation: "push rewritten",
957        })
958    }
959
960    /// Deletes the old history of rewrite journal entries from this
961    /// repository for good: drops the entries' undo pins, expires the
962    /// reflogs that name the old commits, removes the applied runs' folders,
963    /// prunes the object store (`gc --prune=now`), then checks that every
964    /// object reachable only from the old tips is gone. Anything that still
965    /// holds the old history (a branch outside the rewrite's scope, a stash,
966    /// another worktree's HEAD, a remote-tracking ref, a pin of an entry that
967    /// is not part of the request, ...) is a typed
968    /// [`crate::domain::rewrite::PurgeBlocker`] and the call changes
969    /// **nothing** (`PurgeStatus::Blocked`). With `dry_run` it only reports
970    /// (`Ready` or `Blocked`). Stashes are never expired. Not journaled and
971    /// not undoable; the daemon marks the entries `Purged`. `progress` is told
972    /// each step; there is no cancel.
973    fn rewrite_purge(
974        &self,
975        _repo: &RepoRef,
976        _req: &crate::domain::rewrite::PurgeRequest,
977        _progress: crate::domain::rewrite::PurgeProgressSink<'_>,
978    ) -> Result<crate::domain::rewrite::PurgeOutcome> {
979        Err(crate::Error::Unsupported {
980            operation: "rewrite purge",
981        })
982    }
983
984    /// What a content rule did to `path` in the preview's commit `commit`:
985    /// the old and the new file, diffed (the new one is read back from the
986    /// preview's temporary pack). Lines a secret rule removed are hidden. A
987    /// read. `RewriteRefusal::Stale` when the run is gone.
988    fn rewrite_blob_diff(
989        &self,
990        _repo: &RepoRef,
991        _run: &RunId,
992        _commit: Oid,
993        _path: &str,
994    ) -> Result<crate::domain::rewrite::BlobChange> {
995        Err(crate::Error::Unsupported {
996            operation: "rewrite blob diff",
997        })
998    }
999
1000    /// Compiles a script (an inline text, or a file of the repository) and
1001    /// reports its header, the functions it defines and every problem. A
1002    /// syntax error is a problem in the answer, not an error. A read.
1003    /// `Error::Unsupported` without the `rewrite-scripts` feature.
1004    ///
1005    /// An external script (shell, Python, external Lua) is checked against
1006    /// `policy` first: its language switched off is
1007    /// `RewriteRefusal::ScriptsDisabled`, its interpreter missing
1008    /// `RewriteRefusal::ToolMissing`; the answer carries the script's content
1009    /// hash and whether `policy` trusts it (an untrusted script is an answer,
1010    /// not an error, and is not run); a trusted one gets a dry handshake.
1011    fn rewrite_script_check(
1012        &self,
1013        _repo: &RepoRef,
1014        _script: &crate::domain::rewrite::ScriptRef,
1015        _policy: &crate::domain::rewrite::ScriptPolicy,
1016    ) -> Result<crate::domain::rewrite::script::ScriptCheck> {
1017        Err(crate::Error::Unsupported {
1018            operation: "rewrite script check",
1019        })
1020    }
1021
1022    /// Runs a script on `commits` (their original data, in history order,
1023    /// state carried across them) and returns what it would change. Nothing
1024    /// is written. `RewriteRefusal::ScriptFailed` names the commit and the
1025    /// reason. A read. An external script that `policy` does not allow, whose
1026    /// interpreter is missing or that is not trusted is refused before it
1027    /// runs (`ScriptsDisabled`, `ToolMissing`, `ScriptNotTrusted`).
1028    fn rewrite_script_test(
1029        &self,
1030        _repo: &RepoRef,
1031        _script: &crate::domain::rewrite::ScriptRef,
1032        _policy: &crate::domain::rewrite::ScriptPolicy,
1033        _commits: &[Oid],
1034    ) -> Result<Vec<crate::domain::rewrite::script::ScriptTestRow>> {
1035        Err(crate::Error::Unsupported {
1036            operation: "rewrite script test",
1037        })
1038    }
1039
1040    /// Scans the history of `scope` for secrets (token prefixes, private
1041    /// keys, passwords in URLs, `password = value` with enough entropy):
1042    /// every unique blob is read once, text only. The answer holds each
1043    /// finding's rule, path, first and last commit, counts and a redacted
1044    /// preview, never its value; a finding's id is stable, and a content rule
1045    /// with `scan: true` names findings by id (the backend resolves them at
1046    /// preview time). `progress` reports and can cancel. A read.
1047    fn rewrite_scan_secrets(
1048        &self,
1049        _repo: &RepoRef,
1050        _scope: &crate::domain::rewrite::Scope,
1051        _progress: crate::domain::rewrite::RewriteProgressSink<'_>,
1052    ) -> Result<crate::domain::rewrite::SecretScan> {
1053        Err(crate::Error::Unsupported {
1054            operation: "rewrite scan secrets",
1055        })
1056    }
1057
1058    /// The size analysis of the history `scope` walks (slice S18): the
1059    /// `top` largest blobs with their paths, first and last commit and
1060    /// whether they are still in HEAD, the biggest folders (unique blob
1061    /// bytes), the paths deleted from HEAD but kept by the history, and the
1062    /// totals with what removing the history-only data would free (an
1063    /// estimate: after a purge and a `gc` only). One `log --raw` pass plus
1064    /// one `cat-file --batch-check`. `progress` reports and can cancel. A read.
1065    fn rewrite_analyze(
1066        &self,
1067        _repo: &RepoRef,
1068        _scope: &crate::domain::rewrite::Scope,
1069        _top: u32,
1070        _progress: crate::domain::rewrite::RewriteProgressSink<'_>,
1071    ) -> Result<crate::domain::rewrite::SizeAnalysis> {
1072        Err(crate::Error::Unsupported {
1073            operation: "rewrite analyze",
1074        })
1075    }
1076
1077    // -- stash --
1078    /// `None`: there was nothing to stash ("No local changes to save"), no
1079    /// stash was made and nothing changed - callers record no undo entry.
1080    fn stash_push(
1081        &self,
1082        repo: &RepoRef,
1083        message: Option<&str>,
1084        include_untracked: bool,
1085    ) -> Result<Option<StashId>>;
1086    /// Stashes only `paths` (`git stash push -- <paths>`), leaving every
1087    /// other change where it is. Untracked files among `paths` are
1088    /// stashed too (they were asked for by name). An empty `paths` stashes
1089    /// everything, untracked files included.
1090    fn stash_push_paths(
1091        &self,
1092        repo: &RepoRef,
1093        message: Option<&str>,
1094        paths: &[String],
1095    ) -> Result<Option<StashId>>;
1096    fn stash_pop(&self, repo: &RepoRef, id: StashId) -> Result<()>;
1097    fn stash_apply(&self, repo: &RepoRef, id: StashId) -> Result<()>;
1098    fn stash_drop(&self, repo: &RepoRef, id: StashId) -> Result<()>;
1099    /// Puts the stash commit `commit` back on the stash list, at
1100    /// `stash@{0}` (`git stash store -m <message>`): how an undone drop or
1101    /// pop gets its stash back, with the very same commit. `commit` must
1102    /// be a stash commit (a merge of the base, the index and, maybe, the
1103    /// untracked files); anything else is an error and changes nothing.
1104    fn stash_store(&self, repo: &RepoRef, commit: Oid, message: &str) -> Result<()>;
1105    /// Builds a stash holding exactly the changes `commit` made (against
1106    /// its first parent, or the empty tree for a root commit) and puts it
1107    /// on top of the stash list, as `git stash store` would. The working
1108    /// tree, index and HEAD are not touched. `message` defaults to a text
1109    /// naming the commit. Returns the stash commit.
1110    fn stash_from_commit(&self, repo: &RepoRef, commit: Oid, message: Option<&str>) -> Result<Oid>;
1111    /// The repo-relative paths the stash commit `commit` holds changes
1112    /// for, untracked files included, sorted: what applying or popping it
1113    /// can touch. A read.
1114    fn stash_paths(&self, repo: &RepoRef, commit: Oid) -> Result<Vec<String>>;
1115
1116    // -- network (async: fetch/pull/push/clone hit the network) --
1117    /// Sets (or, with `None`, removes) how the network git processes of
1118    /// `repo` authenticate: they get `auth` instead of the process-wide
1119    /// credential mode and SSH key (ADR-0010). Held in memory, per
1120    /// repository, never persisted; no entry means the unchanged behaviour.
1121    /// Not a repository mutation: not journaled, not undoable. `Git2Backend`
1122    /// forwards it to its system-git fallback, which does all networking.
1123    fn set_network_auth(&self, repo: &RepoRef, auth: Option<NetworkAuth>);
1124    /// Connection test: `git ls-remote --heads` against `remote`'s fetch URL
1125    /// (its push URL with [`RemoteAccessOptions::push`]), with the
1126    /// repository's [`NetworkAuth`] applied like for any transfer. A failed
1127    /// connection is **not** an `Err`: it is a report with `ok: false` and a
1128    /// classified [`crate::ErrorDetail`]. `Err` is for a remote that does not
1129    /// exist or a git that cannot start. A read: nothing in the repository
1130    /// changes.
1131    async fn remote_access_check(
1132        &self,
1133        repo: &RepoRef,
1134        remote: &str,
1135        opts: &RemoteAccessOptions,
1136    ) -> Result<RemoteAccessReport>;
1137    async fn fetch(
1138        &self,
1139        repo: &RepoRef,
1140        remote: &str,
1141        opts: &FetchOptions,
1142    ) -> Result<FetchOutcome>;
1143    /// Fetches **every** configured remote (`git fetch --all`), with
1144    /// `--prune` when asked, and refreshes each remote's tag mirror the
1145    /// way [`GitBackend::fetch`] does for one.
1146    ///
1147    /// One operation rather than a frontend looping over `remotes()`:
1148    /// one result, one broadcast, and a remote added by another client a
1149    /// moment ago is included. `updated_refs` covers all remotes.
1150    async fn fetch_all(&self, repo: &RepoRef, opts: &FetchOptions) -> Result<FetchOutcome>;
1151    /// Fetches one `remote_ref` of `remote` that a normal fetch does not
1152    /// bring - a pull/merge request head such as `refs/pull/<n>/head` or
1153    /// `refs/merge-requests/<n>/head`, which is where a fork's commits
1154    /// live - and makes the local branch `branch` track it.
1155    ///
1156    /// The ref lands in `refs/remotes/<remote>/<branch>`; `branch` is
1157    /// created from it (with that as its upstream) or, when it already
1158    /// exists and is a strict ancestor, fast-forwarded. A branch with
1159    /// local commits of its own is left alone. Nothing is checked out
1160    /// (a *checked-out* `branch` is fast-forwarded in place); the caller
1161    /// checks it out. `remote_ref` must start with `refs/`.
1162    async fn fetch_ref_as_branch(
1163        &self,
1164        repo: &RepoRef,
1165        remote: &str,
1166        remote_ref: &str,
1167        branch: &str,
1168    ) -> Result<FetchOutcome>;
1169    /// Fetches one `[+]refs/<src>:refs/gitpoulpi/<dst>` spec from
1170    /// `remote` (a pull/merge request's head into `refs/gitpoulpi/pr/<n>`,
1171    /// for in-app review). Never a branch, tag or remote-tracking ref:
1172    /// the destination must sit strictly inside
1173    /// [`crate::domain::FETCH_REFSPEC_NAMESPACE`] and anything else is
1174    /// refused before git runs (see [`crate::domain::parse_fetch_refspec`]).
1175    /// Nothing is checked out, and the destination is force-updated (a
1176    /// request may be force-pushed). Not journaled and not undoable: it
1177    /// only refreshes a read-only cache ref no user workflow points at.
1178    /// Returns the destination ref in `updated_refs`.
1179    async fn fetch_refspec(
1180        &self,
1181        repo: &RepoRef,
1182        remote: &str,
1183        refspec: &str,
1184    ) -> Result<FetchOutcome>;
1185    /// Pulls into the checked-out branch, integrating as
1186    /// [`crate::domain::PullMode`] says - always explicitly, so the
1187    /// user's `pull.rebase` / `pull.ff` cannot change what was asked.
1188    ///
1189    /// A fast-forward-only pull of a diverged branch is
1190    /// [`crate::Error::NotFastForward`], with nothing changed.
1191    async fn pull(&self, repo: &RepoRef, opts: &PullOptions) -> Result<PullOutcome>;
1192    /// The download half of [`GitBackend::pull`]: fetches what the pull
1193    /// would integrate and touches nothing else (no index, working tree or
1194    /// `HEAD`), so the daemon can cancel it by dropping the future. The
1195    /// default does nothing: a backend without a separate download phase
1196    /// does it all in [`GitBackend::pull_integrate`].
1197    async fn pull_fetch(&self, _repo: &RepoRef, _opts: &PullOptions) -> Result<()> {
1198        Ok(())
1199    }
1200    /// The integrate half: merges, fast-forwards or rebases what
1201    /// [`GitBackend::pull_fetch`] downloaded, without touching the network,
1202    /// and gives `pull`'s outcome and errors. This is the point of no return
1203    /// of a pull: it rewrites the index and the working tree, so it must not
1204    /// be interrupted. The default is the whole `pull`.
1205    async fn pull_integrate(&self, repo: &RepoRef, opts: &PullOptions) -> Result<PullOutcome> {
1206        self.pull(repo, opts).await
1207    }
1208    /// Pushes a local branch (`opts.branch`, or the checked-out one) to
1209    /// the same-named branch on `remote`.
1210    ///
1211    /// A force push is only ever `--force-with-lease`. A rejection the
1212    /// user can act on - the remote diverged, or the lease found it
1213    /// moved - is the typed [`crate::Error::PushRejected`], never a
1214    /// string to parse.
1215    async fn push(&self, repo: &RepoRef, remote: &str, opts: &PushOptions) -> Result<PushOutcome>;
1216    /// Pushes `HEAD` to `refs/for/<branch>` on `remote` - how a Gerrit
1217    /// change is created - with the optional `%topic=<topic>` option.
1218    /// `branch` is the Gerrit target branch (`main`), not a local one. Never
1219    /// forced. Not journaled and not undoable: the change lives on the
1220    /// server (abandon it there). The default is `Unsupported`.
1221    async fn push_for_review(
1222        &self,
1223        _repo: &RepoRef,
1224        _remote: &str,
1225        _branch: &str,
1226        _topic: Option<&str>,
1227    ) -> Result<PushOutcome> {
1228        Err(crate::Error::Unsupported {
1229            operation: "push_for_review",
1230        })
1231    }
1232    async fn clone(&self, url: &str, dest: &Path, opts: &CloneOptions) -> Result<RepoRef>;
1233
1234    /// `clone`, reporting progress to `progress` as it goes.
1235    ///
1236    /// The default runs the plain `clone` and reports a single
1237    /// [`crate::domain::CloneProgress::done`] at the end, so a backend that
1238    /// cannot stream progress is still correct.
1239    ///
1240    /// Pinned by the contract suite: the last report is always `Done`/100,
1241    /// and `percent` never decreases within a phase.
1242    async fn clone_with_progress(
1243        &self,
1244        url: &str,
1245        dest: &Path,
1246        opts: &CloneOptions,
1247        progress: CloneProgressSink<'_>,
1248    ) -> Result<RepoRef> {
1249        let repo = self.clone(url, dest, opts).await?;
1250        progress(crate::domain::CloneProgress::done());
1251        Ok(repo)
1252    }
1253    fn remote_add(&self, repo: &RepoRef, name: &str, url: &str) -> Result<()>;
1254    /// Removes a remote (`git remote remove`) together with its remote-tracking
1255    /// branches and its tag mirror. On a *leftover* name (see
1256    /// [`GitBackend::leftover_remotes`]) there is no config to remove, so it
1257    /// deletes just those refs, never a configured sibling's (`<name>/sub`);
1258    /// a name that is neither is "no such remote".
1259    fn remote_remove(&self, repo: &RepoRef, name: &str) -> Result<()>;
1260    /// Renames a remote (`git remote rename`): its config section, its
1261    /// remote-tracking branches, every local branch's upstream that named
1262    /// it, *and* its tag mirror under
1263    /// [`crate::domain::REMOTE_TAG_MIRROR_PREFIX`] - or every tag it had
1264    /// would read as unpushed until the next fetch.
1265    fn remote_rename(&self, repo: &RepoRef, old_name: &str, new_name: &str) -> Result<()>;
1266    /// Sets a remote's fetch URL (`remote.<name>.url`).
1267    fn remote_set_url(&self, repo: &RepoRef, name: &str, url: &str) -> Result<()>;
1268    /// Sets a remote's separate push URL (`remote.<name>.pushurl`), or
1269    /// removes it with `None` so pushes go to the fetch URL again.
1270    /// [`crate::domain::Remote::push_url`] always reports the URL a push
1271    /// would actually use, so after `None` it equals the fetch URL.
1272    fn remote_set_push_url(&self, repo: &RepoRef, name: &str, url: Option<&str>) -> Result<()>;
1273
1274    /// The repository-local `core.sshCommand`, if one is set. Read-only
1275    /// companion of [`Self::set_ssh_command`].
1276    fn ssh_command(&self, repo: &RepoRef) -> Result<Option<String>>;
1277    /// Sets (or, with `None`, removes) the repository-local
1278    /// `core.sshCommand` - the opt-in way to make one repository use a
1279    /// profile's SSH key (ADR-0008). Clearing an unset value is not an
1280    /// error. Only `core.sshCommand` is reachable: this is deliberately
1281    /// not a general config write.
1282    fn set_ssh_command(&self, repo: &RepoRef, command: Option<&str>) -> Result<()>;
1283
1284    /// The repository-local value of `key` (the repo's own config file, not
1285    /// the global or system one), or `None` when unset. `key` must be on
1286    /// [`crate::repo_config::REPO_CONFIG_KEYS`] (`core.autocrlf`, `core.eol`).
1287    fn repo_config(&self, repo: &RepoRef, key: &str) -> Result<Option<String>>;
1288
1289    /// The entries of the repository-local config (`.git/config` only, not
1290    /// the global or system files) whose key starts, case-insensitively, with
1291    /// one of `prefixes` (`"gitflow."`, `"branch."`), as `(key, value)` in
1292    /// file order, keys spelled as `config --list` does (section and
1293    /// variable lower-cased, subsection as written). Not limited to the
1294    /// [`crate::repo_config::REPO_CONFIG_KEYS`] allow-list: it is read-only and
1295    /// meant for other tools' settings (git-flow, Git Town) and the recorded
1296    /// parent of a branch (`branch.<b>.gitpoulpi-parent`). An entry without a
1297    /// value is skipped.
1298    fn config_entries(&self, repo: &RepoRef, prefixes: &[&str]) -> Result<Vec<(String, String)>>;
1299    /// Sets (or, with `None`, removes) the repository-local `key`, so the
1300    /// repository inherits the global value again. Same allow-list as
1301    /// [`Self::repo_config`], and the value must be one the key accepts.
1302    /// Clearing an unset key is not an error.
1303    fn set_repo_config(&self, repo: &RepoRef, key: &str, value: Option<&str>) -> Result<()>;
1304
1305    // -- Sparse checkout (cone mode) --
1306    /// Whether the working tree is a sparse checkout, in which mode, and
1307    /// which directories are checked out. A repository that never enabled
1308    /// it reports `SparseState::default()` (disabled), never an error.
1309    fn sparse_checkout_status(&self, repo: &RepoRef) -> Result<SparseState>;
1310    /// Makes the checkout sparse (cone mode) showing exactly `dirs` plus
1311    /// the files at the root; replaces any earlier set, so directories left
1312    /// out disappear from the working tree and the new ones appear. `dirs`
1313    /// go through [`crate::domain::normalize_sparse_dirs`] (at least one,
1314    /// relative, no patterns). Not journaled: nothing is lost, "disable"
1315    /// brings every file back.
1316    fn sparse_checkout_set(&self, repo: &RepoRef, dirs: &[String]) -> Result<()>;
1317    /// Turns sparse checkout off: every file of the tree is checked out
1318    /// again. Disabling a repository that is not sparse is not an error.
1319    fn sparse_checkout_disable(&self, repo: &RepoRef) -> Result<()>;
1320
1321    // -- Git LFS (ADR 0009) --
1322    /// What is known about Git LFS in this repository: the `git-lfs`
1323    /// program's availability, whether the repository routes files
1324    /// through it, the tracked patterns, and whether its filters and hook
1325    /// are installed.
1326    ///
1327    /// A read that **never fails because `git-lfs` is missing**: that is
1328    /// `binary: LfsBinary::Missing` in the answer, so a frontend can
1329    /// explain it. Always re-probes the program (no stale cache).
1330    fn lfs_status(&self, repo: &RepoRef) -> Result<LfsRepoStatus>;
1331    /// Which external programs a history rewrite could use here (`gpg`,
1332    /// `ssh-keygen`, `gpgsm`, `git-lfs`, `python`, shells) and whether each
1333    /// works, with the install hint key for this OS. **The core rewrite
1334    /// actions need none of them** (see `RuleKind::required_tools`) and the
1335    /// embedded Lua is always there. Cached for a minute; `fresh` re-asks
1336    /// (the "Check again" button). Runs programs: never call it on a render
1337    /// thread. A read that never fails because a tool is missing.
1338    fn rewrite_tools(
1339        &self,
1340        repo: &RepoRef,
1341        fresh: bool,
1342    ) -> Result<crate::domain::rewrite::RewriteTools>;
1343    /// Signs a dummy payload once with the repository's signing setup
1344    /// (`gpg.format`, `user.signingkey`, `gpg.*.program`) and verifies it:
1345    /// the "Check signing" smoke test before a run that re-signs. May open a
1346    /// passphrase prompt. A broken setup is an `Ok` check with a `reason`,
1347    /// not an error. Runs programs: never on a render thread.
1348    fn rewrite_check_signing(&self, repo: &RepoRef)
1349        -> Result<crate::domain::rewrite::SigningCheck>;
1350    /// The LFS pointer files at a commit (`Some`) or in the index
1351    /// (`None`), each with whether its real object is in the local LFS
1352    /// store. Needs no `git-lfs` program. Empty for a repository that does
1353    /// not use LFS.
1354    fn lfs_files(&self, repo: &RepoRef, at: Option<Oid>) -> Result<Vec<LfsFile>>;
1355
1356    /// `git lfs install`: the clean / smudge filters and the LFS hooks,
1357    /// for this repository only (`Repository`, the default: `--local`) or
1358    /// the user's global git config (`User`). Needs the `git-lfs`
1359    /// program: [`crate::Error::LfsUnavailable`] otherwise, with nothing
1360    /// changed.
1361    fn lfs_install(&self, repo: &RepoRef, scope: LfsInstallScope) -> Result<()>;
1362    /// Routes `patterns` through LFS (`git lfs track`). Writes
1363    /// `.gitattributes` and leaves it **unstaged**, a visible working
1364    /// change. Returns every LFS pattern of the repository afterwards.
1365    /// With `opts.renormalize` the already-committed files that match are
1366    /// re-staged so their next commit stores pointers.
1367    fn lfs_track(
1368        &self,
1369        repo: &RepoRef,
1370        patterns: &[String],
1371        opts: &LfsTrackOptions,
1372    ) -> Result<Vec<LfsPattern>>;
1373    /// Stops routing `patterns` through LFS (`git lfs untrack`). Returns
1374    /// the LFS patterns left.
1375    fn lfs_untrack(&self, repo: &RepoRef, patterns: &[String]) -> Result<Vec<LfsPattern>>;
1376    /// `git lfs fetch <remote>`: download the LFS objects the current ref
1377    /// (or every ref with `opts.all_refs`) points at into the local LFS
1378    /// store, leaving the working tree alone. Network. Reports progress to
1379    /// `progress`; the last report is always `done: true`, and no
1380    /// direction's counters ever decrease (the contract suite pins both).
1381    /// Needs the `git-lfs` program ([`crate::Error::LfsUnavailable`]).
1382    async fn lfs_fetch(
1383        &self,
1384        repo: &RepoRef,
1385        remote: &str,
1386        opts: &LfsFetchOptions,
1387        progress: LfsProgressSink<'_>,
1388    ) -> Result<()>;
1389    /// `git lfs pull <remote>`: fetch, then replace the pointer files in
1390    /// the working tree with the real content. Network.
1391    async fn lfs_pull(
1392        &self,
1393        repo: &RepoRef,
1394        remote: &str,
1395        progress: LfsProgressSink<'_>,
1396    ) -> Result<()>;
1397    /// `git lfs checkout [paths]`: write the real content of every LFS
1398    /// pointer in the working tree (or only `paths`, relative to the
1399    /// root; empty means all) from the objects already in the local LFS
1400    /// store. Offline: it never downloads (that is `lfs_pull`). Installs
1401    /// the repository-local LFS filters first when they are missing, like
1402    /// `lfs_pull`. Not a journaled state change: it only expands pointers.
1403    /// Needs the `git-lfs` program ([`crate::Error::LfsUnavailable`]).
1404    async fn lfs_checkout(
1405        &self,
1406        repo: &RepoRef,
1407        paths: &[PathBuf],
1408        progress: LfsProgressSink<'_>,
1409    ) -> Result<()>;
1410    /// `git lfs push <remote>`: upload the LFS objects of the current
1411    /// branch (or of every ref with `opts.all_refs`). Network; a
1412    /// mutation of the remote.
1413    async fn lfs_push(
1414        &self,
1415        repo: &RepoRef,
1416        remote: &str,
1417        opts: &LfsPushOptions,
1418        progress: LfsProgressSink<'_>,
1419    ) -> Result<()>;
1420    /// The file locks held on the LFS server behind `remote`, each marked
1421    /// `ours` when the current user holds it. Network; a read (never
1422    /// broadcasts `RepoChanged`). Locking is a server feature reached with
1423    /// the remote's own credentials. A server without locking answers
1424    /// git-lfs's `locks` with an empty list, so that is what this returns;
1425    /// [`crate::Error::LfsLockingUnsupported`] comes from `lfs_lock`.
1426    async fn lfs_locks(&self, repo: &RepoRef, remote: &str) -> Result<Vec<LfsLock>>;
1427    /// Locks `path` on the server, so nobody else can lock or push
1428    /// changes to it. Network. A server without the locking API is
1429    /// [`crate::Error::LfsLockingUnsupported`].
1430    async fn lfs_lock(&self, repo: &RepoRef, remote: &str, path: &Path) -> Result<LfsLock>;
1431    /// Releases the lock on `path`. Somebody else's lock is refused unless
1432    /// `force` (which breaks it: destructive). Network.
1433    async fn lfs_unlock(
1434        &self,
1435        repo: &RepoRef,
1436        remote: &str,
1437        path: &Path,
1438        force: bool,
1439    ) -> Result<()>;
1440    /// `git lfs prune`: delete old, already-pushed objects from the local
1441    /// LFS store.
1442    fn lfs_prune(&self, repo: &RepoRef) -> Result<()>;
1443
1444    // -- conflicts --
1445    fn conflicts(&self, repo: &RepoRef) -> Result<Vec<ConflictSet>>;
1446    /// Every unmerged path with its stages' modes and oids and the kind of
1447    /// conflict they make, sorted by path. Reads no blob (the cheap form of
1448    /// [`GitBackend::conflicts`], for the refresh): 1 spawn on system git,
1449    /// none under git2. Empty when nothing is unmerged.
1450    fn conflict_entries(&self, repo: &RepoRef) -> Result<Vec<ConflictEntry>>;
1451    /// Everything the merge conflict editor needs for one unmerged `path`:
1452    /// the three stages read, git's own 3-way merge of them parsed into
1453    /// regions (see [`MergeDocument`]), the pane labels and the state of
1454    /// the file on disk. Text is decoded as `read_blob` does (the fallback
1455    /// encoding applies). A path that is not unmerged is an error.
1456    fn merge_document(&self, repo: &RepoRef, path: &Path) -> Result<MergeDocument>;
1457    /// Resolves the unmerged `path` as `resolution` says and, with
1458    /// `opts.stage`, stages the result. Refused (nothing written) with
1459    /// [`crate::domain::ConflictRefusal::Stale`] when `opts.expected` is
1460    /// not what the index holds, and
1461    /// [`crate::domain::ConflictRefusal::Unencodable`] for text a
1462    /// `UseEncoded` encoding cannot hold. A path that is not conflicted is
1463    /// written and staged like any file unless `expected` is given (then
1464    /// it is stale).
1465    fn resolve_conflict(
1466        &self,
1467        repo: &RepoRef,
1468        path: &Path,
1469        resolution: ConflictResolution,
1470        opts: &ResolveOptions,
1471    ) -> Result<()>;
1472    /// Puts a resolved path back in conflict: the stage 1/2/3 entries of
1473    /// `entry` return to the index (stage 0 goes) and the working tree
1474    /// file is rewritten the way git leaves it (the merge with conflict
1475    /// markers; the surviving side for a non-text conflict). Refused with
1476    /// [`crate::domain::ConflictRefusal::AlreadyConflicted`] when the path
1477    /// is still unmerged.
1478    fn unresolve_conflict(&self, repo: &RepoRef, path: &Path, entry: &ConflictEntry) -> Result<()>;
1479    /// The merge, cherry-pick, revert or rebase in progress, if any
1480    /// (rebase wins when several markers exist).
1481    fn operation_state(&self, repo: &RepoRef) -> Result<Option<OperationState>>;
1482    /// Abandons whatever [`GitBackend::operation_state`] reports
1483    /// (`merge`/`cherry-pick`/`revert`/`rebase --abort`): HEAD, the index
1484    /// and the working tree return to before the operation. Destructive
1485    /// for work done since. Without an operation: refused with
1486    /// [`crate::domain::ConflictRefusal::NoOperation`].
1487    fn operation_abort(&self, repo: &RepoRef) -> Result<()>;
1488    /// `git am --continue`: applies the patch the `am` stopped on (the
1489    /// caller resolved and staged it) and the rest. Without an `am` in
1490    /// progress: refused with [`crate::domain::ConflictRefusal::NoOperation`].
1491    fn am_continue(&self, repo: &RepoRef) -> Result<AmOutcome>;
1492    /// `git am --skip`: drops the patch the `am` stopped on and goes on.
1493    /// Same refusal as [`GitBackend::am_continue`].
1494    fn am_skip(&self, repo: &RepoRef) -> Result<AmOutcome>;
1495    /// `git am --abort`: back to the branch tip from before the `am`.
1496    /// Same refusal as [`GitBackend::am_continue`].
1497    fn am_abort(&self, repo: &RepoRef) -> Result<()>;
1498    /// The repository's `index.lock`, if the file exists. In a linked
1499    /// worktree it is the worktree's own (`.git/worktrees/<name>`).
1500    fn index_lock(&self, repo: &RepoRef) -> Result<Option<IndexLock>>;
1501    /// Deletes a stale `index.lock` (and nothing else). Refused with an
1502    /// error when there is none, or when it is younger than
1503    /// [`crate::domain::STALE_INDEX_LOCK_SECS`].
1504    fn index_lock_remove(&self, repo: &RepoRef) -> Result<()>;
1505    /// Skips what [`GitBackend::operation_state`] reports
1506    /// (`cherry-pick --skip`, `revert --skip`, `rebase --skip`): the
1507    /// stopped commit is given up on and HEAD, the index and the working
1508    /// tree return to HEAD. The way out of a pick or revert that became
1509    /// empty (the change is already applied; git refuses to commit it). A
1510    /// merge has nothing to skip: an `Error::Backend`, nothing changed.
1511    /// Without an operation: [`crate::domain::ConflictRefusal::NoOperation`].
1512    fn operation_skip(&self, repo: &RepoRef) -> Result<()>;
1513}