# Network

> Remote dispatch, fetch, push, and ls-remote over every transport.

Network operations in grit-lib center on `Remote`: a typed URL (`RemoteUrl`), configured fetch refspecs, and one dispatcher for **fetch**, **push**, and **list refs**. Wire bytes still flow through the same fetch/push engines as before; `Remote` picks the transport from the URL scheme.

## Remote URL and config

| Scheme / form | `RemoteUrl` variant | Transport |
| --- | --- | --- |
| Path or `file://` | `Local` / `File` | in-process object copy ([`TransferEndpoint::Local`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/enum.TransferEndpoint.html#variant.Local)) |
| `git://` | `Git` | [`GitDaemonTransport`](https://docs.rs/grit-lib/latest/grit_lib/remote/transport/struct.GitDaemonTransport.html) |
| `ssh://`, scp-style | `Ssh` | [`SshTransport`](https://docs.rs/grit-lib/latest/grit_lib/remote/transport/struct.SshTransport.html) (repo [`CommandRunner`](https://docs.rs/grit-lib/latest/grit_lib/command_runner/trait.CommandRunner.html)) |
| `http(s)://` | `Http` / `Https` | [`SmartHttpTransport`](https://docs.rs/grit-lib/latest/grit_lib/remote/transport/http/struct.SmartHttpTransport.html) ([`TransferEndpoint::Http`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/enum.TransferEndpoint.html#variant.Http)) |

When you already hold the transport — a repository path on this machine, an open [`Connection`](https://docs.rs/grit-lib/latest/grit_lib/remote/transport/trait.Connection.html), or a smart-HTTP URL with your own [`HttpClient`](https://docs.rs/grit-lib/latest/grit_lib/remote/transport/http/trait.HttpClient.html) — fetch and push through [`RepositoryRemotes::fetch_from`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryRemotes.html#method.fetch_from) and [`RepositoryRemotes::push_to`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryRemotes.html#method.push_to) with a [`TransferEndpoint`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/enum.TransferEndpoint.html). They run the same engines as `fetch` and `push` (refspecs, tags, prune, shallow, the same outcomes) but skip URL resolution and the client-side `pre-push` hook.

Parse a literal URL with [`RemoteUrl::try_from`](https://docs.rs/grit-lib/latest/grit_lib/remote/enum.RemoteUrl.html). Load `remote.<name>.url`, optional `pushurl`, and `fetch` refspecs (default `+refs/heads/*:refs/remotes/<name>/*`) via [`Remote::from_config`](https://docs.rs/grit-lib/latest/grit_lib/remote/struct.Remote.html). Config applies `url.*.insteadOf` and `url.*.pushInsteadOf` rewrite rules the same way Git does.

Local paths resolve through [`resolve_local_remote_git_dir`](https://docs.rs/grit-lib/latest/grit_lib/remote/transport_path/fn.resolve_local_remote_git_dir.html) from the repository root, not the process cwd.

A local or `file://` fetch or push copies the same objects the wire protocol would: those reachable from the requested refs that the receiver lacks. Other branches, hidden refs, excluded tags and unreachable leftovers stay behind even when they share a pack with what was asked for. When a source pack holds only objects the transfer must send, grit hard-links it instead of rebuilding it, and it builds a pack for the rest. The send set comes from the source's reachability bitmap when it has one. The one exception is a clone from a plain path (not a `file://` URL): like `git clone --local`, it links the source's packfiles as they are, unreachable objects included ([`FetchOptions::link_source_objects`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/struct.FetchOptions.html#structfield.link_source_objects)).

To turn a user's repository argument (a configured name, a URL, an scp-style `host:path`, or a path) into a `Remote`, call [`resolve_remote_argument`](https://docs.rs/grit-lib/latest/grit_lib/remote/fetch_request/fn.resolve_remote_argument.html). A configured name wins. A name with a config section but no URL fails with `RemoteError::NoUrl`, and anything else fails with [`RemoteError::UnknownRemote`](https://docs.rs/grit-lib/latest/grit_lib/remote/enum.RemoteError.html). `grit fetch`, `grit pull` and `grit remote refs` all resolve their argument this way.

## Managing remotes

[`repo.remotes().configured()`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryRemotes.html#method.configured) lists every remote with a `remote.<name>.*` section, sorted by name, the same set `git remote` prints. Each [`ConfiguredRemote`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.ConfiguredRemote.html) carries its URL, or `None` when the section has no URL, plus raw `push_urls`, `fetch_refspecs`, and effective fetch/push URLs after `url.*.insteadOf` / `pushInsteadOf`. [`list()`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryRemotes.html#method.list) returns only the names that have a URL.

[`repo.remotes().add(name, url)`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryRemotes.html#method.add) writes `remote.<name>.url` and the default fetch refspec to the shared repository config (also from a linked worktree), then reloads the repository's config. Like `git remote add`, it refuses an existing remote (`RemoteError::RemoteExists`) and a name whose tracking refs `refs/remotes/<name>/…` would be invalid (`RemoteError::InvalidRemoteName`), and it stores the URL as given.

[`repo.remotes().set_url(name, url, kind, dry_run)`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryRemotes.html#method.set_url) updates fetch or push URLs on an existing remote (`RemoteUrlKind::Fetch` or `Push`), returning [`UrlChange`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.UrlChange.html). Push replaces every `pushurl` with one value. Returns [`RemoteError::UnknownRemote`](https://docs.rs/grit-lib/latest/grit_lib/remote/enum.RemoteError.html#variant.UnknownRemote) when the section is missing.

[`repo.remotes().prune(name, dry_run, http_factory)`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryRemotes.html#method.prune) deletes stale remote-tracking refs without fetching, using the same stale-ref rules as fetch prune. Returns the full ref names removed (or that would be removed when `dry_run` is true).

[`repo.remotes().set_head(name, mode, dry_run, http_factory)`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryRemotes.html#method.set_head) sets or deletes `refs/remotes/<name>/HEAD` via [`SetHead`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/enum.SetHead.html) (`Auto`, `Branch`, or `Delete`).

[`repo.remotes().inspect(name, options, http_factory)`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryRemotes.html#method.inspect) returns a [`RemoteSummary`](https://docs.rs/grit-lib/latest/grit_lib/remote/struct.RemoteSummary.html): fetch and push URLs, optional [`head_branch`](https://docs.rs/grit-lib/latest/grit_lib/remote/struct.RemoteSummary.html#structfield.head_branch), [`RemoteBranchState`](https://docs.rs/grit-lib/latest/grit_lib/remote/struct.RemoteBranchState.html) rows (`tracked`, `new`, or `stale`), and [`RemotePullBranch`](https://docs.rs/grit-lib/latest/grit_lib/remote/struct.RemotePullBranch.html) entries from `branch.*` config. With [`InspectOptions::query`](https://docs.rs/grit-lib/latest/grit_lib/remote/struct.InspectOptions.html#structfield.query) it lists refs on the remote (symrefs included) and compares them to local tracking refs; stale detection uses the same rules as fetch prune. Without a query, branch names come from `refs/remotes/<name>/…` and are all reported as tracked.

## list refs

`Remote::list_refs` takes `ListRefsOptions` (prefixes, heads, tags, symrefs, peel) and returns `RemoteRef` entries in `git ls-remote` order. On disk it scans the repository's refs directly; [`repo.remotes().ls_remote(remote, options, http_factory)`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryRemotes.html#method.ls_remote) does the same with relative paths resolved from this repository. Over the wire it uses protocol v2 `ls-refs` when available, otherwise the v0/v1 ref advertisement.

With `peel` set, annotated tags come back as two entries, the tag and a `<tag>^{}` line holding the object it peels to: the first non-tag object, through any chain of tags of tags, as `git ls-remote` reports it. [`RemoteRef::peeled_tag`](https://docs.rs/grit-lib/latest/grit_lib/remote/struct.RemoteRef.html#method.peeled_tag) identifies those lines, and [`fold_peeled_refs`](https://docs.rs/grit-lib/latest/grit_lib/remote/fn.fold_peeled_refs.html) folds them into one [`PeeledRemoteRef`](https://docs.rs/grit-lib/latest/grit_lib/remote/struct.PeeledRemoteRef.html) per ref, with `peeled` set, keeping the listing order.

## Fetch and push

[`Remote::fetch`](https://docs.rs/grit-lib/latest/grit_lib/remote/struct.Remote.html) accepts [`FetchOptions`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/struct.FetchOptions.html) and a [`ProgressSink`](https://docs.rs/grit-lib/latest/grit_lib/progress/trait.ProgressSink.html); fetch negotiates protocol v2 when the server supports it. Negotiation offers every local branch, remote-tracking ref, tag and `HEAD` as a starting point and walks local history only as far as each round needs: 16 `have`s first, then twice as many per round, stopping as soon as the server is ready to send the pack. An incremental fetch whose new commits build on local history reads only the newest local commits, not the whole history. Its [`FetchOutcome`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/struct.FetchOutcome.html) holds one `RefUpdate` per matched ref, including the ones that were already up to date. For a report, [`reported_updates`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/struct.FetchOutcome.html#method.reported_updates) keeps the refs that changed or were refused, [`changed_ref_count`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/struct.FetchOutcome.html#method.changed_ref_count) counts the changed ones, and [`has_rejections`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/struct.FetchOutcome.html#method.has_rejections) says whether any update was refused (`UpdateMode::is_rejected`). [`UpdateMode::kind`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/enum.UpdateMode.html#method.kind) folds each update's detailed mode into an [`UpdateKind`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/enum.UpdateKind.html) (new, fast-forward, forced, pruned, rejected or up to date) for display. `grit fetch` builds its output and exit code from these. [`Remote::push`](https://docs.rs/grit-lib/latest/grit_lib/remote/struct.Remote.html) uses [`PushRefSpec`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/struct.PushRefSpec.html) and returns [`PushOutcome`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/struct.PushOutcome.html); [`has_updates`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/struct.PushOutcome.html#method.has_updates) says whether any remote ref changed (or would, on a dry run) and [`has_rejections`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/struct.PushOutcome.html#method.has_rejections) whether any update was refused, which is how `grit push` decides its exit code. Before it sends anything, on every transport and for dry runs too, `Remote::push` runs the repository's `pre-push` hook through [`RepositoryHooks::run_pre_push`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryHooks.html#method.run_pre_push) with one [`PrePushRef`](https://docs.rs/grit-lib/latest/grit_lib/command_runner/hooks/struct.PrePushRef.html) per update it would make; a hook that exits non-zero fails the push with `Error::Hook` and leaves the remote untouched. Set [`PushOptions::no_verify`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/struct.PushOptions.html#structfield.no_verify) to skip it. The lower-level [`RepositoryRemotes::push_to`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryRemotes.html#method.push_to) never runs `pre-push`. A local or `file://` push (including `push_to` with [`TransferEndpoint::Local`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/enum.TransferEndpoint.html#variant.Local)) runs the remote repository's receive hooks (`pre-receive`, `update`, `post-receive`, `post-update`) the way [`ReceivePack`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ReceivePack.html) does, puts their output in [`PushOutcome::remote_messages`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/struct.PushOutcome.html#structfield.remote_messages) and reports a declined update as `PushRefStatus::RemoteRejected`.

A push never holds its packfile in memory. [`write_pack_for_push`](https://docs.rs/grit-lib/latest/grit_lib/objects/pack_objects/fn.write_pack_for_push.html) streams the pack into the connection (ssh, `git://`) or, when the server advertises a resumable `pushBundle` endpoint, into the bundle file on disk. Over plain smart HTTP a receive-pack body larger than 1 MiB (Git's default `http.postBuffer`) is sent with chunked transfer encoding while the pack is still being written. A small probe request goes first so any authentication challenge is answered before the large body, as Git does. A custom [`HttpClient`](https://docs.rs/grit-lib/latest/grit_lib/remote/transport/http/trait.HttpClient.html) should override [`post_streaming`](https://docs.rs/grit-lib/latest/grit_lib/remote/transport/http/trait.HttpClient.html#method.post_streaming); the default buffers the body.

A local push applies the same ref-update checks as [`ReceivePack`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ReceivePack.html) (policy, hidden refs, fast-forward rules) before it copies objects or moves refs on a path remote.

To plan a push the way `grit push` does, start from its positionals: [`resolve_push_invocation`](https://docs.rs/grit-lib/latest/grit_lib/remote/push_plan/fn.resolve_push_invocation.html) splits `[<remote>] [<refspec>...]` into a [`PushInvocation`](https://docs.rs/grit-lib/latest/grit_lib/remote/push_plan/struct.PushInvocation.html) (configured remote, literal URL or path, or refspecs for the default remote). [`repo.remotes().push_plan_context`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryRemotes.html#method.push_plan_context) reads the selected remote's refs ([`Remote::list_push_refs`](https://docs.rs/grit-lib/latest/grit_lib/remote/struct.Remote.html#method.list_push_refs), one scan of the push destination) into a [`PushPlanContext`](https://docs.rs/grit-lib/latest/grit_lib/remote/push_plan/struct.PushPlanContext.html), [`repo.remotes().resolve_push`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryRemotes.html#method.resolve_push) turns a [`PushRequest`](https://docs.rs/grit-lib/latest/grit_lib/remote/push_plan/struct.PushRequest.html) into concrete ref updates, and [`open_push_destination`](https://docs.rs/grit-lib/latest/grit_lib/remote/push_plan/fn.open_push_destination.html) opens the `Remote` to send them to. Pass `PushPlanContext::remote_tips` on as `PushOptions::remote_ref_tips` so a local push does not scan the destination's refs a second time. The same handle turns `--force` / `--force-with-lease` into a `ForceMode` ([`force_mode`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryRemotes.html#method.force_mode)), adds `--follow-tags` refspecs ([`follow_tag_push_specs`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryRemotes.html#method.follow_tag_push_specs)), leases one ref against its tracking ref ([`apply_tracking_lease`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryRemotes.html#method.apply_tracking_lease)), and writes `-u` upstream config after a push ([`set_upstream_after_push`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryRemotes.html#method.set_upstream_after_push)).

[`pull`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/pull/fn.pull.html) is the high-level fetch-and-integrate operation. Build [`PullOptions`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/pull/struct.PullOptions.html) (including shared [`FetchOptions`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/struct.FetchOptions.html), explicit refspec/`FETCH_HEAD` integration, [`resolve_pull_autostash`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/pull/fn.resolve_pull_autostash.html), and dry-run `--check` via [`PullCheck`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/pull/struct.PullCheck.html)), pass a progress sink and HTTP client factory, and receive a typed [`PullOutcome`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/pull/struct.PullOutcome.html). It maps `branch.<name>.merge` through the remote's fetch refspecs, uses `resolve_pull_integration_base` after explicit fetches, skips the fetch for a local `remote = .` upstream, and fast-forwards, merges, or adopts the upstream on an unborn branch. Failures are typed as [`PullError`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/pull/enum.PullError.html); `grit pull` only builds options, invokes this API, and renders the outcome.

## Unreachable remotes

When the remote cannot be talked to at all, every operation (`list_refs`, `fetch`, `push`, [`clone`](https://docs.rs/grit-lib/latest/grit_lib/remote/clone/fn.clone.html), [`pull`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/pull/fn.pull.html)) and every transport fails with [`RemoteError::Unreadable`](https://docs.rs/grit-lib/latest/grit_lib/remote/enum.RemoteError.html#variant.Unreadable) (surfaced as [`Error::Remote`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html#variant.Remote)). It carries the redacted URL or resolved path and a [`RemoteUnreadableReason`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.RemoteUnreadableReason.html):

| Reason | When |
| --- | --- |
| `RepositoryNotFound` | A local path or `file://` URL that is missing or not a Git directory (valid `HEAD`, `objects/` and `refs/`, as Git checks). Listing refs never treats it as an empty remote. A linked worktree or `--separate-git-dir` checkout is followed through its `.git` file and works as a remote. |
| `Transport { detail }` | DNS, refused or reset connection, TLS, or timeout (HTTP and `git://`). Usually worth a retry. |
| `HttpStatus { status }` | A smart-HTTP error status such as 403, 404 or 5xx. A `401` challenge is [`RemoteError::Auth`](https://docs.rs/grit-lib/latest/grit_lib/remote/enum.RemoteError.html#variant.Auth) instead. |
| `NotGitServer { status, content_type }` | HTTP succeeded but the body was not a Git advertisement (for example `200 text/html` from a mistyped or parked host). |
| `NoHandshake` | The transport ran but never spoke Git, for example `ssh` failed to connect, a `git://` peer hung up before any pkt-line, or the ref advertisement ended at EOF without a flush. An empty remote that sends only a flush pkt-line (`0000`) is a completed handshake with no refs. |

Both the umbrella and the area error answer the same question: [`Error::is_remote_unreadable`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html#method.is_remote_unreadable) and [`RemoteError::is_remote_unreadable`](https://docs.rs/grit-lib/latest/grit_lib/remote/enum.RemoteError.html#method.is_remote_unreadable). The `grit` CLI maps all of them to exit code 128 and `kind: remote_unreadable` ([Exit codes](https://grit-scm.com/docs/library/exit-codes.md/index.md)).

A remote that was reached but aborts the conversation itself fails with [`RemoteError::Fatal`](https://docs.rs/grit-lib/latest/grit_lib/remote/enum.RemoteError.html#variant.Fatal) instead. Its `message` is the server's own text, from an `ERR` packet (for example `upload-pack: not our ref <oid>` when a fetch wants an object the server will not send) or from side-band channel 3. Every reader of upload-pack output reports it the same way, over every transport: the ref advertisement (including smart-HTTP `info/refs` discovery), `ls-refs`, negotiation, and the pack stream. Show the message to the user, but don't parse it, because each server words it differently.

HTTP remotes need an [`HttpClient`](https://docs.rs/grit-lib/latest/grit_lib/remote/transport/http/trait.HttpClient.html). Implement [`HttpClientFactory`](https://docs.rs/grit-lib/latest/grit_lib/remote/trait.HttpClientFactory.html) or, with the `http-ureq` feature, pass `None` to use the default ureq-backed factory (`UreqHttpClient` + [`HelperCredentialProvider`](https://docs.rs/grit-lib/latest/grit_lib/remote/credentials/struct.HelperCredentialProvider.html)). The `grit` binary on macOS enables `http-ureq-native-tls` (Secure Transport) for HTTPS throughput; other platforms use rustls unless you opt into `http-ureq-native-tls` when depending on `grit-lib`.

## Credentials and progress

[`HelperCredentialProvider`](https://docs.rs/grit-lib/latest/grit_lib/remote/credentials/struct.HelperCredentialProvider.html) satisfies HTTP `401` responses from configured `credential.helper` programs, then from the askpass program set with [`with_askpass`](https://docs.rs/grit-lib/latest/grit_lib/remote/credentials/struct.HelperCredentialProvider.html#method.with_askpass), and never opens a TTY. Askpass resolution follows Git (`GIT_ASKPASS`, `core.askPass`, `SSH_ASKPASS`) from an [`Environment`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html) you pass in; the default factory reads only `core.askPass` unless you build it with `DefaultHttpClientFactory::with_environment` (with the `http-ureq` feature). [`helpers_for`](https://docs.rs/grit-lib/latest/grit_lib/remote/credentials/struct.HelperCredentialProvider.html#method.helpers_for) lists the helpers it would run for a credential, so you can tell up front whether storing one would be a no-op. When neither the helpers nor askpass can supply a credential, `fill` returns [`RemoteError::CredentialsUnavailable`](https://docs.rs/grit-lib/latest/grit_lib/remote/enum.RemoteError.html#variant.CredentialsUnavailable) with the helpers it asked, and the transport reports [`AuthFailure::CredentialsUnavailable`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.AuthFailure.html#variant.CredentialsUnavailable) carrying the same list, so a caller can tell "no helper configured" from "the helper has nothing for this host". To save a user name and token a person gives you for any host, build the credential with [`Credential::from_url`](https://docs.rs/grit-lib/latest/grit_lib/remote/credentials/struct.Credential.html#method.from_url) (described below), set its `username` and `password`, and `approve` it; `grit auth <url> --username … --token …` does exactly that.

Best-effort requests whose failure is ignored, such as the advertisement [`push_plan_context`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryRemotes.html#method.push_plan_context) reads and the bundle a clone tries first, use [`HttpClientFactory::create_for_preflight`](https://docs.rs/grit-lib/latest/grit_lib/remote/trait.HttpClientFactory.html#tymethod.create_for_preflight): those clients never `reject` a refused credential, so the push or fetch that follows sends it, reports [`AuthFailure::Rejected`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.AuthFailure.html#variant.Rejected), and erases it as Git does. Every factory implements `create_for_preflight`; one whose clients never reject (or carry no credentials) can return the same client as `create`.

After an authenticated retry, [`HelperCredentialProvider`](https://docs.rs/grit-lib/latest/grit_lib/remote/credentials/struct.HelperCredentialProvider.html) (and any custom [`CredentialProvider`](https://docs.rs/grit-lib/latest/grit_lib/remote/credentials/trait.CredentialProvider.html), which must be `Send + Sync`) runs `reject` only when the server still answers `401`; a typo, missing repository, permission denial or server error (403, 404, 429, 5xx) leaves the stored credential untouched.

The HTTP client asks for credentials the way Git does: [`Credential::from_url`](https://docs.rs/grit-lib/latest/grit_lib/remote/credentials/struct.Credential.html#method.from_url) turns the repository URL into protocol and host, adding the repository path only when `credential.useHttpPath` applies, so a host-level entry from `git-credential-store` or a keychain helper serves every repository on the host. The full URL stays in [`Credential::url`](https://docs.rs/grit-lib/latest/grit_lib/remote/credentials/struct.Credential.html#structfield.url) for matching `credential.<url>.helper`, and `HelperCredentialProvider` never sends it to a helper. A `user:password@` in the URL fills the username and password (and is removed from `Credential::url`), so wrong URL credentials fail as [`AuthFailure::Rejected`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.AuthFailure.html#variant.Rejected). Complete URL credentials are also kept in the client's in-memory origin cache so later requests to the same scheme, host and port (such as a `bundle-uri` download with no userinfo) send the same `Authorization` header without writing secrets into a helper or resumable state files.

The GitHub OAuth device flow (`remote::github_auth::DeviceFlow`) that `grit auth` uses, and the grit-server login, share, space and snapshot-checkout clients (`remote::grit_server_*`, `remote::snapshot_checkout`), exist only with the off-by-default `unstable-hosting` feature. They are outside the semver promise and may change in any release, so pin an exact `grit-lib` version if you enable it.

Whenever you show a remote address, in errors or in success output, strip embedded userinfo with [`redact_url_for_display`](https://docs.rs/grit-lib/latest/grit_lib/remote/fn.redact_url_for_display.html) so passwords never reach logs or JSON; it leaves the rest of the URL, and local paths, exactly as given. Keep the original URL for the transport and for config. Pass [`NullProgress`](https://docs.rs/grit-lib/latest/grit_lib/progress/struct.NullProgress.html) to ignore sideband progress, or override [`ProgressSink::message`](https://docs.rs/grit-lib/latest/grit_lib/progress/trait.ProgressSink.html#method.message) for side-band channel 2. Set [`FetchOptions`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/struct.FetchOptions.html) `remote_progress` to omit `no-progress` on the wire so the remote may emit channel 2; decode chunks with [`SidebandLines`](https://docs.rs/grit-lib/latest/grit_lib/remote/sideband_lines/struct.SidebandLines.html) into [`RemoteLine`](https://docs.rs/grit-lib/latest/grit_lib/remote/sideband_lines/enum.RemoteLine.html) updates and lines.

Fetch and clone spool the received pack to a temp file and index it in place with [`ingest_received_pack_path`](https://docs.rs/grit-lib/latest/grit_lib/objects/index_pack/fn.ingest_received_pack_path.html), keeping the pack instead of exploding it into loose objects. Memory does not grow with the pack size. The sequential passes (trailer checksum and object scan) read through a memory map whose resident pages are dropped every few megabytes, and delta resolution reads each compressed object from the file. A thin pack (ref-deltas against objects the receiver already has, which Git servers send on incremental fetches) is completed the way `git index-pack --fix-thin` does it. The missing bases are appended to the file, the object count and trailing checksum are rewritten, and the pack and its `.idx` are named after the new checksum. On `git/git` (325 MB pack, 420k objects), indexing peaks at about 80 MB, against 63 MB for `git index-pack` on the same file.

A received pack's length in bytes is not known until it ends, so byte counts alone cannot say how far a transfer is. Return `true` from [`ProgressSink::wants_received_objects`](https://docs.rs/grit-lib/latest/grit_lib/progress/trait.ProgressSink.html#method.wants_received_objects) and the receive also counts the pack's objects on a background thread, reporting [`ReceivedObjects`](https://docs.rs/grit-lib/latest/grit_lib/progress/struct.ReceivedObjects.html) (received, total from the pack header, and deltas so far) through [`ProgressSink::received_objects`](https://docs.rs/grit-lib/latest/grit_lib/progress/trait.ProgressSink.html#method.received_objects). The counting never makes the receive wait; if it falls far behind a very fast transfer, it stops. The same object-counting logic also exists as a crate-internal pack stream scanner for other callers. To turn the phases of a fetch or clone into one percentage and time-left figure, feed the same events to an [`OverallEstimator`](https://docs.rs/grit-lib/latest/grit_lib/progress/struct.OverallEstimator.html); it takes elapsed time as an argument rather than reading the clock.

## Example

This example resolves `origin`, lists refs on a **local** bare remote, fetches, creates a commit reusing the fetched tip’s tree, and pushes — all over `file://`:

```rust
//! List refs on a local remote, fetch, create a commit, and push over `file://`.
//!
//! Source for the library guide "Network" page (included in the docs site).

use anyhow::Result;
use grit_examples::remote;
use grit_lib::config::environment::RepositoryOptions;
use grit_lib::config::ConfigSet;
use grit_lib::ident::parse_signature;
use grit_lib::objects::NewCommit;
use grit_lib::refs::store::RefName;
use grit_lib::remote::transfer::{FetchOptions, PushOptions, PushRefSpec, TagMode};
use grit_lib::remote::transport_path::resolve_local_remote_git_dir;
use grit_lib::remote::{ListRefsOptions, Remote};
use grit_lib::repo::Repository;
use std::path::Path;

fn main() -> Result<()> {
    let consumer = std::env::args()
        .nth(1)
        .ok_or_else(|| anyhow::anyhow!("usage: guide_network <consumer-repo>"))?;
    let consumer = Path::new(&consumer);
    let repo = Repository::discover(Some(consumer), &RepositoryOptions::from_process())?;
    let git_dir = repo.git_dir().to_path_buf();
    let work_tree = repo.work_tree().map(|p| p.to_path_buf());
    let env = grit_lib::config::environment::Environment::capture_process();
    let config = ConfigSet::load(
        &env,
        Some(&git_dir),
        &grit_lib::config::LoadConfigOptions::standard(&env, Some(&git_dir)),
    )?;

    let remote_info = remote::resolve_remote(&config, &repo, Some("origin"), false)?;

    let remote_git_dir =
        resolve_local_remote_git_dir(&remote_info.url, &git_dir, work_tree.as_deref());
    let refs_on_remote = repo.remotes().ls_remote(
        &Remote::from_url(&remote_git_dir.to_string_lossy())?,
        &ListRefsOptions::default(),
        None,
    )?;
    eprintln!(
        "ls-remote: {} ref(s) on {}",
        refs_on_remote.len(),
        remote_git_dir.display()
    );

    let mut fetch_opts = FetchOptions::new();
    fetch_opts.refspecs = remote_info.fetch_refspecs.clone();
    fetch_opts.tags = TagMode::Following;
    remote::fetch(&repo, &remote_info, &fetch_opts)?;

    let main = RefName::new("refs/heads/main")?;
    let tracking = repo
        .references()
        .resolve(&RefName::new("refs/remotes/origin/main")?)?;
    repo.references().update(&main, &tracking)?;

    let parent = repo.objects().read_commit(&tracking)?;
    let committer = parse_signature(&parent.committer)
        .ok_or_else(|| anyhow::anyhow!("parent committer is not a valid identity"))?;
    let new_oid = repo.objects().write_commit(
        &NewCommit::new(
            parent.tree,
            committer.clone(),
            committer,
            "library guide network example",
        )
        .with_parents([tracking]),
    )?;
    repo.references().update(&main, &new_oid)?;

    let spec = PushRefSpec::default()
        .with_src(Some(new_oid))
        .with_src_ref(Some("refs/heads/main".to_owned()))
        .with_dst("refs/heads/main".to_owned());
    remote::push(&repo, &remote_info, &[spec], &PushOptions::default())?;

    println!("{new_oid}");
    Ok(())
}
```

The `grit-examples` crate also ships `gritx-fetch` and `gritx-push`, which dispatch on URL scheme and print transport/auth discovery lines. Shared wiring lives in `grit-examples/src/remote.rs` (slated to thin over `Remote` in a follow-up step).

Integration test `guide_network` builds bare and consumer repos with system Git, runs the binary, then requires clean `git fsck --strict` on both sides and matching `git rev-parse` on the pushed ref.

## Serving fetches and pushes

The server side of the protocol lives in [`remote::serve`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/index.html). An [`UploadPack`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.UploadPack.html) session answers clones and fetches (protocol v0, v1 and v2) and returns an [`UploadOutcome`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.UploadOutcome.html) with bytes sent, object count, negotiation rounds, and optional [`PackStats`](https://docs.rs/grit-lib/latest/grit_lib/objects/pack_objects/struct.PackStats.html). A [`ReceivePack`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ReceivePack.html) session accepts pushes. Both are built from an opened `Repository` and [`ServeOptions`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ServeOptions.html) (plus a [`ReceivePolicy`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ReceivePolicy.html) for pushes) and `run` over a reader and a writer, so the same code serves a pipe or ssh channel (the defaults) and smart HTTP (`advertise_refs` for `GET info/refs`, `stateless_rpc` for the POST). The library never reads the environment: map `GIT_PROTOCOL` with [`ProtocolVersion::from_git_protocol`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/enum.ProtocolVersion.html#method.from_git_protocol) at your process boundary. Open the repository with `RepositoryOptions::for_serving()`.

To stop a long fetch or push (client disconnect, deadline, quota), pass a [`CancelToken`](https://docs.rs/grit-lib/latest/grit_lib/progress/struct.CancelToken.html) to [`UploadPack::with_cancel`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.UploadPack.html#method.with_cancel) or [`ReceivePack::with_cancel`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ReceivePack.html#method.with_cancel). A fired cancel returns [`Error::Cancelled`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html#variant.Cancelled) and does not move refs on receive-pack.

A protocol v2 `ls-refs` request asks the ref store for its `ref-prefix` ranges only, and reads objects only when the client sent `peel`. Even then, a fully peeled `packed-refs` answers without opening the tags. So the `ls-refs` call that every `git fetch` and `git ls-remote` sends costs in proportion to the refs it returns, not the refs stored. The v0/v1 advertisement always peels tags, and the push advertisement never does. Like Git, every advertisement includes refs whose objects are missing; such a ref just has no peeled value.

A pushed pack is streamed into a temp file (under the repository's `objects/pack/` quarantine for a files primary, or the system temp directory for a custom primary), so memory use does not grow with the pack size, and only bytes up to the pack's trailing checksum are read (a push client keeps its side open until it has the status report). On a files backend, packs with fewer objects than `receive.unpackLimit` are stored as loose objects in the quarantine; larger ones are indexed and kept as a pack there. A custom primary always unpacks object-by-object into an in-memory overlay until pre-receive passes, then copies into the primary (see [Receiving packs into a custom store](https://grit-scm.com/docs/library/network/library/object-stores.md/index.md#receiving-packs-into-a-custom-store)). `receive.maxInputSize` caps the pack size.

A push from a shallow clone starts its command list with a `shallow <oid>` line for each of the client's boundaries, and `ReceivePack` accepts them anywhere before the flush. The parents of those commits are not required when the pushed objects are checked. When the repository's refs already reach the boundary (the usual case: a CI checkout cloned `--depth 1` from this server), the push is applied like any other. When accepting an update would make the repository shallow, it is refused with `RefUpdateRefusal::ShallowUpdateNotAllowed`, unless [`ReceivePolicy::shallow_update`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ReceivePolicy.html#structfield.shallow_update) (`receive.shallowUpdate`) is on. Then the new boundaries are added to the repository's `shallow` file before the ref is written, so `git fsck` accepts the result.

What a push may change is decided in three layers, in this order for each push:

1. [`ReceivePolicy`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ReceivePolicy.html), usually [`ReceivePolicy::from_config`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ReceivePolicy.html#method.from_config) (`receive.denyNonFastForwards`, `receive.denyDeletes`, `deny_current_branch` from `receive.denyCurrentBranch`, `receive.fsckObjects`, `receive.shallowUpdate`), plus the checks every server makes: valid ref names, hidden refs, the expected old value, and that the new objects exist. When `receive.denyCurrentBranch` is `updateInstead`, grit runs `push-to-checkout` (or the built-in deploy) after the `update` hook and before the ref moves, on every non-bare worktree that has the updated branch checked out.
2. An in-process [`ReceiveHook`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/trait.ReceiveHook.html) passed to [`ReceivePack::with_hook`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ReceivePack.html#method.with_hook). Its `pre_receive_ctx` and `update_ctx` methods take a [`ReceiveHookContext`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ReceiveHookContext.html) with the client's push options (the same values hook scripts see in `GIT_PUSH_OPTION_*`), so policy can refuse `-o` values before refs move. The default `pre_receive` / `update` methods ignore push options. `pre_receive_ctx` sees every accepted update and an object database that includes the still-quarantined pushed objects; refusing there refuses the whole push and nothing is moved into the repository. `update_ctx` checks one ref at a time after the objects are moved in. A closure `Fn(&RefCommand, &Odb) -> Result<(), RefUpdateRefusal> + Send + Sync` is a `ReceiveHook` that implements `update`. Hooks are `Send + Sync` so one hook can serve every connection thread; keep mutable state behind a `Mutex` or atomics.
3. The repository's hook scripts (`pre-receive`, `update`, `post-receive`, `post-update`), run through the repository's `CommandRunner` with Git's environment (`GIT_DIR=.`, the quarantine variables and `GIT_PUSH_OPTION_*`). Each in-process check runs just before the matching script.

The [`ReceiveOutcome`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ReceiveOutcome.html) is typed: each [`RefUpdateResult`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.RefUpdateResult.html) carries an `Option<RefUpdateRefusal>` ([`RefUpdateRefusal`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/enum.RefUpdateRefusal.html): `NonFastForward`, `StaleInfo`, `DeletionProhibited`, `PreReceiveHookDeclined`, `Policy(reason)` from your hook, ...), and `unpack_error` is an [`UnpackError`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/enum.UnpackError.html) (`Truncated`, `TooLarge`, `Malformed`, `Ingest`, `Rejected`, `FsckSkipList`, `Io`). It also reports `bytes_received` and `objects_received` from the pushed pack. Match on the variants; their `Display` text is what the client is sent on its `ng <ref> <reason>` and `unpack <reason>` status lines. Neither is an `Err`: `ReceivePack::run` returns [`ServeError`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/enum.ServeError.html) only when the session itself fails (a malformed command list, a broken stream, or a repository error while applying the push).

Hook scripts inherit the repository [`Environment`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html): set `REMOTE_USER` (or any other variable hooks should see) with [`Environment::with_var`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html#method.with_var) on the [`RepositoryOptions`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html) you pass when opening the repository for serve. [`ReceiveHook::post_receive`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/trait.ReceiveHook.html#method.post_receive) and [`ReceiveHook::post_update`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/trait.ReceiveHook.html#method.post_update) run after refs move and the matching scripts; refusals are recorded on [`ReceiveOutcome::post_receive_callback_error`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ReceiveOutcome.html#structfield.post_receive_callback_error) and [`ReceiveOutcome::post_update_callback_error`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ReceiveOutcome.html#structfield.post_update_callback_error) without changing the client status report or undoing ref updates.

[`grit_protocol::ServeSession`](https://docs.rs/grit-protocol/latest/grit_protocol/struct.ServeSession.html) threads an optional in-process [`ReceiveHook`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/trait.ReceiveHook.html) and [`CancelToken`](https://docs.rs/grit-lib/latest/grit_lib/progress/struct.CancelToken.html) through `grit-protocol` and `grit-http-server` smart HTTP handlers; every push still runs [`grit_protocol::PushGuard`](https://docs.rs/grit-protocol/latest/grit_protocol/struct.PushGuard.html) alongside your hook. [`stateless_rpc_with_session`](https://docs.rs/grit-protocol/latest/grit_protocol/receive_pack/fn.stateless_rpc_with_session.html) and [`stateless_rpc_to_reader_with_session`](https://docs.rs/grit-protocol/latest/grit_protocol/upload_pack/fn.stateless_rpc_to_reader_with_session.html) return typed outcomes instead of discarding them.

Setting [`ReceivePolicy::fsck_objects`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ReceivePolicy.html#structfield.fsck_objects) to an [`ObjectFsckPolicy`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/fsck/struct.ObjectFsckPolicy.html) (what `receive.fsckObjects` does) checks every pushed commit, tree and tag while it is still in quarantine. A malformed object refuses the whole push with [`UnpackError::Rejected`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/enum.UnpackError.html#variant.Rejected), which names the object and its fsck message id; every update fails with `unpacker error` and the quarantine is deleted. Transfer checks are strict like Git's (warnings are errors); [`ObjectFsckPolicy::set_level`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/fsck/struct.ObjectFsckPolicy.html#method.set_level) changes single messages, as `receive.fsck.<msg-id>` does in config.

```rust
use grit_lib::maintenance::fsck::{FsckMsgLevel, ObjectFsckPolicy};
use grit_lib::remote::serve::ReceivePolicy;

let mut fsck = ObjectFsckPolicy::default();
fsck.set_level("missingEmail", FsckMsgLevel::Warn);
let policy = ReceivePolicy::default().with_fsck_objects(Some(fsck));
assert!(policy.fsck_objects.is_some());
```

To check objects from some other source with the same rules, call [`ObjectFsckPolicy::checker`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/fsck/struct.ObjectFsckPolicy.html#method.checker) once and [`ObjectFsckChecker::check`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/fsck/struct.ObjectFsckChecker.html#method.check) per object.

This server serves fetches, and refuses pushes to `refs/heads/protected/*` with a closure. Git runs it as `git push --receive-pack='guide_serve receive-pack' <path>` (and `--upload-pack='guide_serve upload-pack'` for clone and fetch):

```rust
//! A minimal Git server on stdin/stdout: serve fetches with `UploadPack` and
//! pushes with `ReceivePack::with_hook`, refusing pushes to protected branches
//! from Rust code instead of a hook script.
//!
//! Git starts it with the repository path as the last argument:
//!
//! ```text
//! git clone --upload-pack='guide_serve upload-pack' /srv/repo.git
//! git push --receive-pack='guide_serve receive-pack' /srv/repo.git main
//! ```
//!
//! Source for the library guide "Network" page (included in the docs site).

use std::io::{BufWriter, Write};
use std::path::Path;

use grit_lib::config::environment::RepositoryOptions;
use grit_lib::objects::odb::Odb;
use grit_lib::remote::serve::{
    self, ProtocolVersion, ReceiveHook, ReceiveHookContext, ReceivePolicy, RefCommand,
    RefUpdateRefusal, ServeOptions,
};
use grit_lib::repo::Repository;

/// Refuse every update to `refs/heads/protected/*`; the reason is shown to the
/// pushing user next to the rejected ref.
fn protect_branches(cmd: &RefCommand, _odb: &Odb) -> Result<(), RefUpdateRefusal> {
    if cmd.refname.starts_with("refs/heads/protected/") {
        return Err(RefUpdateRefusal::Policy("protected branch".to_owned()));
    }
    Ok(())
}

struct ServerHook;

impl ReceiveHook for ServerHook {
    fn pre_receive_ctx(
        &self,
        _commands: &[RefCommand],
        _odb: &Odb,
        ctx: &ReceiveHookContext<'_>,
    ) -> Result<(), RefUpdateRefusal> {
        if ctx.push_options.iter().any(|o| o == "ci.skip") {
            return Err(RefUpdateRefusal::Policy("ci.skip".to_owned()));
        }
        Ok(())
    }

    fn update(&self, command: &RefCommand, odb: &Odb) -> Result<(), RefUpdateRefusal> {
        protect_branches(command, odb)
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut args = std::env::args().skip(1);
    let (Some(service), Some(path)) = (args.next(), args.next()) else {
        return Err("usage: guide_serve <upload-pack|receive-pack> <repository>".into());
    };
    let repo = Repository::open(
        Path::new(&path),
        &RepositoryOptions::from_process().for_serving(),
    )?;

    // The process boundary owns the environment: the library never reads it.
    let protocol = std::env::var("GIT_PROTOCOL")
        .map(|v| ProtocolVersion::from_git_protocol(&v))
        .unwrap_or_default();
    let mut opts = ServeOptions::default()
        .with_protocol(protocol)
        .with_agent("guide-serve/1".to_owned());

    let mut input = std::io::stdin().lock();
    let mut output = BufWriter::new(std::io::stdout().lock());
    match service.as_str() {
        "upload-pack" => {
            let summary = serve::UploadPack::new(&repo, &mut opts).run(&mut input, &mut output)?;
            eprintln!(
                "upload-pack: {} bytes, {} objects, {} negotiation rounds",
                summary.bytes_written, summary.objects_sent, summary.negotiation_rounds
            );
        }
        "receive-pack" => {
            let policy = ReceivePolicy::from_config(&*repo.config().snapshot()?);
            let outcome = serve::ReceivePack::new(&repo, &opts, &policy)
                .with_hook(&ServerHook)
                .run(&mut input, &mut output)?;
            // Typed results: match on the refusal, never on its text.
            for update in &outcome.updates {
                if let Some(RefUpdateRefusal::Policy(reason)) = &update.error {
                    eprintln!("refused {}: {reason}", update.refname);
                }
            }
        }
        other => return Err(format!("unknown service '{other}'").into()),
    }
    output.flush()?;
    Ok(())
}
```

Integration test `guide_serve` clones through it over protocol v0 and v2, pushes a commit, checks `git fsck --strict` on the server, and checks that a push to a protected branch is reported as `[remote rejected] (protected branch)`. The `grit upload-pack` / `grit receive-pack` commands and `grit-http-server` are built on the same sessions.

## Partial clone and promisor fetch

Filtered fetch and clone record a promisor remote (`remote.<name>.promisor`, `extensions.partialclone`, and `remote.<name>.partialclonefilter`). Blobs omitted from the initial pack are **promised**: they appear in the object database as missing until fetched on demand.

Install a [`PromisorFetcher`](https://docs.rs/grit-lib/latest/grit_lib/objects/promisor/trait.PromisorFetcher.html) on [`RepositoryOptions::with_promisor_fetcher`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.with_promisor_fetcher) (no global state). The default [`DefaultPromisorFetcher`](https://docs.rs/grit-lib/latest/grit_lib/objects/promisor/struct.DefaultPromisorFetcher.html) sends `want` lines for the missing object ids with `filter blob:none` (as Git does), does not update refs, and ingests the reply as a promisor pack. It asks the promisor remotes one after another in [`lazy_fetch_order`](https://docs.rs/grit-lib/latest/grit_lib/objects/promisor_remote/fn.lazy_fetch_order.html): config order with the `extensions.partialClone` remote last, each for what is still missing, moving on when one fails. A server refuses a whole request when it lacks one of the objects, so when a remote failed and several objects are still missing, the rest is split in halves that go through the remotes again: a large-object promisor that holds only the large blobs and `origin` holding the small ones serve one checkout between them. A remote that cannot be used at all (unreachable, no usable URL, authentication failed) is not asked again. When objects stay missing, the error is [`ObjectError::PromisorFetchFailed`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.ObjectError.html#variant.PromisorFetchFailed), naming each remote that failed with a summary of its first error, or [`ObjectError::PromisedMissing`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.ObjectError.html#variant.PromisedMissing) when every remote answered without the object. The `grit` CLI installs this fetcher for every opened repository.

When a fetcher is installed and [`fetch.promisorLazy`](https://docs.rs/grit-lib/latest/grit_lib/objects/promisor/constant.PROMISOR_LAZY_FETCH_CONFIG.html) is true (the default), an ODB read miss in a partial-clone repository triggers an isolated fetch (with recursion protection) and retries the read. With no fetcher, or when lazy fetch is disabled, reads return [`ObjectError::PromisedMissing`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.ObjectError.html#variant.PromisedMissing). Set `fetch.promisorLazy=false` in config, or `GRIT_NO_LAZY_FETCH=1` / `GIT_NO_LAZY_FETCH=1` in the environment, to opt out.

[`Repository::prefetch_promised`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.prefetch_promised) batch-fetches object ids before bulk reads. Tree-to-tree checkout (including clone checkout and [`grit switch`](https://grit-scm.com/docs/library/commands/switch.md/index.md)) collects missing blob oids from the diff and prefetches them in a single request when a fetcher is present. Hard reset also batches materialization and repair of unchanged paths, including an empty worktree/index after a metadata-only clone. Its batch includes required attribute blobs before attribute resolution, deduplicates shared blob ids, and excludes gitlinks and sparse-skipped paths that need no content. Files proven up to date by index stat data require no blob download. Repeating a reset after materialization uses the local objects and makes no data fetch.

[`CloneOptions::promisor_fetcher`](https://docs.rs/grit-lib/latest/grit_lib/remote/clone/struct.CloneOptions.html) carries the fetcher through to the opened repository so blobless clone checkout can prefetch without a separate reopen.

On the serving side, pass the client's [`ObjectFilter`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/rev_list/enum.ObjectFilter.html) to [`UploadPackStream::with_filter`](https://docs.rs/grit-lib/latest/grit_lib/objects/pack_objects/struct.UploadPackStream.html#method.with_filter) (or build it in memory with [`UploadPackStream::build`](https://docs.rs/grit-lib/latest/grit_lib/objects/pack_objects/struct.UploadPackStream.html#method.build)). The filtered pack streams like an unfiltered one and holds the objects `git pack-objects --filter` selects: wanted objects and tag targets always, then the commits, trees and blobs the filter keeps.

### Large-object promisors

A server can point clients at the remotes that hold some of its objects, such as a large-object promisor (LOP) with the big blobs, through the protocol v2 `promisor-remote` capability. [`PromisorAdvertisement`](https://docs.rs/grit-lib/latest/grit_lib/objects/promisor_remote/struct.PromisorAdvertisement.html) models it: [`from_server_config`](https://docs.rs/grit-lib/latest/grit_lib/objects/promisor_remote/struct.PromisorAdvertisement.html#method.from_server_config) builds it from `promisor.advertise` and `promisor.sendFields`, and [`UploadPack`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.UploadPack.html) advertises it and collects the names a client accepts in [`ServeOptions::accepted_promisor_remotes`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ServeOptions.html#structfield.accepted_promisor_remotes). `uploadpack.allowAnySHA1InWant` lets a LOP served by grit hand out blobs no ref points at.

On the client, a v2 fetch reads the advertisement and runs [`PromisorHandshake::evaluate`](https://docs.rs/grit-lib/latest/grit_lib/objects/promisor_remote/struct.PromisorHandshake.html#method.evaluate) ([`PromisorHandshakeOptions`](https://docs.rs/grit-lib/latest/grit_lib/objects/promisor_remote/struct.PromisorHandshakeOptions.html) says whether the fetch is partial and whether to pick the filter automatically): [`PromisorAcceptPolicy`](https://docs.rs/grit-lib/latest/grit_lib/objects/promisor_remote/struct.PromisorAcceptPolicy.html) (`promisor.acceptFromServer`, `checkFields`, `storeFields`) decides, against the promisor remotes already in config ([`configured_promisor_remotes`](https://docs.rs/grit-lib/latest/grit_lib/objects/promisor_remote/fn.configured_promisor_remotes.html)), which advertised remotes to accept, and each verdict is a [`PromisorRejection`](https://docs.rs/grit-lib/latest/grit_lib/objects/promisor_remote/enum.PromisorRejection.html) or acceptance. Only a partial fetch accepts anything: one with a filter, or one from a remote configured as a promisor remote. The accepted names go back to the server with both the `ls-refs` and the `fetch` request, so a stateless smart-HTTP server sees them where it builds the pack. With [`FetchOptions::auto_filter`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/struct.FetchOptions.html#structfield.auto_filter) the filter comes from the accepted remotes ([`PromisorDecision::combined_filter`](https://docs.rs/grit-lib/latest/grit_lib/objects/promisor_remote/struct.PromisorDecision.html#method.combined_filter)). The result is in [`FetchOutcome::promisor`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/struct.FetchOutcome.html#structfield.promisor) and [`CloneOutcome::promisor`](https://docs.rs/grit-lib/latest/grit_lib/remote/clone/struct.CloneOutcome.html#structfield.promisor).

```rust
use grit_lib::remote::clone::{clone, CloneOptions};

let opts = CloneOptions::new("https://git.example.com/project.git", "project".into())
    .with_auto_filter(true)
    .with_config(vec![
        ("remote.lop.url".into(), "https://lop.example.com/project.git".into()),
        ("remote.lop.promisor".into(), "true".into()),
        ("promisor.acceptFromServer".into(), "knownUrl".into()),
    ]);
let outcome = clone(opts, &mut progress, &cancel, None)?;
for remote in outcome.promisor.iter().flat_map(|h| h.decision.accepted()) {
    println!("accepted {}", remote.name);
}
```

Accepting never creates a remote, and lazy fetches use the URL configured locally, not the advertised one.

### Serving a repository whose large blobs live on a LOP

After [`repo.maintenance().offload_blobs`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/struct.Maintenance.html#method.offload_blobs) (see [Maintenance](https://grit-scm.com/docs/library/network/maintenance.md/index.md)), a server's large blobs live only on its LOP, and the rest of the repository sits in a `.promisor` pack. [`UploadPack`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.UploadPack.html) serves such a repository by Git's rule. A client that accepted an advertised promisor remote gets packs without the promised blobs it lacks, and fetches those from the LOP. For any other client, the server either fetches them first or refuses with [`ServeError::ObjectMissing`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/enum.ServeError.html#variant.ObjectMissing). That error carries a structured reason and reaches the client as an `ERR` line before any pack data. Fetching first needs [`ServeOptions::lazy_fetch`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ServeOptions.html#structfield.lazy_fetch), or `uploadpack.lazyFetch` when it is `None`, plus a [`PromisorFetcher`](https://docs.rs/grit-lib/latest/grit_lib/objects/promisor/trait.PromisorFetcher.html) on the served repository. The library reads no environment: [`ServeOptions::lazy_fetch_from_environment`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ServeOptions.html#method.lazy_fetch_from_environment) maps `GIT_NO_LAZY_FETCH`, and [`ServeOptions::attach_promisor_fetcher`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ServeOptions.html#method.attach_promisor_fetcher) gives the opened repository a fetcher only when [`ServeOptions::lazy_fetch_enabled`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ServeOptions.html#method.lazy_fetch_enabled), and takes away any it was opened with otherwise, so a server without lazy fetch never fetches. Each fetch is planned again after a lazy fetch, so the client's filter still applies to the fetched blobs. [`ReceivePack`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ReceivePack.html) into such a repository accepts pushed trees that name promised blobs, as Git's connectivity check does. Repositories without promisor remotes keep the bitmap and pack-reuse fast path. Only these partial repositories plan their packs with the object walk, checking each blob is stored.

A local clone or fetch from a repository with promisor remotes of its own goes through the same in-process upload-pack instead of copying its object store, which would come up short.

## Bundles

Offline bundle files are documented on the [Bundle](https://grit-scm.com/docs/library/bundle/index.md) guide (`Bundles`). Smart HTTP and local remotes above cover online fetch/push.
