# grit: the command line

> Everything an agent needs to use `grit` as a Git client: install, the tutorial, global options, scripting with `--json` and `--filter`, the agent guide, and the reference page for every command. `grit` works on any Git repository and talks to any Git remote.

Each section below is one docs page; its heading is the page's URL.

# https://grit-scm.com/docs/index.md

# Docs

> How to use grit, a simple Git client built on grit-lib. Start with the tutorial, then look up any command or open the library guide.

Grit is two things:

- **`grit`** — a Git client with a small, modern command line. It works on any Git repository and talks to any Git remote, but its commands are its own: one obvious way to do the common thing, plain-language output, and `--json` on every command.
- **`grit-lib`** — a fast, linkable Git library for Rust. Everything the CLI does goes through the library; you can embed the same engine in your own tools.

## How these docs are organized

| Section | What you'll find |
| --- | --- |
| **Getting started** | [Install](https://grit-scm.com/docs/install/index.md) grit, follow the [tutorial](https://grit-scm.com/docs/tutorial/index.md), or try the [library quick start](https://grit-scm.com/docs/library-quickstart/index.md). |
| **The grit CLI** | [Global options](https://grit-scm.com/docs/global-options/index.md), [scripting with `--json`](https://grit-scm.com/docs/scripting/index.md), [agent guide](https://grit-scm.com/docs/agents/index.md), and a man page for every command. |
| **Library guide** | Rust-oriented guides for `grit-lib` (growing over time), plus the [API reference on docs.rs](https://docs.rs/grit-lib). |
| **Benchmarks** | How `grit` and `grit-lib` compare to system Git on core operations. |

If you're new to the command line, start with the [tutorial](https://grit-scm.com/docs/tutorial/index.md). If you're wiring Git into a Rust program, start with the [library quick start](https://grit-scm.com/docs/library-quickstart/index.md) and the [library guide overview](https://grit-scm.com/docs/library/index.md).

## CLI vs library

Use **`grit`** when you want a day-to-day Git client from the terminal or in scripts (`--json` / `--filter`). Use **`grit-lib`** when you need programmatic access — opening repositories, reading objects and refs, diffing, revwalking, fetch/push, and the rest of Git's core — inside a Rust binary or service.

On-disk formats and the wire protocol stay compatible with Git; the CLI's argv and messages are deliberately *not* a Git mirror.

See [Install](https://grit-scm.com/docs/install/index.md) for download options, [Global options](https://grit-scm.com/docs/global-options/index.md) for flags shared by every command, [Scripting with grit](https://grit-scm.com/docs/scripting/index.md) for `--json` and `--filter`, and the [Agent guide](https://grit-scm.com/docs/agents/index.md) for automation-focused details.

## For agents

- [grit-cli.md](https://grit-scm.com/docs/grit-cli.md): the whole CLI in one file, to learn grit for everyday Git work.
- [grit-lib.md](https://grit-scm.com/docs/grit-lib.md): the whole library guide in one file, to build Git-compatible Rust programs.
- [llms.txt](https://grit-scm.com/llms.txt): an index of every page with a one-line summary.
- [llms-full.txt](https://grit-scm.com/llms-full.txt): every docs page in one file.

Every page also has a Markdown twin: replace `index.html` with `index.md` in its URL. Run `grit skill` to print an agent skill for the CLI.

## Commands

### Getting started

| Command | Summary |
| --- | --- |
| [`grit init`](https://grit-scm.com/docs/init/index.md) | Create a new, empty repository. |
| [`grit clone`](https://grit-scm.com/docs/clone/index.md) | Copy a remote repository into a new directory. |
| [`grit checkout`](https://grit-scm.com/docs/checkout/index.md) | Start work on a repository from a snapshot of its main branch, or of some of its paths, instead of a clone. |
| [`grit status`](https://grit-scm.com/docs/status/index.md) | Show where you are and what's changed. This is what plain grit runs. |
| [`grit config`](https://grit-scm.com/docs/config/index.md) | Read, set, list or remove configuration values. |

### Making changes

| Command | Summary |
| --- | --- |
| [`grit add`](https://grit-scm.com/docs/add/index.md) | Stage changes. With no paths, stages everything. |
| [`grit commit`](https://grit-scm.com/docs/commit/index.md) | Stage every change and record a new commit. |
| [`grit diff`](https://grit-scm.com/docs/diff/index.md) | Show uncommitted, staged, commit, or range changes. |
| [`grit restore`](https://grit-scm.com/docs/restore/index.md) | Restore working tree and/or index paths from HEAD, the index, or another revision. |
| [`grit rm`](https://grit-scm.com/docs/rm/index.md) | Remove tracked paths from the working tree and index. |
| [`grit mv`](https://grit-scm.com/docs/mv/index.md) | Rename or move tracked paths. |
| [`grit stash`](https://grit-scm.com/docs/stash/index.md) | Save and restore shelved work. |

### History

| Command | Summary |
| --- | --- |
| [`grit log`](https://grit-scm.com/docs/log/index.md) | Show commits, newest first: the whole history in the pager on a terminal, a page at a time for scripts and agents. |
| [`grit blame`](https://grit-scm.com/docs/blame/index.md) | Show who last modified each line of a file. |
| [`grit reflog`](https://grit-scm.com/docs/reflog/index.md) | Show, delete, or expire reflog entries. |
| [`grit shortlog`](https://grit-scm.com/docs/shortlog/index.md) | List the commits on this branch that aren't on the target branch yet. |
| [`grit revs`](https://grit-scm.com/docs/revs/index.md) | List or count commits matching revision ranges. |
| [`grit show`](https://grit-scm.com/docs/show/index.md) | Show a commit, tag or branch, and the change it introduced. |
| [`grit merge-base`](https://grit-scm.com/docs/merge-base/index.md) | Find common ancestors or test whether one commit is an ancestor of another. |
| [`grit notes`](https://grit-scm.com/docs/notes/index.md) | List, show, add, and remove Git notes on commits. |
| [`grit describe`](https://grit-scm.com/docs/describe/index.md) | Nearest reachable tag, exact commit distance, and abbreviated id for a revision. |
| [`grit rebase`](https://grit-scm.com/docs/rebase/index.md) | Replay local commits onto a new base; recover from conflicts and exec commands that leave edits. |
| [`grit history`](https://grit-scm.com/docs/history/index.md) | Stateless history rewrite helpers (reword, and more over time). |

### Branches and tags

| Command | Summary |
| --- | --- |
| [`grit branch`](https://grit-scm.com/docs/branch/index.md) | List branches, or create, delete, rename, or configure one. |
| [`grit switch`](https://grit-scm.com/docs/switch/index.md) | Switch to another branch, remote branch, or detached commit. |
| [`grit merge`](https://grit-scm.com/docs/merge/index.md) | Merge another branch, tag or commit into the current one. |
| [`grit reset`](https://grit-scm.com/docs/reset/index.md) | Move the branch tip and optionally reset the index or worktree. |
| [`grit pick`](https://grit-scm.com/docs/pick/index.md) | Cherry-pick one or more commits onto the current branch. |
| [`grit revert`](https://grit-scm.com/docs/revert/index.md) | Undo commits with new inverse commits. |
| [`grit tag`](https://grit-scm.com/docs/tag/index.md) | List tags, or create or delete one (lightweight or annotated). |
| [`grit worktree`](https://grit-scm.com/docs/worktree/index.md) | List, add, and remove linked worktrees for the same repository. |

### Remotes

| Command | Summary |
| --- | --- |
| [`grit remote`](https://grit-scm.com/docs/remote/index.md) | List remotes, add one, show one, set URLs, rename or remove one, or list refs on a remote. |
| [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) | Download new commits, branches and tags from a remote. |
| [`grit pull`](https://grit-scm.com/docs/pull/index.md) | Fetch from the remote and bring the current branch up to date. |
| [`grit push`](https://grit-scm.com/docs/push/index.md) | Publish branches, tags, or explicit refspecs to a remote. |
| [`grit auth`](https://grit-scm.com/docs/auth/index.md) | Sign in to GitButler Code, GitHub or a grit serve host, or save a username and token for any HTTPS host, so pushes and fetches just work. |
| [`grit bundle`](https://grit-scm.com/docs/bundle/index.md) | Create, verify, list, and unbundle git bundle files for offline transfer. |
| [`grit serve`](https://grit-scm.com/docs/serve/index.md) | Serve repositories over HTTP, with a web view where people sign in with email and password. |
| [`grit checkin`](https://grit-scm.com/docs/checkin/index.md) | Send a snapshot checkout's branches back to the server, rebuilt on its real history. |
| [`grit integrate`](https://grit-scm.com/docs/integrate/index.md) | Merge a branch into the server's target branch, from a snapshot checkout or a clone of a hosted project. |
| [`grit slice`](https://grit-scm.com/docs/slice/index.md) | Name sets of paths to check out together, kept on the server's target branch. |
| [`grit sync`](https://grit-scm.com/docs/sync/index.md) | Push and pull every active branch between a clone and your space on a grit hosting server. |
| [`grit share`](https://grit-scm.com/docs/share/index.md) | Work on a branch together with other users of a grit hosting server, each with their own head of it. |

### Maintenance

| Command | Summary |
| --- | --- |
| [`grit clean`](https://grit-scm.com/docs/clean/index.md) | Remove untracked files from the working tree. |
| [`grit update`](https://grit-scm.com/docs/update/index.md) | Update grit to the latest release. |
| [`grit repack`](https://grit-scm.com/docs/repack/index.md) | Pack reachable objects and remove redundant packs. |
| [`grit skill`](https://grit-scm.com/docs/skill/index.md) | Print an agent skill that explains how to use grit. |
| [`grit completions`](https://grit-scm.com/docs/completions/index.md) | Generate shell completion scripts for bash, zsh, and fish. |
| [`grit gc`](https://grit-scm.com/docs/gc/index.md) | Run repository maintenance — pack refs, expire reflogs, repack, prune, and refresh commit-graph. |
| [`grit fsck`](https://grit-scm.com/docs/fsck/index.md) | Check refs, objects, and pack indexes for problems. |

### Plumbing

| Command | Summary |
| --- | --- |
| [`grit hooks`](https://grit-scm.com/docs/hooks/index.md) | List hook scripts and run them by name. |
| [`grit upload-pack`](https://grit-scm.com/docs/upload-pack/index.md) | Serve a fetch or clone of a repository over stdin and stdout. |
| [`grit patch-id`](https://grit-scm.com/docs/patch-id/index.md) | Stable patch-IDs for commits (cherry-pick equivalence). |
| [`grit receive-pack`](https://grit-scm.com/docs/receive-pack/index.md) | Accept a push to a repository over stdin and stdout. |
| [`grit manager`](https://grit-scm.com/docs/manager/index.md) | A credential helper that stores passwords and tokens in the Windows Credential Manager. |
| [`grit resolve`](https://grit-scm.com/docs/resolve/index.md) | Resolve revision specs to object ids and types. |
| [`grit cat`](https://grit-scm.com/docs/cat/index.md) | Show blob, tree, commit, or tag contents for a revision spec. |
| [`grit ignore`](https://grit-scm.com/docs/ignore/index.md) | Query whether paths match exclude (gitignore) rules. |

# https://grit-scm.com/docs/install/index.md

# Install grit

> Install the grit CLI on your machine, try nightly builds, and keep your copy up to date.

## Stable release (recommended)

On macOS and Linux:

```bash
curl -fsSL https://grit-scm.com/install | sh
```

On Windows, run this in PowerShell:

```bash
irm https://grit-scm.com/install.ps1 | iex
```

The script downloads the latest release from GitHub, installs the `grit` binary (by default into `~/.local/bin` on Unix), and prints the version it installed.

## Linux GNU loader compatibility

Linux x86_64 releases provide two GNU assets. Both preserve PIE and ASLR:

| Asset | Loader support |
| --- | --- |
| `grit-x86_64-unknown-linux-gnu.tar.gz` | Default and fallback; glibc 2.34 or newer, standard relocations |
| `grit-x86_64-unknown-linux-gnu-relr.tar.gz` | Manual opt-in; glibc 2.36 or newer, packed relative relocations (RELR) |

The stable and nightly installers always choose the existing GNU asset on glibc
systems, including glibc 2.36 and newer. The RELR asset is available only as a
manual download for glibc 2.36+. Its smaller relocation metadata does not
consistently improve startup: final-tip review measurements found tiny commands
about **1–2% slower**, despite gains at earlier revisions. Automatic selection
is deferred until measurements on the release artifacts demonstrate a benefit;
see [benchmarks](https://grit-scm.com/docs/install/benchmarks.md/index.md#pie-startup-relocation-probe).

The default asset's weak glibc 2.39 references do not require a newer loader.
GNU aarch64, static musl, macOS and Windows keep their existing artifacts and
selection. Static musl artifacts and source builds remain alternatives for
other systems.

## Shell completions

Tab completion helps you discover `grit`'s subcommands and flags. Generate a script with [`grit completions`](https://grit-scm.com/docs/completions/index.md) and load it from your shell config, or copy the pre-generated files from a release tarball's `completions/` directory.

**bash** — add to `~/.bashrc`:

```bash
eval "$(grit completions bash)"
```

**zsh** — add to `~/.zshrc`:

```bash
eval "$(grit completions zsh)"
```

Or install once under a site-functions directory:

```bash
grit completions zsh > ~/.local/share/zsh/site-functions/_grit
```

**fish** — write a completion file:

```bash
mkdir -p ~/.config/fish/completions
grit completions fish > ~/.config/fish/completions/grit.fish
```

After [`grit update`](https://grit-scm.com/docs/update/index.md), regenerate completions so new commands appear.

## Nightly builds

CI publishes a rolling **nightly** prerelease when the release workflow is triggered manually. To install that build instead of the latest stable release:

```bash
curl -fsSL https://grit-scm.com/install-nightly | sh
```

On Windows:

```bash
irm https://grit-scm.com/install-nightly.ps1 | iex
```

Nightlies track recent `main`; use them when you want to test fixes before the next tagged release.

## Install with Cargo

If you already have a Rust toolchain:

```bash
cargo install grit-cli
```

This builds and installs the `grit` executable into Cargo's bin directory (usually `~/.cargo/bin`). Make sure that directory is on your `PATH`.

## Keep grit up to date

After a script install, run [`grit update`](https://grit-scm.com/docs/update/index.md) to re-run the same installer and replace the binary you're running. If you installed with Cargo, update with:

```bash
cargo install grit-cli
```

## Build from source

Clone [the repository](https://github.com/gitbutlerapp/grit) and build the CLI crate:

```bash
cargo build --release -p grit-cli
```

The binary is `target/release/grit`. You can copy it anywhere on your `PATH`, or run it from the build tree.

### Toolchain

**Contributors** building this repository: the workspace pins **1.99.0** in [`rust-toolchain.toml`](https://github.com/gitbutlerapp/grit/blob/main/rust-toolchain.toml) (with `rustfmt` and `clippy`). `rustup` picks that up automatically when you build in the repo.

**Library and CLI consumers** (your own crate depending on `grit-lib` or `grit-cli` from [crates.io](https://crates.io/crates/grit-lib), without this repo's `rust-toolchain.toml`): the published crates require **Rust 1.95** or newer. Cargo prints that requirement before compiling if your toolchain is too old.

To use `grit-lib` in your own project, see the [library quick start](https://grit-scm.com/docs/library-quickstart/index.md).

# https://grit-scm.com/docs/tutorial/index.md

# Tutorial

> Fifteen minutes with grit. Create a repository, record some changes, work on a branch, and share it with a remote.

This walkthrough covers the commands you'll use every day. It assumes you have [installed grit](https://grit-scm.com/docs/install/index.md) and know roughly what a commit and a branch are. The output shown is what `grit` prints, minus the colors.

Regenerated on 2026-10-07 by running the listed commands with `grit` built from this repository (`cargo build --release -p grit-cli`), with `NO_COLOR=1` and author identity `Ada Lovelace <ada@example.com>`.

## Tell grit who you are

Every commit records an author. Set your name and email once, in your global config:

```console
$ grit config --global user.name "Ada Lovelace"
$ grit config --global user.email ada@example.com
```

`grit` reads and writes the same config files as Git, so if you've already set these up for Git, you can skip this step.

## Create a repository

```console
$ grit init project
Initialized empty repository in /workspace/project/.git
$ cd project
```

To work on an existing project instead, copy it with [`grit clone`](https://grit-scm.com/docs/clone/index.md) and skip ahead to the next section:

```console
$ grit clone https://github.com/gitbutlerapp/grit.git
```

## Your home base: grit status

Running `grit` with no arguments shows where you are and what's changed. Add a couple of files and look:

```console
$ echo "# Notes" > README.md
$ echo "fn main() {}" > main.rs
$ grit
On main — no commits yet

Untracked
  ?  untracked     README.md
  ?  untracked     main.rs

→ grit add <file> to stage
```

The last line always suggests the next step. You'll come back to this screen a lot; [`grit status`](https://grit-scm.com/docs/status/index.md) (or `grit st`) shows the same thing.

## Record a commit

[`grit commit`](https://grit-scm.com/docs/commit/index.md) stages every change in the working tree and records it in one step:

```console
$ grit commit "Start the project"
[main 310fdb0] Start the project
2 changes committed
```

By default `grit commit` records every change in one step. When you need tighter control, use [`grit add`](https://grit-scm.com/docs/add/index.md) (`--dry-run`, `-u`, or path lists) and [`grit commit --staged`](https://grit-scm.com/docs/commit/index.md) or `grit commit -m "…" -- <paths>` to commit only part of the work while leaving other staged edits in the index.

Each grit commit also gets a stable [change id](https://grit-scm.com/docs/change-ids/index.md) that stays with the same logical change when you amend or rewrite history; `grit log` shows a short `change …` prefix beside each commit.

Look at the history with [`grit log`](https://grit-scm.com/docs/log/index.md):

```console
$ grit log
  310fdb0  ada  just now  Start the project
```

## Work on a branch

Create a branch and switch to it with [`grit switch -c`](https://grit-scm.com/docs/switch/index.md):

```console
$ grit switch -c feature
Created and switched to branch feature
```

Make a change and look at it with [`grit diff`](https://grit-scm.com/docs/diff/index.md) before committing:

```console
$ printf 'fn main() {\n    println!("hi");\n}\n' > main.rs
$ grit diff

main.rs
@@ -1 +1 @@
 1    │ - fn main() {}
    1 │ + fn main() {
    2 │ +     println!("hi");
    3 │ + }
```

The two number columns are the old and new line numbers. Commit the change:

```console
$ grit commit "Say hi"
[feature 2e409e2] Say hi
1 change committed
```

[`grit show`](https://grit-scm.com/docs/show/index.md) displays a commit, its message and the files it changed. With no argument, it shows the latest commit:

```console
$ grit show
branch feature
commit 2e409e26f8b370ea1928a8fb93dcf2e025418e1f
Author: Ada Lovelace <ada@example.com>
Date:   2026-10-07 14:55:47 +0000

    Say hi

 main.rs |   4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
```

## Merge it back

Switch back to `main` and [merge](https://grit-scm.com/docs/merge/index.md) the branch in. Nothing else has happened on `main`, so `grit` just moves `main` forward:

```console
$ grit switch main
Switched to branch main
$ grit merge feature
Fast-forwarded feature → 2e409e2
```

The branch is done, so [delete it](https://grit-scm.com/docs/branch/index.md):

```console
$ grit branch -d feature
Deleted branch feature (was 2e409e2).
```

`grit branch -d` refuses to delete a branch whose commits haven't been merged into the branch you're on. Use `--force-delete` (or `-D`) when you really mean it.

## Share it with a remote

A remote is another copy of the repository, usually on a server. Add one called `origin` with [`grit remote add`](https://grit-scm.com/docs/remote/index.md), then [push](https://grit-scm.com/docs/push/index.md):

```console
$ grit remote add origin https://github.com/ada/project.git
Added remote origin → https://github.com/ada/project.git
$ grit push
  pushed main → origin refs/heads/main
```

`grit push` sends the current branch to a branch with the same name on `origin`, creating it if needed. To publish under another name, pass a refspec: `grit push origin HEAD:refs/heads/experiment`. Set upstream tracking with [`grit branch -u`](https://grit-scm.com/docs/branch/index.md) when you want `grit pull` to know which remote branch to follow. For GitHub over HTTPS, [`grit auth`](https://grit-scm.com/docs/auth/index.md) signs you in, and `grit` offers to run it if a push fails for lack of credentials.

To download updates without moving your branch, [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) is enough. Fetch a single branch when you do not need every remote-tracking ref:

```console
$ grit fetch origin main
  refs/remotes/origin/main  ← refs/heads/main  a8e620a → b52cca6
Fetched 1 update from origin.
```

To get other people's work into your branch, run [`grit pull`](https://grit-scm.com/docs/pull/index.md). It fetches and integrates: fast-forward when you have no local commits, a merge commit when both sides moved, or a rebase when you pass `--rebase` (or set `pull.rebase`):

```console
$ grit pull
Merged origin/main into the current branch (91275a2)

$ grit pull --rebase
Rebased onto origin/main (c4f1a9b)
```

Use [`grit pull --ff-only`](https://grit-scm.com/docs/pull/index.md) in scripts that must refuse merge commits (exit **128** with `refused_not_ff` when histories diverged).

If someone pushed before you, a normal `grit push` is rejected:

```console
$ grit push
  rejected origin refs/heads/main: not a fast-forward — run `grit pull` first
```

To replay your own commits onto another base without fetching first, use [`grit rebase`](https://grit-scm.com/docs/rebase/index.md) (default upstream is `@{upstream}`; `--onto` for Git's `--onto`).

After rewriting commits with [`grit history`](https://grit-scm.com/docs/history/index.md) (reword, drop, fixup, squash, or rebase), fetch so your remote-tracking refs are current, then push with a lease. A plain `grit push` after a rewrite is rejected with a hint to use `--force-with-lease` (or pull first):

```console
$ grit fetch origin
$ grit push --force-with-lease
  pushed main → origin refs/heads/main
```

## Tag a release

[`grit tag`](https://grit-scm.com/docs/tag/index.md) marks the current commit, and `grit push --tags` publishes your tags. Signed or `tree-sha256` annotated tags can be checked locally with `grit tag --verify`:

```console
$ grit tag v0.1 -m 'release'
Created tag v0.1
$ grit tag --verify v0.1 --no-signature
tag v0.1 (…): ok
$ grit push --tags
  pushed --tags → origin refs/tags/v0.1
```

## When things conflict

When `grit merge`, `grit pull`, or `grit pick` hits conflicting changes, grit stops with conflict markers in the worktree and records in-progress state (for pick/revert, Git-compatible `CHERRY_PICK_HEAD` and `.git/sequencer/`). Fix the files, `grit add` the resolved paths, then run `grit merge` with a normal commit for merges, or `grit pick --continue` / `grit revert --continue` for cherry-picks and reverts. Use `--abort` on the same command to cancel.

`grit` refuses to switch branches, merge, or pull when your local edits would be overwritten by files that differ on the other side. Unrelated uncommitted edits are kept, like Git. Use [`grit reset --soft HEAD~1`](https://grit-scm.com/docs/reset/index.md) to uncommit while keeping changes staged.

## Offline bundles and linked worktrees

To move commits without a network, [`grit bundle create`](https://grit-scm.com/docs/bundle/index.md) writes a single file; [`grit bundle unbundle`](https://grit-scm.com/docs/bundle/index.md) ingests it into another repository. For a second checkout of the same repository, [`grit worktree add`](https://grit-scm.com/docs/worktree/index.md) creates a linked working tree; [`grit worktree lock`](https://grit-scm.com/docs/worktree/index.md) marks one as locked when you need to prevent accidental removal.

## Scripting

Every command takes `--json` and prints a single JSON object, which is handy for scripts and agents. `--filter` picks out the part you need:

```console
$ grit status --json --filter '{branch, clean}'
{
  "branch": "main",
  "clean": true
}
```

See [Scripting with grit](https://grit-scm.com/docs/scripting/index.md) for details, and each command's page for its JSON fields.

## Where to go next

Every command has a man page with its options and examples. Start from the [command list](https://grit-scm.com/docs/index.md#commands).

# https://grit-scm.com/docs/change-ids/index.md

# Change ids

> Stable change identifiers on commits, Git interop, and revision selection.

Every commit [`grit commit`](https://grit-scm.com/docs/commit/index.md) creates can carry a **`change-id`** header: an opaque token that names the same logical change across rewrites (amend, [`grit history`](https://grit-scm.com/docs/history/index.md) edits, and future rebases). Commits that never received the header still have a **derived** id (Jujutsu-compatible) computed from the commit object id. Grit never rewrites a commit solely to add a header.

## Header format

- On disk: a normal commit header line `change-id <value>` (before any `gpgsig` block).
- Legacy name: `gitbutler-change-id <value>` is still read for compatibility; new writes use `change-id` only.
- Random ids use **reverse-hex**: 16 bytes encoded as 32 characters in the alphabet `k`–`z` (each nibble `n` maps to `'z' - n`).

System **`git`** treats the line like any other commit header: it round-trips through clone and fetch, survives `git cat-file -p`, and passes `git fsck --strict`. Git’s `%(trailers)` pretty-format does not surface `change-id` (it is not a Git trailer), so use `cat-file` or grit’s JSON when you need the stored value.

## Interop with Jujutsu, GitButler, and Gerrit

| Tool | How it relates |
| --- | --- |
| **Jujutsu (`jj`)** | Derives a change id from the commit id with the same algorithm grit uses when no header is present. After grit stores a derived id on rewrite, jj and grit agree on the logical change. |
| **GitButler** | Historically wrote `gitbutler-change-id`; grit reads that name and writes `change-id` on new commits. Stacks and virtual branches can key off the same string grit shows in `log` and `--json`. |
| **Gerrit** | Uses `Change-Id` in the commit message for review matching. Grit’s header is separate (object header, not message footer). Repos imported from Gerrit keep their message trailers; grit adds its own header only on commits it creates. |

## Configuration

| Key | Default | Effect |
| --- | --- | --- |
| [`grit.changeIds`](https://grit-scm.com/docs/config/index.md) | `true` | When `false`, new commits omit the header (byte-identical with plain Git). Existing headers are preserved; history rewrites still copy them but do not invent derived ids. |
| `grit.testing.changeId` | unset | Test-only: `content-hash` makes ids deterministic; any other non-empty value is used verbatim. |

Disable headers when an importer rejects extra commit lines:

```console
$ grit config grit.changeIds false
```

## Display and JSON

**Human [`grit log`](https://grit-scm.com/docs/log/index.md)** (default format) shows the short commit id, then `change` and the first eight reverse-hex characters of the stable id, then author, date, and subject. [`--oneline`](https://grit-scm.com/docs/log/index.md) omits the change column.

**[`--json`](https://grit-scm.com/docs/commands/README.md/index.md#commit-json-object-commitjson)** on [`log`](https://grit-scm.com/docs/log/index.md), [`show`](https://grit-scm.com/docs/show/index.md), [`revs`](https://grit-scm.com/docs/revs/index.md), and [`status`](https://grit-scm.com/docs/status/index.md) includes:

| Field | Meaning |
| --- | --- |
| `change_id` | Stable id (stored header or derived from `oid`). |
| `change_id_stored` | `true` when `change_id` came from a `change-id` / `gitbutler-change-id` header in the object. |

Mutation commands ([`commit`](https://grit-scm.com/docs/commit/index.md), [`pick`](https://grit-scm.com/docs/pick/index.md), [`revert`](https://grit-scm.com/docs/revert/index.md), [`merge`](https://grit-scm.com/docs/merge/index.md), [`pull`](https://grit-scm.com/docs/pull/index.md), [`history`](https://grit-scm.com/docs/history/index.md)) report `change_id` on the commits they create. [`grit commit --json`](https://grit-scm.com/docs/commit/index.md) sets `change_id` to the stored header value or JSON `null` when the header is absent (for example with `grit.changeIds=false`).

## Which commits get ids

- **New ids:** ordinary commits, the initial commit, merge conclusions, pick, revert, and commits inserted during a history rewrite.
- **Same id kept:** amend, history reword/fixup/squash/drop/replay when the logical change survives.
- **Derived id stored on rewrite:** headerless commits (for example from plain `git commit`) receive a stored `change-id` equal to the derived value the first time grit rewrites them.

Pick and revert always allocate a **new** id; they never copy the source commit’s id.

## Revisions

After refs and abbreviated object ids, grit accepts **change ids** as revision tokens:

- **Alphabet:** reverse-hex tokens use `k`–`z`, length 4–32. Such tokens are resolved as change-id prefixes, not Git object ids.
- **Lookup:** grit walks commits reachable from refs and `HEAD`, matches [`resolved_change_id`](https://docs.rs/grit-lib/latest/grit_lib/change_id/fn.resolved_change_id.html) (stored or derived), and requires a unique prefix.
- **Composition:** suffixes work as usual — `\<cid\>~1`, `\<cid\>^`, ranges, peel operators, and `:path` forms compose on the resolved commit.
- **Precedence:** a branch or tag with the same name wins over a change-id token.

Examples:

```console
$ grit show krrtwksq --json
$ grit log yrwyvtvk -n 1 --json
$ grit history reword krrtwksq -m "new subject"
```

Ambiguous prefixes fail with a list of candidate commits (same as ambiguous short oids).

## Library API

For embedders, see the [library guide on change ids](https://grit-scm.com/docs/library/change-ids/index.md) (`ChangeId`, `ChangeIdPolicy`, header helpers, and lookup).

# https://grit-scm.com/docs/global-options/index.md

# Global options

> Options that apply to every grit command.

These options work on any command (and on `grit` itself when you pass no subcommand).

| Option | Description |
| --- | --- |
| `--json` | Print one JSON object instead of human-readable text. Errors become `{"error": "..."}`. |
| `--markdown` | Print agent-friendly Markdown instead of human-readable text. Most commands render structured headings, lists, and tables (or fenced diffs) rather than dumping JSON. Mutually exclusive with `--json`. |
| `--filter <EXPR>` | Apply a jq expression to the JSON output. Requires `--json`. Iterator-style filters always emit a JSON array; singular filters emit one value (`null` when absent). |
| `--threads <N>` | Worker threads for parallel library work inside this process. `0` selects all logical CPUs (Git-style auto); `1` forces serial paths. Does not change human, `--json`, or `--markdown` output shape. |
| `--no-optional-locks` | Skip opportunistic index updates that take optional locks (same as `GIT_OPTIONAL_LOCKS=0`). Stat refresh still runs in memory; `.git/index` is left untouched. |
| `-h`, `--help` | Print help for `grit` or for a command. |
| `-v`, `--version` | Print the version of `grit`. `-V` works too. |

Running `grit` with no command is the same as [`grit status`](https://grit-scm.com/docs/status/index.md).

## Repository and config options

These go **before** the command name (`grit -C repo status`, not `grit status -C repo`), as in Git, so they never collide with a command's own short flags.

| Option | Description |
| --- | --- |
| `-C <DIR>` | Run as if `grit` was started in `<DIR>`. Repeatable: each one is relative to the previous (`-C a -C b` is `a/b`). An empty `<DIR>` (`-C ""`) changes nothing. A directory that does not exist fails with exit `1`. |
| `-c <KEY=VALUE>` | Set a config value for this invocation only, without touching any config file. Repeatable; a later `-c` wins over an earlier one, over `GIT_CONFIG_COUNT` pairs and over every config file. A bare `<KEY>` with no `=` means `true`, and `<KEY>=` sets the empty string. An invalid key is a usage error (exit `2`). |
| `--git-dir <PATH>` | Use this repository directory instead of discovering one. Same as `GIT_DIR`. Without `--work-tree`, the current directory is the work tree (unless the repository is bare or sets `core.worktree`). |
| `--work-tree <PATH>` | Use this directory as the top of the work tree. Same as `GIT_WORK_TREE`. |

`-C` is applied first, so a relative `--git-dir` or `--work-tree` is resolved from the new directory. The overrides are exported to everything `grit` starts, using the same `GIT_DIR`, `GIT_WORK_TREE` and `GIT_CONFIG_PARAMETERS` encoding Git uses, so hooks that run `git` see the same repository and config.

```console
$ grit -C services/api status --json --filter .branch
"main"
$ grit -c user.name="CI Bot" -c user.email=ci@example.com commit -m "Update lockfile"
[main 3f9c2ab] Update lockfile
1 change committed
$ grit --git-dir /srv/site.git --work-tree /var/www/site status
```

On Unix, the final working directory after all `-C` options, and the paths supplied to `--git-dir` and `--work-tree`, must be valid UTF-8. Unsupported repository selections are rejected before discovery or command execution with exit **2**, so a raw-byte name cannot select a similarly named Unicode repository. Human output reports the usage error on stderr; `--json` writes an error object with `kind: "usage"` on stdout; `--markdown` writes `**Error:**` on stdout. Traversing a non-UTF-8 directory with `-C` is supported when a subsequent `-C` returns to a UTF-8 working directory.

Library embedders get the same behavior from [`Environment::with_git_dir`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html), [`Environment::with_work_tree`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html) and [`Environment::push_config_override`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html) with a parsed [`ConfigOverride`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.ConfigOverride.html).

## Environment variables

The `grit` CLI snapshots the process environment into [`Environment`](https://grit-scm.com/docs/library/repository/index.md) when opening a repository. Library embedders should construct an [`Environment`](https://grit-scm.com/docs/library/repository/index.md) explicitly instead of relying on these variables.

| Variable | Effect |
| --- | --- |
| `GIT_DIR`, `GIT_WORK_TREE`, `GIT_CEILING_DIRECTORIES`, `GIT_PREFIX` | Repository discovery |
| `GIT_INDEX_FILE`, `GIT_OBJECT_DIRECTORY`, `GIT_ALTERNATE_OBJECT_DIRECTORIES` | Index and object store paths. With `GIT_OBJECT_DIRECTORY` set, commands that open the repository (including `fetch`, `pull` and `push`) read and write objects there instead of `.git/objects`, which stays visible only when listed in `GIT_ALTERNATE_OBJECT_DIRECTORIES`. The directory must exist; an empty value is an error, as in Git |
| `GIT_CONFIG`, `GIT_CONFIG_GLOBAL`, `GIT_CONFIG_SYSTEM`, `GIT_CONFIG_NOSYSTEM`, `GIT_CONFIG_COUNT`, `GIT_CONFIG_KEY_n`, `GIT_CONFIG_VALUE_n`, `GIT_CONFIG_PARAMETERS` | Config cascade |
| `HOME`, `XDG_CONFIG_HOME`, `USERPROFILE`, `USER`, `USERNAME` | Home and identity fallbacks |
| `GIT_AUTHOR_*`, `GIT_COMMITTER_*` | Author/committer name, email, and date overrides for new objects |
| `GIT_SSH`, `GIT_SSH_COMMAND` | SSH transport command (`GIT_SSH_COMMAND` overrides `core.sshCommand` and `GIT_SSH`; see Git precedence) |
| `GIT_HTTP_LOW_SPEED_LIMIT`, `GIT_HTTP_LOW_SPEED_TIME` | HTTP low-speed abort thresholds (override `http.lowSpeedLimit` / `http.lowSpeedTime` from config) |
| `http.timeout`, `http.lowSpeedLimit`, `http.lowSpeedTime` | Smart HTTP read timeouts in config (see [`fetch`](https://grit-scm.com/docs/fetch/index.md)): `http.timeout` caps the whole transfer (default 600s); low-speed settings abort when throughput stays below the limit for the configured window. Fetch and clone poll cancellation during these waits, not only between read chunks |
| `GIT_NOTES_REF`, `GIT_NOTES_DISPLAY_REF` | Notes ref selection |
| `GIT_ATTR_SOURCE` | Tree to read `.gitattributes` from |
| `GIT_NAMESPACE`, `GIT_REPLACE_REF_BASE`, `GIT_NO_REPLACE_OBJECTS` | Ref namespaces and replace refs |
| `GIT_OPTIONAL_LOCKS` | When set to `0`, `false`, `no`, or `off`, grit skips optional index writes during read-mostly commands such as `status` (same as `--no-optional-locks`). Unset means optional locks are allowed. |
| `GRIT_TRACE` | Grit operation spans to stderr (`1` / `true` / `yes`), or appended to a file when set to an absolute path; see [Debugging and tracing](https://grit-scm.com/docs/debugging/index.md) |
| `PATH` | Helper lookup (e.g. signing programs) |
| `TZ` | Local timezone for dates when no explicit offset is given |
| `GIT_EXEC_PATH`, `GIT_INSTALL_ROOT` | Git helper discovery (credentials) |

Grit does not read `GIT_TEST_*` variables from Git's test suite. Use repository config instead (`pack.writeReverseIndex`, `index.version`, …), [`InitOptions::with_init_filesystem`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.InitOptions.html#method.with_init_filesystem) with [`PrecomposeDetection::Always`](https://docs.rs/grit-lib/latest/grit_lib/config/init_filesystem/enum.PrecomposeDetection.html#variant.Always) for NFD/NFC init probes, and [`RepositoryOptions::with_reftable_write`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.with_reftable_write) to disable reftable auto-compaction in tests. For `safe.directory` behavior in tests, implement [`OwnershipCheck`](https://docs.rs/grit-lib/latest/grit_lib/ownership_check/trait.OwnershipCheck.html) and pass it through [`RepositoryOptions::with_ownership_check`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.with_ownership_check) (keep `GIT_TEST_ASSUME_DIFFERENT_OWNER` only when invoking the system `git` binary for cross-checks). `GIT_INDEX_VERSION` and `GIT_PRINT_SHA1_ELLIPSIS` are also ignored.

# https://grit-scm.com/docs/debugging/index.md

# Debugging and tracing

> Environment knobs for diagnosing grit behavior without changing CLI flags.

## Operation tracing (`GRIT_TRACE`)

Set **`GRIT_TRACE=1`** to print coarse **operation spans** from `grit-lib` to **stderr** while a command runs. Each line shows when a span opens and closes, with elapsed time on close. Spans cover repository open, config load, index read/write, status, revwalk setup, diffs, checkout, pack I/O, fetch negotiation, and push — not per-object work.

This is intended for local debugging and factory performance work. There is **no `--trace` flag**; only the environment variable is supported.

```console
$ GRIT_TRACE=1 grit status
grit.repository.open: new
grit.config.load: new
grit.config.load: close time.busy=147µs time.idle=4.82µs
grit.repository.open: close time.busy=297µs time.idle=26.2µs
grit.status.scan: new
grit.index.read: new
grit.status.scan: close time.busy=18.3ms time.idle=3.13µs
…
```

Set **`GRIT_TRACE`** to an **absolute path** instead to append the same tree to that file, like `GIT_TRACE2_PERF`. That keeps the trace when stderr is discarded or captured; the daily benchmark uses it to record where grit's time goes.

```console
$ GRIT_TRACE=/tmp/grit-trace.txt grit push > /dev/null 2>&1
```

Filter noise with the usual **`RUST_LOG`** / tracing env filter (for example `RUST_LOG=info`).

Library embedders can enable the same spans by building `grit-lib` with the Cargo feature **`tracing`**, installing any `tracing` subscriber, and calling the same code paths. `grit-lib` does not install a global subscriber.

## Network trace (existing)

Network fetch/push tracing still uses repository options and **`GRIT_NET_DEBUG`** (see the [network library guide](https://grit-scm.com/docs/library/network/index.md)). That path is separate from `GRIT_TRACE` operation spans.

# https://grit-scm.com/docs/scripting/index.md

# Scripting with grit

> Use --json and --filter to build scripts on top of grit.

With `--json`, a command prints exactly one JSON value on stdout, so you can pipe it straight into other tools. The shape of each command's outcome is documented on its command page and in the committed v1 JSON Schemas under [`/schemas/`](https://grit-scm.com/docs/schemas/index.md). Shared flag rules (`-n` as limit, long-only `--dry-run` on mutations, message and pathspec groups) are documented in [CLI conventions](https://grit-scm.com/docs/cli-conventions/index.md). `--filter` runs a [jq](https://jqlang.org) expression over that value without needing `jq` installed. Iterator-style filters — path `[]`, comma, `select`, and similar — always come back as a JSON array (`[]`, one element, or many). Singular filters such as `.branch` or `{branch, clean}` still emit one value; a missing field is `null`:

```console
$ grit status --json --filter '{branch, clean}'
{
  "branch": "main",
  "clean": true
}

$ grit log --json --filter '.commits[].subject'
[
  "Say hi",
  "Start the project"
]
```

## JSON contract

| Topic | Rule |
| --- | --- |
| **Success stdout** | Exactly one JSON value: the command outcome object. |
| **Failure stdout** | One object `{"error": "…"}` (see [error schema](https://grit-scm.com/docs/scripting/schemas/error/v1.json/index.md)). Some failures add structured fields such as `kind`; parsers should accept unknown keys. |
| **stderr** | Progress, auth hints, and human `error:` lines. Scripts should parse **stdout only** for the outcome when `--json` is set. |
| **`--filter`** | Requires `--json`. Runs jq-like logic on the outcome. Iterator filters always emit a JSON array; singular filters emit one value (`null` if absent). |
| **Exit codes** | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md). `0` success, `1` command failure, `2` usage (including bad `--hunks` ids and `diff --exit-code` errors), `128`/`129` for cases in the table. With `--json`, usage and most failures still print `{"error":"…"}` on stdout. |

Pass `--json` on every command you script. Plumbing commands ([`grit manager`](https://grit-scm.com/docs/manager/index.md), [`grit upload-pack`](https://grit-scm.com/docs/upload-pack/index.md), [`grit receive-pack`](https://grit-scm.com/docs/receive-pack/index.md)) speak wire protocols instead of JSON.

## Markdown output (`--markdown`)

For agents and tools that prefer readable text, pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) instead of `--json`. The same field contract applies: each command page links the v1 JSON Schema in **both** the JSON output and Markdown output sections so parsers know the stable keys even when stdout is Markdown.

Grit renders `--markdown` with these conventions (shared across commands):

- **Headings** — `##` sections group related output (for example “Staged changes”, “Untracked”).
- **Lists** — bullet lines for commits, paths, and simple enumerations; inline `` `short-oid` `` for object ids where helpful.
- **Tables** — pipe-separated rows for tabular data. Cell text escapes `\|`, `\n`, and `\r` so pipes inside branch names or paths do not break the table.
- **Fenced diffs** — unified patches use a `diff` code fence. If the patch body contains triple backticks, the opening and closing fence markers lengthen (four or more backticks) so the fence never terminates early.

`--markdown` and `--json` are mutually exclusive; `--filter` applies only with `--json`.

Color is used only when stdout is a terminal. Set `NO_COLOR` to turn it off.

For autonomous agents — non-interactive auth, where to find `llms.txt`, credentials, and the full automation contract — see the [Agent guide](https://grit-scm.com/docs/agents/index.md).

# https://grit-scm.com/docs/cli-conventions/index.md

# CLI conventions

> Shared rules for grit command paths, limits, dry-run, messages, pathspecs, and force flags — enforced by the cli_contract tests in grit-cli.

Grit's CLI is intentionally small, but the flags that appear on many commands follow one contract. The `grit-cli` crate encodes that contract in `cli_contract.rs`: every **leaf command path** in the clap tree is classified, and tests fail when a new command is added without a classification or when a rule is broken without a tracked exception.

This page states the rules in grit's own words. It does **not** change runtime behavior; later roadmap steps align commands that still have exceptions.

## Command kinds

Each leaf path (for example `stash.list`, `gc.repack`, or top-level `commit`) has exactly one kind:

| Kind | Meaning |
| --- | --- |
| **List** | Prints a bounded collection. Must expose `-n` as a **limit** (see below). |
| **Mutation** | Changes refs, the index, the working tree, config, or remote state. Must expose long-only `--dry-run` to preview, except where noted. |
| **Query** | Read-only inspection (diff, show, status, fsck, …). |
| **Plumbing** | Wire protocols or credential plumbing (`upload-pack`, `receive-pack`, `manager`). |
| **Generator** | Emits shell completion scripts or the agent skill (`completions`, `skill`). |

Parent commands that run without a subcommand (for example bare `grit stash` for push, `grit remote` for list) are separate leaf paths alongside explicit subcommands such as `stash.push`.

## Limit (`-n`)

On **every** command, `-n` always means **limit** — never “dry-run” or anything else. **List** commands must also expose that limit flag (see below).

- The short flag is `-n`.
- The long name is `--limit`, or `--max-count` when `--limit` is registered as a long alias (as on [`grit log`](https://grit-scm.com/docs/log/index.md) and [`grit revs`](https://grit-scm.com/docs/revs/index.md) today).
- No other argument on the same command may use `-n` for a different meaning.

## Dry-run (`--dry-run`)

On **mutation** commands, preview mode is long-only **`--dry-run`** (no `-n` shortcut). Mutations that support partial selection (`add`, `restore`, `commit` with hunks, …) use `--dry-run` the same way.

If you pass unknown `-n` on **`add`**, **`rm`**, **`mv`**, **`clean`**, or **`push`**, grit prints a usage hint pointing at **`--dry-run`** instead of clap’s misleading “pass `-n` as a value” tip.

**`grit clean`** is a mutation with different defaults: without `-f` / `--force`, it only prints what would be removed. Passing **`--force`** performs the deletion. That is the documented special case instead of an exception entry.

## Message input (`-m`, `-F`)

Commands classified with **takes message** accept:

- `-m` / `--message` for inline text, and
- `-F` / `--message-file` for a file path (`-` reads stdin),

with the two flags mutually exclusive. [`grit merge`](https://grit-scm.com/docs/merge/index.md) uses the shared message group for merge commits; history subcommands such as [`grit history reword`](https://grit-scm.com/docs/history/index.md) follow the same pattern where a message is optional or required per subcommand.

## Pathspecs (`--` paths)

Commands classified with **takes paths** accept:

- trailing `-- <paths>` arguments, plus
- `--pathspec-from-file` and `--pathspec-file-nul` (Git-compatible path lists),

shared via the same Rust argument group in the CLI. [`grit status`](https://grit-scm.com/docs/status/index.md), [`grit log`](https://grit-scm.com/docs/log/index.md), [`grit revs`](https://grit-scm.com/docs/revs/index.md), [`grit diff`](https://grit-scm.com/docs/diff/index.md), and [`grit show`](https://grit-scm.com/docs/show/index.md) use that group.

## Force (`-f`)

Every **`--force`** flag exposes short **`-f`**, unless the command page and `EXCEPTIONS` in `cli_contract.rs` document a deliberate deviation.

## Enforcement and exceptions

Two tests guard the contract:

- `cli_contract_conventions` — every leaf path is classified; clap flags match the rules unless listed in `EXCEPTIONS`.
- `cli_contract_exceptions_are_live` — each exception still describes a real violation; remove the row when the command is fixed.

Exception rows name an **owner** (a later plan step such as `s4 limit`, `s5 dry-run`, or a roadmap bucket like `workspace-extras`). When you fix a violation, delete its exception and rely on the convention test.

Adding a command requires a new row in `COMMAND_CONTRACTS` inside `grit-cli/src/cli_contract.rs`. CI fails with a message that names the path and the rule if you omit it.

## Three layers

Each `grit` command is split into three layers. Later roadmap steps move command logic into this shape; the render layer landed first.

| Layer | Location (today) | Responsibility |
| --- | --- | --- |
| **Parse** | `grit-cli/src/main.rs` (per-command args land in step 2) | Clap parsing, global flags, revision/pathspec helpers. Produces plain Rust input structs — no I/O. |
| **Outcome** | Command modules under `grit-cli/src/commands/` and small `*_args.rs` helpers | Open `grit_lib::repo::Repository` handles, call library APIs, map errors. Returns a typed **outcome** (structs with `Serialize` for `--json`). |
| **Render** | `grit-cli/src/render/` | Turn outcomes into human text, Markdown, or filtered JSON. **No** `Repository`, `context`, or `commands::` imports (see `render_layer_is_repository_free` in `grit-cli`). |

**JSON DTO rule:** serde shapes on outcomes stay in the CLI. They are `From<&LibOutcome>` field mappings (or thin wrappers), not new public `grit-lib` types. The committed v1 JSON schemas remain the contract.

`make cli-layer-ratchet-check` tracks line counts for `render/`, `args/`, `dispatch` (`main.rs`), and the rest of `grit-cli/src`. Non-render layers may not grow without updating `grit-cli/layer-ratchet.toml`.

## See also

- [Scripting with grit](https://grit-scm.com/docs/scripting/index.md) — `--json`, exit codes, and stdout discipline.
- [Agent guide](https://grit-scm.com/docs/agents/index.md) — non-interactive use and schema links.
- [Global options](https://grit-scm.com/docs/global-options/index.md) — `--json`, `--markdown`, `--filter`, `--threads`, and the repository options `-C`, `-c`, `--git-dir`, `--work-tree`.

# https://grit-scm.com/docs/exit-codes/index.md

# Exit codes

> Process exit status for grit commands and structured JSON error kinds.

Grit uses a small set of exit codes. Command-specific yes/no checks (for example `grit diff --exit-code`) reuse **failure** (1) when the answer is “no”. See [Scripting with grit](https://grit-scm.com/docs/scripting/index.md) and the [Agent guide](https://grit-scm.com/docs/agents/index.md) for `--json` behavior.

## Exit status

| Slug | Code | Meaning |
| --- | ---: | --- |
| `success` | 0 | Command completed successfully (including some checks that answer “yes”). |
| `failure` | 1 | Command failed, or a yes/no check answered “no” (`diff --exit-code`, `merge --check`, `pick --check`, `revert --check`, `pull --check`, `merge-base --is-ancestor`, `fsck`, `ignore check`, `tag --verify`, conflicts after `merge` / `pick` / `revert` / `rebase`, rejected `push`, and similar). With `--json`, stdout is usually `{"error":"…"}` or a full outcome object when the failure is part of the result (for example rejected push). |
| `usage` | 2 | Invalid flags or arguments. With `--json`, stdout is still `{"error":"…"}` (clap usage errors and subcommand usage such as `grit branch`). Hunk selection mistakes (`add` / `commit` / `stash` / `restore` with unknown or stale `--hunks` ids) also exit 2. `grit diff --exit-code` / `--quiet` uses 2 when diff itself errors. |
| `needs_decision` | 3 | [`grit push`](https://grit-scm.com/docs/push/index.md) or [`grit sync`](https://grit-scm.com/docs/sync/index.md) did its work, but another member's head of a [shared branch](https://grit-scm.com/docs/share/index.md) diverged from yours in a way someone has to decide about. The output (`shared[].heads[].divergence` in `--json`) names the scenario and what each side did; nothing is lost, since the server keeps every head. Scripts and agents should read the report rather than retry. |
| `remote_unreadable` | 128 | `clone`, `fetch`, `pull`, `push`, or `remote refs` could not reach or read the remote: a missing repository path, a DNS, refused-connection, TLS, or timeout failure, an HTTP error status, or a transport that never spoke Git. With `--json`, stdout is `{"error":"…","kind":"remote_unreadable"}`. Rejected pushes and authentication failures are not in this class (they exit 1). |
| `missing_prerequisite` | 128 | `grit bundle unbundle` when the repository lacks prerequisite commits. |
| `refused_not_ff` | 128 | `grit merge --ff-only` or `grit pull --ff-only` when a fast-forward is not possible. |
| `invalid_commit_filter` | 129 | Invalid `--author`, `--grep`, or pickaxe pattern on `grit log`, `grit revs`, or related commands (`kind`: `invalid_pattern`). |
| `interrupted` | 130 | `grit clone`, `grit fetch`, or `grit push` stopped by Ctrl-C, `SIGTERM`, or `SIGHUP` on Unix (or Ctrl-Break on Windows). Partial work is rolled back (for example an incomplete clone directory, fetch temp pack, or push receive quarantine on the remote), so the same command can be run again. With `--json`, stdout is `{"error":"operation cancelled"}`. |
| `custom` | *varies* | Passthrough from `grit hooks run` (hook exit code) or `grit rebase --exec` when a command fails. |

## Structured error kinds (`kind` in JSON)

These values appear in the `kind` field of structured `--json` errors ([error schema](https://grit-scm.com/docs/exit-codes/schemas/error/v1.json/index.md)). Plain failures omit `kind`.

When grit knows what to do next, the object also has a **`hint`** naming the command to run, and human output prints the same text on a `hint:` line after the `error:` line (Markdown output adds a `**Hint:**` paragraph). Failures about specific files list them in **`paths`** (or `conflicts` / `would_overwrite.paths`).

```console
$ grit push
error: no remote to push to
hint: add one with `grit remote add origin <url>`, or push to a URL with `grit push <url> <branch>`
$ grit push --json
{"error":"no remote to push to","hint":"add one with `grit remote add origin <url>`, or push to a URL with `grit push <url> <branch>`","kind":"no_remote"}
```

| Slug | When |
| --- | --- |
| `conflict` | Merge, pick, rebase, or similar would introduce conflicts (`conflicts`, optional `commit`). A `grit history` rewrite or `grit rebase` that fails replaying another branch it would move also sets `refs` (full branch names) and a `hint` to pass `--update-refs head`. |
| `hash_collision` | Refusing to store content that triggers SHA-1 collision detection (`oid`). |
| `would_overwrite` | Checkout, switch, merge, or pull would overwrite local or untracked files (`would_overwrite.reason`, `would_overwrite.paths`). The hint suggests `grit commit` or `grit stash` for local changes. |
| `operation_in_progress` | `grit switch` refused while a merge, rebase, pick or revert is paused (grit's or one `git` started); finish or abort it first. |
| `invalid_pattern` | Invalid filter pattern (exit 129). |
| `usage` | Subcommand usage mistake (exit 2), e.g. `grit branch` flag combinations. |
| `incompatible_flags` | Flags that cannot be combined (often `--json` with human-only options). |
| `lock_held` | A lock file such as `.git/index.lock` or `refs/heads/main.lock` already exists (exit 1). The lock file is left alone on ordinary commands. Staging and committing stop before changing the index or recording a commit; retry after the holder finishes. `lock.path` names the lock, and `lock.holder.pid` / `lock.holder.running` are present when grit wrote a pid sidecar (default for grit-owned index locks; set `core.lockfilePid=false` to opt out). When `lock.holder.running` is `false`, the lock is stale; interrupted rewrite recovery removes it automatically on the next status or abort. |
| `index_locked` | **Deprecated** alias of `lock_held`, emitted by v0.5.21 for a held index lock. grit no longer emits it; it stays in the [error schema](https://grit-scm.com/docs/exit-codes/schemas/error/v1.json/index.md) for one release so v0.5.21 output still validates, then it is removed. Match `lock_held` instead. |
| `branch_already_exists` | Create branch when the name already exists. |
| `branch_not_found` | Branch name not found. `grit switch` hints at `grit branch` and `grit switch -c <name>`. |
| `no_previous_branch` | `grit switch -` when HEAD has no earlier checkout in the reflog. |
| `branch_invalid_name` | Invalid branch name. |
| `branch_not_fully_merged` | Delete refused: not fully merged. |
| `branch_checked_out` | Branch checked out in this or another worktree. |
| `branch_no_commits` | No commits in repository. |
| `branch_invalid_start_point` | Invalid `--start` / start point. |
| `branch_upstream_not_tracking` | Upstream is not a tracking branch. |
| `branch_no_upstream` | No upstream configured. `grit pull` hints at `grit pull origin <branch>` and `grit push -u origin <branch>`. |
| `branch_error` | Other branch operation failure. |
| `hook_failed` | A hook such as `pre-commit` exited non-zero (`hook.name`, `hook.status`, and the hook's captured `hook.stdout` / `hook.stderr`). |
| `revision_not_found` | A branch, tag, commit id or revision expression names nothing. Any command that resolves a revision may emit this `kind` when the spec names nothing (not only `grit merge`). |
| `remote_unreadable` | The remote could not be reached or read (exit 128); see the exit status table above. When the server answers `404`, the hint asks you to check the URL. |
| `no_remote` | `grit push` with no remote named, no push remote for the branch, and no `origin`. Hint: `grit remote add origin <url>`. |
| `remote_not_found` | A remote name that is not configured (`grit push origin main`, `grit pull`, `grit fetch nosuch`). Hint: `grit remote add <name> <url>`. |
| `remote_no_url` | The remote is configured but has no URL. Hint: `grit remote set-url <name> <url>`. |
| `auth_required` | An HTTPS remote wants credentials and neither a credential helper nor an askpass program (`GIT_ASKPASS`, `core.askPass`, `SSH_ASKPASS`) supplied them. The `error` names the repository URL; the hint is `grit auth` for github.com, otherwise a `credential.helper` or `GIT_ASKPASS`. |
| `auth_rejected` | The remote refused the credentials that were sent. |
| `unmerged_paths` | `grit merge --continue` while conflicts are unresolved, or resolved but not staged with `commit.autoStage=false` (`paths`). The hint names the files and `grit merge --continue` / `grit merge --abort` (or `grit add`). Also a plain or `--staged` `grit restore` of a conflicted path; the hint names `grit restore --ours` / `--theirs` / `--merge` and `grit add`. Also `grit add` / `grit commit` when a file still has conflict markers after its conflict stages were dropped, for example by `git restore --staged` after a merge, pick or stash pop (`paths`); the hint says to edit out the markers. |
| `dirty_worktree` | Staged or unstaged changes block a merge, pick, revert, switch or `rebase --exec` (`paths`). Hint: `grit commit` or `grit stash`. |
| `worktree_path_io` | Checkout, stash, add, diff, or reset could not read or replace a worktree file (`paths`, often one path). Typical causes: another program has the file open, or a permission problem. The hint to close the program and retry appears only when the operating system reports the file as in use. |
| `checkout_incomplete` | A switch or checkout stopped part way (cancelled with Ctrl+C, or failed) and could not put some work-tree paths back (`paths`). `HEAD` and the index did not move; only the listed paths differ. Hint: `grit reset --hard` and `grit clean -f`. |
| `clone_checkout_failed` | `grit clone` downloaded every object and set up the refs, but checking out the work tree failed (exit 1), usually because a partial clone could not fetch its missing blobs. The repository is kept, as `git clone` keeps it; `clone_checkout` has `path`, `commit`, `missing_object` (when a promised object was missing) and `failed_remotes` (`remote`, `error`). Hint: run `grit reset --hard` in the clone to finish the checkout. |
| `git_dir_path_io` | Commit, gc, or ref update could not write under `.git/` (`paths`, often one path such as `.git/objects` or `.git/refs/heads/main`). Typical causes: read-only or root-owned `.git` metadata, or another thread/process updating the same index or ref (Windows often reports this as the file being in use). Hint: for permission problems check `ls -l .git` and fix ownership; when the message says the file is in use, retry after the other updater finishes. |
| `nothing_staged` | `grit commit` with `commit.autoStage=false` or `--staged` while the index matches `HEAD` but the work tree has unstaged or untracked paths. Hint: `grit add` or `grit commit -- <path>`. |
| `nothing_to_commit` | `grit commit` on a genuinely clean tree (or after auto-staging cancels out against `HEAD`). |
| `not_a_repository` | Command run outside any Git repository (or parent directory). |
| `commit_message_required` | `grit commit` without `-m`, `-F`, amend/reuse, or a pending merge message. |
| `empty_commit_message` | `grit commit -m ''`, empty `-F`, or a hook that cleared the message. |
| `identity_unknown` | Author or committer identity could not be resolved (`hint` names `grit config --global user.name` / `user.email`). |
| `tag_already_exists` | Create tag when the name already exists (hint mentions `--force`). |
| `tag_not_found` | Delete or verify a tag when `refs/tags/<name>` does not exist. |
| `no_operation_in_progress` | `merge --abort`, `rebase --continue`, `pick --continue`, or similar when nothing is paused; the `error` text names the operation. |
| `pathspec_no_match` | `grit add`, `rm`, `restore`, `commit -- <paths>`, or stash path selection with no matching files. |
| `stash_not_found` | `grit stash pop` / `apply` / `drop` with an empty stash or an invalid index (`hint` for empty stash). |
| `path_not_found` | `grit blame` (or similar) when the path is absent from the named revision and not on disk. |
| `gitbutler_workspace` | `grit commit` while `HEAD` is on a GitButler workspace (`gitbutler/workspace`, topped by GitButler's workspace commit). GitButler rewrites that branch, so a commit there would be lost. Hint: commit with `but commit`, or switch to a branch first. |
| `unsupported_object_store` | The operation needs the files-backed object store (loose objects and packs under `objects/`), but the repository's primary store is custom (exit 1). `operation` is the refused operation's stable name, such as `prune` (a custom store that cannot delete objects), `repack`, `commit_graph_write` or `partial_fetch`; the [object stores guide](https://grit-scm.com/docs/library/object-stores/index.md#what-works-with-a-custom-primary) lists every name. `grit` itself always opens the files backend, so this comes from repositories opened through `grit-lib` with a custom store. |

# https://grit-scm.com/docs/agents/index.md

# Agent guide

> Run grit from scripts and autonomous agents — JSON output, exit codes, non-interactive use, credentials, and where to read the docs.

This page is for programs and agents that drive [`grit`](https://grit-scm.com/docs/install/index.md) in automation. It describes **existing** CLI behavior only. Machine-readable **v1 JSON Schemas** for each command's `--json` success object are published at `/schemas/<command>/v1.json` (see the [JSON schemas](https://grit-scm.com/docs/schemas/index.md) index). Field-level tables on each command page remain the human-oriented reference; this guide covers the shared contract. Cross-command flag rules (limits, dry-run, messages, pathspecs) are summarized in [CLI conventions](https://grit-scm.com/docs/cli-conventions/index.md).

Examples below were captured on 2026-10-08 with `grit` built from this repository (`cargo build --release -p grit-cli`), in a temporary repository on branch `main`, unless noted.

## Prefer `--json` (and `--filter`)

Pass **`--json`** on every command when something other than a human reads the result. In that mode:

- **stdout** carries exactly **one** JSON value: the command's outcome object on success, or `{"error": "…"}` on failure.
- **stderr** carries progress lines, auth prompts, and human-style `error: …` diagnostics. Parsers should read **stdout only** for the outcome.
- The process still exits non-zero on failure, so you can branch on the exit code **or** the presence of an `error` key.

Use **`--filter`** with a [jq](https://jqlang.org)-like expression to narrow the JSON without piping through `jq`. It requires `--json`. Iterator-style filters (for example `.commits[].oid` or `.staged[].path`) always emit a JSON array, including `[]` when nothing matches. Singular filters such as `.branch` or `{branch, clean}` emit one value; a missing field is `null`.

```console
$ grit status --json --filter '{branch, clean}'
{
  "branch": "main",
  "clean": false
}

$ grit log --json --filter '.commits[].subject'
[
  "Say hi",
  "Start the project"
]
```

Plain `grit` with no subcommand is the same as [`grit status`](https://grit-scm.com/docs/status/index.md); `--json` works there too:

```console
$ grit --json --filter '{branch, clean}'
{
  "branch": "main",
  "clean": false
}
```

See [Scripting with grit](https://grit-scm.com/docs/scripting/index.md) for more `--filter` patterns. Per-command keys are documented under [The grit CLI](https://grit-scm.com/docs/global-options/index.md) command pages.

## JSON schema versioning

Each command path has versioned schema files under `content/schemas/`: `<command>.vN.json` (dotted paths for subcommands, such as `stash.list.v1.json`). The live contract is whatever **`current`** version the per-command table in `grit-cli/src/json_schema.rs` lists; older **`frozen`** versions stay on disk at stable `$id` URLs and are never regenerated.

**Additive on the live version (no bump):** new optional properties, new enum variants, new `definitions`, adding an `enum` to a former free-form string (for example structured `kind`), or widening nullability.

**Breaking (requires publishing vN+1):** property removed or renamed, JSON type narrowed, a property newly required, enum variant removed, `additionalProperties: false` where extra keys were previously allowed, or nullability removed from a field.

CI runs three gates:

- `json_schemas_are_current` — generated live schemas match committed bytes (or run update mode below).
- `json_schema_backward_compatible` — every committed schema file (90 total) stays backward compatible: live files vs freshly generated types; frozen older files are checked against themselves so they never drift silently.
- `json_snapshots_match_schemas` — golden `--json` snapshots validate against the matching schema.

Regenerate live schemas after intentional **additive** contract changes:

```bash
GRIT_UPDATE_SCHEMAS=1 cargo test json_schemas_are_current -p grit-cli -- --nocapture
```

Update mode refuses to overwrite the live file when the diff would be **breaking**; the test output lists each breaking JSON path and tells you to publish `vN+1` (add `<command>.v{N+1}.json`, bump `current`, append `N` to `frozen`). Frozen files are never touched by update mode.

## Error object shape

Schema: [v1](https://grit-scm.com/docs/agents/schemas/error/v1.json/index.md)

On failure with `--json`, stdout is a single object with an **`error`** string (the same message a human sees after `error:` on stderr). Some failures add a **`kind`** and optional fields (for example merge/pick **conflicts**, **`would_overwrite`** with `reason` and `paths` on switch refusal, **`lock_held`** with a **`lock`** object (`path`, and `holder.pid` / `holder.running` when recorded) when an index or low-level loose-ref write encounters a held lock, or **`hash_collision`** with an **`oid`** digest when object ingestion detects an SHA-1 chosen-prefix collision); see the error schema for the plain vs structured union. When grit knows the next step, a **`hint`** names the command to run (`grit remote add origin <url>`, `grit push -u origin main`, `grit auth`, `grit merge --continue`, …), and **`paths`** lists the files an `unmerged_paths` or `dirty_worktree` failure is about. Branch on `kind`, not on the `error` text.

```console
$ grit commit --json
{"error":"provide a commit message, e.g. grit commit \"what changed\""}
```

If `--filter` is set, it runs on `{"error": "…"}` like any other JSON value. A bad filter expression also yields `{"error": "…"}` on stdout:

```console
$ grit status --json --filter 'invalid!!!'
{"error":"invalid filter \"invalid!!!\": [(File { code: \"invalid!!!\", path: () }, Parse([(Nothing, \"!!!\")]))]"}
```

In **human** mode, errors print to **stderr** and stdout stays empty:

```console
$ grit commit
error: provide a commit message, e.g. grit commit "what changed"
```

## Exit codes

| Code | Meaning |
| --- | --- |
| **0** | Success (including some jq filters that evaluate to `null` when a path is missing). |
| **1** | Command failed (missing repo, rejected push, validation error, and similar). With `--json`, stdout still contains `{"error": "…"}`. |
| **2** | Usage error (unknown option, invalid subcommand flags, bad `--hunks` ids, or `diff --exit-code` when diff fails). Clap still prints help to stderr. With **`--json`**, stdout is `{"error":"…"}` even for clap usage errors. Without `--json`, usage errors may have empty stdout. |
| **128** | Remote unreadable (`clone`, `fetch`, `pull`, `push`, `remote refs`; `kind: remote_unreadable`), bundle missing prerequisites, or `merge --ff-only` / `pull --ff-only` refused. |
| **129** | Invalid `--author` / `--grep` / pickaxe pattern (`kind`: `invalid_pattern`). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for the full table and structured `kind` values.

```console
$ grit --nope
error: unexpected argument '--nope' found

Usage: grit [OPTIONS] [COMMAND]

For more information, try '--help'.
```

```console
$ grit --json --nope
{"error":"unexpected argument '--nope' found"}
```

```console
$ grit status --filter '.branch'
error: --filter requires --json
```

[`grit push`](https://grit-scm.com/docs/push/index.md) can exit **1** even after printing a full JSON outcome when a ref was rejected (same idea as Git: the outcome is reported, but the operation failed).

## Color and terminal detection

Human output uses ANSI color only when **stdout is a terminal**, the environment supports ANSI (`grit_lib::porcelain::terminal::ansi_supported()`), and **`NO_COLOR` is unset** ([no-color.org](https://no-color.org)). Piped or redirected stdout is plain text; set `NO_COLOR=1` to force plain text on a TTY.

JSON mode never depends on color; always pass `--json` for machines.

## Markdown output (`--markdown`)

When a human-readable transcript is easier to consume than raw JSON, pass **`--markdown`**. It is mutually exclusive with `--json`; use JSON for strict parsing and Markdown for agent-oriented prose.

Each command page documents real `--markdown` stdout under **Markdown output** and links the same v1 JSON Schema as the JSON section (for example `Schema: [v1](https://grit-scm.com/docs/agents/schemas/status/v1.json/index.md)`). Treat that schema as the stable field contract even when stdout is Markdown.

Grit formats `--markdown` consistently:

| Convention | Behavior |
| --- | --- |
| **Headings** | `##` titles introduce sections (status groups, file lists, subcommand results). |
| **Bullets** | `-` lines for commits, paths, and simple lists; short oids often appear in backticks. |
| **Tables** | Markdown tables for rows of refs, remotes, worktrees, and similar; `\|`, `\n`, and `\r` inside cells are escaped. |
| **Diff fences** | One fenced `diff` block per changed file when a command emits patches; fence backticks lengthen if the patch text contains ``` so the fence stays unambiguous. |

Do not combine `--markdown` with `--filter`. See [Scripting with grit](https://grit-scm.com/docs/scripting/index.md) for exit codes, filters, and the shared JSON error object.

## Stay non-interactive

`grit` does **not** open an external editor for commit messages. [`grit commit`](https://grit-scm.com/docs/commit/index.md) requires a message on the command line (positional or `-m`); there is no `$GIT_EDITOR` path.

Commands and flows that can **block on a person**:

| Area | Behavior | How to avoid blocking |
| --- | --- | --- |
| [`grit auth`](https://grit-scm.com/docs/auth/index.md) | OAuth device flow: instructions on stderr, then polls GitHub until you authorize in a browser. | Run `grit auth` once in an interactive session before automation. Store the token via `credential.helper` (see below). |
| [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) / [`grit push`](https://grit-scm.com/docs/push/index.md) / [`grit pull`](https://grit-scm.com/docs/pull/index.md) | On HTTPS `github.com` auth failure, if **stdin is a TTY**, grit may ask `Sign in to GitHub now? [Y/n]` and run the device flow. | Use a stored token from `grit auth`, or ensure stdin is not a TTY so grit prints a hint and exits without prompting. |
| [`grit clone`](https://grit-scm.com/docs/clone/index.md) / [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) / [`grit pull`](https://grit-scm.com/docs/pull/index.md) / [`grit push`](https://grit-scm.com/docs/push/index.md) over **SSH** | Grit runs `ssh` with protocol stdin/stdout piped but **stderr inherited**, so the SSH child can still talk to `/dev/tty` (host-key confirmation, passphrase prompts, `ssh-askpass`, and similar). `--json` does not disable this. | Preconfigure keys and known hosts; for unattended jobs set `GIT_SSH_COMMAND='ssh -o BatchMode=yes'` so SSH fails fast instead of prompting. Grit resolves the ssh command like Git: `GIT_SSH_COMMAND`, then `core.sshCommand` from config, then `GIT_SSH`, then `ssh` on `PATH`. |
| [`grit update`](https://grit-scm.com/docs/update/index.md) | Runs the release installer (`curl \| sh` on Unix). | Do not invoke in unattended jobs unless you intend to upgrade the binary. |

There is no global `--yes` flag. For commits, always pass `-m` / a message argument.

[`grit auth logout`](https://grit-scm.com/docs/auth/index.md) is non-interactive and reports whether a helper had a token to erase:

```console
$ grit auth logout --json
{
  "logged_out": false,
  "host": "github.com"
}
```

### Plumbing commands (not JSON)

These speak binary or line protocols on stdin/stdout and have **no** `--json` mode: [`grit manager`](https://grit-scm.com/docs/manager/index.md), [`grit upload-pack`](https://grit-scm.com/docs/upload-pack/index.md), [`grit receive-pack`](https://grit-scm.com/docs/receive-pack/index.md). Agents should not wrap them as JSON commands.

`-v` / `--version` (or `-V`) prints a version string and does not emit JSON even if `--json` is passed:

```console
$ grit --json --version
grit 0.5.1
```

## Credentials (HTTPS)

For `https://github.com` remotes, sign in once with [`grit auth`](https://grit-scm.com/docs/auth/index.md). Grit uses GitHub's device flow, then stores an access token through your configured **`credential.helper`** (same mechanism as Git). Override the OAuth app id with `GRIT_GITHUB_CLIENT_ID` or `grit config --global grit.githubClientId …`.

Sign out with `grit auth logout`. You need a credential helper configured (for example `grit config --global credential.helper store` on Linux — see the [`grit auth`](https://grit-scm.com/docs/auth/index.md) page).

The same helpers serve any HTTPS host, not only GitHub. For GitLab, Gitea, Bitbucket or any other host, save a user name and token once with `grit auth <url> --username <user> --token <token>`: it stores them with your credential helper (setting one up if needed) for that host, without contacting it. `grit auth <url>` without `--username` signs in only to GitHub and `grit serve` hosts, and says so for anything else. In CI, a host-level line such as `https://ci:TOKEN@git.example.com` in the store file (`~/.git-credentials`) authenticates `grit clone`, `fetch` and `push` for every repository on that host, exactly as it does for Git.

When no helper has the credentials, grit asks an **askpass** program for them, like Git: `GIT_ASKPASS`, then `core.askPass`, then `SSH_ASKPASS` (the first one set wins; an empty value turns askpass off). The program gets one prompt as its argument, `Username for 'https://git.example.com': ` and then `Password for 'https://ci@git.example.com': `, and prints the answer on stdout. That is how most CI systems inject a token:

```bash
cat > askpass.sh <<'SH'
#!/bin/sh
case "$1" in Username*) echo ci;; *) echo "$CI_TOKEN";; esac
SH
chmod +x askpass.sh
GIT_ASKPASS=$PWD/askpass.sh grit clone https://git.example.com/team/app.git
```

A credential an askpass program supplies is saved with your credential helper once the server accepts it. Grit never prompts on the terminal, even when one is attached: when neither a helper nor an askpass program has the credentials, the command fails with `kind` `auth_required`, and the hint names the helpers that were asked and `grit auth <url> --username … --token …`. Set `credential.interactive=never` to skip askpass as well. When the server refuses a stored credential (an expired or rotated token), the error is `auth_rejected` and the helper erases the entry, as Git does; store the new token the same way. A `user:password@` in the URL is sent as it is; if the server refuses it the error is also `auth_rejected`.

SSH remotes do not use the GitHub device-flow token; they can still block on SSH prompts (see the SSH row above).

## Documentation for agents

| Resource | URL / path | Use |
| --- | --- | --- |
| **Agent skill** | [`grit skill`](https://grit-scm.com/docs/skill/index.md) | A `SKILL.md` for coding agents, printed by the installed binary: `grit skill > .agents/skills/grit/SKILL.md`. Includes CI-tested **Recipes** (precise commit, merge conflicts, rebase + lease push, fetch PR, shallow clone) and links to [CLI conventions](https://grit-scm.com/docs/cli-conventions/index.md). |
| **llms.txt** | [grit-scm.com/llms.txt](https://grit-scm.com/llms.txt) | Curated index of every docs page (llmstxt.org format). |
| **llms-full.txt** | [grit-scm.com/llms-full.txt](https://grit-scm.com/llms-full.txt) | Full text of all docs Markdown twins in site order. |
| **Markdown twin** | Same URL as HTML but `index.md` instead of `index.html` (e.g. [status/index.md](https://grit-scm.com/docs/status/index.md)) | One page per command or guide; linked from HTML as "Markdown". |
| **Command JSON fields** | Under [The grit CLI](https://grit-scm.com/docs/global-options/index.md) | Each command page lists real `--json` examples and field tables. |
| **grit-lib API** | [docs.rs/grit-lib](https://docs.rs/grit-lib) | Rust library reference when embedding grit in your own binary. |
| **Library guide** | [Library guide](https://grit-scm.com/docs/library/index.md) | Narrative Rust workflows on top of `grit-lib`. |

[llms.txt](https://grit-scm.com/llms.txt), [llms-full.txt](https://grit-scm.com/llms-full.txt), the two one-file bundles ([grit-cli.md](https://grit-scm.com/docs/grit-cli.md) and [grit-lib.md](https://grit-scm.com/docs/grit-lib.md)) and every Markdown twin are built from the same sources as the HTML pages on each deploy, so they never drift from the docs.

## See also

- [Scripting with grit](https://grit-scm.com/docs/scripting/index.md) — `--json`, `--filter`, and exit codes in brief
- [Global options](https://grit-scm.com/docs/global-options/index.md) — flags shared by every command
- [Docs overview](https://grit-scm.com/docs/index.md) — how the site is organized

# https://grit-scm.com/docs/schemas/index.md

# JSON schemas

> Versioned v1 JSON Schemas for every grit command's --json success object.

Every command that prints a JSON outcome object with `--json` has a versioned JSON Schema served at a stable URL (`https://grit-scm.com/schemas/<command>/vN.json`). Most commands are still on **v1**; `clone` publishes **v3** while **v1** and **v2** remain frozen; `config`, `merge`, `mv`, `pull`, `pick`, `remote` (and several `remote.*` subcommands), `switch`, `tag`, and `worktree.prune` publish **v2** while **v1** remains frozen for older clients.

See the [Agent guide](https://grit-scm.com/docs/agents/index.md#json-schema-versioning) for additive vs breaking rules, the CI backward-compatibility gate, and how to regenerate live files under `content/schemas/` with `GRIT_UPDATE_SCHEMAS=1`.

Plain command failures with `--json` validate against the shared [error schema](https://grit-scm.com/docs/schemas/schemas/error/v1.json/index.md).

## Command schemas

| Command path | Schema |
| --- | --- |
| `add` | [v2](https://grit-scm.com/docs/schemas/schemas/add/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/add/v1.json/index.md) |
| `auth` | [v1](https://grit-scm.com/docs/schemas/schemas/auth/v1.json/index.md) |
| `auth.logout` | [v1](https://grit-scm.com/docs/schemas/schemas/auth.logout/v1.json/index.md) |
| `blame` | [v1](https://grit-scm.com/docs/schemas/schemas/blame/v1.json/index.md) |
| `branch` | [v1](https://grit-scm.com/docs/schemas/schemas/branch/v1.json/index.md) |
| `bundle.create` | [v1](https://grit-scm.com/docs/schemas/schemas/bundle.create/v1.json/index.md) |
| `bundle.list` | [v1](https://grit-scm.com/docs/schemas/schemas/bundle.list/v1.json/index.md) |
| `bundle.unbundle` | [v1](https://grit-scm.com/docs/schemas/schemas/bundle.unbundle/v1.json/index.md) |
| `bundle.verify` | [v1](https://grit-scm.com/docs/schemas/schemas/bundle.verify/v1.json/index.md) |
| `cat` | [v1](https://grit-scm.com/docs/schemas/schemas/cat/v1.json/index.md) |
| `clean` | [v1](https://grit-scm.com/docs/schemas/schemas/clean/v1.json/index.md) |
| `clone` | [v3](https://grit-scm.com/docs/schemas/schemas/clone/v3.json/index.md), [v2](https://grit-scm.com/docs/schemas/schemas/clone/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/clone/v1.json/index.md) |
| `commit` | [v1](https://grit-scm.com/docs/schemas/schemas/commit/v1.json/index.md) |
| `config` | [v2](https://grit-scm.com/docs/schemas/schemas/config/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/config/v1.json/index.md) |
| `diff` | [v1](https://grit-scm.com/docs/schemas/schemas/diff/v1.json/index.md) |
| `error` | [v1](https://grit-scm.com/docs/schemas/schemas/error/v1.json/index.md) |
| `fetch` | [v1](https://grit-scm.com/docs/schemas/schemas/fetch/v1.json/index.md) |
| `fetch.all` | [v1](https://grit-scm.com/docs/schemas/schemas/fetch.all/v1.json/index.md) |
| `fsck` | [v1](https://grit-scm.com/docs/schemas/schemas/fsck/v1.json/index.md) |
| `gc` | [v1](https://grit-scm.com/docs/schemas/schemas/gc/v1.json/index.md) |
| `gc.commit-graph` | [v1](https://grit-scm.com/docs/schemas/schemas/gc.commit-graph/v1.json/index.md) |
| `gc.drop-large-blobs` | [v1](https://grit-scm.com/docs/schemas/schemas/gc.drop-large-blobs/v1.json/index.md) |
| `gc.midx` | [v1](https://grit-scm.com/docs/schemas/schemas/gc.midx/v1.json/index.md) |
| `gc.pack-refs` | [v1](https://grit-scm.com/docs/schemas/schemas/gc.pack-refs/v1.json/index.md) |
| `gc.offload` | [v1](https://grit-scm.com/docs/schemas/schemas/gc.offload/v1.json/index.md) |
| `gc.prune` | [v1](https://grit-scm.com/docs/schemas/schemas/gc.prune/v1.json/index.md) |
| `gc.repack` | [v1](https://grit-scm.com/docs/schemas/schemas/gc.repack/v1.json/index.md) |
| `history.absorb` | [v1](https://grit-scm.com/docs/schemas/schemas/history.absorb/v1.json/index.md) |
| `history.drop` | [v1](https://grit-scm.com/docs/schemas/schemas/history.drop/v1.json/index.md) |
| `history.fixup` | [v1](https://grit-scm.com/docs/schemas/schemas/history.fixup/v1.json/index.md) |
| `history.move` | [v1](https://grit-scm.com/docs/schemas/schemas/history.move/v1.json/index.md) |
| `history.rebase` | [v1](https://grit-scm.com/docs/schemas/schemas/history.rebase/v1.json/index.md) |
| `history.reword` | [v1](https://grit-scm.com/docs/schemas/schemas/history.reword/v1.json/index.md) |
| `history.split` | [v1](https://grit-scm.com/docs/schemas/schemas/history.split/v1.json/index.md) |
| `history.squash` | [v1](https://grit-scm.com/docs/schemas/schemas/history.squash/v1.json/index.md) |
| `history.undo` | [v1](https://grit-scm.com/docs/schemas/schemas/history.undo/v1.json/index.md) |
| `hooks` | [v1](https://grit-scm.com/docs/schemas/schemas/hooks/v1.json/index.md) |
| `hooks.list` | [v1](https://grit-scm.com/docs/schemas/schemas/hooks.list/v1.json/index.md) |
| `hooks.run` | [v1](https://grit-scm.com/docs/schemas/schemas/hooks.run/v1.json/index.md) |
| `ignore.check` | [v1](https://grit-scm.com/docs/schemas/schemas/ignore.check/v1.json/index.md) |
| `init` | [v1](https://grit-scm.com/docs/schemas/schemas/init/v1.json/index.md) |
| `log` | [v1](https://grit-scm.com/docs/schemas/schemas/log/v1.json/index.md) |
| `merge` | [v2](https://grit-scm.com/docs/schemas/schemas/merge/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/merge/v1.json/index.md) |
| `merge-base` | [v1](https://grit-scm.com/docs/schemas/schemas/merge-base/v1.json/index.md) |
| `mv` | [v2](https://grit-scm.com/docs/schemas/schemas/mv/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/mv/v1.json/index.md) |
| `notes` | [v1](https://grit-scm.com/docs/schemas/schemas/notes/v1.json/index.md) |
| `notes.add` | [v1](https://grit-scm.com/docs/schemas/schemas/notes.add/v1.json/index.md) |
| `notes.list` | [v1](https://grit-scm.com/docs/schemas/schemas/notes.list/v1.json/index.md) |
| `notes.remove` | [v1](https://grit-scm.com/docs/schemas/schemas/notes.remove/v1.json/index.md) |
| `notes.show` | [v1](https://grit-scm.com/docs/schemas/schemas/notes.show/v1.json/index.md) |
| `patch-id` | [v1](https://grit-scm.com/docs/schemas/schemas/patch-id/v1.json/index.md) |
| `pick` | [v2](https://grit-scm.com/docs/schemas/schemas/pick/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/pick/v1.json/index.md) |
| `history.move` | [v1](https://grit-scm.com/docs/schemas/schemas/history.move/v1.json/index.md) |
| `history.reword` | [v1](https://grit-scm.com/docs/schemas/schemas/history.reword/v1.json/index.md) |
| `history.fixup` | [v1](https://grit-scm.com/docs/schemas/schemas/history.fixup/v1.json/index.md) |
| `history.absorb` | [v1](https://grit-scm.com/docs/schemas/schemas/history.absorb/v1.json/index.md) |
| `pull` | [v2](https://grit-scm.com/docs/schemas/schemas/pull/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/pull/v1.json/index.md) |
| `push` | [v1](https://grit-scm.com/docs/schemas/schemas/push/v1.json/index.md) |
| `rebase` | [v1](https://grit-scm.com/docs/schemas/schemas/rebase/v1.json/index.md) |
| `rebase.check` | [v1](https://grit-scm.com/docs/schemas/schemas/rebase.check/v1.json/index.md) |
| `reflog` | [v1](https://grit-scm.com/docs/schemas/schemas/reflog/v1.json/index.md) |
| `reflog.list` | [v1](https://grit-scm.com/docs/schemas/schemas/reflog.list/v1.json/index.md) |
| `reflog.delete` | [v1](https://grit-scm.com/docs/schemas/schemas/reflog.delete/v1.json/index.md) |
| `reflog.expire` | [v1](https://grit-scm.com/docs/schemas/schemas/reflog.expire/v1.json/index.md) |
| `remote` | [v2](https://grit-scm.com/docs/schemas/schemas/remote/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/remote/v1.json/index.md) |
| `remote.add` | [v2](https://grit-scm.com/docs/schemas/schemas/remote.add/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/remote.add/v1.json/index.md) |
| `remote.prune` | [v1](https://grit-scm.com/docs/schemas/schemas/remote.prune/v1.json/index.md) |
| `remote.refs` | [v2](https://grit-scm.com/docs/schemas/schemas/remote.refs/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/remote.refs/v1.json/index.md) |
| `remote.remove` | [v2](https://grit-scm.com/docs/schemas/schemas/remote.remove/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/remote.remove/v1.json/index.md) |
| `remote.rename` | [v2](https://grit-scm.com/docs/schemas/schemas/remote.rename/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/remote.rename/v1.json/index.md) |
| `remote.set-head` | [v1](https://grit-scm.com/docs/schemas/schemas/remote.set-head/v1.json/index.md) |
| `remote.set-url` | [v2](https://grit-scm.com/docs/schemas/schemas/remote.set-url/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/remote.set-url/v1.json/index.md) |
| `remote.show` | [v2](https://grit-scm.com/docs/schemas/schemas/remote.show/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/remote.show/v1.json/index.md) |
| `repack` | [v1](https://grit-scm.com/docs/schemas/schemas/repack/v1.json/index.md) |
| `reset` | [v1](https://grit-scm.com/docs/schemas/schemas/reset/v1.json/index.md) |
| `resolve` | [v1](https://grit-scm.com/docs/schemas/schemas/resolve/v1.json/index.md) |
| `restore` | [v1](https://grit-scm.com/docs/schemas/schemas/restore/v1.json/index.md) |
| `revert` | [v1](https://grit-scm.com/docs/schemas/schemas/revert/v1.json/index.md) |
| `revs` | [v1](https://grit-scm.com/docs/schemas/schemas/revs/v1.json/index.md) |
| `rm` | [v1](https://grit-scm.com/docs/schemas/schemas/rm/v1.json/index.md) |
| `shortlog` | [v1](https://grit-scm.com/docs/schemas/schemas/shortlog/v1.json/index.md) |
| `show` | [v1](https://grit-scm.com/docs/schemas/schemas/show/v1.json/index.md) |
| `skill` | [v1](https://grit-scm.com/docs/schemas/schemas/skill/v1.json/index.md) |
| `stash` | [v1](https://grit-scm.com/docs/schemas/schemas/stash/v1.json/index.md) |
| `stash.apply` | [v2](https://grit-scm.com/docs/schemas/schemas/stash.apply/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/stash.apply/v1.json/index.md) |
| `stash.branch` | [v2](https://grit-scm.com/docs/schemas/schemas/stash.branch/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/stash.branch/v1.json/index.md) |
| `stash.drop` | [v2](https://grit-scm.com/docs/schemas/schemas/stash.drop/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/stash.drop/v1.json/index.md) |
| `stash.list` | [v2](https://grit-scm.com/docs/schemas/schemas/stash.list/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/stash.list/v1.json/index.md) |
| `stash.pop` | [v1](https://grit-scm.com/docs/schemas/schemas/stash.pop/v1.json/index.md) |
| `stash.push` | [v1](https://grit-scm.com/docs/schemas/schemas/stash.push/v1.json/index.md) |
| `stash.show` | [v1](https://grit-scm.com/docs/schemas/schemas/stash.show/v1.json/index.md) |
| `stash.clear` | [v1](https://grit-scm.com/docs/schemas/schemas/stash.clear/v1.json/index.md) |
| `status` | [v1](https://grit-scm.com/docs/schemas/schemas/status/v1.json/index.md) |
| `switch` | [v2](https://grit-scm.com/docs/schemas/schemas/switch/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/switch/v1.json/index.md) |
| `tag` | [v2](https://grit-scm.com/docs/schemas/schemas/tag/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/tag/v1.json/index.md) |
| `update` | [v1](https://grit-scm.com/docs/schemas/schemas/update/v1.json/index.md) |
| `worktree.add` | [v1](https://grit-scm.com/docs/schemas/schemas/worktree.add/v1.json/index.md) |
| `worktree.list` | [v1](https://grit-scm.com/docs/schemas/schemas/worktree.list/v1.json/index.md) |
| `worktree.lock` | [v1](https://grit-scm.com/docs/schemas/schemas/worktree.lock/v1.json/index.md) |
| `worktree.move` | [v1](https://grit-scm.com/docs/schemas/schemas/worktree.move/v1.json/index.md) |
| `worktree.prune` | [v2](https://grit-scm.com/docs/schemas/schemas/worktree.prune/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/worktree.prune/v1.json/index.md) |
| `worktree.remove` | [v1](https://grit-scm.com/docs/schemas/schemas/worktree.remove/v1.json/index.md) |
| `worktree.repair` | [v1](https://grit-scm.com/docs/schemas/schemas/worktree.repair/v1.json/index.md) |
| `worktree.unlock` | [v1](https://grit-scm.com/docs/schemas/schemas/worktree.unlock/v1.json/index.md) |

Plumbing commands (`manager`, `upload-pack`, `receive-pack`) and shell completion generation do not emit JSON outcome objects and have no schemas here.

## See also

[Scripting with grit](https://grit-scm.com/docs/scripting/index.md), [Agent guide](https://grit-scm.com/docs/agents/index.md)

# https://grit-scm.com/docs/init/index.md

# grit init

> Create a new, empty repository.

## Synopsis

```text
grit init [-b|--initial-branch <name>] [--bare] [--object-format sha1|sha256]
          [--ref-format <files|reftable>] [--separate-git-dir <dir>] [<path>]
```

Global options [`--json`](https://grit-scm.com/docs/global-options/index.md) and [`--markdown`](https://grit-scm.com/docs/global-options/index.md) apply.

## Description

Creates an empty Git repository at `<path>`, or in the current directory when no path is given. The directory is created if it doesn't exist. A normal repository keeps its data in a `.git` directory next to your files. A bare repository has no working tree; the repository data is the directory itself, which is what you want for a repository that other people push to.

The first branch defaults to `main`, or to `init.defaultBranch` from your global Git config when you omit `-b`. It has no commits until you make one.

Use `--ref-format reftable` to initialize with Git's reftable ref backend (requires a reftable-capable Git for interoperability). The default is `files` (loose refs under `refs/`).

Use `--object-format sha256` for a SHA-256 object database (Git repository format version 1 with `extensions.objectformat = sha256`). The default is `sha1`.

Use `--separate-git-dir` to keep the git directory outside the work tree (a `gitdir:` gitfile in `.git` points at the real directory).

## Options

| Option | Description |
| --- | --- |
| `<path>` | Where to create the repository. Defaults to the current directory. |
| `-b`, `--initial-branch` | Initial branch name (overrides `init.defaultBranch`). |
| `--bare` | Create a bare repository, with no working tree. |
| `--object-format` | Object hash algorithm: `sha1` (default) or `sha256`. |
| `--ref-format` | Ref storage backend: `files` (default) or `reftable`. |
| `--separate-git-dir` | Place the git directory at this path instead of `<path>/.git`. |

## Examples

Start a new project in a new directory:

```console
$ grit init project
Initialized empty repository in /home/ada/project/.git (ref-format: files)
```

Turn the current directory into a repository:

```console
$ grit init
```

Create a bare repository to use as a shared remote:

```console
$ grit init --bare /srv/git/project.git
Initialized empty bare repository in /srv/git/project.git (ref-format: files)
```

Initialize with the reftable ref backend:

```console
$ grit init --ref-format reftable reftable-demo
Initialized empty repository in /home/ada/reftable-demo/.git (ref-format: reftable)
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/init/schemas/init/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `initialized` | boolean | `true` when a new repository was created. |
| `reinitialized` | boolean | `true` when an existing repository was reinitialized in place (omitted when `false`). |
| `path` | string | Repository directory (the `.git` directory for a normal repository). |
| `bare` | boolean | Whether the repository is bare. |
| `branch` | string | Initial branch name (actual `HEAD` branch after reinit). |
| `object_format` | string | Object hash algorithm (`sha1` or `sha256`). |
| `ref_format` | string | Ref storage backend (`files` or `reftable`). |
| `git_dir` | string | Separate git directory when `--separate-git-dir` was used (omitted when co-located). |

Example:

```json
{
  "initialized": true,
  "path": "/home/ada/project/.git",
  "bare": false,
  "branch": "main",
  "object_format": "sha1",
  "ref_format": "files"
}
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/init/schemas/init/v1.json/index.md)
Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a short prose summary:

```text
Initialized empty repository at `/home/ada/project/.git` (default branch `main`, ref-format `reftable`).
```


## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[grit clone](https://grit-scm.com/docs/clone/index.md), [grit remote](https://grit-scm.com/docs/remote/index.md)

# https://grit-scm.com/docs/clone/index.md

# grit clone

> Copy a remote repository into a new directory.

## Synopsis

```text
grit clone <url> [<dir>] [--depth <N>] [-b|--branch <NAME>] [--blobs <none|auto|SIZE>] [--config <KEY=VALUE>]... [--shallow] [--single-branch | --no-single-branch] [--no-tags] [-o <name>] [--bare] [--no-checkout] [-q|--quiet]
```

## Description

Copies the repository at `<url>` into a new directory and checks out the remote's default branch. The remote is saved as `origin`, so [`grit fetch`](https://grit-scm.com/docs/fetch/index.md), [`grit pull`](https://grit-scm.com/docs/pull/index.md) and [`grit push`](https://grit-scm.com/docs/push/index.md) work with no further setup.

Clone fetches every remote tag under `refs/tags/` on a full multi-branch clone, including tags on commits that are not reachable from any branch tip (matching `git clone`). With `--single-branch` (or a shallow clone without `--no-single-branch`), only tags whose peeled commits are reachable from the fetched branch history are imported — the same tag-following default as `git clone --single-branch`. Later [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) uses tag-following by default; pass `--tags` to fetch all tags again.

With files-based ref storage, clone packs imported tags and remote-tracking refs,
including final peel records for nested annotated tags. Symbolic `HEAD` refs stay
loose, and reflogs are preserved. Bare and shallow clones pack the tags they import;
`--no-tags` imports none. This keeps bounded decorated logs from paying for a loose
file and object lookup for every historical tag. Ordinary fetches keep their
existing ref layout. Reftable repositories continue to use their ref backend.


`<url>` can be an `https://` or `http://` URL, an `ssh://` URL or `user@host:path` address, a `git://` URL, a `file://` URL, a path to a local repository, or a path to a [git bundle](https://git-scm.com/docs/git-bundle) file (recognized by its header signature). A local path is stored as an absolute path so that later fetches work from anywhere.

Cloning a plain local path hard-links the source's packfiles, like `git clone --local`, so the new repository also gets objects no ref reaches. A `file://` URL gets only the objects reachable from the cloned refs, like any other transport. Use it when the source holds history you don't want copied, such as deleted branches or hidden refs.

Without `<dir>`, the directory is named after the last path component of the URL with any `.git` suffix removed (splitting on both `/` and `\`, so Windows paths like `..\..\origin.git` clone into `origin`), so `https://github.com/gitbutlerapp/grit.git` clones into `grit`. The destination must not exist or must be empty. If the path already exists and is not empty, grit refuses the clone and leaves the directory and its files unchanged.

For a local path or `file://` URL, grit checks that the source exists and is a repository (or a bundle file) **before** creating the destination directory. A typo or missing path fails with exit code **128** and leaves no new directory behind. Cloning from a real empty bare repository at another path is unchanged: grit still creates the destination and reports `empty_remote` when the remote has no commits.

On an interactive terminal (human output, not `--json` or `--markdown`), each step of the clone gets one live line on stderr: **Receiving** (pack bytes), **Indexing** (objects), **Resolving** (deltas) and **Checkout** (files). Each line has a scrolling, colored graph of throughput over the last few seconds, a count, a completion bar when the total is known, the current rate and the elapsed time. When a step finishes, its line stays on screen with a graph of the whole step, the total and the average rate.

While the pack streams in, grit counts its objects as they arrive (the total comes from the pack header), so the **Receiving** line shows `received/total` objects and a completion bar, as Git's does. Under the live line, an **Overall** bar estimates how far the whole clone is and how long is left:

```text
⠸ Receiving   253,612/421,673  ━━━━━━────  60%         34.2 MiB/s    7.5s
  Overall    ━━━━━━━━━━━━━━━━━━━━━━──────────────────   53%  ~8s left
```

The step under way is projected from its own pace so far. Steps that have not started are sized from the pack's object and delta counts at typical indexing, delta and checkout rates. Before any objects arrive (while the remote is still preparing the pack), the bar shows `estimating`. The percentage never goes down, but the time left can grow when objects slow down, for example when large blobs follow many small commits. The overall bar needs an ANSI terminal; it is cleared once the clone finishes, before the summary.

After the clone, stdout gets a summary: total time with a bar showing where it went, bytes received with average and peak throughput, objects by type, branches and tags, and the files and bytes in the work tree. Colors follow the terminal and are turned off by `NO_COLOR`.

Over the network, the bar splits the wait before any pack data arrives into three parts: **handshake** (opening the connection — TCP, TLS or SSH, and starting the server's `upload-pack` — until its advertisement is read), **negotiate** (listing refs and the `want`/`have` exchange, until the final request is sent) and **pack prep** (the server counting and compressing objects, until the first pack byte). Local clones and bundles have no such stretch; any wait before their first step shows as **connect**. Time after the last step (writing refs and config) shows as **finish**, and gaps between steps as **other**.

When `core.ignorecase` is enabled, grit stores every remote branch and tag during clone, including pairs that differ only by ASCII case (for example `Release` and `release`), in one `packed-refs` write — the same layout Git uses on APFS and NTFS. Later fetches into a loose files ref store can reject the second spelling of such a pair; see [`grit fetch`](https://grit-scm.com/docs/fetch/index.md).

When `core.ignorecase` or `core.precomposeunicode` is set and the repository contains paths that collide on this filesystem (different ASCII case or NFC/NFD spellings mapping to one file), grit prints a **warning** on **stderr** (human mode only) listing every colliding index path. Only one path from each group exists on disk; the summary **files** and **worktree_bytes** counts reflect distinct on-disk files, not the number of index entries. With `commit.autoStage` (the default), grit does not auto-stage collision losers — their index blobs stay as recorded in the tree even though the work tree shows them as modified.

When the checked-out tree contains **gitlinks** (mode `160000`), grit creates an empty directory at each path and does **not** fetch the nested repository. There is no `grit submodule` command and no `--recurse-submodules` flag. Paths listed in `.gitmodules` are **submodules**: human and `--markdown` output print a **note** on stderr that grit does not fetch them; `--json` includes `submodule_paths` (omitted when empty). Gitlinks with **no** `.gitmodules` entry are **bare gitlinks** (often from copying a nested repo into a parent tree): a separate note explains that the checkout directory is empty and is not a submodule; `--json` includes `bare_gitlink_paths` (omitted when empty). Use the system `git` command if you need submodule checkout or updates.

### Starting from the server's bundle

When an HTTP(S) server offers a prebuilt bundle through Git's `bundle-uri` protocol command (as [`grit serve`](https://grit-scm.com/docs/serve/index.md) does), clone downloads that bundle first, unpacks it, and then fetches only what is newer than it. A bundle is a plain file, so the download resumes instead of starting over:

- a connection that drops is picked up again from where it stopped, a few times, in the same run;
- an interrupted clone (Ctrl-C, a lost network, a closed laptop) keeps what it downloaded in `$XDG_CACHE_HOME/grit/bundles` (`~/.cache/grit/bundles` by default). Run the same `grit clone` again and the download carries on from there.

The bundle download has its own display: an arrow and the bundle's URL, then a bar. A resumed download says where it picked up, and its bar shows the bytes from the earlier run in grey:

```text
↻ Resuming bundle download at 14.1 MiB of 58.5 MiB (24%)  example.com/demo/bundles/1792925548-38bec2f6f89f.bundle
  ━━━━━━━━━━━━━━━━━━━─────────────   60%  35.5 MiB of 58.5 MiB  5.22 MiB/s  ~4s left
```

When it finishes, the line becomes `✓ bundle 58.5 MiB in 8.5s · 5.23 MiB/s · resumed at 14.1 MiB`, and the summary gets a `bundle` row. Shallow (`--depth`) and partial (`--blobs`) clones never use a bundle, and `transfer.bundleURI=false` in config turns bundles off. When the bundle cannot be used, clone warns and fetches everything as usual.

The advertised bundle URL usually has no credentials in it. If the clone URL carries `user:password@` (typical for CI tokens), grit reuses that authentication for the bundle download when it is on the same host as the repository. Authentication failures are not retried like a dropped connection.

For private GitHub repositories over HTTPS, sign in first with [`grit auth`](https://grit-scm.com/docs/auth/index.md). For other hosts, save a user name and token first with `grit auth <url> --username <user> --token <token>`.

When the remote has no commits yet (an empty bare repository), grit still creates the destination directory, configures `origin`, and points `HEAD` at the remote's default branch without checking out files. Human output includes a short note on stderr (`note: the remote repository is empty.`); `--json` reports `"files": 0`, `"no_checkout_reason": "empty_remote"`, and the configured branch name.

When the remote advertises a default branch that has no commits yet but other branches (or tags) were fetched, grit configures `HEAD` to that default branch without checking out files — the same situation as `git clone` when `HEAD` on the server points at an unborn branch. Human output prints a **warning** on stderr that the default branch has no commits, lists remote branches that do have commits, and may suggest `grit switch <branch>`. `--json` sets `"no_checkout_reason": "unborn_default_branch"` and `"branches_with_commits"` to those branch names; `"files"` stays `0` until you switch.

Pass `--depth <N>` for the same result as `git clone --depth`: only one ref is fetched (single-branch), with a `.git/shallow` boundary at its tip. Without `-b` / `--branch`, that ref is the remote's default branch. With `-b`, it is the named branch or tag (branches resolve under `refs/heads/` first, then `refs/tags/`). Tag checkouts detach `HEAD` at the peeled commit and do not create branch config. Other branches are not downloaded until you fetch them explicitly. Later [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) respects the shallow boundary.

`--shallow` is a hidden alias for `--depth 1` and cannot be combined with `--depth`.

### Partial clone (`--blobs`)

`--blobs none` creates a **blobless** (promisor) clone: commits and trees are present locally, but blob objects are omitted from the initial fetch and fetched on demand later (same idea as `git clone --filter=blob:none`). Grit writes Git-compatible promisor configuration (`remote.<name>.partialclonefilter`, `extensions.partialclone`, and related keys) so the system `git` command can lazy-fetch missing blobs through the same remote.

`--blobs <SIZE>` omits blobs whose inflated size is at or above the limit. `<SIZE>` accepts the same suffixes as Git's `blob:limit` filter (`512`, `1k`, `2m`, …). Smaller blobs stay in the first pack, which keeps checkouts working when only large assets are skipped.

`--blobs auto` takes the filter from the server instead: from the [large-object promisors](#large-object-promisors) it advertises and the clone accepts, using the strictest `partialCloneFilter` they advertise (`blob:none` over any limit, else the smallest limit). Without an accepted remote that advertises a filter, nothing is filtered. The clone records `remote.<name>.partialclonefilter=auto`, so each later fetch picks its filter the same way, as Git 2.54 and newer do; older Git does not understand that value.

Partial clone trades disk and bandwidth on the first fetch for extra round-trips when something needs blob bytes (for example `git log -p` or reading a large file). It works with `--depth`, `-b` / `--branch`, and the other clone options. The server must allow filter requests (`uploadpack.allowFilter` on bare repos served over smart HTTP or `file://`); a server that does not sends every blob, and the summary says the filter was ignored. A partial clone of a local path or `file://` URL runs grit's own upload-pack in-process, where Git would start `git upload-pack`, so it needs no `git` installed and follows the same `uploadpack.*` settings, read from the served repository's config and, as with Git, from your global and system config.

When you pass `--blobs` but the server does not advertise filter support, grit warns on stderr (even with `-q`), fetches an unfiltered pack, and does not treat the clone as partial in human output or `--json` (`partial` is omitted or false). Promisor configuration is still written, matching `git clone --filter` when the server ignores the filter, so later commands may warn about a promisor remote even though every blob arrived in the first pack.

`--config <KEY=VALUE>` writes a config value into the new repository before anything is fetched, like `git clone -c`. It can be repeated, and a key given twice gets both values. A key without `=VALUE` is set to `true`. Unlike the global `-c`, which lasts for one command, these values stay in the clone's config.

### Large-object promisors

A server can keep its large blobs on another remote, a large-object promisor (LOP), and say so with the protocol v2 `promisor-remote` capability (see [grit serve](https://grit-scm.com/docs/serve/index.md#large-object-promisors)). A clone that accepts the LOP lets the server leave those blobs out; they are then fetched from the LOP when something needs them, instead of through the server.

Accepting takes two things in the new repository's config, so they go in with `--config`: the LOP itself as a promisor remote (`remote.<name>.url` and `remote.<name>.promisor=true`), and a policy in `promisor.acceptFromServer`:

| Value | Accepts |
| --- | --- |
| `none` (default) | nothing |
| `knownUrl` | a remote configured under the advertised name with the same URL (the safest choice) |
| `knownName` | a remote configured under the advertised name, whatever its URL |
| `all` | every advertised remote; only for servers you fully trust |

`promisor.checkFields` (`partialCloneFilter`, `token`) also requires the advertised value of each listed field to equal the one configured for the remote. `promisor.storeFields` copies the advertised values of the listed fields into the config of a remote that is already configured; it never creates a remote or changes its URL. Lazy fetches always use the URL configured locally, never the advertised one.

Accepting needs a partial clone (`--blobs`): a full clone needs every object from the server, so it declines (`not_partial`). The clone's summary says what it decided:

```console
$ grit clone --blobs auto \
    --config remote.lop.url=https://lop.example.com/project.git \
    --config remote.lop.promisor=true \
    --config promisor.acceptFromServer=knownUrl \
    https://git.example.com/project.git
Cloning into 'project' ...
✓ Cloned into project on main in 128ms
  partial  partial clone; large blobs are fetched on demand
  promisor  lop accepted · blob:limit=5k

  time      ·······················█▓······▒▒▒▒▒▒▒▒▒  128ms
            · connect 72ms  █ receiving 0ms  ▓ indexing 2ms  · other 17ms  ▒ checkout 28ms
  data      225 B received
  objects   3 · 1 commit · 1 tree · 1 blob
  refs      1 branch · 0 tags
  files     2 files · 19.5 KiB in the work tree
```

The checkout's missing blobs came from `lop`. Missing objects are always asked of the promisor remotes in config order, with the remote the clone came from (`extensions.partialClone`) last, so a LOP configured before it is tried first and the server is only asked for what the LOP did not have. A server refuses a request that names any object it lacks, so when the LOP holds only the large blobs, the missing objects are split into smaller requests until each remote is asked only for what it has. When an object cannot be fetched, the error names every remote that failed and why.

`--bare` creates a bare repository at the destination (the directory itself is the git directory, named with a `.git` suffix when the URL is derived automatically), fetches `refs/heads/*` and tags directly, and configures only `remote.<name>.url` — matching `git clone --bare`. `--no-checkout` fetches and sets `HEAD` to the default branch without writing the index or work tree files, matching `git clone --no-checkout`.

After `--no-checkout`, use [`grit switch`](https://grit-scm.com/docs/switch/index.md) to materialize the revision you need, for example `grit -C client switch --detach HEAD~1 --json`. The first switch writes the entire destination tree, including when you select the current branch or `HEAD`. Files you created at destination paths are protected by the usual untracked-file collision checks. `switch --dry-run` previews how many paths will be written without creating an index or changing files or refs.

You can also clone from a shallow repository (including one created with `git clone --depth`); grit copies the shallow boundary into the new repository so history matches the source.

Working-tree materialization after fetch uses the same parallel checkout path as [`grit switch`](https://grit-scm.com/docs/switch/index.md). Configure [`checkout.workers`](https://grit-scm.com/docs/library/parallelism.md/index.md) and `checkout.thresholdForParallelism` in the repository config. Global [`--threads`](https://grit-scm.com/docs/global-options.md/index.md) overrides checkout workers on non-Windows hosts; on **Windows**, set `checkout.workers` explicitly (see [parallelism](https://grit-scm.com/docs/library/parallelism.md/index.md)).

## Options

| Option | Description |
| --- | --- |
| `<url>` | The repository to clone: a URL or a local path. |
| `<dir>` | The directory to clone into. Defaults to the repository's name. |
| `--depth <N>` | Shallow clone: fetch at most `N` commits on the selected ref (`git clone --depth`). |
| `-b`, `--branch <NAME>` | Branch or tag to check out instead of the remote default. |
| `--shallow` | Hidden alias for `--depth 1` (conflicts with `--depth`). |
| `--single-branch` | Fetch only the branch that is checked out and follow tags into that history only (`git clone --single-branch`). JSON `tag_fetch` is `following`. |
| `--no-single-branch` | With `--depth`, fetch every branch tip (`git clone --no-single-branch --depth=1`). |
| `--no-tags` | Do not fetch tags; sets `remote.<name>.tagOpt=--no-tags` like Git. |
| `-o`, `--origin <name>` | Name of the remote (default `origin`). |
| `--blobs <none\|auto\|SIZE>` | Partial clone: omit all blobs (`none`), blobs at/above `<SIZE>` (`1k`, `512`, …), or what the accepted promisor remotes hold (`auto`). |
| `--config <KEY=VALUE>` | Write a config value into the new repository before fetching (`git clone -c`). Repeatable. |
| `--bare` | Bare repository; no working tree (`git clone --bare`). |
| `--no-checkout` | Fetch refs but do not check out files (`git clone --no-checkout`). |
| `-q`, `--quiet` | No progress, no `Cloning into` line and no human summary. Warnings (such as an empty remote) still go to stderr; `--json` and `--markdown` output is unchanged. |

## Examples

Clone a repository from GitHub:

```console
$ grit clone https://github.com/BurntSushi/ripgrep.git
Cloning https://github.com/BurntSushi/ripgrep.git → ripgrep
  remote: Enumerating objects: 14184, done.
  remote: Counting objects: 100% (182/182), done.
  remote: Compressing objects: 100% (99/99), done.
  remote: Total 14184 (delta 128), reused 83 (delta 83), pack-reused 14002 (from 2)
✓ Receiving  ███████████▅▅▅▅▅▅▅▅▅▅          5.76 MiB         39.6 MiB/s   145ms
✓ Indexing   █████████████████████    14,184 objects   288.2k objects/s    49ms
✓ Resolving                             9,918 deltas    833.1k deltas/s    11ms
✓ Checkout   █████████████████████         226 files      10.6k files/s    21ms

✓ Cloned into ripgrep on master in 1.2s

  time      ·······························█████·▓▓▒  1.2s
            · handshake 475ms  · negotiate 197ms  · pack prep 312ms  █ receiving 145ms  ▓ indexing 49ms  ▒ resolving 11ms  ░ checkout 21ms
  data      5.76 MiB received · 39.6 MiB/s avg · 45.3 MiB/s peak
  objects   14,184 · 2,343 commits · 6,420 trees · 5,147 blobs · 274 tags
  refs      16 branches · 274 tags
  files     226 files · 3.09 MiB in the work tree
```

Progress lines are written to stderr and update in place on a terminal; the time bar and legend are colored by step there. When stderr is not a TTY (for example in a CI log or with stderr redirected), only the initial `Cloning into …` line is written to stderr, and the summary still appears on stdout.

Clone into a directory with a different name:

```console
$ grit clone git@github.com:gitbutlerapp/grit.git grit-src
```

Clone a local repository:

```console
$ grit clone /srv/git/project.git
```

Shallow clone (single commit of history on the default branch):

```console
$ grit clone --depth 1 https://github.com/BurntSushi/ripgrep.git
```

Clone a specific branch with limited history:

```console
$ grit clone --depth 3 -b feature file:///srv/git/project.git
```

Clone and detach at a tag:

```console
$ grit clone -b v1.0.0 https://github.com/BurntSushi/ripgrep.git
```

## JSON output

Schema: [v3](https://grit-scm.com/docs/clone/schemas/clone/v3.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `url` | string | The URL or path that was cloned. For network URLs, embedded credentials are stripped from this display copy (the configured `remote.<name>.url` keeps the caller's URL). |
| `path` | string | Directory the clone was created in. |
| `remote` | string | Remote name configured for the source (`origin` by default). |
| `single_branch` | boolean | Whether only one branch was fetched. |
| `tag_fetch` | string | Tag fetch mode for the initial fetch: `all`, `following`, or `none`. Named `tag_fetch` because `tags` is already the count of tag refs fetched. |
| `branch` | string or null | Branch checked out; `null` when detached at a tag. |
| `detached` | boolean | True when `HEAD` is detached (tag checkout). |
| `tag` | string or omitted | Tag name when `-b` named a tag. |
| `depth` | integer or omitted | Shallow depth when `--depth` or `--shallow` was used. |
| `blobs` | string or integer or omitted | The filter used: `"none"` or a byte limit. With `--blobs auto`, the filter it resolved to; omitted when nothing was filtered. |
| `partial` | boolean or omitted | `true` when the server applied the `--blobs` filter on the initial fetch. Omitted or false when the server lacks filter support (see warning above). |
| `filter_auto` | boolean or omitted | `true` with `--blobs auto`. |
| `filter_ignored` | boolean or omitted | `true` when the server does not support filters, so `--blobs` was not sent and every blob was downloaded (`partial` is then omitted); the clone is still set up as a partial clone, as Git leaves it. The human summary then shows a `filter` line saying so instead of calling the clone blobless. |
| `promisor_remotes` | array or omitted | The promisor remotes the server advertised: `name`, `url` (credentials removed), `accepted`, `filter` (the advertised `partialCloneFilter`, or `null`) and `rejected` (why it was not accepted: `policy_none`, `unknown_remote`, `url_mismatch`, `field_missing`, `field_mismatch` or `not_partial`; `null` when accepted). Omitted when the server advertised none. Tokens are never shown. |
| `stored_fields` | array or omitted | Fields copied into config by `promisor.storeFields`: `remote` and `field` (`partialCloneFilter` or `token`), never the value. Omitted when nothing was stored. |
| `promisor_warnings` | array or omitted | Promisor config or advertised values that were ignored: `code` is `unknown_accept_value` (`promisor.acceptFromServer` is not a known policy, so nothing is accepted), `unknown_field` (a `promisor.checkFields` / `promisor.storeFields` entry is not a known field), `invalid_advertised_value` (an advertised field was not stored because its value is invalid) or `unusable_auto_filter` (`--blobs auto` cannot use an accepted remote's filter, such as `tree:0`); `key`, `remote`, `field` and `value` say which, when they apply. A rejected advertised value is never shown. Shown as `promisor  warning: …` lines in the human output and `promisor warning` bullets in `--markdown`. Omitted when there were none. |
| `objects` | integer | Objects installed during fetch: for network clones, objects in the received pack; for local-path clones, objects in newly linked pack indexes plus any reachable loose objects hardlinked from the source. |
| `bytes` | integer | On-disk payload bytes installed during fetch: for network clones, the received `.pack` size; for local-path clones, the sum of newly linked `.pack` files plus reachable loose object files (same bytes as hardlinked/copied object store data). |
| `branches` | integer | Remote branches fetched. |
| `tags` | integer | Remote tags fetched. |
| `files` | integer | Working-tree files checked out (distinct on-disk paths when `core.ignorecase` or `core.precomposeunicode` collapsed spellings). |
| `path_collisions` | array of strings | Index paths that collided during checkout when tracked paths share one on-disk file (case or Unicode normalization). Omitted when empty. |
| `submodule_paths` | array of strings | Gitlink paths listed in `.gitmodules`. Grit does not fetch submodule repositories. Omitted when empty. |
| `bare_gitlink_paths` | array of strings | Gitlink paths with no `.gitmodules` entry (empty directories after checkout). Omitted when empty. |
| `object_types` | object or null | Objects received by type: `commits`, `trees`, `blobs` and `tags` (annotated tag objects). Populated when grit indexed the received pack or can tally every object in the transfer. `null` when a local pack link installed more objects than the transfer summary tracks individually (typical for a single linked pack on clone). |
| `worktree_bytes` | integer | Total size of the checked-out files. |
| `seconds` | number | Wall-clock seconds for the whole clone. |
| `phases` | array | Time spent in each step, in order: `phase` (`bundle`, `receiving`, `indexing`, `resolving_deltas`, `copying` or `checkout`), `unit` (`bytes`, `objects` or `files`), `count` and `seconds`. Steps that processed nothing are left out. |
| `bare` | boolean | `true` when `--bare` was used. |
| `no_checkout_reason` | string or omitted | When no files were checked out: `empty_remote`, `unborn_default_branch`, `bare`, or `no_checkout`. Omitted when checkout succeeded. |
| `branches_with_commits` | array of strings | Remote branch names that have commits when `no_checkout_reason` is `unborn_default_branch`. Omitted when empty. |
| `bundle` | object or omitted | The server's prebuilt bundle the clone started from: `uri` (credentials stripped like `url`), `bytes` (its size) and `resumed_from` (bytes an earlier, interrupted clone had already downloaded). `objects` and `bytes` above include what it brought. Omitted when no bundle was used. |
| `space` | string or omitted | For a clone of an organization's project on GitButler Code (the default grit host): your space's project, `<you>/<project>`. Pushes from the clone go there (`remote.origin.pushurl`), and a `space` remote fetches from it; see [`grit sync`](https://grit-scm.com/docs/sync/index.md). Omitted otherwise, or when you aren't signed in. |

Example (repository with commits):

```json
{
  "url": "/srv/git/project.git",
  "path": "project",
  "remote": "origin",
  "single_branch": false,
  "tag_fetch": "all",
  "branch": "main",
  "detached": false,
  "bare": false,
  "objects": 42,
  "bytes": 8192,
  "branches": 1,
  "tags": 0,
  "files": 3,
  "object_types": {
    "commits": 4,
    "trees": 9,
    "blobs": 29,
    "tags": 0
  },
  "worktree_bytes": 6144,
  "seconds": 0.21,
  "phases": [
    { "phase": "copying", "unit": "objects", "count": 42, "seconds": 0.004 },
    { "phase": "checkout", "unit": "files", "count": 3, "seconds": 0.002 }
  ]
}
```

Empty remote (no branch tips yet):

```json
{
  "url": "/tmp/origin.git",
  "path": "project",
  "remote": "origin",
  "single_branch": false,
  "tag_fetch": "all",
  "branch": "main",
  "detached": false,
  "bare": false,
  "objects": 0,
  "bytes": 0,
  "branches": 0,
  "tags": 0,
  "files": 0,
  "no_checkout_reason": "empty_remote",
  "object_types": null,
  "worktree_bytes": 0,
  "seconds": 0.013,
  "phases": []
}
```

Unborn remote default branch (`HEAD` on the server points at a branch with no commits, but `main` was pushed):

```json
{
  "url": "/tmp/remote.git",
  "path": "clone2",
  "remote": "origin",
  "single_branch": false,
  "tag_fetch": "all",
  "branch": "master",
  "detached": false,
  "bare": false,
  "objects": 3,
  "bytes": 458,
  "branches": 1,
  "tags": 0,
  "files": 0,
  "no_checkout_reason": "unborn_default_branch",
  "branches_with_commits": ["main"],
  "object_types": null,
  "worktree_bytes": 0,
  "seconds": 0.003,
  "phases": [
    {
      "phase": "copying",
      "unit": "objects",
      "count": 1,
      "seconds": 0.00006
    }
  ]
}
```

A clone that accepted a large-object promisor (`--blobs auto`):

```json
{
  "url": "https://git.example.com/project.git",
  "path": "project",
  "remote": "origin",
  "single_branch": false,
  "tag_fetch": "all",
  "branch": "main",
  "detached": false,
  "blobs": 5120,
  "partial": true,
  "filter_auto": true,
  "promisor_remotes": [
    {
      "name": "lop",
      "url": "https://lop.example.com/project.git",
      "accepted": true,
      "filter": "blob:limit=5k",
      "rejected": null
    }
  ],
  "objects": 3,
  "bytes": 225,
  "branches": 1,
  "tags": 0,
  "files": 2,
  "object_types": { "commits": 1, "trees": 1, "blobs": 1, "tags": 0 },
  "worktree_bytes": 20006,
  "seconds": 0.13,
  "phases": [],
  "bare": false
}
```

## Markdown output

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output.

Schema: [v3](https://grit-scm.com/docs/clone/schemas/clone/v3.json/index.md)

Markdown uses headings, bullet lists, and fenced blocks; pipe characters inside table cells are escaped. See the JSON output section for the stable field contract.



```text
## Clone complete

- **path**: `cloned-markdown`
- **branch**: `main`
- **url**: `[UPSTREAM]`
- **objects**: 8
- **object types**: 2 commits, 2 trees, 3 blobs, 1 tags
- **bytes**: 685 ([SIZE])
- **branches**: 2
- **tags**: 1
- **files**: 2
- **worktree bytes**: 23 ([SIZE])
- **elapsed**: [DURATION]

| Phase | Count | Unit | Seconds |
| --- | ---: | --- | ---: |
| copying | 8 | objects | [SECONDS] |
| checkout | 2 | files | [SECONDS] |
```

When the server advertised promisor remotes, a bullet lists them, and one more names each stored field:

```text
- **promisor remotes**: `lop` (accepted)
- **stored**: `partialCloneFilter` for `lop`
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Clone succeeded (including empty remote with no checkout). |
| `1` | Destination not empty, checkout failure (the repository is kept: `kind` `clone_checkout_failed`, see [When the checkout fails](#when-the-checkout-fails)), or other error. Missing or refused credentials are `kind` `auth_required` / `auth_rejected` with a `hint` in `--json` and on the human `hint:` line. HTTPS credentials come from your credential helper (`grit auth <url> --username <user> --token <token>` saves one for any host), then an askpass program (`GIT_ASKPASS`, `core.askPass`, `SSH_ASKPASS`); see [Credentials](https://grit-scm.com/docs/agents/index.md#credentials-https). |
| `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `128` | Could not reach or read the source: missing path, DNS or connection failure, HTTP error status ([`remote_unreadable`](https://grit-scm.com/docs/exit-codes/index.md)); a `404` adds a hint to check the URL. |
| `130` | Interrupted with Ctrl-C, `SIGTERM`, or `SIGHUP` ([`interrupted`](https://grit-scm.com/docs/exit-codes/index.md)). The error is `operation cancelled` (`{"error":"operation cancelled"}` with `--json`). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md).

### When the checkout fails

A failure while downloading or setting up the repository removes the destination again. Once every object and ref is in place and `HEAD` is set, a failure while writing the work tree keeps the repository, as `git clone` does, so the checkout can be finished without downloading everything again. The usual cause is a partial clone whose missing blobs cannot be fetched: a large-object promisor that is unreachable or does not have them yet, or lazy fetch turned off. The error says the clone was kept, the `hint` says how to finish, and `--json` reports `kind` `clone_checkout_failed` with a `clone_checkout` object (exit `1`):

```console
$ GRIT_NO_LAZY_FETCH=1 grit clone --blobs none file:///srv/project.git project
Cloning into 'project' ...
error: the clone into 'project' succeeded, but its checkout failed: promised object not available locally: ce013625030ba8dba906f756967f9e9ca394464a
hint: the repository was kept; run `grit reset --hard` in 'project' to finish the checkout once its promisor remotes can supply the missing objects
$ grit -C project reset --hard
Reset master to 284c599 (hard)
```

| Field | Type | Description |
| --- | --- | --- |
| `clone_checkout.path` | string | The clone's directory, where the repository was kept. |
| `clone_checkout.commit` | string | The commit `HEAD` points at, whose files the checkout was writing. |
| `clone_checkout.missing_object` | string or omitted | The first promised object that could not be fetched, when the checkout failed for lack of one. |
| `clone_checkout.failed_remotes` | array | Each promisor remote that failed to supply the missing objects, in the order they were asked: `remote` (name) and `error` (its first error). Empty when no remote was asked, for example with lazy fetch off. |

A clone interrupted during the checkout is still removed (see below).

### Interrupting a clone

Ctrl-C, `SIGTERM`, and `SIGHUP` stop a clone at any point: while it downloads, copies objects or checks out files. The first signal asks the clone to stop; grit then rolls back the checkout, removes the destination directory it created (or empties one that already existed empty) and exits `130`. Nothing is left in the way, so the same `grit clone` command can simply be run again, and a bundle download carries on where it stopped. A duplicate signal that arrives with the first (`timeout -s INT` or `timeout -s TERM` signals both the process and its group) is ignored; sending the same signal again later ends grit at once, without the cleanup. Only an uncatchable `SIGKILL` (or that second signal after the duplicate window) skips rollback. In a Windows console Ctrl-C and Ctrl-Break behave the same way. Closing the console window still gives grit no chance to clean up, so delete the leftover directory by hand before you clone again.

```console
$ grit clone ../git git
Cloning into 'git' ...
^C
error: operation cancelled
$ echo $?
130
$ ls git
ls: cannot access 'git': No such file or directory
$ grit clone ../git git
Cloning into 'git' ...
✓ Cloned into git on master in 602ms

  time      ·█·············▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓  602ms
            █ copying 3ms  · other 194ms  ▓ checkout 387ms
  data      311 MiB received
  objects   422,423
  refs      1 branch · 1,012 tags
  files     4,856 files · 48.0 MiB in the work tree
```


## See also

[grit init](https://grit-scm.com/docs/init/index.md), [grit remote](https://grit-scm.com/docs/remote/index.md), [grit fetch](https://grit-scm.com/docs/fetch/index.md), [grit auth](https://grit-scm.com/docs/auth/index.md)

# https://grit-scm.com/docs/checkout/index.md

# grit checkout

> Start work on a repository from a snapshot of its main branch, or of some of its paths, instead of a clone.

## Synopsis

```text
grit checkout <url> [<slice>] [-p|--path <path>]... [--into <dir>]
```

## Description

`grit checkout` makes a working repository from a server's newest commit without downloading its history. It asks the server for a **snapshot**: the target branch's tree (the branch the server's `HEAD` names), cut down to the paths you give, in a single commit. It downloads that snapshot and builds a normal Git repository around it: `git` and `grit` work in it as usual.

- With no `--path`, the snapshot is the whole tree.
- With `--path <dir>` (repeatable), it is everything under each path, plus the files directly in every directory above one, the top level included — the same files Git's cone-mode sparse checkout would have.
- With a `<slice>` name, it is that [slice](https://grit-scm.com/docs/slice/index.md)'s paths (plus any `--path`), and the directory defaults to the slice's name.

Download and materialization honor Ctrl+C (and `SIGTERM` / `SIGHUP` on Unix) with `error: operation cancelled` and exit code **130**; a checkout directory grit created for this run is removed when materialization fails or is cancelled.

The new repository's history is one commit, `Snapshot of <commit>: <subject>`, which stands for the real commit on the server. It is at `origin/<branch>` (which `origin/HEAD` names), and you are on a new **work branch** on top of it, named for your `user.email` and two random words (like `alice/amber-brook`). The server picks the final name: it numbers it (`alice/amber-brook-2`) when it already has that branch or has given the name to another checkout, and never gives a name out twice, even across restarts. There is no local copy of the target branch.

`origin` is the repository URL, set up so that plain `git` and `grit` commands stay with the checkout's snapshots:

```text
[remote "origin"]
	url = http://127.0.0.1:8080/demo.git
	fetch = +refs/checkouts/<id>/target:refs/remotes/origin/main
	push = +refs/heads/*:refs/checkouts/<id>/out/heads/*
	tagOpt = --no-tags
```

A plain `git fetch` or `grit fetch` brings only the checkout's own snapshots into `origin/main`, never the real history, other branches or tags. A plain `git push` or `grit push` sends your branches to the check-in area that [`grit checkin`](https://grit-scm.com/docs/checkin/index.md) grafts from, never onto the server's real branches. `grit checkin` and `grit pull` themselves always talk to the server the checkout was made from, even if you point `origin` somewhere else.

What makes the repository a checkout is a small record in its git directory (`grit-checkout.json`): the server, the checkout's id, its target branch, its paths and its snapshots, and the tips of branches it checked in that were since [integrated](https://grit-scm.com/docs/integrate/index.md) into its target branch, whose commits refreshes leave out. Every worktree of the checkout (`git worktree add`) shares it, so checking in and refreshing work from any of them.

Snapshots are made the same way every time, so everyone who checks out the same paths at the same commit gets the same snapshot commit, and the server makes its download once.

The download resumes: if a checkout is interrupted, run the same command again and it picks up where it stopped (partial downloads are kept in `$XDG_CACHE_HOME/grit/checkouts`, `~/.cache/grit/checkouts` by default). The download has the same display as [`grit clone`](https://grit-scm.com/docs/clone/index.md)'s bundle download.

Snapshot checkouts need a server that offers them, such as [`grit serve`](https://grit-scm.com/docs/serve/index.md). They are served at their own endpoint, `<server>/.grit/checkouts/<repository>`, separate from Git's. When a server doesn't have it (a plain Git server, or a repository you can't read), `grit checkout` stops with an error and makes nothing:

```text
error: https://example.com/demo.git offers no grit checkout (no https://example.com/.grit/checkouts/demo endpoint); it may be a plain Git server, or the repository may not exist
```

Sign in to the server first with [`grit auth <url>`](https://grit-scm.com/docs/auth/index.md).

Work comes back with [`grit checkin`](https://grit-scm.com/docs/checkin/index.md), which rebuilds your branches on the server's real history. [`grit integrate <branch>`](https://grit-scm.com/docs/integrate/index.md) merges one into the target branch, and [`grit pull`](https://grit-scm.com/docs/pull/index.md) refreshes the checkout: the server makes a snapshot of the newest commit of the branch the checkout was made from (even if the server's `HEAD` has since moved to another branch) on top of your last one, `grit pull` fetches just the changes in your paths and rebases the current branch onto it. Commits already in the target drop out. A rebase that conflicts stops for you to resolve, then `grit rebase --continue`; other branches still on an older snapshot are named (see [`grit pull`](https://grit-scm.com/docs/pull/index.md#in-a-snapshot-checkout)). `grit pull <branch>` shows you a branch on the server as your checkout sees it and brings your branch onto it, so checkouts of different paths can work on one branch (see [`grit pull`](https://grit-scm.com/docs/pull/index.md#a-server-branch-in-a-snapshot-checkout)).

To switch branches, use [`grit switch`](https://grit-scm.com/docs/switch/index.md) (also `grit co`). Out of Git habit, `grit checkout <branch>` with no URL (nothing with `://`) and no other arguments does the same as `grit switch <branch>`, hints included.

## Options

| Option | Description |
| --- | --- |
| `<url>` | The repository, such as `http://127.0.0.1:8080/demo.git`. |
| `<slice>` | A [slice](https://grit-scm.com/docs/slice/index.md) on the server whose paths to check out. |
| `-p`, `--path <path>` | Check out only this path (a directory or file), plus the files in the directories above it. Repeatable. |
| `--into <dir>` | Directory to check out into. Defaults to the repository's name. It must not exist or must be empty. |

## Examples

Check out one directory of a repository served by `grit serve`:

```console
$ grit checkout http://127.0.0.1:8080/demo.git --path src/deep
✓ Checked out /home/alice/demo on alice/birch-pebble in 117ms

  paths     src/deep
  files     4 files, 293 KiB as a 294 KiB download
  history   one commit, fd590c7, standing for main at 5a80f18

Commit on alice/birch-pebble as usual; origin/main is the snapshot.
$ cd demo && git log --oneline --all
fd590c7 Snapshot of 5a80f18e14a3: Add src and docs
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/checkout/schemas/checkout/v1.json/index.md)

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `url` | string | The repository URL, configured as `origin` (with the fetch and push refspecs above), with any `user:password@` removed. |
| `path` | string | Directory the checkout was made in. |
| `branch` | string | The server's target branch the snapshot was taken from. |
| `work` | string | The new branch checked out for your work. |
| `base` | string | The real commit of the target branch the snapshot stands for. |
| `snapshot` | string | The snapshot commit, the checkout's only commit. |
| `paths` | array of strings | The paths checked out; empty for the whole tree. |
| `files` | integer | Files in the snapshot. |
| `bytes` | integer | Bytes of those files. |
| `download_bytes` | integer | Size of the download. |
| `resumed_from` | integer | Bytes an earlier, interrupted checkout had already downloaded. |
| `id` | string | The server's id for the checkout. |
| `seconds` | number | Wall-clock seconds. |

```json
{
  "url": "http://127.0.0.1:8080/demo.git",
  "path": "demo",
  "branch": "main",
  "work": "alice/amber-elm",
  "base": "5a80f18e14a38d1fddfb042e0b7724901ae7b30f",
  "snapshot": "ebf573ce69beba70f4dfe136c515dc6e2a1899f7",
  "paths": [],
  "files": 5,
  "bytes": 300010,
  "download_bytes": 300744,
  "resumed_from": 0,
  "id": "a093149cf50483d816cc",
  "seconds": 0.13
}
```

## Markdown output

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output.

Schema: [v1](https://grit-scm.com/docs/checkout/schemas/checkout/v1.json/index.md)

```markdown
## Checkout complete

- **path**: `demo`
- **work branch**: `alice/birch-pebble`
- **url**: `http://127.0.0.1:8080/demo.git`
- **target**: `main` at `5a80f18e14a38d1fddfb042e0b7724901ae7b30f`
- **snapshot**: `fd590c7ae90eb06479c29d9640d83e72504483c1`
- **paths**: `src/deep`
- **files**: 4 (300010 bytes)
- **download**: 300744 bytes (resumed at 0)
```

## Exit status

| Code | Meaning |
| --- | --- |
| `0` | The checkout was made. |
| `1` | The server offers no snapshot checkouts for the repository, has no such slice, refused the request (for example a path it doesn't have), the destination is not empty, or the download failed. |

## See also

- [`grit serve`](https://grit-scm.com/docs/serve/index.md) — serves snapshot checkouts.
- [`grit checkin`](https://grit-scm.com/docs/checkin/index.md), [`grit integrate`](https://grit-scm.com/docs/integrate/index.md), [`grit slice`](https://grit-scm.com/docs/slice/index.md) and [`grit pull`](https://grit-scm.com/docs/pull/index.md) — working in a checkout.
- [`grit clone`](https://grit-scm.com/docs/clone/index.md) — a full copy with history.

# https://grit-scm.com/docs/status/index.md

# grit status

> Show where you are and what's changed. This is what plain grit runs.

## Synopsis

```text
grit
grit status
grit st
```

## Description

The status screen is your home base. It shows, from top to bottom:

- **Where you are.** The current branch and how it compares with its target branch: ahead and behind counts, followed by ahead commits (up to ten). A branch with no commits says `no commits yet`, and a detached HEAD shows the commit it's on (short id follows `core.abbrev` and always resolves).
- **Staged** changes, which are ready to commit.
- **Changed (not staged)** files, which have been modified since they were last staged.
- **Untracked** files, which `grit` isn't tracking yet.
- **A hint** with the next command to run.

Each change has a label: `new`, `modified`, `deleted`, `renamed`, `copied`, `type changed` or `conflict`. `type changed` (`type_changed` in `--json`, Git's `T`) means the path switched between a regular file, a symlink and a submodule; a permission-only change such as `chmod +x` is `modified`.

**Submodules:** grit records gitlinks in the index but does not fetch nested repositories ([`grit clone`](https://grit-scm.com/docs/clone/index.md) leaves an empty directory and prints a note). An **uninitialized** submodule directory (no embedded `.git`) is ignored the same way Git ignores it: stray files you create inside that placeholder are not listed as modified or untracked, and `grit commit` agrees with a clean `git status`. A **checked-out** submodule with its own `.git` directory is compared by its HEAD commit and inner worktree dirtiness. Short status uses lowercase `m` when the recorded gitlink commit still matches the checkout but tracked content inside the submodule is dirty; uppercase `M` means the submodule HEAD moved. Git's `diff.ignoreSubmodules`, `submodule.<name>.ignore`, and the `ignore` key in `.gitmodules` apply to unstaged gitlink reporting the same way they do in Git (`none`, `untracked`, `dirty`, `all`; per-submodule settings override the global default). Staged gitlink updates (index commit differs from `HEAD`) stay visible even when ignore is `all`. In default untracked listing, a directory that contains an embedded repository (with or without sibling untracked files) is reported once as `?? parent/` (Git collapses the nested checkout the same way). With `--untracked all`, grit lists the embedded repository directory and any sibling files under the parent, but never files inside the nested checkout.

A tracked file that grit cannot open to compare its content (another program holds it open without sharing, or it has no read permission) is listed as `modified`, like Git does, and the rest of the status is reported as usual. When a **directory** on the path cannot be opened (for example `chmod 000` on a parent of a tracked file or an untracked tree), grit prints a `warning:` on stderr naming the path, skips that subtree, and continues — the rest of status is unchanged and exit status stays `0`. With `--json`, those warnings appear in the `warnings` array alongside the normal status fields. Commands that need the file's bytes, such as `grit add` of that path or a patch from `grit diff`, still fail with [`worktree_path_io`](https://grit-scm.com/docs/exit-codes/index.md), and `grit switch` refuses a branch that would change it.

**Index refresh:** after stat data in the work tree no longer matches `.git/index`, grit re-verifies content and normally writes the refreshed stat cache back to the index (like `git status`). If another command updates the index after status loaded it (for example a concurrent commit), grit skips the write and keeps the on-disk index that command wrote. Use [`--no-optional-locks`](https://grit-scm.com/docs/global-options/index.md) or `GIT_OPTIONAL_LOCKS=0` when a background status must not touch the index file; grit still refreshes stat data in memory so the report matches a full run. Library callers set [`StatusOptions::write_index`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/status/struct.StatusOptions.html#structfield.write_index) to `false` for the same read-only behavior without changing the process environment.

During a paused merge or grit rebase, human output also lists **Conflicts** grouped by kind (`both modified`, `both added`, …). In `--json`, each conflict is `{ "path", "kind" }` and `operation.next_steps` lists the ordered `grit` commands while an operation is paused (for example `grit diff` then `grit add .` with conflicts, or `grit merge --continue` / `grit rebase --continue` once conflicts are resolved). Use `operation.alternatives` for cancel paths such as `grit merge --abort` or `grit rebase --abort` (not part of the ordered sequence). Grit rebase sessions are detected via `.git/rebase-merge/grit-plan`.

A rebase that `git` started (`.git/rebase-merge/` or `.git/rebase-apply/` without grit's plan) is recognised too. The header names the branch being rebased (`Rebasing topic onto 1a2b3c4`), JSON `branch` reports that branch, and `operation` is `rebase-interactive` (Git's default merge backend) or `rebase` (`git rebase --apply`). Its `next_steps` end with `git rebase --continue`, because only git can resume its own todo list. `grit rebase --abort` is listed in `alternatives` and cancels it.

### Conflict kinds

Every grit command that reports conflicts (`status`, `merge`, `pick`, `revert`, `rebase` and `pull`) names each conflicted path with the same `kind`. The kind says which sides still have the path: "us" is the side you were on when the operation started (`HEAD`), "them" is the side being brought in (the merged branch, the picked or reverted commit, or the commit a rebase is replaying). So a conflict reads the same in an operation's output and in `grit status` afterwards, and matches the unmerged XY code of `git status --porcelain=v2`:

| `kind` | Human label | Git XY | Meaning |
| ------ | ----------- | ------ | ------- |
| `both_modified` | both modified | `UU` | Both sides changed the file. |
| `both_added` | both added | `AA` | Both sides added the path with different content. |
| `both_deleted` | both deleted | `DD` | Both sides removed the path. |
| `added_by_us` | added by us | `AU` | Only our side has the path. |
| `added_by_them` | added by them | `UA` | Only their side has the path. |
| `deleted_by_us` | deleted by us | `DU` | We deleted the path and they changed it. |
| `deleted_by_them` | deleted by them | `UD` | We changed the path and they deleted it. |
| `rename_rename` | — | — | Both sides renamed one file to different names (`merge`, `pick`, `revert`, `rebase` and `pull` only; `status` shows the three paths as `both_deleted`, `added_by_us` and `added_by_them`). |
| `directory_rename_moved` | moved with its directory | — | A file one side added to a directory the other side renamed was moved into the new directory; confirm the location (operations only; `status` shows the path as `added_by_us` or `added_by_them`). See [directory renames](https://grit-scm.com/docs/merge/index.md#directory-renames). |
| `directory_rename_split` | directory split up | — | A directory was spread over several directories with no clear destination, so files added to it stayed put. The path is the directory; nothing is unmerged (operations only). |
| `directory_rename_blocked` | directory move blocked | — | Files were not moved into a renamed directory because their destination is taken. The path is the destination; nothing is unmerged (operations only). |

### Interrupted rebases and history edits

A `grit rebase` or `grit history` edit that is killed after moving branches but before the files are updated leaves a recovery journal in `.git/grit/rewrite-apply/`. With optional locks enabled (the default), `grit status` finishes that work before it reports anything, and says what it did in one line above the usual screen. With `--no-optional-locks` / `GIT_OPTIONAL_LOCKS=0`, recovery is deferred and the outcome stays **Pending** until a status run that may write the index:

- **Finished the checkout.** The branches had already moved, so status puts back the files the interrupted checkout was writing and checks out the rewritten commit again. The rebase stands. Unrelated local edits are kept.
- **Rolled back.** When that checkout cannot finish (or for an interrupted `history fixup` or `absorb`), branches, index and files go back to where they were before the command. Status still succeeds.
- **Pending.** Another process holds `.git/index.lock`, so nothing is touched yet. When grit wrote a pid sidecar for that lock (default for grit-owned locks) and the recorded process has exited, the next status removes the stale lock and recovers. When no sidecar exists (for example `core.lockfilePid=false` or a foreign Git lock), the message notes the lock may be stale; run status again after the holder exits, or remove the lock only when nothing else is using the repository.

`--json` reports the outcome in `interrupted_rewrite`. The line and the field appear only on the run that finished or rolled back the work, and on every run while it is pending.

```console
$ grit status
Finished the checkout of an interrupted rebase or history edit; HEAD stays on the rewritten commits.

On feat  ·  1 ahead of master

  4f2a9c1  you  just now  feat

Nothing to commit — working tree clean.
```

Paths are shown relative to the directory you run `grit` from. Valid UTF-8 file names print as-is in human and `--markdown` output (unlike Git’s default `core.quotepath=true`, which octal-escapes non-ASCII bytes). Names that contain C0 control characters (including ESC and BEL) are still C-quoted so a malicious repository cannot inject terminal escape sequences. Set `core.quotepath=true` in config if you want Git-style octal escaping for all non-ASCII bytes. `--json` path fields are always unquoted UTF-8 strings (JSON escapes controls as `\uXXXX`).

### GitButler workspaces

[GitButler](https://gitbutler.com) applies several branches at once by checking out `gitbutler/workspace`, topped by a merge of the applied branches that it maintains itself (its message says `GitButler Workspace Commit`). That commit is GitButler's bookkeeping, so on such a workspace `grit status` lists the applied branches instead of the commits ahead, and leaves the workspace commit out of `commits` and `ahead`. The next-step hint suggests `but commit`, because [`grit commit`](https://grit-scm.com/docs/commit/index.md) refuses to commit there.

```console
$ grit status
On GitButler workspace  ·  2 branches applied  ·  3 behind origin/main

  login-form   4f2a9c1  qzvtyxkl  Ada Lovelace  2 hours ago  Validate the login form
  api-retries  9b3e0d2  mrnwkpst  Ada Lovelace  1 day ago    Retry failed API calls

Nothing to commit — working tree clean.
```

`--json` describes the workspace in `gitbutler_workspace`.

### The target branch

The target is the branch your work is compared against in the header line (`target`, `ahead`, and `behind` in JSON). It uses the first of these that exists:

1. the branch named in the `target.branch` config setting
2. `origin/master`
3. `origin/main`
4. `master`
5. `main`

To compare against something else, set it for the repository:

```console
$ grit config target.branch origin/develop
```

When the current branch has a configured upstream (`branch.<name>.remote` and `branch.<name>.merge`) that differs from the target, human output adds a second line (`↑n ↓m origin/topic`) and JSON includes an `upstream` object with the same counts relative to that tracking ref. When upstream and target resolve to the same ref, `upstream` is `null`.

On Unix, explicit path operands must be valid UTF-8. An operand containing invalid UTF-8 bytes is rejected before the command runs, with exit status **2** and no changes to the repository. Human output reports the usage error on stderr; `--json` writes an error object with `kind: "usage"` on stdout, and `--markdown` writes `**Error:**` on stdout. The argument is never replaced with a similar Unicode filename. Without a path filter, status still reports non-UTF-8 filenames using reversible `grit+pathhex:` encoding in JSON path fields, including untracked paths discovered via the index UNTR cache walk.

## Options

| Flag | Description |
| ---- | ----------- |
| `--untracked <MODE>` | How untracked paths are listed: `normal` (default) shows untracked files and collapses wholly untracked directories to a single directory entry; `all` lists every untracked file; `no` omits untracked paths. When the flag is omitted, `status.showUntrackedFiles` from config is used (Git-compatible; defaults to `normal`). |
| `--no-ahead-behind` | Skip ahead/behind rev-list walks; JSON sets `ahead`, `behind`, and upstream counts to `null`. Also skipped when `status.aheadBehind=false` in config. |
| `PATH`… | Limit the report to paths matching these pathspecs (after `--`). Uses the same pathspec rules as [`grit add`](https://grit-scm.com/docs/add/index.md). |
| `--pathspec-from-file <FILE\|->` | Read pathspecs from a file (`-` for stdin), in addition to any `PATH` arguments. |
| `--pathspec-file-nul` | `--pathspec-from-file` entries are NUL-separated (requires `--pathspec-from-file`). |
| `--ignored` | List ignored paths (traditional mode; same `!!` set as `git status --ignored --porcelain`). |
| `-s`, `--short` | Compact one-line-per-path output for humans only (two-letter staged/unstaged codes; JSON unchanged). |

From a subdirectory, short status uses cwd-relative paths; untracked directories keep a trailing slash (for example `?? ./` inside an untracked folder, or `?? ../other/` for a sibling directory).

Rename detection is on by default (Git’s `status.renames` / `diff.renames`; disable with `status.renames=false`). Human output shows renames as `old → new`; `--json` adds `old_path` on rename and copy entries.

### How changes are detected

Like Git, `grit status` compares each tracked file's size and timestamps with what the index recorded, and reads a file only when they differ. A clean tree costs one file-system lookup per tracked file, whatever the file sizes or `core.filemode`. Files written in the same second as the index (right after `git clone`, a commit or a checkout) cannot be trusted by timestamp alone: status reads them once and saves the refreshed index, so later runs skip them. Like `git status`, it may therefore rewrite `.git/index`; only the cached file information changes, never what is staged.

A changed size alone counts as a change only when nothing converts the file on the way into the repository. When a line-ending setting (`core.autocrlf`, `text`, `eol`), a clean filter, `working-tree-encoding` or `ident` applies, status reads the file and decides by content. So a file rewritten with only different line endings, which cleans to the staged content, is clean, and its index entry is refreshed. `git status` may show such a file as ` M` until its index is refreshed, while `git diff` already shows nothing.

Mode changes the checkout cannot express are not reported: with `core.filemode=false` the executable bit is ignored, and with `core.symlinks=false` a symlink checked out as a plain file holding its target is compared by content, so it shows up only when the target text changes.

See also the [global options](https://grit-scm.com/docs/global-options/index.md).

## Examples

A branch with work in progress:

```console
$ grit
On feature  ·  2 ahead of origin/main

  cf18394  ada  2 hours ago  Say hi
  9a1c2e0  ada  3 hours ago  Add a greeting test

Staged
  +  new           notes.md

Changed (not staged)
  ~  modified      main.rs

Untracked
  ?  untracked     scratch.txt

→ grit add <file> to stage  ·  grit merge --continue to finish
```

Everything committed and pushed:

```console
$ grit st
On main  ·  even with origin/main

Nothing to commit — working tree clean.
```

Behind the target after a fetch:

```console
$ grit status
On main  ·  1 behind origin/main

Nothing to commit — working tree clean.

→ grit pull to update from origin/main
```

On a local branch with no remote, when you are behind another local branch:

```console
$ grit status
On old  ·  1 behind main

Nothing to commit — working tree clean.

→ grit merge main
```

Diverged from the target:

```console
$ grit status
On main  ·  1 ahead, 1 behind origin/main

  abc1234  you  1 hour ago  Local work

Nothing to commit — working tree clean.
```

Merge in progress with a conflict:

```console
$ grit status
On main  ·  merging — resolve conflicts

Staged
  !  conflict      f

Conflicts
  both modified (1)
    f

→ grit diff
→ grit add .
```

A rebase that `git` started, stopped on a conflict:

```console
$ grit status
Rebasing topic onto 3f1c2a9

Staged
  !  conflict      f.txt

Conflicts
  both modified (1)
    f.txt

→ grit diff  ·  grit add .  ·  git rebase --continue
or grit rebase --abort
```

Check from a script whether the working tree is clean:

```console
$ grit status --json --filter .clean
true
```

List every untracked file (for staging scripts and agents):

```console
$ grit status --untracked all --json --filter .untracked
[
  "docs/a.txt",
  "docs/b.txt",
  "plain.txt",
  "src/main.rs"
]
```

With the default `normal` mode, the same tree collapses directories:

```console
$ grit status --json --filter .untracked
[
  "docs/",
  "plain.txt",
  "src/"
]
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/status/schemas/status/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `branch` | string or null | Current branch, or `null` when HEAD is detached. While a rebase is in progress (grit's or git's), the branch being rebased; `null` when the rebase started on a detached HEAD. |
| `detached` | boolean | Whether HEAD is detached. |
| `head` | string or null | Full id of the current commit, or `null` before the first commit. |
| `target` | string or null | Target branch, or `null` when none was found. |
| `ahead` | number or null | Commits on the branch that the target does not have; `null` when ahead/behind counts were skipped. |
| `behind` | number or null | Commits on the target that the branch does not have; `null` when counts were skipped. |
| `upstream` | object or null | When upstream tracking differs from `target`: `{ "ref", "ahead", "behind" }` (counts may be `null` when skipped). Always present; `null` when there is no separate upstream. |
| `commits` | array | Newest of those commits, up to ten, each using the shared [`CommitJson`](https://grit-scm.com/docs/README.md/index.md#commit-json-object-commitjson) shape (including `change_id` and `change_id_stored`). |
| `staged` | array | Staged changes with `path`, `status`, and optional `old_path` (renames/copies). |
| `unstaged` | array | Unstaged changes with `path`, `status`, optional `old_path` (renames/copies), and optional `submodule` (`new_commits`, `modified`, `untracked`) on gitlink worktree changes. |
| `untracked` | array | Untracked paths (raw UTF-8; JSON escapes control characters). With default `--untracked normal`, wholly untracked directories appear once (often with a trailing `/`); with `--untracked all`, every file path is listed. |
| `embedded_repositories` | array | Untracked nested repositories that would be recorded as gitlinks if staged. Omitted when empty. Human and `--markdown` output print a one-line **note** on stderr for each path. A symlink (including one pointing at a repository directory) is an ordinary `120000` entry and is not listed here. |
| `clean` | boolean | `true` when there is nothing to commit and nothing untracked. |
| `merging` | boolean | **Deprecated.** Prefer `operation`. `true` when a merge is in progress (`MERGE_HEAD` exists). |
| `in_progress` | array | **Deprecated.** Prefer `operation`. Stable operation ids while work is paused (for example `merge`, `rebase`). Omitted when empty. |
| `conflicts` | array | Unmerged paths. Each item is `{ "path": "<path>", "kind": "<kind>" }`, with a [conflict kind](#conflict-kinds). Omitted when empty. |
| `operation` | object or null | Primary paused operation: `{ "kind", "next_steps", "alternatives" }`. `next_steps` is the ordered sequence; `alternatives` lists mutually exclusive options (for example `grit merge --abort`). Steps are `grit` commands, except `git rebase --continue` for a rebase that git started. Omitted when no operation is in progress. |
| `ignored` | array | Ignored paths when `--ignored` was passed; omitted otherwise. |
| `stash_count` | number | Entries on the stash reflog (`0` when empty). |
| `interrupted_rewrite` | string | Recovery of a rebase or history edit that was killed after moving refs: `finished_checkout` (the rewrite stands), `rolled_back` (it was undone) or `pending` (another process holds `.git/index.lock`). Omitted when nothing was pending. |
| `gitbutler_workspace` | object | Only on a [GitButler workspace](#gitbutler-workspaces): `commit` (the workspace commit, which `head` names and `commits` and `ahead` leave out) and `heads`, the merged branch tips in the workspace's parent order, each with `commit`, `branches` (local branches pointing there, sorted; empty when none), `subject` and `ahead` (commits not on `target`, or `null` when counts were skipped). Omitted otherwise. |
| `warnings` | array | Non-fatal worktree access problems while scanning. Each item is `{ "kind", "message" }` (for example `worktree_access_failed` when a directory could not be opened). Omitted when empty. |
| `worktree_case_collisions` | array | On case-insensitive volumes: tracked path groups that share one on-disk file and block staging (`[{ "paths": ["Readme.TXT", "readme.txt"] }, …]`). Omitted when empty. Human output prints the collision warning and suggests a case-sensitive volume or `grit reset --hard` instead of `grit add`. |
| `shared` | object | Only on a [shared](https://grit-scm.com/docs/share/index.md) branch: `remote` (where the other members' heads were fetched from) and `heads`, the other members' heads, each with `user`, `tip`, `relation` to your branch (`same`, `ahead`, `behind`, `diverged` or `unknown`), and for a head that diverged from yours `divergence`: `scenario` (a stable code such as `amended_both_conflicting`; see [Divergence scenarios](https://grit-scm.com/docs/share/index.md#divergence-scenarios)), `summary`, `needs_decision`, `base`, `changes` (each commit's `change`, `subject`, and what `you` and `them` did to it), `conflicts` and `also`. Human output lists them under the branch line (`shared with bob, carol`); `--markdown` as a table. Omitted otherwise. |

Example:

```json
{
  "branch": "main",
  "detached": false,
  "head": "83352a61f6715ec3f0a297c6d6150725154fb833",
  "target": "main",
  "ahead": 0,
  "behind": 0,
  "upstream": null,
  "commits": [],
  "staged": [
    {
      "path": "staged.txt",
      "status": "added"
    }
  ],
  "unstaged": [
    {
      "path": "tracked.txt",
      "status": "modified"
    }
  ],
  "untracked": [
    "untracked.txt"
  ],
  "clean": false,
  "merging": false,
  "stash_count": 0
}
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/status/schemas/status/v1.json/index.md)
Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for headed sections that mirror the status screen:

```text
On **`feature`** · **2** ahead of `origin/main`

- `cf18394` Say hi (ada, 1 hour ago)

Staged
- **new** `notes.md`

Changed (not staged)
- **modified** `main.rs`

Untracked
- `scratch.txt`
```


## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[grit shortlog](https://grit-scm.com/docs/shortlog/index.md), [grit diff](https://grit-scm.com/docs/diff/index.md), [grit add](https://grit-scm.com/docs/add/index.md), [grit commit](https://grit-scm.com/docs/commit/index.md)

# https://grit-scm.com/docs/config/index.md

# grit config

> Read, set, list or remove configuration values.

## Synopsis

```text
grit config [<scope>] <key>
grit config [<scope>] <key> <value>
grit config [<scope>] --unset <key>
grit config [<scope>] --unset-all <key>
grit config [<scope>] --add <key> <value>
grit config [<scope>] --all <key>
grit config [<scope>] --list [<prefix>]
grit config [<scope>] --rename-section OLD --rename-section-new NEW
grit config [<scope>] --remove-section NAME
```

`<scope>` is one of `--global`, `--local`, `--system`, `--worktree`, or `-f <path>` (mutually exclusive).

## Description

Reads and writes Git configuration. `grit` uses the same config files as Git: the repository's `.git/config`, and your per-user `~/.gitconfig`. Settings you've made with Git apply to `grit`, and the other way around.

With just a key, `grit config` prints its value. By default, reads use the full config cascade (system, global, local, then command-line overrides), with later layers winning. Writes go to the repository's local config (`.git/config`). Use `--global` or `-f` to read or write a different file instead. `--local` limits reads to the repository config only (writes already target that file).

Keys are written as `section.name`, for example `user.email`.

Path strings in human, `--json`, and `--markdown` output (the `file` field on reads and list entries) use forward slashes and no Windows `\\?\` verbatim prefix, matching other grit commands.

### Settings grit uses

| Key | Used for |
| --- | --- |
| `user.name`, `user.email` | The author and committer of new commits. |
| `target.branch` | The branch [`grit status`](https://grit-scm.com/docs/status/index.md) and [`grit shortlog`](https://grit-scm.com/docs/shortlog/index.md) compare against. |
| `branch.<name>.remote` | Which remote [`grit push`](https://grit-scm.com/docs/push/index.md), [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) and [`grit pull`](https://grit-scm.com/docs/pull/index.md) use for a branch. Defaults to `origin`. |
| `branch.<name>.merge` | Which remote branch a branch pushes to and pulls from. Defaults to the same name. |
| `credential.helper` | Where HTTPS credentials are stored and looked up. See [`grit auth`](https://grit-scm.com/docs/auth/index.md). |
| `grit.githubClientId` | The GitHub OAuth app [`grit auth`](https://grit-scm.com/docs/auth/index.md) signs in with. |
| `grit.changeIds` | When true (default), [`grit commit`](https://grit-scm.com/docs/commit/index.md) adds a `change-id` header to new commits and stores derived ids on amends when the old tip had none. |
| `grit.testing.changeId` | Test-only: `content-hash` makes change ids deterministic from commit bytes; any other value is used verbatim. |
| `receive.denyNonFastForwards` | Refuse pushes that would discard commits. Enforced on the remote for [`grit receive-pack`](https://grit-scm.com/docs/receive-pack/index.md), smart HTTP, and local-path [`grit push`](https://grit-scm.com/docs/push/index.md). |
| `receive.denyDeletes` | Refuse pushes that delete branches or tags. Same enforcement as `receive.denyNonFastForwards`. |
| `receive.denyCurrentBranch` | `refuse` (default) rejects pushes to the checked-out branch. `ignore` / `false` allow the ref to move without updating the worktree. `warn` allows the update and may warn. `updateInstead` updates the worktree via the `push-to-checkout` hook or grit's built-in deploy (same checks as Git). Enforced by [`grit receive-pack`](https://grit-scm.com/docs/receive-pack/index.md), smart HTTP, and local-path [`grit push`](https://grit-scm.com/docs/push/index.md). |
| `receive.denyDeleteCurrent` | Refuse pushes that delete the branch `HEAD` points at, bare repository or not. On by default; same enforcement as the other `receive.deny*` keys. |
| `receive.fsckObjects`, `transfer.fsckObjects` | Refuse pushes that contain malformed commits, trees or tags. Tune single checks with `receive.fsck.<msg-id>` and `receive.fsck.skipList`. Enforced by [`grit receive-pack`](https://grit-scm.com/docs/receive-pack/index.md) and smart HTTP; local-path [`grit push`](https://grit-scm.com/docs/push/index.md) does not check objects. |

## Options

| Option | Description |
| --- | --- |
| `<key>` | The setting to read, set or remove. |
| `<value>` | The value to set. Omit it to read the current value. |
| `--global` | Use your per-user config instead of the repository's. |
| `--local` | Read or write only this repository's config file. Default for writes; optional for reads. |
| `--system` | Read or write the system config file (`GIT_CONFIG_SYSTEM` or `/etc/gitconfig`). |
| `--worktree` | Read or write `config.worktree` (requires `extensions.worktreeConfig` in the common config). |
| `-f`, `--file <path>` | Read or write only the given config file (no repository required). |
| `-l`, `--list` | List settings as `key=value`. Optional `<prefix>` limits to canonical keys with that prefix. |
| `--all` | Print every value for a multi-valued key (load order). |
| `--add` | Append a value without replacing existing entries. |
| `--unset` | Remove the last matching value for a key. |
| `--unset-all` | Remove every value for a key. |
| `--type bool\|int\|path` | Parse or canonicalize values like `git config --type`. |
| `--default <value>` | When reading, use this value if the key is unset (before `--type` coercion). |
| `--rename-section OLD` | Rename a section; requires `--rename-section-new NEW`. |
| `--rename-section-new NEW` | New section name for `--rename-section`. |
| `--remove-section NAME` | Delete a section and all of its keys. |
| `--dry-run` | On writes, report what would change without modifying the config file. |

### Exit codes

| Situation | Code |
| --- | --- |
| Success | `0` |
| `get` when the key is not set | `1` (human mode prints nothing; `--json` still prints a `get` object with `"value": null`) |
| Other errors (invalid key, not in a repository for `--local`, …) | `1` with an error message |

Reading or removing a key that is not set in the chosen scope is an error for `--unset`; `get` treats a missing key as exit `1` without treating it as a command failure in `--json` mode.

## Examples

Set your identity for every repository:

```console
$ grit config --global user.name "Ada Lovelace"
$ grit config --global user.email ada@example.com
```

Read a value:

```console
$ grit config user.email
ada@example.com
```

Use a different email address in one repository:

```console
$ grit config user.email ada@work.example
```

Read only the repository file (ignore global overrides for keys set locally):

```console
$ grit config --local user.email
ada@work.example
```

Edit a standalone config file:

```console
$ grit config -f ~/.gitconfig.user user.email ada@personal.example
```

List everything:

```console
$ grit config --list
user.name=Ada Lovelace
user.email=ada@example.com
core.repositoryformatversion=0
core.bare=false
remote.origin.url=https://github.com/ada/project.git
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
```

Remove a setting:

```console
$ grit config --unset target.branch
```

## JSON output

Schema: [v2](https://grit-scm.com/docs/config/schemas/config/v2.json/index.md) · [v1](https://grit-scm.com/docs/config/schemas/config/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output. The object's `action` field says what happened:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `action` | string | `get`, `get_all`, `set`, `add`, `unset`, `unset_all`, `list`, `rename_section`, or `remove_section`. |
| `key` | string | Configuration key for `get`, `set`, or `unset`. |
| `value` | string or `null` | Value for `get` or `set`. `null` when `get` did not find the key (exit `1`). |
| `scope` | string or `null` | For `get`, which layer won (`system`, `global`, `local`, `worktree`, `command`). |
| `file` | string or `null` | For `get`, source path when file-backed. |
| `line` | integer or `null` | For `get`, one-based line number in `file`. |
| `entries` | array | For `list`, each entry with `key`, optional `value`, `scope`, and optional `file`. |
| `values` | array | For `get_all`, each `{ value, scope, file?, line? }`. |
| `dry_run` | boolean | Present on write actions when `--dry-run` was used. |
| `preview` | string | Human summary of the pending change when `dry_run` is true. |
| `removed` | integer | For `unset_all`, number of values removed. |
| `old_name` | string | For `rename_section`, the previous section name. |
| `new_name` | string | For `rename_section`, the new section name. |
| `section` | string | For `remove_section`, the section that was removed. |

Reading a value:

```json
{
  "action": "get",
  "key": "user.name",
  "value": "Ada Lovelace",
  "scope": "global",
  "file": "/home/ada/.gitconfig",
  "line": 2
}
```

Missing key:

```json
{
  "action": "get",
  "key": "missing.key",
  "value": null,
  "scope": null,
  "file": null,
  "line": null
}
```

Listing values:

```json
{
  "action": "list",
  "entries": [
    {
      "key": "user.name",
      "value": "Ada Lovelace",
      "scope": "global",
      "file": "/home/ada/.gitconfig"
    }
  ]
}
```

## Markdown output

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output.

Schema: [v2](https://grit-scm.com/docs/config/schemas/config/v2.json/index.md) · [v1](https://grit-scm.com/docs/config/schemas/config/v1.json/index.md)

For `get`, markdown includes the value (when set) plus scope, file, and line. See the JSON output section for the stable field contract.




```text
| Key | Value |
| --- | --- |
| `core.repositoryformatversion` | 0 |
| `core.filemode` | true |
| `core.bare` | false |
| `core.logallrefupdates` | true |
| `user.email` | snap@example.com |
| `gc.auto` | 0 |
| `maintenance.auto` | false |
| `grit.testing.changeid` | content-hash |
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[grit auth](https://grit-scm.com/docs/auth/index.md), [grit status](https://grit-scm.com/docs/status/index.md)

# https://grit-scm.com/docs/add/index.md

# grit add

> Stage changes. With no paths, stages everything.

## Synopsis

```text
grit add [-u | --update] [--dry-run] [--hunks <id,...>] [--lines <path:start-end>] [-U<n> | --unified <n>] [--patch-file <file|->] [--executable | --non-executable] [--pathspec-from-file <file|->] [--pathspec-file-nul] [<path>...]
```

## Description

Stages changes so they show up under **Staged** in [`grit status`](https://grit-scm.com/docs/status/index.md). Pathnames in human and `--markdown` output use the same quoting rules as [`grit status`](https://grit-scm.com/docs/status/index.md) (see **Description** there). With no paths, `grit add` stages everything `grit status` reports: modified files, deleted files and untracked files. A tracked file replaced by a directory, or a tracked directory replaced by a file, is staged the way Git does it: the old path as a deletion and the new files as additions. With paths, it stages only those files, or everything under those directories.

Paths are relative to your current directory, so from inside `src/`, `grit add main.rs` stages `src/main.rs`. Paths like `../README.md` and absolute paths inside the repository work too. Attribute pathspecs such as `:(attr:myattr)` stage every matching path under the same `.gitattributes` rules as [`grit diff`](https://grit-scm.com/docs/diff/index.md) and [`grit status`](https://grit-scm.com/docs/status/index.md). A path that matches nothing is an error, and nothing is staged. A path that crosses a symlinked directory (for example `link/file` when `link` is a symlink) is an error: nothing is staged. Naming a path that exists but is excluded by `.gitignore`, `.git/info/exclude`, or `core.excludesfile` is also an error: nothing is staged and the command lists the ignored paths (pathless `grit add` still skips ignored files silently, like Git). With `core.ignorecase=true`, ignore patterns match without regard to case (see [`grit ignore`](https://grit-scm.com/docs/add/ignore.md/index.md)). On a case-folding work tree (typical macOS and Windows volumes), `grit add` keeps the spelling already recorded in the index and stores new paths under those directory names; rename a path's case only with [`grit mv`](https://grit-scm.com/docs/add/mv.md/index.md). Explicitly staging an **unmerged** path fails while Git-style conflict markers remain in the worktree file (the same rule as [`grit commit`](https://grit-scm.com/docs/commit/index.md) auto-staging); remove the markers or use a resolved file, then run `grit add` again. When a broad pathspec (for example `grit add .` after a merge) matches both resolved and still-marked unmerged files, Grit stages every path it can and exits with status **1**, naming each remaining conflict (`path: conflict markers remain; not staged`). Git may stage marker-bearing files in the same situation; Grit refuses to record conflict markers in the index.

Files with a `filter=<driver>` attribute (Git LFS, for example) are staged through the driver's clean filter, which runs through `sh` the way Git runs it. On Windows that is the `sh` bundled with Git for Windows, so you don't need it on `PATH`. If the driver sets `filter.<driver>.required=true` and the filter fails or cannot be started, `grit add` fails, says why, and stages nothing. It never stores the unfiltered file. When an optional filter fails, the file is staged unfiltered, as Git does.

Files of at least `core.bigFileThreshold` bytes (512 MiB unless configured; `k`, `m` and `g` suffixes work) are hashed and compressed as a stream straight into their own pack, as Git does, so staging a multi-gigabyte file takes a few megabytes of memory. This applies to [`grit commit`](https://grit-scm.com/docs/commit/index.md) auto-staging and to the re-hash `grit status` does after a big file's timestamp changes, too. A file that needs a clean filter, `working-tree-encoding` or line-ending conversion is read into memory whatever its size.

On filesystems where Grit sets `core.filemode=false` (typical on Windows), every new file is staged as non-executable (`100644`) even when it is a script. Use `--executable` on the paths you ship as runnable scripts so the index and commits record mode `100755`. Use `--non-executable` to clear an explicit executable bit in the index. These flags require at least one path argument.

[`grit commit`](https://grit-scm.com/docs/commit/index.md) stages every change before it records a commit, so you don't need `grit add` to commit. It's useful for starting to track a new file and checking what will be committed.

Copying or cloning another Git repository into your tree (a directory that contains its own `.git`) is recorded as a **gitlink** (mode `160000`), not as ordinary files. Clones of your repository get an empty directory at that path. When `grit add` newly records such a path, human and `--markdown` output print a **warning** on stderr; `--json` includes `embedded_gitlinks` (omitted when empty). Remove `<path>/.git` and stage again if you meant to vendor the files inside. A symlink (including one aimed at a repository directory) is staged as mode `120000` and does not trigger this warning.

Touching a tracked file's timestamp without changing its bytes or mode is not a stage: `grit add` refreshes the index stat cache silently (same as Git) and reports nothing to stage.

A directory that contains an embedded git repository (for example after `git init` inside the tree, or `cargo new` in a subdirectory) is staged as a **gitlink** (mode `160000`) when that nested repository has at least one commit checked out on its current branch. When the nested repository has **no commits yet**, `grit add` refuses with `embedded_repo_without_commit`, leaves the index unchanged, and does not record the path as a regular file.

On Unix, explicit path operands must be valid UTF-8. An operand containing invalid UTF-8 bytes is rejected before the command runs, with exit status **2** and no changes to the repository. Human output reports the usage error on stderr; `--json` writes an error object with `kind: "usage"` on stdout, and `--markdown` writes `**Error:**` on stdout. The argument is never replaced with a similar Unicode filename.

On an interactive terminal (human output, not `--json` or `--markdown`), a live **Staging** line on stderr counts the files hashed into the index; nothing is drawn when stderr is not a TTY.

## Options

| Option | Description |
| --- | --- |
| `<path>...` | Files or directories to stage. Omit to stage every change. |
| `-u`, `--update` | Stage tracked changes only (modified and deleted paths). Untracked files are left alone. With no paths, applies to the whole tree. |
| `--dry-run` | List paths that would be staged without updating the index or writing objects. |
| `--hunks` | Stage only the listed hunk ids from `grit diff --json` (`hunks[].id`). Comma-separated ids; pass the flag again to add more. Optional `-- paths` narrow the diff scan. Cannot be combined with `--patch-file`, `-u` / `--update`, or `-N` / `--intent-to-add`. |
| `--lines` | Stage only new-side line ranges from `grit diff --json` (`lines[].new`). Use `path:start-end` or `path:line` (1-based, inclusive); comma-separate or repeat the flag. Mix with `--hunks`. Same restrictions as `--hunks`. |
| `-U`, `--unified` | With `--hunks` only: unified context lines for hunk boundaries (same meaning as `grit diff -U`; default 3 when omitted). Use the same value as the diff that produced the ids. |
| `--patch-file` | Apply a unified diff to the index only (like `git apply --cached`). Use `-` for stdin. Cannot be combined with `--hunks`, paths, `-u` / `--update`, or `-N` / `--intent-to-add`. |
| `-N`, `--intent-to-add` | Record intent-to-add entries (empty blob, extended flag) instead of hashing content. |
| `-f`, `--force` | Stage ignored paths when named explicitly (instead of erroring with pathspec ignored). |
| `--pathspec-from-file` | Read additional pathspecs from a file, or `-` for stdin (same rules as Git). |
| `--pathspec-file-nul` | With `--pathspec-from-file`, entries are NUL-separated instead of line-based. |
| `--executable` | Stage listed regular files with mode `100755` in the index (requires at least one path). |
| `--non-executable` | Stage listed regular files with mode `100644` in the index (requires at least one path). |

## Examples

Stage everything:

```console
$ grit add
Staged 3 changes.
```

Stage one file and a directory:

```console
$ grit add README.md src/
Staged 2 changes.
```

Apply a patch to the index (worktree files stay as-is until you edit them):

```console
$ grit add --patch-file changes.diff
Staged 1 change.
```

Stage selected hunks by stable id (from `grit diff --json`):

```console
$ grit diff --unstaged --json -- f.txt | jq -r '.files[0].hunks[0].id'
a1b2c3d4e5f6
$ grit add --hunks a1b2c3d4e5f6 -- f.txt
Staged 1 change.
```

Stage a line range within one hunk:

```console
$ grit add --lines f.txt:10-15 -- f.txt
Staged 1 change.
```

## JSON output

Schema: [v2](https://grit-scm.com/docs/add/schemas/add/v2.json/index.md) · [v1](https://grit-scm.com/docs/add/schemas/add/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output.

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `added` | array | Newly staged paths. |
| `modified` | array | Staged modifications. |
| `removed` | array | Staged deletions. |
| `intent_to_add` | array | Paths recorded with intent-to-add. |
| `dry_run` | boolean | Whether the index was left unchanged. |
| `count` | number | Total paths touched. |
| `staged` | number | Same as `count` for successful staging. |
| `staged_hunks` | object | Path → hunk ids when `--hunks` staged something (empty object when unused). |
| `staged_lines` | object | Path → line ranges when `--lines` staged something (empty object when unused). |
| `embedded_gitlinks` | array | Nested repositories newly recorded as gitlinks. Omitted when empty. |
| `worktree_case_collisions` | array | Case-insensitive path groups that block staging (`[{ "paths": [...] }, …]`). Omitted when empty. |

```json
{
  "added": ["src/new.rs"],
  "modified": ["README.md"],
  "removed": [],
  "intent_to_add": [],
  "dry_run": false,
  "count": 2,
  "staged": 2,
  "staged_hunks": {},
  "staged_lines": {},
  "embedded_gitlinks": ["vendor-hello"]
}
```

When `--hunks` or `--lines` staged something, `staged_hunks` or `staged_lines` maps path → ids or ranges; otherwise those fields are empty objects.

Grit computes blob object ids with the same plain SHA-1 digests as Git. SHAttered test vectors (for example blobs in the `git/git` history) stage and commit normally; grit does not reject them during ingestion.

## Markdown output

Schema: [v2](https://grit-scm.com/docs/add/schemas/add/v2.json/index.md) · [v1](https://grit-scm.com/docs/add/schemas/add/v1.json/index.md)

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for an `Add` heading and how many paths were staged:

```text
- Staged **1** change
```

When there is nothing to stage and you ran `grit add` with no paths:

```text
Nothing to stage — working tree clean.
```

On a case-insensitive volume, when tracked paths collide (for example `Readme.TXT` and `readme.txt` sharing one file), `grit add` with no paths does **not** print “working tree clean”. Human and `--markdown` output show the same path-collision warning as [`grit switch`](https://grit-scm.com/docs/add/switch.md/index.md) and a hint to use a case-sensitive volume or [`grit reset --hard`](https://grit-scm.com/docs/add/reset.md/index.md). `--json` includes `worktree_case_collisions` (`[{ "paths": [...] }, …]`) when any group blocks staging.

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

`grit add` reads and writes the index while holding `.git/index.lock`, so parallel `grit add` (or `git add`) runs in one repository never undo each other: every run that exits `0` has its paths in the index. A run that cannot get the lock within `core.filesRefLockTimeout` (default 100 ms; `-1` waits forever) exits `1` with an `index.lock` error and stages nothing, so a script can simply retry it. `grit rm` follows the same rule.

With `--json`, a held index lock returns `kind: "lock_held"` and `lock.path`. When a PID sidecar exists, `lock.holder.pid` identifies the recorded process and `lock.holder.running` reports whether it was running when checked. Grit leaves both files alone. Retry after the owner finishes, or remove a stale lock after checking that no writer is running.

```json
{"error":"another process holds /work/repo/.git/index.lock; if none is running, remove the stale lock and retry","kind":"lock_held","lock":{"path":"/work/repo/.git/index.lock"}}
```

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.

## See also

[grit status](https://grit-scm.com/docs/status/index.md), [grit commit](https://grit-scm.com/docs/commit/index.md)

# https://grit-scm.com/docs/commit/index.md

# grit commit

> Stage every change and record a new commit.

## Synopsis

```text
grit commit [-a] <message>
grit commit [-a] -m <message>
grit commit --staged -m <message>
grit commit -m <message> -- [<path>…]
grit commit -F <file|->
grit commit --author "Name <email>"
grit commit --no-verify -m <message>
grit commit --dry-run -m <message>
grit commit -q -m <message>
grit commit --allow-empty -m <message>
grit commit --amend [-m <message>]
grit commit --hunks <id,...> -m <message> [-- <path>…]
grit commit --patch-file <file|-> -m <message>
```

## Description

By default, `grit commit` **auto-stages** every change in the working tree (modified, deleted and untracked files) and records a new commit on the current branch. When `status.showUntrackedFiles` is `no` (or a Git boolean false synonym such as `false` or `0`), auto-staging matches `git commit -a`: only tracked modifications and deletions are staged, and untracked paths hidden from [`grit status`](https://grit-scm.com/docs/commit/status.md/index.md) are not added. `normal`, `all`, and the default when the key is unset still auto-stage untracked files. `-a` / `--all` follows the same rule. Auto-staging refuses an embedded git repository that has no commit checked out (same rule as [`grit add`](https://grit-scm.com/docs/commit/add.md/index.md)); the commit is not created and the index is left unchanged. When auto-staging newly records a nested repository as a gitlink, grit prints the same **warning** as [`grit add`](https://grit-scm.com/docs/commit/add.md/index.md) on stderr (human and `--markdown`); `--json` includes `embedded_gitlinks` for paths introduced in that staging pass only (not when the gitlink was already in the index). Paths it cannot access because a directory is unreadable are left as-is in the index (with a `warning:` on stderr, same as [`grit status`](https://grit-scm.com/docs/commit/status.md/index.md)); other staged changes still commit. With `core.ignorecase=true` on a case-folding volume, auto-staging keeps indexed path spellings (same as [`grit add`](https://grit-scm.com/docs/commit/add.md/index.md)) and does not rewrite either spelling of a case-colliding path when the shared on-disk file already matches one of the indexed blobs (including directory-name collisions such as `Docs/` vs `docs/`); use [`grit mv`](https://grit-scm.com/docs/commit/mv.md/index.md) to change a path's case on purpose.

On a [GitButler workspace](https://grit-scm.com/docs/status/index.md#gitbutler-workspaces), `grit commit` refuses (exit **1**, `kind: "gitbutler_workspace"`) and changes nothing, because GitButler rewrites the `gitbutler/workspace` branch and would lose the commit. Commit with `but commit`, or switch to a branch first.

Use **`--staged`** to commit the index as-is without auto-staging (Git’s `git commit` without `-a`). Use **`-a` / `--all`** to force auto-staging even when `commit.autoStage=false`.

Use **trailing paths** (`grit commit -m msg -- a b`) or **`--pathspec-from-file`** to commit only those paths from the worktree while leaving other staged changes in the index (Git’s `git commit --only --` paths). Partial path commits are refused while a merge, cherry-pick, or revert is in progress.

Use **`--hunks`** with stable ids from [`grit diff --json`](https://grit-scm.com/docs/diff/index.md) to stage and commit only selected unstaged hunks in one step (like `git apply --cached` on those hunks, then commit). Optional **`-- paths`** narrow the diff scan the same way as [`grit add --hunks`](https://grit-scm.com/docs/add/index.md). Use **`--patch-file`** to apply a unified diff to the index and commit the result (`-` reads stdin). These modes do not auto-stage the rest of the worktree (same effective scope as **`--staged`**). They cannot be combined with `-a` / `--all`, **`--staged`**, or path-only commits. **`--lines`** follows the same rules as `grit add --lines` when that flag is available.

The message can be given as an argument, with `-m`, or with `-F` / `--message-file` (`-` reads stdin). Messages may start with `-` when quoted on the shell (for example `grit commit -m "-fix typo"`) or passed via `--message=-fix typo`. A positional message that starts with `-` must contain whitespace (`grit commit "-fix typo"`): a single hyphen-leading word such as `-q`, `--bogus` or `--opt=value` is treated as an unknown flag and rejected with exit status `2` before anything is staged or committed, so a misspelled or unsupported flag never becomes the commit message. Pass such a message with `-m` (`grit commit -m --bogus`). Message text is normalized with Git-style stripspace before hooks run (leading/trailing blank lines collapse; a trailing newline is added). A message with several lines is recorded as is after normalization; its first line is the subject that [`grit log`](https://grit-scm.com/docs/log/index.md) shows. A normal commit needs a message: without one, `grit commit` stops with an error and does not change the index or working tree. You cannot combine `-m`, a positional message, and `--message-file`.

Use **`--dry-run`** to preview what would be committed: path list, parents, and author, without writing objects, updating refs, running hooks, or changing the index on disk. The preview includes executable-bit-only changes the same way the commit does, and lists modified or deleted files whose names are not valid UTF-8 under the same stored paths as the commit's `files`. Dry-run returns the same errors as a real commit for nothing-to-commit and unmerged index.

A commit either completes or changes nothing. Pressing Ctrl+C, or sending `SIGTERM` or `SIGHUP` on Unix, while the index is being updated or files are being checked out stops the commit with `error: operation cancelled`; `HEAD`, the index and the work tree are left as they were before the command started, no `.git/index.lock` is left behind, and the same commit can simply be run again. This works the same in a Windows console, where Ctrl+Break counts as Ctrl+C. A second interrupt terminates grit at once, without that cleanup; only `SIGKILL` skips rollback. Auto-staging may leave unreachable loose blobs in the object database if you interrupt mid-write; they are harmless. In the rare case that a path cannot be put back during checkout rollback, the error has kind `checkout_incomplete` and lists those paths in `paths`.

With `--amend`, `grit commit` replaces the **tip** commit on the current branch instead of adding a new one. It does not reword or squash older commits; positional arguments are always the commit message, not a revision (for example `grit commit --amend HEAD~1` records the message `HEAD~1`, it does not amend that commit). The new commit keeps the previous tip's parents and author; the committer and commit time come from your identity and `GIT_COMMITTER_DATE` as usual. If you omit the message while amending, the previous commit message is reused. Amending with no staged changes is allowed when the tree is unchanged (Git-compatible). You cannot amend on a branch that has no commits yet.

The author and committer come from `user.name` and `user.email` (see [`grit config`](https://grit-scm.com/docs/config/index.md)), or from `GIT_AUTHOR_NAME` / `GIT_AUTHOR_EMAIL` and `GIT_COMMITTER_NAME` / `GIT_COMMITTER_EMAIL`. Use `--author "Name <email>"` (or a bare email) to override the author for one commit; the committer line still comes from your committer identity. If none of those are set and no repo or global `user.email` is configured, `grit commit` fails with an identity error instead of inventing an address (the same sources Git uses before it refuses with “unable to auto-detect email address”). Set identity once with:

```console
$ grit config --global user.name "Your Name"
$ grit config --global user.email "you@example.com"
```

To set the recorded time, use the `GIT_AUTHOR_DATE` and `GIT_COMMITTER_DATE` environment variables, or pass `--date` for the author timestamp on this commit (Git date formats, RFC 3339, `@epoch`, and the same loose strings Git accepts). On amend, the author line is taken from the commit being replaced unless you pass `--author` or `--reset-author`.

Repeat `--trailer key=value` (or `key: value`) to append trailers the same way `git interpret-trailers` would. `-s` / `--signoff` adds a `Signed-off-by` line for the committer. `--reset-author` sets the author to the committer with a fresh author date (also when amending). `-C` / `--reuse-message <commit>` reuses that commit's message and author; it is a copy and gets a new change id. `-S` / `--gpg-sign` and `--no-gpg-sign` override `commit.gpgsign` for one commit.

When `commit.gpgsign` is true (or `commit.gpgSign`), `grit commit` signs the new commit object the same way Git does: OpenPGP and X.509 via your configured `gpg`/`gpgsm` program, or SSH via `ssh-keygen -Y sign` when `gpg.format` is `ssh`. Signing uses `user.signingkey` and the same `gpg.*` settings Git reads. [`grit merge`](https://grit-scm.com/docs/merge/index.md) and [`grit pick`](https://grit-scm.com/docs/pick/index.md) honor the same policy when they create commits.

`grit commit` fails when there's nothing to commit (except when amending with an unchanged tree, or when you pass `--allow-empty`), when no message is provided (for a normal commit), and when the index still has **unmerged** paths after staging (for example when a merge conflict is not fully resolved in the working tree). With **`commit.autoStage=false`** or **`--staged`**, an empty index while the work tree still has changes is **`nothing staged to commit`** (not “working tree clean”): human output names how many files are unstaged or untracked and suggests `grit add` or `grit commit -- <path>`. With **`--json`**, `kind` is `nothing_staged` (dirty work tree, nothing staged) or `nothing_to_commit` (genuinely clean). On a case-insensitive volume, when tracked paths such as `Readme.TXT` and `readme.txt` share one on-disk file and cannot be staged, commit fails with **`kind` `worktree_case_collision`** (library [`CommitError::WorktreeCaseCollision`](https://grit-scm.com/docs/library/index.md)) instead of `nothing_staged` or `nothing_to_commit`; human and `--markdown` output name the colliding paths and suggest a case-sensitive volume or [`grit reset --hard`](https://grit-scm.com/docs/commit/reset.md/index.md)—not `grit add`. Auto-staging does **not** treat a conflicted file as resolved while Git-style conflict markers (`<<<<<<<`, `=======`, `>>>>>>>`) remain in the worktree copy — edit the file to remove them, then run `grit commit` again. The same check applies when a file's conflict stages were dropped without editing it (for example by `git restore --staged` after a merge, pick, revert, rebase or `stash pop`): the commit fails with `kind` `unmerged_paths`, names the file, and leaves the index, `HEAD` and any operation state untouched, so `--abort` still works. Marker text that is already in the committed version of the file (for example an example in documentation) is not refused, but any new conflict block next to it is. Validation failures such as a missing message or empty message leave the index and working tree unchanged. When auto-staging finds changes that cancel out against `HEAD` (for example a new file that was staged and then deleted, or a staged edit that was reverted in the working tree), `grit commit` still records the staged index before reporting nothing to commit, so the index matches `HEAD` and `git status` is clean afterward; `--dry-run` never writes the index.

On a **detached HEAD** (for example after [`grit switch --detach`](https://grit-scm.com/docs/switch/index.md)), `grit commit` records a new commit and moves `HEAD` to it without updating any branch — the same as `git commit` in that state. Use [`grit switch -c <name>`](https://grit-scm.com/docs/switch/index.md) afterward to name the branch if you want to keep the work. With `--json`, a detached-HEAD commit reports `"branch": null` and `"detached": true`. A failed commit (missing message, nothing to commit) does not advance `HEAD` or stage your working tree on detached HEAD, the same as on a branch.

Auto-staging records the modes Git would. With `core.symlinks=false` (common on Windows, where Git and Grit check symlinks out as plain files holding the link target), a symlink stays a symlink (`120000`): an untouched link is not part of the commit, and editing the file stages the new link target. With `core.filemode=false`, a tracked file keeps the executable bit the index already has.

Symlinks to files, directories and missing paths are staged as link-target bytes, without clean filters or line-ending conversion. `--dry-run` uses the same comparison in serial and parallel scans: an unchanged tree returns `nothing_to_commit` under `--json`, and retargeted links appear in the preview just as they will in the commit. Preview leaves the index, refs and stored objects unchanged.

With `--allow-empty`, grit records a new commit whose tree matches the parent even when the working tree is clean (staging still runs first, the same as any other commit). Use this to mark a point in history (for example to trigger CI) without changing files. The resulting commit is valid for Git the same way as `git commit --allow-empty`.

When a merge is in progress (`MERGE_HEAD` is present) and every conflict is resolved in the index, `grit commit` records a **merge commit** with two parents (your branch tip and the merged tip) and clears merge state the same way Git does after `git commit`.

When a cherry-pick or revert is paused (`CHERRY_PICK_HEAD` or `REVERT_HEAD`) and conflicts are resolved, `grit commit` finishes the current step the same way `git commit` does during `git cherry-pick`: it keeps the picked commit’s **author** and **author date** (revert keeps the committer as author), uses `MERGE_MSG` when you omit `-m`, clears replay state, and writes a reflog entry `commit (cherry-pick): …` for picks. Auto-staging applies as usual; you do not need `grit pick --continue` after a resolving commit unless more steps remain in a multi-commit sequence.

During a **rebase conflict stop** (grit-owned `.git/rebase-merge/` with `grit-plan`), a resolving `grit commit` records the replayed pick on the detached replay parent: it keeps that commit’s **author**, **change id**, and `MERGE_MSG` when you omit `-m`, and leaves the rebase session in place so `grit rebase --continue` replays only the remaining commits.

`pre-commit`, `prepare-commit-msg` and `commit-msg` hooks run, in that order, before the commit object is written when they are installed (config `hook.*` entries or scripts under the hooks directory). `prepare-commit-msg` gets `.git/COMMIT_EDITMSG` and where the message came from: `message` for `-m`, `-F` or the argument, `commit <oid>` when `--amend` or a reused message keeps a commit's message, `merge` when finishing a merge with its `MERGE_MSG`, and `squash` after `grit merge --squash`. Both message hooks may edit the file, and the commit records what they leave. Pass `--no-verify` to skip `pre-commit` and `commit-msg`; `prepare-commit-msg` and `post-commit` still run, matching Git. A `pre-commit`, `prepare-commit-msg` or `commit-msg` hook that exits non-zero or cannot be started aborts the commit, and the error names the hook and its exit status (or the OS error). The index and working tree stay as they were before the attempt (including a deliberate staged/unstaged split on the same file and untracked paths not yet in the index). In human mode the hook's output appears on stderr as it runs, followed by the error. With `--json` the failure is a structured error with `kind: "hook_failed"` and a `hook` object carrying `name`, `status`, and the hook's captured `stdout` and `stderr`; `--markdown` prints the error followed by the captured output in `text` blocks. `post-commit` never changes the result: the commit is already written, so a non-zero exit is ignored, and a hook that cannot be started prints a warning on stderr (`hook_not_run`). With `--amend`, grit then runs `post-rewrite amend` with `<old commit> <new commit>` on stdin, as Git does (library callers can skip it with `CommitRequest::post_rewrite`); like `post-commit`, its outcome never changes the result. Dry-run skips all hooks. See [`grit hooks`](https://grit-scm.com/docs/commit/hooks.md/index.md).

After a successful commit (not `--dry-run`), grit checks `gc.auto` and `gc.autoPackLimit` like `git commit` does and, once loose objects or packs pile up, starts background maintenance with one stderr line in human mode. See [Automatic maintenance](https://grit-scm.com/docs/commit/gc.md/index.md#automatic-maintenance).

For a `pre-commit` hook that prints a line on each stream and exits 1, `grit commit --json` prints (exit status 1):

```json
{
  "error": "hook pre-commit failed with exit status 1",
  "kind": "hook_failed",
  "hook": {
    "name": "pre-commit",
    "status": 1,
    "stdout": "stdout from hook\n",
    "stderr": "lint failed: bad stuff\n"
  }
}
```

### Change ids

Every commit `grit commit` creates gets a `change-id` header (reverse-hex by default) that stays with the same logical change across amends. Commits created without the header still have a deterministic id derived from the commit object id (Jujutsu-compatible); amending such a commit stores that derived value. Set `grit.changeIds=false` to omit the header (Git byte-identical commits for tests or importers that reject extra headers). See [Change ids](https://grit-scm.com/docs/library/change-ids/index.md) for policy, testing knobs, and library APIs.

On an interactive terminal (human output, not `--json`, `--markdown` or `-q`), a live **Staging** line on stderr counts the files auto-staged before the commit; nothing is drawn when stderr is not a TTY.

## Options

| Option | Description |
| --- | --- |
| `<message>` | The commit message. A single hyphen-leading word is rejected as an unknown flag; use `-m` for it. |
| `-q`, `--quiet` | Print nothing on success in human mode. `--json` and `--markdown` output is unchanged; errors still go to stderr. |
| `-m`, `--message <message>` | The commit message, as an option (repeatable; each `-m` starts a new paragraph separated by a blank line, like Git). Do not combine with `-F` / `--message-file` or a positional message. Optional with `--amend` (keeps the previous message when omitted). |
| `-F`, `--message-file <file\|->` | Read the commit message from a file, or from stdin when the path is `-`. |
| `--author <ident>` | Author for this commit (`Name <email>` or bare email). Committer unchanged. |
| `--no-verify` | Skip `pre-commit` and `commit-msg` hooks (`prepare-commit-msg` still runs). |
| `--dry-run` | Preview the commit; no objects, refs, hooks, or on-disk index changes. |
| `-a`, `--all` | Stage every change first, then commit. Conflicts with `--staged` and path arguments. |
| `--staged` | Commit only what is already in the index (no auto-stage). Conflicts with `-a` and path arguments. |
| `--hunks` | Commit only listed hunk ids from `grit diff --json` (comma-separated, repeatable). Optional `-- paths` narrow the diff scan. Conflicts with `--patch-file`, `--lines`, `-a`, and `--staged`. |
| `--patch-file` | Apply a unified diff to the index, then commit (`-` for stdin). Conflicts with `--hunks`, `--lines`, `-a`, and `--staged`. |
| `--lines` | Commit only line ranges from the unstaged diff (same format as [`grit add --lines`](https://grit-scm.com/docs/add/index.md)). Mix with `--hunks`. Optional `-- paths`. Conflicts with `--patch-file`, `-a`, and `--staged`. |
| `--pathspec-from-file`, `--pathspec-file-nul` | Same as on [`grit add`](https://grit-scm.com/docs/add/index.md): read pathspecs from a file; combine with trailing `PATH` arguments. |
| `--amend` | Replace the tip commit on the current branch. |
| `--allow-empty` | Record a commit even when staged content matches the parent tree (empty tree change). |
| `--dry-run` | Stage in memory and list the files the commit would change, without writing objects, the index or refs, or running hooks. |
| `-F`, `--message-file <path>` | Read the commit message from a file; use `-` for stdin (same body rules as `-m`). |
| `--author <author>` | Override the author line (`Name <email>`); committer identity is unchanged unless you also set `GIT_COMMITTER_*`. |
| `--no-verify` | Skip `pre-commit` and `commit-msg` hooks; `prepare-commit-msg` and `post-commit` still run on a real commit. |

## Examples

Commit everything:

```console
$ grit commit "Add the greeting"
[main 217c6f9] Add the greeting
2 changes committed
```

Preview before committing:

```console
$ grit commit --dry-run -m "Add the greeting"
Would commit 2 files
  M README
  A src/main.rs
```

The same, written the way you'd write it for `git`:

```console
$ grit commit -am "Add the greeting"
```

A longer message with a body:

```console
$ grit commit -m "Add the greeting

Prints hi on startup so we know the binary runs."
```

Amend the latest commit after fixing staged files:

```console
$ grit commit --amend -m "Add the greeting (fixed typo)"
```

Record an empty commit on a clean tree:

```console
$ grit commit --allow-empty -m "Trigger CI"
[main a1b2c3d] Trigger CI
0 changes committed
```

Commit only staged paths when another file is staged but should not be in this commit:

```console
$ grit add baz
$ grit commit -m "file only" -- file
```

Commit the index without auto-staging (with `commit.autoStage=true`, or always with `--staged`):

```console
$ grit add a.txt
$ grit commit --staged -m "index only"
```

## JSON output

Schema: [v2](https://grit-scm.com/docs/commit/schemas/commit/v2.json/index.md) · [v1](https://grit-scm.com/docs/commit/schemas/commit/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `oid` | string or omitted | Full commit object id; omitted when `dry_run` is true |
| `branch` | string or null | Short name of the branch the commit advanced (e.g. `main`); `null` on a detached `HEAD` |
| `detached` | boolean | `true` when the commit was made on a detached `HEAD` (only `HEAD` moved) |
| `subject` | string | First line of the commit message |
| `changes` | number | Path changes vs the parent commit tree |
| `amended` | boolean | `true` when `--amend` was used |
| `dry_run` | boolean | `true` when `--dry-run` was used |
| `scope` | string | `auto_stage`, `staged`, `paths`, or `patch` — how the index was prepared |
| `dry_run` | boolean | `true` when `--dry-run` was passed |
| `files` | array | Path-level changes (`path`, `status`, optional `old_path` for renames). Each `path` uses the same stored encoding as [`grit status`](https://grit-scm.com/docs/commit/status.md/index.md) JSON (UTF-8 when valid, else `grit+pathhex:`). |
| `change_id` | string or null | Stored `change-id` header on the new commit, or null when absent or dry-run (see [Change ids](https://grit-scm.com/docs/library/change-ids/index.md)) |
| `parents` | array of strings | Parent commit OIDs that would be stored |
| `author` | object | `name`, `email`, and `date` (RFC 3339, same shape as [`grit log`](https://grit-scm.com/docs/log/index.md) / [`grit show`](https://grit-scm.com/docs/show/index.md)) |
| `hooks_run` | array of strings | Hook names that ran, in order (`pre-commit`, `prepare-commit-msg`, `commit-msg`, `post-commit`, and `post-rewrite` after `--amend`); empty on dry-run |
| `embedded_gitlinks` | array | Nested repositories newly recorded as gitlinks during auto-staging for this commit. Omitted when empty. |

Example:

```json
{
  "oid": "92501f188ae0815af09a0cef6e121eddda4113cf",
  "branch": "main",
  "detached": false,
  "subject": "second",
  "changes": 1,
  "amended": false,
  "dry_run": false,
  "scope": "auto_stage",
  "files": [{ "path": "b.txt", "status": "M" }],
  "change_id": "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
  "parents": ["abc123…"],
  "author": {
    "name": "Your Name",
    "email": "you@example.com",
    "date": "2023-11-14T22:13:20Z"
  },
  "hooks_run": ["pre-commit", "post-commit"]
}
```

Human output includes a `hooks:` line only when at least one hook ran.

Preview a commit without writing (message required):

```console
$ grit commit --dry-run -m "preview"
```

Read the message from stdin (agents):

```console
$ printf '%s\n' "Subject line" "" "Body." | grit commit --staged -F -
```

## Markdown output

Schema: [v2](https://grit-scm.com/docs/commit/schemas/commit/v2.json/index.md) · [v1](https://grit-scm.com/docs/commit/schemas/commit/v1.json/index.md)
Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a `Commit` heading, branch and commit summary, and change count:

```text
- **`main`** · `9244cbd` — third
- **3** changes committed
```

With `--amend`, the first bullet notes the amended branch tip:

```text
- Amended **`main`** at `2fb4e89` — third (amended)
- **3** changes committed
```

With `--dry-run`, output lists the paths that would be committed instead of a new OID.


## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

An unknown flag is a usage error even when it lands where the positional message goes; nothing is staged or committed:

```console
$ grit commit --bogus
error: unexpected argument '--bogus' found

  tip: to use '--bogus' as text, pass it with '-m --bogus'

Usage: grit commit [OPTIONS] [MESSAGE] [-- <PATH>...]

For more information, try '--help'.
```

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.

When another process holds `.git/index.lock`, `grit commit` exits `1` with `kind` `lock_held` under `--json`. `lock.path` names the lock file, and `lock.holder` gives its owning process and whether it still runs when `core.lockfilePid` recorded one; the message says whether the lock looks live or stale. Every scope checks the lock before it creates the commit, so on this error no commit was recorded and `HEAD`, the branch, the reflog and the index are unchanged. It is safe to retry once the other process finishes. Path commits (`-- paths`), `--hunks` and `--patch-file` take the lock before writing anything at all; auto-staging may leave an unreferenced blob behind for a later `git gc` to prune. Ordinary commands never remove a foreign lock; interrupted rewrite recovery may remove a stale grit index lock when its pid sidecar shows the holder exited.

```console
$ grit commit -m "fix" -- f1.txt
error: another process holds /work/repo/.git/index.lock; if none is running, remove the stale lock and retry
$ grit commit -m "fix" --json -- f1.txt
{"error":"another process holds /work/repo/.git/index.lock; if none is running, remove the stale lock and retry","kind":"lock_held","lock":{"path":"/work/repo/.git/index.lock"}}
```

Several `grit commit` processes can run in one checkout at once, for example parallel jobs each committing their own `-- paths`. The index lock serializes them: each one either records a commit with its own message and only its own paths, or fails with `lock_held` and changes nothing. The message always comes from `-m`, `-F` or the positional argument; `.git/COMMIT_EDITMSG` is read back only after a `prepare-commit-msg` or `commit-msg` hook ran, so one process never records another's message. A commit is built on the `HEAD` it read first: if another tool moves the branch before the commit lands, `grit commit` fails with `ref 'refs/heads/<branch>' did not match expected state` (exit `1`) instead of recording a commit that would undo the other change.


## See also

[grit add](https://grit-scm.com/docs/add/index.md), [grit status](https://grit-scm.com/docs/status/index.md), [grit log](https://grit-scm.com/docs/log/index.md), [grit config](https://grit-scm.com/docs/config/index.md)

# https://grit-scm.com/docs/diff/index.md

# grit diff

> Show uncommitted, staged, commit, or range changes.

## Synopsis

```text
grit diff [--staged] [--unstaged] [--against <ref>] [<commit> [<commit>]]
  [--pathspec-from-file <file|->] [--pathspec-file-nul] [-- <path>…]
grit diff [--staged] [--unstaged] [--against <ref>] [<base>..<tip>]
  [--pathspec-from-file <file|->] [--pathspec-file-nul] [-- <path>…]
grit diff --no-index <path> <path>
```

## Description

With no argument, shows every uncommitted change: the working tree and index together, compared with the last commit (`HEAD`). Pass `--staged` to compare only the index to `HEAD` (staged changes). Pass `--unstaged` to compare only the working tree to the index (changes not yet staged). Pass `--against <ref>` to compare the working tree to another ref’s tree instead of `HEAD` (useful for “what changed since `main`?” while keeping a single commit argument as “show this commit’s patch”). Untracked paths are not diff entries—they appear only in [`grit status`](https://grit-scm.com/docs/diff/status.md/index.md). When a tracked path lives under a worktree directory grit cannot read (for example permission denied), grit warns with the path and continues with the rest of the diff; pathspecs limit the scan so unreadable directories outside the selection are not touched.

Symlinks are compared using the bytes of their link targets, including links to directories and missing paths. Clean filters and line-ending conversion do not apply to link targets. Serial and parallel scans produce the same changes, including on large worktrees; an unchanged symlink does not make a clean tree dirty. With `core.symlinks=false`, regular files checked out as symlink placeholders retain the link mode recorded in the index.

With one commit, shows the change that commit introduced (its first parent’s tree against its own tree). Commit, range, **staged**, and **unstaged** diffs detect renames by default (Git `-M50`): a move with small edits appears as one `renamed` file instead of a full delete and add. With two commits, or a two-dot range such as `A..B`, shows the tree diff between those commits with the same rename detection. A three-dot range `A...B` diffs from the merge base of `A` and `B` to `B`. When many add/delete candidates remain after exact and basename pairing, inexact rename detection may be skipped because of `diff.renameLimit`; grit then prints a one-line notice on **stderr** with the candidate counts, the configured limit, and a suggested limit to retry with (`grit -c diff.renameLimit=<n>`). JSON and Markdown output are unchanged.

Pass one or more paths after `--` (or as trailing arguments when unambiguous) to limit any diff form to those paths—the same pathspec rules as [`grit log`](https://grit-scm.com/docs/diff/log.md/index.md). For commit and tree diffs, that limit is applied before rename detection, so a pathspec that matches only one side of a move is reported as an add or delete, same as Git. Pathspec magic works as in Git, including attribute selection from `.gitattributes`: `grit diff -- ':(attr:diff=rust)'` limits the diff to files with `diff=rust`, and `':(exclude,attr:-diff)'` drops files marked `-diff`. A single positional argument that is neither a revision nor a range is still treated as a worktree path for unstaged changes (`grit diff a.txt`). If paths after `--` or entries from `--pathspec-from-file` are supplied, an unknown revision is reported as a revision error. With **two** positional arguments, both are revisions (tree diff); a path limit requires `--` (for example `grit diff HEAD~1 HEAD -- f`) or the `commit known-path` form when the second token names a file in the repo (`grit diff HEAD f`).

Each file starts with its path (UTF-8 names print literally; C-quoted only when the name contains control characters, unless `core.quotepath=true`), and each hunk with its position. Lines have two number columns, the line number before and after the change. In a terminal, removed lines are red, added lines are green, and the words that changed within a line are highlighted when the diff touches at most 64 changed files; larger tree and commit-range diffs stay line-level for throughput. When the output isn't a terminal, or `NO_COLOR` is set, lines are marked with `-` and `+` instead. `--json` and `--markdown` use line-level hunks only (no word-level `emphasis` segments) so large commit-range diffs stay fast. Tree and commit diffs that change 16 or more files honor the global `--threads` flag and `index.threads` when loading blobs and computing line diffs; smaller ones run on one thread, which is faster than starting workers. Three lines of unchanged context are shown around each change. Binary files print `Binary file differs` when the blob changed (mode-only binary changes show mode lines only).

`<commit>` can be anything that names a commit: a full or short commit id, a branch or tag name, or an expression like `HEAD~2`.

In a shallow clone, a commit listed in `.git/shallow` is diffed like a root (against the empty tree), even when its object still names a parent that was not fetched.

## Options

| Option | Description |
| --- | --- |
| `-p`, `--patch` | Full patch (the default). Mutually exclusive with the other format flags below. |
| `--stat` | Per-file change counts with `+`/`-` bars and a summary line (like `git diff --stat`). Mutually exclusive with the other format flags below. |
| `--numstat` | Machine-readable `insertions<TAB>deletions<TAB>path` lines (`-<TAB>-` for binary). |
| `--shortstat` | Only the summary line (`N files changed, …`). |
| `--name-only` | Changed paths, one per line. |
| `--name-status` | Status letter and path(s) per line (`M`, `A`, `R100<TAB>old<TAB>new`, …). |
| `--patch-text` | Git-apply-compatible unified patch on stdout (`git diff --binary` shape): `index` lines carry abbreviated preimage and postimage blob ids (including unstaged worktree content, hashed at render time), and binary files appear as `GIT binary patch` sections so `git apply --index` reproduces them. Human output only; not combinable with `--json` or `--markdown`. |
| `-M`, `--find-renames[=<n>]` | Detect renames (default similarity 50). Long form requires `=` when a threshold is given. |
| `--no-renames` | Do not detect renames. |
| `--diff-algorithm <algo>` | Line diff algorithm (`myers`, `minimal`, `patience`, `histogram`). |
| `--diff-filter <letters>` | Limit to change types (`A` added, `D` deleted, `M` modified, `R` renamed, …). |
| `-w`, `--ignore-all-space` | Ignore whitespace when comparing lines. |
| `-b`, `--ignore-space-change` | Ignore changes in the amount of whitespace. |
| `--ignore-blank-lines` | Ignore changes whose lines are all blank. |
| `-U`, `--unified <n>` | Lines of context around each hunk when the output is a patch (bare `-U` means 3). |
| `-M`, `--find-renames[=<n>]` | Detect renames; optional similarity threshold (`50` default, or `50%`). Attached `-M30` is accepted. |
| `--no-renames` | Do not detect renames (show separate delete and add entries). |
| `--diff-algorithm <algo>` | Line diff algorithm (`myers`, `patience`, `histogram`, …); overrides `diff.algorithm`. |
| `--diff-filter <letters>` | Limit output to change types (`A` added, `D` deleted, `M` modified, `R` renamed, …). |
| `-w`, `--ignore-all-space` | Ignore whitespace when comparing lines. |
| `-b`, `--ignore-space-change` | Ignore changes in the amount of whitespace. |
| `--ignore-blank-lines` | Ignore changes whose lines are all blank. |
| `-W`, `--function-context` | Expand patch hunks to enclosing function boundaries (Git `-W`). |
| `-p`, `--patch` | Unified patch output (default when no other format flag is set). |
| `--exit-code` | Exit with status **1** when there are changes (for scripts); **0** when clean. |
| `--quiet` | Print nothing; implies `--exit-code`. |
| `--staged`, `-S` | Staged changes only (index vs `HEAD`). Cannot be combined with `--unstaged`, commit arguments, or `--against`. Optional path limits after `--` are allowed. |
| `--unstaged` | Unstaged changes only (worktree vs index). Cannot be combined with `--staged`, commit arguments, or `--against`. Optional path limits after `--` are allowed. |
| `--against <ref>` | Compare the worktree to `<ref>`’s tree instead of `HEAD`. No commit arguments. Optional path limits after `--` are allowed. |
| `--no-index` | Compare two filesystem paths without a repository: two files, two directories (recursive), or a file and a directory (compared with `directory/<file name>`, as Git does). Takes exactly two paths and cannot be combined with `--staged`, `--unstaged`, `--against` or commits. Exits 1 when they differ, as with `--exit-code`. |
| `--exit-code` | Exit with status 1 when there are changes and 0 when there are none; errors exit 2. |
| `--quiet` | Print nothing and exit as with `--exit-code`. |
| `<commit>` | One commit (that commit’s patch), two commits (tree diff), or a range `A..B` / `A...B`. Omit for uncommitted changes. |
| `--pathspec-from-file <file\|->` | Read pathspecs from a file (`-` for stdin), in addition to argv paths after `--`. |
| `--pathspec-file-nul` | `--pathspec-from-file` entries are NUL-separated. |
| `<path>…` | After `--`, limit the diff to these paths (all forms above, including `--staged`). |

## Examples

What have I changed since the last commit?

```console
$ grit diff

main.rs
@@ -1 +1 @@
 1    │ - fn main() {}
    1 │ + fn main() {
    2 │ +     println!("hi");
    3 │ + }
```

What is staged but not yet committed?

```console
$ grit diff --staged
```

What changed in the working tree since the last `grit add`?

```console
$ grit diff --unstaged
```

What changed between two commits?

```console
$ grit diff HEAD~1 HEAD
$ grit diff HEAD~1..HEAD
```

Only one file between two branches:

```console
$ grit diff main feature -- README.md
```

What does my worktree look like compared to `main`?

```console
$ grit diff --against main
```

What did the commit before the last one change?

```console
$ grit diff HEAD~1
```

List the files changed by a commit:

```console
$ grit diff v0.1 --json --filter '.files[].path'
[
  "README.md",
  "main.rs"
]
```

Write the staged changes, binary files included, as a patch `git apply` can replay elsewhere:

```console
$ grit diff --staged --patch-text
diff --git a/b.bin b/b.bin
new file mode 100644
index 0000000000000000000000000000000000000000..eaf36c1daccfdf325514461cd1a2ffbc139b5464
GIT binary patch
literal 4
Lc${NkWMT#Y01f~L

literal 0
Hc$@<O00001

$ grit diff --staged --patch-text > ../change.patch
$ cd ../other && git apply --index ../change.patch
```

Compare two files or directories that aren't in a repository:

```console
$ grit diff --no-index ./old ./new
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/diff/schemas/diff/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `changed` | boolean | Whether any selected change exists (matches `--exit-code` / `--quiet`). |
| `files` | array | Changed files (see nested fields below). |
| `totals` | object | Present for `--stat`, `--numstat`, and `--shortstat`: `files_changed`, `insertions`, `deletions`. |
| `changed` | boolean | Whether any change was selected; the same answer `--exit-code` gives as an exit status. |

Each `files[]` entry includes `path`, `status`, `binary`, optional `old_path` (renames), optional `similarity` (0–100 on renames/copies), optional `combined_status` (per-parent combined letters such as `MM` or `DD` on merge `--cc` / `--name-status` output; omitted on ordinary two-tree diffs), optional `stat` (`{ "insertions", "deletions" }` when line counts were computed; omitted when `binary` is true), optional `old_size` / `new_size` (byte lengths on each side when `binary` is true, matching `--stat`’s `Bin old -> new bytes` line), optional `old_mode` / `new_mode`, optional `old_encoding_lossy` / `new_encoding_lossy`, and `hunks` only for the default patch format.

Nested fields include `files[].status` (`added`, `modified`, `deleted`, `renamed`, and so on; `type_changed`, Git's raw `T`, when a path switches between a regular file, a symlink and a submodule, reported the same way for unstaged, staged, worktree-vs-commit and commit-to-commit diffs, while a permission-only change stays `modified`), optional `files[].old_path` when `status` is `renamed`, `hunks[].old_start` / `new_start` / `old_lines` / `new_lines`, optional `hunks[].id` (twelve lowercase hex characters; present on `--staged` and `--unstaged` patch JSON for stable hunk selection), optional `hunks[].index` (0-based hunk index within the file; same scopes as `id`), optional `hunks[].context` (the `@@` function-name suffix from the path's `diff` driver, or the enclosing definition when `-W` / `--function-context` is set), `hunks[].lines[].kind` (`context`, `add`, or `del`), line numbers on `old` and `new`, a compact `text` string per line (or `segments` with optional `emphasis` only when intra-line word highlights are present), and `no_newline_at_eof` when that side lacks a trailing newline (Git’s `\ No newline at end of file`). JSON is written in compact form (no pretty-printing). When `files[].binary` is true, `hunks` is always an empty array — blob bytes are never included in JSON (use human or `--markdown` output for the “Binary file differs” note). For unstaged and other worktree-sourced sides, line text is normalized to repository form (`.gitattributes` / `core.autocrlf`) before diffing, so trailing `\r` from CRLF checkouts does not appear in line `text`. Commit and staged diffs compare stored blobs and may still show carriage returns when the on-disk object bytes differ. When file bytes are not valid UTF-8 and the file is treated as text, `old_encoding_lossy` or `new_encoding_lossy` is true and non-UTF-8 bytes appear as U+FFFD in text fields. Unstaged gitlinks honor Git's submodule ignore settings (`diff.ignoreSubmodules`, `submodule.<name>.ignore`, `.gitmodules` `ignore`); `--staged` omits gitlinks only when ignore is `all` (index-vs-`HEAD` OID compare).

Example:

```json
{
  "changed": true,
  "files": [
    {
      "path": "staged.txt",
      "status": "added",
      "new_mode": "100644",
      "binary": false,
      "hunks": [
        {
          "old_start": 0,
          "new_start": 1,
          "old_lines": 0,
          "new_lines": 1,
          "lines": [
            {
              "kind": "add",
              "new": 1,
              "text": "staged contents"
            }
          ]
        }
      ]
    },
    {
      "path": "tracked.txt",
      "status": "modified",
      "old_mode": "100644",
      "new_mode": "100644",
      "binary": false,
      "hunks": [
        {
          "old_start": 1,
          "new_start": 1,
          "old_lines": 1,
          "new_lines": 1,
          "lines": [
            {
              "kind": "del",
              "old": 1,
              "text": "tracked v2"
            },
            {
              "kind": "add",
              "new": 1,
              "text": "tracked modified"
            }
          ]
        }
      ]
    }
  ]
}
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/diff/schemas/diff/v1.json/index.md)
Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for one section per changed file: a level-2 heading, then metadata lines (`**status:**`, and `**old_mode:**` / `**new_mode:**` when the git mode changed), then a `diff`-fenced unified patch when there are text hunks (binary files note `Binary file differs.` when content changed). Mode-only or rename-only changes omit the fence when the patch would be empty.

```text
## main.rs
**status:** modified
```

When there are text hunks, a unified patch follows in a `diff` code fence:

```diff
@@ -1,1 +1,2 @@
 fn main() {
+    println!("hello");
 }
```

Mode-only changes list modes and omit an empty fence:

```text
## run.sh
**status:** modified
**old_mode:** `100644`
**new_mode:** `100755`
```


## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | No changes selected, or success without `--exit-code` / `--quiet`. |
| `1` | Changes exist when `--exit-code` or `--quiet` is set ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or diff error while `--exit-code` / `--quiet` is set ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for the full table.


## See also

[grit status](https://grit-scm.com/docs/status/index.md), [grit show](https://grit-scm.com/docs/show/index.md), [grit log](https://grit-scm.com/docs/log/index.md)

# https://grit-scm.com/docs/restore/index.md

# grit restore

> Restore working tree and/or index paths from HEAD, the index, or another revision.

## Synopsis

```text
grit restore [--staged] [--worktree] [--hunks <id,...>] [--lines <path:start-end>] [--dry-run] [--source=<rev>] [--ours|--theirs|--merge] [--conflict=merge|diff3|zdiff3] [--pathspec-from-file <file|->] [--pathspec-file-nul] -- <path>…
```

## Description

Discards local changes for tracked paths you name. Pathnames in human and `--markdown` output use the same quoting rules as [`grit status`](https://grit-scm.com/docs/status/index.md) (see **Description** there). By default, `grit restore` resets the **working tree** to match the **index** (the same idea as unstaging worktree edits while keeping the index as-is).

- `--staged` resets the **index** from `HEAD` (or from `--source` when you pass it). On an unborn branch, staged paths are removed from the index.
- `--worktree` resets the **working tree**. When you omit both flags, only the worktree is restored.
- `--hunks` and `--lines` reverse-apply only the selected diff hunks instead of whole files. Unstaged ids come from `grit diff --unstaged --json`; with `--staged`, ids come from `grit diff --staged --json`. Line ranges use new-side line numbers from `grit diff --json` (`lines[].new`), same as `grit add --lines`. Cannot be combined with `--source`, `--ours`, `--theirs`, or `--merge`. A worktree hunk restore rewrites `.git/index` only when it updates a path's cached stat data, which it checks once the selected ids cover every remaining hunk of a file; while the file still differs from the index (or when `--lines` brought it back), the index file is left as it was, like `git apply -R`, and the next `grit status` re-reads the file.
- `--dry-run` with `--hunks` or `--lines` validates selection and reports paths without writing the worktree or index.
- `--source=<rev>` reads content from a commit or tree instead of the usual default (`HEAD` for `--staged`, the index for the worktree).
- Paths that are missing in the source are removed from the target. Untracked files are never touched.
- Index entries with the skip-worktree bit (for example after `git update-index --skip-worktree`) are left out of restore, the same as Git: `grit restore .` does not rewrite them or clear the flag.
- During a merge conflict, `--ours` and `--theirs` write index stage 2 or 3 into the worktree (filters and line endings apply) and leave the index unmerged. `--merge` rebuilds conflict markers from stages 1–3; `--conflict` picks the marker style and implies `--merge`. These options cannot be combined with `--staged` or `--source`.
- A plain worktree restore (no `--staged`, no `--source`) refuses paths that are still unmerged, for example after a conflicted `grit merge` or `grit stash pop`: there is no single index version to restore. It fails before writing anything, even when other matched paths could be restored (`grit restore .` included), and tells you to pick `--ours`, `--theirs` or `--merge`. Exclude the conflicted path (`-- . ':!f.txt'`) to restore the rest. `--staged` on its own refuses unmerged paths the same way (Git would drop the conflict stages and leave the markers in the file, and grit's auto-staging commit would then record them); to resolve, edit out the markers and `grit add` the file. `--staged --worktree` resets both the index and the file to `HEAD`, and `--source` without `--staged` writes only the worktree and leaves the conflict stages in place.

## Options

| Option | Description |
| --- | --- |
| `<path>…` | One or more pathspecs (required for full-file restore unless `--pathspec-from-file` is set). Optional with `--hunks` / `--lines` to narrow the diff scan. Attribute pathspecs such as `:(attr:myattr)` use the same `.gitattributes` stack as [`grit log`](https://grit-scm.com/docs/restore/log.md/index.md). |
| `--pathspec-from-file` | Read pathspecs from a file, or `-` for stdin (same rules as Git). |
| `--pathspec-file-nul` | With `--pathspec-from-file`, entries are NUL-separated instead of line-based. |
| `-S`, `--staged` | Restore the index (or unstage selected hunks with `--hunks` / `--lines`). |
| `-W`, `--worktree` | Restore the working tree (default when `--staged` is absent). |
| `--hunks` | Discard or unstage only the listed hunk ids (comma-separated, repeatable). |
| `--lines` | Discard or unstage only new-side line ranges (`path:start-end`, repeatable). Mix with `--hunks`. |
| `--dry-run` | With `--hunks` or `--lines`, report paths that would change without writing. |
| `-s`, `--source` | Commit or tree to restore from. |
| `--ours` | Unmerged paths only: check out our side (stage 2) in the worktree. |
| `--theirs` | Unmerged paths only: check out their side (stage 3) in the worktree. |
| `--merge` | Unmerged paths only: recreate conflict markers in the worktree (default style from `merge.conflictStyle`). |
| `--conflict` | With `--merge`: `merge`, `diff3`, or `zdiff3` marker style. |

## Examples

Discard unstaged edits to a file (worktree ← index):

```console
$ grit restore README.md
Restored README.md
```

Unstage a file (index ← HEAD):

```console
$ grit restore --staged README.md
Restored README.md
```

Discard one unstaged hunk by id:

```console
$ grit diff --unstaged --json -- f.txt | jq -r '.files[0].hunks[0].id'
a1b2c3d4e5f6
$ grit restore --hunks a1b2c3d4e5f6 -- f.txt
Restored f.txt
```

Restore the working tree from the previous commit:

```console
$ grit restore --source=HEAD~1 -- README.md
Restored README.md
```

During a merge, inspect one side or bring conflict markers back:

```console
$ grit restore --ours -- README.md
Restored README.md

$ grit restore --merge --conflict=diff3 -- README.md
Restored README.md
```

A plain or `--staged` restore on a conflicted path names the options that work:

```console
$ grit restore README.md
error: path 'README.md' is unmerged
hint: take one side with `grit restore --ours README.md` or `grit restore --theirs README.md`, bring the conflict markers back with `grit restore --merge README.md`, or edit out the markers and run `grit add README.md`
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/restore/schemas/restore/v1.json/index.md)

Pass `--json` for scripting:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `restored` | array of strings | Paths created or updated (non-UTF-8 names use reversible `grit+pathhex:` encoding, same as [`grit status`](https://grit-scm.com/docs/restore/status.md/index.md)). |
| `removed` | array of strings | Paths removed because the source had no entry (same encoding as `restored`). |
| `path_collisions` | array of strings | On a case-insensitive work tree, index paths that share one dentry (informational; same shape as `grit switch` / `grit clone`). Omitted when empty. |
| `restored_hunks` | object | When `--hunks` was used: map of path → hunk id strings. |
| `restored_lines` | object | When `--lines` was used: map of path → range strings (`start` or `start-end`). |
| `dry_run` | boolean | True when `--dry-run` was passed with hunk/line selection. |

Example:

```json
{
  "restored": ["README.md"],
  "removed": [],
  "restored_hunks": {},
  "restored_lines": {},
  "dry_run": false
}
```

When a plain or `--staged` restore refuses an unmerged path, stdout with `--json` is a single error object with `kind` `unmerged_paths`, a `paths` array of the unmerged paths and a `hint` naming the `grit restore --ours` / `--theirs` / `--merge` commands and `grit add`. See the [error schema](https://grit-scm.com/docs/restore/schemas/error/v1.json/index.md).

## Markdown output

Schema: [v1](https://grit-scm.com/docs/restore/schemas/restore/v1.json/index.md)
Pass `--markdown` for agent-friendly bullet lists of restored and removed paths.




```text
## Restore

### Restored
- `tracked.txt`
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)), including a plain or `--staged` restore of an unmerged path. |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.

When another process holds `.git/index.lock`, `grit restore` fails with exit `1` (`kind` `lock_held` under `--json`) before restoring any path, so the worktree and index are unchanged.


## See also

[grit add](https://grit-scm.com/docs/add/index.md), [grit status](https://grit-scm.com/docs/status/index.md)

# https://grit-scm.com/docs/rm/index.md

# grit rm

> Remove tracked paths from the working tree and index.

## Synopsis

```text
grit rm [--cached] [-f|--force] [--dry-run] [--ignore-unmatch] [--pathspec-from-file <file|->] [--pathspec-file-nul] <path>...
```

## Description

Removes tracked files or directories from the index and, by default, from the working tree. Pathnames in human and `--markdown` output use the same quoting rules as [`grit status`](https://grit-scm.com/docs/status/index.md) (see **Description** there). With `--cached`, the file stays on disk as an untracked file but is removed from the index.

Grit refuses to remove a path when doing so would lose content that is stored nowhere else, unless you pass `--force`. The rules match Git's safety rules for `git rm`:

| The path has… | `grit rm` | `grit rm --cached` |
| --- | --- | --- |
| No changes since `HEAD` | removed | removed |
| Local modifications (the file differs from the index) | refused | removed, file kept |
| Staged changes (the index differs from `HEAD`, or there is no commit yet) | refused | removed, file kept |
| Staged content that differs from both `HEAD` and the file | refused | refused |
| A file already deleted from the working tree | removed | removed |

So the usual way to stop tracking an accidentally committed file (`.env`, build output) works even after you edited it: `grit rm --cached .env` keeps your copy on disk and stages the deletion. When a path is refused, nothing is changed; the error lists each refused path with its reason and suggests `--cached` only when it would help.

Directory pathspecs remove every tracked file under that directory; trailing slashes on a directory path (or a path that names an existing directory) imply recursive removal. Attribute pathspecs such as `:(attr:myattr)` use the same `.gitattributes` stack as [`grit log`](https://grit-scm.com/docs/rm/log.md/index.md) (including with `--cached`).

`--dry-run` runs the same checks and lists paths that would be removed without writing the index or work tree. `--ignore-unmatch` treats non-matching pathspecs as success with an empty result (like `git rm --ignore-unmatch`).

## Options

| Option | Description |
| --- | --- |
| `<path>...` | Files or directories to remove (required unless `--pathspec-from-file` is set). |
| `--pathspec-from-file` | Read pathspecs from a file, or `-` for stdin (same rules as Git). |
| `--pathspec-file-nul` | With `--pathspec-from-file`, entries are NUL-separated instead of line-based. |
| `--cached` | Remove from the index only; keep the working tree copy. |
| `-f`, `--force` | Remove even when the safety rules above would refuse the path. |
| `--dry-run` | Preview removals without changing the index or work tree. |
| `--ignore-unmatch` | Do not error when a pathspec matches nothing. |

## Examples

Remove a tracked file:

```console
$ grit rm old.txt
Removed old.txt.
```

Preview removal:

```console
$ grit rm --dry-run old.txt
Would remove old.txt.
```

Keep the file on disk but stop tracking it:

```console
$ grit rm --cached config.local
Removed config.local.
```

A file with unsaved content is refused:

```console
$ grit rm notes.txt
error: not removed, these files have content that would be lost:
    notes.txt (local modifications)
(use --cached to stop tracking them and keep the files, or --force to remove them anyway)
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/rm/schemas/rm/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `removed` | array of strings | Repository-relative paths removed from the index (and work tree unless `--cached`), or that would be removed when `--dry-run` is set. |
| `dry_run` | boolean | `true` when `--dry-run` was passed. |

Example:

```json
{
  "dry_run": false,
  "removed": ["old.txt"]
}
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/rm/schemas/rm/v1.json/index.md)
Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output:

```text
- **Removed**:
  - `old.txt`
```


## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)), including a refusal by the safety rules; with `--json` the refusal is an `{"error": "..."}` object listing the refused paths. |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[grit add](https://grit-scm.com/docs/add/index.md), [grit mv](https://grit-scm.com/docs/mv/index.md), [grit status](https://grit-scm.com/docs/status/index.md)

# https://grit-scm.com/docs/mv/index.md

# grit mv

> Rename or move tracked paths.

## Synopsis

```text
grit mv [-f|--force] [--dry-run] <source>... <destination>
```

## Description

Renames or moves tracked paths in the working tree and index, preserving object ids and cached stat data. Pathnames in human and `--markdown` output use the same quoting rules as [`grit status`](https://grit-scm.com/docs/status/index.md) (see **Description** there). The last argument is the destination; earlier arguments are sources.

When the destination is an existing directory, each source is moved into that directory under its original base name. A trailing slash on the destination (`docs/` or `docs//`) is accepted and means the same as naming the directory without the slash. Moving a directory renames the whole tree of tracked files. Multiple sources are validated together before anything moves; the index is updated once.

Grit refuses untracked sources, overwriting an existing destination without `--force`, and moving a directory into one of its own subdirectories.

On case-insensitive volumes with `core.ignorecase=true`, case-only renames succeed: the worktree spelling updates and the index tracks the destination path. That includes renaming a tracked directory to a case-only spelling (for example `Dir` to `dir`), which updates every indexed path under that tree (for example `Dir/x.txt` becomes `dir/x.txt`). Single-file case-only renames behave like `git mv`; upstream Git still fails directory case-only renames on APFS.

When a move leaves a source directory empty, grit leaves that directory on disk (same as `git mv`).

## Options

| Option | Description |
| --- | --- |
| `<source>...` | One or more tracked paths to move. |
| `<destination>` | Final path or existing directory (last argument). |
| `-f`, `--force` | Replace an existing file at the destination. |
| `--dry-run` | List planned renames without changing the index or work tree. |

## Examples

Rename a file:

```console
$ grit mv draft.txt final.txt
Renamed draft.txt -> final.txt.
```

Move into a directory:

```console
$ grit mv report.txt docs/
Renamed report.txt -> docs/report.txt.
```

## JSON output

Live `--json` output follows schema [v2](https://grit-scm.com/docs/mv/schemas/mv/v2.json/index.md). The frozen [v1](https://grit-scm.com/docs/mv/schemas/mv/v1.json/index.md) schema documents the legacy `{from, to}` shape.

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `moves` | array of `{from, to}` | Each rename performed or previewed. |
| `dry_run` | boolean | `true` when `--dry-run` was passed. |

Example:

```json
{
  "dry_run": false,
  "moves": [
    {
      "from": "draft.txt",
      "to": "final.txt"
    }
  ]
}
```

## Markdown output

Schema: [v2](https://grit-scm.com/docs/mv/schemas/mv/v2.json/index.md)
Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output:

```text
- **moves**:
  - `draft.txt` → `final.txt`
```


## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[grit add](https://grit-scm.com/docs/add/index.md), [grit rm](https://grit-scm.com/docs/rm/index.md), [grit status](https://grit-scm.com/docs/status/index.md)

# https://grit-scm.com/docs/stash/index.md

# grit stash

> Save and restore shelved work.

## Synopsis

```text
grit stash [-m <msg>] [-u] [-- path…]
grit stash push [-m <msg>] [-u] [-S] [-k] [--hunks <id,...>] [--lines <path:start-end>] [--dry-run] [--pathspec-from-file <file|->] [--pathspec-file-nul] [-- path…]
grit stash list
grit stash show [<n>|<commit>] [--stat] [-p] [-u]
grit stash apply [<n>|<commit>] [--index]
grit stash pop [<n>|<commit>] [--index]
grit stash branch <name> [<n>|<commit>]
grit stash drop [<n>]
grit stash clear [--force] [--dry-run]
```

## Description

Shelve uncommitted changes and restore them later. With no subcommand, `grit stash` saves local changes (same as `grit stash push`), resets the working tree and index to `HEAD`, and records a stash entry compatible with Git's `refs/stash` format. Skip-worktree paths are not stashed or reset on push, and the bit stays set through pop, matching Git. Unreadable worktree directories produce a warning naming the path; stash still saves readable changes and does not treat files under those directories as deleted. Like Git, dirty content inside a checked-out submodule whose gitlink commit is unchanged does not count as a local change to save (push reports that there is nothing to stash); a submodule whose HEAD moved away from the recorded gitlink is still stashed.

Like Git, stash never signs the commits it records, even when `commit.gpgsign` is true, so a configured signing program is not run on push.

Pass `--` followed by pathspecs (or `--pathspec-from-file`) on push to stash only matching paths; other staged and unstaged changes stay in place. The stash commit still records the full index on its index parent; the working-tree parent and optional untracked parent are limited to those paths, matching `git stash push -- <pathspec>`. Attribute pathspecs such as `:(attr:myattr)` use the same `.gitattributes` stack as [`grit log`](https://grit-scm.com/docs/stash/log.md/index.md).

Stash indices follow Git: `0` is the newest entry. You can pass an integer or `stash@{n}`. An all-decimal token is always an index (never a short object id). Any other revision resolves to a stash commit id: `apply` and `branch` accept dangling stash commits (for example after `drop`), and `pop` accepts a commit id only while that commit is still on the stack.

`grit stash pop` applies the entry and removes it when there are no conflicts. When applying would leave merge conflicts, the stash entry is kept and the command exits non-zero; conflicting paths are listed. There is no merge to continue: edit the files, mark them resolved with `grit add <file>`, then remove the kept entry with `grit stash drop` (or pick a side with `grit restore --ours|--theirs <file>`). `grit stash apply` stops the same way but never drops the entry.

`apply` and `pop` preserve the exact tracked filename bytes, including literal names beginning with `grit+pathhex:` and non-UTF-8 names on Unix. If a stashed change would overwrite local edits to that file, the operation fails before changing files and keeps the stash. Conflict paths use reversible `grit+pathhex:` encoding when needed; Rust callers can recover the original bytes with `repo_relpath::storage_bytes`.

When a stash was created with `-u` / `--include-untracked`, `apply` and `pop` refuse to write stashed untracked files onto a path that already exists on disk (visible untracked, ignored, or tracked content you added after stashing). The command exits non-zero, the stash entry is kept, and your existing file bytes are unchanged.

On an interactive terminal (human output, not `--json` or `--markdown`), push shows a live **Staging** line while it hashes local changes and a **Checkout** line while it resets them, and apply and pop show a **Checkout** line; nothing is drawn when stderr is not a TTY.

Push, apply, and pop either complete or change nothing. A pop or apply that includes untracked files finishes restoring every path (tracked and untracked) before it writes the index or drops the stash entry; if an object cannot be read (for example because background repack moved it while the command was running), the worktree and index are rolled back and the stash entry stays. Pressing Ctrl+C, or sending `SIGTERM` or `SIGHUP` on Unix, while the index or work tree is being updated stops the command with `error: operation cancelled`; `HEAD`, the index and the work tree are left as they were, no `.git/index.lock` is left behind, and the same stash command can simply be run again. This works the same in a Windows console, where Ctrl+Break counts as Ctrl+C. A second interrupt terminates grit at once, without that cleanup; only `SIGKILL` skips rollback. Staging may leave unreachable loose blobs if you interrupt mid-write; they are harmless.

## Options

| Option | Description |
| --- | --- |
| `-m`, `--message` | Message stored on the stash reflog (push / bare `grit stash`). |
| `-u`, `--include-untracked` | Include untracked files in the stash (not with `--hunks` / `--lines` or `--staged`). |
| `-S`, `--staged` | Stash only index changes vs `HEAD`; unstaged edits on other paths remain (not with `-u`, `--hunks`, or `--lines`). |
| `-k`, `--keep-index` | Stash tracked changes but leave the index and worktree matching staged content afterward. |
| `--hunks` | Stash only listed unstaged hunk ids from `grit diff --unstaged --json`. |
| `--lines` | Stash only unstaged line ranges (`path:start-end`, same as `grit add --lines`). |
| `--dry-run` | Preview what would be stashed; no objects, refs, index, or worktree updates. |
| `-n`, `--limit` | Cap path lists in `--dry-run` preview output. |
| `<path>…` | Limit what is stashed (after `--`); with `--staged`, only matching index changes are saved and reset. |
| `--pathspec-from-file` | Read pathspecs from a file, or `-` for stdin (same rules as Git). |
| `--pathspec-file-nul` | With `--pathspec-from-file`, entries are NUL-separated instead of line-based. |
| `--index` | On `apply` / `pop`, restore the stashed index as well as the worktree. Changes that were unstaged when you stashed come back unstaged, including when nothing was staged at all. |
| `<n>` | Stash index for `show`, `apply`, `pop`, or `drop` (default `0`). |
| `--stat` | Show a diffstat in `grit stash show` (default when `-p` is not set). |
| `-p`, `--patch` | Show the full patch in `grit stash show` instead of a diffstat. |
| `-u`, `--include-untracked` | On `show`, include untracked files from the stash U parent (same as `git stash show -u`). |
| `push` | Save changes explicitly (same flags as bare `grit stash`). |
| `list` | List stash entries. |
| `show` | Show a diffstat or patch for one entry. |
| `apply` | Apply an entry without removing it. |
| `pop` | Apply an entry and drop it when clean. |
| `drop` | Remove an entry without applying it. |
| `branch` | Create a branch at the stash base commit, check it out, apply with `--index` (staged changes come back staged, unstaged ones unstaged), and drop the entry on success. |
| `clear` | Remove every stash entry. Requires `--force`; without it the command exits non-zero and reports how many entries would be cleared. `--dry-run` reports the count without deleting. |

## Examples

Save work in progress:

```console
$ grit stash -m "wip feature"
Saved working directory and index state On main: wip feature a1b2c3d
```

List entries:

```console
$ grit stash list
stash@{0} a1b2c3d: On main: wip feature
```

Show the newest stash as a diffstat:

```console
$ grit stash show
 f.txt | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
```

Human and `--markdown` diffstat output C-quotes C0 control characters in path names (including ESC, tab, and newline), the same as [`grit status`](https://grit-scm.com/docs/stash/status.md/index.md) and other diffstat commands; `--json` `stat.files[].path` values stay raw UTF-8 strings (JSON escapes controls as `\uXXXX`).

Pop the newest entry:

```console
$ grit stash pop
Dropped stash@{0} (applied)
```

When pop leaves conflicts:

```console
$ grit stash pop
Stash pop left conflicts in:
  f.txt
The stash entry was kept.
→ resolve conflicts, grit add <file>, then grit stash drop
$ echo resolved > f.txt
$ grit add f.txt
Staged f.txt
$ grit stash drop
Dropped stash@{0}
```

When pop would overwrite an existing path from a `-u` stash:

```console
$ grit stash pop
stash untracked restore blocked: 'notes.txt' already exists on disk
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/stash/schemas/stash/v1.json/index.md) · [stash.push v1](https://grit-scm.com/docs/stash/schemas/stash.push/v1.json/index.md) · [stash.list v2](https://grit-scm.com/docs/stash/schemas/stash.list/v2.json/index.md), [v1](https://grit-scm.com/docs/stash/schemas/stash.list/v1.json/index.md) · [stash.show v1](https://grit-scm.com/docs/stash/schemas/stash.show/v1.json/index.md) · [stash.apply v2](https://grit-scm.com/docs/stash/schemas/stash.apply/v2.json/index.md), [v1](https://grit-scm.com/docs/stash/schemas/stash.apply/v1.json/index.md) · [stash.pop v1](https://grit-scm.com/docs/stash/schemas/stash.pop/v1.json/index.md) · [stash.drop v2](https://grit-scm.com/docs/stash/schemas/stash.drop/v2.json/index.md), [v1](https://grit-scm.com/docs/stash/schemas/stash.drop/v1.json/index.md) · [stash.branch v2](https://grit-scm.com/docs/stash/schemas/stash.branch/v2.json/index.md), [v1](https://grit-scm.com/docs/stash/schemas/stash.branch/v1.json/index.md) · [stash.clear v1](https://grit-scm.com/docs/stash/schemas/stash.clear/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output.

### `grit stash` / `grit stash push`

When something was stashed:

```json
{
  "oid": "6e513d5cd6ab8d618238e22d7ca55d942b55964a",
  "message": "On main: wip feature",
  "mode": "all"
}
```

Partial stash (`--hunks` / `--lines`) also includes `stashed_hunks` and `stashed_lines` maps (same shape as `grit add --json`).

`--dry-run` preview (no `oid`):

```json
{
  "dry_run": true,
  "mode": "staged_only",
  "paths": ["staged_new.txt"],
  "untracked": []
}
```

When there was nothing to save:

```json
{
  "stashed": false
}
```

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `oid` | string | Full object id of the stash commit (success object only). |
| `message` | string | Reflog message (for `-m`, `On <branch>: …`; otherwise Git-style `WIP on …`). |
| `mode` | string | `all`, `staged_only`, or `keep_index`. Omitted when `all`. |
| `dry_run` | boolean | Always `true` on the preview object; omitted on successful save (`false`). |
| `paths` | array of strings | Tracked paths that would be stashed (`--dry-run` preview only). |
| `untracked` | array of strings | Untracked paths in a dry-run preview when `-u` is set. |
| `stashed_hunks` | object | Map of repository-relative path → hunk id strings stashed (partial `--hunks` only; same shape as `grit add --json`). Omitted when empty. |
| `stashed_lines` | object | Map of path → line range labels stashed (partial `--lines` only). Omitted when empty. |
| `paths` | array of strings | Resolved pathspecs when push was limited with `-- path…` or `--pathspec-from-file`. Omitted when empty. |
| `stashed` | boolean | Present and `false` only on the empty-worktree result. |

### `grit stash list`

```json
{
  "action": "list",
  "entries": [
    {
      "index": 0,
      "oid": "6e513d5cd6ab8d618238e22d7ca55d942b55964a",
      "message": "On main: second"
    }
  ]
}
```

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `action` | string | Always `"list"`. |
| `entries` | array | Stash entries, newest first. |
| `entries[].index` | number | Index matching `stash@{index}`. |
| `entries[].oid` | string | Full stash commit id. |
| `entries[].message` | string | Reflog message. |

### `grit stash show`

Diffstat (default):

```json
{
  "index": 0,
  "include_untracked": true,
  "stat": {
    "files_changed": 1,
    "insertions": 1,
    "deletions": 1,
    "files": [
      {
        "path": "f.txt",
        "status": "modified",
        "insertions": 1,
        "deletions": 1,
        "binary": false
      }
    ]
  }
}
```

With `--patch`, a `patch` object with the same shape as [`grit diff`](https://grit-scm.com/docs/diff/index.md) is included instead of `stat`.

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `index` | number | Stash index shown. |
| `include_untracked` | boolean | Whether `-u` / `--include-untracked` was used (omitted when false). |
| `stat` | object | Diffstat summary (when `-p` is not set). |
| `patch` | object | Full diff outcome (when `-p` is set). |

### `grit stash branch`

```json
{
  "branch": "from-stash",
  "base": "a1b2c3d4e5f6789012345678901234567890abcd",
  "oid": "d78432c4772cb8509513bca138a60d13e5ad50fd",
  "index": 0,
  "conflicts": false
}
```

When `conflicts` is true, `conflict_paths` lists paths with unmerged index entries.

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `branch` | string | Branch created and checked out. |
| `base` | string | Stash base commit (parent 1 of the W commit). |
| `oid` | string | Stash W commit that was applied. |
| `index` | number | Stash index when the commit was on the stack (omitted for an off-stack commit id). |
| `conflicts` | boolean | Whether merge conflicts remain after apply. |
| `conflict_paths` | array of strings | Conflicted paths when `conflicts` is true. |

### `grit stash clear`

Without `--force` (preview only):

```json
{
  "cleared": 2,
  "dry_run": true
}
```

After `grit stash clear --force`:

```json
{
  "cleared": 2,
  "dry_run": false
}
```

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `cleared` | number | Stash reflog entries removed or that would be removed. |
| `dry_run` | boolean | True when nothing was deleted (`--force` missing or `--dry-run`). |

### `grit stash apply` / `grit stash pop`

```json
{
  "oid": "d78432c4772cb8509513bca138a60d13e5ad50fd",
  "index": 0,
  "conflicts": false,
  "index_restored": false,
  "dropped": true
}
```

When `conflicts` is true, `conflict_paths` lists paths with unmerged index entries. On a clean apply or pop the field is omitted.

Pop adds `dropped` (whether the entry was removed):

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `oid` | string | Stash W commit id (always set on apply). |
| `index` | number | Stash index when the selector was on the stack (omitted for a bare commit id). |
| `conflicts` | boolean | Whether merge conflicts remain. |
| `index_restored` | boolean | Whether `--index` was used. |
| `conflict_paths` | array of strings | Paths with unmerged index entries when `conflicts` is true. |
| `dropped` | boolean | (`pop` only) Whether the stash entry was removed. |

### `grit stash drop`

```json
{
  "index": 0,
  "oid": "d78432c4772cb8509513bca138a60d13e5ad50fd"
}
```

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `index` | number | Stash index removed. |
| `oid` | string | Full hex id of the dropped stash W commit (for recovery with `grit stash apply <oid>`). |

## Markdown output

Schema: [v1](https://grit-scm.com/docs/stash/schemas/stash/v1.json/index.md)
With `--markdown`, list/apply/pop/drop use bullet lists; `show` renders the diffstat or patch like other diff commands.



```text
## Stash

- Saved **On main: wip** · `690b7a6`
```

A conflicted pop lists the paths and the next steps:

```text
## Stash pop

- **stash@{0}** · stopped with conflicts (entry kept)
  - `f.txt`

→ resolve conflicts, `grit add PATH`, then `grit stash drop`
```

When the stash is empty, `pop` (and `apply` with no entries) reports a plain message instead of stash ref syntax:

```console
$ grit stash pop
error: no stash entries
hint: save local changes with `grit stash push`
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.

With `--json`, typed stash failures use the shared [error schema](https://grit-scm.com/docs/stash/schemas/error/v1.json/index.md). Common `kind` values include `stash_not_found` when `apply`, `pop`, `drop`, or `show` names an index with no entry (for example `pop` on an empty stack), `not_a_repository` when the command needs a repository, and `lock_held` when another process holds `.git/index.lock` before any stash write. Human messages name the missing index (`stash@{n}`) or say `no stash entries` when the stack is empty. Apply and pop that would overwrite local tracked edits or clobber an on-disk untracked file exit **1** without changing the stash entry; `--json` still carries the error string (no separate `kind` yet for those cases).

When another process holds `.git/index.lock`, `grit stash`, `stash push`, `apply`, `pop` and `branch` fail with exit `1` (`kind` `lock_held` under `--json`) before writing anything: no stash commit or `refs/stash` entry is created, and the worktree and index are unchanged. Retry once the other process finishes. If a push fails after `refs/stash` was updated (for example an I/O error while resetting the worktree), the entry stays on the stash so the saved changes are never only a dangling object.


## See also

[grit status](https://grit-scm.com/docs/status/index.md), [grit restore](https://grit-scm.com/docs/restore/index.md), [grit commit](https://grit-scm.com/docs/commit/index.md)

# https://grit-scm.com/docs/log/index.md

# grit log

> Show commits, newest first: the whole history in the pager on a terminal, a page at a time for scripts and agents.

## Synopsis

```text
grit log [<REV>…] [-n <N>] [--cursor <token>] [--no-pager]
  [-p] [--stat | --numstat | --shortstat | --name-only | --name-status] [-U<N>]
  [--oneline] [--decorate] [--graph] [--graph-ascii] [--graph-unicode] [--group-by author] [--count]
  [--skip <N>] [--since|--after <date>] [--until|--before <date>]
  [--first-parent] [--follow] [--merges | --no-merges] [--reverse]
  [--author <pat>] [--committer <pat>] [--grep <pat>]
  [-S <string>] [-G <pat>] [--pickaxe-regex]
  [-i] [--all-match] [--invert-grep] [-F] [--no-mailmap]
  [--all] [--branches[=<glob>]] [--tags[=<glob>]] [--remotes[=<glob>]]
  [--pathspec-from-file <file|->] [--pathspec-file-nul]
  [-- <path>…]
```

## Description

Lists commits reachable from the selected revisions (default `HEAD`), newest first. Each line shows the short commit id, the change id, the author, when the commit was made and its subject (the first line of its message). Short ids follow `core.abbrev` (Git’s auto length from the number of packed objects when unset) and extend when needed so they always resolve with `grit show` or `grit log <id>`. The author is the commit's author name when present, otherwise the part of their email address before the `@`.

How much it shows depends on who is reading:

- **On a terminal**, `grit log` shows the whole history, one line per commit, through the pager, and cuts every row to the terminal width so nothing wraps. Each row ends at the right edge with the lines the commit added and removed (`+12 -3`, against its first parent; merges and commits that change no lines show none). History is walked a batch at a time, so the first screen appears at once, and the walk stops when you quit the pager. `--no-pager` writes straight to the terminal. `-n` still limits the listing.
- **For scripts and agents** (`--json`, `--markdown`, or output piped or redirected), it shows a page of twenty commits (or `-n`). When there is more history, the last line gives the command for the next page, `→ more: grit log --cursor=<token>` (in Markdown, ``More history: run `grit log --cursor=<token>` ``), and `--json` puts the same token in `next`.

The pager is `GRIT_PAGER`, then the `core.pager` config, then `PAGER`, then `less`; an empty value or `cat` turns paging off. As in Git, `LESS=FRX` and `LV=-c` are set unless you set them, so a history that fits on one screen prints and exits. When the pager executable is missing or the shell cannot start it, grit prints a short note on stderr and writes the log straight to the terminal instead.

On a [GitButler workspace](https://grit-scm.com/docs/status/index.md#gitbutler-workspaces), `grit log` with no revision starts from the applied branches instead of `HEAD`, so GitButler's workspace commit is not listed. Naming a revision (`grit log HEAD`) walks exactly that.

In a shallow clone, commits listed in `.git/shallow` are treated as roots for `-p` and `--stat`: their patch is against the empty tree, the same as [`grit show`](https://grit-scm.com/docs/show/index.md).

Revision selection matches [`grit revs`](https://grit-scm.com/docs/revs/index.md): plain tips, `A..B`, `A...B`, `^tip`, and the same ref-set flags (`--all`, `--branches`, and so on). With no revision arguments, `--branches`, `--tags`, and `--remotes` (and optional globs) replace the usual default start at `HEAD`; they do not add `HEAD` on top. If the selection matches no refs, the log is empty (exit 0), like `git log`. Path operands after `--` limit to commits that touch those paths (same cwd rules as [`grit diff`](https://grit-scm.com/docs/diff/index.md)). Attribute pathspecs such as `:(attr:myattr)` use the repository's current `.gitattributes` stack, like diff and status; they do not read historical attribute files from each commit's tree. Long-form magic pathspecs (`:(...)`) can appear as trailing operands without `--` (they are not treated as revision names). When a path filter matches no commits on a repository that already has history, human output is blank (not "No commits yet."). Path filters use the same author/date output as the default log, not the bare oid list from `grit revs`. Without `-n`, every matching commit is listed when paths are set (not capped at a page).

The continuation token is short and local to the repository (`lw1.s.` plus eight characters, stored under `.git/grit/log-walk/`; in a read-only repository it is the longer self-contained `lw1.` form instead); it encodes the revision selection, so the next page needs only `--cursor=<token>`. Path filters, commit filters (`--author`, `--grep`, …), pickaxe filters (`-S`, `-G`), `--reverse`, `--first-parent`, merge filters, `--skip`, and a one-shot `-n` without `--cursor` do not emit a continuation cursor; when such a listing stops early, the hint is ``→ more: rerun with a larger `-n` ``.

Pickaxe filters match Git's `-S` and `-G`: `-S` keeps commits where the number of occurrences of a string changed in the diff against the first parent (literal string unless `--pickaxe-regex`); `-G` keeps commits where added or removed lines match a BRE. `-i` applies to both. Binary files are skipped for `-G` (not for `-S`). `-S` and `-G` cannot be combined.

As in Git, the diff is limited to the path operands first, then deleted and added files are paired as renames (`diff.renames`, `diff.renameLimit`), and only then is each file tested. A rename whose old and new file hold the same number of matches (`-S`), or whose diff changes no matching line (`-G`), is not listed. A file moved into the path operands from outside them counts as added, so `grit log -S needle -- new/path` still lists the move. With `diff.renames=false` every rename is a deletion plus an addition. Merges are skipped, except under `--first-parent`, where they are diffed against their first parent.

Author, committer, and message filters match [`grit revs`](https://grit-scm.com/docs/revs/index.md): patterns use Git's default POSIX BRE rules unless `-F` / `--fixed-strings` is set; multiple `--author` or `--committer` patterns OR together; multiple `--grep` patterns OR together unless `--all-match`; `--invert-grep` negates only the grep group; `-i` applies to all. When `log.mailmap` is unset or true (and `--no-mailmap` is not passed), `.mailmap` is applied before matching author or committer (same sources as Git). Invalid patterns exit **129** with `kind: "invalid_pattern"` in `--json` output.

Diff detail flags (same family as [`grit diff`](https://grit-scm.com/docs/diff/index.md)) append output under each commit line: `-p` / `--patch` (unified patch), `--stat`, `--numstat`, `--shortstat`, `--name-only`, or `--name-status`. Only one format at a time. `-U` sets unified context lines for patches (default from `diff.context`).

With `--stat`, each commit is also summarized in JSON under `stat` (legacy shape matching [`grit show`](https://grit-scm.com/docs/show/index.md)). By default, merge commits include no diff in any detail mode (same as `git log` without `-m`, `-c`, or `--cc`); there is no grit flag for a first-parent or combined merge diff yet. Path operands limit both which commits appear and the paths included in each patch.

With `--graph`, human output draws a commit graph in the left margin (Unicode box-drawing by default, or ASCII `*|` with `--graph-ascii`). `--graph-unicode` is accepted as an alias for the default Unicode graph and implies `--graph`. Graph mode uses topological ordering like Git's `log --graph`, including with path and author/committer/grep filters (filtered commits are skipped while keeping lane connectivity). `--json` rejects `--graph` (exit **1**, `kind: "incompatible_flags"`) because graph columns are human-only; `--markdown` lists commits without graph columns and includes a note that `--graph` is human-only. `--graph` cannot be combined with diff format flags, `--group-by`, or `--cursor`.

## Options

| Option | Description |
| --- | --- |
| `<REV>…` | Tips and ranges to walk (default `HEAD`). |
| `-n`, `--limit <N>` | Stop after `N` commits (on a terminal too). On the default walk, this is the page size when continuing with `--cursor`. With path filters, caps how many matching commits are returned; omit it to list all matches. A one-shot `-n` without `--cursor` and without paths lists `N` commits with no `next` cursor. `--max-count` is Git’s well-known alias. Git’s `-1` / `-3` shorthand (for example `grit log -1` or `grit log --graph --oneline -3`) is accepted as `-n`. |
| `--cursor <token>` | Continue a paged walk using the token from the `→ more` line or `next` from `--json` (short `lw1.s.` tokens are stored under `.git/grit/log-walk/`; long `lw1.` base64 tokens still work). An empty value is ignored. The cursor encodes the original revision selection, date cutoffs, and walk queue—when resuming, pass `--cursor=<token>` alone (optional `-n` for page size). Revision operands, date filters, and ref-set flags are rejected when continuing. Cannot be combined with path operands. |
| `--before <date>` | Alias for `--until` (date cutoff on committer date). |
| `--skip <N>` | Skip `N` commits after ordering (cursor walks do not support `--skip`). |
| `--since`, `--after <date>` | Exclude commits older than this date (committer date). Accepts Git approxidate strings (for example `2024-01-01`, `1 week ago`, `yesterday`) as well as ISO/RFC forms. |
| `--until`, `--before <date>` | Exclude commits newer than this date. |
| `--first-parent` | Follow only the first parent at merges (disables cursor paging). |
| `--follow` | With exactly one literal file path after `--`, include commits before a rename of that file (Git `log --follow`). Still walks when the path no longer exists at the start commit. |
| `--merges` | Only merge commits (conflicts with `--no-merges`; disables cursor paging). |
| `--no-merges` | Exclude merge commits (conflicts with `--merges`; disables cursor paging). |
| `--reverse` | Print the selected window oldest-first. `-n`, `--skip`, and date filters choose the window (newest `N` commits after skip); `--reverse` only flips that window (disables cursor paging). |
| `--all` | Include every ref tip. |
| `--branches[=<glob>]` | Branch tips, optionally filtered by glob under `refs/heads/`. |
| `--tags[=<glob>]` | Tag tips, optionally filtered by glob under `refs/tags/`. |
| `--remotes[=<glob>]` | Remote-tracking tips, optionally filtered by glob under `refs/remotes/`. |
| `-p`, `--patch` | Unified patch under each commit (merge commits omit the patch). |
| `--patch-text` | Git-apply-compatible unified patch per commit (`git diff --binary` shape). Honors trailing pathspecs. Paged walks print the `→ more` continuation after the final patch. Merge commits omit the patch body (same as `-p`). Human output only; not combinable with `--json` or `--markdown`. |
| `-W`, `--function-context` | Expand patch hunks to enclosing function boundaries (same as [`grit diff`](https://grit-scm.com/docs/log/diff.md/index.md)). |
| `--stat` | Per-file change bars and totals under each commit. The JSON `stat` summary uses the same path selection and counts as `files` and `totals`; it does not compute patch hunks. |
| `--numstat` | Tab-separated insertion/deletion/path lines per commit. |
| `--shortstat` | One summary line per commit. |
| `--name-only` | Changed paths only, one per line per commit. |
| `--name-status` | Status letter and path(s) per line per commit. |
| `-U`, `--unified <N>` | Context lines for `-p` (Git `-U`). |
| `-W`, `--function-context` | Expand patch hunks to enclosing function boundaries when `-p` is set. |
| `--oneline` | One line per commit: collision-aware short oid and subject (`--json` unchanged). With `--decorate`, refs appear in parentheses after the oid. |
| `--graph` | Draw a commit graph beside each commit in human output only (implies topological order; Unicode lanes by default). |
| `--no-pager` | On a terminal, write straight to it instead of through the pager. |
| `--graph-ascii` | Use ASCII `*|` lane characters in `--graph` output instead of Unicode. |
| `--graph-unicode` | Same as `--graph` with Unicode lanes (default); implies `--graph`. Conflicts with `--graph-ascii`. |
| `--decorate` | Show branch/tag/`HEAD` labels on each commit in human and Markdown output (refs are always in `--json`). |
| `--group-by author` | Aggregate by author (mailmap-aware, sorted like `git shortlog -sne`). Uses the rev walk for the full selection (no cursor paging). |
| `--count` | With `--group-by`, omit per-commit lists in `--json` (counts and author names only). |
| `--author <pat>` | Only commits whose author matches (repeatable; OR). |
| `--committer <pat>` | Only commits whose committer matches (repeatable; OR). |
| `--grep <pat>` | Only commits whose message matches (repeatable; OR unless `--all-match`). |
| `-S <string>` | Only commits where this string's occurrence count changed in the tree diff vs the first parent. |
| `-G <pat>` | Only commits where added/removed lines match this BRE (binary files skipped). |
| `--pickaxe-regex` | Treat `-S` as a BRE instead of a literal string (not valid with `-G`). |
| `-i`, `--regexp-ignore-case` | Case-insensitive patterns for author, committer, grep, and pickaxe. |
| `--all-match` | Every `--grep` pattern must match. |
| `--invert-grep` | Exclude commits that match the grep group. |
| `-F`, `--fixed-strings` | Literal string patterns (no regex). |
| `--no-mailmap` | Do not apply `.mailmap` for author/committer matching. |
| `--pathspec-from-file <file\|->` | Read pathspecs from a file (`-` for stdin), in addition to argv paths after `--`. |
| `--pathspec-file-nul` | `--pathspec-from-file` entries are NUL-separated. |
| `<path>…` | After `--`, limit to commits that touch these paths (cwd-relative under the work tree, like `grit diff`; all matches unless `-n` is set). |

## Examples

Browse the whole history on a terminal (in the pager):

```console
$ grit log
  b52cca6  wuwxlkvx  Ada Lovelace  2 minutes ago  Handle empty input     +9  -3
  5fbefea  nrntqslp  Ada Lovelace  1 hour ago     Add a greeting test   +24  -0
  ...
  2efcc2d  krnxwkpm  Ada Lovelace  3 days ago     Start the project     +41  -0
```

From a script or an agent, the same command shows a page and how to get the next one:

```console
$ grit log | cat
  b52cca6  wuwxlkvx  Ada Lovelace  2 minutes ago  Handle empty input
  5fbefea  nrntqslp  Ada Lovelace  1 hour ago     Add a greeting test
  ...

→ more: grit log --cursor=lw1.s.a1b2c3d4
```

Show the next page:

```console
$ grit log --cursor=lw1.s.a1b2c3d4
```

See which files each recent commit touched:

```console
$ grit log --stat
  b52cca6  ada  2 minutes ago  Handle empty input

 src/parse.rs | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)

  5fbefea  ada  1 hour ago     Add a greeting test
  ...
```

Get the subjects of the last twenty commits:

```console
$ grit log --json --filter '.commits[].subject'
```

Show the five newest commits:

```console
$ grit log -n 5
```

History of one file:

```console
$ grit log -- src/lib.rs
```

Commits on a range:

```console
$ grit log -n 20 main..feature
```

Authors and dates:

```console
$ grit log --author=ada --since='2 weeks ago' -n 20
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/log/schemas/log/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `commits` | array | Up to twenty commits by default, or up to `-n` when set, newest first. Each entry uses the shared [`CommitJson`](https://grit-scm.com/docs/README.md/index.md#commit-json-object-commitjson) shape (`oid`, `parents`, `author`, `committer`, `subject`, `message`, `refs`, `change_id`, `change_id_stored`, optional `relative_date`). Defaults to `[]` when omitted (for example with `--group-by author`, which fills `groups` instead). |
| `commits[].files` | array | With any diff detail flag: same [`FileDiff`](https://grit-scm.com/docs/log/schemas/diff/v1.json/index.md) objects as [`grit diff`](https://grit-scm.com/docs/diff/index.md) (including `stat` sub-objects for `--stat` / `--numstat`). |
| `commits[].totals` | object | With `--stat`, `--numstat`, `--shortstat`, or `-p`: `files_changed`, `insertions`, `deletions` (for `-p`, summed from patch hunks). Omitted with `--name-only` and `--name-status`. |
| `commits[].stat` | object | Only with `--stat`: duplicate summary in the legacy [`grit show`](https://grit-scm.com/docs/show/index.md) `stat` shape (`files`, `files_changed`, …). |
| `groups` | array | With `--group-by author`: `{name, email, count, commits?}` sorted like `git shortlog -sne`. `commits` holds full [`CommitJson`](https://grit-scm.com/docs/README.md/index.md#commit-json-object-commitjson) rows unless `--count` is set. |
| `next` | string or null | Opaque continuation cursor (prefix `lw1.`) to pass to `--cursor` for the next page, or `null` when there is no more history or when the walk does not support paging (paths, `--reverse`, `--group-by`, and similar). |
| `truncated` | boolean | **Required.** `true` when more commits matched the query than returned in this page (`-n` or the default page size). |

Combining `--json` with `--graph` fails with exit **1** and `{"error":"…","kind":"incompatible_flags"}` on stdout (same message as human mode).

Example:

```json
{
  "commits": [
    {
      "oid": "83352a61f6715ec3f0a297c6d6150725154fb833",
      "parents": [
        "062ca6e74f5603f4d09063c0f46cd07d8c96e019"
      ],
      "author": {
        "name": "Test",
        "email": "test@example.com",
        "date": "2023-11-14T22:13:20Z"
      },
      "committer": {
        "name": "Test",
        "email": "test@example.com",
        "date": "2023-11-14T22:13:20Z"
      },
      "subject": "second",
      "message": "second",
      "refs": [
        {
          "name": "HEAD",
          "kind": "head"
        },
        {
          "name": "main",
          "kind": "branch"
        }
      ],
      "relative_date": "[TIME_AGO]",
      "change_id": "xzyqzyyzswyupvtlsovyzultryuqzlvk",
      "change_id_stored": true
    },
    {
      "oid": "062ca6e74f5603f4d09063c0f46cd07d8c96e019",
      "parents": [],
      "author": {
        "name": "Test",
        "email": "test@example.com",
        "date": "2023-11-14T22:13:20Z"
      },
      "committer": {
        "name": "Test",
        "email": "test@example.com",
        "date": "2023-11-14T22:13:20Z"
      },
      "subject": "first",
      "message": "first",
      "refs": [
        {
          "name": "feature",
          "kind": "branch"
        }
      ],
      "relative_date": "[TIME_AGO]",
      "change_id": "prkwwuwrytvxrwozplzrxmvozwutplkq",
      "change_id_stored": true
    }
  ],
  "next": null,
  "truncated": false
}
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/log/schemas/log/v1.json/index.md)
Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a bullet list of commits (short oid, subject, author, relative date):

```text
- `b52cca6` Handle empty input (Ada Lovelace, 2 minutes ago)
- `5fbefea` Add a greeting test (Ada Lovelace, 1 hour ago)

More history: run `grit log --cursor=lw1.s.a1b2c3d4`
```


When the current branch has no commits yet (for example right after [`grit init`](https://grit-scm.com/docs/log/init.md/index.md)):

```console
$ grit log
error: no commits yet on branch main — make one with `grit commit "message"`
hint: make one with `grit commit "message"`
```

Structured `--json` failures use `kind` `branch_no_commits` (see [Exit codes](https://grit-scm.com/docs/exit-codes/index.md)).

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[grit revs](https://grit-scm.com/docs/revs/index.md), [grit shortlog](https://grit-scm.com/docs/shortlog/index.md), [grit show](https://grit-scm.com/docs/show/index.md)

# https://grit-scm.com/docs/blame/index.md

# grit blame

> Show who last modified each line of a file.

## Synopsis

```text
grit blame [<rev>] [--rev <commit>] [--contents <file>] [-L RANGE] [--first-parent]
  [--group] [-w] [-M] [-C]... [--ignore-rev <REV>]... [--ignore-revs-file <FILE>]... [--] <file>
```

## Description

Walks history for one file and prints each line with the commit that last modified it, the author, when that commit was made, and the line number in the blamed file. Human and `--markdown` output use collision-aware short commit ids (`core.abbrev`); `--json` always includes full oids. The file operand uses Git pathspec cwd rules (same as [`grit diff`](https://grit-scm.com/docs/diff/index.md)): from a subdirectory, a bare name like `f.txt` refers to that path under your current directory.

Paths returned by `grit status --json` can be passed directly as the file operand, including reversible `grit+pathhex:` strings for non-UTF-8 filenames. These encoded paths are repository-relative, even when invoked from a subdirectory. Blame decodes one storage layer and compares exact filename bytes, so raw invalid-byte names, valid Unicode names, and literal names beginning with `grit+pathhex:` remain distinct. JSON `original_path` values (both lines and grouped hunks) use the same reversible encoding, including rename and copy origins. In Rust, use `repo_relpath::storage_bytes` to recover the original bytes; use `storage_string` when supplying raw names that begin with the reserved prefix.

### Uncommitted changes

Without a revision, blame reads the file from the working tree, so line numbers match what is on disk (and in your editor). The file is cleaned the way `grit add` would store it (line-ending conversion, clean filters; a symlink blames its target path), then blamed as if it were a commit on top of `HEAD`: lines that match `HEAD` keep their history, and lines that exist only in the working tree are reported as **not committed**. They show the null commit `0000000` and the author `Not Committed Yet`, and every later line keeps its working-tree line number. During an unfinished merge, the commits in `MERGE_HEAD` are parents too, so lines brought in by the merge are blamed on the incoming branch. With `--first-parent` only `HEAD` is a parent, so those lines are not committed (as in Git). A file that is staged but not yet committed is entirely not committed; a file that is neither committed nor staged is an error. When the working tree matches `HEAD`, blame is the same as `--rev HEAD`. Nothing is written to the object database.

Passing a revision (`<rev>` or `--rev`, including `HEAD`) blames that commit's file and ignores the working tree. `--contents <file>` blames the given file's content instead (`-` reads standard input), on top of the revision or `HEAD`; this is how an editor can blame an unsaved buffer. Those uncommitted lines show the author `External file (--contents)`. In a bare repository, blame without `--contents` uses `HEAD`.

`-L` ranges (numbers, `/regex/`, `:funcname`) are resolved against the same text that is blamed, so `-L /pattern/` finds the line where it sits in the working tree or `--contents` buffer.

For a literal root filename such as `grit+pathhex:6162`, `./grit+pathhex:6162` also works; ordinary operands (including `../` from a subdirectory) are normalized before the result is escaped for storage lookup.

Blame visits commits newest first (by committer date) and keeps one entry per commit that still owns lines. When a merge hands lines to several parents and those branches meet again at an older commit, their lines join that commit's entry, so a commit is normally diffed against its parents once, however many merge paths reach it (a commit whose timestamp is older than one of its descendants can be visited again when clocks were skewed). File versions that no queued commit needs are dropped once more than 64 are cached, and parent/child line maps are cached only when `--ignore-rev` or `-C` can ask for the same pair twice. On git.git's `Makefile` (4.1k lines touched across thousands of merges) that is about 1.2 s and 335 MB peak RSS on a 4-core Linux VM, against about 1.0 s and 290 MB for system `git blame`. Each parent step attributes lines the way `git blame` places hunks: the diff sees the files as Git hands them to xdiff (with the common tail dropped in 1 KiB blocks), counts how often each line occurs across all of that, and slides inserted or deleted blocks into the unchanged ends exactly as Git's compaction and indent heuristic do. Lines still being tracked that fall in an unchanged prefix or suffix beyond the reach of such a slide (past the first unchanged line whose text appears nowhere in the edited region) are mapped to the parent without running a diff, and only a window around the edit is diffed; when every remaining line is outside that reach, the step skips diffing entirely. With `-L`, that often avoids almost all diffs on large files whose recent edits are far from the requested range (for example tail-only churn). Stretches of history where the file does not change are skipped by reading only each commit's header and the tree entries on the file's path (unchanged subdirectories are not re-read), and parsed tree data is released once its entry is found. Earlier full-file measurements showed: blaming `README.md` in git.git (22.5k first-parent commits) takes about 0.37 s and 290 MB peak RSS, against about 0.29 s and 245 MB for system `git blame`. On this repository, blaming `grit-lib/src/pack.rs` (~4.6k lines, ~90 commits) completes in a few seconds on a release build; system `git blame` on the same path is still faster on some very large real-world files, and parity work continues.

With `-L`, packed history is read with positioned reads of individual indexed entries. Ranged blame retains up to 32 pack readers per object directory, with eight 16 KiB compressed windows per reader. Evicting an inactive reader closes its file and releases its windows; active reads keep their original file handle until completion. It uses private delta-base caches capped at 16 MiB per object directory, including alternates, and leaves the repository's shared caches and configuration untouched. Pack residency therefore follows the entries being read rather than every pack page touched during the walk. Memory also includes pack indexes, visited commit/path metadata, and complete blobs and delta chains needed to compare the requested lines; a three-line result does not imply that only three lines of source data are decoded. See the [ranged blame measurements](https://grit-scm.com/docs/benchmarks/index.md#ranged-blame-pack-residency).

When a commit renamed or moved the file (including rename-and-edit in the same commit), blame follows the predecessor path using rename detection with Git's default similarity threshold (50%, like `git blame` with `-M`). This behavior is independent of `diff.renames` (system Git blame still follows renames when that diff setting is off). Git's `diff.renameLimit` and `status.renameLimit` cap how many rename pairings diff/status consider; they do not change blame's similarity percentage.

On Unix, explicit file operands must be valid UTF-8. An operand containing invalid UTF-8 bytes is rejected before the command runs, with exit status **2** and no changes to the repository. Human output reports the usage error on stderr; `--json` writes an error object with `kind: "usage"` on stdout, and `--markdown` writes `**Error:**` on stdout. The argument is never replaced with a similar Unicode filename.

Adding or removing the final newline attributes the last line to the commit that changed it. With `-w` / `--ignore-all-space`, newline-only changes are ignored along with other whitespace-only changes. Line content in the output excludes LF in either mode.

Lines attributed to a commit with no effective parents (a repository root or a shallow boundary in `.git/shallow`) are prefixed with `^` in human output, the same marker Git uses. `--json` sets `"boundary": true` on those lines.

### Benchmarking

Measured on 2026-10-26 on a 4-core Linux VM with system Git 2.55.0 and release builds. The baseline is `origin/main` at `5d557d222cbe621d4d3bd41f7ecf1ab7d71c477b`. These are the existing deep-history and large-tail blame fixtures used by `grit-bench`.

Each cell shows median wall time in milliseconds / peak RSS in KiB. Nine fresh-process measurements are interleaved across Git, baseline grit, and fixed grit after two warmups. Executable files and repository data are warmed equally before measurement; stdout is discarded. Git uses `blame --porcelain`, grit uses `blame`, and peak RSS comes from `/usr/bin/time -v`.

| Scenario | System Git (ms / KiB) | Baseline grit (ms / KiB) | Fixed grit (ms / KiB) |
| --- | ---: | ---: | ---: |
| 2,000 commits, full file | 12.31 / 7,296 | 21.53 / 16,780 | 21.02 / 16,860 |
| 5,000 lines / 150 commits, full file | 53.37 / 7,736 | 41.21 / 29,872 | 37.13 / 29,832 |
| 5,000 lines / 150 commits, `-L 100,120` | 52.33 / 7,736 | 31.02 / 28,252 | 26.90 / 27,708 |

Wall time improves by about 2–13% against the baseline. Peak RSS is effectively flat for deep history (+80 KiB, within observed run variation), and falls by 40 KiB for full-file tail churn and 544 KiB for the range. The unchanged-prefix/suffix shortcut remains enabled.

#### Rename metadata regression

Measured on 2026-10-27 on a 4-core Linux x86_64 VM with system Git 2.55.0 and Rust 1.99.0 release builds. Baseline grit is `origin/main` at `80dc322f7c2fafae948c30b9e6de159f884504e0`. Nine measurements are interleaved across Git, baseline grit, and the fix after two warmups, with builds and tests stopped. Each cell shows median wall milliseconds / peak RSS KiB; wall time uses a monotonic subprocess timer and RSS comes from `/usr/bin/time -v`. Output is discarded.

The real-history case is `--rev 7e34d8174d -L 1,3 --json git-gui/git-gui.sh` in git/git (Git uses `--line-porcelain`). The tail cases use the existing 5,000-line / 150-commit fixture with `grit blame` versus `git blame --porcelain`, and `-L 100,120` for the range.

| Scenario | System Git (ms / KiB) | Baseline grit (ms / KiB) | Fixed grit (ms / KiB) |
| --- | ---: | ---: | ---: |
| git/git git-gui, lines 1–3 | 191.81 / 83,372 | 527.11 / 335,004 | 527.43 / 334,968 |
| Large-tail full file | 70.37 / 6,252 | 52.35 / 26,828 | 51.61 / 26,760 |
| Large-tail lines 100–120 | 69.89 / 6,304 | 42.44 / 25,128 | 42.33 / 25,188 |

The source-path fix retains the unchanged-prefix/suffix shortcut. Median wall time changes by at most 1.5%; the largest peak RSS increase is 60 KiB against baseline in this run.

### Benchmarking encoded paths

Measured on a 4-core Linux x86_64 VM with system Git 2.55.0 and Rust 1.99.0,
using `dist` builds of main (`5a715a522`) and this fix. Each cell reports median
**wall milliseconds / peak RSS KiB** from ten measured invocations after two
warmups, interleaving Git, main, and the fix on an idle VM. RSS comes from
`/usr/bin/time -v`; stdout is discarded. Grit uses `blame --json`; Git uses
`blame --line-porcelain`. Ranges use `-L 1,200`.

The packed fixture has 201 commits and two identical 4,096-line files, one UTF-8
path and one raw-byte directory/filename, with Git-written changed-path Bloom
filters. The real-repository case blames `grit-lib/src/blame.rs` at the baseline
revision, whose file history has 76 changes.

| Scenario | System Git | Main | Fix |
| --- | ---: | ---: | ---: |
| Packed UTF-8, full file | 73.9 / 30,226 | 101.7 / 75,230 | 102.7 / 75,262 |
| Packed UTF-8, lines 1–200 | 56.5 / 30,174 | 71.1 / 68,962 | 71.9 / 68,810 |
| Packed encoded path, full file | 74.5 / 30,266 | Path error | 101.7 / 75,290 |
| Packed encoded path, lines 1–200 | 56.1 / 30,196 | Path error | 70.7 / 69,194 |
| Grit repository, UTF-8, full file | 97.6 / 40,774 | 92.8 / 68,084 | 92.2 / 68,010 |
| Grit repository, UTF-8, lines 1–200 | 63.5 / 39,864 | 72.9 / 64,658 | 72.2 / 64,672 |

UTF-8 timings remain within 1.2% of the baseline in this run, with no material
RSS increase. Encoded paths now complete both full-file and ranged blame;
main's path errors provide no comparable successful-operation timing.

## Options

| Option | Description |
| --- | --- |
| `<rev>` | Optional revision before `--` (same values as `--rev`). Without a revision the working-tree file is blamed on top of `HEAD`. |
| `--rev <commit>` | Blame the file as committed at this revision, ignoring the working tree. Cannot be combined with a positional `<rev>`. |
| `--contents <file>` | Blame this file's content (`-` for standard input) instead of the working tree, on top of the revision (default `HEAD`). Lines not in the revision are reported as not committed. |
| `-L RANGE` | Limit output with a Git-style line range in the final file (see below). Blame stops once every line in the range is attributed. |
| `--lines` | Same as `-L` (long form). |
| `--first-parent` | At merge commits, follow only the first parent when attributing lines. Default matches Git blame: all parents are considered. |
| `--group` | With `--json` only: emit grouped `hunks[]` instead of per-line `lines[]` (smaller on large files). Human and `--markdown` output stay per line. |
| `--ignore-rev <REV>` | Treat this commit as transparent while walking history (repeatable). Unknown revisions are an error. |
| `--ignore-revs-file <FILE>` | Read full-length commit oids to ignore, one per line (`#` comments, blank lines skipped). Repeatable; `""` clears entries loaded from config or earlier files. Missing files are an error. Relative paths are resolved from the repository root. Config `blame.ignoreRevsFile` (multi-valued) is applied before CLI files. |
| `-w`, `--ignore-all-space` | Ignore whitespace when comparing lines between revisions (same rules as [`grit diff -w`](https://grit-scm.com/docs/diff/index.md)). Whitespace-only edits do not move blame to a newer commit. |
| `-M`, `--move-detection` | Detect lines moved within the same file (`git blame -M`). Relocated blocks are blamed on the commit that originally wrote them when the move scores above Git's default threshold. |
| `-C`, `--copy-detection` | Detect lines copied from other files (repeat up to three times for deeper search, matching `git blame -C` / `-C -C` / `-C -C -C`). A fourth `-C` is rejected with exit code 2. Using `-C` also enables move detection, matching Git (`-C` implies `-M`). |

Human output prefixes ignored lines with `?` and lines that cannot be blamed past an ignored commit with `*` (same markers Git uses when `blame.markIgnoredLines` / `blame.markUnblamableLines` are enabled).

## Examples

Blame a file as it is in the working tree:

```console
$ grit blame src/lib.rs
0000000 (Not Committed Yet just now    1) // edited
a1b2c3d (ada 2 days ago    2) use std::io;
f4e5d6c (bob 1 week ago    3) fn main() {
```

Blame the committed file, or an unsaved editor buffer piped on standard input:

```console
$ grit blame --rev HEAD src/lib.rs
$ cat buffer.rs | grit blame --contents - src/lib.rs
```

Blame an older revision and a slice of lines:

```console
$ grit blame v1.0 -- README.md
$ grit blame --rev=v1.0 -L 10,25 README.md
$ grit blame -L 10,+20 src/lib.rs
$ grit blame -L '/fn main/' src/main.rs
$ grit blame -L ':my_function' src/lib.rs
```

Scripting with JSON:

```console
$ grit blame --json story.txt
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/blame/schemas/blame/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `file` | string | Work-tree path that was blamed (repository-relative after cwd resolution). |
| `rev` | string | Full commit oid of the start revision (the `HEAD` commit unless a revision was given, also when blaming the working tree or `--contents`). |
| `lines` | array | One record per line (after any `-L` filter), in final-line order. |
| `lines[].commit` | string | Full commit oid for the line; all zeros for a line that is not committed. |
| `lines[].original_line` | number | 1-based line number in the originating commit. |
| `lines[].original_path` | string | Reversibly stored path in the originating commit, preserving filename bytes through renames and copies. |
| `lines[].final_line` | number | 1-based line number in the blamed file (the working tree or `--contents` when those are blamed). |
| `lines[].content` | string | Line text (lossy UTF-8 when `encoding_lossy` is true). |
| `lines[].encoding_lossy` | boolean | Present and `true` when the line bytes were not valid UTF-8 and `content` used lossy decoding. Raw bytes are not included in JSON; use [`grit_lib::blame::BlameAttributedLine::content_bytes`](https://docs.rs/grit-lib/latest/grit_lib/blame/struct.BlameAttributedLine.html#structfield.content_bytes) from the library when you need them. |
| `lines[].ignored` | boolean | Present and `true` when the line was attributed through an ignored revision. |
| `lines[].unblamable` | boolean | Present and `true` when the line was added in an ignored revision and cannot be blamed further back. |
| `lines[].boundary` | boolean | Present and `true` when the attributed commit has no effective parents (root or shallow boundary). Human output prefixes the line with `^`. |
| `lines[].not_committed` | boolean | Present and `true` when the line exists only in the working tree or `--contents` buffer. `commit` is then all zeros and `original_line` equals `final_line`. |
| `commits` | object | Map of commit oid → metadata for every line. |
| `commits.<oid>.author` | object | Author with `name`, `email`, and `date` (RFC 3339 — same shape as [`grit show`](https://grit-scm.com/docs/show/index.md)). Author date is only here, not repeated on each line or hunk. |
| `commits.<oid>.summary` | string | First line of the commit message. |

Lines that are not committed share the all-zeros entry in `commits`: its author is `Not Committed Yet` (or `External file (--contents)`) with email `not.committed.yet`, dated when the command ran, and its summary repeats that label.

### Grouped JSON (`--json --group`)

Same top-level `file`, `rev`, and `commits` map. Replaces `lines[]` with `hunks[]` (omit `lines`):

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `hunks[].commit` | string | Full commit oid for every line in the hunk. |
| `hunks[].original_path` | string | Reversibly stored originating path for the hunk (same encoding as status). |
| `hunks[].original_start` | number | 1-based first line in the originating commit. |
| `hunks[].final_start` | number | 1-based first line in the blamed revision. |
| `hunks[].count` | number | Number of consecutive final lines in the hunk. |
| `hunks[].ignored` | boolean | Present and `true` when the hunk passed through an ignored revision. |
| `hunks[].unblamable` | boolean | Present and `true` when blame could not continue past an ignored revision. |
| `hunks[].not_committed` | boolean | Present and `true` when the hunk's lines are not committed (`commit` is all zeros). |
| `hunks[].lines` | array of strings | Line text for each row in the hunk (same order as final lines). |
| `hunks[].line_encoding_lossy` | array of boolean | Present when any line in the hunk was decoded lossily; parallel to `lines`, one flag per row. Omitted when every line is valid UTF-8. |

Every `original_path` names the file in its reported `commit`, even when a line range crosses rename-and-edit commits or subtree imports. After decoding the filename bytes, read that commit's file at `original_line` (or `original_start` for a hunk). The path can differ from both the requested path and intermediate names in history.

Hunk boundaries match `git blame --porcelain` group headers (`<oid> <orig> <final> <count>`). Prefer `--group` for agents and scripts on large files.

Example:

```json
{
  "file": "story.txt",
  "rev": "92501f188ae0815af09a0cef6e121eddda4113cf",
  "lines": [
    {
      "commit": "919c45f33de5e5c0bd05f8ffb089f697f4644976",
      "original_line": 1,
      "original_path": "story.txt",
      "final_line": 1,
      "content": "alpha ONE"
    }
  ],
  "commits": {
    "919c45f33de5e5c0bd05f8ffb089f697f4644976": {
      "author": {
        "name": "Blame Test",
        "email": "blame@example.com",
        "date": "2024-03-09T12:26:40Z"
      },
      "summary": "edit first line"
    }
  }
}
```

## Markdown output

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output.

Schema: [v1](https://grit-scm.com/docs/blame/schemas/blame/v1.json/index.md)

Markdown uses headings, bullet lists, and fenced blocks; pipe characters inside table cells are escaped. See the JSON output section for the stable field contract.

```text
## Blame: `tracked.txt`

Revision `83352a61f6715ec3f0a297c6d6150725154fb833`

| Line | Mark | Commit | Author | Date | Original | Content |
| ---: | :---: | --- | --- | --- | ---: | --- |
| 1 |  | `0000000` | Not Committed Yet | [TIME_AGO] | 1 | tracked modified |
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.

## See also

- [`grit log`](https://grit-scm.com/docs/blame/log.md/index.md) — commit history
- [`grit show`](https://grit-scm.com/docs/blame/show.md/index.md) — one commit's message and file stats

# https://grit-scm.com/docs/reflog/index.md

# grit reflog

> Show, delete, or expire reflog entries.

## Synopsis

```text
grit reflog [REF] [-n N] [--since DATE] [--until DATE] [--grep PAT]
grit reflog list [-n N]
grit reflog delete <REF@{N}>...
grit reflog expire [--all] [--expire <DATE>] [--expire-unreachable <DATE>] [--dry-run]
```

## Description

Inspect and maintain reference logs. With no subcommand, lists entries for `REF` (default `HEAD`) in newest-first order. Each line shows the selector (`REF@{n}`), the `new_oid` after the update, a relative date, and the log message.

Filters apply to the reflog entry identity timestamp (not the commit date). Scanning stops once `-n` matches are collected, so large logs are not fully materialized.

`delete` removes explicit entries without rewriting the branch tip. In `ref@{n}`, `n` is a nonnegative integer: `0` selects the newest entry, `1` the next older entry. Date selectors and bare indices are not accepted by `delete`. `list` prints every ref that currently has a reflog file (sorted), bounded by `-n` / `--limit`. `expire` applies Git-compatible `gc.reflogExpire*` rules (same layering as `grit gc`), using explicit `--expire` / `--expire-unreachable` values when given and merged config otherwise. An entry older than the unreachable cutoff is dropped when its old or new commit is not reachable from the ref's tip (from any ref for `HEAD`), with annotated tags peeled as current Git does; when the tip does not name a commit, every such entry is dropped. The check walks commits only: history down to the `--expire` cutoff first, and the rest once, only if an entry names an older commit. It never reads trees or fetches missing objects in a partial clone. Refs expired in one run share the commits already read, so expiring many branches with old entries costs little more than one. With `--dry-run`, `expire` reports per-ref prune counts without rewriting any log file.

A branch literally named `list` is ambiguous with the `list` subcommand; use the full ref (`refs/heads/list`) when showing that branch's entries.

## Options

| Option | Description |
| --- | --- |
| `REF` | Ref to list (default `HEAD`). Branch short names are accepted (`main` → `refs/heads/main`). |
| `-n`, `--max-count` | Show at most `N` matching entries (newest first). Alias: `--limit`. |
| `--since`, `--after` | Exclude entries older than this date (Git `--since`). |
| `--until`, `--before` | Exclude entries newer than this date (Git `--until`). |
| `--grep` | Keep entries whose message contains this substring (case-sensitive). |
| `list` | List refs that have a reflog (`-n` / `--limit` bounds the list). |
| `delete` | Remove one or more `ref@{n}` selectors. |
| `expire` | Drop old reflog entries using gc expiry rules. |
| `--all` | On `expire`, walk every ref under `refs/`, not only refs that already have log files. |
| `--expire` | Reachable expiry time (`now`, `never`, `2.weeks.ago`, Unix time, …). |
| `--expire-unreachable` | Unreachable expiry time (same syntax as Git). |
| `--dry-run` | On `expire`, preview pruning without writing reflog files. |

## Examples

Show the last three `HEAD` reflog entries:

```console
$ grit reflog HEAD -n 3
HEAD@{0} b5ea30de417ac84c09b8cfc0acf5f2c39efc611f 2 minutes ago commit: second
HEAD@{1} 72934dedd47ecaf7e340fd6c5ef46620187fb317 1 hour ago commit: first
```

Entries since yesterday whose message mentions `checkout`:

```console
$ grit reflog --since=yesterday --grep=checkout -n 20 --json
```

Delete one entry:

```console
$ grit reflog delete main@{1}
Deleted main@{1}
```

Expire using gc defaults:

```console
$ grit reflog expire
Pruned 0 reflog entries
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/reflog/schemas/reflog/v1.json/index.md) (show entries), [list v1](https://grit-scm.com/docs/reflog/schemas/reflog.list/v1.json/index.md), [delete v1](https://grit-scm.com/docs/reflog/schemas/reflog.delete/v1.json/index.md), [expire v1](https://grit-scm.com/docs/reflog/schemas/reflog.expire/v1.json/index.md)

List (`grit reflog [REF]`):

| Field | Type | Meaning |
| --- | --- | --- |
| `ref` | string | Ref that was listed. |
| `truncated` | boolean | `true` when listing stopped before the oldest entry (typically because of `-n`). |
| `entries` | array | Newest-first entries. |
| `entries[].index` | integer | Newest-first index in the full reflog (`0` is latest). |
| `entries[].oid` | string | Hex object id stored as `new_oid` for that entry (v1 alias of `new_oid`). |
| `entries[].old_oid` | string | Previous object id before the update. |
| `entries[].new_oid` | string | Object id after the update (same as `oid`). |
| `entries[].date` | string | Reflog committer time in RFC 3339 (original offset preserved). |
| `entries[].relative_date` | string | Human-relative time from the entry identity. |
| `entries[].committer` | object | `name`, `email`, and `date` (same shape as `log` / `blame`). |
| `entries[].message` | string | Reflog message (may be empty). |
| `entries[].action` | string (optional) | Best-effort prefix before the first `": "` in the message. |

```json
{
  "ref": "HEAD",
  "truncated": false,
  "entries": [
    {
      "index": 0,
      "oid": "b5ea30de417ac84c09b8cfc0acf5f2c39efc611f",
      "old_oid": "72934dedd47ecaf7e340fd6c5ef46620187fb317",
      "new_oid": "b5ea30de417ac84c09b8cfc0acf5f2c39efc611f",
      "date": "2026-10-23T18:15:00Z",
      "relative_date": "2 minutes ago",
      "committer": {
        "name": "Example User",
        "email": "user@example.com",
        "date": "2026-10-23T18:15:00Z"
      },
      "message": "commit: second",
      "action": "commit"
    }
  ]
}
```

Delete (`grit reflog delete …`):

| Field | Type | Meaning |
| --- | --- | --- |
| `deleted` | array of strings | Selectors that were removed. |

List refs (`grit reflog list`):

| Field | Type | Meaning |
| --- | --- | --- |
| `refs` | array | Sorted ref names that have a log. |
| `refs[].ref` | string | Full ref name (for example `refs/heads/main`). |

```json
{
  "refs": [
    { "ref": "HEAD" },
    { "ref": "refs/heads/main" }
  ]
}
```

Expire (`grit reflog expire`):

| Field | Type | Meaning |
| --- | --- | --- |
| `entries_pruned` | integer | Reflog lines removed (or that would be removed with `--dry-run`). |
| `dry_run` | boolean | `true` when `--dry-run` was passed (default `false`). |
| `refs` | array | Per-ref prune counts. |
| `refs[].ref` | string | Ref that was processed. |
| `refs[].pruned` | integer | Entries pruned on that ref. |

```json
{
  "entries_pruned": 0,
  "dry_run": false,
  "refs": []
}
```

## Markdown output

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output.

Schema: [v1](https://grit-scm.com/docs/reflog/schemas/reflog/v1.json/index.md) (show entries); subcommands use [list v1](https://grit-scm.com/docs/reflog/schemas/reflog.list/v1.json/index.md), [delete v1](https://grit-scm.com/docs/reflog/schemas/reflog.delete/v1.json/index.md), and [expire v1](https://grit-scm.com/docs/reflog/schemas/reflog.expire/v1.json/index.md).

List mode emits a bullet per entry with `REF@{n}`, abbreviated oid, **absolute** `date`, and message (human mode keeps relative dates). Delete and expire print short confirmation lines.




```text
- HEAD@{0} 83352a6 2023-11-14T22:13:20Z commit: second
- HEAD@{1} 062ca6e 2023-11-14T22:13:20Z commit (initial): first
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[grit log](https://grit-scm.com/docs/reflog/log.md/index.md), [grit gc](https://grit-scm.com/docs/reflog/gc.md/index.md)

# https://grit-scm.com/docs/shortlog/index.md

# grit shortlog

> List the commits on this branch that aren't on the target branch yet.

## Synopsis

```text
grit shortlog [-n COUNT] [--behind] [--stat | --name-only] [--target REF]
grit sl [-n COUNT] [--behind] [--stat | --name-only] [--target REF]
grit ahead [-n COUNT] [--behind] [--stat | --name-only] [--target REF]
```

## Description

Shows the current branch, its target branch, and every commit on the current branch that the target doesn't have, newest first. It's the list of what you would be proposing if you opened a pull request now.

The target branch is found the same way as for [`grit status`](https://grit-scm.com/docs/status/index.md#the-target-branch): the `target.branch` setting, then `origin/master`, `origin/main`, `master` and `main`. Use `--target <REF>` to compare against any ref or revision instead (branch, remote-tracking ref, tag, or commit id). `grit ahead` is an alias for the same command — grit's shortlog means commits ahead of a target, not Git's author-grouped `shortlog -sne`. Unlike `grit status`, which shows at most ten commits, `grit shortlog` lists up to `-n` / `--max-count` commits (default **100**). Full ahead and behind **counts** are always exact even when the lists are truncated.

When no target branch can be discovered, the result is an empty list. An explicit `--target` that cannot be resolved is an error.

With `--behind`, also lists commits that are on the target but not on this branch yet (the commits you would pick up by fast-forwarding or merging the target).

For author commit counts over an arbitrary revision range (Git's `shortlog -sne` shape), use [`grit log --group-by author`](https://grit-scm.com/docs/shortlog/log.md/index.md#options) instead — `grit shortlog` means commits ahead of the target branch, not author grouping.

## Options

| Flag | Meaning |
| ---- | ------- |
| `--target <REF>` | Ref or revision to compare against instead of the discovered target branch. |
| `-n`, `--max-count` | Maximum commits to list on each side (default 100). Counts stay exact when the list is truncated. |
| `--behind` | Also list commits on the target that are not on this branch (`behind` / `behind_commits` in JSON). |
| `--stat` | Per-commit diffstat (same shape as [`grit log --stat`](https://grit-scm.com/docs/shortlog/log.md/index.md)). |
| `--name-only` | Per-commit changed paths (same shape as [`grit log --name-only`](https://grit-scm.com/docs/shortlog/log.md/index.md)). |

Only `--stat` and `--name-only` are supported for per-commit diffs; use [`grit log`](https://grit-scm.com/docs/shortlog/log.md/index.md) for patch and other formats.

Global options: [global options](https://grit-scm.com/docs/global-options/index.md).

## Examples

```console
$ grit shortlog
On feature
Ahead of origin/main by 2 commits
  cf18394  ada  2 hours ago  Say hi
  9a1c2e0  ada  3 hours ago  Add a greeting test
```

List at most one ahead commit and show how far behind the target you are:

```console
$ grit sl -n 1 --behind --json --filter '{ahead, behind, truncated, behind_truncated, commits: .commits|length, behind_commits: .behind_commits|length}'
```

Per-commit stats for the ahead list:

```console
$ grit shortlog --stat
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/shortlog/schemas/shortlog/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `branch` | string | Current branch name. |
| `target` | string or null | Target branch used for comparison, or `null` when none was found. |
| `ahead` | number | How many commits are on the branch but not on the target. |
| `behind` | number or null | How many commits are on the target but not on the branch; `null` when no target was found. |
| `commits` | array | Ahead commits, newest first, each using the shared [`CommitJson`](https://grit-scm.com/docs/README.md/index.md#commit-json-object-commitjson) shape plus optional `stat` / `files` when `--stat` / `--name-only` is set. |
| `truncated` | boolean | `true` when `ahead` exceeds the number of commits listed. |
| `behind_commits` | array or null | Behind commits when `--behind` is set; same commit object shape as `commits`. |
| `behind_truncated` | boolean or null | `true` when `behind` exceeds `behind_commits` length; only with `--behind`. |
| `next` | null | Reserved for future paging; always `null` today. |

Example:

```json
{
  "branch": "main",
  "target": "main",
  "ahead": 2,
  "behind": 0,
  "commits": [],
  "truncated": false,
  "next": null
}
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/shortlog/schemas/shortlog/v1.json/index.md)
Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a branch summary and commit bullets:

```text
# Branch `feature`

Ahead of `main` by **2** commits.

- `cf18394` Say hi (ada, 1 hour ago)
- `9a1c2e0` Add a greeting test (ada, 2 hours ago)
```


## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for the shared rules and structured `--json` `kind` values.


## See also

[grit status](https://grit-scm.com/docs/status/index.md), [grit log](https://grit-scm.com/docs/log/index.md), [grit config](https://grit-scm.com/docs/config/index.md)

# https://grit-scm.com/docs/revs/index.md

# grit revs

> List or count commits matching revision ranges.

## Synopsis

```text
grit revs <RANGE>... [-n <N>] [--count] [--left-right] [--cherry-mark]
  [--skip <N>] [--since|--after <date>] [--until|--before <date>]
  [--first-parent] [--follow] [--merges | --no-merges] [--reverse]
  [--author <pat>] [--committer <pat>] [--grep <pat>]
  [-S <string>] [-G <pat>] [--pickaxe-regex]
  [-i] [--all-match] [--invert-grep] [-F] [--no-mailmap]
  [--all] [--branches[=<glob>]] [--tags[=<glob>]] [--remotes[=<glob>]]
  [--pathspec-from-file <file|->] [--pathspec-file-nul]
  [-- <PATH>...]
```

## Description

Walks commits reachable from one or more revision ranges and prints each commit’s full object id and subject (first line of the message), one commit per line. Ranges use the same syntax as Git’s `rev-list`: plain tips, `A..B`, symmetric difference `A...B`, and `^tip` exclusions.

With no revision arguments, `--branches`, `--tags`, and `--remotes` (and optional globs) select only those ref tips—they replace the implicit `HEAD` default, they do not union with it, and if nothing matches the count is `0` with exit **0** (like `git rev-list`).

Use `--count` to print only the number of reachable commits (no subject lines). With `--left-right` and exactly one `A...B` range, `--count` prints left and right counts (same as `git rev-list --left-right --count`). Without `--count`, `--left-right` lists the range with a `<` (left) or `>` (right) prefix on each commit.

### Reviewing a rewritten branch

`--cherry-mark` compares the two sides of one `A...B` range by [patch-ID](https://grit-scm.com/docs/patch-id/index.md), the way `git rev-list --left-right --cherry-mark` does. Run it on the version you reviewed and the version that was force-pushed (`old...new`) to see which commits are the same change and which are new:

- `=` marks a commit whose patch-ID also appears on the other side. When exactly one commit on each side has that patch-ID, the line names its counterpart and says whether the commit message changed, so a reworded commit stands out from an untouched one.
- `<` and `>` mark commits found only on the left or right side: dropped, added, or edited commits, and commits that came in with the new base.

When several commits on one side share a patch-ID, they are all marked equivalent without being paired. Matching uses the stable patch-ID (path-limited when paths follow `--`). Only the diff counts: a commit whose content changed is a new commit on its side, and no content interdiff is shown. `--cherry-mark` and `--left-right` need exactly one `A...B` range and exit **1** otherwise, even with `-n 0`; `--cherry-mark` cannot be combined with `--count`. When a commit-graph file is present, the walk takes parents and commit dates from it instead of reading commit objects. Unfiltered counts use that graph linkage, and listings read each listed commit once to render its row.

`A..B` and `A...B` counts walk the range once: the excluded side is marked down
to where it meets the included side, and the walk stops there instead of
building ancestor sets for the shared history. `--since`, `--until`,
`--merges`, `--no-merges` and `--first-parent` only decide which of those
commits are counted, so counting a range costs about the same as listing it.
With a commit-graph, generation numbers let the walk stop as soon as the
included side is resolved, so a small range stays bounded even in a repository
with a deep history. As in Git, `--first-parent` follows first parents from the
included tips only; everything an excluded tip reaches through any parent stays
excluded.

Path arguments after `--` limit history to commits that touched those paths. Operands use Git pathspec cwd rules (same as [`grit diff`](https://grit-scm.com/docs/diff/index.md)): from a subdirectory, `.` limits to that directory, and bare filenames are relative to the current directory, not the repository root. Attribute pathspecs such as `:(attr:myattr)` use the repository's current `.gitattributes` stack (work tree, index, `info/attributes`, and macros), the same way as [`grit diff`](https://grit-scm.com/docs/diff/index.md); they do not read historical trees' attribute files.

Author, committer, message, and pickaxe filters use the same rules as [`grit log`](https://grit-scm.com/docs/log/index.md) (`-S`, `-G`, `--pickaxe-regex`, and the same `-i` / `-F` / mailmap behavior). Invalid patterns exit **129** with `kind: "invalid_pattern"` in `--json` output.

## Options

| Option | Description |
| --- | --- |
| `<RANGE>…` | One or more revision ranges (required unless a ref-set flag such as `--all` is used). |
| `-n`, `--limit <N>` | Stop after `N` commits (listing mode only). `--max-count` is Git’s well-known alias. |
| `--count` | Print only the commit count (or left/right counts with `--left-right`). |
| `--left-right` | With one `A...B` range, mark each listed commit as left (`<`) or right (`>`); with `--count`, print `{left, right}` instead of a single total. |
| `--cherry-mark` | With one `A...B` range, pair the two sides by patch-ID: `=` marks equivalent commits, `<` / `>` the rest (implies `--left-right`; conflicts with `--count`). |
| `--skip <N>` | Skip `N` commits after ordering. |
| `--since`, `--after <date>` | Exclude commits older than this date (committer date). |
| `--until`, `--before <date>` | Exclude commits newer than this date. |
| `--first-parent` | Follow first parents only at merges. |
| `--follow` | With exactly one literal file path after `--`, walk history across renames (Git `log --follow`). Still walks when the path no longer exists at the start commit. |
| `--merges` | Only merge commits (conflicts with `--no-merges`). |
| `--no-merges` | Exclude merge commits (conflicts with `--merges`). |
| `--reverse` | Print the selected window oldest-first. `-n` and `--skip` choose the window (newest `N` commits after skip); `--reverse` only flips that window. |
| `--all` | Include every ref tip. |
| `--branches[=<glob>]` | Branch tips, optionally filtered by glob. |
| `--tags[=<glob>]` | Tag tips, optionally filtered by glob. |
| `--remotes[=<glob>]` | Remote-tracking tips, optionally filtered by glob. |
| `--author <pat>` | Only commits whose author matches (repeatable; OR). |
| `--committer <pat>` | Only commits whose committer matches (repeatable; OR). |
| `--grep <pat>` | Only commits whose message matches (repeatable; OR unless `--all-match`). |
| `-i`, `--regexp-ignore-case` | Case-insensitive patterns. |
| `--all-match` | Every `--grep` pattern must match. |
| `--invert-grep` | Exclude commits that match the grep group. |
| `-F`, `--fixed-strings` | Literal string patterns. |
| `--no-mailmap` | Do not apply `.mailmap` for author/committer matching. |
| `--pathspec-from-file <file\|->` | Read pathspecs from a file (`-` for stdin), in addition to argv paths after `--`. |
| `--pathspec-file-nul` | `--pathspec-from-file` entries are NUL-separated. |
| `-- <PATH>…` | Limit to commits touching these paths (cwd-relative under the work tree, like `grit diff`). |

## Examples

List commits on the current branch:

```console
$ grit revs HEAD
92501f188ae0815af09a0cef6e121eddda4113cf  second
919c45f33de5e5c0bd05f8ffb089f697f4644976  initial
```

Count reachable commits:

```console
$ grit revs --count HEAD
2
```

Left/right counts on a symmetric range:

```console
$ grit revs --count --left-right main...feature
3	5
```

What changed in a force-pushed branch since review (`old-feature` is the reviewed version; the branch was rebased onto a new `main` commit, `c3` was reworded and `c4` was added):

```console
$ grit revs --cherry-mark old-feature...feature
= 09d5318d2c9bb2881fd2b503861aadf43737463e  c3  (message changed, pairs with 05075c9436c1)
> 42f209db819ee73ae750d5d33a85a4a972c75c36  c4 edits f1
= 05075c9436c17c49302513b5960c332ecfcdbae4  c3 reworded  (message changed, pairs with 09d5318d2c9b)
= 9000bf12a1499df8fc46332773bfd822e31dbcbd  c2  (pairs with a41d2d81bcbe)
= 8d35e4e808b5b12bdd0910e7fbc0eaad0804d1d4  c1  (pairs with e778fe04f497)
> 4c78873b7c8588803452c16634f5b36ae4164264  m
= a41d2d81bcbea60b67ac7f6c530d71bea889b628  c2  (pairs with 9000bf12a149)
= e778fe04f49705176ea24d7fa28182952a835187  c1  (pairs with 8d35e4e808b5)
```

Commits on one branch but not another:

```console
$ grit revs main..feature
```

Count commits mentioning an issue id on a range:

```console
$ grit revs --count --grep=JIRA-123 main..
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/revs/schemas/revs/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `commits` | array | Commits in walk order. Each entry uses the shared [`CommitJson`](https://grit-scm.com/docs/README.md/index.md#commit-json-object-commitjson) shape, plus the side fields below with `--left-right` or `--cherry-mark`. Empty when `--count` is set. |
| `commits[].side` | string or omitted | `left` or `right`: which side of the `A...B` range the commit is on. Only with `--left-right` or `--cherry-mark`. |
| `commits[].equivalent` | boolean or omitted | With `--cherry-mark`: `true` when a commit on the other side has the same patch-ID. |
| `commits[].equivalent_to` | string or omitted | With `--cherry-mark`, when exactly one commit on each side shares the patch-ID: the other side's commit. |
| `commits[].message_changed` | boolean or omitted | Present with `equivalent_to`: `true` when the two commit messages differ. |
| `count` | number or null | Total reachable commits when `--count` is set without `--left-right`; otherwise `null`. |
| `left_right` | object or omitted | When `--count` and `--left-right` are set: `left` and `right` commit counts for the symmetric range. |
| `truncated` | boolean | `true` when more commits matched than returned (`-n`). |
| `next` | null | Reserved for future paging; always `null` today. |

Example (listing):

```json
{
  "commits": [
    {
      "oid": "83352a61f6715ec3f0a297c6d6150725154fb833",
      "parents": [
        "062ca6e74f5603f4d09063c0f46cd07d8c96e019"
      ],
      "author": {
        "name": "Test",
        "email": "test@example.com",
        "date": "2023-11-14T22:13:20Z"
      },
      "committer": {
        "name": "Test",
        "email": "test@example.com",
        "date": "2023-11-14T22:13:20Z"
      },
      "subject": "second",
      "message": "second",
      "refs": [
        {
          "name": "HEAD",
          "kind": "head"
        },
        {
          "name": "main",
          "kind": "branch"
        }
      ],
      "relative_date": "[TIME_AGO]",
      "change_id": "xzyqzyyzswyupvtlsovyzultryuqzlvk",
      "change_id_stored": true
    },
    {
      "oid": "062ca6e74f5603f4d09063c0f46cd07d8c96e019",
      "parents": [],
      "author": {
        "name": "Test",
        "email": "test@example.com",
        "date": "2023-11-14T22:13:20Z"
      },
      "committer": {
        "name": "Test",
        "email": "test@example.com",
        "date": "2023-11-14T22:13:20Z"
      },
      "subject": "first",
      "message": "first",
      "refs": [
        {
          "name": "feature",
          "kind": "branch"
        }
      ],
      "relative_date": "[TIME_AGO]",
      "change_id": "prkwwuwrytvxrwozplzrxmvozwutplkq",
      "change_id_stored": true
    }
  ],
  "count": null,
  "truncated": false,
  "next": null
}
```

Example (`--cherry-mark -n 1 old-feature...feature`):

```json
{
  "commits": [
    {
      "oid": "09d5318d2c9bb2881fd2b503861aadf43737463e",
      "parents": [
        "a41d2d81bcbea60b67ac7f6c530d71bea889b628"
      ],
      "author": {
        "name": "Test",
        "email": "test@example.com",
        "date": "2023-11-14T22:13:20Z"
      },
      "committer": {
        "name": "Test",
        "email": "test@example.com",
        "date": "2023-11-14T22:13:20Z"
      },
      "subject": "c3",
      "message": "c3",
      "refs": [
        {
          "name": "old-feature",
          "kind": "branch"
        }
      ],
      "relative_date": "[TIME_AGO]",
      "change_id": "sntxlnlnxkouurtynzpmvokryyvmmqwv",
      "change_id_stored": false,
      "side": "left",
      "equivalent": true,
      "equivalent_to": "05075c9436c17c49302513b5960c332ecfcdbae4",
      "message_changed": true
    }
  ],
  "count": null,
  "truncated": true,
  "next": null
}
```

Example (`--count`):

```json
{
  "commits": [],
  "count": 2,
  "truncated": false,
  "next": null
}
```

Example (`--count --left-right`):

```json
{
  "commits": [],
  "count": null,
  "truncated": false,
  "next": null,
  "left_right": {
    "left": 3,
    "right": 5
  }
}
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/revs/schemas/revs/v1.json/index.md)

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a heading and bullet list of oid/subject pairs, or a bold count when `--count` is used.




```text
# Commits

- `83352a61f6715ec3f0a297c6d6150725154fb833` second
- `062ca6e74f5603f4d09063c0f46cd07d8c96e019` first
```

With `--left-right` or `--cherry-mark`, each bullet starts with the side in bold, and equivalent pairs carry a note:

```text
# Commits

- **left, equivalent** `09d5318d2c9bb2881fd2b503861aadf43737463e` c3 _(message changed, pairs with 05075c9436c1)_
- **right** `42f209db819ee73ae750d5d33a85a4a972c75c36` c4 edits f1
- **right, equivalent** `05075c9436c17c49302513b5960c332ecfcdbae4` c3 reworded _(message changed, pairs with 09d5318d2c9b)_
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[grit log](https://grit-scm.com/docs/log/index.md), [grit merge-base](https://grit-scm.com/docs/merge-base/index.md), [grit patch-id](https://grit-scm.com/docs/patch-id/index.md), [grit shortlog](https://grit-scm.com/docs/shortlog/index.md)

# https://grit-scm.com/docs/show/index.md

# grit show

> Show a commit, tag or branch, and the change it introduced.

## Synopsis

```text
grit show [<object>…] [--diff-merges first-parent|combined] [--stat | --numstat | --shortstat | --name-only | --name-status] [-U[n]] [-W]
  [--pathspec-from-file <file|->] [--pathspec-file-nul] [-- <path>…]
```

## Description

Shows a commit's id, author, date and full message, followed by the change that commit introduced (delta-style patch by default, like `grit diff <commit>`). With no argument, it shows the current commit.

`<object>` can be a commit id (full or short), an expression like `HEAD~2`, a branch or a tag. For a branch or tag, the first line names it. For an annotated tag, the tag's own author, date and message come before the commit it points at.

**Merge commits** default to **combined** parent diffs (`--diff-merges=combined`, like `git show --cc`). Use `--diff-merges=first-parent` for a diff against the first parent only.

Pass several `<object>` values to show more than one commit (human and markdown output are concatenated). With `--json`, multiple objects are wrapped as `{ "objects": [ … ] }`; a single object keeps the usual top-level shape.

`revision:path` specs (same resolution as [`grit cat`](https://grit-scm.com/docs/show/cat.md/index.md)) show blob contents or list tree entries without commit metadata.

Use `--stat` (or other diff format flags below) instead of the default patch. Limit output to paths with `-- <path>…` after the commit arguments.

In a shallow clone, a commit listed in `.git/shallow` is diffed like a root (against the empty tree), even when its object still names a missing parent.

## Options

| Option | Description |
| --- | --- |
| `<object>…` | Commits, branches, tags, or `rev:path` specs. Defaults to `HEAD`. |
| `--diff-merges` | `combined` (default) or `first-parent` for merge commits. |
| `-p`, `--patch` | Full patch (the default). |
| `--patch-text` | Git-apply-compatible unified patch on stdout (`git diff --binary` shape): branch or tag metadata (when present), commit metadata, then `diff --git` / `index` / hunks. Preserves this order when stdout is piped or redirected. Honors trailing pathspecs. Merge commits omit the patch unless `--diff-merges=first-parent`. Human output only; not combinable with `--json` or `--markdown`. |
| `-W`, `--function-context` | Expand patch hunks to enclosing function boundaries (same as [`grit diff`](https://grit-scm.com/docs/show/diff.md/index.md)). |
| `--stat` | Summary with change bars per file instead of a full patch. |
| `--numstat` | Machine-readable `insertions<TAB>deletions<TAB>path` lines. |
| `--shortstat` | Only the summary line (`N files changed, …`). |
| `--name-only` | Changed paths, one per line. |
| `--name-status` | Status letter and path(s) per line. |
| `-p`, `--patch` | Unified patch (default when no other format flag is set). |
| `-U`, `--unified <n>` | Lines of context around each change in patch mode (bare `-U` means 3). |
| `-W`, `--function-context` | Expand hunks to enclosing function boundaries (patch mode). |
| `-p`, `--patch` | Unified patch output (default when no other format flag is set). |
| `--pathspec-from-file <file\|->` | Read pathspecs from a file (`-` for stdin), in addition to argv paths after `--`. |
| `--pathspec-file-nul` | `--pathspec-from-file` entries are NUL-separated. |
| `-- <path>…` | Limit the diff to these paths (pathspecs). |

## Examples

Show the latest commit with patch (default):

```console
$ grit show
branch feature
commit cf18394a62c3f845bd9c44927a5a55e014b2a99d
change yrwyvtvk
Author: Ada Lovelace <ada@example.com>
Date:   2026-10-07 10:00:00 +0000

    Say hi

## main.rs
**status:** modified

- 1  1
+ 1  2
 context line
- old line
+ new line
```

Show only the diffstat (previous default style):

```console
$ grit show HEAD --stat
```

Show one file from a commit:

```console
$ grit show HEAD~1 -- README.md
```

Show what a tag points at:

```console
$ grit show v0.1
```

Get the subject of a commit:

```console
$ grit show HEAD~1 --json --filter .commit.subject
"Start the project"
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/show/schemas/show/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `objects` | array | When more than one `<object>` is requested: each element is a commit show object or a `rev:path` blob/tree object (below). |
| `warnings` | array | Non-fatal diagnostics emitted while resolving the object; omitted when empty. |
| `kind` | string | For a commit, branch, tag, or annotated tag: `commit`, `branch`, `tag`, or `annotated_tag`. For `rev:path`: `blob` or `tree`. |
| `ref_name` | string | Branch or tag name when you named a ref; omitted for a raw commit id. |
| `tag` | object | For an annotated tag: `name`, `tagger`, and `message`. |
| `commit` | object | Shared [`CommitJson`](https://grit-scm.com/docs/README.md/index.md#commit-json-object-commitjson) row: `oid`, parents, author, committer, subject, message, ref decorations, `change_id`, and `change_id_stored`. |
| `files` | array | Per-file diff rows (same shape as [`grit diff`](https://grit-scm.com/docs/show/diff.md/index.md) `--json`), including optional `combined_status` (`MM`, `DD`, …) on combined merge name-status output. |
| `totals` | object | Aggregate line counts when a stat-style format is selected; omitted for patch-only output unless the library computed totals. |
| `stat` | object | Summary diffstat with `files`, `files_changed`, `insertions`, and `deletions` (always present on commit shows). |
| `spec` | string | For `rev:path`: the object spec you passed (for example `HEAD:README.md`). |
| `path` | string | For `rev:path`: repository-relative path after the first revision colon. |
| `oid` | string | For `rev:path`: object id of the blob or tree. |
| `size` | integer | For `rev:path`: uncompressed object size in bytes. |
| `text` | string | For a text blob at `rev:path`; omitted for binary blobs. |
| `data_base64` | string | For a binary blob at `rev:path`; standard base64 of raw bytes. |
| `binary` | boolean | For `rev:path` blobs: true when `data_base64` is used instead of `text`. |
| `entries` | array | For `rev:path` trees: `mode`, `type`, `oid`, and `path` per entry. |

Combined merge hunks may attach a `parents` array on each patch line in `files[].hunks[].lines[]`.

Example:

```json
{
  "kind": "branch",
  "ref_name": "main",
  "commit": {
    "oid": "83352a61f6715ec3f0a297c6d6150725154fb833",
    "parents": [
      "062ca6e74f5603f4d09063c0f46cd07d8c96e019"
    ],
    "author": {
      "name": "Test",
      "email": "test@example.com",
      "date": "2023-11-14T22:13:20Z"
    },
    "committer": {
      "name": "Test",
      "email": "test@example.com",
      "date": "2023-11-14T22:13:20Z"
    },
    "subject": "second",
    "message": "second",
    "refs": [
      {
        "name": "HEAD",
        "kind": "head"
      },
      {
        "name": "main",
        "kind": "branch"
      }
    ],
    "relative_date": "[TIME_AGO]",
    "change_id": "xzyqzyyzswyupvtlsovyzultryuqzlvk",
    "change_id_stored": true
  },
  "files": [
    {
      "path": "second.txt",
      "status": "added",
      "new_mode": "100644",
      "binary": false,
      "hunks": [
        {
          "old_start": 0,
          "new_start": 1,
          "old_lines": 0,
          "new_lines": 1,
          "lines": [
            {
              "kind": "add",
              "new": 1,
              "text": "second file"
            }
          ]
        }
      ]
    },
    {
      "path": "tracked.txt",
      "status": "modified",
      "old_mode": "100644",
      "new_mode": "100644",
      "binary": false,
      "hunks": [
        {
          "old_start": 1,
          "new_start": 1,
          "old_lines": 1,
          "new_lines": 1,
          "lines": [
            {
              "kind": "del",
              "old": 1,
              "text": "tracked v1"
            },
            {
              "kind": "add",
              "new": 1,
              "text": "tracked v2"
            }
          ]
        }
      ]
    }
  ],
  "stat": {
    "files": [
      {
        "path": "second.txt",
        "status": "added",
        "insertions": 1,
        "deletions": 0,
        "binary": false
      },
      {
        "path": "tracked.txt",
        "status": "modified",
        "insertions": 1,
        "deletions": 1,
        "binary": false
      }
    ],
    "files_changed": 2,
    "insertions": 2,
    "deletions": 1
  }
}
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/show/schemas/show/v1.json/index.md)

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for headings, commit metadata, the message body in a length-adaptive `text` fence (so commit text cannot forge grit headings or tables), and fenced `diff` blocks per file (or a diffstat table with `--stat`):

```text
# Commit `b52cca6`

**Oid:** `92501f188ae0815af09a0cef6e121eddda4113cf`
**Change:** `yrwyvtvk`
**Author:** Ada Lovelace <ada@example.com>
**Date:** 2026-10-07T14:54:02Z

## second

~~~diff
@@ -1,1 +1,2 @@
 line
+added
~~~
```


With no commits on the current branch yet, default `HEAD` fails with `branch_no_commits`:

```console
$ grit show
error: no commits yet on branch main — make one with `grit commit "message"`
hint: make one with `grit commit "message"`
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

- [`grit diff`](https://grit-scm.com/docs/show/diff.md/index.md) — compare commits, ranges, or the working tree without commit metadata.
- [`grit log`](https://grit-scm.com/docs/show/log.md/index.md) — list recent commits.

# https://grit-scm.com/docs/merge-base/index.md

# grit merge-base

> Find common ancestors or test whether one commit is an ancestor of another.

## Synopsis

```text
grit merge-base <A> <B> [--all] [--is-ancestor]
```

## Description

Finds merge bases between two commits, or checks reachability. With no flags, prints one minimal merge base (same default as Git). `--all` lists every minimal base (needed for criss-cross histories). `--is-ancestor` exits `0` when `A` is an ancestor of `B`, `1` when it is not, and prints nothing in human mode.

## Options

| Option | Description |
| --- | --- |
| `<A>`, `<B>` | Two commits or refs to compare. |
| `--all` | List all minimal merge bases. |
| `--is-ancestor` | Exit status only: ancestor test (`A` vs `B`). |

## Examples

Default merge base:

```console
$ grit merge-base main feature
919c45f33de5e5c0bd05f8ffb089f697f4644976
```

All merge bases:

```console
$ grit merge-base --all topic-a topic-b
```

Ancestor check (exit code 0):

```console
$ grit merge-base --is-ancestor HEAD~1 HEAD
$ echo $?
0
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/merge-base/schemas/merge-base/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `merge_bases` | array of strings | Hex object ids of merge bases (empty when `--is-ancestor` is set). |
| `is_ancestor` | boolean or null | `true` or `false` with `--is-ancestor`; otherwise `null`. |

Example:

```json
{
  "merge_bases": ["919c45f33de5e5c0bd05f8ffb089f697f4644976"],
  "is_ancestor": null
}
```

Example (`--is-ancestor`):

```json
{
  "merge_bases": [],
  "is_ancestor": true
}
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/merge-base/schemas/merge-base/v1.json/index.md)

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a short heading and bullet list of merge bases, or a sentence for `--is-ancestor`.



```text
# Merge bases

- `062ca6e74f5603f4d09063c0f46cd07d8c96e019`
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success, or `--is-ancestor` when the first commit is an ancestor of the second. |
| `1` | `--is-ancestor` when not an ancestor, or other failure. |
| `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md).


## See also

[grit revs](https://grit-scm.com/docs/revs/index.md), [grit log](https://grit-scm.com/docs/log/index.md), [grit diff](https://grit-scm.com/docs/diff/index.md)

# https://grit-scm.com/docs/notes/index.md

# grit notes

> List, show, add, and remove Git notes on commits.

## Synopsis

```text
grit notes [--ref REF]
grit notes list [--ref REF]
grit notes show <rev> [--ref REF]
grit notes add <rev> (-m <message> | -F / --message-file <path|->) [--force] [--dry-run] [--ref REF]
grit notes remove <rev>... [--dry-run] [--ref REF]
```

## Description

Git **notes** are extra blob objects attached to commits via a notes ref (default `refs/notes/commits`, or `core.notesRef` / `GIT_NOTES_REF`). They do not change history; they add metadata Git and other tools can read with `git notes`.

With no subcommand, `grit notes` lists every note under the selected ref. `show` prints one note body to stdout (like `git notes show`). `add` writes a new note commit; without `--force`, adding when a note already exists fails. `remove` drops notes from the given revisions in a single notes commit when multiple revs are passed.

Notes update commits use your configured `user.name` / `user.email` (and optional `GIT_*` overrides), with the committer date taken from the process clock passed into the library — the same identity rules as [`grit commit`](https://grit-scm.com/docs/notes/commit.md/index.md).

## Options

| Option | Description |
| --- | --- |
| `--ref` | Notes namespace (`commits`, `refs/notes/commits`, …). Overrides `core.notesRef` / `GIT_NOTES_REF`. |
| `-n`, `--limit <N>` | List at most `N` notes (`truncated` in JSON when more exist). |
| `-m`, `--message` | Note text for `add` (conflicts with `--message-file`). |
| `-F`, `--message-file` | Read note text from a file, or `-` for stdin (conflicts with `-m`). |
| `--force` | Replace an existing note on `add`. |
| `--dry-run` | Preview `add` or `remove` without writing objects, refs, or reflogs. |

Subcommands: `list`, `show`, `add`, `remove`.

## Examples

```console
$ grit notes add HEAD -m 'Reviewed by Alex'
Added note for abc1234

$ grit notes show HEAD
Reviewed by Alex

$ grit notes
abc1234567890abcdef1234567890abcdef123456  Reviewed by Alex

$ grit notes remove HEAD~1 HEAD
Removed note for def5678

$ grit notes list --ref refs/notes/review
No notes yet.
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/notes/schemas/notes/v1.json/index.md) (subcommands also have `notes.list`, `notes.show`, `notes.add`, and `notes.remove` schemas).

Pass `--json` for stable output. The top-level `action` field is `list`, `show`, `add`, or `remove`.

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `action` | string | `list`, `show`, `add`, or `remove`. |
| `notes_ref` | string | Ref that was read or updated. |
| `notes` | array | For `list`: `object`, `blob`, and `body` for each note. |
| `truncated` | boolean | For `list`: `true` when more notes exist than returned (`-n`). |
| `object` | string | For `show` / `add`: annotated commit id (full hex). |
| `body` | string | For `show`: note text. |
| `replaced` | boolean | For `add`: whether a note was overwritten. |
| `dry_run` | boolean | For `add` / `remove`: `true` when nothing was written. |
| `notes_ref_old` | string or null | For `add` / `remove` dry-run: notes ref tip before the operation. |
| `notes_ref_new` | string or null | For `add` / `remove` dry-run: predicted notes ref tip after the operation. For `remove` with several revisions, this is the single notes commit the real run writes; `null` when no listed revision has a note. |
| `note_blob` | string or null | For `add` dry-run: blob id that would store the note bytes. |
| `objects` | array | For `remove`: ids whose notes were removed (or would be, with `--dry-run`), in argument order. Revisions without a note and repeats are left out. |

Listing:

```json
{
  "action": "list",
  "notes_ref": "refs/notes/commits",
  "notes": [
    {
      "object": "abc1234567890abcdef1234567890abcdef123456",
      "blob": "d719f2387b35d9751843418fe3b613e61d7fd2d0",
      "body": "Reviewed by Alex\n"
    }
  ]
}
```

## Markdown output

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output.

Schema: [v1](https://grit-scm.com/docs/notes/schemas/notes/v1.json/index.md)

List actions render a heading with the notes ref and one bullet per note (short object id and body preview). Show wraps the note body in a fenced `text` block. Add and remove print a short confirmation line per action; with `--dry-run` it starts with "Would" (for example ``Would remove notes on `refs/notes/commits`:``).



```text
## Notes (`refs/notes/commits`)
- _(no notes)_
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[Library: Notes](https://grit-scm.com/docs/library/notes/index.md), [`grit show`](https://grit-scm.com/docs/notes/show.md/index.md)

# https://grit-scm.com/docs/describe/index.md

# grit describe

> Nearest reachable tag, exact commit distance, and abbreviated id for a revision.

## Synopsis

```text
grit describe [REV] [--tags] [--match GLOB] [--first-parent] [--abbrev N]
```

## Description

Finds the nearest tag reachable from `REV` (default `HEAD`) and reports the exact number of commits in the range from the tag’s peeled commit to `REV`. Output uses the long form `tag-distance-gabbrev` (including `-0-` when `REV` is exactly the tag commit).

By default only annotated tags are considered; `--tags` includes lightweight tags. The distance is the exact `peeled..REV` count (what `grit revs --count` reports), which can differ from Git’s lazy `git describe` depth and from which tag Git picks when many tags are reachable.

## Options

| Option | Description |
| --- | --- |
| `REV` | Commit or ref to describe (default `HEAD`). |
| `--tags` | Include lightweight tags (default: annotated only). |
| `--match GLOB` | Only consider tags whose short name matches `GLOB`. |
| `--first-parent` | Count distance along first-parent chains only. |
| `--abbrev N` | Minimum abbreviated commit id length (default follows `core.abbrev`, extending on collision like Git). |

## Examples

```console
$ grit describe --tags
v1.2.0-3-g4a1b2c3
```

With `--json`:

```console
$ grit describe --tags --json
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/describe/schemas/describe/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `tag` | string | Full `refs/tags/…` name. |
| `tag_short` | string | Short tag name. |
| `tag_oid` | string | Object id at the tag ref. |
| `peeled` | string | Peeled commit oid. |
| `distance` | integer | Exact commits in `peeled..commit`. |
| `commit` | string | Described commit oid. |
| `abbrev` | string | Abbreviated commit oid. |
| `long_format` | string | `tag-distance-gabbrev` line. |

Example:

```json
{
  "tag": "refs/tags/v1.2.0",
  "tag_short": "v1.2.0",
  "tag_oid": "a1b2c3d4e5f6789012345678901234567890abcd",
  "peeled": "1111111111111111111111111111111111111111",
  "distance": 3,
  "commit": "2222222222222222222222222222222222222222",
  "abbrev": "2222222",
  "long_format": "v1.2.0-3-g2222222"
}
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/describe/schemas/describe/v1.json/index.md)

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a short heading and bullet list of the tag, distance, and abbrev.

```text
# Describe

- **Tag:** `v1.2.0`
- **Distance:** 3
- **Commit:** `2222222`
- **Long:** `v1.2.0-3-g2222222`
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success. |
| `1` | No reachable tag, or other failure. |
| `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md).

## See also

- [`revs`](https://grit-scm.com/docs/describe/revs.md/index.md) — count commits in a range.
- [`tag`](https://grit-scm.com/docs/describe/tag.md/index.md) — list or create tags.

# https://grit-scm.com/docs/rebase/index.md

# grit rebase

> Replay local commits onto a new base; recover from conflicts and exec commands that leave edits.

## Synopsis

```text
grit rebase [<upstream>]
grit rebase [--onto <rev>] [<upstream>]
grit rebase --continue | --abort | --skip
grit history rebase [<upstream>]
grit rebase|history rebase … [--check] [-X ours|theirs] [--dry-run] [--exec <cmd>]… [--fork-point] [--no-fork-point] [--update-refs=(branches|head)] [--empty=(drop|keep|abort)] [--keep-committer] [--no-verify]
```

## Description

`grit rebase` replays commits reachable from `HEAD` but not from `<upstream>` onto `<upstream>` (or onto `--onto` when set). It uses the same history engine as [`grit history`](https://grit-scm.com/docs/rebase/history.md/index.md). When every commit replays cleanly, grit writes new commit objects and updates refs in one batch.

During checkout or replay, Ctrl+C (or `SIGTERM` / `SIGHUP` on Unix) stops with `error: operation cancelled` and exit code **130**. Partial ref moves and the worktree are rolled back, and no stale `.git/index.lock` is left behind. A second interrupt exits immediately without cleanup.

Before it replays anything, grit runs the `pre-rebase` hook with the upstream as you typed it (`pre-rebase main`), or the configured upstream's full ref name (`pre-rebase refs/remotes/origin/main`) when you omitted it, as Git does. It runs once there is something to replay and before any commit is replayed, so a refusal comes before a replay conflict on every path (`-X` and `--exec` included): not when the branch is already up to date, and not for `--check`, `--dry-run`, `--continue`, `--skip` or `--abort`. When the hook exits non-zero, the rebase stops with exit **1** and a `hook_failed` error, and nothing changes. `--no-verify` skips it.

```console
$ grit rebase main
error: hook pre-rebase failed with exit status 1
$ grit rebase main --no-verify
Rebased 1 commit(s)
  commit 9c1f2d3 → 4e5a6b7 (feature work)
  refs/heads/feature 9c1f2d3 → 4e5a6b7
```

When the rebase moves the branch, grit runs the `post-checkout` hook with Git's arguments, `<old tip> <onto> 1`: Git checks out the onto commit before replaying, and the hook names that commit even though grit applies the rebase in one step. This also happens when a rebase stops on conflicts. When the rebase finishes, grit runs `post-rewrite rebase` with one `<old> <new>` line per replayed commit on stdin, oldest first. Dropped commits, commits already upstream, and fast-forwards are not listed, so a fast-forward rebase runs only `post-checkout`. Unlike Git, grit does not run `post-commit` for each replayed commit. Hook exit statuses never change the result. See [`grit hooks`](https://grit-scm.com/docs/rebase/hooks.md/index.md).

When `notes.rewriteRef` is configured, grit copies notes from each replayed commit to its replacement (same rules as Git's `git notes copy --for-rewrite`) before `post-rewrite` runs. See the [notes library guide](https://grit-scm.com/docs/library/notes.md/index.md).

A commit whose patch is already upstream (for example one you cherry-picked from the upstream branch) is skipped, as `git rebase` skips it. The commits before and after it are still replayed in order on top of the new base, and a branch that pointed at the skipped commit moves to the replayed commit before it, or to the new base when nothing came before. In the output and the `rewritten` JSON rows, the skipped commit maps to the upstream commit that carries its patch.

When `<upstream>` is omitted, grit uses `@{upstream}` of the current branch. If no upstream is configured, the command fails with a hint to run [`grit branch -u`](https://grit-scm.com/docs/rebase/branch.md/index.md). On a **detached `HEAD`**, an explicit `<upstream>` is required (same as `git rebase`); omitting it fails with `cannot rebase detached HEAD without an upstream argument`. With implicit upstream on a branch, grit uses the upstream tracking ref's reflog to find where your branch forked (`rebase.forkPoint`, default true), matching `git rebase` with `--fork-point`. An explicit `<upstream>` uses the merge base unless you pass `--fork-point`; `--no-fork-point` disables reflog fork detection even for implicit upstream.

When replay stops on conflicts, grit writes Git-compatible `.git/rebase-merge/` state (including `grit-plan`), leaves conflict markers in the worktree, and exits **1**. As with [`grit pick`](https://grit-scm.com/docs/rebase/pick.md/index.md) (and `git rebase`), the incoming `>>>>>>>` marker names the commit being replayed as `<abbrev> (<subject>)`, so each stop shows which commit it came from; the current side is `HEAD`. The branch tip recorded in `orig-head` is unchanged until you `--continue`, `--skip`, or `--abort`. While stopped (and after `--abort` re-attaches the branch), grit appends `HEAD` reflog entries for each detach and reattach so `HEAD@{0}` always matches the current `HEAD` and `HEAD@{n}` recovery stays consistent. Resume with the same conflict model as [`grit pick`](https://grit-scm.com/docs/rebase/pick.md/index.md) and [`grit revert`](https://grit-scm.com/docs/rebase/revert.md/index.md): inspect (`grit diff`), resolve, then either stage and `grit rebase --continue` (`grit add` + `--continue`) or record the resolution with [`grit commit`](https://grit-scm.com/docs/rebase/commit.md/index.md) (auto-staging applies) and run `grit rebase --continue` to replay only the remaining commits. Use `--skip` / `--abort` to drop the stopped pick or restore `orig-head` (the checked-out branch, or detached `HEAD` when the rebase started detached). [`grit pull --rebase`](https://grit-scm.com/docs/rebase/pull.md/index.md) stops the same way.

When the replayed range contains merge commits (the default, unlike `git pull --rebase`), grit keeps merge topology like `git rebase --rebase-merges`: the first-parent chain from your branch tip is replayed onto the new base; a side branch that forked at the rebase boundary is replayed onto the new base, while one that forked inside the range follows its rewritten parent until mapping moves it, and resolving a conflict on a merge commit with `--continue` keeps every parent (the current `HEAD` as the first parent, mapped originals for the rest). Merged-in files and refs on side branches are not dropped silently.

Stopping resets the index and worktree to the replayed commits, so grit only stops when that loses nothing. If replay would conflict while you have staged or unstaged changes, or an untracked file sits where the stop would check out a path, the rebase refuses (`kind: dirty_worktree`, or the untracked-overwrite error) and nothing changes; commit or stash first. A rebase that replays cleanly still carries local changes along, like a branch switch.

The conflict stop state is complete enough for `git` to take over: `git rebase --continue`, `--skip` and `--abort` all work on a rebase grit started (grit writes `author-script`, `stopped-sha` and the current pick in `done`, as git does). With the default `--update-refs=branches`, Git's todo lists only the rebased branch's own commits so `git rebase --continue` finishes that branch; stacked-branch updates happen when you resume with `grit rebase --continue`.

A rebase that replays commits records the branch's pre-rebase tip in `ORIG_HEAD`, as `git rebase` does. That includes `-X ours|theirs`, `--exec` (including when the branch is already based on the upstream and only the commands run), a rebase that stops on conflicts, and an `--exec` stop (`exec_dirty` or a replay conflict after an amending command); an `--exec` command that fails rolls everything back and leaves `ORIG_HEAD` alone. It stays there after the rebase finishes, `--continue`, `--skip` or `--abort`, so `grit reset --hard ORIG_HEAD` undoes a finished rebase. When there is nothing to replay and no `--exec`, `--check` and `--dry-run`, `ORIG_HEAD` is left alone.

When grit records history for [`grit history undo`](https://grit-scm.com/docs/rebase/history.md/index.md), finishing a conflict stop with `--continue` or `--skip` writes `.git/grit/history-last` from the reattached branch (pre-rebase tip to final tip), the same shape as a rebase that never stopped.

A rebase that `git` started (`.git/rebase-merge/` or `.git/rebase-apply/` without `grit-plan`) blocks `grit rebase <upstream>` and [`grit switch`](https://grit-scm.com/docs/rebase/switch.md/index.md). `grit rebase --abort` cancels it: `HEAD` is re-attached to the rebased branch at `orig-head`, the index and worktree are reset, git's state directory is removed, and unresolved rerere records for the abandoned conflict (`MERGE_RR`) are cleared, as `git rebase --abort` does. When git recorded an autostash, grit leaves the rebase alone and asks you to run `git rebase --abort`. `grit rebase --continue` and `--skip` refuse with a pointer to `git rebase --continue` / `--skip`, since only git can resume its own todo list.

`--check` predicts success or conflicts without touching refs, the index, or the worktree (exit **1** when conflicts are predicted, like [`grit merge --check`](https://grit-scm.com/docs/rebase/merge.md/index.md)). It does not start a rebase session.

`-X ours` and `-X theirs` auto-resolve replay conflicts the way `git rebase -X` does. During replay, **ours** is the onto (upstream) side and **theirs** is the commit being replayed — the opposite of everyday merge wording where “ours” is your checked-out branch. A conflict that `-X` cannot resolve (for example a file deleted on one side and modified on the other) stops the rebase like any other conflict, and `--continue` keeps replaying with the same `-X` side.

`--dry-run` still uses the stateless planner only: it lists ref updates without starting a session and without writing objects for a real rebase.

When there is nothing to replay and no `--exec` commands, human output is `Already up to date` and `--json` sets `result` to `completed` with `rewritten` as `[]`. With `--exec`, grit still runs the commands at every commit in the rebase range even when the branch is already based on the upstream (the usual `git rebase -x` idiom for testing each commit). Human output is `Exec commands ran; branch is unchanged`, `--json` includes an `exec` array, and `rewritten` stays empty when no commit OIDs changed. A failing command still rolls back and returns the command's exit code.

Shared rewrite flags match [`grit history`](https://grit-scm.com/docs/rebase/history.md/index.md): `--dry-run`, `--update-refs`, `--empty`, and `--keep-committer`.

With the default `--update-refs branches`, stacked branches move with the rebase: a branch on one of the replayed commits, or on a commit built on top of them, ends up on its replayed copy. Another branch at the same commit as the checked-out branch is not moved, so a `backup` branch created right before the rebase still points at the original commits:

```console
$ grit branch backup
$ grit rebase main
Rebased 2 commit(s)
  commit cc10d19 → 931f74a (X)
  commit 874d334 → 8489106 (Y)
  refs/heads/feature 874d334 → 8489106
$ grit log --oneline backup
874d334 Y
cc10d19 X
70709d8 base
```

### Exec commands that amend or add commits

An `--exec` command may rewrite the commit it runs at, the way it can with `git rebase
--exec`. When it exits zero with a detached `HEAD` that amends the replay commit, or
adds new commits on top of it, grit keeps the result: later commits are replayed onto
the new `HEAD`, later commands see its tree, and the branch ends up on the rewritten
history. The common "format every commit" loop works as expected:

```console
$ grit rebase main --exec 'cargo fmt && git commit -qa --amend --no-edit'
Rebased 2 commit(s)
  commit d9b09e2 → 4ec1aa7 (one)
  commit 3fe1bb2 → 0c24bc2 (two)
  refs/heads/feature 3fe1bb2 → 0c24bc2
```

`git commit --amend` keeps the commit's change id. A command that leaves `HEAD`
anywhere else (switching branches, resetting the commit away) fails the rebase: grit
restores `HEAD`, the index, and the worktree without moving refs, and the commits the
command made stay in the object database.

If the first replayed commit conflicts before any `--exec` command runs, grit stops the same
way as a plain rebase: conflict markers, `rebase-merge/grit-plan`, and the branch ref left at
its pre-rebase tip. If a later commit no longer applies on top of an amended one, replay
stops with `result: "conflicts"` and conflict markers, like any rebase conflict, without
undoing the commits already rewritten. Resolve and stage the paths, then run
`grit rebase --continue` (the exec commands run at the resolved commit), or use
`--skip` to drop that commit (its exec commands still run, at the current `HEAD`, as
with Git), or `--abort` to restore the original branch. Resuming keeps the options the
rebase started with, such as `--empty keep`; there is no need to repeat them.

### Successful exec commands that leave edits

After **every** successful `--exec` command, grit reloads the index and checks tracked
staged and unstaged changes against the resulting `HEAD` (the replay commit, or the
commit the command amended it into). If anything changed, replay stops immediately
with exit **1** and `result: "exec_dirty"`. The edits and index stay exactly as the
command left them, `HEAD` remains detached at that commit, and the original branch
refs remain unchanged. Later exec commands do not run.

Save the edits before continuing:

```bash
grit stash push -m "exec edits"
grit rebase --continue
grit stash pop
```

`--continue` resumes after the successful command, so it does not repeat the edit.
`--skip` skips any remaining exec commands at that commit and keeps the already
replayed commit. Both require a clean index and worktree at the recorded replay
HEAD. If you move HEAD or create a commit while stopped, save new commits on a
branch, then abort and restart. `--abort` explicitly discards exec edits and restores
the original HEAD, index, and tracked files; save any edits you want first.

Exec stops use grit's `rebase-merge/grit-exec` recovery record. Resume these with
grit. Commands exiting nonzero retain their existing rollback behavior and command
exit code.

If grit is interrupted (Ctrl-C or `kill`) while an `--exec` command is running, the
recovery record is kept at the detached replay commit. `grit status` reports the
interrupted rebase and suggests `--continue` or `--abort`; `--abort` restores the
branch tip, index, and worktree from before the rebase started.

Starting a second rebase while one is already paused:

```console
$ grit rebase main
error: cannot rebase while a rebase is in progress; finish it with `grit rebase --continue` or cancel it with `grit rebase --abort`
```

### When the branch moves during a stop

Something else may move the rebased branch while the rebase is stopped: a commit from
another worktree, `git branch -f`, `git update-ref`, or checking the branch out and
amending it. The saved plan no longer applies then, so `--continue` and `--skip` refuse
with exit **1** and change nothing:

```console
$ grit rebase --continue
error: refs/heads/feature moved to 045e4cc while the rebase was stopped, so it cannot be continued or skipped; run `grit rebase --abort` to restore refs/heads/feature to b37ca7f (the moved tip stays in its reflog)
```

`--abort` always works: it resets the branch to its pre-rebase tip (`orig-head`), clears
the rebase state, and reports the tip it overwrote, which stays reachable as
`<branch>@{1}` (logged as `rebase (abort)`). This holds for conflict stops and exec stops
alike:

```console
$ grit rebase --abort
Rebase aborted.
  refs/heads/feature was moved during the rebase; reset 045e4cc → b37ca7f (the moved tip stays in its reflog)
```

In `--json`, the overwritten branch appears in `refs` as `{ref, old, new}`, with `old`
the moved tip and `new` the restored one. An abort of an unmoved branch has no `refs`.

## Options

| Option | Description |
| --- | --- |
| `<upstream>` | Exclude commits reachable from this revision (default: `@{upstream}`). |
| `--onto` | Replay onto this revision instead of `<upstream>`. |
| `--continue` | Finish the current conflict resolution (including a replay conflict after an amending exec), or resume exec after saving its edits. |
| `--abort` | Cancel the rebase and restore the branch or detached `HEAD` to `orig-head`, even if something moved it during the stop (the overwritten tip is reported). Also cancels a rebase that `git` started. |
| `--skip` | Skip a conflicted commit, or remaining exec commands at an exec stop (save edits first). |
| `--dry-run` | List ref updates without moving refs (no session). |
| `--update-refs` | `branches` (default: the checked-out branch and every stacked branch on or above the replayed commits, but not other branches at the `HEAD` commit) or `head`. |
| `--empty` | `drop` (default), `keep`, or `abort` when a replay would become empty. |
| `--keep-committer` | Preserve committer ident and timestamp on replayed commits. |
| `--exec` | After each replayed commit is checked out, run `CMD` via `sh -c` in the worktree (repeatable; runs in order at every commit). Requires a clean index and worktree. Incompatible with `--dry-run`, `--check`, and `-X`. Command output goes to stderr. On nonzero command exit, grit restores `HEAD`, the index, and the worktree without moving refs; exit code is the command's exit code. A successful command may amend the replayed commit or add commits on top of it; later commits are replayed onto the result. A successful command that leaves tracked edits stops with `exec_dirty` and preserves them for recovery. |
| `--check` | Predict success or conflicts without changing refs, index, or worktree (conflicts with `--dry-run`). |
| `--fork-point` | Use the upstream reflog to find where the branch forked (on by default when `<upstream>` is omitted). |
| `--no-fork-point` | Use the merge base with `<upstream>` instead of the reflog fork point. |
| `-X ours\|theirs` | Auto-resolve replay conflicts in favor of the onto side (`ours`) or replayed commits (`theirs`). |
| `--no-verify` | Skip the `pre-rebase` hook. |

## Examples

```console
$ grit rebase --onto release/v2 origin/main --dry-run
Dry run — refs would change:
  commit abc1234 → def5678 (feature work)
  refs/heads/feature abc1234 → def5678
```

```console
$ grit rebase origin/main
CONFLICT (both_modified): docs/guide.md

Rebase stopped on conflicts; fix them and run `grit rebase --continue`, or `grit rebase --abort` / `grit rebase --skip`.
$ grit add docs/guide.md
$ grit rebase --continue
Rebased 3 commit(s)
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/rebase/schemas/rebase/v1.json/index.md)

Pass `--json` on `grit rebase` or `grit history rebase`:

| Field | Type | Meaning |
| --- | --- | --- |
| `result` | string | `completed`, `conflicts`, `exec_dirty`, or `aborted`. |
| `operation` | string | `rebase` when present. |
| `rewritten` | array | `{old,new,change_id,subject}` per replayed commit when `result` is `completed`. |
| `refs` | array | `{ref,old,new}` for each ref that moved. For `aborted`, each branch the abort reset after something else moved it during the stop (`old` is the overwritten tip, `new` the restored `orig-head`); omitted when nothing was overwritten. |
| `head` | object or null | `{old,new}` for the completed invocation's `HEAD` OID change; `null` when unchanged. Dry runs show the planned change; conflict and abort outcomes use `null`. |
| `dry_run` | boolean | Whether refs were left unchanged. |
| `exec` | array | Captured invocations during this call, on completion or an exec stop: `{commit, command, exit_code}` per invocation (full hex `commit`). |
| `commit` | string | Source commit for `conflicts`; `HEAD` after the command (the replay commit or its amended replacement) for `exec_dirty`. |
| `command` | string | Successful command that left edits, for `exec_dirty`. |
| `paths` | array of strings | Changed tracked paths at an exec stop. |
| `conflicts` | array | `{path,kind,summary?}` when `result` is `conflicts`; `kind` is a [conflict kind](https://grit-scm.com/docs/status/index.md#conflict-kinds). |
| `rerere` | array | Rerere events when `rerere.enabled` is active at a conflict stop (`path`, `kind` as for [`grit merge`](https://grit-scm.com/docs/merge/index.md#json-output)). Omitted when empty. |
| `next_steps` | array | Ordered `grit` commands after a stop. |
| `alternatives` | array | `grit rebase --abort` and `grit rebase --skip` when paused. |

For completed results, `head.old` is the OID immediately before this command and `head.new` is the final OID. On `--continue` and `--skip`, this compares the stopped, detached `HEAD` with the completed branch tip after reattachment. `refs` and `rewritten` still describe the whole rebase, so their old OIDs can differ from `head.old`. Skipping the final conflicting commit can reattach `HEAD` without changing its OID; then `head` is `null`.

After resolving a conflict (with `grit add` or `grit commit`), `grit rebase --continue --json` reports:

```json
{
  "result": "completed",
  "operation": "rebase",
  "rewritten": [
    {
      "old": "420bacbf7a90d30965b669336667fc144be897c1",
      "new": "77fc7445860c1cc5a111ddd9bc9e0be97884522c",
      "change_id": "rwlqysmxxrwkltttnnqttmptqznozqul",
      "subject": "feature"
    }
  ],
  "refs": [
    {
      "ref": "refs/heads/feature",
      "name": "refs/heads/feature",
      "old": "420bacbf7a90d30965b669336667fc144be897c1",
      "new": "77fc7445860c1cc5a111ddd9bc9e0be97884522c"
    }
  ],
  "head": {
    "old": "8f302b0a5bc73aecb1c2f23b8a00953c7c64ed6c",
    "new": "77fc7445860c1cc5a111ddd9bc9e0be97884522c"
  }
}
```

With `--check` when already up to date:

```json
{
  "operation": "rebase",
  "result": "up_to_date",
  "check": true
}
```

With `--check --json`, stdout is a result object instead of a stop/resume payload:

Schema: [rebase.check v1](https://grit-scm.com/docs/rebase/schemas/rebase.check/v1.json/index.md)

| Field | Type | Meaning |
| --- | --- | --- |
| `operation` | string | Always `rebase`. |
| `result` | string | `up_to_date`, `clean`, or `conflicts`. |
| `check` | boolean | Always `true`. |
| `commits` | array of strings | Replacement commit OIDs when `result` is `clean`. |
| `conflicts` | array | `{path, kind}` entries when `result` is `conflicts`, with the [conflict kind](https://grit-scm.com/docs/status/index.md#conflict-kinds) the replay would leave. |
| `commit` | string | Original commit OID when `result` is `conflicts`. |
| `refs` | array of strings | Present when the conflicting commit is only on other branches that `--update-refs branches` would move: their full names. Rebasing with `--update-refs head` leaves them alone. |

Exit code is **0** for `up_to_date` and `clean`, **1** for `conflicts`.

## Markdown output

Schema: [v1](https://grit-scm.com/docs/rebase/schemas/rebase/v1.json/index.md)

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a `## Rebase` heading (or `## History rebase` for the alias). On conflict or exec stops, lists paths, the stopped commit, and `next_steps` / `alternatives` like pick and revert.



```text
## Rebase check

- Already up to date
```

On a branch with no commits yet, rebase onto any upstream fails with `branch_no_commits` and a hint to make the first commit (see [`grit log`](https://grit-scm.com/docs/rebase/log.md/index.md)).

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Rebase completed, `--check` predicts success, or `--dry-run`. |
| `1` | Conflicts, successful exec with tracked edits, `pre-rebase` refused (`kind: hook_failed`), or other failure. |
| `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |
| *varies* | `--exec` command failure ([`custom`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md).


## See also

- [`grit history`](https://grit-scm.com/docs/rebase/history.md/index.md) — other rewrite helpers (`reword`, `drop`, `squash`, …)
- [`grit status`](https://grit-scm.com/docs/rebase/status.md/index.md) — `operation` hints while a grit rebase is paused
- [`grit pull --rebase`](https://grit-scm.com/docs/rebase/pull.md/index.md) — fetch then rebase onto the remote tip
- [`grit push --force-with-lease`](https://grit-scm.com/docs/rebase/push.md/index.md) — publish rewritten history safely

# https://grit-scm.com/docs/history/index.md

# grit history

> Stateless history rewrite helpers (reword, and more over time).

## Synopsis

```text
grit history drop <commit>
grit history move <commit> (--before <anchor> | --after <anchor>)
grit history reword <commit> (-m <message> | -F / --message-file <path|-> | --author <ident>)
grit history reword <commit> --author <ident> [-m <message>]
grit history drop|move|reword|fixup|squash|absorb|rebase … [--dry-run] [--update-refs=(branches|head)] [--empty=(drop|keep|abort)] [--keep-committer]
grit history fixup <commit> [-m | -F / --message-file] [--hunks <id,…>] [--lines <path:start-end>] [-- <path>…]
grit history squash <range>… [-m | -F / --message-file | --combine]
grit history absorb [--base <rev>]
grit history rebase [<upstream>] [--onto <rev>]
grit history split <commit> -m <message> [--rest-message <message>] -- <path>…
grit history undo [--dry-run]
```

## Description

`grit history` groups **stateless** rewrite operations: grit plans how commits and refs should change, writes new commit objects into the object database, then applies ref updates in one atomic batch. There is no sequencer state file and no hooks run during planning. Once a rewrite is applied, grit runs `post-checkout` (`<old HEAD> <new HEAD> 1`) when `HEAD`'s tree changed, then `post-rewrite rebase` with an `<old> <new>` line per rewritten commit on stdin (dropped commits are left out), as Git does after `rebase -i`. `--dry-run` and `history undo` run no hooks. Rewrites preserve stable [change ids](https://grit-scm.com/docs/change-ids/index.md) on surviving logical changes and store derived ids when the source commit had no header. With `notes.rewriteRef` set, notes on rewritten commits are copied to the new objects before `post-rewrite` (see [notes](https://grit-scm.com/docs/library/notes.md/index.md)).

Shared behavior for every subcommand:

- **Interrupts** — while a rewrite is applying (checkout or ref updates), Ctrl+C (or `SIGTERM` / `SIGHUP` on Unix) stops with `error: operation cancelled` and exit code **130**. Partial work is rolled back and no stale `.git/index.lock` remains. A second interrupt terminates grit without that cleanup.
- **Conflicts abort** — if replaying a descendant would conflict, nothing is applied (planned objects may already exist in the ODB from planning). The error names the commit that could not be replayed. When that commit is only on another branch that `--update-refs branches` would move (a branch built on top of the edited commit), the error also names that branch and hints at `--update-refs head`, which rewrites only the current branch and leaves the others where they are.
- **`--dry-run`** — print which refs would move; refs, the index, and the worktree stay unchanged. New commit objects are still written during planning, matching Git’s `git history --dry-run` model. Commit signing is skipped during dry-run planning (no `gpg` / `ssh-keygen` invocation); a full run signs replacement commits when [`commit.gpgsign`](https://grit-scm.com/docs/commit/index.md) is enabled, like [`grit commit`](https://grit-scm.com/docs/commit/index.md).
- **`--update-refs`** — `branches` (default) updates every local branch whose tip descends from the edited commit, except other branches at the same commit as `HEAD` (a `backup` branch made before the edit keeps the old history); `head` updates only the commit `HEAD` points at.

### `drop`

Remove one commit from history and replay its descendants onto that commit’s first parent. The dropped commit’s tree changes are omitted; descendant commits are replayed with three-way merges like other history rewrites.

You cannot drop a **root** commit (no parent) or a **merge** commit itself. Descendant **merge** commits are replayed: mapped parents are updated and the merge tree is recomputed (first-parent transplant when side branches are unchanged, otherwise a fresh merge of the mapped parents).

### `move`

Reorder one commit on the **first-parent chain** of `HEAD` (no merge commits in the affected range). Grit replays the segment in the new order with the same cherry-pick semantics as other history helpers; branches pointing at commits in the segment move to the rewritten tips.

Provide exactly one of `--before` or `--after` naming another commit on that chain. Moving a commit to its current position is an error.

### `reword`

Replace one commit’s message and/or author and replay descendants onto the rewritten history. On the edited commit, tree and parents stay the same; only the message and/or author line change. Committer identity and time come from your configured committer and `GIT_COMMITTER_DATE`, like [`grit commit`](https://grit-scm.com/docs/history/commit.md/index.md).

Provide at least one of `-m` / `--message`, `--message-file` (use `-` to read from stdin), or `--author`. The author value uses the same `Name <email>` / bare-email rules as [`grit commit --author`](https://grit-scm.com/docs/history/commit.md/index.md); when you omit a date, grit keeps the edited commit’s author timestamp. Grit does not open an editor.

Descendant **merge** commits are replayed the same way as for [`drop`](#drop): parents are remapped and the merge tree is updated to match the rewritten first-parent chain.

### `fixup`

Fold **staged** changes into an earlier commit on the first-parent chain of `HEAD`, then replay descendants onto the rewritten history. Grit three-way merges staged edits into the target commit’s tree; descendant commits are replayed like other history rewrites. If the merge would make the target empty, grit aborts unless `--empty keep` or `--empty drop` is set (same shared `--empty` flag as other history subcommands).

Provide exactly one of `-m` / `--message` or `--message-file` when you want an explicit fixup message; otherwise grit uses the staged diff to build the amended commit.

### `absorb`

Assign **staged** hunks into the commits that last touched overlapping lines (between `--base` and `HEAD`), then replay descendants in **one** rewrite. Grit uses blame line mapping to find candidate commits and checks that each hunk commutes with commits after its target. Assigned hunks are folded into target commits via the same three-way merge as [`fixup`](#fixup); unassigned hunks stay staged.

`--base` is exclusive: commits at and before the base are not considered. When omitted, grit hides other local branch tips (except a second branch name at the checked-out tip, such as a backup or review branch parked at `HEAD`), applies an upstream fork-point when configured, and caps the stack at ten commits. When a hunk’s introducing commit is excluded because of another local tip, `--json` and human output report `hidden_by_ref` with the ref name and suggest `--base`.

### `rebase`

Replay commits on the current branch onto `<upstream>` (or `--onto`), matching [`grit rebase`](https://grit-scm.com/docs/history/rebase.md/index.md) including `--continue`, `--abort`, and `--skip`. Prefer the top-level command for everyday use; `grit history rebase` shares the same handler and JSON shape. `--exec` commands may [amend or add commits](https://grit-scm.com/docs/history/rebase.md/index.md#exec-commands-that-amend-or-add-commits) at each replayed commit; later commits are replayed onto the result. Successful `--exec` commands that leave tracked edits stop with `exec_dirty`, preserve the index and worktree, and use the same [exec recovery](https://grit-scm.com/docs/history/rebase.md/index.md#successful-exec-commands-that-leave-edits) workflow.

### `undo`

Restore branch tips (and the worktree when `HEAD`'s tree changed) from the last successful history rewrite that moved refs. Grit records each apply in `.git/grit/history-last` (ignored by `git fsck --strict`); `undo` inverts that plan when every recorded ref is still at its post-rewrite tip. A second `undo` redoes the rewrite. Recorded applies always write reflog entries for moved refs (even when `core.logAllRefUpdates=false`) so the pre-rewrite tips stay reachable until undo or reflog expiry.

`fixup` and `absorb` consume staged (or `--hunks` / `--lines` selected) edits. Undoing one puts those edits back: each consumed path gets the index entry and work tree file it had before the command, so a staged fixup comes back staged, unstaged edits on the same path come back unstaged, and a `--hunks` fixup leaves the selected hunks unstaged again. A staged submodule pointer comes back staged too; the submodule's own checkout is never touched. The saved state lives next to the record in `.git/grit/history-last-work` (also ignored by `git fsck`), and the next recorded rewrite replaces it. A second `undo` returns to the post-fixup state. Undo refuses to run when one of those paths changed after the command, because putting the edit back would overwrite the newer change.

```console
$ git add a.txt
$ grit history fixup HEAD~2
Fixed up 3 commit(s)
  commit 6904103 → 32a5464 (c1)
  commit 8b9fec5 → 384d455 (c2)
  commit 16a0857 → 46f21c2 (c3)
  refs/heads/main 16a0857 → 46f21c2
$ grit history undo
Undid last history rewrite
  refs/heads/main 46f21c2 → 16a0857
  restored a.txt (index and work tree)
$ git status --short
M  a.txt
```

A record written by an older grit has no saved state. Undoing a `fixup` or `absorb` from such a record still moves the refs, and prints the commit that still holds the folded edits (`unrestored_edits` in `--json`), so you can recover them from it.

There is nothing to undo when no record exists, when a listed ref moved, or when local changes would be overwritten by the checkout.

### `squash`

Fold every commit in a **connected** revision range into the **oldest** commit in that range, then replay descendants onto the new history. The squashed commit keeps the oldest commit's author and parents; its tree matches the range tip. By default the squashed commit keeps the oldest commit's message (including `amend!` handling inside the range). Use `-m` / `--message-file` for an explicit message, or `--combine` for an autosquash-style combined message from every commit in the range.

The range uses the same revision syntax as `git rev-list` (for example `HEAD~3..HEAD` or full OIDs `abc..def`). With `--update-refs head`, grit may fold at `HEAD` without replaying when the range ends at the current tip and the message mode allows it.

### `split`

Peel changes that match pathspecs out of one commit into a **new parent commit**, then leave the target commit’s tree unchanged and replay descendants. The new parent’s tree is the target’s first parent plus only the selected paths; the target commit keeps its author and tree (and its message unless `--rest-message` is set).

Provide `-m` / `--message-file` for the new parent commit and one or more paths after `--` (or `--pathspec-from-file`). Grit errors when the pathspec matches nothing or every change in the commit.

## Options

| Option | Description |
| --- | --- |
| `<commit>` | Commit to drop, move, or reword (revision spec). |
| `--before` | Place `<commit>` immediately before this revision (`move` only). |
| `--after` | Place `<commit>` immediately after this revision (`move` only). |
| `-m`, `--message` | New commit message (conflicts with `--message-file`). |
| `-F`, `--message-file` | Read the new message from a file, or `-` for stdin. |
| `--author` | Replacement author ident (`Name <email>` or bare email). |
| `--dry-run` | List ref updates without moving refs. |
| `--update-refs` | `branches` (default) or `head`. |
| `--empty` | `drop` (default), `keep`, or `abort` when a replay would become empty. |
| `--keep-committer` | Preserve committer ident and timestamp on replayed commits. |

### `split` options

| Option | Description |
| --- | --- |
| `<commit>` | Commit to split (revision spec). |
| `-m`, `--message` | Message for the new parent commit (conflicts with `--message-file`). |
| `-F`, `--message-file` | Read the new parent message from a file, or `-` for stdin. |
| `--rest-message` | Replace the remaining commit’s message after the split. |
| `PATH`… | Pathspecs after `--` limiting which changes move into the new parent (required). |
| `--pathspec-from-file` | Read pathspecs from a file, or `-` for stdin (same as other commands). |
| `--pathspec-file-nul` | `--pathspec-from-file` entries are NUL-separated. |
| `--dry-run` | List ref updates without moving refs. |
| `--update-refs` | `branches` (default) or `head`. |
| `--empty` | When a replayed commit would not change the tree: `drop` (default), `keep`, or `abort`. |
| `--keep-committer` | Keep each replayed commit’s original committer line instead of your configured committer. |

## Examples

### `squash` options

| Option | Description |
| --- | --- |
| `<range>…` | One or more revision specs defining the commits to fold (required). |
| `-m`, `--message` | Message for the squashed commit (conflicts with `--message-file` and `--combine`). |
| `-F`, `--message-file` | Read the squashed commit message from a file, or `-` for stdin. |
| `--combine` | Combine messages from every commit in the range. |
| `--dry-run` | List ref updates without moving refs. |
| `--update-refs` | `branches` (default) or `head`. |

### `absorb` options

| Option | Description |
| --- | --- |
| `--base` | Oldest commit boundary (exclusive) for absorb targets. |
| `--dry-run` | List assignments and ref updates without moving refs. |
| `--update-refs` | `branches` (default) or `head`. |

Move a commit before its parent on a linear branch:

```console
$ grit history move HEAD~1 --before HEAD~3
Rewrote 3 commit(s)
  commit a1b2c3d → d4e5f60
  refs/heads/main f6a7b89 → c0ffee0
```

Reword the parent of `HEAD` on a linear branch:

```console
$ grit history reword HEAD~1 -m " clearer subject line "
Rewrote 2 commit(s)
  commit a1b2c3d → d4e5f60
  refs/heads/main d4e5f60 → f6a7b89
```

Change only the author on an older commit (message and author date unchanged):

```console
$ grit history reword HEAD~2 --author "Ada Lovelace <ada@example.com>" --json
{"operation":"reword","rewritten":[…],"refs":[…],"head":{…},"dry_run":false}
```

Preview ref movements without updating branches:

```console
$ grit history reword HEAD~1 -m "new message" --dry-run
Dry run — refs would change:
  commit a1b2c3d → d4e5f60
  refs/heads/main f6a7b89 → c0ffee0
```

Fix up the parent of `HEAD` using staged edits:

```console
$ grit add file.txt
$ grit history fixup HEAD~1
Fixed up 2 commit(s)
  commit a1b2c3d → d4e5f60
  refs/heads/main f6a7b89 → c0ffee0
```

Fold only selected **unstaged** hunks (same ids and `--lines` syntax as [`grit add`](https://grit-scm.com/docs/history/add.md/index.md)) without staging the whole file first:

```console
$ grit diff --unstaged --json -- file.txt   # copy hunks[].id
$ grit history fixup HEAD~1 --hunks abcdef012345 -- file.txt
Fixed up 2 commit(s)
  commit a1b2c3d → d4e5f60
  refs/heads/main f6a7b89 → c0ffee0
```

Unknown or stale hunk ids exit **2** (same as `grit add --hunks`). Hunk ids and `--lines` ranges are resolved against the same index→worktree diff as [`grit diff --unstaged --json`](https://grit-scm.com/docs/history/diff.md/index.md). Other unstaged hunks on the same paths stay in the worktree; pre-staged edits on those paths are preserved after apply, including when the selected hunk changes line count.

Absorb staged fixes on a linear branch:

```console
$ grit add file.txt
$ grit history absorb
Absorbed 1 hunk(s) into 2 commit(s)
  file.txt @@ -2,0 +3 @@ → a1b2c3d touch line 4
```

Preview hunk → commit assignment without changing refs or the index:

```console
$ grit add file.txt
$ grit history absorb --dry-run
Dry run — absorb would change 2 commit(s)
  file.txt @@ -2,0 +3 @@ → a1b2c3d touch line 4
  other.txt @@ -1,0 +2 @@ — no_candidate
  commit a1b2c3d → d4e5f60
  refs/heads/main f6a7b89 → c0ffee0
```

Split one file out of the parent of `HEAD`:

```console
$ grit history split HEAD~1 -m "add foo only" -- foo
Split 2 commit(s)
  commit a1b2c3d → d4e5f60
  refs/heads/main f6a7b89 → c0ffee0
```

## JSON output

Schemas: [drop v1](https://grit-scm.com/docs/history/schemas/history.drop/v1.json/index.md), [move v1](https://grit-scm.com/docs/history/schemas/history.move/v1.json/index.md), [reword v1](https://grit-scm.com/docs/history/schemas/history.reword/v1.json/index.md), [fixup v1](https://grit-scm.com/docs/history/schemas/history.fixup/v1.json/index.md), [squash v1](https://grit-scm.com/docs/history/schemas/history.squash/v1.json/index.md), [absorb v1](https://grit-scm.com/docs/history/schemas/history.absorb/v1.json/index.md), [undo v1](https://grit-scm.com/docs/history/schemas/history.undo/v1.json/index.md), [rebase v1](https://grit-scm.com/docs/history/schemas/history.rebase/v1.json/index.md), [split v1](https://grit-scm.com/docs/history/schemas/history.split/v1.json/index.md)

Pass `--json` on `grit history drop`, `grit history move`, `grit history reword`, `grit history fixup`, `grit history squash`, `grit history split`, `grit history absorb`, or `grit history undo`:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `operation` | string | `"drop"`, `"move"`, `"reword"`, `"fixup"`, `"squash"`, `"split"`, `"absorb"`, `"undo"`, or `"rebase"`. |
| `result` | string | `rebase` only: `completed`, `conflicts`, `exec_dirty`, or `aborted`. |
| `rewritten` | array | `{old,new,change_id,subject}` full hex OIDs, stored change id (`null` when dropped or absent), and the first line of the replacement commit message (or the original when dropped). |
| `refs` | array | `{ref,old,new}` for each ref that would move or moved. `name` duplicates `ref` and is deprecated; it will be removed in a future release. |
| `head` | object or null | `{old,new}` when `HEAD`'s commit OID changes; `null` when unchanged. |
| `dry_run` | boolean | `true` when `--dry-run` was set. |
| `commit` | string | `rebase` when paused: source commit for `conflicts`, or `HEAD` after the command for `exec_dirty` (full hex). |
| `conflicts` | array | `rebase` when `result` is `conflicts`: `{path,kind,summary?}`. |
| `rerere` | array | `rebase` when `rerere.enabled` is active at a conflict stop (`path`, `kind` as for [`grit merge`](https://grit-scm.com/docs/merge/index.md#json-output)). Omitted when empty. |
| `next_steps` | array | `rebase` when paused: ordered follow-up `grit` commands. |
| `alternatives` | array | `rebase` when paused: `grit rebase --abort` and `grit rebase --skip`. |

For `rebase` with `--exec`, the object also includes:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `exec` | array | `{commit,command,exit_code}` per successful `--exec` invocation through completion or a dirty stop (full hex `commit`). |
| `command` | string or null | Successful command that left tracked edits when `result` is `exec_dirty`. |
| `paths` | array | Changed tracked paths preserved when `result` is `exec_dirty`. |

For `absorb`, the object also includes:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `assignments` | array | `{path,hunk_range,commit,subject}` for hunks assigned to historical commits. |
| `unassigned` | array | `{path,hunk_range,reason,detail?}` for hunks left staged (`reason` is a stable code; `detail` explains `hidden_by_ref`). |
| `excluded_refs` | array | `{ref,commit}` for local branch tips hidden from the stack (always present; empty when none apply). |

For `undo`, the object also includes:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `restored_paths` | array | Paths whose index entry and work tree file were put back (or would be, with `--dry-run`) because the undone `fixup` or `absorb` had consumed their edits. Omitted when empty. |
| `unrestored_edits` | string | Full hex OID of the commit that still holds edits an undone `fixup` or `absorb` folded in, when the record had no saved state to restore. Omitted otherwise. |

For `rebase`, use the [`grit rebase`](https://grit-scm.com/docs/history/rebase.md/index.md) JSON table (`result`, `commit`, `conflicts`, `next_steps`, `alternatives`, plus `rewritten` / `refs` / `head` when `result` is `completed`).

Example:

```json
{
  "operation": "reword",
  "rewritten": [
    {
      "old": "6e513d5cd6ab8d618238e22d7ca55d942b55964a",
      "new": "1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d",
      "change_id": "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
      "subject": "Reworded subject"
    }
  ],
  "refs": [
    {
      "ref": "refs/heads/main",
      "name": "refs/heads/main",
      "old": "9f8e7d6c5b4a392817061524334352637281910",
      "new": "0a1b2c3d4e5f60718293a4b5c6d7e8f901234567"
    }
  ],
  "head": {
    "old": "9f8e7d6c5b4a392817061524334352637281910",
    "new": "0a1b2c3d4e5f60718293a4b5c6d7e8f901234567"
  },
  "dry_run": false
}
```

History rewrite commands other than `rebase` report planning conflicts as structured errors (`kind: "conflict"`) with `conflicts` (paths) and `commit` (the commit that could not be replayed). When that commit is only on other branches the rewrite would move, `refs` lists them and `hint` suggests `--update-refs head`. `grit history rebase` uses the same stop/resume JSON as [`grit rebase`](https://grit-scm.com/docs/history/rebase.md/index.md) (`result: "conflicts"`, exit **1**).

Here `other` was built on `topic` and edits the line that `c2` added, so dropping `c2` from `topic` cannot move `other`:

```console
$ grit history drop topic~1
error: history drop has conflicts moving refs/heads/other onto the new history:
  commit 78d765c o1
  a.txt

Nothing was changed. grit can't resolve conflicts yet.
hint: pass --update-refs head to rewrite only the current branch and leave the others as they are
$ grit history drop topic~1 --json
{"commit":"78d765caa49114094c4779be2dc3e505979ba6c4","conflicts":["a.txt"],"error":"history drop has conflicts","hint":"pass --update-refs head to rewrite only the current branch and leave the others as they are","kind":"conflict","refs":["refs/heads/other"]}
$ grit history drop topic~1 --update-refs head
Dropped 1 commit, replayed 2 descendant commit(s)
  commit e8de07f → (dropped) (c2)
  commit a8a77a4 → 844233b (c3)
  refs/heads/topic a8a77a4 → 844233b
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/history/schemas/history.reword/v1.json/index.md)

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a heading such as `History squash` or `History reword` (matching `operation`), plus rewritten commits, ref updates, and optional `HEAD` movement.



```text
## History drop

- Dry run (refs unchanged)
- commit `e813550` → (dropped) — two
- commit `ac49499` → `5973cf5` — three
  - change id `nlwnxqt`
- `refs/heads/main` `ac49499` → `5973cf5`
- HEAD `ac49499` → `5973cf5`
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[Library guide: History rewrite](https://grit-scm.com/docs/library/history.md/index.md), [`grit log`](https://grit-scm.com/docs/history/log.md/index.md), [`grit pick`](https://grit-scm.com/docs/history/pick.md/index.md)

# https://grit-scm.com/docs/branch/index.md

# grit branch

> List branches, or create, delete, rename, or configure one.

## Synopsis

```text
grit branch [--list <glob>]... [-r | -a] [--merged [REV]] [--no-merged [REV]]
            [--contains [REV]] [--sort name|version|date] [--reverse] [-n <N>]
            [--show-current]
grit branch <name> [<start>]
grit branch -d <name>
grit branch -D <name>
grit branch -m [<old>] <new>
grit branch -M <new>
grit branch -u <upstream> [<name>]
grit branch --unset-upstream [<name>]
grit branch [--dry-run] …
```

## Description

With no arguments, lists your local branches and marks the current one with `*`. When a branch has a configured upstream, the line includes a short marker such as `[origin/main: ahead 2, behind 1]` or `[gone]` when the tracking ref is missing.

Use `-r` / `--remotes` for remote-tracking branches (`origin/main`, …) and `-a` / `--all` for both (remote names use the `remotes/origin/main` form, like `git branch -a`). `--list`, `--merged`, `--no-merged`, `--contains`, `--sort`, `--reverse`, and `-n` / `--limit` follow Git’s branch listing filters (`--max-count` is an alias). `--show-current` prints only the current branch name.

With `--json` or `--markdown`, list output includes `full_ref`, commit `subject` and `date`, upstream details, and linked `worktree` paths when present. Plain human list stays names plus upstream markers.

Path strings in human, `--json`, and `--markdown` output use forward slashes and no Windows `\\?\` verbatim prefix (same spelling as [`grit worktree`](https://grit-scm.com/docs/branch/worktree.md/index.md)), so scripts can compare `branches[].worktree` with `worktrees[].path`.

With a name, creates `refs/heads/<name>` at `<start>` or at `HEAD`. It does not switch to the new branch; use [`grit switch -c`](https://grit-scm.com/docs/switch/index.md) to create and switch in one step.

Branch names follow the same rules as `git check-ref-format --branch`. Invalid names fail before anything is written under `.git/refs`.

With `-d`, deletes a branch when its tip is reachable from the current branch's upstream (if configured) or from `HEAD`. With `-D` or `--force-delete`, deletes even when commits would otherwise be lost. You cannot delete the branch you are on, or a branch checked out in another linked worktree.

With `-m` / `--move`, renames a branch (one argument renames the current branch). `-M` is the same as `-m --force`, replacing an existing `refs/heads/<new>` when needed.

With `-u` / `--set-upstream-to`, writes `branch.<name>.remote` and `branch.<name>.merge` from a local or remote-tracking branch. With `--unset-upstream`, removes those keys.

Use `--dry-run` on any mutation to preview the JSON outcome without changing refs, config, or reflogs.

## Options

| Option | Description |
| --- | --- |
| `<name>` | Branch to create, delete, rename, or configure. Omit to list. |
| `<start>` | Commit to start from when creating (`rev-parse` syntax). Defaults to `HEAD`. |
| `-f`, `--force` | On create or rename, replace an existing branch tip (refuses when that branch is checked out in a worktree). |
| `-t`, `--track` | When creating, always configure upstream from `<start>` when possible. |
| `--no-track` | When creating, never configure upstream. |
| `-u`, `--set-upstream-to` | Set upstream for `<name>` or the current branch when `<name>` is omitted. |
| `--unset-upstream` | Clear upstream for `<name>` or the current branch. |
| `-m`, `--move` | Rename: `-m <new>` or `-m <old> <new>`. |
| `-M` | Force rename: `-M <new>` (current branch) or `-M <old> <new>`. |
| `-d`, `--delete` | Delete the branch when it is fully merged. |
| `-D`, `--force-delete` | Delete even when not fully merged. |
| `--list <glob>` | Include only branches whose short name matches `GLOB` (repeatable). |
| `-r`, `--remotes` | List remote-tracking branches (list mode). |
| `-a`, `--all` | List local and remote-tracking branches (list mode). |
| `--merged [REV]` | Branches merged into `REV` (default `HEAD`). |
| `--no-merged [REV]` | Branches not merged into `REV` (default `HEAD`). |
| `--contains [REV]` | Branches whose tip contains `REV` (default `HEAD`). |
| `--sort name\|version\|date` | Sort key (default name). |
| `--reverse` | Reverse sort order. |
| `-n`, `--limit <N>` | Limit the number of branches listed (`--max-count` alias). |
| `--show-current` | Print only the current branch name (nothing when detached). |
| `--dry-run` | Preview without writing refs, config, or reflogs. |

`--force` does not delete branches. Use `--force-delete` (or `-D`) instead; passing `--force` with `--delete` is a usage error.

## Examples

```console
$ grit branch
  feature
* main [origin/main: ahead 1, behind 0]

$ grit branch --list 'feat*' --sort date -n 5
  feature-old
* feature

$ grit branch --show-current
main

$ grit branch experiment
Created branch experiment at a1b2c3d

$ grit branch topic main~1
Created branch topic at 9f8e7d6

$ grit branch -d experiment
Deleted branch experiment (was cf18394).

$ grit branch -m topic renamed
Renamed branch topic to renamed

$ grit branch -u origin/main renamed
Set upstream of renamed to origin/main
```

While a rebase is paused and `HEAD` is detached, renaming the branch being rebased is refused:

```console
$ grit branch -m renamed
error: cannot rename the branch while a rebase is in progress; finish it with `grit rebase --continue` or cancel it with `grit rebase --abort`
```

Deleting a branch with unmerged work:

```console
$ grit branch -d spike
error: the branch 'spike' is not fully merged into 'main'
If you are sure you want to delete it, run 'grit branch --force-delete spike'

$ grit branch -D spike
Deleted branch spike (was a7020c2).
```

A branch name cannot also be a directory of other branches. Creating `rel` while `rel/1.0` exists (loose or packed, or with only its reflog left under `.git/logs/`) names the branch in the way, and `grit switch -c rel` refuses the same way:

```console
$ grit branch rel
error: cannot lock ref 'refs/heads/rel': 'refs/heads/rel/1.0' exists; cannot create 'refs/heads/rel'
```

## JSON output

List results include `truncated: true` when `-n` / `--limit` caps the branch list and more branches matched. With `--contains` and name ordering (including `--reverse`), the limit bounds matching rows: grit checks tips in name order and stops after the extra match needed to detect truncation. Earlier nonmatching branches do not consume the limit. Graft-defined ancestry, including cycles, has the same ordered matches and truncation as an unlimited query.

Schema: [v1](https://grit-scm.com/docs/branch/schemas/branch/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output. The object's `action` field says what happened:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `action` | string | `list`, `create`, `delete`, `rename`, `set_upstream`, or `unset_upstream`. |
| `current` | string or null | For `list`, the current branch, or `null` when detached. |
| `branches` | array | For `list`, each branch (see below). |
| `truncated` | boolean | For `list`: `true` when more branches matched than returned (`-n` / `--limit`). |
| `branches[].name` | string | Short name (`main`, `origin/main`, `remotes/origin/main` with `-a`, …). |
| `branches[].current` | boolean | Whether this is the checked-out local branch. |
| `branches[].is_remote` | boolean | True for remote-tracking refs. |
| `branches[].full_ref` | string | Full ref (`refs/heads/…`, `refs/remotes/…`). |
| `branches[].oid` | string | Tip object id (full hex). |
| `branches[].short_oid` | string | Abbreviated tip id (seven hex digits when possible). |
| `branches[].subject` | string or null | Tip commit subject (`--json` / `--markdown` list). |
| `branches[].date` | string or null | Tip committer time (RFC 3339). |
| `branches[].upstream` | object or omitted | `ref`, optional `remote`, `gone`, `ahead`, `behind`. |
| `branches[].worktree` | string or null | Linked worktree path when checked out elsewhere. |
| `name` | string | For `create` or `delete`, the branch name. |
| `oid` | string | For `create` or `delete`, full tip id. For `rename`, tip before rename when present. |
| `short_oid` | string | Abbreviated tip id (seven hex digits when possible). |
| `upstream` | string or null | For `create`, the branch's upstream display name afterwards: the one tracking configures, or the one already configured when `--force` resets an existing branch (`--dry-run` reports what the live create would). For `set_upstream`, the upstream display name (for example `origin/main`). |
| `old` | string | For `rename`, previous short name. |
| `new` | string | For `rename`, new short name. |
| `replaced` | string or null | For `rename` with `--force`, previous tip of `new` when overwritten. |
| `branch` | string | For `set_upstream` / `unset_upstream`, the branch that was updated. |
| `dry_run` | boolean | Present and `true` when the operation was preview-only. |

Listing branches:

```json
{
  "action": "list",
  "current": "main",
  "branches": [
    {
      "name": "feature",
      "current": false,
      "is_remote": false,
      "full_ref": "refs/heads/feature",
      "oid": "a1b2c3d4e5f6789012345678901234567890abcd",
      "short_oid": "a1b2c3d",
      "subject": "Add feature",
      "date": "2023-11-14T22:13:20Z",
      "upstream": {
        "ref": "origin/feature",
        "remote": "origin",
        "gone": false,
        "ahead": 0,
        "behind": 2
      }
    },
    {
      "name": "main",
      "current": true,
      "is_remote": false,
      "full_ref": "refs/heads/main",
      "oid": "b2c3d4e5f6789012345678901234567890abcde1",
      "short_oid": "b2c3d4e",
      "subject": "Initial commit",
      "date": "2023-11-14T22:13:20Z"
    }
  ]
}
```

Remote-tracking list:

```json
{
  "action": "list",
  "current": "main",
  "branches": [
    {
      "name": "origin/main",
      "current": false,
      "is_remote": true,
      "oid": "b2c3d4e5f6789012345678901234567890abcde1",
      "short_oid": "b2c3d4e"
    }
  ]
}
```

Creating a branch:

```json
{
  "action": "create",
  "name": "experiment",
  "oid": "a1b2c3d4e5f6789012345678901234567890abcd",
  "short_oid": "a1b2c3d"
}
```

## Markdown output

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output.

Schema: [v1](https://grit-scm.com/docs/branch/schemas/branch/v1.json/index.md)

Markdown lists branches in a table with upstream and worktree columns when present. Table cells escape `|` and internal newlines so commit subjects and paths stay on one row. See the JSON output section for the stable field contract.



```text
## Branches
| Branch | Current | OID | Subject | Upstream | Worktree |
| --- | --- | --- | --- | --- | --- |
| `feature` |  | `062ca6e` | first |  |  |
| `main` | yes | `83352a6` | second |  | [REPO] |
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success, including `--dry-run` previews. |
| `1` | Branch not found, not fully merged, checked out elsewhere, invalid start point (`branch_invalid_start_point`), or other operational failure. |
| `2` | Usage error (missing arguments, incompatible flags). |

On failure with `--json`, stdout includes `error` and a stable `kind`. See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md).


## See also

[grit switch](https://grit-scm.com/docs/switch/index.md), [grit merge](https://grit-scm.com/docs/merge/index.md)

# https://grit-scm.com/docs/switch/index.md

# grit switch

> Switch to another branch, remote branch, or detached commit.

## Synopsis

```text
grit switch <branch>
grit switch -
grit switch @{-1}
grit switch -c <branch> [<start-point>]
grit switch --detach <rev>
grit switch [--dry-run] …
```

`grit co` does the same thing, and so does `grit checkout <branch>`; `grit checkout <url>` makes a [snapshot checkout](https://grit-scm.com/docs/checkout/index.md) from a server instead.

## Description

Switches to a local branch, creates a branch from a remote-tracking ref or start point, or checks out a commit in detached `HEAD` mode. Updates tracked files in the working tree to match the destination.

Local edits are allowed when they only touch paths that are the same on both sides of the switch, or when a changed path already matches the destination tree in the index. Grit still refuses when your changes would conflict with files that differ between branches, or when an untracked file would be overwritten.

After a [`clone --no-checkout`](https://grit-scm.com/docs/clone/index.md), the first switch creates the index and materializes the entire destination tree. This works with clones created by grit or system Git, including switching to the current branch, detaching at `HEAD`, or creating a branch at a commit with the same tree. The previous `HEAD` is still used for reflogs and hooks. Untracked files at destination paths block the switch. An existing empty index continues to represent staged deletions and receives the normal local-change protection.

Use `--dry-run` to run the same overwrite checks and report how many paths would change without updating `HEAD`, the index, the worktree, or reflogs. Agents can preflight a switch with `--json --dry-run` before mutating the tree.

On the first switch after `clone --no-checkout`, the dry-run count includes every path to materialize, including files unchanged between the old and new commits.

A switch either completes or changes nothing. Pressing Ctrl+C, or sending `SIGTERM` or `SIGHUP` on Unix, while files are being checked out stops the switch with `error: operation cancelled`; `HEAD`, the index and the work tree are left exactly as they were, so `grit status` stays clean, no `.git/index.lock` is left behind and the same switch can simply be run again. If cancellation is already requested before the switch starts (or is observed while the plan is being built), grit returns cancelled without deleting work-tree paths. This works the same in a Windows console, where Ctrl+Break counts as Ctrl+C. A second interrupt terminates grit at once, without that cleanup; only `SIGKILL` or closing the console window skips rollback. In the rare case that a path cannot be put back (for example a directory that became read-only), the error has kind `checkout_incomplete` and lists those paths in `paths`; `HEAD` and the index still did not move.

Switching is refused while a merge, rebase, pick, revert or `am` is paused, whether grit or `git` started it: those operations finish by committing onto the current `HEAD`, so moving it would land their result on the wrong branch. When grit knows how the operation finishes or is cancelled (merge, rebase, pick, revert), the error names those commands. `--dry-run` is refused too. A bisect does not block a switch.

A local branch can only be checked out in one worktree at a time (including linked worktrees created with `git worktree add`). Switching to a branch that is already checked out elsewhere fails.

With `-c`, creates the branch at the current commit (or at `<start-point>` when you pass one), then switches to it. When `<start-point>` is a remote-tracking branch (for example `origin/main`), grit configures upstream tracking the same way as [`grit branch --track`](https://grit-scm.com/docs/branch/index.md) and `git switch -c`, unless you pass `--no-track` or `branch.autoSetupMerge` is `false`/`simple`.

When `<branch>` names a remote-tracking branch (for example `origin/feature`), Grit creates `feature` at the same commit and switches to it if no local branch exists yet. It also records upstream tracking in the repository config (`branch.feature.remote` and `branch.feature.merge`), the same keys `git switch` writes, so `grit status`, `grit pull`, and `grit push` use the matching remote branch.

`--detach` checks out `<rev>` without moving a branch tip. Use another branch or `grit switch <branch>` to reattach.

In a sparse checkout (`git sparse-checkout`), only paths inside the sparse patterns are written to the worktree. Paths outside them are recorded in the index with the skip-worktree bit, the same as `git switch`. The same applies to [`grit merge`](https://grit-scm.com/docs/merge/index.md), [`grit pull`](https://grit-scm.com/docs/pull/index.md) and [`grit reset`](https://grit-scm.com/docs/reset/index.md).

After a real switch (not `--dry-run`), grit runs the `post-checkout` hook with the previous `HEAD` commit, the new one, and `1`, as Git does. The old id is all zeros when switching away from a branch with no commits. The hook also runs when you switch to the branch or commit you are already on. Its exit status never changes the result; a hook that cannot be started prints a `hook_not_run` warning. See [`grit hooks`](https://grit-scm.com/docs/hooks/index.md).

Leaving a detached `HEAD` that carries commits of its own (made with `grit commit` after `--detach`) would leave those commits on no branch, recoverable only through `grit reflog` until garbage collection removes them. Grit still switches, but warns on stderr with the commits it leaves behind (newest first, up to 20) and a `grit branch <name> <oid>` command that keeps them. A commit counts as left behind when no ref, the stash, another worktree's `HEAD`, or the switch destination reaches it, so `grit switch -c <new>` from the detached commit leaves nothing behind. Without a commit-graph the check ends by commit date like Git's `rev-list`, so heavy clock skew can make the count wrong (see [grit reset](https://grit-scm.com/docs/reset/index.md)). `--dry-run` reports the same list without switching. Leaving a branch never warns: the branch still holds its commits.

Updating the working tree uses parallel checkout when the change set is large enough; tune [`checkout.workers`](https://grit-scm.com/docs/library/parallelism.md/index.md) and `checkout.thresholdForParallelism`. On non-Windows hosts, global [`--threads`](https://grit-scm.com/docs/global-options.md/index.md) can cap checkout workers for this run; on **Windows**, checkout stays serial until `checkout.workers` is set in config (see [parallelism](https://grit-scm.com/docs/library/parallelism.md/index.md)).

## Options

| Option | Description |
| --- | --- |
| `<branch>` | Local branch to switch to, remote-tracking name to DWIM, or new branch name with `-c`. |
| `-`, `@{-1}` | Switch to the previous branch (from the `HEAD` reflog); fails when there is no prior checkout entry. |
| `<start-point>` | With `-c`, commit to create the branch from (defaults to `HEAD`). |
| `-c`, `--create` | Create the branch first, then switch to it. Fails if the branch already exists. |
| `-t`, `--track` | With `-c`, always configure upstream from the start point. |
| `--no-track` | With `-c`, do not configure upstream. |
| `--detach` | Check out a commit in detached `HEAD` mode instead of switching a branch. |
| `--dry-run` | Run overwrite checks and report how many paths would change; do not update refs, the index, or the worktree. |

## Examples

```console
$ grit switch -c feature
Created and switched to branch feature

$ grit switch main
Switched to branch main
hooks: post-checkout

$ grit switch -
Switched to branch feature

$ grit switch -c work origin/main
Created and switched to branch work
  tracking origin/main

$ grit switch -c br2 origin/br2
Created and switched to branch br2
  tracking origin/br2

$ grit switch --detach HEAD~1
HEAD detached at a1b2c3d

$ grit switch other --dry-run
Would switch to other (3 path(s) would change)
```

When you leave a detached `HEAD` with commits no branch holds:

```console
$ grit switch main
Switched to branch main
Warning: 1 commit left behind, not on any branch:
  85ffcb0 work done on detached HEAD
Keep it on a branch with: grit branch <name> 85ffcb090615556eb238400c577de383ca034213
```

When local changes would conflict with the destination branch:

```console
$ grit switch other
error: you have uncommitted changes — commit them before switching
  notes.txt
hint: commit them with `grit commit`, or set them aside with `grit stash`, then try again
```

When `grit switch -` has no previous branch to return to (for example right after `grit init`):

```console
$ grit switch -
error: there is no previous branch to go back to
```

When no branch has that name:

```console
$ grit switch nonexistent
error: no branch named 'nonexistent'
hint: `grit branch` lists your branches; create this one with `grit switch -c nonexistent`
```

While a rebase that `git` started is stopped on a conflict:

```console
$ grit switch main
error: cannot switch branches while an interactive rebase is in progress; finish it with `git rebase --continue` or cancel it with `grit rebase --abort`
```

When an untracked file would be overwritten:

```console
$ grit switch other
error: untracked file 'new.txt' would be overwritten — move or remove it first
  new.txt
hint: move or remove those files, then try again
```

## JSON output

Schema: [v2](https://grit-scm.com/docs/switch/schemas/switch/v2.json/index.md) · [v1](https://grit-scm.com/docs/switch/schemas/switch/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `branch` | string or null | Short branch name `HEAD` is on after the switch; `null` when detached. |
| `created` | boolean | `true` when `-c` or remote DWIM created the branch. |
| `upstream` | string or null | When `-c` configured upstream tracking, the remote branch name (for example `origin/main`); omitted when none was set. |
| `detached` | boolean | `true` when `HEAD` is detached after the switch (`branch` is `null`). |
| `commit` | string or null | Full hex oid when `detached` is true; omitted when attached. |
| `dry_run` | boolean | `true` when `--dry-run` was used (omitted when false). |
| `changed_paths` | integer or null | With `--dry-run`, count of paths that would differ after checkout. |
| `hooks_run` | array of strings | Hooks that ran after the switch (`post-checkout` when installed); empty on `--dry-run`. |
| `stranded_commits` | array | Commits only the previous detached `HEAD` reached, newest first, at most 20. Each has `oid`, `change_id` and `subject`. Omitted when nothing is left behind. |
| `stranded_total` | integer | Advisory count of commits left behind (may exceed the length of `stranded_commits`). Without a commit-graph, severe clock skew can make this inaccurate; it never controls the switch. Omitted when zero. |
| `stranded_truncated` | boolean | `true` when `stranded_commits` was capped (omitted when false). |
| `path_collisions` | array of strings | Index paths that collided during checkout when tracked paths share one on-disk file (case or Unicode normalization). Omitted when empty. |

When `core.ignorecase` or `core.precomposeunicode` is set and the destination tree contains paths that collide on this filesystem (different ASCII case or NFC/NFD spellings mapping to one file), grit prints a **warning** on **stderr** in human mode listing every colliding index path, the same message as [`grit clone`](https://grit-scm.com/docs/clone/index.md). Only one path from each group exists on disk; status and diff treat index rows whose blob does not match the shared dentry as modified.

Example (branch switch):

```json
{
  "branch": "feature",
  "created": true,
  "detached": false,
  "hooks_run": ["post-checkout"]
}
```

Example (`--dry-run`):

```json
{
  "branch": "other",
  "created": false,
  "detached": false,
  "dry_run": true,
  "changed_paths": 3,
  "hooks_run": []
}
```

Example (detached):

```json
{
  "branch": null,
  "created": false,
  "detached": true,
  "commit": "a1b2c3d4e5f6789012345678901234567890abcd",
  "hooks_run": []
}
```

Example (leaving a detached `HEAD` with one commit of its own):

```json
{
  "branch": "main",
  "created": false,
  "detached": false,
  "hooks_run": [],
  "stranded_commits": [
    {
      "oid": "85ffcb090615556eb238400c577de383ca034213",
      "change_id": "zrmsknstkznuqxynsolvwoovmolrxwum",
      "subject": "work done on detached HEAD"
    }
  ],
  "stranded_total": 1
}
```

On overwrite refusal with `--json`, stdout is a single object with `kind` `would_overwrite` and `would_overwrite.reason` (`local_changes` or `untracked`) plus a sorted `paths` array, and a `hint`, for example `{"error":"you have uncommitted changes — commit them before switching","hint":"…","kind":"would_overwrite","would_overwrite":{"paths":["notes.txt"],"reason":"local_changes"}}`. See the [error schema](https://grit-scm.com/docs/switch/schemas/error/v1.json/index.md).

A branch that does not exist is `kind` `branch_not_found` with a `hint`.

With `--create`, an existing name is `kind` `branch_already_exists`, an invalid name is `branch_invalid_name`, and an empty repository with no start point is `branch_no_commits`. A start point that does not resolve is `revision_not_found`; one that resolves to a non-commit object is a plain error string with no dedicated `kind`.

While a merge, rebase, pick or revert is paused, the refusal is `{"error": "interactive rebase in progress", "kind": "operation_in_progress"}` (the `error` names the paused operation).

## Markdown output

Schema: [v2](https://grit-scm.com/docs/switch/schemas/switch/v2.json/index.md) · [v1](https://grit-scm.com/docs/switch/schemas/switch/v1.json/index.md)
Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a `Switch` heading and one summary line, plus a `- Hooks:` line when a hook ran:

```text
- Switched to **`feature`**
```

Creating a branch:

```text
- Created and switched to **`topic`**
```

Dry run:

```text
- Would switch to **`other`** (3 path(s) would change)
```

Detached HEAD:

```text
- HEAD detached at `9244cbd`
```

Leaving commits behind adds a warning block after the summary line:

```text
- Switched to **`main`**

> **Warning:** 1 commit left behind, not on any branch:

- `85ffcb0` work done on detached HEAD

Keep it with `grit branch <name> 85ffcb090615556eb238400c577de383ca034213`.
```


## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.

When another process holds `.git/index.lock`, a switch that would update the worktree fails with exit `1` (`kind` `lock_held` under `--json`) before touching anything: the worktree, index, `HEAD` and branches are unchanged. `--dry-run` never takes the lock.


## See also

[grit branch](https://grit-scm.com/docs/branch/index.md), [grit reset](https://grit-scm.com/docs/reset/index.md), [grit merge](https://grit-scm.com/docs/merge/index.md), [grit status](https://grit-scm.com/docs/status/index.md)
Sparse indexes keep unchanged excluded directory trees compact during checkout.
Only affected directories or directories present outside the sparse cone need
individual index rows. Performance and scaling methodology are documented in
[Benchmarks](https://grit-scm.com/docs/benchmarks.md/index.md).

Unmerged indexes use the full worktree guard checks.

# https://grit-scm.com/docs/merge/index.md

# grit merge

> Merge another branch, tag or commit into the current one.

## Synopsis

```text
grit merge <rev>
grit merge --check <rev>
grit merge --dry-run <rev>
grit merge --continue [-m <message>]
grit merge --abort
grit merge [--ff-only | --no-ff] [--squash | --no-commit] [-X ours|theirs] [--conflict diff3|zdiff3|merge] [--allow-unrelated-histories] [--no-verify] [-m <message> | -F / --message-file <path|->] <rev>
```

## Description

Brings the commits from `<rev>` into the current branch. Pathnames in human, stderr conflict lines, and `--markdown` output use the same quoting rules as [`grit status`](https://grit-scm.com/docs/status/index.md) (see **Description** there).

- If the current branch already has everything, nothing changes.
- If the current branch has no commits of its own since they diverged, it's moved forward to `<rev>` (a fast-forward). No new commit is made.
- Otherwise both sides are merged. When there are no overlapping edits, a merge commit is recorded with the message `Merge <rev>`, using `<rev>` as you typed it. That commit gets a new `change-id` header like [`grit commit`](https://grit-scm.com/docs/commit/index.md). When `commit.gpgsign` is enabled, that merge commit is signed like [`grit commit`](https://grit-scm.com/docs/commit/index.md).
- When the same lines were changed on both sides, `grit merge` stops with conflicts: it updates the index and working tree, writes conflict markers around each conflicting hunk, records merge-in-progress state (`MERGE_HEAD`, `ORIG_HEAD`, `MERGE_MSG`), and leaves the branch ref unchanged. When `rerere.enabled` is true (or `.git/rr-cache/` already exists), grit replays resolutions Git recorded in `.git/rr-cache/` and records new preimages and postimages in Git's format on conflict stops and when you `--continue` or [`grit commit`](https://grit-scm.com/docs/commit/index.md) after resolving. Replayed files stay unstaged unless `rerere.autoupdate` is set; `--abort` drops unresolved rerere state like Git. Fix conflicts, then run `grit merge --continue` to create the two-parent merge commit (message from `MERGE_MSG` with comment lines stripped, or `-m` to override). When `commit.autoStage` is true (the default), `--continue` stages resolved paths from the work tree the same way [`grit commit`](https://grit-scm.com/docs/commit/index.md) does, so you do not need `grit add` after editing away conflict markers. With `commit.autoStage=false`, stage resolved paths with `grit add` before `--continue`. [`grit commit`](https://grit-scm.com/docs/commit/index.md) can also finish a resolved merge. Run `grit merge --abort` to discard the in-progress merge and restore the pre-merge branch, index, and working tree.
- After a merge with `--no-commit` (when supported), run `grit merge --continue` to record the merge commit without re-running the three-way merge.

Before a clean merge records its commit, grit runs the same hooks as Git, in Git's order: `pre-merge-commit` (no arguments), then `prepare-commit-msg .git/MERGE_MSG merge` and `commit-msg .git/MERGE_MSG`, which see `MERGE_HEAD` and may rewrite the message (the commit records what they leave). Files a `pre-merge-commit` hook stages go into the merge commit. When one of them exits non-zero, the merge stops with exit **1** and a `hook_failed` error (as for [`grit commit`](https://grit-scm.com/docs/commit/index.md)): the merged files stay in the work tree and index, `MERGE_HEAD`, `ORIG_HEAD` and `MERGE_MSG` are recorded, and the branch does not move. Finish with `grit merge --continue` (which runs `pre-commit` like `grit commit`, as Git does) or cancel with `grit merge --abort`; edits a [`grit pull --autostash`](https://grit-scm.com/docs/pull/index.md) stashed come back either way. `--no-verify` skips `pre-merge-commit` and `commit-msg`; `prepare-commit-msg` and `post-merge` still run. None of these run for a fast-forward, `--squash`, `--no-commit`, conflicts, `--check` or `--dry-run`.

```console
$ grit merge topic -m 'WIP merge'
pre-merge-commit: blocked
error: hook pre-merge-commit failed with exit status 1
hint: the merge is still in progress: run `grit merge --continue` to commit it, or `grit merge --abort` to cancel
$ grit merge --abort
Merge aborted.
```

A merge either completes, stops for conflicts, or changes nothing. Pressing Ctrl+C, or sending `SIGTERM` or `SIGHUP` on Unix, while files are being checked out during a fast-forward or three-way merge stops the merge with `error: operation cancelled`; `HEAD`, the index and the work tree are left as they were before the merge started (no `MERGE_HEAD`), no `.git/index.lock` is left behind, and the same merge can simply be run again. This works the same in a Windows console, where Ctrl+Break counts as Ctrl+C. A second interrupt terminates grit at once, without that cleanup; only `SIGKILL` skips rollback. In the rare case that a path cannot be put back during checkout rollback, the error has kind `checkout_incomplete` and lists those paths in `paths`.

With `--json` the error carries the hook's output and the same `hint`:

```json
{
  "error": "hook pre-merge-commit failed with exit status 1",
  "hint": "the merge is still in progress: run `grit merge --continue` to commit it, or `grit merge --abort` to cancel",
  "hook": {
    "name": "pre-merge-commit",
    "status": 1,
    "stderr": "pre-merge-commit: blocked\n",
    "stdout": ""
  },
  "kind": "hook_failed"
}
```

After a fast-forward or a merge commit, grit runs the `post-merge` hook with `0`; after `--squash` it passes `1`, as Git does. The hook does not run when the branch is already up to date, when the merge stops on conflicts, with `--no-commit`, or for `--check` and `--dry-run`. `grit merge --continue` runs `post-commit` like [`grit commit`](https://grit-scm.com/docs/commit/index.md), not `post-merge` (Git behaves the same). The hook's exit status never changes the result. See [`grit hooks`](https://grit-scm.com/docs/hooks/index.md).

Every merge records the commit the branch was on in `ORIG_HEAD`, as `git merge` does: an up-to-date merge, a fast-forward, a merge commit, `--squash`, `--no-commit`, a merge that stops on conflicts, and a `--ff-only` merge refused because it cannot fast-forward. It replaces any earlier value and stays after the merge finishes, `--continue` or `--abort`, so `grit reset --hard ORIG_HEAD` undoes a merge you regret. `--check` and `--dry-run` leave it alone.

`<rev>` can be any branch, tag or commit: a local branch, a remote-tracking branch such as `origin/main`, a tag such as `v1.2` (annotated tags merge the commit they point at), a full or abbreviated commit id, or a revision expression such as `topic~2`, `origin/main^` or `ORIG_HEAD`. A name is looked up as a local branch first, then a remote-tracking branch, then a tag, then as a revision. Ranges (`a..b`, `a...b`) and trees or blobs are refused.

Literal braces are allowed in ref names: `grit merge 'foo{bar'` merges that branch, while `grit merge 'foo{bar...main'` refuses the range without moving HEAD. Dots within selectors, such as `main^{/release..candidate}`, remain part of a single revision.

On a criss-cross history the two branches have several merge bases (`grit merge-base --all` lists them). grit then merges those bases into one virtual base first and merges the two branches against it, like Git, so `grit merge` and `grit merge --check` give the same answer whichever base comes first. When the two sides resolved the same old conflict in different ways, the merge stops with a conflict instead of silently keeping one resolution. In that case the base version (stage 1 in the index, the `|||||||` section with `--conflict diff3`) holds the bases' own conflict, with markers labelled `Temporary merge branch 1` and `Temporary merge branch 2`. `-X ours|theirs` applies only to the final merge, not to the merge of the bases.

Local edits are allowed when they only touch paths the merge does not change, or when a changed path already matches the post-merge tree in the index (same scoped rule as [`grit switch`](https://grit-scm.com/docs/switch/index.md)). Grit refuses when your changes would be overwritten by files the merge updates, when an untracked file would be replaced by a path the merge would check out, or on a branch with no commits; the branch (or detached `HEAD`) and file are left unchanged.

With a **detached `HEAD`**, grit merges into `HEAD` like Git: a fast-forward or merge commit moves only `HEAD` (branch tips such as `main` stay put). `--check` and `--dry-run` work the same way and leave `HEAD`, the index, and merge state untouched.

### Merge modes

- **`--ff-only`** — Refuse when a fast-forward is not possible (histories diverged). Nothing changes. Exit code **128** (same as Git's `merge --ff-only`).
- **`--no-ff`** — Always record a merge commit with two parents when a real merge is needed, even if a fast-forward was possible.
- **`--squash`** — Apply the merged tree to the index and worktree, write a Git-compatible `SQUASH_MSG`, and do not update the branch ref or write `MERGE_HEAD`. Finish with [`grit commit`](https://grit-scm.com/docs/commit/index.md) (which uses `SQUASH_MSG` as the default message when you omit `-m`).
- **`--no-commit`** — Perform the merge but stop before committing: writes `MERGE_HEAD`, `ORIG_HEAD`, and `MERGE_MSG` (and `MERGE_MODE` when `--no-ff` applies). Finish with [`grit commit`](https://grit-scm.com/docs/commit/index.md) or `grit merge --continue` (when implemented).

`-m` / `-F` / `--message-file` override the default merge commit message and the text stored in `MERGE_MSG` on conflicts or `--no-commit`.

**`-X ours|theirs`** — When both sides edited the same region, prefer the current branch (`ours`) or the branch being merged (`theirs`) instead of leaving conflict markers. Matches Git's merge strategy options (union is not exposed). `--check` and `--dry-run` honor the same option when predicting the outcome.

**`--conflict diff3|zdiff3|merge`** — Conflict marker style in the worktree. When omitted, grit reads `merge.conflictStyle` (default `merge`).

Textual merges during a three-way tree merge use the histogram diff algorithm, matching Git's merge-ort strategy (distinct from `git merge-file`, which uses Myers).

**`--allow-unrelated-histories`** — Merge branches that share no commits, using the empty tree as the merge base (Git-compatible). Without this flag, grit refuses unrelated histories.

On an interactive terminal (human output, not `--json` or `--markdown`), a live **Checkout** line on stderr counts the files the merge writes, and `--continue` shows a **Staging** line while it auto-stages; nothing is drawn when stderr is not a TTY.

### Directory renames

When one branch moved every file out of a directory (renaming `a/` to `b/`) and the other branch added a file inside the old directory, the new file most likely belongs in `b/`. Grit detects this the way Git does: the directory must be gone on the renaming side, and its destination is the directory that received the most of its files. The `merge.directoryRenames` config decides what happens:

- **`conflict`** (default, as in Git) — The file is moved to `b/` and left unmerged so you can confirm the location. It's in the work tree at the new path; stage it there (or move it back) and run `grit merge --continue`.
- **`true`** — The file is moved to `b/` and the merge is clean.
- **`false`** — The file stays in `a/`.

Any other value is an error. With `conflict` or `true`, two cases still stop the merge without moving anything, and leave nothing unmerged: a directory whose files went to several directories with no clear winner (`directory_rename_split`), and a new file whose destination already exists on the branch that added it, or would be shared with another new file (`directory_rename_blocked`). When only the base or the renaming branch has a file at the destination, the moved file is merged with it there, as Git does; that can stop with an ordinary conflict at the new path, such as `deleted_by_us` when the renaming branch deleted that file. Review the placement, then run `grit merge --continue`. [`grit pick`](https://grit-scm.com/docs/pick/index.md), [`grit revert`](https://grit-scm.com/docs/revert/index.md), [`grit rebase`](https://grit-scm.com/docs/rebase/index.md) and [`grit pull`](https://grit-scm.com/docs/pull/index.md) follow the same setting.

```console
$ grit merge theirs
CONFLICT (directory_rename_moved): a/new was added to a directory the other side renamed, so it now sits at b/new; stage it there or move it back

Automatic merge failed; fix conflicts and run `grit merge --continue`, or run `grit merge --abort`.

$ grit add b/new
$ grit merge --continue
Merged theirs into the current branch (06e1c12)
```

## Options

| Option | Description |
| --- | --- |
| `<rev>` | The branch, tag or commit to merge into the current one. |
| `--check` | Predict whether the merge would succeed without changing refs, the index, or the working tree. Exit **0** when it would fast-forward, already be up to date, or merge cleanly; exit **1** when it would conflict. Uses the same `-X ours\|theirs` as the merge it predicts. Other failures use the usual error exit. |
| `--dry-run` | Report the planned merge outcome (up to date, fast-forward, merge commit with parents, or conflicts) without changing refs, the index, or the working tree. Exit **0** unless the merge would be refused (for example `--ff-only` when a fast-forward is not possible, exit **128**). Conflicts are reported in the JSON but do not fail the command. Mutually exclusive with `--check`. |
| `--continue` | Finish an in-progress merge after conflicts are resolved (or after `--no-commit`). Auto-stages resolved paths when `commit.autoStage` is true (default). Conflicts with `<rev>`, `--check`, and `--abort`. |
| `-m`, `--message` | Commit message for `--continue` only (overrides `MERGE_MSG`). |
| `--abort` | Cancel an in-progress merge and restore the state recorded in `ORIG_HEAD`. |
| `--ff-only` | Refuse when a fast-forward is not possible (exit code 128). Mutually exclusive with `--no-ff`. |
| `--no-ff` | Create a merge commit even when a fast-forward is possible. Mutually exclusive with `--ff-only`. |
| `--squash` | Squash merged commits into the index; write `SQUASH_MSG` (no `MERGE_HEAD`). Mutually exclusive with `--no-commit`. |
| `--no-commit` | Apply the merge but do not commit yet (Git-compatible merge state). Mutually exclusive with `--squash`. |
| `-m`, `--message` | Merge commit / `MERGE_MSG` message (conflicts with `--message-file`). |
| `-F`, `--message-file` | Read the message from a path, or `-` for stdin (conflicts with `-m`). |
| `-X ours\|theirs` | Prefer one side on overlapping edits (same as Git `-X`). |
| `--conflict` | Marker style: `merge`, `diff3`, or `zdiff3`. |
| `--allow-unrelated-histories` | Merge with no common ancestor (empty-tree base). |
| `--no-verify` | Skip the `pre-merge-commit` and `commit-msg` hooks (`prepare-commit-msg` and `post-merge` still run). Not with `--continue`, `--abort`, `--check` or `--dry-run`. |

## Examples

```console
$ grit switch old
$ grit merge main
Fast-forwarded old → cf18394 (main)

$ grit merge origin/main
Merged origin/main into the current branch (acd1d4b)

$ grit merge --no-ff topic
Merged topic into the current branch (1a2b3c4)

$ grit merge v1.2
Merged v1.2 into the current branch (15d4bf9)

$ grit merge a79778433f24ac0955d38d912c13644b0920de68
Merged a79778433f24ac0955d38d912c13644b0920de68 into the current branch (e3ca27d)

$ grit merge --squash topic
Squash merge applied from topic — run `grit commit` to record the squashed commit

$ grit merge --no-commit topic
Merge from topic applied — run `grit commit` to finish, or `grit merge --abort` to cancel
```

When both branches change the same lines:

```console
$ grit merge topic
CONFLICT (both_modified): README.md

Automatic merge failed; fix conflicts and run `grit merge --continue`, or run `grit merge --abort`.
```

When one branch deleted a file and the other modified it, grit leaves the modified side's content in the work tree (like Git) so you can run `grit add <path>` to keep it or `grit rm <path>` to accept the deletion:

```console
$ grit merge feat
CONFLICT (deleted_by_us): f deleted on the current branch and modified in feat; feat's version is in the work tree

Automatic merge failed; fix conflicts and run `grit merge --continue`, or run `grit merge --abort`.
```

When one branch deleted a file and the other renamed it, grit reports the same `deleted_by_us` conflict at the **new** path (the rename target), with unmerged stages in the index and the renamed side's content in the work tree. `grit merge --check` exits **1** for this case, as it does for modify/delete.

When both branches renamed the same file to different names, grit cannot pick a name, so it stops (like Git) and keeps both names in the work tree. Each one holds the merged content. The old name stays unmerged in the index next to the two new names. To keep one name, remove the old name and the other new name with `grit rm`, then run `grit merge --continue`. `grit merge --check` exits **1** for this case.

```console
$ grit merge topic
CONFLICT (rename_rename): a renamed to b on the current branch and to c in topic; both names are in the work tree
CONFLICT (rename_rename): b
CONFLICT (rename_rename): c

Automatic merge failed; fix conflicts and run `grit merge --continue`, or run `grit merge --abort`.

$ grit rm a c
Removed 2 paths.

$ grit merge --continue
Merged topic into the current branch (b3e1fe8)
```

When the branches put two different files at the same path (each renamed a different file to it, or one renamed a file onto a path the other added), grit reports a `both_added` conflict at that path, like Git. Both versions stay in the index and the work-tree file shows them between conflict markers; a renamed file already carries the other branch's edits to it. The old names are gone, so nothing is lost until you resolve the path.

```console
$ grit merge topic
CONFLICT (both_added): c

Automatic merge failed; fix conflicts and run `grit merge --continue`, or run `grit merge --abort`.
```

After resolving markers (staging is optional when `commit.autoStage` is true):

```console
$ grit merge --continue
Merged topic into the current branch (acd1d4b)
```

To cancel:

```console
$ grit merge --abort
Merge aborted.
```

When nothing has that name:

```console
$ grit merge nonexist
error: no branch, tag or commit named 'nonexist'
```

While a rebase is paused, starting another merge is refused (same wording as [`grit switch`](https://grit-scm.com/docs/switch/index.md)):

```console
$ grit merge main
error: cannot merge while a rebase is in progress; finish it with `grit rebase --continue` or cancel it with `grit rebase --abort`
```

When `--continue` runs while conflict markers are still in a file:

```console
$ grit merge --continue
error: you still have unmerged paths: notes.txt
hint: resolve the conflict markers in notes.txt, then run `grit merge --continue` (or `grit merge --abort` to start over)
```

When local edits on a path the merge would update would be overwritten:

```console
$ grit merge feature
error: local changes would be overwritten by merge
  a.txt
```

When an untracked file would be overwritten:

```console
$ grit merge feature
error: untracked file 'notes.txt' would be overwritten — move or remove it first
```

When `--ff-only` cannot fast-forward:

```console
$ grit merge --ff-only topic
Cannot fast-forward topic — histories have diverged (use merge without --ff-only)
```

(Exit code 128.)

## JSON output

Schema: [v2](https://grit-scm.com/docs/merge/schemas/merge/v2.json/index.md) · [v1](https://grit-scm.com/docs/merge/schemas/merge/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `result` | string | `up_to_date`, `fast_forward`, `clean` (`--check` only), `merged`, `squashed`, `stopped`, `conflicts`, `refused_not_ff`, or `aborted`. |
| `check` | boolean | `true` when this outcome is from `--check` (nothing was merged). Omitted for real merges. |
| `dry_run` | boolean | `true` when this outcome is from `--dry-run` (nothing was merged). Omitted for real merges. |
| `branch` | string | The branch, tag or commit that was merged in, exactly as given on the command line. |
| `updated_branch` | string or null | After a fast-forward, the current branch whose tip moved. Omitted when it matches `branch`. |
| `oid` | string or null | Resulting commit after a real merge or fast-forward; for `--check` with `result: clean`, the predicted merge tree OID (the id `git merge-tree --write-tree` prints; `--check` does not store that tree, so it is not in the object database). Omitted for `--dry-run` when a new merge commit would be created. |
| `parents` | array or null | For `--dry-run` with `result: merged`, the two parent commit ids of the merge commit that would be recorded. |
| `change_id` | string or null | Stored `change-id` on `oid` when present (merge commit or fast-forward tip). |
| `conflicts` | array or null | When `result` is `conflicts`, each item has `path`, a [conflict `kind`](https://grit-scm.com/docs/status/index.md#conflict-kinds) (the same names `grit status` uses, plus `rename_rename` and the `directory_rename_*` kinds), and optional `summary` text for `deleted_by_us`, `deleted_by_them`, `rename_rename` and directory rename conflicts. A `rename_rename` conflict lists all three paths (the old name and both new names); the `summary` is on the old name's item. |
| `rerere` | array | When rerere is active on `conflicts` or after a successful `merged` from `--continue`, each item has `path` and `kind`: `resolved_from_previous`, `staged_from_previous`, `recorded_preimage`, or `recorded_resolution`. Omitted when empty. |
| `next_steps` | array or null | Ordered follow-up commands when `result` is `conflicts` (for example `grit diff`, `grit add .`), or suggested commands when `result` is `squashed` or `stopped`. |
| `alternatives` | array or null | Mutually exclusive options such as `grit merge --abort` (not part of the ordered sequence). |

Example:

```json
{
  "result": "up_to_date",
  "branch": "main"
}
```

Dry-run prediction with `--check` (exit code 0):

```json
{
  "result": "clean",
  "check": true,
  "branch": "topic",
  "oid": "4b825dc642cb6eb9a06054e089d91b5929f0d0a"
}
```

Squash merge:

```json
{
  "result": "squashed",
  "branch": "topic",
  "next_steps": [
    "grit commit",
    "Review SQUASH_MSG or pass -m / --message-file"
  ]
}
```

When the merge stops on conflicts (exit code 1), stdout is still a single JSON object:

```json
{
  "result": "conflicts",
  "branch": "topic",
  "conflicts": [
    {
      "path": "src/lib.rs",
      "kind": "both_modified"
    }
  ],
  "next_steps": ["grit diff", "grit add ."],
  "alternatives": ["grit merge --abort"]
}
```

When `<rev>` names nothing, the command exits **1** with `{"error":"no branch, tag or commit named 'nonexist'","kind":"revision_not_found"}` on stdout (see [`revision_not_found`](https://grit-scm.com/docs/exit-codes/index.md)).

When `--continue` finds unresolved conflicts, it exits **1** with `kind` `unmerged_paths`, the files in `paths` and the next step in `hint` (with `commit.autoStage=false`, files that are resolved but not staged get a `grit add` hint instead), for example `{"error":"you still have unmerged paths: notes.txt","hint":"…","kind":"unmerged_paths","paths":["notes.txt"]}`.

On overwrite refusal with `--json`, stdout is a single object with `kind` `would_overwrite` and `would_overwrite.reason` (`local_changes` or `untracked`) plus a sorted `paths` array, and a `hint` — the same shape as [`grit switch`](https://grit-scm.com/docs/switch/index.md). For example `{"error":"local changes would be overwritten by merge","hint":"…","kind":"would_overwrite","would_overwrite":{"paths":["a.txt"],"reason":"local_changes"}}`. See the [error schema](https://grit-scm.com/docs/merge/schemas/error/v1.json/index.md).

## Markdown output

Schema: [v2](https://grit-scm.com/docs/merge/schemas/merge/v2.json/index.md) · [v1](https://grit-scm.com/docs/merge/schemas/merge/v1.json/index.md)
Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a `Merge` heading and a result summary. Fast-forward:

```text
- Fast-forwarded **`main`** → `9244cbd`
```

When the merge stops on conflicts (exit code 1), stdout still carries structured Markdown with conflict paths and next steps:

```text
- Merge **`side`** stopped with conflicts

- `f.txt`

→ fix conflicts, then `grit merge --continue`, or `grit merge --abort`
```


## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Merge completed, `--check` predicts success, or `--dry-run` preview. |
| `1` | Conflicts (`result: conflicts`), `<rev>` names nothing (`kind: revision_not_found`), a hook refused the merge commit (`kind: hook_failed`), or other failure ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `128` | `--ff-only` when not fast-forward ([`refused_not_ff`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md).


## See also

[grit pull](https://grit-scm.com/docs/pull/index.md), [grit pick](https://grit-scm.com/docs/pick/index.md), [grit branch](https://grit-scm.com/docs/branch/index.md)

# https://grit-scm.com/docs/reset/index.md

# grit reset

> Move the branch tip and optionally reset the index or worktree.

## Synopsis

```text
grit reset [<rev>]
grit reset --soft [<rev>]
grit reset --mixed [<rev>]
grit reset --hard [<rev>]
grit reset --keep [<rev>]
grit reset --dry-run [<rev>]
```

## Description

Moves the current branch (or detached `HEAD`) to `<rev>`, which defaults to `HEAD`. Use this to uncommit while keeping changes (`--soft`), drop commits from the tip but keep your files in the worktree (`--mixed`, the default), discard local changes entirely (`--hard`), or move the tip while merging index and worktree updates toward the target but keeping unrelated local edits (`--keep`).

`--soft` updates the branch ref only: staged and unstaged files stay as they are. That is the usual way to “uncommit” the last commit while keeping everything staged.

`--mixed` moves the tip and resets the index to match `<rev>`; the worktree is not touched.

`--hard` moves the tip, resets the index, and updates tracked files in the worktree to match `<rev>`. Untracked files are left alone. Paths that were unmerged when the reset started and are absent from `<rev>` are removed from the worktree (including files another side introduced during a conflict). Intent-to-add paths stay on disk as untracked files, as in Git.

In a blobless clone, `--hard` batches missing blobs needed to materialize or repair tracked paths into one promisor fetch. This includes `reset --hard HEAD` after `clone --blobs none --no-checkout`, and unchanged paths missing from the worktree when resetting to another commit. Repeated blob ids are requested once; sparse-excluded paths and submodule gitlinks do not download blob content. The usual partial-clone lazy-fetch opt-outs still apply.

In a sparse checkout (`git sparse-checkout`), `--hard` and `--mixed` keep paths outside the sparse patterns out of the worktree: their index entries keep the skip-worktree bit, the same as `git reset`. User skip-worktree entries (for example `git update-index --skip-worktree`) are preserved on `--mixed` and `--hard` as well; hard reset refuses when the target tree would change such a path and your worktree edit differs from the index. Hard reset handles tracked directories replaced by files or symlinks, including directories with materialized files outside the sparse patterns. Files reached through a symlinked parent are left untouched.

`--keep` moves the tip and updates paths that differ between the current commit and `<rev>`, but refuses when a path that would change also has local staged or unstaged edits. Unrelated local changes (files that do not differ between the commits) are preserved.

`--dry-run` reports what would happen — including paths that `--hard` would discard or `--keep` would refuse on — without moving refs, the index, or the worktree.

A successful reset (any mode except `--dry-run`) ends an in-progress merge, cherry-pick, or revert the same way Git's `reset` does: operation sentinel files such as `MERGE_HEAD` and `CHERRY_PICK_HEAD` are removed.

A reset that moves the tip checks that the branch (or detached `HEAD`) still names the commit the reset started from, so a concurrent update is reported instead of overwritten. The move is appended to the branch's and `HEAD`'s reflogs where `core.logAllRefUpdates` asks for one or the reflog already exists, as Git does.

Every successful reset, in any mode and also to the commit `HEAD` is already on, records the commit `HEAD` was on before it in `ORIG_HEAD` (as `git reset` does, with no reflog), replacing any earlier value. `grit reset ORIG_HEAD` with the same mode undoes the reset, and `grit reset --hard ORIG_HEAD` is the usual way to undo a merge, rebase or pull, which record `ORIG_HEAD` too. `--dry-run` and a refused reset leave `ORIG_HEAD` alone.

When resetting backward, grit lists commits that would leave the branch (not reachable from `<rev>` or any other ref, including branches, tags, remotes, stash, and other worktrees). After a successful reset, human output reports how many commits are no longer on the branch, the previous tip (abbreviated), and how to recover with the same mode you used — for example `grit reset --hard <previous>` after a hard reset, or `grit reset <previous>` after the default mixed reset (also recorded in `ORIG_HEAD`, and in the reflog when reflogs are enabled). With `--dry-run`, the same count uses future tense (“would leave …”) because nothing has moved yet. The check usually stays near the commits being left behind, so undoing the last commit stays fast on deep repositories; annotated tags are peeled from `packed-refs` when it records their targets, and without a commit-graph the tip commits of hundreds of refs are read in parallel, headers only. Refs recorded in `packed-refs` (on a clone, usually every tag) are not read at all when every commit being left behind is dated more than a day after the file was last written: such a ref named a commit that already existed then, so it cannot reach them. Otherwise, and in repositories with grafts, replace refs or a shallow boundary, those refs are read as above. With a commit-graph the count is exact. Without one, the walk ends by commit date like Git's `git rev-list <previous> --not <refs>`, so under heavy clock skew (a ref that reaches a commit through history dated more than a day before it, or a commit dated more than a day ahead of when it was made) the count can be wrong.

`<rev>` is any revision Grit understands: branch name, `HEAD~1`, full or abbreviated commit id, and so on.

## Options

| Option | Description |
| --- | --- |
| `<rev>` | Commit to reset to. Defaults to `HEAD`. |
| `--soft` | Move the branch tip only. |
| `--mixed` | Move the tip and reset the index (default when no mode flag is given). |
| `--hard` | Move the tip, reset the index, and update the worktree. |
| `--keep` | Move the tip and update differing paths; refuse when local edits block a tree change. |
| `--dry-run` | Preview the reset without changing refs, index, or worktree. |
| `-n`, `--limit` | Cap the `orphaned_commits` list in `--json` output (default 20). |

## Examples

Uncommit the last commit but keep changes staged:

```console
$ grit reset --soft HEAD~1
Reset refs/heads/main to a1b2c3d (soft)
Warning: 1 commit is no longer on refs/heads/main (was d4e5f6a). Recover it with `grit reset --soft d4e5f6a` (recorded in ORIG_HEAD and, when reflogs are on, the reflog).
```

Hard reset two commits back, then follow the recovery hint to restore the branch and worktree:

```console
$ grit reset --hard HEAD~2
Reset refs/heads/main to a1b2c3d (hard)
Warning: 2 commits are no longer on refs/heads/main (was f6a7b8c). Recover them with `grit reset --hard f6a7b8c` (recorded in ORIG_HEAD and, when reflogs are on, the reflog).
$ grit reset --hard f6a7b8c
Reset refs/heads/main to f6a7b8c (hard)
```

Move the tip back one commit and unstage, keeping file contents:

```console
$ grit reset HEAD~1
Reset main to a1b2c3d (mixed)
```

Preview a hard reset without discarding work:

```console
$ grit reset --dry-run --hard HEAD~1
Would reset main to a1b2c3d (hard)
Would discard local changes in:
  tracked.txt
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/reset/schemas/reset/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `mode` | string | `soft`, `mixed`, `hard`, or `keep`. |
| `target` | string | Full hex oid of the commit `HEAD` will point at (or would, when `dry_run` is true). |
| `previous` | string | Full hex oid before the reset. |
| `ref` | string | Branch ref updated, or `HEAD` when detached. |
| `dry_run` | boolean | True when nothing was written. |
| `would_overwrite` | string[] | With `--dry-run --hard`: tracked paths whose local edits would be discarded. |
| `would_block` | string[] | With `--dry-run --keep`: paths that would make the reset refuse. |
| `orphaned_commits` | object[] | Sample of commits that would leave the branch (`oid`, `change_id`, `subject`). |
| `orphaned_total` | number | Advisory unreachable count (may exceed `orphaned_commits.length`). Without a commit-graph, severe clock skew can make this inaccurate; it never controls the reset. |
| `orphaned_truncated` | boolean | True when `-n`/`--limit` capped the orphan list. |

Example:

```json
{
  "mode": "soft",
  "target": "062ca6e74f5603f4d09063c0f46cd07d8c96e019",
  "previous": "83352a61f6715ec3f0a297c6d6150725154fb833",
  "ref": "refs/heads/main",
  "dry_run": false,
  "would_overwrite": [],
  "would_block": [],
  "orphaned_commits": [
    {
      "oid": "83352a61f6715ec3f0a297c6d6150725154fb833",
      "change_id": "xzyqzyyzswyupvtlsovyzultryuqzlvk",
      "subject": "second"
    }
  ],
  "orphaned_total": 1,
  "orphaned_truncated": false
}
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/reset/schemas/reset/v1.json/index.md)
Pass `--markdown` for agent-friendly output: a short heading plus bullet list of ref, mode, target, previous, dry-run, and orphan summary.



```text
## Reset

- **ref:** `refs/heads/main`
- **mode:** `soft`
- **target:** `062ca6e74f5603f4d09063c0f46cd07d8c96e019`
- **previous:** `83352a61f6715ec3f0a297c6d6150725154fb833`
- **dry_run:** `false`
- **orphaned_total:** `1` (truncated: `false`)
- **recovery:** `grit reset --soft 83352a61f6715ec3f0a297c6d6150725154fb833` restores it (also recorded in ORIG_HEAD; reflog when enabled)
```

Resetting to default `HEAD` on an unborn branch reports `branch_no_commits` (same message as [`grit log`](https://grit-scm.com/docs/reset/log.md/index.md)) instead of an opaque revision error.

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.

When another process holds `.git/index.lock`, `--hard`, `--keep` and the default mixed reset fail with exit `1` (`kind` `lock_held` under `--json`) before touching anything: `HEAD`, the branch, the index and the worktree are unchanged. Retry once the other process finishes.


## See also

[grit switch](https://grit-scm.com/docs/switch/index.md), [grit restore](https://grit-scm.com/docs/restore/index.md), [grit commit](https://grit-scm.com/docs/commit/index.md)
Sparse indexes keep unchanged excluded directory trees compact during checkout.
Only affected directories or directories present outside the sparse cone need
individual index rows. Performance and scaling methodology are documented in
[Benchmarks](https://grit-scm.com/docs/benchmarks.md/index.md).

Hard reset reapplies the sparse definition: tracked files that appeared outside
the cone are removed again. `sparse.expectFilesOutsideOfPatterns=true` preserves
outside files whose index entries still have skip-worktree set. Keep-reset uses
the full worktree guard checks for unmerged indexes.

# https://grit-scm.com/docs/pick/index.md

# grit pick

> Cherry-pick one or more commits onto the current branch.

## Synopsis

```text
grit pick [<commit> | <range>]...
grit pick --check [<commit> | <range>]...
grit pick --continue | --abort | --skip
```

## Description

Replays commits from another branch (or arbitrary revisions) onto the current branch, like `git cherry-pick`. Each new commit keeps the original **author** and message (unless you pass `--message` / `--message-file` for a single commit), gets a fresh **`change-id`**, and records a normal reflog entry. Textual merges use the histogram diff algorithm, matching Git merge-ort (same as [`grit merge`](https://grit-scm.com/docs/merge/index.md)).

Positional arguments are applied **oldest first**. Each argument is either:

- a single commit (`feature`, `abc1234`, `HEAD~2`), or
- a two-dot range `A..B` (commits reachable from `B` but not from `A`, same as `git log A..B`).

`grit pick` stops — leaving Git-compatible sequencer state — when:

- a step has **merge conflicts** (conflict markers in the worktree, `CHERRY_PICK_HEAD`, `MERGE_MSG`, `.git/sequencer/`)
- a step would be **empty** and `--empty stop` (default)
- the worktree is **dirty**, or the branch has **no commits** (detached `HEAD` is allowed, like `git cherry-pick`)
- a commit is a **merge** without `--mainline` (not yet exposed on the CLI)

Resolve conflicts, then either run [`grit commit`](https://grit-scm.com/docs/commit/index.md) (auto-stages the worktree and finishes the step, keeping the picked author) or stage with [`grit add`](https://grit-scm.com/docs/add/index.md) and run `grit pick --continue`. Use `grit pick --skip` to drop the current step, or `grit pick --abort` to cancel. If the branch tip moved because you already committed the resolution, `--abort` clears replay state without moving the branch (Git warns and exits 0 in the same situation).

Pick either completes a step, stops for conflicts or an empty commit, or changes nothing. Pressing Ctrl+C, or sending `SIGTERM` or `SIGHUP` on Unix, while files are being checked out stops the pick with `error: operation cancelled`; `HEAD`, the index and the work tree are left as they were before the pick started (no `CHERRY_PICK_HEAD`), no `.git/index.lock` is left behind, and the same pick can simply be run again. This works the same in a Windows console, where Ctrl+Break counts as Ctrl+C. A second interrupt terminates grit at once, without that cleanup; only `SIGKILL` skips rollback.

## Options

| Option | Description |
| --- | --- |
| `<commit>`… | Commits or ranges to replay (oldest first). |
| `--continue` | Finish the paused pick after conflicts are resolved and staged. |
| `--abort` | Cancel the in-progress pick and restore the branch tip and worktree (conflict-only files from the other side are removed). Uses `sequencer/head` when grit wrote a sequencer directory; otherwise resets the index and worktree to the current tip (including after a conflicting `git cherry-pick`). A stale `ORIG_HEAD` from an earlier operation is ignored. |
| `--skip` | Skip the current todo step and continue with the rest; the worktree is reset to the saved tip, including removing conflict-only paths. |
| `-x`, `--record-origin` | Append `(cherry picked from commit …)` to each new message. |
| `--no-commit` | Apply the patch to the index and worktree without committing. |
| `--empty` | When a step would not change the tree: `stop` (default), `keep` (empty commit), or `drop`. |
| `-m`, `--message` | Replace the message (only with exactly one commit). |
| `-F`, `--message-file` | Read the message from a file, or `-` for stdin (only with exactly one commit). |
| `--mainline` | Parent number when replaying a merge commit (library support; CLI wiring pending). |
| `--check` | Predict whether the pick would succeed without changing refs, the index, or the worktree. Exit **0** when every step would apply cleanly; exit **1** when a step would conflict or stop as empty (with `--empty stop`), including rename/delete conflicts at the new path (same as [`grit merge`](https://grit-scm.com/docs/pick/merge.md/index.md)). Conflicts with `--continue`, `--abort`, `--skip`, and `--dry-run`. |
| `--dry-run` | Print the commits that would be replayed without changing refs or the worktree. Conflicts with `--check`. |
| `-X ours\|theirs` | Auto-resolve replay conflicts: keep the current branch side (`ours`) or the picked change (`theirs`). |
| `--conflict merge\|diff3\|zdiff3` | Conflict marker style when a step stops with conflicts (default from `merge.conflictStyle`). |

## Examples

Pick the latest commit on a topic branch:

```console
$ grit pick feature
Picked cf18394 → 4be20a1 Say hi
```

Pick a range of commits:

```console
$ grit pick main..feature
Picked a1b2c3d → d4e5f6a First change
Picked b2c3d4e → e5f6a7b Second change
```

While a rebase is paused, `grit pick` refuses (it does not treat conflict markers as a dirty worktree):

```console
$ grit pick main
error: cannot pick while a rebase is in progress; finish it with `grit rebase --continue` or cancel it with `grit rebase --abort`
```

Conflict, then continue:

```console
$ grit pick topic~1..topic
CONFLICT (both_modified): shared.txt
→ grit restore --ours shared.txt (or edit markers)
→ grit add shared.txt
→ grit pick --continue
Picked … → … Resolved topic change
```

## JSON output

Schema: [v2](https://grit-scm.com/docs/pick/schemas/pick/v2.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `result` | string | `picked`, `clean`, `conflicts`, `empty`, `aborted`, or `skipped`. |
| `oid` | string or null | Predicted final tree oid when `result` is `clean` (`--check` only). |
| `check` | boolean | True when `--check` was used (nothing was picked). |
| `commits` | array | Each picked or attempted step: `source`, `oid`, `change_id`, `subject`. |
| `dropped` | array | Source commit oids skipped as empty (`--empty drop`). |
| `conflicts` | array or null | Conflicted paths when `result` is `conflicts`, each `{path, kind}` with a [conflict kind](https://grit-scm.com/docs/status/index.md#conflict-kinds). |
| `rerere` | array | Rerere events when `rerere.enabled` is active and the pick stops on conflicts (`path`, `kind` as for [`grit merge`](https://grit-scm.com/docs/merge/index.md#json-output)). Omitted when empty. |
| `next_steps` | array or null | Suggested commands when stopped (`conflicts` or `empty`). |
| `alternatives` | array or null | `grit pick --abort` / `--skip` when a sequence is paused. |
| `dry_run` | boolean or null | `true` when `--dry-run` was set (no refs or objects were updated). |

Example (success):

```json
{
  "result": "picked",
  "commits": [
    {
      "source": "6e513d5cd6ab8d618238e22d7ca55d942b55964a",
      "oid": "a1b2c3d4e5f6789012345678901234567890abcd",
      "change_id": "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
      "subject": "Say hi"
    }
  ],
  "dropped": []
}
```

On conflicts, exit code is **1** with `result: "conflicts"` and the same conflict shape as [`grit merge`](https://grit-scm.com/docs/merge/index.md).

## Markdown output

Schema: [v2](https://grit-scm.com/docs/pick/schemas/pick/v2.json/index.md)

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a `Pick` heading, one bullet per replayed commit, and conflict next steps when stopped.




```text
## Pick

- `d5d832b` → `d5d832b` — pick me
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Pick completed or `--check` predicts a clean replay. |
| `1` | Conflicts, empty commit, or other failure. |
| `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md).


## See also

[grit merge](https://grit-scm.com/docs/merge/index.md), [grit revert](https://grit-scm.com/docs/revert/index.md), [grit log](https://grit-scm.com/docs/log/index.md)

# https://grit-scm.com/docs/revert/index.md

# grit revert

> Undo commits with new inverse commits.

## Synopsis

```text
grit revert [<commit>...]
grit revert --check [<commit>...]
grit revert --continue | --abort | --skip
```

## Description

Creates new commits on the current branch that undo the changes introduced by each listed commit. Reverts run **newest first** within a revision range, matching `git revert`. Each revert commit uses the standard `Revert "…"` subject and a `This reverts commit <oid>.` body (unless you pass `-m` / `--message-file` for a single commit), and gets a new `change-id`.

`<commit>` can be a full or short commit id, a branch name, a range such as `v1.0..main`, or several commits in one invocation.

When a step would conflict, grit stops with conflict markers in the worktree and unmerged index entries — the same model as [`grit pick`](https://grit-scm.com/docs/pick/index.md) and [`grit merge`](https://grit-scm.com/docs/merge/index.md). Resolve conflicts, then either run [`grit commit`](https://grit-scm.com/docs/commit/index.md) (auto-stages and finishes the step) or stage with [`grit add`](https://grit-scm.com/docs/add/index.md) and run `grit revert --continue`. Use `--abort` to restore the branch to its pre-revert state when the tip has not moved; if you already committed the resolution, `--abort` only clears revert state. Use `--skip` to drop the current step and continue with any remaining commits.

Merge commits require `--mainline <n>` (1-based parent number, long option only) so grit knows which parent line to replay.

Revert either completes a step, stops for conflicts or an empty commit, or changes nothing. Pressing Ctrl+C, or sending `SIGTERM` or `SIGHUP` on Unix, while files are being checked out stops the revert with `error: operation cancelled`; `HEAD`, the index and the work tree are left as they were before the revert started (no `REVERT_HEAD`), no `.git/index.lock` is left behind, and the same revert can simply be run again. This works the same in a Windows console, where Ctrl+Break counts as Ctrl+C. A second interrupt terminates grit at once, without that cleanup; only `SIGKILL` skips rollback.

## Options

| Option | Description |
| --- | --- |
| `<commit>…` | Commits or revision ranges to revert (required unless continuing). |
| `--mainline <n>` | Parent number when reverting a merge commit. |
| `--continue` | Finish a revert stopped on conflicts or an empty commit. |
| `--abort` | Cancel the in-progress revert and restore the branch tip and worktree (conflict-only files from the other side are removed). Uses `sequencer/head` when grit wrote a sequencer directory; otherwise resets the index and worktree to the current tip (including after a conflicting `git revert`). A stale `ORIG_HEAD` from an earlier operation is ignored. |
| `--skip` | Skip the current commit and continue with the rest of the sequence; the worktree is reset to the saved tip, including removing conflict-only paths. |
| `--no-commit` | Apply the revert to the index only; do not create a commit yet. |
| `--empty stop\|keep\|drop` | When a step would not change the tree: stop (default), record an empty commit, or skip the step. |
| `-m`, `--message` | Replace the revert message (**single commit only**). |
| `-F`, `--message-file` | Read the revert message from a file, or `-` for stdin (**single commit only**). |
| `--check` | Predict whether the revert would succeed without changing refs, the index, or the worktree. Exit **0** when every step would apply cleanly; exit **1** when a step would conflict or stop as empty (with `--empty stop`). Conflicts with `--continue`, `--abort`, `--skip`, and `--dry-run`. |
| `--dry-run` | List commits that would be reverted without changing refs or the worktree. Conflicts with `--check`. |
| `-X ours\|theirs` | Auto-resolve replay conflicts: keep the current branch side (`ours`) or the reverted change (`theirs`). |
| `--conflict merge\|diff3\|zdiff3` | Conflict marker style when a step stops with conflicts (default from `merge.conflictStyle`). |

## Examples

Revert the previous commit:

```console
$ grit revert HEAD~1
Reverted a1b2c3d → e4f5g6h Revert "Add feature"
```

Revert a merge (first parent as mainline):

```console
$ grit merge feature
$ grit revert --mainline 1 HEAD
Reverted 9a1c2e0 → b2c3d4e Revert "Merge branch 'feature'"
```

Revert a range (newest commit in the range first):

```console
$ grit revert release~5..release
Reverted f1e2d3c → … Revert "Prepare release"
Reverted a1b2c3d → … Revert "Bump version"
```

While a rebase is paused:

```console
$ grit revert main
error: cannot revert while a rebase is in progress; finish it with `grit rebase --continue` or cancel it with `grit rebase --abort`
```

When the revert conflicts:

```console
$ grit revert feature
CONFLICT (both_modified): f.txt

Revert stopped on conflicts; fix them and run `grit revert --continue`, or `grit revert --abort` / `grit revert --skip`.
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/revert/schemas/revert/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `result` | string | `completed`, `clean`, `conflicts`, `aborted`, or `empty`. |
| `source` | string or null | Source commit for the last revert created when `result` is `completed`. |
| `oid` | string or null | New revert commit when `result` is `completed`, or the predicted final tree oid when `result` is `clean`. |
| `subject` | string or null | Subject of the last revert commit when `result` is `completed`. |
| `change_id` | string or null | Stored `change-id` on the last revert commit, or `null`. |
| `commits` | array | Each revert commit created in this invocation (newest first). |
| `dropped` | array | Source commits skipped as empty per `--empty drop`. |
| `conflicts` | array or null | Conflicted paths when `result` is `conflicts`, each `{path, kind}` with a [conflict kind](https://grit-scm.com/docs/status/index.md#conflict-kinds). |
| `rerere` | array | Rerere events when `rerere.enabled` is active and the revert stops on conflicts (`path`, `kind` as for [`grit merge`](https://grit-scm.com/docs/merge/index.md#json-output)). Omitted when empty. |
| `next_steps` | array or null | Suggested follow-up commands when paused. |
| `alternatives` | array or null | `--abort` / `--skip` when paused. |
| `dry_run` | boolean or null | True when `--dry-run` was used. |
| `check` | boolean | True when `--check` was used (nothing was reverted). |

Example:

```json
{
  "result": "completed",
  "source": "6e513d5cd6ab8d618238e22d7ca55d942b55964a",
  "oid": "a8f2c1d0e9b876543210abcdef0123456789abcd",
  "subject": "Revert \"Add feature\"",
  "commits": [
    {
      "source": "6e513d5cd6ab8d618238e22d7ca55d942b55964a",
      "oid": "a8f2c1d0e9b876543210abcdef0123456789abcd",
      "subject": "Revert \"Add feature\"",
      "change_id": "zzzzzzzz"
    }
  ],
  "dropped": []
}
```

When `result` is `conflicts`, exit code is **1** and the object includes `conflicts`, `next_steps`, and `alternatives` (same shape as [`grit merge`](https://grit-scm.com/docs/merge/index.md) conflicts).

## Markdown output

Schema: [v1](https://grit-scm.com/docs/revert/schemas/revert/v1.json/index.md)

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a `Revert` heading and one bullet per reverted commit:

```text
- `9244cbd` → `bbbca73` — Revert "third"
```


## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Revert completed or `--check` predicts success. |
| `1` | Conflicts, empty revert, or other failure. |
| `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md).


## See also

[grit pick](https://grit-scm.com/docs/pick/index.md), [grit merge](https://grit-scm.com/docs/merge/index.md)

# https://grit-scm.com/docs/tag/index.md

# grit tag

> List tags, or create or delete one (lightweight or annotated).

## Synopsis

```text
grit tag
grit tag -l [<pattern>...]
grit tag --sort version|date|name [--reverse] [--contains [REV]] [--points-at REV] [-n N]
grit tag <name>
grit tag <name> [<target>]
grit tag <name> -m <message>
grit tag <name> -F <path|->
grit tag <name> -s -m <message>
grit tag <name> -s --tree-sha256 -m <message>
grit tag <name> -f
grit tag <name> --dry-run
grit tag -d <name>
grit tag --verify <name>...
grit tag -v <name>... --no-signature
```

## Description

With no arguments, lists tag names sorted by **version** (`version:refname`). Use `-l` / `--list` with optional glob patterns (repeatable), `--sort version|date|name`, `--reverse`, `--contains [REV]` (defaults to `HEAD`), `--points-at <REV>` (repeatable), and `-n` / `--limit` to cap the list. Plain human output reads names only and avoids loading annotated tag objects; `--json` and `--markdown` retain full annotation metadata.

With a name and no `-m`/`-F`, creates a **lightweight** tag pointing at `HEAD` or the optional `<target>` revision. With `-m` or `-F`, creates an **annotated** tag object with that message (comment lines starting with `#` are stripped, matching Git's default cleanup). Use `-s` / `--sign` (or `tag.gpgSign=true`) to cryptographically sign an annotated tag; signed tags verify with `git verify-tag` and system `git tag -v`.

Annotated tag messages are stored as raw bytes (Git has no `encoding` header on tags). When listing with `--json` or `--markdown`, a message that is not valid UTF-8 is shown as a Unicode string with U+FFFD replacement characters, not as a corrupt object.

Use `-f` / `--force` to replace an existing tag (lightweight or annotated). The previous ref target is reported in `--json` as `replaced`.

Use `--dry-run` on create or delete to preview the outcome without changing refs.

Use `--tree-sha256` on a signed tag to attach a [tree-sha256](https://grit-scm.com/docs/library/tree-sha256.md/index.md) content digest of the tagged commit's tree (implies signing). Repeat `--exclude-submodule <glob>` to record excluded submodule paths in `tree-sha256-excluded` headers.

Use `--verify` / `-v` on one or more **annotated** tag names to check the tag object's signature (OpenPGP or SSH, when present) and, when the tag carries a `tree-sha256` header, recompute that digest against the tagged commit's tree. Lightweight tags cannot be verified. Use `--no-signature` to skip signature checking while still validating `tree-sha256` when present.

**Exit codes:** `grit tag --verify` exits **0** when every named tag passes and **1** when any tag fails verification or is not an annotated tag. Other `grit tag` modes use the default exit code (**0** on success).

Tag names must be valid as `refs/tags/<name>` under Git's ref-name rules (same checks as `git check-ref-format refs/tags/<name>`). Invalid names are rejected before writing under `.git/refs`.

Tags are local until you publish them with [`grit push --tags`](https://grit-scm.com/docs/push/index.md). Delete a remote tag with [`grit push --delete`](https://grit-scm.com/docs/push/index.md).

## Options

| Option | Description |
| --- | --- |
| `<name>` | The tag to create or delete. Omit to list tags. |
| `<target>` | Revision to tag (default `HEAD`). |
| `-l`, `--list` | List tags matching `PATTERN` (repeatable). Omit `PATTERN` to list all. |
| `--sort` | `version` (default), `date`, or `name`. |
| `--reverse` | Reverse the sort order. |
| `--contains` | Only tags whose peeled commit contains `REV` (default `HEAD`). |
| `--points-at` | Only tags pointing at `REV` (repeatable). |
| `-n`, `--limit` | Maximum number of tags to print. |
| `-d`, `--delete` | Delete the tag locally. |
| `-a`, `--annotate` | Git habit for an annotated tag; ignored when `-m` or `-F` is set (those already create an annotated tag). Without a message, grit errors instead of opening an editor. |
| `-m`, `--message` | Annotated tag message (repeatable; paragraphs are separated by a blank line, like Git). |
| `-F`, `--message-file` | Read the annotated tag message from a file (`-` reads stdin). |
| `--file` | Hidden alias for `--message-file` (deprecated; emits a one-time warning). |
| `-f`, `--force` | Replace an existing tag with the same name. |
| `--dry-run` | Preview create or delete without updating refs. |
| `-s`, `--sign` | Sign the tag object (implies annotated; honors `tag.gpgSign` when omitted). |
| `--no-sign` | Do not sign, even when `tag.gpgSign` is true. |
| `--signing-key` | Signing key id or path for this tag (overrides `user.signingkey`). |
| `--tree-sha256` | Attach a tree-sha256 digest (implies `--sign`). |
| `--exclude-submodule` | Submodule path glob excluded from the digest (repeatable). |
| `-v`, `--verify` | Verify annotated tags (one or more names). |
| `--no-signature` | With `--verify`, skip signature checks (digest still checked when present). |
| `--object` | Hidden alias for `<target>` (one release). |

## Examples

```console
$ grit tag v0.1 -m 'First release'
Created tag v0.1

$ grit tag v0.2 -s -m 'Signed release'
Created tag v0.2

$ grit tag v0.1 main -f -m 'Repointed release'
Created tag v0.1

$ grit tag
  v0.1

$ grit push --tags
  pushed --tags → origin refs/tags/v0.1

$ grit push --delete v0.1
  deleted v0.1 from origin

$ grit tag -d v0.1
Deleted tag v0.1

$ grit tag --verify v0.2 --no-signature
tag v0.2 (92501f1…): ok
  target: abc1234…
  signature: not_checked (—)
  elapsed: 12 ms
```

## JSON output

Schema: [v2](https://grit-scm.com/docs/tag/schemas/tag/v2.json/index.md), [v1](https://grit-scm.com/docs/tag/schemas/tag/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output. The object's `action` field says what happened:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `action` | string | `list`, `create`, `delete`, or `verify`. |
| `tags` | array | For `list`, each tag with `name`, `oid`, `kind`, `target_kind`, optional `peeled`, and optional `annotation` (`subject`, `message`, `tagger` with `name`, `email`, `date` in RFC 3339). |
| `truncated` | boolean | For `list`: `true` when more tags matched than returned (`-n` / `--limit`). |
| `name` | string | For `create` or `delete`, the tag name. |
| `oid` | string | For `create`, full id the tag ref points at (tag object or commit). |
| `kind` | string | For `create` or list entries: `lightweight` or `annotated`. |
| `signed` | boolean | For `create`, whether the tag object was signed. |
| `peeled` | string | Commit oid when the tag peels to a commit. |
| `replaced` | string | For `create` with `--force`, oid the tag ref pointed at before replacement. |
| `dry_run` | boolean | For `create` or `delete`, whether refs were left unchanged. |
| `tree_sha256` | string | For `create` with `--tree-sha256`, hex digest recorded on the tag. |
| `tree_sha256_excluded` | array | Submodule paths excluded from the digest (when `--exclude-submodule` is used). |
| `tree_sha256_files` | integer | Blob count hashed for the tree-sha256 claim. |
| `tree_sha256_submodules` | integer | Submodule trees included in the digest walk. |
| `tree_sha256_hash_ms` | number | Wall time spent computing the tree-sha256 digest (milliseconds). |
| `ok` | boolean | For `verify`, whether every tag passed. |

For `action: verify`, each element of `tags` includes `name`, `oid`, `target`, `ok`, `signature` (with `verdict`, optional `signer`, `key`, `trust`), optional `tree_sha256` (`claimed`, `computed`, `match_digest`, `files`, `submodules`, `excluded`, `bogus_excluded`, `cycles`), `not_verifiable_submodules` (`path`, `reason`), and `elapsed.ms`.

Listing tags:

```json
{
  "action": "list",
  "tags": [
    {
      "name": "v0.1",
      "oid": "92501f188ae0815af09a0cef6e121eddda4113cf",
      "kind": "annotated",
      "target_kind": "commit",
      "peeled": "abc1234567890abcdef1234567890abcdef123456",
      "annotation": {
        "subject": "First release",
        "message": "First release\n",
        "tagger": {
          "name": "Alex",
          "email": "alex@example.com",
          "date": "2023-11-14T22:13:20Z"
        }
      }
    }
  ]
}
```

Creating an annotated tag:

```json
{
  "action": "create",
  "name": "v0.1",
  "oid": "92501f188ae0815af09a0cef6e121eddda4113cf",
  "kind": "annotated",
  "signed": false,
  "dry_run": false,
  "peeled": "abc1234567890abcdef1234567890abcdef123456"
}
```

Verifying tags:

```json
{
  "action": "verify",
  "ok": true,
  "tags": [
    {
      "name": "v0.2",
      "oid": "92501f188ae0815af09a0cef6e121eddda4113cf",
      "target": "abc1234567890abcdef1234567890abcdef123456",
      "ok": true,
      "signature": {
        "verdict": "good",
        "signer": "Release Bot <bot@example.com>",
        "key": "ABCD1234",
        "trust": "fully"
      },
      "tree_sha256": {
        "claimed": "a119881755f081b9f694f1f05eb31fa4771a108bc854d61fdd4d12482e2a14e2",
        "computed": "a119881755f081b9f694f1f05eb31fa4771a108bc854d61fdd4d12482e2a14e2",
        "match_digest": true,
        "files": 3,
        "submodules": 0,
        "excluded": [],
        "bogus_excluded": [],
        "cycles": []
      },
      "not_verifiable_submodules": [],
      "elapsed": { "ms": 12 }
    }
  ]
}
```

## Markdown output

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output.

Schema: [v2](https://grit-scm.com/docs/tag/schemas/tag/v2.json/index.md), [v1](https://grit-scm.com/docs/tag/schemas/tag/v1.json/index.md)

Markdown uses headings, bullet lists, and fenced blocks; pipe characters inside table cells are escaped. See the JSON output section for the stable field contract.



```text
No tags yet.
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success, or `--verify` when every tag passes. |
| `1` | `--verify` when any tag fails or is not annotated. |
| `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md).


## See also

[grit push](https://grit-scm.com/docs/push/index.md)

# https://grit-scm.com/docs/worktree/index.md

# grit worktree

> List, add, and remove linked worktrees for the same repository.

## Synopsis

```text
grit worktree list
grit worktree add <path> [<rev>]
grit worktree add -b <branch> <path> [<rev>]
grit worktree add -B <branch> <path> [<rev>]
grit worktree add --detach <path> [<rev>]
grit worktree add --lock [--reason <text>] <path> [<rev>]
grit worktree add --no-checkout <path> [<rev>]
grit worktree add --track <path> [<rev>]
grit worktree add -f <path> [<rev>]
grit worktree remove <path>
grit worktree remove -f <path>
grit worktree lock <path> [--reason <text>]
grit worktree unlock <path>
grit worktree move <worktree> <new-path> [-f] [--dry-run]
grit worktree repair [<path>…] [--dry-run]
grit worktree prune
```

## Description

Git linked worktrees share one object database but have separate working trees and `HEAD`. `grit worktree list` shows the main worktree first, then linked worktrees (same order as `git worktree list`). The current worktree is prefixed with `*` in human output. Detached checkouts are labeled `(detached HEAD)` in human output (same idea as `git worktree list`). When the repository was opened from a bare clone, the main row is shown as `(bare)` without `*` or a branch name — bare `HEAD` is not a checkout and does not block `grit worktree add` for that branch. Linked rows whose working tree directory is gone are marked `prunable`, matching `git worktree list --porcelain` reason text in JSON.

Paths in human, `--json`, and `--markdown` output use normal absolute paths (no Windows `\\?\` verbatim prefix) with forward slashes, so scripts can pass them to `cd` or `grit worktree remove` unchanged.

`grit worktree add` creates the admin directory under `.git/worktrees/`, writes the `gitdir` / `commondir` files, checks out the tree (unless `--no-checkout`), and registers the new worktree. After checkout it runs the `post-checkout` hook from the new worktree with a null old object id, the start commit, and flag `1`, as Git does (skipped for `--no-checkout` and orphan branches). With only a path, grit creates a new branch named after the directory basename at `HEAD`. With a `<rev>` that names an existing branch, that branch is checked out (it must not already be checked out elsewhere). Use `-b` to create a new branch at `<rev>` (default `HEAD`). Use `-B` to create or reset a branch to `<rev>` (writes a reflog entry when resetting). Use `--detach` for a detached HEAD at the resolved commit. Use `--lock` (optional `--reason`) to write the `locked` file before checkout finishes. Use `--no-checkout` to register `HEAD` without populating the working tree. Use `--track` when the start point is a remote-tracking branch to set `branch.*.remote` / `merge` like `git worktree add --track`.

If `<path>` is already registered but its directory was deleted manually, grit refuses the add (same as Git). Use `-f` / `--force` to replace the stale registration, or `grit worktree prune` / `grit worktree remove` to clear it first.

While `grit worktree add` is checking out files, Ctrl+C (or `SIGTERM` / `SIGHUP` on Unix) stops with `error: operation cancelled` and exit code **130**. Grit removes the half-created worktree registration, rolls back a newly created branch, and leaves no stale `index.lock` in the linked admin directory. A second interrupt terminates grit immediately without that cleanup.

`grit worktree remove` deletes the linked worktree's admin directory and, with `-f`, the working tree even when it has local changes.

`grit worktree prune` removes admin directories for linked worktrees whose working tree is missing (skips locked worktrees). Use `--dry-run` to list what would be pruned without deleting registrations.

`grit worktree lock` writes a `locked` file under the worktree admin directory (same on-disk format as `git worktree lock`). Locked worktrees are skipped by `prune` and refused by `remove` unless `-f`.

`grit worktree unlock` removes that lock file.

`grit worktree move` relocates a linked worktree and rewrites the worktree `.git` gitfile and admin `gitdir` file atomically (same on-disk layout as `git worktree move`). The main worktree cannot be moved. Locked worktrees require `-f` / `--force` (Git requires `-f` twice; grit uses one force flag). Populated submodules block the move, matching Git.

`grit worktree repair` fixes broken `.git` / `gitdir` links after a manual directory move. With no paths, grit repairs every registered linked worktree from the open repository.

## Options

### `list`

No flags.

### `add`

| Option | Description |
| --- | --- |
| `<path>` | Directory for the new working tree (must be missing or empty). |
| `<rev>` | Commit or branch to check out (default `HEAD`). |
| `-b`, `--branch` | Create and check out a new branch at `<rev>`. |
| `-B` | Create or reset a branch to `<rev>` (refuses when that branch is checked out elsewhere). |
| `--detach` | Detached HEAD at the resolved commit. |
| `--lock` | Write the `locked` file before checkout completes. |
| `--reason` | Reason stored in the lock file (requires `--lock`). |
| `--no-checkout` | Register the worktree without checking out files. |
| `--track` | Set upstream when `<rev>` is a remote-tracking branch. |
| `-f`, `--force` | Replace a stale registration when the directory is missing. |

### `remove`

| Option | Description |
| --- | --- |
| `<path>` | Path to the linked worktree. |
| `-f`, `--force` | Remove even when locked or dirty. |

### `lock`

| Option | Description |
| --- | --- |
| `<path>` | Path to the linked worktree. |
| `--reason` | Optional reason stored in the lock file (shown by `git worktree list`). |

### `unlock`

| Option | Description |
| --- | --- |
| `<path>` | Path to the linked worktree. |

### `prune`

| Option | Description |
| --- | --- |
| `--dry-run` | Report prunable worktrees without removing registrations. |

### `move`

| Option | Description |
| --- | --- |
| `<worktree>` | Path to the linked worktree to move. |
| `<new-path>` | Destination (must not exist; if it is an existing directory, the worktree basename is appended). |
| `-f`, `--force` | Move even when the worktree is locked. |
| `--dry-run` | Preview the move without renaming or rewriting link files. |

### `repair`

| Option | Description |
| --- | --- |
| `[<path>…]` | Linked worktree roots to repair (default: all linked worktrees). |
| `--dry-run` | List repairs without writing files. |

## Examples

```console
$ grit worktree add ../hotfix -b hotfix main
Created worktree at /tmp/hotfix on branch hotfix

$ grit worktree list
  /tmp/repo
  /tmp/hotfix [hotfix]

$ grit worktree remove ../hotfix -f
Removed worktree /tmp/hotfix

$ grit worktree prune
Pruned worktree /tmp/old-wt
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/worktree/schemas/worktree.list/v1.json/index.md) · [worktree.add v1](https://grit-scm.com/docs/worktree/schemas/worktree.add/v1.json/index.md) · [worktree.remove v1](https://grit-scm.com/docs/worktree/schemas/worktree.remove/v1.json/index.md) · [worktree.prune v2](https://grit-scm.com/docs/worktree/schemas/worktree.prune/v2.json/index.md) · [worktree.lock v1](https://grit-scm.com/docs/worktree/schemas/worktree.lock/v1.json/index.md) · [worktree.unlock v1](https://grit-scm.com/docs/worktree/schemas/worktree.unlock/v1.json/index.md) · [worktree.move v1](https://grit-scm.com/docs/worktree/schemas/worktree.move/v1.json/index.md) · [worktree.repair v1](https://grit-scm.com/docs/worktree/schemas/worktree.repair/v1.json/index.md)

Pass `--json` on any subcommand. The top-level `action` is `list`, `add`, `remove`, `prune`, `lock`, `unlock`, `move`, or `repair`.

List:

```json
{
  "action": "list",
  "worktrees": [
    {
      "path": "/tmp/repo",
      "head": "abc1234…",
      "branch": "main",
      "detached": false,
      "bare": false,
      "locked": false,
      "lock_reason": null,
      "prunable": false,
      "prunable_reason": null,
      "is_current": true
    }
  ]
}
```

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `action` | string | `list`, `add`, `remove`, `prune`, `lock`, `unlock`, `move`, or `repair`. |
| `worktrees` | array | For `list`, one object per worktree (fields below). |
| `path` | string | For `add` / `remove` / `lock` / `unlock`, absolute path to the working tree. |
| `from` | string | For `move`, previous worktree path. |
| `to` | string | For `move`, new worktree path. |
| `repairs` | array | For `repair`, objects with `path` and `kind` for each link rewritten. |
| `head` | string | For `add`, current commit oid checked out in the new worktree. |
| `branch` | string or null | For `add`, branch checked out when not detached. |
| `locked` | boolean | For `add`, whether the worktree was created locked. |
| `checked_out` | boolean | For `add`, whether files were checked out (`false` with `--no-checkout`). |
| `dry_run` | boolean | For `prune`, whether registrations were left intact. |
| `reason` | string or null | For `lock`, optional reason stored in the lock file. |
| `pruned` | array | For `prune`, objects with `path` and `reason` for each pruned (or would-be pruned) worktree. |

Each object in `worktrees` (list action) includes `path`, `head`, `branch`, `detached`, `bare`, `locked`, `lock_reason` (always present, `null` when absent), `prunable`, optional `prunable_reason`, and `is_current`.

Add:

```json
{
  "action": "add",
  "path": "/tmp/hotfix",
  "branch": "hotfix",
  "head": "abc1234…",
  "locked": false,
  "checked_out": true
}
```

Remove:

```json
{
  "action": "remove",
  "path": "/tmp/hotfix"
}
```

Prune:

```json
{
  "action": "prune",
  "dry_run": false,
  "pruned": [
    {
      "path": "/tmp/old-wt",
      "reason": "gitdir file points to non-existent location"
    }
  ]
}
```

Lock:

```json
{
  "action": "lock",
  "path": "/tmp/hotfix",
  "reason": "maintenance"
}
```

Unlock:

```json
{
  "action": "unlock",
  "path": "/tmp/hotfix"
}
```

Move:

```json
{
  "action": "move",
  "from": "/tmp/linked",
  "to": "/tmp/moved",
  "dry_run": false
}
```

Repair:

```json
{
  "action": "repair",
  "repairs": [
    {
      "path": "/tmp/moved",
      "kind": "gitdir_worktree_path"
    }
  ],
  "dry_run": false
}
```

Repair `kind` values: `git_file_admin_dir`, `gitdir_worktree_path`, `git_file_path_style`, `gitdir_path_style`.

## Markdown output

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for structured output.

Schema: [worktree.list v1](https://grit-scm.com/docs/worktree/schemas/worktree.list/v1.json/index.md) · [worktree.add v1](https://grit-scm.com/docs/worktree/schemas/worktree.add/v1.json/index.md) · [worktree.remove v1](https://grit-scm.com/docs/worktree/schemas/worktree.remove/v1.json/index.md) · [worktree.prune v2](https://grit-scm.com/docs/worktree/schemas/worktree.prune/v2.json/index.md) · [worktree.lock v1](https://grit-scm.com/docs/worktree/schemas/worktree.lock/v1.json/index.md) · [worktree.unlock v1](https://grit-scm.com/docs/worktree/schemas/worktree.unlock/v1.json/index.md) · [worktree.move v1](https://grit-scm.com/docs/worktree/schemas/worktree.move/v1.json/index.md) · [worktree.repair v1](https://grit-scm.com/docs/worktree/schemas/worktree.repair/v1.json/index.md)

List shows a table of path, branch, and HEAD:

```text
| Path | Branch | HEAD |
| --- | --- | --- |
| /tmp/repo | `main` | `abc1234` |
| /tmp/hotfix | `hotfix` | `abc1234` |
```

Add and remove use short headings with the path and branch (or detached HEAD) and commit oid.


## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[grit switch](https://grit-scm.com/docs/switch/index.md), [grit branch](https://grit-scm.com/docs/branch/index.md)

# https://grit-scm.com/docs/remote/index.md

# grit remote

> List remotes, add one, show one, set URLs, rename or remove one, or list refs on a remote.

## Synopsis

```text
grit remote [-v]
grit remote add <name> <url> [--fetch]
grit remote set-url <name> <url> [--push] [--dry-run]
grit remote remove <name> [--dry-run]
grit remote prune <name> [--dry-run]
grit remote set-head <name> (--auto | <branch> | --delete) [--dry-run]
grit remote show <name> [--no-query] [-n N]
grit remote rename <old> <new> [--dry-run]
grit remote refs <remote-or-url> [--heads] [--tags] [--sort name|version] [--reverse] [-n N] [<prefix>…]
```

## Description

A remote is another copy of the repository that you fetch from and push to, usually on a server. With no arguments, `grit remote` lists your remotes and their URLs, sorted by name. Like `git remote`, the list includes a remote that has config but no URL, shown as `(no url)`.

`grit remote add` adds a remote. It writes `remote.<name>.url` and the fetch refspec `+refs/heads/*:refs/remotes/<name>/*` to the repository's shared config, also when run from a linked worktree. It fails if a remote with that name is already configured, or if the name could not be used in a ref such as `refs/remotes/<name>/main` (for example names with spaces, `..` or `:`). With `--fetch` (long only; `-f` means force elsewhere in grit), it runs [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) for that remote immediately after adding it. [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) stores the remote's branches as remote-tracking branches named `<name>/<branch>`, such as `origin/main`. [`grit clone`](https://grit-scm.com/docs/clone/index.md) adds a remote called `origin` for you.

`grit remote prune` deletes stale remote-tracking refs for one remote without fetching: it lists refs on the remote, compares them to local tracking refs under that remote's fetch refspecs (same rules as `git fetch --prune`), and removes refs whose upstream branch is gone. `refs/remotes/<name>/HEAD` is never pruned. `--dry-run` lists refs that would be removed without deleting them.

`grit remote set-head` updates or deletes the `refs/remotes/<name>/HEAD` symref. `--auto` queries the remote default branch and points HEAD at `refs/remotes/<name>/<branch>` when that tracking ref exists locally. A branch argument sets HEAD to that branch. `--delete` removes the symref. `--dry-run` reports the change without updating refs.

`-v` / `--verbose` lists fetch and push URLs on separate lines (`name url (fetch)` and `name url (push)`), like `git remote -v`. With `--json`, each remote also includes `fetch_url` and `push_url` after `url.*.insteadOf` / `pushInsteadOf` rewrites, plus `refspecs`.

`grit remote set-url` changes the fetch URL (`remote.<name>.url`) or, with `--push`, replaces every `remote.<name>.pushurl` with a single new push URL. It fails when the remote is not configured. `--dry-run` reports the change without writing config.

`grit remote remove` deletes a configured remote: it removes the `remote.<name>` section from the shared config, deletes every remote-tracking ref this remote's fetch refspecs map to (including `refs/remotes/<name>/HEAD`), and clears `branch.<b>.remote`, `branch.<b>.merge`, and matching `branch.<b>.pushRemote` / `remote.pushDefault` keys. Tracking refs that another remote's fetch refspec also maps to are kept. `--dry-run` reports what would change without writing config or refs. There is no `rm` alias.

`grit remote show` summarizes one configured remote: fetch and push URLs, the remote `HEAD` branch, each remote branch classified as tracked, new, or stale (when the remote is queried), and local branches whose `branch.<name>.remote` points at this remote. By default it contacts the remote (same transports as [`grit fetch`](https://grit-scm.com/docs/fetch/index.md)). With `--no-query`, branch rows come from local remote-tracking refs only and every branch is reported as tracked.

`grit remote rename` renames a configured remote. When the remote uses the default fetch refspec into `refs/remotes/<name>/`, every remote-tracking ref is renamed in one transaction (reflogs preserved), then the config section is renamed, default fetch refspecs are updated, and `branch.*.remote`, `branch.*.pushRemote`, and `remote.pushDefault` entries that pointed at the old name are retargeted. Custom fetch refspecs that do not map into `refs/remotes/<old>/` are left unchanged. `--dry-run` reports counts without changing the repository.

`grit remote refs` lists references on a configured remote name or a literal URL, scp-style `host:path` or path (same transports as [`grit clone`](https://grit-scm.com/docs/clone/index.md)), matching `git ls-remote` ordering. An argument that is none of these fails with `unknown remote`. SSH URLs use the same `GIT_SSH_COMMAND`, `GIT_SSH`, and `core.sshCommand` resolution as [`grit clone`](https://grit-scm.com/docs/clone/index.md) and [`grit fetch`](https://grit-scm.com/docs/fetch/index.md). Like fetch, listing uses `protocol.version` from config (default **2**): SSH sets `GIT_PROTOCOL=version=N` on the ssh child when `N > 0`, and adds `-o SendEnv=GIT_PROTOCOL` when the resolved program basename is `ssh` / `ssh.exe` (including a `GIT_SSH_COMMAND` line that starts with `ssh`), or when `GIT_SSH_VARIANT=ssh`.

## Options

| Option | Description |
| --- | --- |
| `-v`, `--verbose` | With no subcommand, show fetch and push URLs (like `git remote -v`). |
| `add <name> <url>` | Add a remote called `<name>` at `<url>`. Fails if a remote with that name exists or the name is not valid in a ref. |
| `--fetch` | With `add`, fetch from the new remote after writing config. |
| `prune <name>` | Delete stale remote-tracking refs for `<name>`. `--dry-run` previews without deleting. |
| `set-head <name> …` | Set or delete `refs/remotes/<name>/HEAD` (`--auto`, a branch name, or `--delete`). |
| `--auto` | With `set-head`, follow the remote `HEAD` symref. |
| `--delete` | With `set-head`, remove the local HEAD symref. |
| `set-url <name> <url>` | Set the fetch URL for `<name>`. Use `--push` for `pushurl`. |
| `--push` | With `set-url`, update push URL(s) instead of fetch. |
| `remove <name>` | Remove remote `<name>` and its tracking refs. `--dry-run` previews without writing. |
| `show <name>` | Summarize `<name>` (URLs, HEAD branch, remote branches, pull config). |
| `--no-query` | With `show`, use local remote-tracking refs only; do not contact the remote. |
| `--dry-run` | With `set-url`, `remove`, or `rename`, show the change without writing. |
| `rename <old> <new>` | Rename remote `<old>` to `<new>`. Fails when `<new>` exists or is not a valid remote name. |
| `refs <remote-or-url>` | List refs on the remote (or URL). |
| `--heads` | With `refs`, only `refs/heads/`. |
| `--tags` | With `refs`, only `refs/tags/`. |
| `--sort` | With `refs`, `name` (default) or `version` (`git ls-remote --sort=version:refname`). |
| `--reverse` | With `refs`, reverse `--sort` order. |
| `-n`, `--limit` | With `show` or `refs`, return at most `N` branch or ref lines after sorting. |
| `<prefix>…` | With `refs`, optional ref prefixes (same rules as `git ls-remote`). |

## Examples

```console
$ grit remote add origin https://github.com/ada/project.git
Added remote origin → https://github.com/ada/project.git

$ grit remote
origin	https://github.com/ada/project.git

$ grit remote -v
origin	https://github.com/ada/project.git (fetch)
origin	https://github.com/ada/project.git (push)

$ grit remote set-url origin git@github.com:ada/project.git
Set remote origin fetch URL to git@github.com:ada/project.git

$ grit remote show origin
* remote origin
  Fetch URL: https://github.com/ada/project.git
  Push  URL: https://github.com/ada/project.git
  HEAD branch: main
  Remote branches:
    main tracked
    feature new
  Local branches configured for pull:
    main merges with remote main

$ grit remote rename origin upstream
Renamed remote origin → upstream (3 tracking refs updated)

$ grit remote refs upstream
a1b2c3d4e5f6789012345678901234567890abcd	refs/heads/main
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/remote/schemas/remote/v1.json/index.md) · [remote.add v1](https://grit-scm.com/docs/remote/schemas/remote.add/v1.json/index.md) · [remote.remove v1](https://grit-scm.com/docs/remote/schemas/remote.remove/v1.json/index.md) · [remote.show v1](https://grit-scm.com/docs/remote/schemas/remote.show/v1.json/index.md) · [remote.rename v1](https://grit-scm.com/docs/remote/schemas/remote.rename/v1.json/index.md) · [remote.refs v1](https://grit-scm.com/docs/remote/schemas/remote.refs/v1.json/index.md) (set-url uses the main remote schema)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `action` | string | `list`, `add`, `set_url`, `remove`, `prune`, `set_head`, `show`, `rename`, or `refs`. |
| `remotes` | array | For `list`, each remote with `name` and `url`; with `-v`, also `fetch_url`, `push_url`, and `refspecs`. |
| `name` | string | For `add`, `set_url`, `remove`, or `show`, the remote name. |
| `url` | string | For `add` or `set_url`, the remote URL or path. |
| `fetched` | boolean | For `add`, whether a fetch ran after adding (`--fetch`). |
| `refs_pruned` | array | For `prune`, full ref names deleted or that would be deleted. |
| `target` | string or null | For `set_head`, new symref target, or null when deleted. |
| `previous_target` | string or null | For `set_head`, symref target before the update, if any. |
| `kind` | string | For `set_url`, `fetch` or `push`. |
| `old_url` | string or null | For `set_url`, previous URL for that kind, if any. |
| `refs_deleted` | array | For `remove`, deleted remote-tracking ref names. |
| `branches_untracked` | array | For `remove`, local branch short names whose upstream keys were cleared. |
| `dry_run` | boolean | For `set_url`, `remove`, or `rename`, whether changes were only reported. |
| `fetch_url` | string | For `show`, fetch URL after config rewrite. |
| `push_url` | string | For `show`, push URL (`pushurl` when set). |
| `head_branch` | string or null | For `show`, remote default branch when known. |
| `branches` | array | For `show`, each `{ name, state }` with `state` `tracked`, `new`, or `stale`. |
| `pull` | array | For `show`, each `{ local, merges }` from `branch.*` config. |
| `old` | string | For `rename`, the previous remote name. |
| `new` | string | For `rename`, the new remote name. |
| `refs_renamed` | number | For `rename`, remote-tracking refs renamed. |
| `refspecs_updated` | array | For `rename`, fetch refspec strings rewritten for the new name. |
| `branches_updated` | array | For `rename`, branch short names whose upstream remote was retargeted. |
| `refs` | array | For `refs`, each entry with `name`, `oid`, optional `peeled`, optional `symref_target`. |

Listing remotes:

```json
{
  "action": "list",
  "remotes": [
    {
      "name": "origin",
      "url": "https://github.com/ada/project.git"
    }
  ]
}
```

Adding a remote:

```json
{
  "action": "add",
  "name": "origin",
  "url": "https://github.com/ada/project.git",
  "fetched": false
}
```

Showing a remote:

```json
{
  "action": "show",
  "name": "origin",
  "fetch_url": "https://github.com/ada/project.git",
  "push_url": "https://github.com/ada/project.git",
  "head_branch": "main",
  "branches": [
    { "name": "main", "state": "tracked" },
    { "name": "feature", "state": "new" }
  ],
  "pull": [
    { "local": "main", "merges": "refs/heads/main" }
  ]
}
```

Pruning stale tracking refs:

```json
{
  "action": "prune",
  "name": "origin",
  "refs_pruned": ["refs/remotes/origin/topic"],
  "dry_run": false
}
```

Setting remote HEAD:

```json
{
  "action": "set_head",
  "name": "origin",
  "target": "refs/remotes/origin/main",
  "previous_target": null,
  "dry_run": false
}
```

Setting a URL:

```json
{
  "action": "set_url",
  "name": "origin",
  "kind": "fetch",
  "old_url": "https://github.com/ada/old.git",
  "url": "https://github.com/ada/project.git",
  "dry_run": false
}
```

Removing a remote:

```json
{
  "action": "remove",
  "name": "origin",
  "refs_deleted": ["refs/remotes/origin/HEAD", "refs/remotes/origin/main"],
  "branches_untracked": ["main"],
  "dry_run": false
}
```

Renaming a remote:

```json
{
  "action": "rename",
  "old": "origin",
  "new": "upstream",
  "refs_renamed": 3,
  "refspecs_updated": ["+refs/heads/*:refs/remotes/upstream/*"],
  "branches_updated": ["main"],
  "dry_run": false
}
```

Listing refs:

```json
{
  "action": "refs",
  "refs": [
    {
      "name": "refs/heads/main",
      "oid": "a1b2c3d4e5f6789012345678901234567890abcd",
      "peeled": null,
      "symref_target": null
    }
  ]
}
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/remote/schemas/remote/v1.json/index.md)
Pass `--markdown` for an agent-friendly Markdown table of refs (a “Remote refs” heading, then columns — not JSON). Example shape:

```text
Remote refs

| Ref | Object | Peeled | Symref target |
| --- | --- | --- | --- |
| `refs/heads/main` | `a1b2c3…` | — | — |
| `refs/tags/v1` | `tagoid…` | `commitoid…` | — |
```


## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `128` | `remote refs` could not reach or read the remote ([`remote_unreadable`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[grit fetch](https://grit-scm.com/docs/fetch/index.md), [grit push](https://grit-scm.com/docs/push/index.md), [grit clone](https://grit-scm.com/docs/clone/index.md)

# https://grit-scm.com/docs/fetch/index.md

# grit fetch

> Download new commits, branches and tags from a remote.

## Synopsis

```text
grit fetch [<remote>] [<refspec>…] [--all] [--depth N] [--deepen N] [--unshallow] [--tags] [--no-tags] [--prune] [--no-prune] [--dry-run] [-f] [-q]
```

## Description

Downloads objects and updates refs from a remote. Your working tree and current branch are unchanged; use [`grit merge`](https://grit-scm.com/docs/merge/index.md) or [`grit pull`](https://grit-scm.com/docs/pull/index.md) to integrate fetched commits.

`<remote>` defaults to the current branch's remote (`branch.<name>.remote`, the remote `grit branch -u` and `grit push -u` record), and to `origin` when that is not set, when the branch tracks a local branch (`branch.<name>.remote = .`), or when `HEAD` is detached. It may be a configured remote name, a URL, an scp-style `host:path`, a filesystem path, or a [git bundle](https://git-scm.com/docs/git-bundle) file. Anything else fails with `unknown remote`.

Each `<refspec>` selects what to fetch (`main`, `refs/heads/x:refs/heads/y`, `+refs/…` to force). When no refspecs are given, configured `remote.<name>.fetch` refspecs apply (usually all heads into `refs/remotes/<remote>/…`).

When the source is a **literal path or URL** (not a configured remote), grit does not update `refs/remotes/origin/*` unless you pass refspecs with destinations. With no refspecs, grit fetches the bundle's `HEAD` into [`FETCH_HEAD`](https://git-scm.com/docs/git-fetch#_discussion) (matching Git's anonymous fetch). A bundle whose header lists no `HEAD` — typical of incremental range bundles — fails with a clear ref error instead of reporting "already up to date"; pass an explicit refspec (for example `main:refs/remotes/bundle/main` or `main` to update `FETCH_HEAD` only) to take a listed branch.

Human output lists each local ref with its remote source and old → new oids. Pruned refs show `deleted`; rejected updates are listed and exit **1** (same as [`grit push`](https://grit-scm.com/docs/push/index.md) rejections). When a stale remote-tracking ref blocks another update (for example `origin/gone/x` still exists locally but the remote now has `gone`), grit still applies every ref it can and reports the blocked ref as rejected; the `reason` field suggests `grit fetch --prune` or `grit remote prune <remote>` when pruning would remove the stale ref. With `core.ignorecase`, when the remote advertises two refs that differ only by case, grit stores the first and rejects the second as a loose ref; the `reason` mentions case and suggests `grit init --ref-format=reftable` if you need both spellings locally.

When the fetch received objects, the ref list is followed by the same transfer summary [`grit clone`](https://grit-scm.com/docs/clone/index.md) prints: a `time` bar splitting the run into the network wait before the pack (**handshake**, **negotiate** and the server's **pack prep**, as described for [`grit clone`](https://grit-scm.com/docs/clone/index.md)), receiving, indexing, resolving deltas and finishing; the `data` received off the wire with its average and peak rate; and the `objects` received by type. Local `file://` and plain-path remotes use the same summary shape, with **Enumerating** (reachability walk) and **Copying** (link or pack the send set) instead of network **Receiving**. Nothing extra is printed when the fetch was already up to date. With `--all`, one summary after the last remote covers the whole run.

On a terminal, stderr first shows `Fetching <remote> <url>`, then one live progress line per phase with a throughput graph and, under it, an overall bar with a time-left estimate. Finished phases stay on screen as `✓` lines. When stderr is not a TTY, or with `--json`, `--markdown` or `-q`, no progress is drawn.

By default grit follows tags, fetching every tag (lightweight or annotated) that points into the fetched history. That includes tags on commits, trees and blobs that arrive with the fetch, and tags on trees or blobs you already have. A tag on a commit you already have is followed only when the fetched refs reach that commit; Git also follows it when the commit is unreachable from them. In a partial clone, tag following never downloads missing objects. `--tags` fetches every remote tag, and `--no-tags` disables automatic tags. Tag following costs milliseconds even on large repositories. `remote.<name>.tagOpt` (`--tags` / `--no-tags`) applies when the CLI does not override it.

Default tag following never updates a tag you already have locally, even when the remote retargets it — a plain `grit fetch` stays quiet and exits **0**, matching Git. To refresh moved release tags, use `grit fetch --tags` (reports a rejection until you accept the move) or `grit fetch --tags --force`. A refspec that names tags (`refs/tags/rel:refs/tags/rel2`, `refs/tags/*:refs/tags/*`) is honoured like any other refspec; a leading `+` or `--force` on the fetch forces the update (status `forced`).

`--dry-run` negotiates and reports updates without writing refs, objects, or `FETCH_HEAD`. Human output ends with **Would fetch N update(s) from …** when anything would change, or **Already up to date with …** when nothing would.

`--depth`, `--deepen`, and `--unshallow` match Git’s shallow fetch controls (mutually exclusive). `--depth` truncates history on the first shallow fetch; `--deepen` adds commits relative to an existing shallow clone; `--unshallow` fetches the rest and removes `.git/shallow`. `--unshallow` on a complete repository is a typed error. With default tag following, tags on newly fetched history (including annotated tags) arrive in that same operation; a second fetch is unnecessary. Following tags does not extend the requested branch depth. A shallow source can only supply its available history, so boundaries remain when the source is incomplete. A shallow fetch still offers the server the commits you have (the tips being deepened and your other branches and tags), over every protocol version, so only history the repository lacks is transferred.

In a partial clone, a fetch takes part in the server's `promisor-remote` exchange (protocol v2) the way [`grit clone`](https://grit-scm.com/docs/clone/index.md#large-object-promisors) does: it accepts the advertised large-object promisors that `promisor.acceptFromServer` allows, tells the server so, and applies `promisor.storeFields`. A remote whose `partialclonefilter` is `auto` (a clone made with `--blobs auto`) picks its filter on every fetch from the accepted remotes' advertised `partialCloneFilter`. A fetch that is neither filtered nor from a promisor remote declines every promisor remote (`not_partial`), because it needs every object from the server; that includes an unfiltered fetch from a second, non-promisor remote of a partial clone, whose pack would otherwise be marked promisor although no promisor remote can give its objects back. The human output adds a `promisor` line per advertised remote, for example `promisor  lop accepted · blob:limit=5k`, and `promisor  stored partialCloneFilter for lop` for each stored field.

`-q` / `--quiet` suppresses progress and human output (JSON and markdown are unchanged).

Local fetches reuse the repository's ref store across tracking refs and tags. An up-to-date fetch skips object-copy preparation while still handling pruning, `FETCH_HEAD`, and the remote's default branch. See the [many-ref local fetch measurements](https://grit-scm.com/docs/benchmarks/index.md#local-fetch-with-many-refs).

When `core.logAllRefUpdates` is enabled (grit's default for new repositories), each fetch that moves a remote-tracking branch writes a reflog entry on that ref (`fetch: fast-forward`, `fetch: forced-update`, or `fetch: storing head` for a newly stored tracking ref). [`grit pull`](https://grit-scm.com/docs/pull/index.md) uses the same mechanism with a `pull:` prefix. The initial clone fetch does not create branch tracking reflogs (Git matches this); only `refs/remotes/<remote>/HEAD` gets `clone: from <url>`. Pruning a stale tracking ref removes its reflog file. Tags are not logged unless a reflog already exists or logging is set to `always`.

`--all` fetches every configured remote in config order. Remotes with `remote.<name>.skipFetchAll=true` are skipped. Each remote uses its own `remote.<name>.prune` and `remote.<name>.tagOpt` unless `--prune`, `--no-prune`, `--tags`, or `--no-tags` override on the command line. Failures on one remote do not stop the rest; the command exits **1** if any remote failed or any ref update was rejected. `--all` cannot be combined with `<remote>` or `<refspec>` arguments.

When a fetch is interrupted (`SIGINT`, `SIGTERM`, or `SIGHUP`, including Ctrl+C from a terminal), grit cancels the in-progress transfer, removes any partial pack temp file it was writing, and exits **130** without leaving `tmp_pack_*` or pack install staging directories behind. Stale temp files from a hard kill (`SIGKILL`) are removed later by [`grit gc`](https://grit-scm.com/docs/fetch/gc.md/index.md) once they are older than `gc.pruneExpire`, the same way `git gc` prunes `tmp_pack_*`.

## Options

| Option | Description |
| --- | --- |
| `<remote>` | Remote name, URL, path, or bundle. Defaults to the current branch's remote, else `origin`. |
| `<refspec>…` | What to fetch; short names expand like Git (`main` → `refs/heads/main`). |
| `--tags` | Fetch all tags from the remote. |
| `--no-tags` | Do not fetch tags automatically. |
| `--prune` | Remove stale remote-tracking refs. |
| `--no-prune` | Do not prune, even when config enables it. |
| `--dry-run` | Report updates without writing. |
| `--all` | Fetch all configured remotes (see above). |
| `--depth N` | Shallow fetch: keep at most N commits from each tip. |
| `--deepen N` | Deepen a shallow clone by N commits (relative). |
| `--unshallow` | Fetch full history and drop shallow boundaries. |
| `-f`, `--force` | Force non-fast-forward branch updates and tag moves when combined with `--tags` or a forced refspec. Does not move existing tags on a default fetch. |
| `-q`, `--quiet` | Suppress progress and human stdout/stderr. |

## Examples

```console
$ grit fetch origin main
  refs/remotes/origin/main  ← refs/heads/main  a8e620a → b52cca6
Fetched 1 update from origin.

$ grit fetch
Already up to date with origin.

$ grit fetch origin '+refs/heads/*:refs/remotes/origin/*'
  refs/remotes/origin/ag/bstr-migration  ← refs/heads/ag/bstr-migration  new → 4b88e08
  refs/remotes/origin/ag/changelog  ← refs/heads/ag/changelog  new → f3146f8
  …
  refs/remotes/origin/ag/snafu  ← refs/heads/ag/snafu  new → 7bf7ceb
Fetched 15 updates from origin.

  time      ···································█·▓▒·  1.4s
            · connect 1.3s  █ receiving 0ms  ▓ indexing 13ms  ▒ resolving 22ms  · finish 139ms
  data      201 KiB received
  objects   249 · 35 commits · 82 trees · 132 blobs

$ grit fetch --prune
  refs/remotes/origin/gone1  a1b2c3d → deleted
Fetched 1 update from origin.

$ grit fetch --dry-run --prune
  refs/remotes/origin/gone1  a1b2c3d → deleted
  refs/remotes/origin/feature  ← refs/heads/feature  new → b52cca6
Would fetch 2 updates from origin.
```

On a terminal, with progress on stderr above the summary (here filling in a shallow clone, which moves no refs):

```console
$ grit fetch --unshallow
Fetching origin https://github.com/BurntSushi/ripgrep.git
✓ Receiving  █████████████████████          4.64 MiB         48.1 MiB/s    96ms
✓ Indexing   █████████████████████    13,715 objects   223.6k objects/s    61ms
✓ Resolving  █████████████████████      9,905 deltas    451.8k deltas/s    21ms
Already up to date with origin.

  time      ·····························███·▓▓▒····  1.2s
            · handshake 259ms  · negotiate 584ms  · pack prep 61ms  █ receiving 96ms  ▓ indexing 61ms  ▒ resolving 21ms  · finish 138ms
  data      4.64 MiB received · 48.1 MiB/s avg · 48.1 MiB/s peak
  objects   13,868 · 2,302 commits · 6,319 trees · 4,977 blobs · 270 tags
```

The rates are left out when the pack arrived in a single read, too fast to time. A fetch pack can be *thin*: grit completes it with the delta bases it already has, so `objects` can be a little higher than the `Indexing` count.

Fetch a pull request ref into a local branch:

```console
$ grit fetch origin pull/123/head:pr-123
  refs/heads/pr-123  ← refs/pull/123/head  … → …
Fetched 1 update from origin.
```

## JSON output

Pass `--json` for stable, scripting-friendly output.

### Single remote (default)

Schema: [v1](https://grit-scm.com/docs/fetch/schemas/fetch/v1.json/index.md)

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `remote` | string | Remote that was fetched: its name, or the URL given with any `user:password@` removed. Human and Markdown output show the same value. |
| `dry_run` | boolean | True when `--dry-run` was used. |
| `rejected` | boolean | True when any update was rejected (exit 1). |
| `updates` | array | Per-ref results. Each object has `ref`, `remote_ref`, `status` (`new`, `fast_forward`, `forced`, `pruned`, `rejected`, or `up_to_date`), `old_oid` and `new_oid` (full hex or `null`), and `reason` when `status` is `rejected`. |
| `updated` | number | Count of refs that actually changed. Always **0** when `dry_run` is true (nothing is written); count pending changes by filtering `updates` where `status` is not `up_to_date`. |
| `shallow` | object | When present: `added` and `removed` lists of full hex oids for new/removed `.git/shallow` boundaries. |
| `promisor_remotes` | array | When the server advertised promisor remotes: `name`, `url` (credentials removed), `accepted`, `filter` (advertised `partialCloneFilter` or `null`) and `rejected` (`policy_none`, `unknown_remote`, `url_mismatch`, `field_missing`, `field_mismatch`, `not_partial`, or `null` when accepted). Tokens are never shown. |
| `stored_fields` | array | When `promisor.storeFields` changed config: `remote` and `field` (`partialCloneFilter` or `token`), never the value. |
| `promisor_warnings` | array | Promisor config or advertised values that were ignored: `code` is `unknown_accept_value` (`promisor.acceptFromServer` is not a known policy, so nothing is accepted), `unknown_field` (a `promisor.checkFields` / `promisor.storeFields` entry is not a known field), `invalid_advertised_value` (an advertised field was not stored because its value is invalid) or `unusable_auto_filter` (`--blobs auto` cannot use an accepted remote's filter, such as `tree:0`); `key`, `remote`, `field` and `value` say which, when they apply. A rejected advertised value is never shown. Shown as `promisor  warning: …` lines in the human output and `promisor warning` bullets in `--markdown`. |

Example:

```json
{
  "remote": "origin",
  "dry_run": false,
  "rejected": false,
  "updates": [
    {
      "ref": "refs/remotes/origin/main",
      "remote_ref": "refs/heads/main",
      "status": "fast_forward",
      "old_oid": "a8e620a111111111111111111111111111111111",
      "new_oid": "b52cca6222222222222222222222222222222222"
    }
  ],
  "updated": 1
}
```

Dry run:

```json
{
  "remote": "origin",
  "dry_run": true,
  "rejected": false,
  "updates": [
    {
      "ref": "refs/remotes/origin/main",
      "remote_ref": "refs/heads/main",
      "status": "fast_forward",
      "old_oid": "a8e620a111111111111111111111111111111111",
      "new_oid": "b52cca6222222222222222222222222222222222"
    }
  ],
  "updated": 0
}
```

### `--all`

Schema: [all v1](https://grit-scm.com/docs/fetch/schemas/fetch.all/v1.json/index.md)

When `--all` is used, JSON has no top-level `remote` field. Each entry in `remotes` matches the single-remote shape (`remote`, `updates`, `updated`) plus an optional `error` string when that remote could not be fetched.

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `dry_run` | boolean | True when `--dry-run` was used. |
| `remotes` | array | One object per remote attempted (skipFetchAll remotes omitted). |
| `updated` | number | Total refs changed across all successful remotes. Always **0** when `dry_run` is true. |

Example:

```json
{
  "remote": "origin",
  "updates": [],
  "updated": 0,
  "dry_run": false,
  "rejected": false
}
```

## Markdown output

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output.

Schema: [v1](https://grit-scm.com/docs/fetch/schemas/fetch/v1.json/index.md)

Markdown uses headings, bullet lists, and fenced blocks; pipe characters inside table cells are escaped. See the JSON output section for the stable field contract.




```text
Already up to date with `origin`.
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `128` | Could not reach or read the remote: missing repository, DNS or connection failure, HTTP error status ([`remote_unreadable`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.

An HTTPS remote that wants credentials fails with `kind` `auth_required` (none available) or `auth_rejected` (refused). Credentials come from your credential helper, then an askpass program (`GIT_ASKPASS`, `core.askPass`, `SSH_ASKPASS`), as in Git; save a user name and token for any host with `grit auth <url> --username <user> --token <token>`. See [Credentials](https://grit-scm.com/docs/agents/index.md#credentials-https).


## See also

[grit pull](https://grit-scm.com/docs/pull/index.md), [grit merge](https://grit-scm.com/docs/merge/index.md), [grit remote](https://grit-scm.com/docs/remote/index.md)

# https://grit-scm.com/docs/pull/index.md

# grit pull

> Fetch from the remote and bring the current branch up to date.

## Synopsis

```text
grit pull
grit pull [<remote>] [<refspec>…]
grit pull --ff-only
grit pull --rebase
grit pull --no-rebase
grit pull --autostash
grit pull --check [<remote>] [<refspec>…]
grit pull <branch>                 # in a snapshot checkout
grit pull origin <branch>          # the same
```

## Description

Runs [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) (same shared fetch flags: tags, prune, dry-run, quiet), then merges the fetched upstream into the **current** branch, as [`grit merge`](https://grit-scm.com/docs/merge/index.md) would: a fast-forward when you have no new commits of your own, and a merge commit when both sides do. Pathnames in human, stderr conflict lines, and `--markdown` output use the same quoting rules as [`grit status`](https://grit-scm.com/docs/status/index.md) (see **Description** there). On a branch with no commits yet, it simply takes the remote's.

Positional arguments follow [`grit fetch`](https://grit-scm.com/docs/fetch/index.md): an optional remote (configured name, URL, or path), then optional refspecs. With `grit pull origin feature`, grit fetches that branch and integrates the tip recorded in `FETCH_HEAD`, even when no remote-tracking ref exists yet — the same model as `git pull origin feature`.

The default remote is `branch.<name>.remote`, or `origin`; every mode (`--ff-only`, `--rebase`, `--autostash`, `--check`) fetches from that remote, so a branch tracking `backup/main` pulls from `backup`. With no refspecs, the upstream is `branch.<name>.merge`, or `refs/remotes/<remote>/<branch>`. The remote's `remote.<name>.fetch` refspecs decide which local ref holds each fetched branch. With `branch.<name>.remote = .` the upstream is a local branch, and `grit pull` merges it without fetching.

On a branch with no commits yet, the branch is created at the upstream commit with an `initial pull` reflog entry.

Like `grit merge`, `grit pull` uses the same scoped local-change rules as [`grit switch`](https://grit-scm.com/docs/switch/index.md) and won't run with a detached HEAD (except to refresh a [snapshot checkout](#in-a-snapshot-checkout)). Conflicts follow the same model as `grit merge` and `grit rebase`: the pull stops with conflict markers and an operation in progress (a merge, or a rebase), and the result tells you how to finish it.

The fetch step uses the same terminal progress as [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) and [`grit clone`](https://grit-scm.com/docs/clone/index.md): a `Pulling <remote> <url>` line, then live stderr progress with an overall bar on a TTY in human mode, silent when stderr is piped or when you pass `--json` or `--markdown`. When the fetch received objects, the result line is followed by the same `time`, `data` and `objects` summary rows as `grit fetch`. When you need an explicit fetch refspec or fetch-only flags (`--depth`, `--deepen`, `--unshallow`, `--tags`, `--no-tags`, `--prune`, `--no-prune`, `--dry-run`, `-q`), run [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) first, then integrate with `grit merge` or the pull integration flags below.

Integration mode follows Git's `pull.ff`, `pull.rebase`, and `branch.<name>.rebase` unless overridden on the command line. With rebase, local commits replay onto the fetched upstream tip via the history engine, exactly as [`grit rebase`](https://grit-scm.com/docs/rebase/index.md) does. Rebasing uses the upstream tracking ref's reflog fork point (as `git pull --rebase` does), so commits a teammate dropped with a force-push are not replayed from your older view of the branch. When a commit conflicts, the rebase stops (exit **1**) with conflict markers, unmerged paths and Git-compatible `.git/rebase-merge/` state; the branch still points at its old tip until the rebase finishes. Resolve, `grit add`, then `grit rebase --continue`, or run `grit rebase --skip` / `grit rebase --abort` (`git rebase --continue` / `--abort` work on the same state). The rebase only stops when it can do so without losing work: if staged or unstaged changes exist, or an untracked file sits where the stop would check out a path, the pull refuses with `kind: dirty_worktree` (or the overwrite error) and nothing changes. Use `--autostash` or commit first. `pull.rebase=interactive` is rejected. For a standalone rebase without fetching, use [`grit rebase`](https://grit-scm.com/docs/pull/rebase.md/index.md).

The integration step records the branch's pre-pull tip in `ORIG_HEAD`, the way [`grit merge`](https://grit-scm.com/docs/merge/index.md) and [`grit rebase`](https://grit-scm.com/docs/rebase/index.md) do, so `grit reset --hard ORIG_HEAD` undoes a pull. A branch with no commits yet has no previous tip, so the first pull onto it leaves `ORIG_HEAD` alone.

Integration runs the same hooks as `git pull`: `post-merge 0` after a fast-forward or merge commit (in rebase mode too, when the branch is only behind and simply fast-forwards), and `post-checkout <old tip> <upstream> 1` plus `post-rewrite rebase` after a rebase (see [`grit hooks`](https://grit-scm.com/docs/hooks/index.md)). Before anything is recorded it also runs `pre-merge-commit`, `prepare-commit-msg` and `commit-msg` for a merge commit (as [`grit merge`](https://grit-scm.com/docs/merge/index.md) does), and `pre-rebase <commit>` before a rebase replays commits; a hook that exits non-zero stops the pull.

`--autostash` stashes dirty index/worktree changes (including untracked files) before integrating, then re-applies them afterward. Config `merge.autoStash` / `rebase.autoStash` enables the same behavior by default for merge and rebase pulls respectively. On a branch with no commits yet, autostash is skipped and the upstream tip is checked out instead (same as Git). If re-applying the stash conflicts, the pull integration is kept, the stash entry remains on `refs/stash`, and the result is `autostash_conflict` (exit **1**). When a rebase pull stops on conflicts, the stash is not applied over the conflict markers: it stays on `refs/stash` (reported as `autostash`) so you can `grit stash pop` once the rebase is finished or aborted. When a hook refuses the merge commit, the merge stays in progress and the stash waits in `MERGE_AUTOSTASH`, as with Git: your edits stay out of the merge, and `grit merge --continue` (or `grit commit`) or `grit merge --abort` puts them back.

### In a snapshot checkout

In a [snapshot checkout](https://grit-scm.com/docs/checkout/index.md), `grit pull` with no refspecs **refreshes** the checkout (so does `grit pull origin`, or a pull naming whatever remote has the checkout's server URL now):

1. It asks the server for a snapshot of the newest commit of the target branch the checkout was made from (the server keeps following that branch even when its `HEAD` moves to another), made on top of the checkout's last snapshot.
2. It gives the current branch's commits made with plain `git` a change id, as [`grit checkin`](https://grit-scm.com/docs/checkin/index.md#change-ids) does, so the rebase below keeps an id the server can match them by (`Gave 1 commit made with git a change id.`; not with `--check`).
3. It fetches that snapshot into `origin/<target>` (`refs/remotes/origin/<target>`) from the server the checkout came from, with an explicit refspec and no tags, whatever `origin` is configured as now. Only what changed in the checkout's paths comes down. The checkout records the new snapshot only once it has arrived and is the one the server described.
4. It brings the current branch onto it: a rebase unless `--ff-only` or `--no-rebase` says otherwise. Commits already merged into the target drop out. Commits of a branch this checkout checked in and [integrated](https://grit-scm.com/docs/integrate/index.md) into the branch it follows are never replayed, since the snapshot already has their result (replaying them one by one could conflict with themselves): a branch with nothing above them moves to the new snapshot, keeping uncommitted and untracked changes as `git reset --keep` does (`landed`), and one with commits of its own above them rebases only those, as `git rebase --onto origin/<target> <integrated tip>` would. When the rebase hits a conflict, it **stops** in a resumable rebase, as [`grit rebase`](https://grit-scm.com/docs/rebase/index.md) does: resolve the files, `grit add` them, then `grit rebase --continue` (or `grit rebase --abort` to put the branch back on the older snapshot). Until then, another `grit pull` refuses to start. When the index or worktree has changes of their own, the rebase can't stop there, so nothing changes; commit or stash them and pull again.
5. A local branch named after the target (a `main` you made with `grit branch main origin/main`) that has no commits of its own follows to the new snapshot, and so does any other branch whose commits have all been integrated. Every other branch with commits of its own that still builds on an older snapshot is named, with how to bring it up: `grit switch <branch>`, then `grit pull` (which leaves out its integrated commits, too).

With `HEAD` detached, the refresh still fetches the new snapshot into `origin/<target>` and leaves `HEAD` where it is. It works the same from any worktree of the checkout.

The first lines say how far the target moved and what changed in the checkout's paths (as `git diff --shortstat` counts it), or that it hasn't moved:

```console
$ grit pull
main moved 4f06b71 → 3182ed4; new snapshot 39dfeba at origin/main
  1 file changed, 1 insertion(+), 1 deletion(-) in this checkout's paths
Rebased onto origin/main (2b87e20)
main follows to 39dfeba
side still builds on an older snapshot; run `grit switch side`, then `grit pull`
```

```console
$ grit pull
main moved e8d5aa5 → f3dbd6f; new snapshot 552fbc6 at origin/main
  1 file changed, 1 insertion(+), 1 deletion(-) in this checkout's paths
CONFLICT (both_modified): src/a.rs
Rebasing onto origin/main stopped on a conflict; the rebase is in progress.
Resolve the conflicts, `grit add` the files, then run `grit rebase --continue`; or run `grit rebase --abort` to put the branch back where it was.
$ grit add src/a.rs && grit rebase --continue
Rebased 1 commit(s)
```

### A server branch in a snapshot checkout

In a snapshot checkout, `grit pull <branch>` (or `grit pull origin <branch>`, naming the checkout's server) brings your `<branch>` onto the server's branch of that name, as your checkout sees it. That is how you pick up a teammate's branch, or work on one with someone whose checkout has other paths. `<branch>` must not be the name of a configured remote (then it is an ordinary pull from that remote); naming the branch the checkout follows (`grit pull main`) is just a refresh.

1. The server **shows you its branch**: each of its commits that the target lacks is rewritten with its tree cut down to your checkout's paths, on top of your newest snapshot under it, at `refs/checkouts/<id>/in/heads/<branch>` (see [`grit serve`](https://grit-scm.com/docs/serve/index.md#snapshot-checkouts)). Author, date and message are kept. A commit that only touched paths you don't have shows up as an empty commit, so the history still lines up with the server's. Your own commits that the server's are grafts of come back as they are, and files outside your paths that they added stay in the commits above them while they are still files there (one the server turned into a directory is dropped). Another checkout's commit is never shown to you as it is when it has files outside your paths, even on the same snapshot. On a server whose file system can't tell names apart by case, a name that differs from the server's branch only in case is that branch, and you get it under the server's spelling (`grit pull feature` creates `Feature`), so its check-ins aren't refused as a case conflict.
2. It **fetches** that into `origin/<branch>` (`refs/remotes/origin/<branch>`) from the server the checkout came from, with no tags, and checks that what arrived is what the server described.
3. It gives the branch's commits made with plain `git` a change id, as `grit checkin` does.
4. It **brings your branch onto it**:
   - a branch you don't have yet is **created** at the server's (`created`; switch to it with `grit switch <branch>`);
   - a branch that has every commit already is left alone (`up_to_date`: `feature already has them.`);
   - one with nothing of its own on top moves to it (`fast_forward`), keeping uncommitted changes when it is the current branch;
   - otherwise **your own commits are rebased onto it** (`rebased`): those above the newer of where your branch meets the server's and the newest snapshot it builds on. Copies of the server's commits that your branch holds (made when a refresh rebased it onto a newer snapshot, say) are left out, recognized by change id or by patch, so only your work moves. A rebase that conflicts **stops** for you to resolve, then `grit rebase --continue` (or `--abort`), as a refresh's does (`rebase_stopped`). When the branch is not the current one, you are switched to it first, as `git rebase <upstream> <branch>` does, and switched back when the rebase can't go ahead (local changes it would overwrite, say). A branch that another worktree has checked out, or is rebasing or bisecting, is refused. A rebase of yours goes through cleanly when the server's branch turned a directory into a file (or the other way round) and your commits never touched it.

Checking the branch in afterwards is a fast-forward on top of the server's: work you build on its commits is grafted onto the real commits they stand for (see [`grit checkin`](https://grit-scm.com/docs/checkin/index.md#sharing-a-branch)). It always rebases, so `--ff-only`, `--no-rebase`, `--autostash` and `--dry-run` are refused; `--check` says what it would do to the branch without changing it (the server still shows the branch, and it is fetched).

```console
$ grit pull feature
The server's feature is at bcd6c48: 2 commits on this checkout's snapshots, at origin/feature (19a3116).
Rebased feature onto origin/feature (4c2d9e1), 1 commit of yours on top.
feature builds on the server's now; `grit checkin feature` sends it.
$ grit pull feature
The server's feature is at bcd6c48: 2 commits on this checkout's snapshots, at origin/feature (19a3116).
feature already has them.
$ grit pull theirs
The server's theirs is at 6f1c2d3: 1 commit on this checkout's snapshots, at origin/theirs (a2b3c4d).
Created theirs at a2b3c4d, the server's; `grit switch theirs` to work on it.
```

The server refuses a branch it doesn't have, one the target already has every commit of, and one that builds on a commit from before your checkout's first snapshot (its author can rebase it onto a newer target first). A local branch by that name that shares nothing with the server's is refused too; rename it to get the server's.

A merge commit a `--no-rebase` refresh makes checks in as a merge whose result keeps the target's changes outside your paths (see [`grit checkin`](https://grit-scm.com/docs/checkin/index.md)). A later rebasing refresh drops the merge commits a `--no-rebase` refresh made and replays your own commits onto the new snapshot.

`--dry-run` asks the server where the target is now and says whether a refresh would move, without the server making a snapshot, and without fetching or changing anything here. `--check` refreshes for real (the server makes the snapshot and it is fetched into `origin/<target>`), then reports what bringing the branch onto it would do, without changing the branch, the index or the worktree.

`--check` fetches (always for real — not a dry run) and reports whether the branch could fast-forward or is already up to date, without changing `HEAD`, the index, the worktree, or reflogs. In rebase mode it also predicts whether the replay would stop on conflicts (`would` is `conflicts`). It cannot be combined with `--autostash` or integration mode overrides (`--ff-only`, `--rebase`, `--no-rebase`).

## Options

| Option | Description |
| --- | --- |
| `<remote>` | Remote to pull from (same rules as [`grit fetch`](https://grit-scm.com/docs/fetch/index.md); defaults to the branch remote or `origin`). In a snapshot checkout, a name that is not a configured remote is a branch: `grit pull <branch>` brings it onto the [server's branch](#a-server-branch-in-a-snapshot-checkout). |
| `<refspec>…` | Refspecs to fetch before integrating (same as fetch); integration uses `FETCH_HEAD` when refspecs are given. |
| `--tags` / `--no-tags` | Tag fetching policy (same as [`grit fetch`](https://grit-scm.com/docs/fetch/index.md)). |
| `--all` | Fetch all configured remotes before integrating (same as [`grit fetch`](https://grit-scm.com/docs/fetch/index.md); cannot combine with `<remote>` or refspecs). |
| `--depth N` | Shallow fetch: keep at most N commits from each tip (same as fetch). |
| `--deepen N` | Deepen a shallow clone by N commits (same as fetch). |
| `--unshallow` | Fetch full history and drop shallow boundaries (same as fetch). |
| `--prune` / `--no-prune` | Prune stale remote-tracking refs after fetch. |
| `--dry-run` | Fetch dry-run only: report ref updates without writing refs or objects; integration is skipped. |
| `-f`, `--force` | Same as [`grit fetch --force`](https://grit-scm.com/docs/fetch/index.md) (tag clobber with `--tags`, forced refspecs). |
| `-q`, `--quiet` | Suppress fetch progress (human mode). |
| `--ff-only` | Refuse to create a merge commit when the current branch has local commits; exit with `refused_not_ff` in `--json` output instead. Honors `pull.ff=only` when set. Conflicts with `--rebase`, `--no-rebase`, and `--check`. |
| `--rebase` | Rebase local commits onto the upstream tip, overriding `pull.rebase=false`. As with `git pull --rebase`, merge commits on the branch (such as an earlier merge pull) are dropped, and the branch's own commits are replayed one after another on top of the upstream tip, skipping any whose change is already upstream. Conflicts with `--ff-only`, `--no-rebase`, and `--check`. |
| `--no-rebase` | After fetch, merge the upstream with a merge commit when a fast-forward is not possible (the default when `pull.rebase` is not true). Conflicts with `--ff-only`, `--rebase`, and `--check`. |
| `--autostash` | Stash before integrating and re-apply after (see `merge.autoStash` / `rebase.autoStash`). Conflicts with `--check`. |
| `--check` | Fetch and report whether a fast-forward or up-to-date result is possible; exit **0** when yes, **1** when a merge or rebase would be required. Conflicts with `--autostash` and mode overrides. |

All [global options](https://grit-scm.com/docs/global-options/index.md) apply as well.

## Examples

```console
$ grit pull
Fast-forwarded origin/main → 9119bc7

  time      ███·························              8ms
            █ copying 0ms  · finish 5ms
  data      318 B received
  objects   3 · 1 commit · 1 tree · 1 blob

$ grit pull origin feature
Fetched 1 update from origin.
Fast-forwarded origin/feature → d4e5f6a

$ grit pull --check
Would fast-forward (0 ahead, 2 behind). Fast-forward possible.

$ grit pull --autostash
Merged origin/main into the current branch (acd1d4b)
```

When a rebase pull conflicts:

```console
$ grit pull --rebase
CONFLICT (both_modified): f

Rebase stopped on conflicts; fix them and run `grit rebase --continue`, or `grit rebase --abort` / `grit rebase --skip`.
$ grit status
Rebasing main onto 3f6a904
…
$ grit add f
$ grit rebase --continue
Rebased 1 commit(s)
  commit 1e64458 → e79b420 (local)
  refs/heads/main 1e64458 → e79b420
```

When the branch has no upstream yet:

```console
$ grit pull
error: no upstream configured for branch main
hint: pull a branch by name with `grit pull origin main`, or publish this one and track it with `grit push -u origin main`
```

While a rebase is paused (for example after a conflict), `grit pull` refuses with the same guidance as [`grit switch`](https://grit-scm.com/docs/switch/index.md):

```console
$ grit pull
error: cannot pull while a rebase is in progress; finish it with `grit rebase --continue` or cancel it with `grit rebase --abort`
```

When local edits on a path the pull would update would be overwritten (fast-forward, merge, or rebase):

```console
$ grit pull
error: local changes would be overwritten by merge
  f
hint: commit them with `grit commit`, or set them aside with `grit stash`, then try again
```

On overwrite refusal with `--json`, stdout is a single object with `kind` `would_overwrite` and `would_overwrite.reason` (`local_changes` or `untracked`) plus a sorted `paths` array, and a `hint` — the same shape as [`grit merge`](https://grit-scm.com/docs/merge/index.md) and [`grit switch`](https://grit-scm.com/docs/switch/index.md). For example `{"error":"local changes would be overwritten by merge","hint":"…","kind":"would_overwrite","would_overwrite":{"paths":["f"],"reason":"local_changes"}}`. See the [error schema](https://grit-scm.com/docs/pull/schemas/error/v1.json/index.md).

With `--json` that is `{"error":"no upstream configured for branch main","hint":"…","kind":"branch_no_upstream"}`. A missing remote is `kind` `remote_not_found` and an authentication failure `auth_required` or `auth_rejected`, each with a `hint` (see [Exit codes](https://grit-scm.com/docs/exit-codes/index.md)).

## JSON output

Schema: [v2](https://grit-scm.com/docs/pull/schemas/pull/v2.json/index.md) · [v1](https://grit-scm.com/docs/pull/schemas/pull/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

Exit codes (also apply to default human output): **0** on success (`up_to_date`, `fast_forward`, `merged`, `rebased`, `set_upstream`, `detached`, `landed`, or `created`) and on `--check` when `check.fast_forward_possible` is true; **128** when `--ff-only` (or `pull.ff=only`) refuses diverged history (`refused_not_ff`; the branch is unchanged), as with `grit merge --ff-only`; **1** when integration stops with conflicts (`conflicts`, with `operation` `merge` or `rebase` in progress), a snapshot checkout's refresh stops in a rebase (`rebase_stopped`), `--check` when a merge or rebase would be required, or `autostash_conflict`.

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `result` | string | `up_to_date`, `fast_forward`, `merged`, `rebased`, `refused_not_ff`, `conflicts`, `set_upstream`, `autostash_conflict`, `rebase_stopped` (a snapshot checkout's rebase stopped on a conflict and is in progress), `detached` (a snapshot checkout refreshed with `HEAD` detached: only `origin/<target>` moved), `landed` (in a snapshot checkout, every commit of the branch was integrated, so it moved to the new snapshot, keeping uncommitted changes), or `created` (`grit pull <branch>` in a snapshot checkout made the branch at the server's). |
| `branch` | string | Remote branch label that was integrated (or checked). |
| `oid` | string or null | Commit the current branch points at after the pull, when applicable (absent when a rebase stopped). |
| `change_id` | string or null | Stored `change-id` on `oid` when present. |
| `upstream` | string or null | For `set_upstream`, the remote-tracking branch that was adopted. |
| `conflicts` | array of strings or null | Path names when `result` is `conflicts` or `rebase_stopped` (legacy list). |
| `conflict_details` | array or null | Structured conflict items when `result` is `conflicts` or `rebase_stopped`: `path`, a [conflict `kind`](https://grit-scm.com/docs/status/index.md#conflict-kinds) (the same names `grit status` uses, plus `rename_rename` and the `directory_rename_*` kinds), and for merges a `summary`. |
| `operation` | string or null | When `result` is `conflicts` or `rebase_stopped`: the operation left in progress, `merge` or `rebase`. |
| `commit` | string or null | When `operation` is `rebase`: the local commit that could not be replayed. |
| `next_steps` | array of strings or null | When `result` is `conflicts`: ordered `grit` commands to finish (for a rebase, ending in `grit rebase --continue`). |
| `alternatives` | array of strings or null | When `result` is `conflicts`: other ways out (`grit merge --abort`, or `grit rebase --abort` / `grit rebase --skip`). |
| `autostash` | string or null | Autostash commit kept on `refs/stash` because a rebase stopped or re-applying it conflicted. |
| `ahead` | integer or null | Local-only commits when `result` is `refused_not_ff` or with `--check`. |
| `behind` | integer or null | Upstream-only commits when `result` is `refused_not_ff` or with `--check`. |
| `check` | object or null | Present with `--check`: `ahead`, `behind`, `fast_forward_possible`, and `would` (same result strings as `result`). |
| `refresh` | object or omitted | In a snapshot checkout, the refresh (fields below). |
| `refresh.target` | string | The server's target branch the checkout follows. |
| `refresh.upstream_ref` | string | The local ref holding the newest snapshot, `refs/remotes/origin/<target>`. |
| `refresh.base` | string | The real commit the newest snapshot stands for. With `--dry-run`, where the target is now. |
| `refresh.snapshot` | string | The newest snapshot commit, now at `upstream_ref`. With `--dry-run`, the checkout's snapshot as it is. |
| `refresh.previous_base` | string or null | The real commit the checkout's previous snapshot stood for. |
| `refresh.previous_snapshot` | string or null | The checkout's previous snapshot. |
| `refresh.moved` | boolean | Whether the target moved since the checkout's last snapshot. |
| `refresh.changes` | object or null | What changed in the checkout's paths between the two snapshots: `files`, `insertions`, `deletions`; null when the target didn't move. |
| `refresh.dry_run` | boolean | True with `--dry-run`: nothing was fetched or changed, and the server made no snapshot. |
| `refresh.followed` | array | Local branches with no commits of their own that moved along (the one named after the target, and any whose commits were all integrated): `name`, `from`, `to`. |
| `refresh.behind` | array | Other branches with commits of their own still on an older snapshot: `name`, `tip`. |
| `refresh.gave_change_ids` | integer | Commits made with plain `git` on the current branch that were given a change id before the rebase (the branch was rewritten); `0` when none needed one. |
| `server_branch` | object or omitted | In a snapshot checkout, `grit pull <branch>`: the server's branch and what your branch did (fields below). `branch` is then `origin/<branch>` and `oid` where your branch is now. |
| `server_branch.name` | string | The branch, as the server spells it (which can differ in case from the name you gave, on a server that ignores case). |
| `server_branch.upstream_ref` | string | The local ref holding the server's branch as the checkout sees it, `refs/remotes/origin/<branch>`. |
| `server_branch.tip` | string | Where the server's branch is, on its real history. |
| `server_branch.projected` | string | What the checkout sees of it, now at `upstream_ref`. |
| `server_branch.commits` | integer | The server branch's commits the target lacks, all shown to the checkout. |
| `server_branch.made` | integer | How many of them were made afresh for this checkout. |
| `server_branch.reused` | integer | How many were commits that were there already: checkout commits on the same snapshots that the server's are grafts of (your own among them), and what you were shown before. |
| `server_branch.previous` | string or null | Where your branch was; null when it was `created`. |
| `server_branch.own` | integer | Your commits replayed onto the server's (`rebased`), without the copies of the server's that were left out. |
| `server_branch.switched` | boolean | Whether `HEAD` was moved onto the branch to rebase it. |
| `server_branch.was_on` | string or null | The branch `HEAD` was on before. |
| `server_branch.gave_change_ids` | integer | Commits made with plain `git` on the branch that were given a change id first. |

Example:

```json
{
  "result": "fast_forward",
  "branch": "origin/main",
  "oid": "b52cca65378cf17309f0b1f917c6dc4fdd9256f2"
}
```

A rebase pull that stopped on conflicts:

```json
{
  "result": "conflicts",
  "branch": "origin/main",
  "conflicts": ["f"],
  "conflict_details": [{ "path": "f", "kind": "both_modified" }],
  "operation": "rebase",
  "commit": "1e644589243fb885b773ec4d697b779000495741",
  "next_steps": ["grit diff", "grit add .", "grit rebase --continue"],
  "alternatives": ["grit rebase --abort", "grit rebase --skip"]
}
```

In a snapshot checkout:

```json
{
  "result": "rebased",
  "branch": "origin/main",
  "oid": "2b87e20c6d1f0a9e8b7c6d5e4f3a2b1c0d9e8f7a",
  "refresh": {
    "target": "main",
    "upstream_ref": "refs/remotes/origin/main",
    "base": "3182ed489b694ae64834b5f6648079c4f30c5e64",
    "snapshot": "39dfeba2cfa4b1d0e9f8a7b6c5d4e3f2a1b0c9d8",
    "previous_base": "4f06b71eca1af2057ee312b06eecac8f40c15b00",
    "previous_snapshot": "5c892b5783dbdeb57f7228eb6a13ffb2fa17d832",
    "moved": true,
    "changes": { "files": 1, "insertions": 1, "deletions": 1 },
    "dry_run": false,
    "followed": [
      {
        "name": "main",
        "from": "5c892b5783dbdeb57f7228eb6a13ffb2fa17d832",
        "to": "39dfeba2cfa4b1d0e9f8a7b6c5d4e3f2a1b0c9d8"
      }
    ],
    "behind": [
      { "name": "side", "tip": "8e2d26b0a1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6" }
    ],
    "gave_change_ids": 0
  }
}
```

`grit pull feature` in a snapshot checkout, from another branch:

```json
{
  "result": "rebased",
  "branch": "origin/feature",
  "oid": "4c2d9e1b7a6f5e4d3c2b1a0f9e8d7c6b5a4f3e2d",
  "server_branch": {
    "name": "feature",
    "upstream_ref": "refs/remotes/origin/feature",
    "tip": "bcd6c48a1f2e3d4c5b6a79881726354a5b6c7d8e",
    "projected": "19a3116f0e9d8c7b6a5f4e3d2c1b0a9f8e7d6c5b",
    "commits": 2,
    "made": 1,
    "reused": 1,
    "previous": "8e2d26b0a1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6",
    "own": 1,
    "switched": true,
    "was_on": "alice/elm-orchid",
    "gave_change_ids": 1
  }
}
```

With `--check`:

```json
{
  "result": "fast_forward",
  "branch": "origin/main",
  "ahead": 0,
  "behind": 2,
  "check": {
    "ahead": 0,
    "behind": 2,
    "fast_forward_possible": true,
    "would": "fast_forward"
  }
}
```

## Markdown output

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output.

Schema: [v2](https://grit-scm.com/docs/pull/schemas/pull/v2.json/index.md) · [v1](https://grit-scm.com/docs/pull/schemas/pull/v1.json/index.md)

Markdown uses headings, bullet lists, and fenced blocks; pipe characters inside table cells are escaped. See the JSON output section for the stable field contract.



```text
## Pull

- Fast-forwarded **`origin/main`** → `d0f5bdf`
```

In a snapshot checkout, the refresh comes first, and branches it moved or left behind follow the result:

```text
## Pull

- Refresh: **`main`** moved `4f06b71` → `3182ed4` · new snapshot `39dfeba` at `refs/remotes/origin/main` · 1 file changed, 1 insertion(+), 1 deletion(-) in this checkout's paths
- Rebased onto **`origin/main`** · `2b87e20`
- `main` follows to `39dfeba`
- `side` still builds on an older snapshot → `grit switch side`, then `grit pull`
```

`grit pull <branch>` in a snapshot checkout names the server's branch first:

```text
## Pull

- Change ids: gave 1 commit made with git a change id
- Server branch: **`feature`** at `bcd6c48` · 2 commits on this checkout's snapshots · at `refs/remotes/origin/feature` (`19a3116`)
- Rebased **`feature`** onto **`origin/feature`** · `4c2d9e1` · 1 commit of yours on top → `grit checkin feature` sends it
- Now on `feature` (was `alice/elm-orchid`)
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success (`up_to_date`, `fast_forward`, `merged`, `rebased`, `set_upstream`, `detached`, `landed`, `created`) or `--check` when fast-forward is possible. |
| `1` | Conflicts, refused merge/rebase, a snapshot checkout's rebase stopped in progress (`rebase_stopped`), a refresh refused while a rebase or merge is in progress, `--check` when integration would be required, `autostash_conflict`, or a server branch `grit pull <branch>` can't take (the server has none, or it is already on the target or older than the checkout's first snapshot). |
| `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `128` | `--ff-only` or `pull.ff=only` when history diverged ([`refused_not_ff`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `128` | The fetch could not reach or read the remote ([`remote_unreadable`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md).


## See also

[grit fetch](https://grit-scm.com/docs/fetch/index.md), [grit merge](https://grit-scm.com/docs/merge/index.md), [grit push](https://grit-scm.com/docs/push/index.md)

# https://grit-scm.com/docs/push/index.md

# grit push

> Publish branches, tags, or explicit refspecs to a remote.

## Synopsis

```text
grit push [<remote>] [<refspec>...]
grit push <owner>/<project> <refspec>...
grit push --tags
grit push [<remote>] --delete <ref>...
grit push --dry-run
grit push --force-with-lease[=<rev>]
grit push --force
grit push -u [--set-upstream]
grit push --atomic
grit push -o <option> [--push-option <option>]
grit push --follow-tags
grit push --all
grit push --mirror
grit push --prune
grit push -q [--quiet]
grit push --remote <name>   # hidden alias for one release
```

## Description

Pushes refs to a remote over SSH, smart HTTP, or the `file://` transport. With no refspecs, grit pushes the current branch using the same remote-selection rules as Git (`branch.<name>.pushRemote`, `remote.pushDefault`, `branch.<name>.remote`, then `origin`) and applies `remote.<name>.push` refspecs when configured.

When you pass refspecs, the optional `<remote>` may be a configured remote name, a URL, an scp-style `host:path`, or a filesystem path (including relative paths such as `../bare`), the same as [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) and [`grit pull`](https://grit-scm.com/docs/pull/index.md). A lone positional that is not one of those is still a refspec pushed to the default remote. With several positionals, the first must name a remote, URL, or path; anything else fails with `unknown remote`. A push to a URL or filesystem path (such as `C:\t\remote.git` or `../bare`) creates and updates no remote-tracking refs, as with Git; only a configured remote's `refs/remotes/<name>/…` refs follow the push.

A remote written as `<owner>/<project>` and followed by at least one refspec is a repository on the default grit host: `grit push me/app main` pushes to `https://code.gitbutler.com/me/app.git`, or to that path under `$GRIT_DEFAULT_HOST` when it is set. A configured remote with the same name takes precedence. After a push like this from a repository with no remotes yet, grit saves the URL as `origin`, so later `grit push` and `grit fetch` go there. A lone `<owner>/<project>` argument is still a refspec, so `grit push topic/x` pushes a branch to the default remote.

Incremental SSH and HTTP pushes stop exploring advertised commit history once the new commit frontier is exhausted. A one-commit push does not need to walk every advertised branch and tag back to its root. Annotated tags targeting blobs or trees may be advertised alongside commit refs without preventing a push.

On the remote, `receive.denyNonFastForwards`, `receive.denyDeletes`, and `receive.denyCurrentBranch` are enforced for every transport, including local-path remotes (not only [`grit receive-pack`](https://grit-scm.com/docs/receive-pack/index.md) over HTTP).

From a shallow clone, grit announces each shallow boundary in the push command stream (like Git) and sends only the reachable commits. When the remote does not already have the history below those boundaries, the remote must set `receive.shallowUpdate=true` or the update is refused with `shallow update not allowed`; see [`grit receive-pack`](https://grit-scm.com/docs/receive-pack/index.md).

A push to a local path or `file://` URL runs the remote repository's `pre-receive`, `update`, `post-receive` and `post-update` hooks just as [`grit receive-pack`](https://grit-scm.com/docs/receive-pack/index.md) and Git do: the pushed objects wait in a quarantine that `pre-receive` can read, a non-zero `pre-receive` refuses every update (`pre-receive hook declined`) and keeps the objects out of the repository, a non-zero `update` refuses its own ref (`hook declined`), and `post-receive` and `post-update` run after the refs are written. Hook output is reported like any remote's messages. `--dry-run` runs none of these hooks, as with Git.

Explicit refspecs follow Git push rules: any revision on the left (`HEAD`, tags, branches), optional `+` for force, `:dst` to delete, and a bare branch name DWIMs to the matching local ref (then through configured push refspecs when present). Wildcard refspecs such as `refs/heads/*:refs/heads/*` or `refs/remotes/origin/*:refs/heads/*` expand against local refs the same way as `remote.<name>.push` entries in config.

`--all` pushes every local branch (`refs/heads/*:refs/heads/*`), including branches the remote does not have yet. `--mirror` pushes all refs under `refs/*`, forces updates, and deletes remote refs under `refs/` with no local counterpart (it implies `--prune` and force). `--prune` deletes stale refs only in the destination namespace of a wildcard or matching refspec (for example with `--all` or `refs/heads/*:refs/heads/*`, including `refs/heads/*:refs/tmp/*`). Pushing a single branch with `--prune` does not remove other remote branches. `--all`, `--mirror`, and `--delete` cannot be combined with each other or with positional refspecs.

`--dry-run` negotiates with the remote and reports what would change without updating refs or sending objects.

With `--tags`, pushes every local tag under `refs/tags/`.

With `--delete`, every positional after the remote names a remote branch or tag to delete (short names map like Git), and nothing is pushed. All of them are deleted in one push, with one result per ref. They must be plain ref names: a `src:dst` refspec next to `--delete` is an error and nothing is sent, as is `--delete` with no ref. To publish one ref and delete another, run two pushes or use a `:dst` refspec without `--delete` (`grit push origin HEAD:release :old`). `--delete` cannot be combined with `--tags`.

`--force-with-lease` updates a remote ref only when it still matches the local remote-tracking ref mapped from the push destination (or when the ref is absent if there is no tracking ref). Use `--force-with-lease=<rev>` when pushing exactly one ref to compare against a specific commit. `--force` overwrites the remote ref unconditionally. The two flags cannot be combined.

A branch you [share](https://grit-scm.com/docs/share/index.md) (`branch.<name>.shared` is `true`) is pushed with `--force-with-lease` without your asking: your head of it is yours alone, so replacing it after an amend or rebase is safe, as long as the server's head is still the one you last fetched. After the push, grit fetches the other members' heads: one that diverged from yours but goes together with it without losing anything is combined with your branch here and pushed again (`combined` in `--json`); one that needs a decision is reported with its options, and the push exits `3`.

`-u` / `--set-upstream` writes `branch.<name>.remote` and `branch.<name>.merge` for each successfully pushed branch (skipped with `--dry-run`).

`--atomic` requires every ref update in the push to succeed or none are applied, including when a remote update hook rejects one ref. Over SSH, `git://`, and smart HTTP, the server must advertise the `atomic` capability. If it does not, grit fails before sending ref updates or objects; it never falls back to a non-atomic push. This capability check also applies to `--dry-run`.

`-o` / `--push-option` sends server-side push options (for example `ci.skip`), which the remote's `pre-receive` and `post-receive` hooks see as `GIT_PUSH_OPTION_COUNT` and `GIT_PUSH_OPTION_<n>`. The remote must accept them: a server advertises the `push-options` capability, and a local-path or `file://` remote must set `receive.advertisePushOptions`. Otherwise the push fails before anything is sent, `--dry-run` included.

`--follow-tags` pushes annotated tags that point to commits reachable from the refs being pushed (lightweight tags and unreachable annotated tags are skipped). The config key `push.followTags` enables the same behavior by default.

In human output, messages the remote sends while it processes the push (hook output, CI links, policy text) are shown on stderr as `remote: …` lines, including when stderr is not a terminal. `-q` / `--quiet` hides them and the human summary, so a successful push prints nothing; a rejected push is still reported and exits `1`. With `--json` or `--markdown`, the same lines appear in `remote_messages` (omitted when empty).

On a TTY, grit draws live progress on stderr while it builds and streams the pack (enumerating objects, then writing/compressing), then prints a short time/data summary after the ref results when anything was sent — the same style as [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) and [`grit pull`](https://grit-scm.com/docs/pull/index.md). `--json` and `--markdown` omit the live lines and summary; phase timings are not exported in JSON today.

Before anything is sent, grit runs the repository's `pre-push` hook (see [`grit hooks`](https://grit-scm.com/docs/hooks/index.md)) once the remote's current refs are known, on every transport and with `--dry-run` too. The hook gets the remote name (or the URL, for an unnamed remote) and the push URL as arguments, and one line per ref update on stdin, `<local ref> <local oid> <remote ref> <remote oid>`, in Git's format: `(delete)` and a zero object id for deletions, a zero remote object id for new refs, and no line for refs that are up to date or already rejected. If the hook exits non-zero, the push stops, the remote is left untouched and grit exits `1`. The hook's stdout is sent to stderr so `--json` and `--markdown` output stays clean. `--no-verify` skips the hook.

### Large pushes

When a smart-HTTP server advertises a resumable push endpoint (the `pushBundle` capability, as [`grit serve`](https://grit-scm.com/docs/serve/index.md) does) and the pack to send is larger than 16 MiB, grit writes the pack as a bundle and uploads it with the [TUS](https://tus.io/protocols/resumable-upload) resumable-upload protocol instead of one long request, then asks the server to apply the ref updates. The result is reported like any other push. A dropped connection is retried from the server's offset, and an interrupted push keeps its bundle and upload in `.git/grit/push-bundles/`: run the same `grit push` again and it skips building the pack and sends only the rest.

```text
↻ Resuming push bundle upload at 12.0 MiB of 29.6 MiB (41%)  example.com/demo/push/97d00bc69d6359be08d3a13753f95d2a
  ✓ push bundle 29.6 MiB in 3.4s · 5.20 MiB/s · resumed at 12.0 MiB
```

Set `push.bundleThreshold` (bytes, with optional `k`, `m` or `g`) to change the size at which this starts.

When a push is interrupted (`SIGINT`, `SIGTERM`, or `SIGHUP`, including Ctrl+C from a terminal), grit cancels the in-progress transfer, removes any partial receive quarantine or `tmp_pack_*` file it was writing on the remote, and exits **130** without updating remote refs. Stale temp files from a hard kill (`SIGKILL`) are removed later by [`grit gc`](https://grit-scm.com/docs/push/gc.md/index.md) once they are older than `gc.pruneExpire`, the same way `git gc` prunes abandoned quarantine directories.

For GitHub over HTTPS, if a push fails because you aren't signed in, `grit` offers to run [`grit auth`](https://grit-scm.com/docs/auth/index.md) and then tries again.

## Options

| Option | Description |
| --- | --- |
| `<remote>` | Remote name, URL, or filesystem path (optional; defaults from branch / config). |
| `<refspec>...` | Push refspecs (`feature`, `HEAD:refs/heads/x`, `+main:main`, `:gone`, …). |
| `-t`, `--tags` | Push all local tags instead of the current branch. |
| `--delete` | Delete the remote refs named by the positionals instead of pushing (plain names only). |
| `--all` | Push every local branch (`refs/heads/*:refs/heads/*`). |
| `--mirror` | Mirror all refs under `refs/` (force + prune remote-only refs). |
| `--prune` | Delete stale refs in the wildcard refspec destination namespace (not on single-ref pushes). |
| `--dry-run` | Contact the remote but do not update refs or send objects. |
| `-f`, `--force` | Overwrite remote refs when the update is not a fast-forward. |
| `--force-with-lease` | Push only if the remote ref matches the local remote-tracking ref (or is absent when there is no tracking ref). |
| `--force-with-lease=<rev>` | Same check against `<rev>` (exactly one ref must be pushed). |
| `-u`, `--set-upstream` | Set upstream config for pushed branches. |
| `--atomic` | All ref updates succeed or none are applied; fails before sending updates if the server does not support atomic pushes. |
| `-o`, `--push-option` | Server-side push option (repeatable; the remote must accept push options). |
| `--follow-tags` | Push annotated tags reachable from the commits being pushed. |
| `-q`, `--quiet` | Suppress remote messages and the human summary of a successful push. |
| `--no-verify` | Skip the `pre-push` hook. |
| `--remote` | Hidden alias for the remote name (prefer the positional `<remote>`). |

## Examples

```console
$ grit push
  pushed main → origin refs/heads/main

$ grit push origin feature
  pushed feature → origin refs/heads/feature

$ grit push origin v1
  pushed v1 → origin refs/tags/v1

$ grit push origin HEAD:refs/heads/bench
  pushed main → origin refs/heads/bench

$ grit push --dry-run
  would push main → origin refs/heads/main

$ grit push --tags
  pushed v0.1 → origin refs/tags/v0.1

$ grit push --delete v0.1
  deleted v0.1 from origin

$ grit push origin --delete old-topic stale-fix
  deleted old-topic from origin
  deleted stale-fix from origin
```

A refspec next to `--delete` is refused before anything is sent:

```console
$ grit push origin HEAD:refs/heads/release --delete old-topic
error: cannot delete 'HEAD:refs/heads/release': --delete takes ref names, not src:dst refspecs
$ echo $?
1
```

When someone else pushed first (your branch is behind the remote):

```console
$ grit push
  rejected origin refs/heads/main: not a fast-forward — run `grit pull` first
```

When your branch was rewritten and no longer fast-forwards (for example after a rebase):

```console
$ grit push
  rejected origin refs/heads/main: not a fast-forward — run `grit push --force-with-lease` after integrating, or `grit pull` first
```

When the remote moved since your last fetch:

```console
$ grit push --force-with-lease
  rejected origin refs/heads/main: stale remote ref — run `grit fetch --prune` and try again
```

When another push created the same new branch while yours was in flight (each ref update is compare-and-swapped against what the push saw, so the other push's commit is never overwritten, even with `--force`):

```console
$ grit push origin HEAD:refs/heads/shared
  rejected origin refs/heads/shared: created on the remote meanwhile — run `grit fetch` and try again
```

When the `pre-push` hook refuses the push (nothing is sent):

```console
$ grit push
pre-push: secrets found in config/prod.env
error: hook pre-push failed with exit status 1
$ echo $?
1
```

When the delete target is not on the remote:

```console
$ grit push origin --delete no-such-branch
  rejected origin refs/heads/no-such-branch: remote ref does not exist
```

When there is nowhere to push yet, or the server wants credentials, the error says so and the `hint:` line names the next command:

```console
$ grit push
error: no remote to push to
hint: add one with `grit remote add origin <url>`, or push to a URL with `grit push <url> <branch>`

$ grit push upstream main
error: unknown remote 'upstream'
hint: add it with `grit remote add upstream <url>`, or pass a URL or path instead; `grit remote` lists the configured remotes

$ grit push
error: authentication failed for https://github.com/ada/project.git: credentials required but unavailable (non-interactive)
hint: sign in to GitHub with `grit auth` and try again; if it still fails, check the URL
```

For other HTTPS hosts the hint points at `grit auth <url> --username <user> --token <token>`, which saves a token with your credential helper, or `GIT_ASKPASS`; when a helper is configured but has nothing for the host, the hint names it. A stored credential the server refuses fails with `auth_rejected` (and the helper drops it, as in Git) rather than claiming none exist. When no helper has the credentials, an askpass program (`GIT_ASKPASS`, `core.askPass`, `SSH_ASKPASS`) is asked for them, as in Git (see [Credentials](https://grit-scm.com/docs/agents/index.md#credentials-https)). With `--json` these failures are `{"error", "kind", "hint"}` objects with `kind` `no_remote`, `remote_not_found`, `remote_no_url`, `auth_required` or `auth_rejected` (see [Exit codes](https://grit-scm.com/docs/exit-codes/index.md)).

## JSON output

Schema: [v1](https://grit-scm.com/docs/push/schemas/push/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `remote` | string | Remote that was pushed to: its name, or the URL given with any `user:password@` removed. Human and Markdown output show the same value. |
| `kind` | string | `branch`, `tags`, `delete`, or `refspecs`. |
| `branch` | string or null | Short branch name when `kind` is `branch`, or the deleted branch’s short name when `kind` is `delete` and exactly one branch is deleted. Omitted for tag and other explicit refspec pushes (`kind`: `refspecs`). |
| `dry_run` | boolean | `true` when `--dry-run` was used (no refs or objects written). |
| `results` | array | Per-ref outcomes; each object has `ref`, `status` (`ok`, `up_to_date`, or `rejected`), optional `reason` (`stale` for a failed lease or a ref another push moved meanwhile, `already_exists` when another push created the new ref first, `tag_exists` when the remote already has that tag and the push did not use `--force`, `remote_ref_missing` when `--delete` targets a ref absent on the remote), optional `deleted` (`true` when the ref was removed), `old_oid`, `new_oid`, `src`, and `forced`. |
| `rejected` | boolean | `true` if any ref was rejected (exit status is also `1`). |
| `upstream_set` | array of strings | Branch short names whose upstream config was written (`-u` only; omitted when empty). |
| `origin_added` | string | URL saved as `origin` after an `<owner>/<project>` push from a repository with no remotes (omitted otherwise). |
| `remote_messages` | array of strings | Hook and diagnostic text from the remote (same lines as `remote: …` on stderr in human mode; omitted when empty). |
| `shared` | array | For each [shared](https://grit-scm.com/docs/share/index.md) branch pushed: `branch`, `combined` (members whose heads were combined into yours and pushed again), `head` (your head after combining) and `heads`, the other members' heads fetched right after the push, each with `user`, `tip`, `relation` to your branch (`same`, `ahead`, `behind`, `diverged` or `unknown`), and for a head that diverged from yours `divergence`: `scenario` (a stable code such as `amended_both_conflicting`; see [Divergence scenarios](https://grit-scm.com/docs/share/index.md#divergence-scenarios)), `summary`, `needs_decision`, `base`, `changes` (each commit's `change`, `subject`, and what `you` and `them` did to it), `conflicts` and `also`. Omitted when no shared branch was pushed. |
| `pushed_to_integrated` | array | Branches this push made again after a share of them was integrated, bringing integrated commits: nobody shares them now (see [After integrating](https://grit-scm.com/docs/share/index.md#after-integrating)). Each has `branch`, `scenario` (`pushed_to_integrated`), `summary`, `by`, `at`, `into`, `target_branch`, `pull`, `url`, `integrated` and `new` (how many of its commits were integrated, and how many are new) and `options` (`rebase`, `rename`, `reshare`, each with `id`, `label`, `loses` and `command`). Omitted when empty. |

Example:

```json
{
  "remote": "origin",
  "kind": "branch",
  "branch": "main",
  "dry_run": false,
  "results": [
    {
      "ref": "refs/heads/main",
      "status": "ok",
      "old_oid": null,
      "new_oid": "83352a61f6715ec3f0a297c6d6150725154fb833",
      "forced": false,
      "src": "refs/heads/main"
    }
  ],
  "rejected": false
}
```

When the `pre-push` hook fails, the push exits **1** with `{"error":"hook pre-push failed with exit status 1"}` on stdout and nothing is sent.

## Markdown output

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output.

Schema: [v1](https://grit-scm.com/docs/push/schemas/push/v1.json/index.md)

Markdown uses headings, bullet lists, and fenced blocks; pipe characters inside table cells are escaped. See the JSON output section for the stable field contract.




```text
## Push to `origin`
- **`refs/heads/main`** · pushed `main` → `origin refs/heads/main`
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed, a ref was rejected, or the `pre-push` hook exited non-zero ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `3` | Pushed, but a [shared](https://grit-scm.com/docs/share/index.md) branch's heads diverged in a way someone has to decide about, or the push made a branch again that was shared and integrated (`pushed_to_integrated`) ([`needs_decision`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `128` | Could not reach or read the remote: missing repository, DNS or connection failure, HTTP error status ([`remote_unreadable`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[grit pull](https://grit-scm.com/docs/pull/index.md), [grit tag](https://grit-scm.com/docs/tag/index.md), [grit auth](https://grit-scm.com/docs/auth/index.md)

# https://grit-scm.com/docs/auth/index.md

# grit auth

> Sign in to GitButler Code, GitHub or a grit serve host, or save a username and token for any HTTPS host, so pushes and fetches just work.

## Synopsis

```text
grit auth [--token <token>]
grit auth <url> [--token <token>]
grit auth <url> --username <user> --token <token>
grit auth logout [<url>] [--dry-run]
```

`grit login` is the same command.

## Description

Signs you in and saves the token, so that [`grit push`](https://grit-scm.com/docs/push/index.md), [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) and [`grit clone`](https://grit-scm.com/docs/clone/index.md) work with private repositories over HTTPS.

Without a URL, `grit auth` signs in to [GitButler Code](https://code.gitbutler.com), unless you run it inside a repository whose `origin` is on github.com: then it signs in to GitHub. GitButler Code signs in like a [`grit serve` host](#signing-in-to-a-grit-serve-host): `grit` opens GitButler Code's sign-in page in your browser, you sign in with Google or your email address and approve the code, and `grit` saves the new token. Set the `GRIT_DEFAULT_HOST` environment variable to sign in to another grit server by default. `grit auth https://github.com` always signs in to GitHub.

GitHub sign-in uses GitHub's device flow. It prints a web address and a short code. Open `https://github.com/login/device` in your browser, enter the code and approve access. `grit` waits until you do, then saves the token with your credential helper. Every request goes straight to github.com.

The token is saved with your credential helper. When no `credential.helper` is set, `grit` sets one in your global config first and tells you which:

- on macOS, `osxkeychain` (the keychain);
- on Linux, `libsecret` when it is installed;
- on Windows, its built-in one ([`grit manager`](https://grit-scm.com/docs/manager/index.md)), stored as the absolute path of `grit.exe` followed by `manager` so that `git` can run it too;
- otherwise `store`, which keeps tokens in plain text in `~/.git-credentials`.

To use a different one, set it yourself with [`grit config`](https://grit-scm.com/docs/config/index.md) before signing in:

```console
$ grit config --global credential.helper libsecret
```

The helper is shared with Git and asked the same way: `grit` sends it the protocol and host (`protocol=https`, `host=github.com`), so one stored entry covers every repository on that host, and entries Git already saved, such as lines in `~/.git-credentials`, work as they are. Set `credential.useHttpPath` to keep a separate entry per repository; the helper then also gets the repository path (`path=owner/repo.git`).

`grit auth logout` removes the saved token for the same default host from your credential helper: GitButler Code's, or GitHub's inside a repository whose `origin` is on github.com.

`grit` signs in with its own GitHub OAuth app. To use a different one, set its client id in the `GRIT_GITHUB_CLIENT_ID` environment variable or the `grit.githubClientId` setting.

### Signing in to a `grit serve` host

`grit auth <url>` signs in to a server run by [`grit serve`](https://grit-scm.com/docs/serve/index.md) instead. The URL can be the server's address or any repository URL on it, such as `http://git.example.com:8080/app.git`; without a scheme it is taken as `https://`. A `github.com` URL signs in to GitHub as above.

It works like the GitHub sign-in. `grit` prints the server's sign-in page and a short code, and opens the page in your browser when it can. Sign in there with your email address and password (from the server's admin), check that the page shows the same code, and approve. `grit` then saves a new token with your credential helper for the server's scheme and host, under your email address. After that, `grit` and `git` clone, fetch and push to every repository on the host without asking.

To store a token you already have instead, for example one an admin made with `grit serve token` for a CI job, pass `--token`: `grit` checks it with the server before saving it.

`grit auth logout <url>` removes the token saved for that host.

Any other host, such as GitLab, Gitea or a company server, is not a `grit serve` host: `grit auth <url>` says so and points at `--username` and `--token` below, without changing your config.

### Saving a username and token for any HTTPS host

`grit` never asks for a password on the terminal, so pushes and fetches don't hang waiting for input. To save the user name and personal access token (or password) a host gave you, pass both:

```console
$ grit auth https://gitlab.com/team/app.git --username ada --token "$GITLAB_TOKEN"
✓ Stored the token for ada on gitlab.com — the next push or fetch uses it.
```

This works for any `http://` or `https://` URL, GitHub included. `grit` saves the pair with your credential helper (setting one up first, as above) under the URL's scheme and host, so it covers every repository on that host, for Git as well. With `credential.useHttpPath` set, it is saved for that repository's path instead, matching how pushes and fetches look it up, so pass the repository URL; `credential.<url>.helper` settings for the URL apply too. Nothing is sent to the host at this point: the next push, fetch or clone uses the token, and if the host refuses it, that command fails with `kind` `auth_rejected` and the helper drops it, as Git does. Run the same command again with the new token. A token on the command line can end up in your shell history; in CI, an askpass program (see [Credentials](https://grit-scm.com/docs/agents/index.md#credentials-https)) avoids that.

## Options

| Option | Description |
| --- | --- |
| `<url>` | Sign in to the `grit serve` host this URL names instead of GitHub (or, with `--username`, the host to store a token for). |
| `--token <token>` | Store this access token: alone, for a `grit serve` host (from `grit serve token`), checked with the server instead of signing in in the browser; with `--username`, for any HTTP(S) host. A token on the command line can end up in your shell history. |
| `--username <user>` | Store `--token` for this user name on the URL's host, without contacting it. Needs `<url>` and `--token`. |
| `logout` | Remove the saved GitHub token. |
| `logout <url>` | Remove the token saved for a `grit serve` host. |
| `--dry-run` | On `logout`, report which stored credential would be erased without calling the helper. |

## Examples

```console
$ grit auth
To authorize grit, open this page in your browser:

    https://github.com/login/device

and enter the code:

    1A2B-3C4D

Waiting for you to authorize… (press Ctrl-C to cancel)

✓ Signed in to GitHub — token stored for github.com.

$ grit auth logout
✓ Signed out of GitHub — removed the stored token for github.com.
```

Sign in to a `grit serve` host in the browser, then clone without a password:

```console
$ grit login http://git.example.com:8080
To sign in, open this page in your browser:

    http://git.example.com:8080/.grit/authorize?code=K7MQ-3XZP

and check that it shows the code:

    K7MQ-3XZP

(Opened it for you.)
Waiting for you to approve… (press Ctrl-C to cancel)
✓ Signed in to git.example.com:8080 as bob@example.com — token stored.
$ grit clone http://git.example.com:8080/app.git
$ grit auth logout http://git.example.com:8080
✓ Signed out of git.example.com:8080 — removed the stored token for git.example.com:8080.
```

Store a token made with `grit serve token`, for example on a CI machine:

```console
$ grit auth http://git.example.com:8080 --token "$GRIT_TOKEN"
✓ Signed in to git.example.com:8080 as ci@example.com — token stored.
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/auth/schemas/auth/v1.json/index.md) · [auth.logout v1](https://grit-scm.com/docs/auth/schemas/auth.logout/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `authenticated` | boolean | For sign-in, whether a token was stored. |
| `logged_out` | boolean | For `logout`, whether a stored token was removed (or would be removed with `--dry-run`). |
| `host` | string | Host the credential applies to: `github.com`, or a `grit serve` host with its port (`git.example.com:8080`). |
| `user` | string or omitted | For sign-in to a `grit serve` host, the email address of the user the token belongs to; with `--username`, that user name. Omitted for GitHub. |
| `verified` | boolean | For sign-in, whether the host confirmed the token. `false` with `--username`, which stores the token without contacting the host. |
| `dry_run` | boolean | On `logout`, `true` when `--dry-run` was used. |
| `credential` | object or omitted | With `--dry-run`, describes the helper entry that would be removed (`protocol`, `host`, `username`; never includes a password). |

After sign-in:

```json
{
  "authenticated": true,
  "host": "github.com",
  "verified": true
}
```

After signing in to a `grit serve` host:

```json
{
  "authenticated": true,
  "host": "git.example.com:8080",
  "user": "bob@example.com",
  "verified": true
}
```

After storing a token with `--username`:

```json
{
  "authenticated": true,
  "host": "gitlab.com",
  "user": "ada",
  "verified": false
}
```

After logout:

```json
{
  "logged_out": true,
  "host": "github.com"
}
```

`logged_out` is `false` when no credential helper is configured, since there's nowhere a token could be stored.

## Markdown output

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output.

Schema: [v1](https://grit-scm.com/docs/auth/schemas/auth/v1.json/index.md) · [auth.logout v1](https://grit-scm.com/docs/auth/schemas/auth.logout/v1.json/index.md)

Markdown uses headings, bullet lists, and fenced blocks; pipe characters inside table cells are escaped. See the JSON output section for the stable field contract.



```text
## Auth

- Signed in to **`github.com`**
```

For a `grit serve` host the line names the user: ``- Signed in to **`git.example.com:8080`** as **`bob@example.com`**``. With `--username` it reads ``- Stored a token for **`ada`** on **`gitlab.com`** (not verified; the next push or fetch uses it)``.

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[grit push](https://grit-scm.com/docs/push/index.md), [grit config](https://grit-scm.com/docs/config/index.md), [grit manager](https://grit-scm.com/docs/manager/index.md), [grit serve](https://grit-scm.com/docs/serve/index.md)

# https://grit-scm.com/docs/bundle/index.md

# grit bundle

> Create, verify, list, and unbundle git bundle files for offline transfer.

## Synopsis

```text
grit bundle create <file> [--all] [--dry-run] [<rev>…]
grit bundle verify <file>
grit bundle list <file>
grit bundle unbundle <file> [--dry-run]
```

## Description

Git bundles pack refs and objects into a single file. Use them to move history without a network remote, or to seed a clone from removable media.

`create` walks the given revision specs (same rules as [`grit log`](https://grit-scm.com/docs/log/index.md)), writes prerequisite commits the recipient must already have, lists tip refs in the header, and appends a pack stream. Bundles are detected by the `# v2 git bundle` / `# v3 git bundle` signature, not by the `.bundle` file extension alone.

When the repository's objects are already packed, `create` copies the existing deltas and whole objects straight from the packs instead of recomputing them, and streams the pack into the file. A bundle of a packed repository is close to a copy of its pack: it takes seconds and its memory is bounded by the pack index, not by the size of the history. Bundles with prerequisites are thin, so an object can be sent as a delta against a prerequisite's blob. Only objects that are not already stored as deltas (for example, loose objects from recent commits) go through a new delta search, as `git bundle create` does; it covers blobs, trees and commits and reads each object only while it is in the search window.

`create` and `unbundle` honor Ctrl+C (and `SIGTERM` / `SIGHUP` on Unix) with `error: operation cancelled` and exit code **130**. A failed or cancelled `create` leaves an existing destination file unchanged and removes only the temporary `*.bundle.part` file; `unbundle` rolls back before refs are updated.

`verify` checks the pack checksum and, when run inside a repository, confirms prerequisite commits are present and their exclusive history is readable. Prerequisites already reachable from your refs satisfy this immediately; otherwise an unreferenced but complete object graph in the repository is enough (for example after `unbundle` of a full bundle leaves dangling prerequisites).

`list` prints the refs recorded in the bundle header.

`unbundle` ingests the embedded pack into the current repository (objects only; refs in the header are reported but not updated on disk). Run inside the destination repository. When prerequisite commits from an incremental bundle are missing locally, `unbundle` refuses before reading the pack (same checks as `verify`) with exit **128** and a message listing the missing commit ids—it does not report pack corruption or leave partial objects behind.

You can also treat a bundle path like a remote: [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) and [`grit clone`](https://grit-scm.com/docs/clone/index.md) accept a path to a bundle file.

## Options

`create`:

| Argument / flag | Description |
| --- | --- |
| `<file>` | Output bundle path. |
| `--all` | Include `HEAD`, every branch, and every tag in the bundle header (same idea as `git bundle create --all`). Omit `<rev>…` when using this flag. |
| `<rev>…` | One or more positive revision specs (commits, branches, ranges). Not used together with `--all`. |
| `--dry-run` | List refs, prerequisites, and pack object count without writing `<file>`. |

`verify` / `list` / `unbundle`:

| Argument | Description |
| --- | --- |
| `<file>` | Existing bundle file. |
| `-n`, `--limit <N>` | For `list`: print at most `N` header refs (`truncated` in JSON when more exist). |

`unbundle`:

| Option | Description |
| --- | --- |
| `--dry-run` | Verify the bundle and report refs that differ from local tips; do not ingest objects or write refs (`unbundle` never updates refs). |

## Examples

```console
$ grit bundle create backup.bundle --all
Wrote bundle backup.bundle (5 refs).

$ grit bundle create backup.bundle main
Wrote bundle backup.bundle (1 refs).

$ grit bundle verify backup.bundle
backup.bundle is valid
The bundle uses this hash algorithm: sha1
The bundle contains 1 refs:
f4e623f540cd491f8856e9487a3da5f8242307f0 refs/heads/main

$ grit bundle list backup.bundle
f4e623f540cd491f8856e9487a3da5f8242307f0 refs/heads/main
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/bundle/schemas/bundle.create/v1.json/index.md) · [bundle.list v1](https://grit-scm.com/docs/bundle/schemas/bundle.list/v1.json/index.md) · [bundle.verify v1](https://grit-scm.com/docs/bundle/schemas/bundle.verify/v1.json/index.md) · [bundle.unbundle v1](https://grit-scm.com/docs/bundle/schemas/bundle.unbundle/v1.json/index.md)

`grit bundle verify --json`:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `path` | string | Bundle file path. |
| `ok` | boolean | Whether verification succeeded. |
| `hash_algorithm` | string | Object hash used by the pack (`sha1` or `sha256`). |
| `references` | array | Each entry has `name` and `oid`. |
| `prerequisites` | array of strings | Required commit ids (hex). |
| `missing_prerequisites` | array of strings | Prerequisite ids absent from the current repo (empty when not in a repo or when `ok` is true). |

```json
{
  "path": "backup.bundle",
  "ok": true,
  "hash_algorithm": "sha1",
  "references": [
    {
      "name": "refs/heads/main",
      "oid": "f4e623f540cd491f8856e9487a3da5f8242307f0"
    }
  ],
  "prerequisites": [],
  "missing_prerequisites": []
}
```

`grit bundle list --json`:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `path` | string | Bundle file path. |
| `references` | array | Refs from the bundle header (`name`, `oid`). |
| `truncated` | boolean | `true` when the header held more refs than returned (`-n` / `--limit`). |

```json
{
  "path": "backup.bundle",
  "references": [
    {
      "name": "refs/heads/main",
      "oid": "f4e623f540cd491f8856e9487a3da5f8242307f0"
    }
  ]
}
```

`grit bundle create --json`:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `path` | string | Output bundle path. |
| `refs` | number | Count of refs written to the header. |
| `dry_run` | boolean | `true` when `--dry-run` was used (omitted when false). |
| `object_count` | number | With `--dry-run`, objects that would be packed. |
| `references` | array | With `--dry-run`, planned header refs (`name`, `oid`). |
| `prerequisites` | array of strings | With `--dry-run`, prerequisite commit ids. |

`grit bundle unbundle --json`:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `path` | string | Bundle file path. |
| `references` | array | Ref tips from the bundle header (`name`, `oid`). |
| `objects` | number | Objects installed from the pack (omitted on `--dry-run`). |
| `bytes` | number | Pack size in bytes (omitted on `--dry-run`). |
| `dry_run` | boolean | `true` when `--dry-run` was used. |
| `object_count` | number | With `--dry-run`, objects in the embedded pack. |
| `ref_updates` | array | With `--dry-run`, refs that differ from local tips (`name`, `old_oid`, `new_oid`). |
| `ok` | boolean | With `--dry-run`, whether verification succeeded. |
| `missing_prerequisites` | array of strings | With `--dry-run`, prerequisite ids absent locally. |

```json
{
  "path": "backup.bundle",
  "references": [
    {
      "name": "refs/heads/main",
      "oid": "f4e623f540cd491f8856e9487a3da5f8242307f0"
    }
  ],
  "objects": 3,
  "bytes": 512
}
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/bundle/schemas/bundle.create/v1.json/index.md)
Pass `--markdown` on any `grit bundle` subcommand for the same JSON document wrapped for agents (see [Global options](https://grit-scm.com/docs/global-options/index.md)).



```text
## Bundle verify

- **path:** `snap.bundle`
- **ok:** true
- **hash_algorithm:** sha1

| Ref | OID |
| --- | --- |
| `HEAD` | `83352a61f6715ec3f0a297c6d6150725154fb833` |
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success. |
| `1` | Verify failure or other error. |
| `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `128` | `unbundle` missing prerequisite commits ([`missing_prerequisite`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md).


## See also

[grit fetch](https://grit-scm.com/docs/fetch/index.md), [grit clone](https://grit-scm.com/docs/clone/index.md), [grit remote](https://grit-scm.com/docs/remote/index.md)

# https://grit-scm.com/docs/serve/index.md

# grit serve

> Serve repositories over HTTP, with a web view where people sign in with email and password.

## Synopsis

```text
grit serve [--root <path>] [--db <file>] [--bind <host:port>] [--bundle-interval <duration>] [--no-bundles] [--header-timeout <duration>] [--idle-timeout <duration>] [--max-git-requests <n>] [--shutdown-timeout <duration>]
grit serve --setup [--email <email>] [--root <path>] [--db <file>]
grit serve add-user <email> [--admin] [--root <path>] [--db <file>]
grit serve token <email> [--root <path>] [--db <file>]
grit serve grant <email> <repository> [--write] [--root <path>] [--db <file>]
grit serve users [--root <path>] [--db <file>]
```

## Description

`grit serve` runs a Git server over HTTP. Any Git client, `git` or `grit`, can clone, fetch and push through it, and a browser shows each repository's branches and recent commits. Fetch speaks Git protocol v0, v1 and v2 (whichever the client asks for); push uses receive-pack, which has no v2 form. Everything runs in-process: the server needs no `git` or other `grit` binary.

Fetch and clone POST bodies (`git-upload-pack`) are streamed as they arrive; the server rejects decoded bodies larger than 1 GiB with HTTP 413 (matching a generous reading of Git's `http.maxRequestBuffer`), which is enough for several million `want` lines. Push bodies are streamed separately and are limited only by each repository's `receive.maxInputSize`.

When a client is still uploading a large POST body, early responses such as `401`, `404`, `403` or `413` drain the remainder of that body (up to the same 1 GiB cap) before the connection closes, so a reverse proxy relays the real status instead of answering `502 Bad Gateway`.

`--root` names what to serve:

- a **directory of repositories**: each child directory that is a repository (bare `project.git` or a working tree `project`) is served as `project`. New repositories show up without a restart.
- a **single repository**: it is the only one served, under its directory name.

Clients reach a repository at `http://<host>:<port>/<name>.git` (the `.git` is optional).

### Users and passwords

A user is an email address with a password. Users, their access and their tokens live in a SQLite database, `grit-serve.db` in the root by default (or in the root's `.git` directory when the root is a working tree, so the file never shows up as untracked). Pick another path with `--db`.

Path strings in the startup banner, errors, and `--json` fields such as `database` use forward slashes and no Windows `\\?\` verbatim prefix, matching other grit commands.

- `grit serve --setup` creates the database and the first **admin** user. It asks for the admin's email (or takes `--email`) and a password. An admin can read and write every repository, and add users in the web view.
- `grit serve add-user <email>` adds a user. Add `--admin` for another admin.
- `grit serve grant <email> <repository>` gives a user read access (fetch and clone) to one repository; `--write` also allows pushing. Granting again replaces the earlier access.
- `grit serve users` lists every user, their token count and their access.

Both `--setup` and `add-user` ask for the password twice without echoing it. Leave it empty to have one generated instead: a **temporary password** like `5qy3-ewqt-mgjj-3jnv`, printed once, which the user must replace with their own the first time they sign in. Without a terminal, the password is read from the first line of stdin, and empty input generates one. Passwords need at least 8 characters; the database keeps only an Argon2 hash.

### Signing in

People sign in to the web view at `http://<host>:<port>/` with their email and password. There they can change their password, and admins get a **Users** page to add users and give them access. Adding a user there generates a temporary password to send them, together with their email address, yourself.

Git uses access tokens instead of passwords. To get one, run [`grit auth <url>`](https://grit-scm.com/docs/auth/index.md) (or `grit login <url>`) with the server's address or any repository URL on it. It opens the server's sign-in page in your browser and waits; after you sign in and approve the code it shows, it saves a new token with your credential helper, so `grit` and `git` clone, fetch and push without asking.

For scripts and CI, which cannot sign in in a browser, an admin can make a token with `grit serve token <email>` and hand it over: `grit auth <url> --token <token>` stores it, a URL carries it (`git clone http://bob:<token>@host:8080/project.git`, where the user name is ignored), or a client can send `Authorization: Bearer <token>`. Each token is printed once; the database keeps only a SHA-256 hash of it. A token starts with `grit_`.

A Git request without a valid token gets `401`, and a browser without a session is sent to the sign-in page. A repository the user cannot read answers `404`, the same as one that does not exist, and a push from a user with read access answers `403`.

### Clone bundles

The server keeps a prebuilt [bundle](https://git-scm.com/docs/git-bundle) of each repository's branches and tags in `grit-serve/bundles/` inside its Git directory. A background thread builds a repository's first bundle as soon as the server starts (or as soon as the repository gets its first branch), and builds a new one after pushes have changed its refs, once the current bundle is older than `--bundle-interval` (24 hours by default; `0s` rebuilds right after every push). Each bundle gets a new file name and the previous one is kept, so a client part way through downloading the old bundle can still finish it.

Fetches over protocol v2 see the `bundle-uri` command in the server's capabilities. It answers with the current bundle's URL, `http://<host>:<port>/<name>/bundles/<file>`, which serves the file with `Range` support so an interrupted download can resume. [`grit clone`](https://grit-scm.com/docs/clone/index.md) downloads the bundle first and then fetches only what is newer; credentials embedded in the clone URL apply to that same-origin bundle download as well. `git clone` does the same with `-c transfer.bundleURI=true` and a credential helper that knows the token, because Git's advertised bundle URL has no userinfo. Downloading a bundle needs read access, like fetching.

`--no-bundles` turns this off: nothing is built and nothing is advertised.

A repository with promisor remotes gets no bundle, and any bundle built earlier is removed. This covers a repository offloaded with [`grit gc offload`](https://grit-scm.com/docs/gc/index.md#grit-gc-offload): some of its blobs live elsewhere, and a bundle holding them would undo the offload. Its clients clone through upload-pack, which points them at the promisor.

### Partial clone filters

[`grit clone --blobs`](https://grit-scm.com/docs/clone/index.md) and filtered fetches need the server to advertise Git's `filter` capability. On each served bare repository, enable it the same way as with `git upload-pack`:

```console
$ git -C /path/to/root/project.git config uploadpack.allowFilter true
```

Filter support is off by default (matching stock `git upload-pack`). Without it, clients that pass `--blobs` or `--filter` still connect, but the server sends a full pack; grit warns when that happens.

### Resumable pushes

The push advertisement carries a `pushBundle=/push` capability: a [TUS](https://tus.io/protocols/resumable-upload) upload endpoint at `http://<host>:<port>/<name>/push`. [`grit push`](https://grit-scm.com/docs/push/index.md) sends a large push there as a bundle, in chunks that survive a dropped connection, then posts the usual ref updates to `…/push/<id>/receive`. The server applies them exactly as for a normal push (the same checks, policy and hooks) and answers with the usual push report. Uploading needs write access, and an upload belongs to the user who started it. Unfinished uploads are deleted after a week. Git clients ignore the capability and push the usual way.

Hook scripts on push see the token user's email as `REMOTE_USER` and `GRIT_USER` (not the username in the clone URL), on both `git-receive-pack` and `…/push/<id>/receive`.

| Request | Answer |
| --- | --- |
| `OPTIONS /<name>/push` | TUS version and extensions (`creation`) |
| `POST /<name>/push` with `Upload-Length` | `201` and the upload's `Location` |
| `HEAD /<name>/push/<id>` | `Upload-Offset`: bytes received so far |
| `PATCH /<name>/push/<id>` with `Upload-Offset` | appends the body; answers the new offset |
| `POST /<name>/push/<id>/receive` | applies the bundle with the posted ref updates |

### Snapshot checkouts

[`grit checkout <url>`](https://grit-scm.com/docs/checkout/index.md) starts work on a repository without its history: the server makes a snapshot commit of the target branch (where `HEAD` points), cut down to the paths asked for, and serves it as a resumable download. These requests have their own endpoint, apart from Git's, and need read access:

| Request | Answer |
| --- | --- |
| `GET /.grit/checkouts/<name>` | the repository's name, target branch and its tip |
| `POST /.grit/checkouts/<name>` | makes a checkout of the paths in the JSON body |
| `GET /.grit/checkouts/<name>/<id>` | the checkout |
| `GET /.grit/checkouts/<name>/<id>/bundle` | its snapshot as a bundle, with `Range` support |
| `POST /.grit/checkouts/<name>/<id>/update` | a snapshot of the newest tip of the branch the checkout was made from, on top of the checkout's last one, at `refs/checkouts/<id>/target` (`grit pull`) |
| `POST /.grit/checkouts/<name>/<id>/checkin` | grafts branches pushed to `refs/checkouts/<id>/out/heads/*` onto the real history and sets them (`grit checkin`; write access) |
| `POST /.grit/checkouts/<name>/<id>/branch` | shows the checkout the server's branch named in the JSON body (`name`): its commits the target lacks, cut down to the checkout's paths on its snapshots, at `refs/checkouts/<id>/in/heads/<branch>` (`grit pull <branch>`) |
| `POST /.grit/checkouts/<name>/<id>/work` | reserves a fresh work-branch name for the checkout, from the `work` name in the JSON body, as making a checkout does (`grit integrate`, moving you off the branch it merged) |
| `POST /.grit/checkouts/<name>/integrate` | merges a branch into the target with a merge commit (`grit integrate`; write access) |
| `GET /.grit/checkouts/<name>/slices` | the slices in `.grit/slices.toml` on the target |
| `PUT`, `DELETE /.grit/checkouts/<name>/slices/<slice>` | changes a slice with a commit on the target (`grit slice`; write access) |

The server keeps checkouts in `grit-serve/checkouts/` inside the Git directory (each checkout's record in `<id>.json`, replaced whole so a crash never leaves half of one, the work-branch names it has given out under `names/`, so a name is never given out twice, and the graft log under `grafts/`: which real commit each checkout commit stands for, filed by the first two hex digits of each side and only ever appended to) and points `refs/checkouts/<id>/target` at each one's snapshot. Requests on one checkout take turns, and so do check-ins setting the repository's branches: of several check-ins of one branch at once, the first sets it and the others are refused. Branches are set with a compare-and-swap, so a branch that moved meanwhile is decided again rather than overwritten. A branch the server has moves only as a fast-forward, when the same checkout set it last, when the new branch keeps every commit the old one had beyond the target by change id (a rebase of it whose copies keep what the originals changed outside the checking-in checkout's paths), or when the check-in is forced; the server's log line and the check-in's answer name the rule (see [`grit checkin`](https://grit-scm.com/docs/checkin/index.md)). A grafted commit with no `change-id` header gets the one derived from the checkout commit's own id. Check-ins record the commits they graft in the graft log once the branch is set (a log that can't be written is reported in the server's log, and the check-in still succeeds), and so does showing a checkout a branch, so work built on a branch a checkout was shown grafts onto the real commits it stands for, and a check-in replays only commits it hasn't grafted before; a check-in's walk stops at the target branch, so a branch built on the real history is refused at once. A shown commit keeps its author, date and message, gets a change id derived from the real commit when it has none, and drops signatures; a checkout's own commits (those its pushed branches at `refs/checkouts/<id>/out/heads/*` reach) come back as they are, and another checkout's only when they have the tree the projection would make. Where the repository ignores case (`core.ignorecase`), a branch asked for in another case is shown under the server's spelling (see [`grit pull`](https://grit-scm.com/docs/pull/index.md#a-server-branch-in-a-snapshot-checkout)).

Once a repository has checkouts, its target branch changes only through integrations and slice changes. Pushes that create, update or delete it are refused, by `git` and `grit` clients alike, over smart HTTP and the resumable endpoint (and by [`grit receive-pack`](https://grit-scm.com/docs/receive-pack/index.md)); branches whose names differ from it only in case are refused too. The refusal (`main is the target branch; it changes only through integrate`, or Git's own `branch is currently checked out` when the repository has it checked out) comes with instructions, which Git clients show as `remote:` lines: push another branch and run [`grit integrate <branch>`](https://grit-scm.com/docs/integrate/index.md). A repository without checkouts keeps Git's rules for pushes, including refusing to delete the branch `HEAD` names (`receive.denyDeleteCurrent`).

Integrations and slice changes take turns, one at a time per repository, and each starts over on the new tip if the target moves while it is made (by another process). Integrating refuses names that are not valid branch names, the target itself and branches that share no history with it. A server-made commit's author comes from the request (the client's own author identity) or is the signed-in user; `<`, `>` and line breaks are cleaned out of it, so it can't break the commit's header. When the repository has a working tree with the target checked out (`HEAD` names it), that tree and its index move with each integration and slice change, keeping uncommitted changes there as `git reset --keep` does; a change that would overwrite them is refused and the target stays where it was. Every ref move the server makes is logged where the repository keeps reflogs (`core.logAllRefUpdates`, on by default in a repository with a working tree), as `checkin: from checkout <id>`, `integrate: Merge branch '<branch>' into <target>` or `slice: <message>`, so `git reflog <branch>` shows it and `<branch>@{1}` undoes it.

### Large-object promisors

A repository can point clients at promisor remotes that hold some of its objects, such as a large-object promisor (LOP) with the big blobs. Set `promisor.advertise = true` and give the repository a promisor remote (`remote.<name>.url` and `remote.<name>.promisor = true`); the protocol v2 capabilities then carry a `promisor-remote` line naming it, and `promisor.sendFields` adds its `partialCloneFilter` and `token`. A LOP served by `grit serve` needs `uploadpack.allowFilter` and `uploadpack.allowAnySHA1InWant`, so clients can fetch blobs no ref points at. See [grit upload-pack](https://grit-scm.com/docs/upload-pack/index.md#promisor-remotes) for the exchange, and [grit clone](https://grit-scm.com/docs/clone/index.md) for the client side.

Over smart HTTP every request stands alone, so the server only knows a client accepted a promisor remote when the `fetch` request itself says so. `grit` clients send their acceptance with every command; `git` clients send it with `ls-refs` only, so for them the server behaves as if nothing was accepted. A `git` fetch whose filter is no looser than the promisor remotes' `partialCloneFilter` still gets its pack without the offloaded blobs, since its filter leaves them out anyway (see [upload-pack](https://grit-scm.com/docs/upload-pack/index.md#serving-a-repository-whose-large-blobs-live-elsewhere)).

To keep a repository's big blobs out of it, host the LOP as a second repository next to it and run [`grit gc offload`](https://grit-scm.com/docs/gc/index.md#grit-gc-offload) on the main one. Point `remote.<lop>.url` at the URL clients should use (for example `http://<host>:<port>/<lop>.git` on this server), and pass `--lop-dir` with the LOP's directory on disk. The main repository then serves clients that accept the LOP without the offloaded blobs. A client that accepts nothing is refused with a hint, unless the server may fetch the blobs itself: set `uploadpack.lazyFetch = true` in the main repository, or start `grit serve` with `GIT_NO_LAZY_FETCH=0`. Only those requests get a promisor fetcher, upload-pack and snapshot checkouts alike; clone bundles and pushes never do. So a server without lazy fetch never fetches anything, and nothing pulls an offloaded blob back into the main repository. A snapshot holds every file it names, so a snapshot checkout follows the same rule as a client that accepted nothing: with lazy fetch on, the server first fetches the offloaded blobs the snapshot needs, all in one request, and they stay in the main repository until the next `grit gc offload`; with it off, `POST /.grit/checkouts/<name>` (and `update`) answer `409` naming the first missing blob and how many there are, and a fetch that fails answers `502`. Pushes may name offloaded blobs in their trees. If the LOP sits behind this server's authentication, the server needs credentials for it, like any other client. See [Serving a repository whose large blobs live elsewhere](https://grit-scm.com/docs/upload-pack/index.md#serving-a-repository-whose-large-blobs-live-elsewhere).

### Running it

`grit serve` with no subcommand and no `--setup` runs the server until interrupted. It refuses to start until `--setup` has created a user. It listens on `127.0.0.1:8080`; use `--bind 0.0.0.0:8080` to accept connections from other machines. The server speaks plain HTTP, so put it behind a TLS-terminating proxy before sending passwords and tokens across a network you don't trust.

Git smart HTTP connections drop peers that stop sending: `--header-timeout` (default `30s`) closes incomplete request headers, and `--idle-timeout` (default `60s`) closes POST bodies or upload-pack responses that stall between chunks (a large push that keeps sending is unaffected). When `--max-git-requests` concurrent Git operations (default `128`) are already in flight, further `info/refs`, fetch, push and resumable-push apply requests get HTTP `503` immediately instead of queuing, so the web UI and sign-in still have threads to answer.

On SIGTERM, SIGINT or SIGHUP (Ctrl+C on Windows), the server logs that it is closing the listener, stops accepting new connections, and lets in-flight clone and push requests finish. The clone-bundle background thread stops after its current build. By default it waits up to `--shutdown-timeout` (30 seconds) for those requests; `--shutdown-timeout 0s` waits with no cap until they finish. When the grace period ends, remaining connections are closed and in-flight receive-pack hook processes are terminated so the server process can exit. A second signal in that window stops those hooks and exits immediately without waiting.
## Options

| Option | Description |
| --- | --- |
| `--root <path>` | A repository, or a directory of repositories, to serve. Defaults to the current directory. Also accepted after a subcommand. |
| `--db <file>` | The user database. Defaults to `grit-serve.db` in the root (in its `.git` directory for a working tree). Also accepted after a subcommand. |
| `--bind <host:port>` | Address to listen on. Defaults to `127.0.0.1:8080`. |
| `--setup` | Create the database and its first admin user, then exit. Prompts for a password, or generates a temporary one. Fails when the database already has users. |
| `--email <email>` | Email address of the admin `--setup` creates. Asked for on a terminal when omitted. Requires `--setup`. |
| `--bundle-interval <duration>` | How old a changed repository's clone bundle gets before a new one is built: a number with `s`, `m`, `h` or `d`. Defaults to `24h`. |
| `--no-bundles` | Do not build or advertise clone bundles. |
| `--header-timeout <duration>` | How long to wait for a complete HTTP request header on a new connection before closing it. Defaults to `30s`. |
| `--idle-timeout <duration>` | How long to wait between bytes on a Git smart HTTP POST body or upload-pack response before closing the connection. Defaults to `60s`. |
| `--max-git-requests <n>` | Maximum concurrent Git smart HTTP operations (`info/refs`, fetch, push, resumable push). Further requests get HTTP `503`. Defaults to `128`. |
| `--shutdown-timeout <duration>` | After a shutdown signal, how long to keep serving in-flight requests before closing remaining connections. Defaults to `30s`; `0s` waits until they finish. A second signal exits immediately. |
| `add-user <email>` | Add a user, named by their email address. Prompts for a password, or generates a temporary one. |
| `add-user --admin` | Make the new user an admin. |
| `token <email>` | Create an access token for a user and print it, for scripts and CI. |
| `grant <email> <repository>` | Give a user read access to a repository, by name with or without `.git`. |
| `grant --write` | Give write (push) access instead of read access. |
| `users` | List users, their tokens and their access. |

## Examples

Set up a directory of repositories and run the server:

```console
$ cd /srv/git
$ grit serve --setup --email admin@example.com
Password for admin@example.com (leave empty to generate a temporary one):
Repeat it:
✓ Created admin user admin@example.com in ./grit-serve.db
$ grit serve
Serving 1 repository from /srv/git at http://127.0.0.1:8080/
  http://127.0.0.1:8080/demo.git
Sign in at http://127.0.0.1:8080/ (command line: grit auth http://127.0.0.1:8080)
Clone bundles are built in the background and rebuilt every 24h after pushes
bundle: built 1792924806-0bfb630026ae.bundle (30309803 bytes) for /srv/git/demo
```

Sign in from another terminal, approve the code in the browser, then clone and push:

```console
$ grit auth http://127.0.0.1:8080
To sign in, open this page in your browser:

    http://127.0.0.1:8080/.grit/authorize?code=K7MQ-3XZP

and check that it shows the code:

    K7MQ-3XZP

(Opened it for you.)
Waiting for you to approve… (press Ctrl-C to cancel)
✓ Signed in to 127.0.0.1:8080 as admin@example.com — token stored.
$ grit clone http://127.0.0.1:8080/demo.git
```

Add a user with a generated password who can only fetch `demo`:

```console
$ grit serve add-user bob@example.com
Password for bob@example.com (leave empty to generate a temporary one):
✓ Created user bob@example.com in ./grit-serve.db

  Email:    bob@example.com
  Password: 5qy3-ewqt-mgjj-3jnv

The password is temporary and not shown again: it must be changed at the first sign-in.
$ grit serve grant bob@example.com demo
✓ bob@example.com now has read access to demo
$ grit serve users
admin@example.com  1 token    all repositories (admin)
bob@example.com    0 tokens   demo (read)  (temporary password)
```

A push from `bob` is refused:

```console
$ git push origin main
remote: bob@example.com has read-only access to demo
fatal: unable to access 'http://127.0.0.1:8080/demo/': The requested URL returned error: 403
```

Give a CI job its own token:

```console
$ grit serve token bob@example.com
✓ Created a token for bob@example.com

  Token: grit_617db60c2d54601c6109c9a9e7aaeac0dd3c5307

Save it now; it is not shown again. Use it as the password when Git asks, or run `grit auth <url> --token <token>`.
```

Rebuild bundles an hour after pushes, or not at all:

```console
$ grit serve --bundle-interval 1h
$ grit serve --no-bundles
```

Serve a single repository from its working tree:

```console
$ grit serve --root ~/projects/app --setup --email me@example.com
$ grit serve --root ~/projects/app --bind 0.0.0.0:8080
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/serve/schemas/serve/v1.json/index.md) · [serve.add-user v1](https://grit-scm.com/docs/serve/schemas/serve.add-user/v1.json/index.md) · [serve.token v1](https://grit-scm.com/docs/serve/schemas/serve.token/v1.json/index.md) · [serve.grant v1](https://grit-scm.com/docs/serve/schemas/serve.grant/v1.json/index.md) · [serve.users v1](https://grit-scm.com/docs/serve/schemas/serve.users/v1.json/index.md)

Pass `--json` with `--setup` or a subcommand for one JSON object on stdout. The running server has no JSON output: it logs to stderr.

`grit serve --setup` and `grit serve add-user`:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `database` | string | The user database the user was added to. |
| `user` | string | The new user's email address. |
| `admin` | boolean | Whether the user is an admin (read and write on every repository). |
| `password` | string or omitted | The generated temporary password, shown only once. Omitted when the password was typed in. |
| `temporary` | boolean | Whether the user must choose a new password at their first sign-in (`true` for a generated password). |

<!-- schema: serve.add-user -->

```json
{
  "database": "./grit-serve.db",
  "user": "carol@example.com",
  "admin": false,
  "password": "y3hm-yphb-9y4a-2sdd",
  "temporary": true
}
```

`grit serve token`:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `user` | string | The user's email address. |
| `token` | string | The new access token. It is shown only once. |

<!-- schema: serve.token -->

```json
{
  "user": "bob@example.com",
  "token": "grit_2d8cd88f35edd8b65b6d8d3a1023dd2225f87866"
}
```

`grit serve grant`:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `user` | string | The email address of the user given access. |
| `repository` | string | The repository name, without `.git`. |
| `access` | string | `read` or `write`. |

<!-- schema: serve.grant -->

```json
{
  "user": "bob@example.com",
  "repository": "demo",
  "access": "read"
}
```

`grit serve users`:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `database` | string | The user database read. |
| `users` | array | Every user, sorted by email address. |
| `users[].email` | string | The user's email address. |
| `users[].admin` | boolean | Admins read and write every repository. |
| `users[].temporary_password` | boolean | The user still has a generated password and must choose their own at the next sign-in. |
| `users[].tokens` | integer | How many access tokens the user has. |
| `users[].grants` | array | Repository grants, sorted by repository: `repository` and `access` (`read` or `write`). |

<!-- schema: serve.users -->

```json
{
  "database": "/srv/git/grit-serve.db",
  "users": [
    {
      "email": "admin@example.com",
      "admin": true,
      "temporary_password": false,
      "tokens": 1,
      "grants": []
    },
    {
      "email": "bob@example.com",
      "admin": false,
      "temporary_password": true,
      "tokens": 2,
      "grants": [
        {
          "repository": "app",
          "access": "write"
        },
        {
          "repository": "docs",
          "access": "read"
        }
      ]
    }
  ]
}
```

## Markdown output

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output.

Schema: [v1](https://grit-scm.com/docs/serve/schemas/serve/v1.json/index.md) · [serve.add-user v1](https://grit-scm.com/docs/serve/schemas/serve.add-user/v1.json/index.md) · [serve.token v1](https://grit-scm.com/docs/serve/schemas/serve.token/v1.json/index.md) · [serve.grant v1](https://grit-scm.com/docs/serve/schemas/serve.grant/v1.json/index.md) · [serve.users v1](https://grit-scm.com/docs/serve/schemas/serve.users/v1.json/index.md)

Markdown uses headings, bullet lists, and tables; pipe characters inside table cells are escaped. See the JSON output section for the stable field contract.

```text
## Serve users

Database: `/srv/git/grit-serve.db`

| User | Tokens | Access |
| --- | ---: | --- |
| `admin@example.com` | 1 | all repositories (admin) |
| `bob@example.com` | 2 | app (write), docs (read) |
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)): no database, already set up, unknown user, an invalid email address or too short a password, or the server could not start. |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.

## See also

[`auth`](https://grit-scm.com/docs/auth/index.md) · [`push`](https://grit-scm.com/docs/push/index.md) · [`fetch`](https://grit-scm.com/docs/fetch/index.md) · [`clone`](https://grit-scm.com/docs/clone/index.md) · [`upload-pack`](https://grit-scm.com/docs/upload-pack/index.md) · [`receive-pack`](https://grit-scm.com/docs/receive-pack/index.md)

# https://grit-scm.com/docs/checkin/index.md

# grit checkin

> Send a snapshot checkout's branches back to the server, rebuilt on its real history.

## Synopsis

```text
grit checkin [<branch>...] [-f|--force]
```

## Description

In a [snapshot checkout](https://grit-scm.com/docs/checkout/index.md), your commits sit on a snapshot commit that holds only the checkout's paths. `grit checkin` sends branches back to the server it came from, which **grafts** them onto its real history: it replays each commit's changes onto the full tree of the real commit the snapshot stands for, keeping the commit's author, date and message. On the server, the branch is then an ordinary branch whose parent is the real commit, with the whole tree — files outside your checkout's paths stay as the target branch has them.

With no branches named, every local branch with commits on top of the snapshot is checked in; when there is none, `grit checkin` says there is nothing to check in and succeeds. The branch's commits are first pushed to `refs/checkouts/<id>/out/heads/<branch>` on the server the checkout was made from (a large push uses the [resumable upload](https://grit-scm.com/docs/push/index.md#large-pushes)), then grafted. That push always goes to the URL the checkout was made from, even if `origin` now points elsewhere. A plain `git push` or `grit push` in a checkout pushes to the same place, so it never puts raw snapshot commits on the server's real branches; run `grit checkin` to graft what you pushed. Grafts are deterministic: checking the same commits in again changes nothing.

A grafted commit has a new tree and new parents, so a signature (`gpgsig`) or merged tag (`mergetag`) it carried no longer holds and is dropped; every other header is kept. A merge commit, such as the one [`grit pull --no-rebase`](https://grit-scm.com/docs/pull/index.md) makes, is grafted onto a three-way merge of its parents' grafts: what the target changed outside your paths since your older snapshot is kept, and inside your paths the merge's own result wins. A file that replaces a directory (or the other way round) checks in like any other change.

The resumable push during check-in can be interrupted with Ctrl+C (or `SIGTERM` / `SIGHUP` on Unix); grit exits with `error: operation cancelled` and code **130** without leaving the server in a half-applied graft state from this command.

Check-ins need write access to the repository.

### Change ids

Commits made with `grit commit` carry a `change-id` header, and `grit rebase` keeps it, so the server can tell a rebased copy of one of its commits from new work. Commits made with plain `git` (by an editor, an agent or a script) have none, so before anything is pushed, `grit checkin` gives every commit on the branches it checks in, above the snapshot, that lacks one the id derived from its own commit id: the id `grit log` already shows for it. The branch is rewritten with it (commits on top move to the new parents and keep their ids), and the output says so (`· gave 1 commit made with git a change id`). Only the header is added (a signature, which no longer holds, is dropped), so trees, the index and the worktree stay as they are. Nothing is rewritten under the snapshot, in remote-tracking refs, in commits that were already integrated, or when `grit.changeIds` is `false`, and nothing at all while a rebase, merge, cherry-pick or revert (one paused between its commits too) is in progress in any of the checkout's worktrees; the check-in then sends the commits as they are. The server gives a commit that reaches it without an id the same derived id when it grafts it. Plain `git rebase` drops the header, so when you share a branch, rebase it with `grit rebase`, or bring it up to date with [`grit pull <branch>`](https://grit-scm.com/docs/pull/index.md#a-server-branch-in-a-snapshot-checkout).

### Refused branches

A branch is refused when:

- **it is the target branch**, in any case (`Main` too): the branch the checkout was made from, or the branch the server's `HEAD` names now. Only [`grit integrate`](https://grit-scm.com/docs/integrate/index.md) and [`grit slice`](https://grit-scm.com/docs/slice/index.md) change the target (the server refuses plain pushes to it too); check your work in on another branch.
- **a commit changes a path outside your checkout's paths that the target holds differently.** A refresh never brings such a path into your checkout, so make that change from a checkout whose paths include it. The same goes for a directory replaced by a file when the target has files there your checkout can't see.
- **a merge commit's parents conflict outside your paths**, where your checkout can't resolve them.
- **the server's branch has commits yours doesn't.** Rebase onto the server's branch with `grit pull <branch>` and check in again, or pass `--force` to replace it.
- **its name differs only in case from a branch the server has**, on a server whose file system can't tell them apart.
- **a commit builds on none of your checkout's snapshots**, such as one made on the server's own history fetched with plain Git (`not_on_snapshot`). Take a branch of the server's with `grit pull <branch>` and build on that, or put your commits on the snapshot: `grit switch -c <new branch> origin/<target>`, then `grit pick <commits>`.

### When a branch moves

A branch the server already has moves when one of these holds, checked in this order, and the output names the rule (`rule` in `--json`):

- **fast-forward** (`fast_forward`): your branch has the server's branch in its history;
- **this checkout set it last** (`own_last_set`), so you are replacing your own work after an amend or rebase;
- **it keeps every commit the server's branch had** (`keeps_every_commit`), matched by change id: every commit of the server's branch that the target doesn't have is in yours, as a copy with the same id, perhaps rebased and with more on top. Say a teammate rebased the shared branch onto a newer `main` with `grit rebase` and force-pushed it, and you then add a commit to your copy: your check-in has every commit theirs had, so it goes through without `--force`. A copy only counts when it also has what the server's commit changed outside your checkout's paths, which you can't see: if the teammate amended the commit to change `docs/` as well and your checkout is of `src`, your copy would put `docs/` back, so the branch is refused as diverged instead;
- **`--force`** (`forced`), when none of the others holds.

### Sharing a branch

Checkouts of different paths can work on one branch. The server keeps a **graft log** of which real commit each checkout commit stands for: every check-in adds the commits it grafts, and so does [`grit pull <branch>`](https://grit-scm.com/docs/pull/index.md#a-server-branch-in-a-snapshot-checkout), which shows you the server's branch cut down to your paths. A commit you build on one of those grafts onto the real commit it stands for, so files outside your paths keep the other checkout's changes. Say Alice has `builtin/` and `Documentation/`, and Bob has `Documentation/` and `t/`:

1. Alice commits to `builtin/` and `Documentation/` on `blame-docs` and runs `grit checkin blame-docs`.
2. Bob runs `grit pull blame-docs`. He sees her `Documentation/` change; her `builtin/` change is on the server but not in his files.
3. Bob commits to `Documentation/` and `t/` on top and runs `grit checkin blame-docs`: a fast-forward, his commit on top of her real one, so `builtin/` keeps her change.
4. Alice runs `grit pull blame-docs` and gets his `Documentation/` change on top of her own commit, which comes back as it is. His `t/` change stays out of her files.

When someone else checks in to a branch you have too, your next check-in of it is refused as diverged; `grit pull <branch>` rebases your commits onto theirs, and the check-in after that is a fast-forward. A branch you pulled and haven't added to is left as it is (`unchanged`) when the server's has moved on since, so a plain `grit checkin` of your other work still succeeds (`· theirs has nothing new: the server's is ahead, at e32980a`); only `--force` would take the server's back to yours. The log also means checking a branch in again replays only its new commits. A check-in whose grafts the server can't record (say its disk is full) still sets the branch; the server logs the failure, and later grafts of those commits walk the history again.

When several checkouts check in the same branch at once, they take turns: the first sets it, and the others are refused because the server's branch now has commits they don't. On a server whose repository keeps reflogs (Git's default when it has a worktree), every branch a check-in sets gets a `checkin: from checkout <id>` reflog entry.

## Options

| Option | Description |
| --- | --- |
| `<branch>...` | Branches to check in. Defaults to every branch with commits on top of the snapshot. |
| `-f`, `--force` | Replace a server branch even where that drops commits it has. |

## Examples

```console
$ echo a2 > src/a.rs && grit add src/a.rs && grit commit -m "Change a"
$ grit checkin
✓ alice/elm-orchid created on the server at 7fb21e5 (1 commit)
$ grit checkin
· alice/elm-orchid already at 7fb21e5 on the server
```

A commit made with plain `git` is given a change id first; a teammate's rebase of the shared branch is replaced without `--force` when your branch still has all its commits:

```console
$ echo a3 > src/a.rs && git commit -qam "Change a again"
$ grit checkin
· gave 1 commit made with git a change id
✓ alice/elm-orchid updated on the server 7fb21e5 → 2c41d0e (1 commit; fast-forward)
$ grit checkin shared
✓ shared updated on the server 9a4b911 → c41d0e2 (2 commits; rebased, keeps every commit the server's branch had)
```

```console
$ grit checkout http://127.0.0.1:8080/demo.git -p src --into fresh && cd fresh
$ grit checkin
· nothing to check in: no branch has commits on top of the snapshot
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/checkin/schemas/checkin/v1.json/index.md)

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `url` | string | The server repository, with any `user:password@` removed. |
| `gave_change_ids` | integer | Commits made with plain `git` that were given a change id before the check-in (their branches were rewritten); `0` when none needed one. |
| `branches` | array | One entry per branch (empty when there was nothing to check in): `name`, `status` (`created`, `updated`, `unchanged` or `refused`; `unchanged` when the server's branch was at the graft already or ahead of it), `grafted` (the server commit the branch became), `previous` (where the server's branch was), `commits` (commits replayed), `rule` for an updated branch, and for a refused branch `message` (why, in words) and `reason`. |
| `branches[].rule` | string or omitted | What let an `updated` branch move: `fast_forward`, `own_last_set` (this checkout set it last), `keeps_every_commit` (a rebase that keeps every commit the server's branch had, by change id) or `forced`. |
| `branches[].reason` | string | The kind of refusal: `target_branch`, `conflict` (a path the target holds differently), `merge_conflict`, `diverged` (the server's branch has commits yours doesn't), `case_conflict`, `not_on_snapshot`, `not_pushed`, `invalid_name` or `invalid_tip`. |
| `refused` | boolean | Whether any branch was refused; the exit status is then `1`. |

```json
{
  "url": "http://127.0.0.1:8080/demo.git",
  "gave_change_ids": 0,
  "branches": [
    {
      "name": "alice/elm-orchid",
      "status": "created",
      "grafted": "7fb21e5a0c1e4f7d9b2e6a3c8d0f1e2a3b4c5d6e",
      "commits": 1
    }
  ],
  "refused": false
}
```

An update allowed by the change-id rule, after a commit made with `git` was given an id:

```json
{
  "url": "http://127.0.0.1:8080/demo.git",
  "gave_change_ids": 1,
  "branches": [
    {
      "name": "shared",
      "status": "updated",
      "grafted": "c41d0e2b9a8f7e6d5c4b3a2f1e0d9c8b7a6f5e4d",
      "previous": "9a4b9113f0c1e4f7d9b2e6a3c8d0f1e2a3b4c5d6",
      "commits": 2,
      "rule": "keeps_every_commit"
    }
  ],
  "refused": false
}
```

A refused branch, and a check-in with nothing to send:

```json
{
  "url": "http://127.0.0.1:8080/demo.git",
  "gave_change_ids": 0,
  "branches": [
    {
      "name": "shared",
      "status": "refused",
      "previous": "9a4b9113f0c1e4f7d9b2e6a3c8d0f1e2a3b4c5d6",
      "commits": 0,
      "message": "the server's shared is at 9a4b9113f0c1, which has commits this checkout doesn't; rebase onto it with `grit pull shared` and check in again, or check in with --force to replace it",
      "reason": "diverged"
    }
  ],
  "refused": true
}
```

```json
{
  "url": "http://127.0.0.1:8080/demo.git",
  "gave_change_ids": 0,
  "branches": [],
  "refused": false
}
```

## Markdown output

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output.

Schema: [v1](https://grit-scm.com/docs/checkin/schemas/checkin/v1.json/index.md)

```markdown
## Check-in to `http://127.0.0.1:8080/demo.git`

- Change ids: gave 1 commit made with git a change id

| Branch | Status | Server commit | Commits | Rule |
| --- | --- | --- | ---: | --- |
| `alice/elm-orchid` | created | `7fb21e5a0c1e4f7d9b2e6a3c8d0f1e2a3b4c5d6e` | 1 |  |
| `shared` | updated | `c41d0e2b9a8f7e6d5c4b3a2f1e0d9c8b7a6f5e4d` | 2 | rebased, keeps every commit the server's branch had |
```

## Exit status

| Code | Meaning |
| --- | --- |
| `0` | Every branch was checked in (or was already there), or there was nothing to check in. |
| `1` | A branch was refused, or this is not a snapshot checkout. |

## See also

- [`grit checkout`](https://grit-scm.com/docs/checkout/index.md), [`grit integrate`](https://grit-scm.com/docs/integrate/index.md), [`grit pull`](https://grit-scm.com/docs/pull/index.md).

# https://grit-scm.com/docs/integrate/index.md

# grit integrate

> Merge a branch into the server's target branch, from a snapshot checkout or a clone of a hosted project.

## Synopsis

```text
grit integrate <branch> [--without <user>...]
```

## Description

In a [snapshot checkout](https://grit-scm.com/docs/checkout/index.md), the target branch only changes on the server. `grit integrate <branch>`:

1. **checks the branch in** first when you have it here, after giving its commits made with plain `git` a change id (see [`grit checkin`](https://grit-scm.com/docs/checkin/index.md#change-ids));
2. **merges it into the target branch on the server**, with a merge commit by you, when it merges without conflicts. The merge is by the author your own commits get (`GIT_AUTHOR_NAME` and `GIT_AUTHOR_EMAIL`, then `author.*` and `user.*` config, as [`grit commit`](https://grit-scm.com/docs/commit/index.md) has it), or the signed-in user when none is set; the server cleans `<`, `>` and line breaks out of the name and email. A branch that conflicts is not merged: the error names the files and tells you to run [`grit pull`](https://grit-scm.com/docs/pull/index.md) on the checkout, then integrate again. A branch the target already has is left alone;
3. **refreshes this checkout** onto the new target, as [`grit pull`](https://grit-scm.com/docs/pull/index.md#in-a-snapshot-checkout) does. The branch's commits are in the new snapshot now, but not as its ancestors (a snapshot is one commit standing for the target's tree), so they are never replayed: replaying them one by one could conflict with themselves, as three commits editing one line would against a snapshot that has the last edit. Instead:
   - **when you are on the branch**, it moves to the new snapshot, keeping uncommitted and untracked changes as `git reset --keep` does (`refresh.result` is `landed`);
   - **when you are on a branch built on it**, only that branch's own commits are rebased onto the new snapshot, as `git rebase --onto origin/<target> <integrated tip>` would;
   - **other branches**: one whose commits were all integrated follows to the new snapshot, like a local branch named after the target with no commits of its own; ones with work of their own still on an older snapshot are named, with how to bring each up (`grit switch <branch>`, then `grit pull`, which leaves the integrated commits out too). With `HEAD` detached, only `origin/<target>` moves.

   The checkout remembers the integrated tip (in its marker) until no branch, and no worktree's detached `HEAD`, builds on it any more, so later refreshes leave those commits out as well, in any of the checkout's worktrees;
4. **moves you to a new branch** when you were on the branch it merged: the server reserves a fresh work branch name for the checkout (from your `user.email`, numbered past names it has given out, as [`grit checkout`](https://grit-scm.com/docs/checkout/index.md) does), and the merged branch is renamed to it. The merged branch is gone here; it stays on the server. New commits then check in as a new branch instead of adding to one the target already has.

The server merges into its current target, the branch its `HEAD` names, while a checkout follows the branch it was made from. When the two differ (the server's `HEAD` was moved to another branch since), the merge is not in this checkout's snapshots: the refresh in step 3 treats the branch like any other, nothing is remembered, step 4 is skipped, and the branch keeps its commits here, so refreshes rebase them onto newer snapshots as usual. The output says which branch the checkout follows (`follows`).

The branch can also be one somebody else checked in or pushed: a plain push to the target itself is refused (see [`grit serve`](https://grit-scm.com/docs/serve/index.md#snapshot-checkouts)), so push to another branch and integrate that. Integrating needs write access. Where the server's repository keeps reflogs, the move of the target is logged as `integrate: Merge branch '<branch>' into <target>`, so `git reflog <target>` on the server shows it.

These are refused, and the target is left alone:

- **the target branch itself** (in any case): name the branch to merge into it;
- **a name that is not a valid branch name**, such as one with `..` in it;
- **a branch the server doesn't have**: check it in first;
- **a branch that shares no history with the target**, such as an orphan branch, or raw checkout commits pushed straight to a branch (they sit on a snapshot commit rather than on the real history): check them in with [`grit checkin`](https://grit-scm.com/docs/checkin/index.md) instead;
- **a merge that would overwrite uncommitted changes in the server's worktree**, when the server's repository has the target checked out: the server's worktree moves with each integration (keeping uncommitted changes there, as `git reset --keep` does), so commit or stash those changes on the server first.

Integrations, and [slice](https://grit-scm.com/docs/slice/index.md) changes, take turns on the server: several at once all merge, each onto the target the one before left. Each is merged again if the target moves while it is made, so none is lost or refused for coming second.

### In a clone of a hosted project

In a clone (not a snapshot checkout) of a project on a grit hosting server such as [GitButler Code](https://code.gitbutler.com), `grit integrate <branch>`:

1. **pushes the branch to your space** (`<you>/<project>`), as [`grit sync`](https://grit-scm.com/docs/sync/index.md) would, setting the clone up for it first when it isn't yet;
2. **asks the server to merge it into the target**. For your copy of an organization's project, that is the organization's target branch (usually `main`): the server opens a pull request from the branch, or uses the open one, and integrates it at once. Only members of the organization may; anyone else is told to propose the branch instead, with the link. For a project of your own, it is the project's own target branch. A branch that conflicts is refused with the conflicting files, and nothing changes;
3. **fetches `origin` and fast-forwards the target branch here** to the new tip (`local`).

The branch you are on stays as it is; once merged, [`grit sync`](https://grit-scm.com/docs/sync/index.md) stops pushing it.

**A [shared](https://grit-scm.com/docs/share/index.md) branch** merges your head of it. Every other member's head has to be in yours first: when one has changes yours doesn't (matched by change id), nothing is merged, and the refusal names each such member and their commits. Take them with [`grit sync`](https://grit-scm.com/docs/sync/index.md) and integrate again, or pass `--without <user>` to merge without them; their changes stay in their copy, as a branch nobody shares. Once merged, the share is over: the branch is deleted from every member's copy (except the heads of members left out), every member is told, and `unshared` lists them. The server remembers what was merged for 14 days, so a later push of the branch's name that brings those commits is reported as `pushed_to_integrated` (see [`grit share`](https://grit-scm.com/docs/share/index.md#after-integrating)).

## Options

| Option | Description |
| --- | --- |
| `<branch>` | The branch to merge into the target. |
| `--without <user>` | For a shared branch: merge without waiting for this member's changes, which stay in their copy. Repeatable. |

## Examples

Integrating the branch you are on, with an untracked file you haven't committed:

```console
$ grit integrate alice/elm-orchid
✓ alice/elm-orchid created on the server at 538e7ad (2 commits)
✓ Merged alice/elm-orchid into main on the server: d08f98a → 7f51f16 (2 commits)
main moved d08f98a → 7f51f16; new snapshot 2b12f15 at origin/main
  1 file changed, 1 insertion(+), 1 deletion(-) in this checkout's paths
Moved to origin/main (2b12f15), which has this branch's commits; uncommitted changes are kept.
alice/elm-orchid is in main now, so it's gone here. You're on alice/maple-elm, a new branch.
$ grit status --short
?? src/draft.rs
```

The merge is reported even when the refresh after it fails, here because of an uncommitted change to a file the target changed too. The exit status is then `1`:

```console
$ grit integrate alice/maple-elm
✓ alice/maple-elm created on the server at 1c3e9a0 (1 commit)
✓ Merged alice/maple-elm into main on the server: 7f51f16 → 9a0b1c2 (1 commit)
✗ Refreshing this checkout failed: local changes would be overwritten: src/deep/b.rs
  The merge stands on the server; fix that, then run `grit integrate alice/maple-elm` again to finish.
```

Running `grit integrate` again then finds the target already has the branch (`already_integrated`), refreshes, and moves you to a new branch. That also finishes an integration whose refresh worked but whose move to a new branch failed (the server could not reserve a name, say): the branch is at the new snapshot with nothing of its own, so it is renamed. A refresh whose rebase stops on a conflict reports the conflict as [`grit pull`](https://grit-scm.com/docs/pull/index.md) does, and also exits `1`.

When the server's `HEAD` names another branch than the one this checkout follows:

```console
$ grit integrate alice/elm-orchid
✓ alice/elm-orchid created on the server at 538e7ad (2 commits)
✓ Merged alice/elm-orchid into develop on the server: d08f98a → 7f51f16 (2 commits)
· This checkout follows main, not develop, so alice/elm-orchid keeps its commits here.
main has not moved since this checkout's last snapshot (still at d08f98a).
Already up to date.
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/integrate/schemas/integrate/v1.json/index.md)

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `name` | string | The branch merged. |
| `target` | string | The server's target branch. |
| `status` | string | `merged` or `already_integrated`. |
| `previous` | string | Where the target was. |
| `head` | string | Where it is now. |
| `commits` | integer | The branch's commits the merge brought in. |
| `checkin` | object or omitted | The check-in done first (see [`grit checkin`](https://grit-scm.com/docs/checkin/index.md)'s JSON). |
| `refresh` | object or omitted | The refresh done after (see [`grit pull`](https://grit-scm.com/docs/pull/index.md)'s JSON); `refresh.result` is `landed` when the branch you were on moved to the new snapshot. Omitted when the refresh failed. |
| `moved_to` | string or omitted | The new work branch you are on, when you were on the branch merged (it is gone here and stays on the server). |
| `follows` | string or omitted | The branch this checkout follows, when the server merged into another one (`target`, the branch its `HEAD` names now): the merge is not in this checkout's snapshots, so the branch keeps its commits here and you stay on it. |
| `refresh_error` | string or omitted | Why refreshing this checkout after the merge, or moving you to a new branch, failed. The merge stands; the exit status is `1`. |
| `project` | string or omitted | In a clone: the project merged into, `<owner>/<project>` (the organization's, for your copy of one). |
| `pull` | integer or omitted | In a clone: the pull request the merge went through, for a copy of an organization's project. |
| `url` | string or omitted | In a clone: the pull request's web page. |
| `local` | object or omitted | In a clone: the target branch here after the merge, as [`grit sync`](https://grit-scm.com/docs/sync/index.md)'s `target` reports it (`name`, `action`, `tip`). |
| `unshared` | array of strings or omitted | For a [shared](https://grit-scm.com/docs/share/index.md) branch: the other members. Integrating ended the share and deleted the branch from their copies. |

```json
{
  "name": "alice/elm-orchid",
  "target": "main",
  "status": "merged",
  "previous": "d08f98a93fcf6c0bd1f4d7e1c5a0b9e8f7d6c5b4",
  "head": "7f51f16b2cb0e4d3c2b1a0f9e8d7c6b5a4f3e2d1",
  "commits": 2,
  "refresh": {
    "result": "landed",
    "branch": "origin/main",
    "oid": "2b12f15c0d9e8f7a6b5c4d3e2f1a0b9c8d7e6f5a",
    "refresh": {
      "target": "main",
      "upstream_ref": "refs/remotes/origin/main",
      "base": "7f51f16b2cb0e4d3c2b1a0f9e8d7c6b5a4f3e2d1",
      "snapshot": "2b12f15c0d9e8f7a6b5c4d3e2f1a0b9c8d7e6f5a",
      "previous_base": "d08f98a93fcf6c0bd1f4d7e1c5a0b9e8f7d6c5b4",
      "previous_snapshot": "5c892b5783dbdeb57f7228eb6a13ffb2fa17d832",
      "moved": true,
      "changes": { "files": 1, "insertions": 1, "deletions": 1 },
      "dry_run": false,
      "followed": [],
      "behind": [],
      "gave_change_ids": 0
    }
  },
  "moved_to": "alice/maple-elm"
}
```

When the refresh fails, `refresh` is omitted and `refresh_error` says why:

```json
{
  "name": "alice/maple-elm",
  "target": "main",
  "status": "merged",
  "previous": "7f51f16b2cb0e4d3c2b1a0f9e8d7c6b5a4f3e2d1",
  "head": "9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b",
  "commits": 1,
  "refresh_error": "local changes would be overwritten: src/deep/b.rs"
}
```

## Markdown output

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output.

Schema: [v1](https://grit-scm.com/docs/integrate/schemas/integrate/v1.json/index.md)

The check-in done first, and the refresh done after, have their own sections, as [`grit checkin`](https://grit-scm.com/docs/checkin/index.md) and [`grit pull`](https://grit-scm.com/docs/pull/index.md) render them; a move to a new branch, a merge into another branch than the one this checkout follows, and a failed refresh are listed with the merge:

```markdown
## Check-in to `http://127.0.0.1:8080/demo.git`

| Branch | Status | Server commit | Commits | Rule |
| --- | --- | --- | ---: | --- |
| `alice/elm-orchid` | created | `538e7ad0c3b2a1f0e9d8c7b6a5f4e3d2c1b0a9f8` | 2 |  |

## Integrate `alice/elm-orchid` into `main`

- **status**: merged
- **previous**: `d08f98a93fcf6c0bd1f4d7e1c5a0b9e8f7d6c5b4`
- **head**: `7f51f16b2cb0e4d3c2b1a0f9e8d7c6b5a4f3e2d1`
- **commits**: 2
- **moved to**: `alice/maple-elm`, a new branch (`alice/elm-orchid` is in `main` now, so it's gone here)

## Pull

- Refresh: **`main`** moved `d08f98a` → `7f51f16` · new snapshot `2b12f15` at `refs/remotes/origin/main` · 1 file changed, 1 insertion(+), 1 deletion(-) in this checkout's paths
- Moved to **`origin/main`** · `2b12f15`, which has this branch's commits; uncommitted changes kept
```

A merge into another branch than the one this checkout follows:

```markdown
- **follows**: `main` (the merge went into `develop`, so `alice/elm-orchid` keeps its commits here)
```

A failed refresh:

```markdown
- **refresh failed**: local changes would be overwritten: src/deep/b.rs → the merge stands on the server; fix that, then `grit integrate alice/maple-elm` again to finish
```

## Exit status

| Code | Meaning |
| --- | --- |
| `0` | The branch was merged, or the target already had it, and the checkout was refreshed. |
| `1` | The branch was merged (or the target had it), but the refresh after failed (`refresh_error`) or stopped (`refresh.result` is `rebase_stopped`, `conflicts`, `refused_not_ff` or `autostash_conflict`): the output says so and what to do. Or nothing was merged: the branch conflicts with the target, shares no history with it, is the target, is not a valid branch name, could not be checked in, or does not exist on the server; uncommitted changes in the server's worktree block the merge; in a clone, you aren't a member of the organization, the branch couldn't be pushed to your space, or it is a shared branch another member's head has changes of that yours lacks (pass `--without <user>` to merge anyway); or this is neither a snapshot checkout nor a clone of a hosted project. |

## See also

- [`grit checkin`](https://grit-scm.com/docs/checkin/index.md), [`grit pull`](https://grit-scm.com/docs/pull/index.md), [`grit checkout`](https://grit-scm.com/docs/checkout/index.md).

# https://grit-scm.com/docs/slice/index.md

# grit slice

> Name sets of paths to check out together, kept on the server's target branch.

## Synopsis

```text
grit slice list [--url <url>]
grit slice new <name> -p|--path <path>... [-d|--description <text>] [--url <url>]
grit slice edit <name> [--add <path>]... [--remove <path>]... [-d|--description <text>] [--url <url>]
grit slice delete <name> [--url <url>]
```

## Description

A slice names a set of paths so people check out the same part of a repository without listing it each time: `grit checkout <url> <slice>` checks out a slice's paths (into a directory named after the slice), and `--path` adds more.

Slices live in `.grit/slices.toml` on the server's target branch, so they're versioned with the code they describe and every checkout sees the same ones:

```toml
[slices.desktop]
description = "The desktop app and its UI package"
paths = ["apps/desktop", "packages/ui"]
```

Each `new`, `edit` or `delete` is one commit on the target branch, made by the server, by you: the author your own commits get (`GIT_AUTHOR_NAME` and `GIT_AUTHOR_EMAIL`, then `author.*` and `user.*` config, as [`grit commit`](https://grit-scm.com/docs/commit/index.md) has it), or the signed-in user when none is set. The server cleans `<`, `>` and line breaks out of the name and email. The paths must exist on the target. Slice changes and [integrations](https://grit-scm.com/docs/integrate/index.md) take turns on the server, so several at once all land, each on the target the one before left; each is checked again on the target it lands on (a name taken meanwhile is refused). When the server's repository has the target checked out in a worktree, the worktree moves with the commit, keeping uncommitted changes there; changes the commit would overwrite refuse it. Inside a [snapshot checkout](https://grit-scm.com/docs/checkout/index.md), `grit slice` talks to the server the checkout came from; elsewhere, pass `--url`. Changing slices needs write access; listing them needs read access. A checkout made from a slice keeps its paths when the slice changes later.

## Options

| Option | Description |
| --- | --- |
| `list` | List the slices. |
| `new <name>` | Make a slice. Names use letters, digits, `-`, `_` and `.`. |
| `edit <name>` | Change a slice's paths or description. |
| `delete <name>` | Delete a slice. |
| `-p`, `--path <path>` | With `new`: a path in the slice (repeatable, at least one). |
| `--add <path>` | With `edit`: add a path (repeatable). |
| `--remove <path>` | With `edit`: remove a path (repeatable). |
| `-d`, `--description <text>` | With `new` or `edit`: what the slice is for. |
| `--url <url>` | The repository whose slices to use. Defaults to the checkout you are in. |

## Examples

```console
$ grit slice new code -p src/deep -d "The deep code"
✓ Added slice code on main: 7f51f16 → 0416f7e
  src/deep
$ grit slice edit code --add docs
✓ Changed slice code on main: 0416f7e → 2f44ddc
  docs, src/deep
$ grit slice list
code  docs, src/deep
      The deep code
$ grit checkout http://127.0.0.1:8080/demo.git code
```

## JSON output

Schema: [slice.list v1](https://grit-scm.com/docs/slice/schemas/slice.list/v1.json/index.md) · [slice.new v1](https://grit-scm.com/docs/slice/schemas/slice.new/v1.json/index.md) · [slice.edit v1](https://grit-scm.com/docs/slice/schemas/slice.edit/v1.json/index.md) · [slice.delete v1](https://grit-scm.com/docs/slice/schemas/slice.delete/v1.json/index.md)

`grit slice list`:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `url` | string | The server repository, with any `user:password@` removed. |
| `target` | string | The target branch the slices are on. |
| `head` | string | Where it is. |
| `slices` | array | Each slice's `name`, `description` (when set) and `paths`. |

<!-- schema: slice.list -->

```json
{
  "url": "http://127.0.0.1:8080/demo.git",
  "target": "main",
  "head": "2f44ddc44831f89c598c98491de99dab2af647c8",
  "slices": [
    { "name": "code", "description": "The deep code", "paths": ["docs", "src/deep"] }
  ]
}
```

`grit slice new`, `edit` and `delete`:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `action` | string | `new`, `edit` or `delete`. |
| `name` | string | The slice's name. |
| `slice` | object or omitted | The slice as it is now: `name`, `description` and `paths`. Omitted once deleted. |
| `target` | string | The target branch. |
| `previous` | string | Where it was. |
| `head` | string | Where it is: the server's commit changing the slices file (`previous` when nothing changed). |

<!-- schema: slice.new -->

```json
{
  "action": "new",
  "name": "code",
  "slice": { "name": "code", "description": "The deep code", "paths": ["src/deep"] },
  "target": "main",
  "previous": "7f51f16b2cb0e4d3c2b1a0f9e8d7c6b5a4f3e2d1",
  "head": "0416f7e1b2c3d4e5f60718293a4b5c6d7e8f9012"
}
```

## Markdown output

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output.

Schema: [slice.list v1](https://grit-scm.com/docs/slice/schemas/slice.list/v1.json/index.md) · [slice.new v1](https://grit-scm.com/docs/slice/schemas/slice.new/v1.json/index.md) · [slice.edit v1](https://grit-scm.com/docs/slice/schemas/slice.edit/v1.json/index.md) · [slice.delete v1](https://grit-scm.com/docs/slice/schemas/slice.delete/v1.json/index.md)

```markdown
## Slices on `main`

| Slice | Paths | Description |
| --- | --- | --- |
| `code` | `docs`, `src/deep` | The deep code |
```

## Exit status

| Code | Meaning |
| --- | --- |
| `0` | Success. |
| `1` | The slice exists (`new`) or doesn't (`edit`, `delete`), a path is not on the target, the name is invalid, uncommitted changes in the server's worktree block the commit, the server offers no snapshot checkouts, or no server was named outside a checkout. |

## See also

- [`grit checkout`](https://grit-scm.com/docs/checkout/index.md), [`grit serve`](https://grit-scm.com/docs/serve/index.md).

# https://grit-scm.com/docs/sync/index.md

# grit sync

> Push and pull every active branch between a clone and your space on a grit hosting server.

## Synopsis

```text
grit sync
```

## Description

On a grit hosting server such as [GitButler Code](https://code.gitbutler.com), your work on a project lives in your space, `<you>/<project>`, private to you. An organization's projects (`<domain>/<project>`) are read-only: you work in a copy of one in your space, which follows the organization's branches, and [integrate](https://grit-scm.com/docs/integrate/index.md) from there.

`grit sync`, in a clone of a project on such a server:

1. **asks the server where your work goes**: the project in your space for the one `origin` names. For an organization's project, the server makes your copy when you have none yet. The clone is then set up to push there: a `space` remote fetches from it, and `remote.origin.pushurl` points at it, so a plain [`grit push`](https://grit-scm.com/docs/push/index.md) (or `git push`) sends branches to your space while fetches still come from the organization. [`grit clone`](https://grit-scm.com/docs/clone/index.md) of a GitButler Code project does this setup too, when you are signed in;
2. **fetches** `origin` and your space;
3. **fast-forwards the target branch** (the branch work is integrated into, usually `main`) to the project's. A target with commits of its own is left alone: it changes only by integrating;
4. **brings down your space's branches**: one you don't have here is made, tracking your space's; one that is behind is fast-forwarded (when it is checked out, the working tree follows, as `grit merge --ff-only` would);
5. **pushes every active branch** to your space: every branch but the target, the branches your space follows from upstream (read-only there), and branches already merged into the target, such as one you integrated.

A branch that has commits here and in your space that the other lacks is left alone and reported as `diverged`: switch to it, run [`grit pull --rebase`](https://grit-scm.com/docs/pull/index.md), and sync again. Nothing is ever force-pushed.

### Shared branches

A branch you [share](https://grit-scm.com/docs/share/index.md) with other people works differently, because each member has their own head of it and only you move yours:

- the other members' heads are fetched too, as `<remote>/shared/<branch>/<user>`, and reported under the branch with how each compares with yours;
- when another member's head builds on yours, your branch is fast-forwarded to it (to the furthest such head, when they are on one line) and then pushed as your head (`took bob's head, which builds on yours`);
- when your branch here and your head in your space have diverged (you amended or rebased here), your head is replaced: it is yours alone, and the server keeps the old one in the share's log;
- a member's head that has diverged from yours, but goes together with it without losing anything, is combined with yours, and the result pushed (`combined with bob's head, ...`). One that needs a decision is reported with its options (see [`grit share resolve`](https://grit-scm.com/docs/share/index.md#resolving-a-divergence)), and sync exits `3`.

Sync works in a clone. In a [snapshot checkout](https://grit-scm.com/docs/checkout/index.md), send branches with [`grit checkin`](https://grit-scm.com/docs/checkin/index.md) and update with [`grit pull`](https://grit-scm.com/docs/pull/index.md). You need to be signed in to the server ([`grit login`](https://grit-scm.com/docs/auth/index.md)).

## Options

`grit sync` takes no options besides the [global options](https://grit-scm.com/docs/global-options/index.md).

## Examples

A clone of an organization's project, the first time:

```console
$ grit clone https://code.gitbutler.com/example.com/widget
$ cd widget
$ grit switch -c feature
$ grit commit -am "Make widgets faster"
$ grit sync
Syncing alice/widget (a copy of example.com/widget)
· Pushes from this clone now go to alice/widget (remote `space`)
✓ main fast-forwarded to 7f51f16
✓ feature pushed 538e7ad
✓ docs pulled 1c3e9a0
✓ from-laptop created 9a0b1c2
✗ spike diverged 2b12f15
  spike and space/spike each have commits the other lacks: switch to it and run `grit pull --rebase`, then sync again
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/sync/schemas/sync/v1.json/index.md)

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `space` | string | Your space's project, `<you>/<project>`. |
| `upstream` | string or omitted | The project it follows, for a copy of an organization's project. |
| `remote` | string | The remote branches are pushed to and pulled from: `origin` when it is your space, else `space`. |
| `configured` | boolean | Whether this run set the clone up to push to your space. |
| `target` | object or omitted | The target branch: `name`, `action` (`up_to_date`, `fast_forwarded`, `created`, `ahead` or `diverged`) and `tip`. |
| `branches` | array | Each active branch: `name`, `action` (`pushed`, `pulled`, `created`, `up_to_date`, `diverged` or `refused`), `tip`, a `message` for a divergence or refusal, and for a [shared](https://grit-scm.com/docs/share/index.md) branch `shared`: the other members' heads, each with `user`, `tip`, `relation` to your branch (`same`, `ahead`, `behind`, `diverged` or `unknown`), and for a head that diverged from yours `divergence`: `scenario` (a stable code such as `amended_both_conflicting`; see [Divergence scenarios](https://grit-scm.com/docs/share/index.md#divergence-scenarios)), `summary`, `needs_decision`, `base`, `changes` (each commit's `change`, `subject`, and what `you` and `them` did to it), `conflicts` and `also`. For a branch the sync made again after a share of it was integrated, `integrated`: the `pushed_to_integrated` report, as [`grit push`](https://grit-scm.com/docs/push/index.md) has it. |

```json
{
  "space": "alice/widget",
  "upstream": "example.com/widget",
  "remote": "space",
  "configured": false,
  "target": { "name": "main", "action": "up_to_date", "tip": "7f51f16b2cb0e4d3c2b1a0f9e8d7c6b5a4f3e2d1" },
  "branches": [
    { "name": "feature", "action": "pushed", "tip": "538e7ad0c3b2a1f0e9d8c7b6a5f4e3d2c1b0a9f8" }
  ]
}
```

## Markdown output

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output.

Schema: [v1](https://grit-scm.com/docs/sync/schemas/sync/v1.json/index.md)

```markdown
## Sync `alice/widget`

- **upstream**: `example.com/widget`
- **remote**: `space`
- **main**: fast-forwarded
- `feature`: pushed
- `spike`: diverged — spike and space/spike each have commits the other lacks: switch to it and run `grit pull --rebase`, then sync again
```

## Exit status

| Code | Meaning |
| --- | --- |
| `0` | Every active branch is in step with your space. |
| `1` | A branch diverged or a push was refused (the output names it), the target diverged from upstream, or sync could not run: not a clone of a hosted project, not signed in, or this is a snapshot checkout. |
| `3` | Everything else is in step, but another member's head of a [shared](https://grit-scm.com/docs/share/index.md) branch diverged from yours in a way someone has to decide about, or a branch was pushed again after it was integrated (`pushed_to_integrated`) (`needs_decision`). |

## See also

- [`grit integrate`](https://grit-scm.com/docs/integrate/index.md), [`grit push`](https://grit-scm.com/docs/push/index.md), [`grit clone`](https://grit-scm.com/docs/clone/index.md), [`grit login`](https://grit-scm.com/docs/auth/index.md).

# https://grit-scm.com/docs/share/index.md

# grit share

> Work on a branch together with other users of a grit hosting server, each with their own head of it.

## Synopsis

```text
grit share add <branch> [<user>|<email>...] [--link [--uses <n>|unlimited] [--expires <days>]] [--no-history] [--path <path>...]
grit share list [<branch>]
grit share accept <link>
grit share remove <branch> [<user>|<email>...]
grit share leave <branch>
grit share resolve <branch> [<option> [<name>]] [--with <user>]
grit share revoke <branch> <link-id>
```

## Description

On a grit hosting server such as [GitButler Code](https://code.gitbutler.com), your branches are private to your space. `grit share` lets other people work on one of them with you. A shared branch is in every member's space, and **each member has their own head of it**: only you move yours. Nobody's push can overwrite anyone else's work, so there is nothing to force, and every head anyone pushes is kept in the share's log on the server.

The other members' heads are fetched beside yours as `<remote>/shared/<branch>/<user>` (from the server's `refs/shared/<branch>/<user>`, which nobody pushes to). [`grit status`](https://grit-scm.com/docs/status/index.md) shows them under your branch, [`grit sync`](https://grit-scm.com/docs/sync/index.md) fast-forwards your branch to a member's head that builds on yours, and [`grit push`](https://grit-scm.com/docs/push/index.md) replaces your head after an amend or rebase without `--force` (it still checks that the server's head is the one you last fetched).

- **`grit share add <branch> <user>...`** shares a branch of your space with people, each of whom is emailed. Name them by user name or email address: an address that belongs to an account adds that account, and any other address is emailed an invitation. The invitation's link asks them to create an account, then shows them how to work on the branch with grit or plain git; it works once, for 30 days. A branch that isn't in your space yet, or differs there, is pushed first. Anyone on the branch can add people. Someone added by name gets their copy of the project (with the branch in it) the first time they fetch from their space: `grit clone https://<server>/<them>/<project>`, or `grit sync` in a clone they have.
- **`--no-history`** and **`--path <path>`** make it a [snapshot share](#snapshot-shares) for the people added (and the link): the branch's own history, without the rest of the project's, cut down to those paths.
- **`--link`** makes a share link instead (or as well): a URL anyone signed in can accept, in the browser or with `grit share accept`. A link works once and for 7 days unless you pass `--uses` (a number or `unlimited`) and `--expires` (1 to 30 days). The URL is shown only now; the server keeps only its hash.
- **`grit share list`** shows your shared branches: who is on each, where each head is, and how it compares with your branch here (`same as yours`, `has commits you don't`, `behind yours`, `diverged from yours`), and any open links.
- **`grit share accept <link>`** accepts a link: you are on the branch, and your copy of the project is made in your space. In a clone of the project it fetches the branch into it; anywhere else it clones your copy into a new directory.
- **`grit share remove <branch> <user>...`** removes people, and withdraws invitations to the email addresses you name. Only the person who shared the branch (or, for a copy of an organization's project, someone who can integrate into it) can remove people, and nobody can remove the person who shared it. With no users, it ends the share. Nobody loses work: each member's head stays a branch in their own space.
- **`grit share leave <branch>`** takes you off a branch; your head stays a branch in your space.
- **`grit share resolve <branch> [<option>]`** puts your head and another member's back together after they diverged (see [Resolving a divergence](#resolving-a-divergence)). Name the member with `--with` when several heads diverged from yours. For a branch pushed again after it was integrated, it takes `rebase`, `rename <name>` or `reshare` (see [After integrating](#after-integrating)).
- **`grit share revoke <branch> <link-id>`** stops a link from working. Link ids are in `grit share list`.

### Your copy

When the project is a copy of an organization's project, everyone's copy is a copy of that organization's project. Otherwise each member's copy holds just the shared branches and the sharer's default branch, read-only, as the base they build on; the sharer's other branches stay private.

### When heads differ

`grit sync` compares your branch with every other member's head:

- one that builds on yours: your branch is fast-forwarded to it (to the furthest such head, when they are on one line), and your head is pushed;
- one that your branch builds on: nothing to do;
- one that has diverged from yours: reported. Rebase onto it with `grit rebase <remote>/shared/<branch>/<user>` (or have them rebase onto yours) and sync again.

### Divergence scenarios

When another member's head has diverged from yours, `grit sync`, `grit status`, `grit share list` and `grit push` say what happened, commit by commit: for each commit, what you did and what they did (`unchanged`, `moved`, `reworded`, `amended`, `dropped`, `squashed`, `split`, `new`), matched by change id. The situation gets one of these codes, which scripts and agents can rely on. Some can be put together without losing anything; the rest need someone to decide, and `grit push` and `grit sync` exit with status `3` for them.

| Scenario | What happened | Needs a decision |
| --- | --- | --- |
| `added_both` | You both added commits on top of the same base, and they don't conflict. | no |
| `rewrote_one` | One of you rewrote commits (amended, reordered, split, squashed or dropped); the other only added on top. | no |
| `amended_both_compatible` | You both amended the same commit, without overlapping (or one changed only its message). | no |
| `amended_one_reordered_other` | One reordered commits; the other amended one of them. | no |
| `amended_different` | You each amended different commits. | no |
| `rebased_one` | One rebased onto a newer target; the other only changed commits. | no |
| `rebased_both` | You both rebased, onto different target commits. | no |
| `dropped_one` | One dropped a commit the other didn't touch. | no |
| `dropped_both` | You both dropped the same commit. | no |
| `split_one` | One split a commit the other didn't touch. | no |
| `squashed_one_added_other` | One squashed commits; the other added on top. | no |
| `squashed_one_amended_other` | One squashed a commit into another; the other amended it. | no |
| `split_one_amended_other` | One split a commit; the other's amendment of it fits one piece. | no |
| `amended_both_conflicting` | You both amended the same commit, and the edits overlap. | yes |
| `added_both_conflict` | You both added commits, which conflict with each other. | yes |
| `dropped_one_amended_other` | One deleted a commit; the other amended it. | yes |
| `reordered_both` | You both reordered the commits, into different orders. | yes |
| `split_both` | You both split the same commit, differently. | yes |
| `split_one_amended_other_spanning` | One split a commit; the other's amendment of it spans the pieces. | yes |
| `squashed_both_differently` | You both squashed commits, differently. | yes |
| `reset_one` | One head drops most of the branch, with or without new commits on top: perhaps an accidental reset. | yes |
| `merge_commit` | One head has a merge commit. | yes |
| `no_change_ids` | Commits made or rebased with plain `git` have no change ids, so an amend can't be told from a new commit. | yes |

Heads that haven't diverged are `same`, `ahead`, `behind`, `same_content` (the same changes as different commits) or `same_rewrite` (the same amend, drop or squash on both sides).

The comparison starts from the last head you both had, read from the reflogs of your branch and of their head here; without one, from where the two heads meet. Use `grit commit` and `grit rebase`, which keep change ids, so commits can be followed across amends.

### Resolving a divergence

Every divergence report lists its options, the recommended one first, each with the command that applies it and what it leaves out (`loses`, `null` when it keeps every change). What an option leaves out is never lost: every head anyone pushed stays in the share's log on the server.

| Option | What it does |
| --- | --- |
| `combine` | Every change from both heads, commit by commit: their commits kept as they are where possible, yours replayed on top, so they can fast-forward to the result. |
| `keep_both` | For a commit you both amended, differently: their head as it is, then your version as a commit of its own on top, so they can fast-forward to the result. |
| `keep_amended` / `drop` | For a commit one of you dropped and the other amended: keep the amended version, or drop it. |
| `my_order` / `their_order` | When you both reordered the commits. |
| `my_split` / `their_split` | When you both split a commit. |
| `restore` | When one head dropped most of the branch: the head that kept it, as it is, with the other head's new commits on top. |
| `keep_mine` / `keep_theirs` | One head as it is. |
| `resolve` | By hand: rebase onto their head (`grit rebase <remote>/shared/<branch>/<user>`), settle the conflicts, `grit rebase --continue`, and `grit push`. |

`grit share resolve <branch>` with no option applies `combine` when nothing would be lost; otherwise it lists the options and exits with status `3`. With an option, it moves your branch to the result (when the branch is checked out, as `grit reset --keep` does, keeping local changes or refusing) and pushes your head.

**Without asking.** When another member's head and yours can be put together without losing anything (any scenario that doesn't need a decision), `grit sync` and `grit push` do it themselves: they combine the two, move your branch, and push the result, and the other member's next `grit sync` fast-forwards to it. Only when someone has to decide do they stop, report the options, and exit `3`.

### Snapshot shares

`grit share add <branch> bob --path src/rpc` (or `--no-history` alone, for the whole tree) shares the branch without the project's history. bob's copy is a project of its own in his space that holds only what he may see:

- its base branch (`main`) is a **snapshot**: one commit standing for the base where the branch starts, cut down to his paths. Each path brings everything under it, plus the files directly in each directory above it (as Git's cone-mode sparse checkout does);
- the branch, and the other members' heads under `origin/shared/<branch>/<user>`, are their commits **projected** onto the snapshot, cut down the same way. So he has the branch's history, not the project's;
- when the base moves, his next fetch brings a new snapshot of it on top of the last one, and `grit sync` fast-forwards his base branch to it; to build on it, he rebases his branch onto it (`grit rebase origin/main`), as anyone would. His base branch is read-only.

He works with grit or plain git as usual. What he pushes is grafted back onto the real history as his head, so everyone with the whole branch gets full commits, with the files outside his paths as they were. A push that would undo changes outside his paths stays in his space, unshared, and the push's `remote:` lines say why with the code `outside_paths`:

- rewriting a commit (an amend, a rebase that drops it) that also changed files outside his paths. Add new commits on top instead;
- a commit that changes a file the base now holds differently outside his paths. Rebase onto the newest snapshot first.

A member with a snapshot share can add people only with the same view, and can't integrate the branch: someone with the whole branch does.

### After integrating

[`grit integrate`](https://grit-scm.com/docs/integrate/index.md) on a shared branch merges your head, once every other member's changes are in it (or the members whose aren't are left out with `--without`). Then the share is over: the branch is deleted from every member's copy and the server's `refs/shared/` heads with it, and everyone is told. Your clone keeps its local branch; [`grit sync`](https://grit-scm.com/docs/sync/index.md) leaves it alone once its commits are on the target.

The server remembers the integration for 14 days. When a push or sync makes a branch of that name again and it brings commits that were integrated (by change id), it is pushed as a branch nobody shares, and [`grit push`](https://grit-scm.com/docs/push/index.md) and [`grit sync`](https://grit-scm.com/docs/sync/index.md) report it with scenario `pushed_to_integrated`, how many of its commits were integrated and how many are new, and these options (exit status `3`). Reusing the name for unrelated work gets no report.

| Option | What it does |
| --- | --- |
| `rebase` | Replay only the new commits onto the target (`origin/<target>`), leaving out every commit that was integrated, even amended since, and push the branch. |
| `rename <name>` | Rename the branch here and in your space, deleting the old name there. |
| `reshare` | Share it again with everyone who was on it. |

Plain git sees the same report as `remote:` lines on the push.

## Options

| Option | Description |
| --- | --- |
| `--link` | `add`: make a share link anyone signed in can accept. |
| `--uses <n>` | `add --link`: how many times it can be accepted, or `unlimited`. Default 1. |
| `--expires <days>` | `add --link`: how many days it works, 1 to 30. Default 7. |
| `--no-history` | `add`: a [snapshot share](#snapshot-shares), without the project's history. |
| `--path <path>` | `add`: a snapshot share of only this path (implies `--no-history`). Repeatable. |

## Examples

Share a branch with bob, and make a link for anyone else:

```console
$ grit share add feature bob --link
· pushed feature to alice/widget first
✓ shared with bob, who is emailed
✓ share link (1 use, until 2026-11-11T12:00:00Z):
  https://code.gitbutler.com/share/0f3a9c
feature, shared with bob
  you    538e7ad
  bob    -        hasn't fetched it yet
  link 12  1 use left, until 2026-11-11T12:00:00Z
```

Accept a link outside any clone:

```console
$ grit share accept https://code.gitbutler.com/share/0f3a9c
✓ Joined feature, shared by alice
  your copy  bob/widget
  cloned to  /home/bob/widget
Switch to it with `grit switch feature`; push your head with `grit push`, and `grit sync` brings the others' in.
```

See where everyone is:

```console
$ grit share list
feature, shared with bob, carol, dave
  you    538e7ad
  bob    1c3e9a0  has commits you don't   grit sync
  carol  2b12f15  diverged from yours
  dave   -        hasn't fetched it yet
  link 12  1 use left, until 2026-11-11T12:00:00Z
```

## JSON output

Schema: [share.add v1](https://grit-scm.com/docs/share/schemas/share.add/v1.json/index.md) · [share.list v1](https://grit-scm.com/docs/share/schemas/share.list/v1.json/index.md) · [share.accept v1](https://grit-scm.com/docs/share/schemas/share.accept/v1.json/index.md) · [share.remove v1](https://grit-scm.com/docs/share/schemas/share.remove/v1.json/index.md) · [share.leave v1](https://grit-scm.com/docs/share/schemas/share.leave/v1.json/index.md) · [share.revoke v1](https://grit-scm.com/docs/share/schemas/share.revoke/v1.json/index.md) · [share.resolve v1](https://grit-scm.com/docs/share/schemas/share.resolve/v1.json/index.md)

`grit share add`, `list`, `remove`, `leave` and `revoke` have the same shape:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `action` | string | `add`, `list`, `remove`, `leave` or `revoke`. |
| `project` | string | Your project the shares are in, `<you>/<project>`. |
| `shares` | array | Each shared branch: `branch`, `origin`, `sharer`, `state` (`active`, `integrated`, `ended`), `mode` (`full`), `base_branch`, `members` (`user`, `sharer`, `you`, `head`, `project`, `relation` to your branch: `same`, `ahead`, `behind`, `diverged`, `unknown`, for a diverged head `divergence`, as in [`grit sync`](https://grit-scm.com/docs/sync/index.md#json-output), and for a snapshot member `snapshot`, the paths they see, empty for the whole tree), `invited` (email addresses that haven't accepted yet), `links` (`id`, `uses_left`, `expires_at`, and `snapshot` for a snapshot share link) and `url`. |
| `link` | object or omitted | The link `add --link` made: `id`, `url`, `uses_left`, `expires_at`, and `snapshot` (its paths) for a snapshot share link. |
| `added` | array or omitted | People added, who were emailed: user names, and the email addresses invited. |
| `removed` | array or omitted | People removed (or you, when leaving), and the email addresses whose invitations were withdrawn. |
| `pushed` | boolean or omitted | Whether the branch was pushed to your space first. |

<!-- schema: share.list -->

```json
{
  "action": "list",
  "project": "alice/widget",
  "shares": [
    {
      "branch": "feature",
      "origin": "alice/widget",
      "sharer": "alice",
      "state": "active",
      "mode": "full",
      "base_branch": "main",
      "members": [
        { "user": "alice", "sharer": true, "you": true, "head": "538e7ad0c3b2a1f0e9d8c7b6a5f4e3d2c1b0a9f8", "project": "alice/widget" },
        { "user": "bob", "sharer": false, "you": false, "head": "1c3e9a0b2d4f6a8c0e2b4d6f8a0c2e4b6d8f0a2c", "project": "bob/widget", "relation": "ahead" }
      ],
      "url": "https://code.gitbutler.com/alice/widget"
    }
  ]
}
```

`grit share accept`:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `status` | string | `accepted` or `already_member`. |
| `branch` | string | The shared branch. |
| `sharer` | string | Who shared it. |
| `origin` | string | The project it was shared from. |
| `project` | string | Your copy, `<you>/<project>`. |
| `url` | string | Your copy's clone URL. |
| `path` | string or omitted | The clone it was fetched into, or cloned as. |
| `cloned` | boolean | Whether this made a new clone. |

<!-- schema: share.accept -->

```json
{
  "status": "accepted",
  "branch": "feature",
  "sharer": "alice",
  "origin": "alice/widget",
  "project": "bob/widget",
  "url": "https://code.gitbutler.com/bob/widget.git",
  "path": "/home/bob/widget",
  "cloned": true
}
```

`grit share resolve`:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `branch` | string | The shared branch. |
| `with` | string | The member whose head yours was put together with. |
| `scenario` | string | What the two heads added up to, before. |
| `summary` | string | What happened, in a sentence. |
| `option` | string or omitted | The option applied; omitted when a decision is needed and none was chosen. |
| `previous` | string | Your head before. |
| `head` | string or omitted | Your head afterwards, when it moved. |
| `pushed` | boolean | Whether your head was pushed. |
| `next` | string or omitted | What to run next, for `resolve`, which is done by hand. |
| `options` | array or omitted | When a decision is needed and none was chosen: each option's `id`, `label`, `loses` and `command`. |
| `renamed` | string or omitted | For `rename`: the branch's new name, here and in your space. |
| `shared_with` | array of strings or omitted | For `reshare`: who the branch is shared with again. |

<!-- schema: share.resolve -->

```json
{
  "branch": "pairing",
  "with": "carol",
  "scenario": "amended_both_conflicting",
  "summary": "You and carol both amended \"Add the history RPC\", and the edits overlap in src/rpc.rs.",
  "option": "keep_both",
  "previous": "538e7ad0c3b2a1f0e9d8c7b6a5f4e3d2c1b0a9f8",
  "head": "9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b",
  "pushed": true
}
```

## Markdown output

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output.

Schema: [share.add v1](https://grit-scm.com/docs/share/schemas/share.add/v1.json/index.md) · [share.list v1](https://grit-scm.com/docs/share/schemas/share.list/v1.json/index.md) · [share.accept v1](https://grit-scm.com/docs/share/schemas/share.accept/v1.json/index.md) · [share.remove v1](https://grit-scm.com/docs/share/schemas/share.remove/v1.json/index.md) · [share.leave v1](https://grit-scm.com/docs/share/schemas/share.leave/v1.json/index.md) · [share.revoke v1](https://grit-scm.com/docs/share/schemas/share.revoke/v1.json/index.md) · [share.resolve v1](https://grit-scm.com/docs/share/schemas/share.resolve/v1.json/index.md)

```markdown
## Shared branches in `alice/widget`

### `feature`

Shared by `alice` from `alice/widget`; state active, base `main`.

| Member | Head | Compared with yours |
| --- | --- | --- |
| `alice` (you) | `538e7ad` | - |
| `bob` | `1c3e9a0` | has commits you don't |
| `carol` | `2b12f15` | diverged from yours |
| `dave` | not fetched yet | - |
```

## Exit status

| Code | Meaning |
| --- | --- |
| `0` | Done. |
| `1` | The server refused (the message says why: not on the branch, only the sharer can remove people, a used-up or expired link), the option chosen conflicts, or the command could not run: not a clone of a hosted project, not signed in. |
| `3` | `grit share resolve` without an option, for a divergence that needs a decision, or a branch pushed again after it was integrated: the options are listed (`needs_decision`). |
| `2` | Invalid arguments, such as `--uses` without `--link`. |

## See also

- [`grit sync`](https://grit-scm.com/docs/sync/index.md), [`grit push`](https://grit-scm.com/docs/push/index.md), [`grit status`](https://grit-scm.com/docs/status/index.md), [`grit clone`](https://grit-scm.com/docs/clone/index.md), [`grit login`](https://grit-scm.com/docs/auth/index.md).

# https://grit-scm.com/docs/clean/index.md

# grit clean

> Remove untracked files from the working tree.

## Synopsis

```text
grit clean [--pathspec-from-file <file|->] [--pathspec-file-nul] [<path>...]
grit clean -f [--pathspec-from-file <file|->] [<path>...]
grit clean [--dry-run] [--ignored | --only-ignored] [-e <pattern>] [--files-only] [<path>...]
```

## Description

Removes untracked files (and untracked directories) from the working tree. Pathnames in human and `--markdown` output use the same quoting rules as [`grit status`](https://grit-scm.com/docs/status/index.md) (see **Description** there). Tracked files and nested Git repositories (directories that contain their own `.git`) are never removed.

Without `-f` / `--force`, `grit clean` is a **dry run**: it prints what would be removed and leaves the work tree unchanged. This differs from Git’s `clean.requireForce` error on purpose — previewing is the default so you can see the impact before deleting anything. `--dry-run` is accepted explicitly (and conflicts with `-f`).

While files are being deleted, Ctrl+C (or `SIGTERM` / `SIGHUP` on Unix) stops with `error: operation cancelled` and exit code **130**. Paths removed before the interrupt stay removed; there is no index lock to restore.

Pass `-f` to actually delete the listed paths. Pass `--ignored` to also remove ignored files (similar to `git clean -x`). Pass `--only-ignored` to remove only ignored paths (similar to `git clean -X`); it cannot be combined with `--ignored`.

Use `-e` / `--exclude` (repeatable) to add exclude patterns: matching paths are not removed (like `git clean -e`). Use `--files-only` to skip untracked directories (like `git clean` without `-d`).

With path arguments, only untracked paths matching those pathspecs are considered.

## Options

| Option | Description |
| --- | --- |
| `<path>...` | Limit cleaning to these paths. Omit to scan the whole tree. |
| `--pathspec-from-file` | Read pathspecs from a file, or `-` for stdin (same rules as Git). |
| `--pathspec-file-nul` | With `--pathspec-from-file`, entries are NUL-separated instead of line-based. |
| `-f`, `--force` | Delete untracked paths instead of only listing them. Conflicts with `--dry-run`. |
| `--dry-run` | Explicit preview (default when `-f` is not passed). Conflicts with `-f`. |
| `--ignored` | Remove ignored files and directories as well (`git clean -x`). Conflicts with `--only-ignored`. |
| `--only-ignored` | Remove only ignored paths (`git clean -X`). Conflicts with `--ignored`. |
| `-e`, `--exclude` | Additional exclude pattern (repeatable). Matching paths are kept. |
| `--files-only` | Remove untracked files but not directories. |

## Examples

Preview removals (default):

```console
$ grit clean
Would remove untracked.txt
Would remove nested/
```

Delete untracked paths:

```console
$ grit clean -f
Removed untracked.txt
Removed nested/
```

Remove only ignored files:

```console
$ grit clean --only-ignored
Would remove build/output.tmp
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/clean/schemas/clean/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `dry_run` | boolean | `true` when `-f` was not passed (preview only); `false` when paths were actually deleted. |
| `removed` | array of strings | Repository-relative paths removed, or that would be removed when `-f` was not passed. Non-UTF-8 names use the reversible `grit+pathhex:` storage form (same as `grit status` and `grit diff --json`); a work tree file literally named `grit+pathhex:…` is double-encoded in this field. |
| `scope` | string | `untracked`, `untracked_and_ignored`, or `only_ignored`. |

Example (dry run):

```json
{
  "dry_run": true,
  "scope": "untracked",
  "removed": [
    "untracked.txt",
    "nested/"
  ]
}
```

Example (with `-f`):

```json
{
  "dry_run": false,
  "scope": "untracked",
  "removed": [
    "untracked.txt",
    "nested/"
  ]
}
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/clean/schemas/clean/v1.json/index.md)
Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a bullet list of paths under **Would remove** or **Removed**.




```text
## Would remove

- `untracked.txt`
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[grit status](https://grit-scm.com/docs/status/index.md), [grit add](https://grit-scm.com/docs/add/index.md)

# https://grit-scm.com/docs/update/index.md

# grit update

> Update grit to the latest release.

## Synopsis

```text
grit update
```

## Description

Downloads the latest release of `grit` and installs it over the copy you're running. It does this by running the same install script as the one-line install on the [Install](https://grit-scm.com/docs/install/index.md) page: `curl -fsSL https://grit-scm.com/install | sh` on macOS and Linux, which needs `sh` and `curl`, and `irm https://grit-scm.com/install.ps1 | iex` in PowerShell on Windows.

The installer prints its own progress. If you installed `grit` with `cargo install`, update it with `cargo install grit-cli` instead.

## Options

`grit update` takes no options beyond the [global ones](https://grit-scm.com/docs/global-options/index.md).

## Examples

```console
$ grit update
Updating grit (current: 0.5.0)
Install directory: /home/ada/.local/bin
...
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/update/schemas/update/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `updated` | boolean | Whether the install script was started successfully. |
| `version` | string | Version of `grit` that ran the update (not necessarily the version installed). |

Example:

```json
{
  "updated": true,
  "version": "0.5.0"
}
```

With `--json`, the installer's progress goes to stderr so stdout carries only the JSON object.

## Markdown output

Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output.

Schema: [v1](https://grit-scm.com/docs/update/schemas/update/v1.json/index.md)

Markdown uses headings, bullet lists, and fenced blocks; pipe characters inside table cells are escaped. See the JSON output section for the stable field contract.



```text
## Update

- Updated grit (ran installer; previous version **[VERSION]**)
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[Docs overview](https://grit-scm.com/docs/index.md)

# https://grit-scm.com/docs/repack/index.md

# grit repack

> Pack reachable objects and remove redundant packs.

## Synopsis

```text
grit repack
grit repack --force
grit repack --dry-run
grit repack --quiet
```

## Description

Packs local objects reachable from maintenance roots (refs, reflogs, and the index) into a single new packfile (similar to `git repack -ad`), removes older pack files, and deletes loose objects that are already stored in the new pack. When `objects/info/alternates` is configured, only objects in this repository's object store are packed (Git's `repack -l`); borrowed objects stay in the alternate. Unlike full [`grit gc`](https://grit-scm.com/docs/repack/gc.md/index.md), **`grit repack` always runs** (it does not apply `gc.auto` skip heuristics).

Objects already stored in a pack keep their stored form: whole objects are copied byte for byte and deltas are copied with only their base reference rewritten, as long as the base is packed too and the chain stays within `pack.depth`. Only the remaining objects (loose objects, and deltas whose base is dropped) go through a delta search over `pack.window` neighbours, so repacking an already packed repository costs about as much as copying it. With `--force` (like `git repack -adf`) every delta is recomputed, which takes longer but can make a pack written by a weaker packer smaller. Both modes stream object payloads and the new pack instead of holding them in memory.

Ctrl+C (or `SIGTERM` / `SIGHUP` on Unix) during repack stops before the new pack is installed, with `error: operation cancelled` and exit code **130**.

Unreachable objects that lived only in removed packs are written loose first so they are not dropped silently; when [`grit gc`](https://grit-scm.com/docs/repack/gc.md/index.md) runs with `gc.pruneExpire`, recently written unreachable objects are kept for the grace window before loose pruning.

In a shallow clone (`grit clone --depth` or `git clone --depth`), the commits listed in `.git/shallow` (in the common Git directory, shared by linked worktrees) are history boundaries, as in Git: their trees are packed, but their parents are neither packed nor required to exist.

In a partial clone, maintenance works offline after local commits. Existing `.promisor` packs and all their sidecars stay in place. Ordinary packs that hold promised objects unavailable in those promisor packs are also retained with their sidecars, so already available content stays readable offline. These retained ordinary packs may contain both local and promised objects. The new unmarked pack contains local objects only; promised historical blobs or trees may remain absent. Promisor packs are never loosened or folded into the local pack. Bitmap generation is skipped when promises prevent a complete object closure. `--dry-run` follows the same boundary without fetching. `pack_path` and `pack_bytes` describe the newly written local pack even when promisor packs remain alongside it.

Use this when a repository has accumulated many loose objects after local commits. Clones and fetches already install packs; repack is mainly for long-lived worktrees built entirely with `grit commit`.

### Benchmarking

Measured on 2026-10-26 using Linux x86_64, four CPUs, 15 GiB RAM, system Git 2.55.0, and Rust 1.99.0 with the `release` profile. The real Grit repository fixture has 11,278 commits and 125,062 reachable objects after adding one local indexed-file commit. Its blobless copy leaves 54,133 blobs promised, with the origin unavailable. Neither fixture has a checkout.

Each cell shows **wall time in ms / peak RSS in KiB**, as medians of five fresh repository copies. Runs alternate among all four binaries to control measurement variation. Wall time includes process launch, measured with a monotonic clock around `/usr/bin/time -v`; RSS comes from that same invocation. Git runs `gc` or `repack -a -d`; Grit runs `gc --json` or `repack --json`.

| Repository / operation | System Git | Main (`a33000428`) | Reviewed (`a3a1bbce`) | Fixed |
| --- | ---: | ---: | ---: | ---: |
| Complete / gc | 1,663.0 / 296,124 | 1,710.3 / 293,256 | 1,712.5 / 293,104 | 1,729.1 / 293,304 |
| Complete / repack | 1,516.1 / 296,228 | 1,545.4 / 291,068 | 1,550.9 / 291,128 | 1,562.5 / 296,268 |
| Blobless / gc | 401.4 / 34,976 | 1,193.3 / 174,592 (failed) | 1,748.5 / 166,468 | 1,751.1 / 166,360 |
| Blobless / repack | 274.2 / 35,040 | 1,210.0 / 174,728 (failed) | 1,545.9 / 166,176 | 1,551.1 / 165,836 |

Main blobless GC exits 128 and repack exits 1 while trying the unavailable remote; those measurements cover failed operations. Reviewed and fixed runs finish offline. The fixed complete-repository median times are within 1% of the reviewed revision, with overlapping sample ranges and peak RSS within 1.8%. Blobless median times are within 0.4%. Promisor classification still costs more time and memory than Git on this metadata-heavy fixture.

The availability regression covered by the maintenance tests uses a different storage shape: a marked tree references a blob or subtree stored only in an ordinary pack. Fixed maintenance retains that source pack; the reviewed revision could delete its only available copy even though `git fsck --strict` passed.

## Options

| Option | Description |
| --- | --- |
| `-f`, `--force` | Recompute every delta instead of reusing the ones already in packs (whole objects are still copied when they stay whole). |
| `--dry-run` | Report how many objects would be packed without writing. |
| `-q`, `--quiet` | Suppress the human summary (JSON and Markdown output are unchanged). |

## Examples

Repack a repository with many loose commits:

```console
$ grit repack
Packed 412 objects into .git/objects/pack/pack-….pack (0 redundant pack files removed, 380 loose objects pruned).
```

Recompress a pack received from a server with full delta search:

```console
$ grit repack --force
Packed 195008 objects into .git/objects/pack/pack-….pack (1 redundant pack files removed, 0 loose objects pruned).
```

Preview only:

```console
$ grit repack --dry-run
Would pack 412 objects (380 loose, 0 pack files now).
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/repack/schemas/repack/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `dry_run` | boolean | Whether this run only estimated work. |
| `loose_before` | number | Loose object files before repack. |
| `packs_before` | number | `.pack` / `.idx` pairs before repack. |
| `objects_packed` | number or null | Objects in the new local pack, or the estimated count on dry run (`null` when none). |
| `pack_bytes` | number or null | Size of the pack payload in bytes. |
| `pack_path` | string or null | Path to the installed `.pack` file. |
| `removed_pack_files` | number | Pack sidecar files removed. |
| `pruned_loose` | number | Loose files removed after packing. |

Example:

```json
{
  "dry_run": false,
  "loose_before": 380,
  "packs_before": 0,
  "objects_packed": 412,
  "pack_bytes": 88234,
  "pack_path": ".git/objects/pack/pack-abc123….pack",
  "removed_pack_files": 0,
  "pruned_loose": 380
}
```

## Markdown output

Pass `--markdown` for an agent-friendly summary with the same fields as JSON in bullet and table form.

Schema: [v1](https://grit-scm.com/docs/repack/schemas/repack/v1.json/index.md)

```text
## Repack

- **dry_run:** true
- **loose_before:** 9
- **packs_before:** 0
- **objects_packed:** 9
- **removed_pack_files:** 0
- **pruned_loose:** 0
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.

## See also

- [`grit gc`](https://grit-scm.com/docs/repack/gc.md/index.md) — repack plus unreachable loose-object prune
- [`grit fsck`](https://grit-scm.com/docs/repack/fsck.md/index.md) — verify integrity after maintenance

# https://grit-scm.com/docs/skill/index.md

# grit skill

> Print an agent skill that explains how to use grit.

## Synopsis

```text
grit skill
```

## Description

Prints a `SKILL.md` file for coding agents that explains how to use `grit`: the JSON output contract, [CLI conventions](https://grit-scm.com/docs/cli-conventions/index.md) and [exit codes](https://grit-scm.com/docs/exit-codes/index.md), everyday commands, copy-paste **Recipes** (CI-tested command sequences), how `grit commit` differs from `git commit`, how to stay non-interactive, and what to do with `git` instead. It uses the [Agent Skills](https://agentskills.io) format, with `name` and `description` front matter, so agents that load skills pick it up when a task involves version control.

The skill is built into the binary and names the version that printed it, so regenerate it after [`grit update`](https://grit-scm.com/docs/update/index.md) to keep it current.

Save it where your agent looks for skills, for example `.agents/skills/grit/SKILL.md` in a project, or `~/.claude/skills/grit/SKILL.md` for Claude Code across all projects.

## Options

`grit skill` takes no options besides the [global options](https://grit-scm.com/docs/global-options/index.md).

## Examples

Install the skill in the current project:

```console
$ mkdir -p .agents/skills/grit
$ grit skill > .agents/skills/grit/SKILL.md
```

Read the start of it:

```console
$ grit skill | head -4
---
name: grit
description: Use the grit CLI for version control in Git repositories — status, diffs, commits, branches, merges, cherry-picks, fetch/pull/push and tags — with JSON output for scripts and agents. Use when a task involves committing, branching, syncing with a remote or reading history and `grit` is installed.
---
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/skill/schemas/skill/v1.json/index.md)

Pass `--json` to get the skill text along with where to save it:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `name` | string | The skill's name, `grit`. |
| `version` | string | The grit version that generated the skill. |
| `path` | string | A conventional place to save it, relative to a project root. |
| `content` | string | The full `SKILL.md` text, front matter included. |

Example (with `content` shortened):

```json
{
  "name": "grit",
  "version": "0.5.2",
  "path": ".agents/skills/grit/SKILL.md",
  "content": "---\nname: grit\ndescription: Use the grit CLI for version control …"
}
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/skill/schemas/skill/v1.json/index.md)
Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) to print the full `SKILL.md` text on stdout (same bytes as human mode, suitable for saving or parsing):

```text
---
name: grit
description: Use the grit CLI for version control …
---
```


## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[Agent guide](https://grit-scm.com/docs/agents/index.md), [grit update](https://grit-scm.com/docs/update/index.md), [Global options](https://grit-scm.com/docs/global-options/index.md)

# https://grit-scm.com/docs/completions/index.md

# grit completions

> Generate shell completion scripts for bash, zsh, and fish.

## Synopsis

```text
grit completions <shell>
```

## Description

Prints a shell completion script for the `grit` subcommands and flags in the running binary. Redirect stdout to a file your shell loads, or evaluate it in the current session during setup.

Supported shells: `bash`, `elvish`, `fish`, `powershell`, and `zsh` (whatever `clap_complete` exposes for the installed `grit` version).

The script always matches the CLI you built or installed. After [`grit update`](https://grit-scm.com/docs/update/index.md), regenerate completions so new commands and flags appear.

Release archives also ship pre-generated scripts under `completions/` when you install from a tarball.

## Options

| Argument | Meaning |
| -------- | ------- |
| `<shell>` | One of `bash`, `elvish`, `fish`, `powershell`, or `zsh`. |

`grit completions` rejects the global [`--json`](https://grit-scm.com/docs/global-options/index.md) and [`--markdown`](https://grit-scm.com/docs/global-options/index.md) flags; stdout is always the raw completion script.

## Examples

Generate bash completions for the current session:

```console
$ grit completions bash > /tmp/grit.bash
$ source /tmp/grit.bash
```

Install zsh completions for your user (typical layout):

```bash
grit completions zsh > ~/.local/share/zsh/site-functions/_grit
```

Install fish completions:

```bash
mkdir -p ~/.config/fish/completions
grit completions fish > ~/.config/fish/completions/grit.fish
```

## JSON output

There is no JSON form. `--json` and `--markdown` exit with an error; use the human completion script only.

## Markdown output

None. `--markdown` is rejected for the same reason as `--json`.

```console
$ grit completions bash --markdown
**Error:** `grit completions` does not support --json or --markdown
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[Install grit](https://grit-scm.com/docs/install/index.md), [grit update](https://grit-scm.com/docs/update/index.md), [Global options](https://grit-scm.com/docs/global-options/index.md)

# https://grit-scm.com/docs/gc/index.md

# grit gc

> Run repository maintenance — pack refs, expire reflogs, repack, prune, and refresh commit-graph.

## Synopsis

```text
grit gc
grit gc --dry-run
grit gc --quiet
grit gc --auto [--dry-run]
grit gc repack [--bitmaps] [--force] [--dry-run]
grit gc commit-graph [--dry-run]
grit gc midx [--dry-run]
grit gc pack-refs [--dry-run]
grit gc prune [--older-than DATE] [--dry-run]
grit gc offload --to REMOTE [--blobs none|SIZE] [--lop-dir PATH] [--configure-lop] [--dry-run]
grit gc drop-large-blobs [--min-size SIZE] [--older-than DATE] [--dry-run]
```

## Description

Runs Git-compatible maintenance in-process (never shells out to the system `git` binary).

Long-running phases check for Ctrl+C (and `SIGTERM` / `SIGHUP` on Unix). When interrupted before a new pack is published, grit exits with `error: operation cancelled` and code **130** without leaving a partial pack visible to readers.

Bare **`grit gc`** runs, in order:

1. **pack-refs** — merge loose refs into `packed-refs` (or compact reftable), unless `gc.packRefs` is `false`. Empty ref subdirectories are removed; `refs/heads`, `refs/tags`, and `refs/remotes` stay as directories even when empty, like Git.
2. **reflog-expire** — apply `gc.reflogExpire*` rules using the current time. Entries older than `gc.reflogExpireUnreachable` are checked against the commits reachable from the ref, as described for [`grit reflog expire`](https://grit-scm.com/docs/gc/reflog.md/index.md); each commit is read once per run however many reflogs need it, and each ref's walk only marks commits already read, so this phase stays fast on a large repository with month-old reflogs and many branches.
3. **repack** — consolidate reachable and retained unreachable objects into pack files, removing redundant loose objects and merging multiple packs when present. In a clone with `objects/info/alternates`, only objects stored in this repository are packed (Git's `repack -l` / `pack-objects --local`); the rest keep being read from the alternate. **Skips** rebuilding when Git would (`gc.auto` loose count and `gc.autoPackLimit`, typically a single pack with no loose objects after clone), unless repack side effects are requested (for example `repack.writeBitmaps` or `pack.writeBitmaps`). When repack runs, objects already in packs are copied in their stored form (deltas included) and only loose objects go through delta search, as described for [`grit repack`](https://grit-scm.com/docs/gc/repack.md/index.md). Writes a `.bitmap` when the winning `repack.writeBitmaps` or `pack.writeBitmaps` entry is true, or when neither is set and the repository is bare. Explicit [`grit repack`](https://grit-scm.com/docs/gc/repack.md/index.md) does not use this skip (`auto_skip` stays false).
4. **prune** — delete unreachable loose objects older than `gc.pruneExpire` (default `2.weeks.ago`), and remove stale temporary object paths left by interrupted fetch, repack, or index-pack (`tmp_pack_*`, `tmp_obj_*`, `.pack-*-install-*` staging directories, and `objects/incoming/pack-receive-*.tmp`) under the same expiry. Reachability treats every non-bare worktree's index (main and linked, including prunable entries) as a root, matching Git, so staged blobs in a linked worktree are not pruned from the shared object store. Before that sweep, gc also reclaims orphaned `next-index-<pid>` hook index copies in `.git` (and linked worktree git dirs) when the PID is no longer running on this machine — the same cleanup that runs before any index-locking command. The object graph is only walked when some loose object is old enough to delete, and one gc walks it at most once (shared with the repack step), so gc of an already packed repository does not read the object graph at all.
5. **drop-large-blobs** — only when `maintenance.drop-large-blobs.enabled` is true, in a partial clone: drop large promised blobs not needed recently (see [`grit gc drop-large-blobs`](#grit-gc-drop-large-blobs)). It runs after repack, which leaves promisor packs as they are, and is skipped (reported as `skipped`) during a merge, rebase, cherry-pick, revert, am or bisect, without a promisor remote, or with `extensions.preciousObjects`. Its config is checked before the first phase, so an invalid `maintenance.drop-large-blobs.*` value stops `grit gc` before it changes anything.
6. **commit-graph** — write `objects/info/commit-graph` when `gc.writeCommitGraph` is not `false` and `core.commitGraph` is not `false`, except when there are no reachable commits (same as `git commit-graph write --reachable`: no file is created and any existing graph is kept). Like `git gc`, changed-path Bloom filters are kept when the existing commit-graph has them and are not computed from scratch otherwise; run `grit gc commit-graph` to add them (that subcommand ignores `gc.writeCommitGraph`). In a **shallow** clone, with `info/grafts`, or with replace refs (unless `core.useReplaceRefs=false`), commit parents differ from what the commit objects record, so Git uses no commit-graph there: grit writes none, reports the task as `skipped`, and deletes any existing graph (which `git fsck` would reject).

Every step that walks history (repack, prune, bitmap) stops at the shallow boundaries in `.git/shallow`, so gc works in shallow clones and keeps everything down to the boundary commits.

Task subcommands run a single step and return the same JSON shape with one entry in `tasks`.

Progress lines go to **stderr**. The human summary lists each task, key counters, and elapsed milliseconds.

### Automatic maintenance

Like Git, grit keeps loose objects from piling up without you scheduling anything. After a successful **`grit commit`**, **`merge`**, **`pick`**, **`revert`**, **`rebase`**, **`history`** rewrite, **`stash`** (push), **`fetch`** or **`pull`** (none of them with `--dry-run` or `--check`), grit runs the same check as `git gc --auto`:

- **Too many packs:** more local packs without a `.keep` file than `gc.autoPackLimit` (default 50). Every pack is consolidated into one, as a full `grit gc` does.
- **Too many loose objects:** the loose-object count is estimated from one fan-out directory (`objects/17`, times 256) and compared with `gc.auto` (default 6700). The reachable loose objects are packed into one new pack and existing packs are left alone, so the cost depends on the loose objects rather than the repository size. The new pack is delta-compressed with `pack.window` and `pack.depth` like [`grit repack`](https://grit-scm.com/docs/gc/repack.md/index.md), pairing each file's versions by path, so successive versions of a large binary cost one copy plus small deltas; it never deltas against objects in older packs. Unreachable loose objects stay loose until `gc.pruneExpire` (default `2.weeks.ago`; `now` expires them at once) lets the prune step delete them, as with Git.

When either fires, `grit gc --auto` runs: pack-refs, reflog expiry, the repack above, unreachable-object pruning under `gc.pruneExpire`, and commit-graph. The check itself is two directory reads, so commands do not get slower in the common case.

| Config | Default | Effect |
| --- | --- | --- |
| `gc.auto` | `6700` | Loose-object threshold. `0` or a negative value turns automatic maintenance off entirely. |
| `gc.autoPackLimit` | `50` | Pack-count threshold. `0` or a negative value turns off only this trigger. |
| `gc.autoDetach` | `true` | Run in the background (`grit gc --auto --quiet` in a separate process) so the command returns at once. `false` runs it before the command exits. |
| `maintenance.auto` | `true` | `false` stops commands from starting automatic maintenance; `grit gc --auto` still works. |

Full **`grit gc`** (and `grit gc --auto` when it runs every step) also honors:

| Config | Default | Effect |
| --- | --- | --- |
| `gc.writeCommitGraph` | `true` | When `false`, skip the commit-graph step; any existing graph is kept. Does not affect `grit gc commit-graph`. Also skipped when `core.commitGraph=false`. |
| `gc.packRefs` | `true` | When `false`, skip pack-refs during gc. `notbare` packs only in non-bare repositories (bare repos keep loose refs). Does not affect `grit gc pack-refs`. |
| `repack.writeBitmaps` | unset (bare: true) | When true, gc repack writes a reachability `.bitmap` even if it must rewrite a single pack. |
| `pack.writeBitmaps` | — | Deprecated Git synonym of `repack.writeBitmaps`; when both keys are set, the last entry in config load order wins. |

Before doing any work, an automatic run takes the `gc.pid` lock that Git uses, so it never overlaps another grit or Git gc, and runs the `pre-auto-gc` hook; a non-zero hook exit skips the run. In human mode the triggering command prints one line on stderr when it starts background maintenance, or after foreground maintenance has run (nothing when the hook declines or another gc holds the lock); `--json` and `--markdown` output are unchanged.

On Windows, the background child requests job breakaway, in addition to a detached console and a separate process group. This lets job-based command runners finish waiting for the triggering command while maintenance continues. The child also does not inherit grit's stdin, stdout or stderr, so a caller that reads the command's output until it closes (PowerShell, `cmd /c`, a captured spawn) gets it as soon as the command exits, not when packing finishes. If the surrounding job denies breakaway or the child otherwise cannot start, grit falls back to foreground maintenance: human output warns about the failed spawn and reports completed packing without claiming a background run.

A plain `grit gc` always runs and also takes the `gc.pid` lock: it fails with an error when another gc is running.

### Commit benchmark

An 8,000-file first commit across 160 directories, with default `gc.auto=6700`:

| Command | Median commit wall time | Peak RSS |
| --- | --- | --- |
| System Git 2.55.0 | 170.56 ms | 9,996 KiB |
| grit before Windows job breakaway (`a1f4e2168`) | 62.49 ms | 19,904 KiB |
| grit with Windows job breakaway | 62.17 ms | 19,744 KiB |

Measured on an Ubuntu 24.04 x86-64 VM with four AMD EPYC vCPUs, using `dist` builds and `/usr/bin/time -v`. Five fresh repositories per command were measured in alternating order. Each tool staged its own files before timing; filesystem writes were flushed before the commit, with warm caches. RSS is the highest per-run peak across the five runs and excludes detached maintenance. Each background run finished before the next measurement.

Every commit returned with 8,162 loose objects and no packed objects; background maintenance subsequently completed and `git fsck --strict --no-dangling` passed. Linux already detached on the baseline, so these measurements check the unchanged Unix path, not Windows job-object behavior. Windows jobs that prohibit breakaway still require the foreground fallback described above.

Partial clones can run maintenance offline, including after creating local commits. GC retains existing `.promisor` packs and their sidecars separately from the new local-object pack. Ordinary packs that hold promised objects unavailable in the retained promisor packs also stay in place, preserving offline access to content already present locally. Promised historical blobs and trees may remain absent; GC, pruning, and `--dry-run` do not fetch them. Missing objects outside the known promise boundary still cause an error. Bitmaps are omitted when promises prevent a complete object closure.

## Options

| Option | Description |
| --- | --- |
| `--dry-run` | Preview maintenance without writing refs or objects (full `grit gc`, or combine with a task subcommand). |
| `--auto` | Run only when `gc.auto` or `gc.autoPackLimit` is exceeded (see [Automatic maintenance](#automatic-maintenance)). With `--dry-run`, report the decision and the planned work. Cannot be combined with a task subcommand. |
| `-q`, `--quiet` | Suppress the human task summary. |

### `grit gc repack`

| Option | Description |
| --- | --- |
| `--bitmaps` | Write a reachability `.bitmap` sidecar for the new pack. |
| `-f`, `--force` | Recompute every delta instead of reusing the ones already in packs (like `git repack -f`). |
| `--dry-run` | Report how many objects would be packed; no pack files or refs are modified. |

### `grit gc commit-graph`, `grit gc midx`, `grit gc pack-refs`

| Option | Description |
| --- | --- |
| `--dry-run` | Report counters and paths that would be written; leave the repository unchanged. |

`grit gc midx` writes multi-pack-index format version 1, which every Git with multi-pack-index support reads (Git 2.43 included). Set `midx.version = 2` in config to write version 2 instead; only newer Git releases read it. Any other `midx.version` value is an error, even with `--dry-run`, and nothing is written.

### `grit gc prune`

| Option | Description |
| --- | --- |
| `--older-than DATE` | Git approxidate cutoff; default is `gc.pruneExpire` from config. |
| `--dry-run` | Report unreachable loose objects that would be deleted without removing them. |

Like `git prune`, `grit gc prune` returns immediately when there is no loose object older than the cutoff: it only checks that the objects named by refs, reflogs and the index exist instead of walking the object graph.

Also like `git prune`, it refuses with an error and deletes nothing when `extensions.preciousObjects` is set.

### `grit gc offload`

Moves large blobs out of the repository to a *large-object promisor* (LOP): a second repository that holds only the big blobs. The repository you run it in becomes a partial repository of the LOP. Its `remote.<REMOTE>.promisor` is set, and its remaining objects move into one `.promisor` pack, the blobs it keeps included. Those blobs exist only in this repository, but they have to be in the promisor pack: Git treats every blob a tree in a promisor pack names as promised, and `git repack -a -d`, `git gc --prune=now` and `git gc` keep a promised object only when it sits in a promisor pack. A kept blob in an ordinary pack beside it would be deleted (or moved to a cruft pack and pruned two weeks later), with `git fsck` still clean and nothing to fetch it back from. Clients that accept the LOP through the `promisor-remote` capability get packs without the offloaded blobs and fetch those from the LOP themselves (see [grit upload-pack](https://grit-scm.com/docs/gc/upload-pack.md/index.md#serving-a-repository-whose-large-blobs-live-elsewhere)). This is the layout Git's own large-object-promisor setup uses, built there with `git repack -a -d --filter=blob:limit=<n> --filter-to=<lop>`.

| Option | Description |
| --- | --- |
| `--to REMOTE` | The promisor remote the blobs go to. `remote.<REMOTE>.url` must be set. |
| `--blobs none\|SIZE` | Which blobs move: `none` moves every blob, a size such as `512k` or `1m` moves blobs of at least that many bytes (`k`, `m`, `g` are KiB, MiB, GiB, as for [`grit clone --blobs`](https://grit-scm.com/docs/gc/clone.md/index.md)). Defaults to `remote.<REMOTE>.partialCloneFilter`; one of the two is required. A given value is also stored as `partialCloneFilter` when that is unset, so `promisor.sendFields = partialCloneFilter` passes it on to clients. |
| `--lop-dir PATH` | The LOP's git directory on this machine, for when `remote.<REMOTE>.url` is the URL clients use (such as `https://…`) rather than a local path. |
| `--configure-lop` | Also set `uploadpack.allowFilter` and `uploadpack.allowAnySHA1InWant` in the LOP, which it needs to answer clients' lazy fetches. |
| `--dry-run` | Report what would move; write nothing. |

Nothing is removed from the repository before the LOP holds it. The blobs go into one new LOP pack, whole, with a `.keep` marker written before the pack appears: nothing in the LOP refers to them, so this protects them from `gc` there. A blob the LOP already holds in a pack an earlier offload wrote there (its `.keep` marker reads `grit offload: large-object promisor pack`) is not copied again. Any other copy there is copied anyway: a loose or unkept one, since the LOP's next `gc` may prune it, one in a pack kept for a while by another writer (`receive-pack` and `fetch-pack` keep the pack they write until they have updated the refs, then remove the marker), and one the LOP only reaches through its alternates. Every blob is checked to be in such a pack of the LOP, and the new pack is flushed to disk. Only then are the config set (including `grit.lopGitDir`, the LOP's git directory, which [`grit gc drop-large-blobs`](#grit-gc-drop-large-blobs) checks before dropping anything here) and the repository's own packs and loose objects rewritten without the blobs. Unreachable objects are kept, and a pack pushed during the run is left alone. Blobs that a checkout needs (a worktree's index or `HEAD`) stay, as do blobs in `.keep` packs. `promisor.advertise` and `extensions.partialClone` are left for you to set. The run takes the `gc.pid` lock like `grit gc`. It refuses a LOP that stores its objects where the repository does (the repository itself, a linked worktree of it, or a directory whose `objects/` is linked to the repository's).

Offload never rewrites a `.keep` pack, and it refuses to run, before changing anything, when an ordinary `.keep` pack (one without `.promisor`) holds the only copy of an object that a commit, tree or tag going into the promisor pack names: the parent commit of a pushed one, or a file it left unchanged. Git would count that object as promised, and `git repack -a -d` deletes a promised object outside a promisor pack once the `.keep` marker is gone (while the marker stays, it also leaves any copy out of the promisor pack it writes, so a copy is no help). The error names the pack, the object and the one naming it. Remove the marker and run offload again to fold the pack in, or mark the pack `.promisor` yourself to keep it as it is. A `.keep` pack whose objects nothing else names is left alone. Without ordinary `.keep` packs the check costs nothing; with them, it reads the commits, trees and tags to be rewritten.

Besides `remote.<REMOTE>.promisor`, offload sets `repack.writeBitmaps = false` in the repository, and the repository cannot use reachability bitmaps afterwards. A bitmap, for one pack or a multi-pack-index, needs every object its commits reach in the packs it covers, and the offloaded blobs are in none of them. Git's repack keeps promisor and other objects in separate packs, so once a push adds a commit outside the promisor pack, Git fails with `Packfile doesn't have full closure`: `git gc` exits 128 on a bare repository, where bitmaps are on by default, and `git repack -a -d -b --write-midx` fails as well (Git 2.50 and 2.56). `grit gc` and `grit gc repack --bitmaps` leave the bitmap out instead, so the setting is there for Git. Git's own `git repack --filter-to` setup fails the same way on a bare repository unless bitmaps are off.

Run it again whenever new large blobs have been pushed. It moves only those. Each run also folds objects pushed since the last one back into the single `.promisor` pack, even when no blob moves, so later fetches can tell from the pack alone that an offloaded blob is promised, and Git's maintenance keeps the small blobs pushed since. A repository whose kept blobs sit in an ordinary pack (as an earlier grit wrote it) is folded the same way on the next run. It does nothing when there is nothing to move or fold. `grit gc`, `git gc` and `git fsck` keep the offloaded blobs promised and never fetch them back, and pushes to the repository (through `grit receive-pack` or Git's) may name offloaded blobs in their trees.

#### Setting up a large-object promisor

```console
$ grit init --bare /srv/lop.git
$ cd /srv/main.git
$ grit remote add lop /srv/lop.git
$ grit config promisor.advertise true
$ grit config promisor.sendFields partialCloneFilter
$ grit config uploadpack.allowFilter true
$ grit gc offload --to lop --blobs 1m --configure-lop
offload: moved 12 blobs (1.4 GiB) to lop; main packs 1.5 GiB -> 92 MiB (3104 ms).
  wrote lop pack pack-bc97733c….pack (12 objects, 1.4 GiB)
  wrote promisor pack pack-32d0e589….pack (59662 objects, 92 MiB)
  set remote.lop.promisor = true (main)
  set remote.lop.partialCloneFilter = blob:limit=1048576 (main)
  set repack.writeBitmaps = false (main)
  set grit.lopGitDir = /srv/lop.git (main)
  set uploadpack.allowFilter = true (lop)
  set uploadpack.allowAnySHA1InWant = true (lop)
```

Clients then clone with the LOP accepted, for example `git clone -c remote.lop.url=… -c remote.lop.promisor=true -c promisor.acceptFromServer=All --filter=blob:limit=1m <url>`, or `grit clone --blobs auto` with the same `--config` values. Git 2.49 and newer understand the `promisor-remote` capability; before 2.54 the client must pass `--filter` itself. A client that accepts nothing is refused with a hint, unless the server lazily fetches the blobs for it (`uploadpack.lazyFetch = true`, or `GIT_NO_LAZY_FETCH=0` for `grit upload-pack` / `grit serve`). When clients reach the LOP at a different URL than the server, give `remote.lop.url` that URL and pass `--lop-dir /srv/lop.git` to offload.

### `grit gc drop-large-blobs`

Reclaims space in a partial clone. A partial clone fetches large blobs when something needs them and then keeps them; this drops the ones the promisor remote can supply again and nothing has needed for a while. The next read of a dropped blob fetches it again, as the first read did.

| Option | Description |
| --- | --- |
| `--min-size SIZE` | Drop blobs of at least this many bytes, such as `512k` or `1m` (`k`, `m`, `g` are KiB, MiB, GiB). Default: `maintenance.drop-large-blobs.minSize`, else the smallest `blob:limit` among the promisor remotes' `partialCloneFilter`, else `1m`. |
| `--older-than DATE` | Keep blobs needed at or after `DATE` (Git approxidate, such as `2.weeks.ago`); `now` keeps none for recency. Default: `maintenance.drop-large-blobs.expire`, else `2.weeks.ago`. Given, it takes the place of `expire` entirely, so it also runs the task when `expire` is `never` (or invalid); `--min-size` and its defaults still apply. |
| `--dry-run` | List the blobs that would be dropped, one `<oid> <size>` line each, and change nothing. |

A blob is dropped only when every one of these holds:

- It is stored in a `.promisor` pack (fetched from a promisor remote), and nowhere else in the repository: not loose, not in an ordinary pack. None of the packs holding it has a `.keep` marker.
- A promisor can supply it again. In a partial clone, a blob in a promisor pack was fetched from the promisor, so that is enough, and nothing else is read when every promisor remote is a network one. But [`grit gc offload`](#grit-gc-offload) puts the blobs only this repository has in its promisor pack too, so the promisors this machine can read are checked directly: promisor remotes with a local URL (a path or `file://`) and the LOP directories offload recorded in `grit.lopGitDir`. A blob one of them stores in its own object directory (not through its alternates) can go. In a LOP offload recorded, only a copy in a pack offload wrote there counts: nothing in the LOP reaches a blob, so its own `gc` prunes any other copy. A promisor that stores its objects where this repository does (a linked worktree of it, say) holds nothing for this. One none of them stores stays (`not_in_promisor`) when every promisor was read, and also (`unverified`) when offload has run here, since a network promisor cannot be asked whether it has a blob without fetching it, or when a promisor with a local path cannot be read: its directory no longer opens as a repository (a disk that is not mounted, say) or uses another object format.
- A tree or tag stored in a promisor pack names it. That is what keeps it a *promised* object once it is gone, so `git fsck` and `git rev-list --exclude-promisor-objects` accept it as missing. A blob fetched by id and committed only in local trees stays.
- No worktree's index or `HEAD` tree uses it (linked worktrees and sparse-index directories included). With `GIT_INDEX_FILE` set, that index counts as well as the worktree's own.
- No commit that a worktree's `HEAD` reflog moved to or from since the cutoff uses it.
- None of the promisor packs holding it was written or freshened since the cutoff. A lazy fetch writes a new pack, so this is when the blob last arrived.

Each blob that stays is counted under the first of these reasons that applies (`kept` in the output). Recency is approximate: reading an old blob that is already here (`grit cat` of an old commit, say) leaves no trace, so such a blob goes once its pack is older than the cutoff. Nothing is fetched while deciding.

A pack that held only dropped blobs is deleted. Any other affected pack is rewritten without them: a delta against a dropped blob is stored again against something that stays (or whole), the new pack keeps the old `.promisor` contents, and its modification time is set to the old pack's, so the blobs it still holds keep their age. The new pack is on disk before the old one is removed. A multi-pack-index is rewritten (without a bitmap). The run takes the `gc.pid` lock like `grit gc` (not with `--dry-run`). It refuses with an error during a merge, rebase, cherry-pick, revert, am or bisect in any worktree, in a repository without a promisor remote, and with `extensions.preciousObjects`.

| Config | Default | Effect |
| --- | --- | --- |
| `maintenance.drop-large-blobs.enabled` | `false` | Run the task as part of `grit gc` and automatic maintenance. `grit gc drop-large-blobs` runs regardless. |
| `maintenance.drop-large-blobs.minSize` | promisor `blob:limit`, else `1m` | Size threshold (see `--min-size`). |
| `maintenance.drop-large-blobs.expire` | `2.weeks.ago` | Recency cutoff (see `--older-than`). `now` or `all` keep nothing for recency; `never` or `false` turn the `grit gc` phase off. |

Git has no maintenance task for this. Git 2.56 added a manual equivalent, `git repack -a -d --filter=blob:limit=<n> --drop-filtered [--dry-run]`, which drops the same kind of candidates (blobs in promisor packs of at least `n` bytes) without the recency and promise checks and refuses to run when the index names one. `git repack -a` (and `git gc`) consolidate promisor packs into a new one, which makes every blob in it look freshly fetched: after a Git repack, blobs need the full window to age again. `grit gc` leaves promisor packs alone.

```console
$ grit gc drop-large-blobs --older-than now --dry-run
Dry run: no changes written.
drop-large-blobs: would drop 2 promised blobs >= 100 KiB, about 586 KiB (kept: 1 checked out) (1 ms).
  0be894fc2cbd410875c1e28b5c8fafdc385728a6 300000
  0d2993714f679f291a2a06dee665d04da7e8f6db 300000
$ grit gc drop-large-blobs --older-than now
drop-large-blobs: dropped 2 promised blobs >= 100 KiB, reclaimed 588 KiB (kept: 1 checked out) (9 ms).
```

Deciding costs one header read per object in the promisor packs plus reading trees breadth first from the promisor commits until every candidate is found to be promised, so it is quick even on a large clone. On a `blob:limit=50k` clone with 142,261 objects (2,000 commits) and 1,000 versions of a 120 KiB file fetched back in 10 packs (release build, Apple M-series laptop), a dry run took 31 ms and the real run, which dropped 999 blobs and shrank the pack directory from 147 MiB to 30 MiB, 61 ms; `git fsck --strict` was clean afterwards. A blob that turns out not to be promised (fetched by id and named only by local trees) makes the check read every tree in the promisor packs before keeping it. Git 2.56's `repack --drop-filtered` was not available to compare; for scale, `git repack -a -d --filter=blob:limit=50k --filter-to=<dir>` on the same clone (Git 2.50.1), which rewrites every pack, took 0.97 s. Where a promisor is checked directly, that check comes right after the pack scan and costs one index lookup per candidate in each of its packs: on a 369,000-object repository offloaded at `100k`, a dry run at `--min-size 10k` took 0.2 s to keep all 39,870 candidates as `not_in_promisor`.

## Examples

```console
$ grit gc
reflog-expire: removed 0 entries (12 ms).
repack: packed 412 objects into .git/objects/pack/pack-….pack (842 ms).
commit-graph: wrote 87 commits to .git/objects/info/commit-graph (120 ms).
```

Dry run (reflog expiry and repack estimate only; JSON includes the same counters):

```console
$ grit gc --dry-run
Dry run: no changes written.
reflog-expire: removed 0 entries (11 ms).
repack: would pack 412 objects (380 loose, 0 pack files now) (268 ms).
```

Single task:

```console
$ grit gc repack --bitmaps
repack: packed 412 objects into .git/objects/pack/pack-….pack (800 ms).
```

Automatic maintenance, below and above the threshold:

```console
$ grit gc --auto
auto: nothing to do (below gc.auto and gc.autoPackLimit).
$ grit gc --auto
auto: ran for about 8192 loose objects (gc.auto = 6700).
pack-refs: packed 1 refs (1 loose removed) → .git/packed-refs (0 ms).
reflog-expire: removed 0 entries (3 ms).
repack: packed 9633 objects into .git/objects/pack/pack-….pack (469 ms).
prune: removed 0 unreachable loose objects (0 kept, 0 ms).
commit-graph: wrote 2401 commits to .git/objects/info/commit-graph (25 ms).
```

With `--json`, the decision is in `auto` (abbreviated):

```json
{
  "dry_run": false,
  "auto": {
    "status": "ran",
    "trigger": "loose-objects",
    "estimate": 8192,
    "limit": 6700
  },
  "tasks": [
    {
      "task": "repack",
      "duration_ms": 469,
      "loose_before": 9633,
      "packs_before": 0,
      "objects_packed": 9633,
      "pack_bytes": 2675908,
      "pack_path": ".git/objects/pack/pack-6ac7a5ee….pack",
      "removed_pack_files": 0,
      "pruned_loose": 9633,
      "unreachable_loose_pruned": 0
    }
  ]
}
```

In a shallow clone:

```console
$ grit gc commit-graph
commit-graph: skipped, parents are rewritten (shallow); any existing graph removed (0 ms).
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/gc/schemas/gc/v1.json/index.md) (task subcommands also have [gc.repack](https://grit-scm.com/docs/gc/schemas/gc.repack/v1.json/index.md), [gc.commit-graph](https://grit-scm.com/docs/gc/schemas/gc.commit-graph/v1.json/index.md), [gc.midx](https://grit-scm.com/docs/gc/schemas/gc.midx/v1.json/index.md), [gc.pack-refs](https://grit-scm.com/docs/gc/schemas/gc.pack-refs/v1.json/index.md), [gc.prune](https://grit-scm.com/docs/gc/schemas/gc.prune/v1.json/index.md), [gc.offload](https://grit-scm.com/docs/gc/schemas/gc.offload/v1.json/index.md), and [gc.drop-large-blobs](https://grit-scm.com/docs/gc/schemas/gc.drop-large-blobs/v1.json/index.md) schemas).

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `dry_run` | boolean | Whether this run only estimated work (full gc). |
| `auto` | object | Only with `--auto`. `status` is `not-needed`, `already-running` (with `pid` and `host` from `gc.pid`, each `null` when unreadable), `declined-by-hook` (with the hook's `exit_code`), or `ran`. For `ran`, `trigger` is `loose-objects` (with `estimate` and `limit`) or `packs` (with `count` and `limit`). |
| `tasks` | array | One object per maintenance task; each value includes `task` (`pack-refs`, `reflog-expire`, `repack`, `prune`, `drop-large-blobs`, `commit-graph`, `midx`, `offload`) and task-specific counters plus `duration_ms`. |
| `tasks[].skipped` | string | `commit-graph` only, present when no graph was written: `shallow`, `grafts` or `replace-refs`. `commit_count` is then `0` and any existing graph has been deleted (dry run: would be). |

Example (abbreviated):

```json
{
  "dry_run": false,
  "tasks": [
    {
      "task": "reflog-expire",
      "duration_ms": 12,
      "entries_pruned": 0
    },
    {
      "task": "repack",
      "duration_ms": 842,
      "loose_before": 380,
      "packs_before": 0,
      "objects_packed": 412,
      "pack_bytes": 88234,
      "pack_path": ".git/objects/pack/pack-abc123….pack",
      "removed_pack_files": 0,
      "pruned_loose": 380,
      "unreachable_loose_pruned": 0
    },
    {
      "task": "commit-graph",
      "duration_ms": 120,
      "commit_count": 87,
      "path": ".git/objects/info/commit-graph",
      "removed_chain": false
    }
  ]
}
```

The `offload` task (from `grit gc offload`) has these fields:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `tasks[].remote` | string | The promisor remote the blobs moved to. |
| `tasks[].lop_git_dir` | string | The LOP's git directory. |
| `tasks[].filter` | string | The filter that chose the blobs, `blob:limit=<bytes>` or `blob:none`. |
| `tasks[].candidates` | number | Blobs selected that may move. |
| `tasks[].candidate_bytes` | number | Their uncompressed size. |
| `tasks[].copied_to_lop` | number | Blobs written into a new LOP pack. |
| `tasks[].already_in_lop` | number | Blobs the LOP already had in a pack an earlier offload wrote there. |
| `tasks[].dropped_from_main` | number | Blobs no longer stored here afterwards (`0` on a dry run). |
| `tasks[].skipped_checked_out` | number | Selected blobs kept because a worktree's index or `HEAD` needs them. |
| `tasks[].skipped_kept_pack` | number | Selected blobs kept because they are in a `.keep` pack. |
| `tasks[].lop_pack` | string or null | The pack added to the LOP. |
| `tasks[].main_pack` | string or null | The `.promisor` pack the rest of the repository (its commits, trees, tags and the blobs it keeps) now lives in; null when nothing had to be rewritten. |
| `tasks[].packs` | array | Every pack the run wrote, in order: `role` (`lop` or `main-promisor`), `path` (the `.pack` file), `objects` and `bytes` (size of the `.pack` file). Empty on a dry run or when nothing was written. |
| `tasks[].main_bytes_before` | number | Size of this repository's packs and loose objects before the run. |
| `tasks[].main_bytes_after` | number | The same afterwards. |
| `tasks[].config_changes` | array | Each `{repo, key, value}` set, `repo` being `main` or `lop`. |
| `tasks[].lop_ready` | object | `allow_filter` and `allow_any_sha1_in_want`: the LOP's upload-pack settings afterwards. |
| `tasks[].advertised` | boolean | `promisor.advertise` is on, so clients are told about the LOP. |

```json
{
  "dry_run": false,
  "tasks": [
    {
      "task": "offload",
      "duration_ms": 95,
      "remote": "lop",
      "lop_git_dir": "/srv/lop.git",
      "filter": "blob:limit=102400",
      "candidates": 2,
      "candidate_bytes": 500000,
      "copied_to_lop": 2,
      "already_in_lop": 0,
      "dropped_from_main": 2,
      "skipped_checked_out": 0,
      "skipped_kept_pack": 0,
      "lop_pack": "/srv/lop.git/objects/pack/pack-bc97733c….pack",
      "main_pack": "/srv/main.git/objects/pack/pack-32d0e589….pack",
      "packs": [
        { "role": "lop", "path": "/srv/lop.git/objects/pack/pack-bc97733c….pack", "objects": 2, "bytes": 500324 },
        { "role": "main-promisor", "path": "/srv/main.git/objects/pack/pack-32d0e589….pack", "objects": 6, "bytes": 506 }
      ],
      "main_bytes_before": 500813,
      "main_bytes_after": 1690,
      "config_changes": [
        { "repo": "main", "key": "remote.lop.promisor", "value": "true" },
        { "repo": "main", "key": "remote.lop.partialCloneFilter", "value": "blob:limit=102400" },
        { "repo": "main", "key": "repack.writeBitmaps", "value": "false" },
        { "repo": "main", "key": "grit.lopGitDir", "value": "/srv/lop.git" }
      ],
      "lop_ready": { "allow_filter": true, "allow_any_sha1_in_want": true },
      "advertised": true
    }
  ]
}
```

The `drop-large-blobs` task (from `grit gc drop-large-blobs`, or from `grit gc` when the task is enabled) has these fields:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `tasks[].min_size` | number | Blobs of at least this many bytes were candidates. |
| `tasks[].keep_newer_than` | number | Unix time of the recency cutoff; absent when nothing is kept for recency. |
| `tasks[].candidates` | number | Blobs in promisor packs at or above `min_size`. |
| `tasks[].dropped` | number | Blobs dropped (on a dry run, that would be). |
| `tasks[].bytes_reclaimed` | number | Bytes freed from the pack directory; on a dry run, the packed size of the dropped entries. |
| `tasks[].packs_rewritten` | number | Promisor packs rewritten without the dropped blobs. |
| `tasks[].packs_removed` | number | Promisor packs deleted because they held only dropped blobs. |
| `tasks[].kept` | object | Candidates that stayed, each counted once under the first reason that applies: `kept_pack`, `outside_promisor_packs`, `not_in_promisor` (no promisor stores it, and every promisor is on this machine and was read), `unverified` (no promisor this machine could read stores it, and offload has run here, so a network promisor is not trusted to, or a local promisor could not be read), `checked_out`, `recently_checked_out`, `recently_fetched`, `not_promised_elsewhere`. |
| `tasks[].blobs` | array | `{oid, size}` for each dropped blob, sorted by `oid`. |
| `tasks[].skipped` | string | `grit gc` only, when the enabled phase did not run: `no-promisor-remote`, `operation-in-progress`, `precious-objects`, `no-current-time` (a library caller gave gc no time; the `grit` command always does) or `other` (a reason newer than this grit). |

```json
{
  "dry_run": false,
  "tasks": [
    {
      "task": "drop-large-blobs",
      "duration_ms": 9,
      "min_size": 102400,
      "candidates": 3,
      "dropped": 2,
      "bytes_reclaimed": 602586,
      "packs_rewritten": 0,
      "packs_removed": 2,
      "kept": {
        "kept_pack": 0,
        "outside_promisor_packs": 0,
        "not_in_promisor": 0,
        "unverified": 0,
        "checked_out": 1,
        "recently_checked_out": 0,
        "recently_fetched": 0,
        "not_promised_elsewhere": 0
      },
      "blobs": [
        { "oid": "0be894fc2cbd410875c1e28b5c8fafdc385728a6", "size": 300000 },
        { "oid": "0d2993714f679f291a2a06dee665d04da7e8f6db", "size": 300000 }
      ]
    }
  ]
}
```

`grit gc commit-graph --json` in a shallow clone:

```json
{
  "dry_run": false,
  "tasks": [
    {
      "task": "commit-graph",
      "duration_ms": 0,
      "commit_count": 0,
      "path": ".git/objects/info/commit-graph",
      "removed_chain": false,
      "skipped": "shallow"
    }
  ]
}
```

## Markdown output

Pass `--markdown` for an agent-friendly report with the same fields as JSON as labelled bullets per task.

Schema: [v1](https://grit-scm.com/docs/gc/schemas/gc/v1.json/index.md)

Example (abbreviated):

```markdown
## Garbage collection

- **dry_run:** false

### Tasks

#### reflog-expire

- **duration_ms:** 12
- **entries_pruned:** 0

#### repack

- **duration_ms:** 842
- **loose_before:** 380
- **packs_before:** 0
- **objects_packed:** 412
- **pack_bytes:** 88234
- **pack_path:** `.git/objects/pack/pack-abc123….pack`
- **removed_pack_files:** 0
- **pruned_loose:** 380
- **unreachable_loose_pruned:** 0

#### commit-graph

- **duration_ms:** 120
- **commit_count:** 87
- **path:** `.git/objects/info/commit-graph`
- **removed_chain:** false
```

A skipped commit-graph task adds a `- **skipped:** shallow` (or `grafts`, `replace-refs`) bullet. An `offload` task lists its JSON fields as bullets, one `config_change` bullet per value set, and `lop_allow_filter` / `lop_allow_any_sha1_in_want` for `lop_ready`. A `drop-large-blobs` task lists its counters as bullets (the `kept` reasons as `kept_checked_out`, `kept_recently_fetched` and so on) followed by an `| oid | size |` table of the dropped blobs.


## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

- [`grit repack`](https://grit-scm.com/docs/gc/repack.md/index.md)
- [`grit fsck`](https://grit-scm.com/docs/gc/fsck.md/index.md)
- [`grit reflog expire`](https://grit-scm.com/docs/gc/reflog.md/index.md)

# https://grit-scm.com/docs/fsck/index.md

# grit fsck

> Check refs, objects, and pack indexes for problems.

## Synopsis

```text
grit fsck
grit fsck --connectivity-only
grit fsck --dangling
grit fsck --no-dangling
grit fsck --strict
grit fsck --verbose
grit verify
```

## Description

Verifies repository integrity without invoking the system `git` binary:

- Full run: loose and packed object validation, connectivity from ref roots, refs, multi-pack-index, and commit-graph checks when present.
- With `--connectivity-only`: walk reachability from refs, verify each linked object exists with the expected kind (commit, tree, tag, blob), and skip store-wide content validation and blob inflation (faster than a full run; does not re-hash or content-fsck every object).
- With `--dangling` (or by default on a full run): list **dangling** objects — present in the object database (including alternates), not reachable from refs, and not referenced by another object (matches Git’s default dangling tips, not the full unreachable closure).

In a shallow clone, the commits listed in `.git/shallow` count as having no parents, as in `git fsck`. Their missing parents are not reported. If a parent is present anyway, it is listed as dangling.

Ref checks include loose ref files, symrefs and `packed-refs`. On the **reftable** backend, Git-compatible placeholder files (`refs/heads` and loose `HEAD`) are ignored; refs are validated from the reftable store instead. A `packed-refs` file whose header claims the `sorted` trait while its records are out of order is an error (`packedRefUnsorted`, at the first out-of-order line). Normal reads trust that trait and binary-search the file, as Git does, so refs on the wrong side of the disorder can be invisible until the file is rewritten (for example by `grit gc`).

Progress during long checks is written to **stderr** in human mode (suppressed for `--json` / `--markdown`).

Packed objects are verified in a single streaming pass over each pack's delta trees, spread over `--threads` workers, so memory stays close to `git fsck` even on large repositories (git/git, about 422,000 objects: roughly 640 MB peak for grit against 510 MB for git, in about half git's time). An object whose delta base is corrupt or missing is reported as `corruptObject` together with every object built on top of it.

`grit verify` is an alias for `grit fsck`. Exit status **1** when any **error-severity** issue is reported. Warnings alone exit **0** unless `--strict` promotes ref warnings. Unreachable (**dangling**) objects alone do not fail the command.

## Options

| Option | Description |
| --- | --- |
| `--connectivity-only` | Skip full object-store validation; walk from ref roots and check object existence and link kinds (no per-object content fsck or blob body reads). |
| `--dangling` | With `--connectivity-only`, also compute and list unreachable objects (full fsck always includes dangling). |
| `--no-dangling` | Skip unreachable-object listing (matches Git `--no-dangling`). |
| `--strict` | Treat ref-fsck warnings as errors. |
| `-v`, `--verbose` | Include info-level object diagnostics in human output (Git hides these by default). |

## Examples

Clean repository:

```console
$ grit fsck
Checked 12 objects.
No integrity problems found.
```

Report problems:

```console
$ grit fsck
Checked 8 objects.

Issues:
  missingObject (1):
    deadbeef…: object deadbeef… referenced by abcd1234…

Integrity check failed.
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/fsck/schemas/fsck/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `ok` | boolean | `true` when no error-severity issues were found (warnings and info alone still yield `true`). |
| `objects_checked` | integer | Loose and packed objects examined during store validation in the primary `objects/` directory and any alternates (0 with `--connectivity-only`). |
| `issues` | array | Each entry has `kind` (camelCase msg-id), `severity` (`error`, `warning`, or `info`), optional `oid` and `path`, and `detail`. Known kinds include `missingObject`, `hasSha1`, and `sha1Collision` (optional sha1dc signal; default severity is **warning**, matching Git’s tolerance for SHAttered objects). |
| `dangling` | array | Unreachable objects as `{kind, oid}` (`kind` is `commit`, `tree`, `blob`, or `tag`). |

Example:

```json
{
  "ok": true,
  "objects_checked": 12,
  "issues": [],
  "dangling": []
}
```

Example with a problem:

```json
{
  "ok": false,
  "objects_checked": 8,
  "issues": [
    {
      "kind": "missingObject",
      "severity": "error",
      "oid": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
      "detail": "object deadbeefdeadbeefdeadbeefdeadbeefdeadbeef referenced by abcd1234abcd1234abcd1234abcd1234abcd1234"
    }
  ],
  "dangling": []
}
```

When configured to surface sha1dc diagnostics, `sha1Collision` is a **warning**
by default (strict mode promotes it to an error). Detection covers the object
header and payload together, as in Git, so a blob that merely contains colliding
bytes, such as the SHAttered PDFs in Git's own test suite, is an ordinary object:

```json
{
  "ok": true,
  "objects_checked": 1,
  "issues": [
    {
      "kind": "sha1Collision",
      "severity": "warning",
      "oid": "ba9aaa145ccd24ef760cf31c74d8f7ca1a2e47b0",
      "detail": "SHA-1 chosen-prefix collision: …"
    }
  ],
  "dangling": []
}
```

## Markdown output

Pass `--markdown` for a summary with `ok`, a table of issues (including severity), and dangling objects. Info-level issues appear in `--json` and `--markdown` but are omitted from default human output unless `--verbose` is set.

Schema: [v1](https://grit-scm.com/docs/fsck/schemas/fsck/v1.json/index.md)




```text
## Fsck

- **ok:** true
- **objects_checked:** 9

### Dangling

- `blob` `cc7c1250b368e807ba98143f3b0b47c3cd8b74fe`
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | No error-severity issues (warnings alone are OK unless `--strict`). |
| `1` | At least one error-severity issue ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

Unreachable objects alone do not fail the command. See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md).


## See also

- [`grit gc`](https://grit-scm.com/docs/fsck/gc.md/index.md)
- [`grit bundle verify`](https://grit-scm.com/docs/fsck/bundle.md/index.md)

# https://grit-scm.com/docs/hooks/index.md

# grit hooks

> List hook scripts and run them by name.

## Synopsis

```text
grit hooks
grit hooks list
grit hooks run <NAME> [-- ARGS...]
```

## Description

Discovers traditional hook scripts in the resolved hooks directory (`core.hooksPath` when set, otherwise `.git/hooks`). A relative `core.hooksPath` is relative to the directory hooks run in (the top of the work tree, or the git directory in a bare repository), so the same hooks are found from any subdirectory. Configured `hook.<name>.*` aliases are resolved when a hook runs, not in the list.

`grit hooks run` executes every hook registered for the event (config hooks first, then the script in the hooks directory) through the repository [`CommandRunner`](https://grit-scm.com/docs/library/maintenance.md/index.md). The process exits with the hook's status when a hook ran and returned non-zero.

What a hook prints depends on the output mode. In human mode the hook writes straight to the terminal as it runs, with its stdout sent to stderr (every hook except `pre-push`, as in Git), so stdout stays free for grit's own output. With `--json` or `--markdown`, grit captures both streams and puts them in the result instead (`stdout` and `stderr` below), and nothing reaches the terminal.

Hooks run with the invoking environment (including `PATH`), from the top of the work tree. A script the OS will not execute directly runs through `sh`: `/bin/sh` on Unix, while on Windows a script's `#!` line names its interpreter (`#!/bin/sh` → `sh`, `#!/usr/bin/env bash` → `bash`), looked up first in the Git for Windows install that owns the `git` on `PATH` (`usr\bin`, `bin`), then on `PATH`, skipping the WSL launchers in `System32` and `WindowsApps`. When the interpreter comes from a Git for Windows install, that install's `mingw64\bin` (or `clangarm64\bin`, `ucrt64\bin`, `mingw32\bin`) and `usr\bin` go in front of the hook's `PATH`, as Git does, so `grep`, `sed`, `env` and the other MSYS tools are found. Hook paths, in `list` output and on the hook's command line, and the repository paths hooks receive (`GIT_DIR`, `GIT_COMMON_DIR`, `GIT_WORK_TREE`, `GIT_INDEX_FILE`, `GIT_OBJECT_DIRECTORY`) never carry the Windows `\\?\` prefix, so `git` run inside a hook reads the same index grit wrote. Commit hooks (`pre-commit`, `pre-merge-commit`, `prepare-commit-msg`, `commit-msg`, `post-commit`) get `GIT_INDEX_FILE` for the index being committed, and `GIT_EDITOR=:` because grit never opens an editor.

When a hook cannot be started at all (for example, its interpreter is missing), the command fails with an error naming the hook, the program it tried to start and the OS error, instead of reporting an exit status:

```console
$ grit hooks run pre-commit
error: failed to run hook pre-commit (.git/hooks/pre-commit): No such file or directory (os error 2)
$ echo $?
1
```

In `--json` mode the same message is the `error` field. [`grit commit`](https://grit-scm.com/docs/hooks/commit.md/index.md), [`grit merge`](https://grit-scm.com/docs/hooks/merge.md/index.md) and [`grit rebase`](https://grit-scm.com/docs/hooks/rebase.md/index.md) report it the same way for the hooks that run before they change anything (the table below); for `post-commit` and the other hooks that run after an operation completes, it is a warning and the operation still succeeds.

These hooks run before an operation records anything, with Git's arguments and in Git's order. A non-zero exit (or a hook that cannot be started) stops the operation:

| Hook | Run by | Arguments | Skipped by `--no-verify` |
| --- | --- | --- | --- |
| `pre-commit` | [`grit commit`](https://grit-scm.com/docs/hooks/commit.md/index.md), `grit merge --continue` | none | yes |
| `pre-merge-commit` | [`grit merge`](https://grit-scm.com/docs/hooks/merge.md/index.md) and [`grit pull`](https://grit-scm.com/docs/hooks/pull.md/index.md) before a clean merge records its commit | none | yes |
| `prepare-commit-msg` | `grit commit`, then `grit merge` | the message file (`.git/COMMIT_EDITMSG`, or `.git/MERGE_MSG` for a merge) and its source: `message` (`-m`, `-F`), `commit <oid>` (`--amend` or `-C` reusing a message), `merge` (a merge message, always for `grit merge`) or `squash` (`SQUASH_MSG`) | no, as in Git |
| `commit-msg` | `grit commit`, then `grit merge` | the message file | yes |
| `pre-rebase` | [`grit rebase`](https://grit-scm.com/docs/hooks/rebase.md/index.md) and `grit pull --rebase` when there are commits to replay | the upstream as you named it (the configured upstream's full ref, such as `refs/remotes/origin/main`, when omitted; the commit id for a pull) | yes |
| `pre-push` | [`grit push`](https://grit-scm.com/docs/hooks/push.md/index.md) before sending anything | remote name and URL; stdin lists the refs | yes |

`prepare-commit-msg` and `commit-msg` may rewrite the message file, and the commit records what they leave (an empty message aborts). A merge's message hooks see `MERGE_HEAD`, as in Git. A refused merge leaves the merged files with `MERGE_HEAD` recorded and the branch unchanged; finish it with `grit merge --continue` (or [`grit commit`](https://grit-scm.com/docs/hooks/commit.md/index.md)) or cancel it with `grit merge --abort`. Changes a `pre-merge-commit` hook stages (lint-staged style) go into the merge commit. A refused commit or rebase changes nothing. JSON commit output lists hook basenames that actually ran in `hooks_run`. Replayed commits ([`grit rebase`](https://grit-scm.com/docs/hooks/rebase.md/index.md), [`grit pick`](https://grit-scm.com/docs/hooks/pick.md/index.md), [`grit revert`](https://grit-scm.com/docs/hooks/revert.md/index.md)) do not run the commit hooks.

Other commands run the hooks Git runs after them, with Git's arguments:

| Hook | Run by | Arguments and stdin |
| --- | --- | --- |
| `post-checkout` | [`grit switch`](https://grit-scm.com/docs/hooks/switch.md/index.md), [`grit worktree add`](https://grit-scm.com/docs/hooks/worktree.md/index.md) (after checkout), [`grit rebase`](https://grit-scm.com/docs/hooks/rebase.md/index.md) and [`grit history`](https://grit-scm.com/docs/hooks/history.md/index.md) rewrites that change `HEAD`'s tree | `<old HEAD> <new HEAD> 1` (all-zero old id from an unborn branch or a new linked worktree); for a rebase, `<old tip> <onto> 1` like Git |
| `post-merge` | [`grit merge`](https://grit-scm.com/docs/hooks/merge.md/index.md) and [`grit pull`](https://grit-scm.com/docs/hooks/pull.md/index.md) after a fast-forward or merge commit (`0`) or a squash (`1`) | `0` or `1` |
| `post-rewrite` | `grit commit --amend` (`amend`), `grit rebase` and `grit history` rewrites (`rebase`) | `amend` or `rebase`; stdin has one `<old> <new>` line per rewritten commit |

These hooks run after the operation is complete, so their exit status never changes the result, and a hook that cannot be started is a `hook_not_run` warning. `--dry-run` and `--check` run no hooks. [`grit switch`](https://grit-scm.com/docs/hooks/switch.md/index.md) and [`grit commit`](https://grit-scm.com/docs/hooks/commit.md/index.md) list the hooks that ran in their JSON `hooks_run` field.

### `reference-transaction`

Grit runs the [`reference-transaction`](https://git-scm.com/docs/githooks#_reference_transaction) hook for every ref-store transaction that changes direct object ids (create, update, delete, or reflog-only oid lines on `HEAD`). Pure symbolic updates (for example switching between two existing branches without moving a tip) do not run the hook, matching Git 2.43.

| Phase | When | Exit status |
| --- | --- | --- |
| `prepared` | After locks are taken, before any ref or reflog is written | Non-zero aborts the whole batch; grit then runs `aborted` (exit ignored) |
| `committed` | After the transaction commits successfully | Ignored |
| `aborted` | After `prepared` refused or the batch was aborted without writing | Ignored |

Stdin is one line per ref update, sorted by ref name: `<old-hex> <new-hex> <ref>\n`. Old and new ids use the repository hash width; absent refs or deletions use the null object id. Attached commits on the files backend emit the same `HEAD` and branch lines Git does (same old and new commit ids, `HEAD` first lexicographically).

This hook is **not** skipped by `--no-verify` on commands that honor `--no-verify` for other hooks. Configured `hook.reference-transaction.*` entries and `core.hooksPath` apply the same way as for other hooks.

## Options

### `grit hooks list`

| `-n`, `--limit <N>` | List at most `N` hook scripts (`truncated` in JSON when more exist). |

Other [global options](https://grit-scm.com/docs/global-options.md/index.md) apply.

### `grit hooks run`

| Argument | Description |
| --- | --- |
| `NAME` | Hook basename (e.g. `pre-commit`). |
| `ARGS` | Optional arguments after `--`, forwarded to the hook. |

## Examples

List installed scripts:

```console
$ grit hooks list
pre-commit  /path/to/repo/.git/hooks/pre-commit  executable=yes  hooks_dir
```

Run a hook:

```console
$ grit hooks run pre-commit
$ echo $?
0
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/hooks/schemas/hooks/v1.json/index.md). Subcommands: [hooks.list](https://grit-scm.com/docs/hooks/schemas/hooks.list/v1.json/index.md), [hooks.run](https://grit-scm.com/docs/hooks/schemas/hooks.run/v1.json/index.md).

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `action` | string | `list` or `run`. |
| `hooks` | array | For `list`: each entry has `name`, `path`, `executable`, and `source` (`hooks_dir` or `core_hooks_path`). |
| `truncated` | boolean | For `list`: `true` when more hook scripts existed than returned (`-n` / `--limit`). |
| `name` | string | For `run`: hook basename. |
| `exit_code` | number | For `run`: subprocess exit code (`0` when the hook was missing). |
| `executed` | boolean | For `run`: whether any hook script ran. |
| `stdout` | string | For `run`: what the hooks wrote to stdout (lossy UTF-8; empty when no hook ran). |
| `stderr` | string | For `run`: what the hooks wrote to stderr (lossy UTF-8; empty when no hook ran). |

Example list:

```json
{
  "action": "list",
  "hooks": [
    {
      "name": "pre-commit",
      "path": "/tmp/repo/.git/hooks/pre-commit",
      "executable": true,
      "source": "hooks_dir"
    }
  ]
}
```

Example run of a `pre-commit` hook that prints a line on each stream and exits 17:

```json
{
  "action": "run",
  "name": "pre-commit",
  "exit_code": 17,
  "executed": true,
  "stdout": "to-stdout\n",
  "stderr": "to-stderr\n"
}
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/hooks/schemas/hooks/v1.json/index.md)

`--markdown` renders a table of hooks for `list`, or a short summary for `run` followed by the hook's captured output under **Hook stdout:** and **Hook stderr:** headings, each in a `text` code block (a stream the hook left empty is omitted).

```text
## Hooks

| Name | Path | Executable | Source |
| --- | --- | --- | --- |
| `pre-commit` | `[REPO]/.git/hooks/pre-commit` | true | hooks_dir |
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | `hooks list` or `hooks run` when the hook exits 0 (or the hook is missing). |
| *varies* | `hooks run` returns the hook subprocess exit code ([`custom`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | `hooks run` when a hook could not be started ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md).


## See also

- [Library maintenance — hooks](https://grit-scm.com/docs/library/maintenance.md/index.md)
- [`grit patch-id`](https://grit-scm.com/docs/hooks/patch-id.md/index.md)

# https://grit-scm.com/docs/upload-pack/index.md

# grit upload-pack

> Serve a fetch or clone of a repository over stdin and stdout.

## Synopsis

```text
grit upload-pack [--stateless-rpc] [--advertise-refs] <directory>
```

## Description

The server side of fetch and clone. It speaks the Git wire protocol on stdin and stdout, so any Git client, `git` or `grit`, can fetch from a repository it serves. You don't normally run it yourself: an SSH server runs it when a client connects, and `grit-http-server` answers smart HTTP requests by calling the same logic in `grit-lib` in-process (no separate `grit` binary next to the server). It doesn't appear in `grit --help`.

`<directory>` is the repository to serve: a bare repository, a working tree, or a path that names one once `.git` is added. Unlike other commands, `grit upload-pack` doesn't search parent directories, so it serves exactly the repository it was given.

It supports Git protocol versions 0, 1 and 2, chosen by the client through the `GIT_PROTOCOL` environment variable. Refs matching `uploadpack.hideRefs` or `transfer.hideRefs` are not shown to clients.

The pack is built the way Git builds one when serving: objects already stored in the repository's packs are copied as they are, whole objects and deltas alike, and only objects that are not yet stored as deltas (loose or newly written blobs, trees and commits) go through the delta search, which reads each object only while it is in the search window, so serving a repository full of loose objects costs about as much memory as serving a packed one. `pack.window` and `pack.depth` set that search's window and maximum chain length; as with Git, `pack.depth = 0` stops new deltas but still sends the deltas already on disk. Each delta's base is written before it, so deltas use the compact offset form, and partial-clone (filtered) packs stream the same way. A thin pack is sent only when the client asked for one and already has objects to delta against. The pack is streamed to the client while it is written, so a full clone of an already-packed repository costs about as much time and memory as it does with `git upload-pack`.

In protocol v2 negotiation, each round of `have` lines is answered with an `acknowledgments` section that lists the haves the server also has (or `NAK` when there are none). When those haves already cover everything the client wants, the server adds `ready` and sends the pack in the same response, so a client that is a few commits behind finishes after one round instead of walking its whole history back to the server. A want counts as covered when its history reaches an acknowledged commit or one of that commit's parents, without going past the oldest acknowledged commit's date. Wants that are trees or blobs never hold the negotiation open. A client that sends `wait-for-done` (as `git fetch --negotiate-only` does) never gets `ready`: the server keeps answering with acknowledgments until the client sends `done`.

Shallow and deepen requests (`deepen`, `deepen-since`, `deepen-not`, `deepen-relative`, client `shallow` lines) are honored in protocol v0/v1 and in v2 `fetch` (including the `shallow-info` section). Over smart HTTP (v0/v1 `--stateless-rpc`), a request that carries `deepen`, `deepen-since`, or `deepen-not` sends the flush-terminated `shallow` / `unshallow` section before any negotiation ACKs, as Git does. `deepen-not`, which `git clone --shallow-exclude=<ref>` sends, takes a ref name as Git does: a full name such as `refs/tags/v1.0`, or a short name such as `v1.0` that must match exactly one ref. A full object id also works. Annotated tags are peeled to their commit. Wanted annotated tags count depth from the commit they name, and `shallow` lines always name commits. With `include-tag`, the pack gets every annotated tag (and the tags it names in turn) whose final object, whether a commit, tree or blob, is among the objects being sent. The check runs against the pack's object list, not the history, so its cost follows the size of the fetch. A shallow fetch therefore only adds the tags on commits it actually sends, and `git clone --depth 1` of a tagged repository receives one commit, as with `git upload-pack`. Partial-clone filters (`filter blob:none`, `blob:limit=<n>`, `tree:<depth>`, `object:type=<type>`, `sparse:oid=<blob>`, and `combine:` of them) follow `uploadpack.allowFilter` and `uploadpackfilter.*` policy.

A filtered pack holds the objects `git upload-pack` would send for the same request: the wanted objects and every annotated tag the client asked for or that `include-tag` adds, then the commits, trees and blobs the filter keeps. It is built and streamed like an unfiltered one, reusing the objects and deltas already stored, and the pack bitmap selects the objects when it can apply the filter (`blob:none`, `blob:limit`, `tree:0`). A blob-less clone therefore costs about what a full clone does without the blobs. Trees a filter rules out are not read, and blob sizes are only looked up for `blob:limit`. Under `combine:` with `tree:<depth>`, `git` can leave out a tree it first met too deep even when it meets the tree again within the depth; grit sends such a tree.

Protocol v2 `want-ref` is accepted only when `uploadpack.allowRefInWant` is set, and the response then includes a `wanted-refs` section with the object each requested ref resolved to. Asking for the same ref twice is a protocol error. Protocol v2 `sideband-all` is advertised and accepted only when `uploadpack.allowSidebandAll` is set. Optional `want` rules follow `uploadpack.allowTipSha1InWant`, `uploadpack.allowReachableSha1InWant` and `uploadpack.allowAnySHA1InWant`. The last lets a client want any object the repository has, reachable or not, and also turns on the other two capabilities in protocol v0. A large-object promisor needs it: it holds blobs that no ref points at, and clients fetch them by object id.

In `--stateless-rpc` mode (smart HTTP POST), any commit reachable from the server's current ref tips may appear in a `want` line without those config flags. That matches Git when ref discovery and the fetch run as separate requests and a push can move refs in between. Stateful sessions (SSH and the negotiation half of a long-lived connection) still require each `want` to match the ref advertisement from that session unless `uploadpack.allowReachableSha1InWant` or `uploadpack.allowTipSha1InWant` is set.

### Promisor remotes

A repository that keeps some of its objects on other remotes (a large-object promisor holding the big blobs, for example) can tell clients about them. With `promisor.advertise = true`, the protocol v2 capabilities end with a `promisor-remote` line that names each of the repository's promisor remotes (`remote.<name>.promisor = true`, a `remote.<name>.partialCloneFilter`, or the `extensions.partialClone` remote, listed last) that has a URL. `promisor.sendFields` adds each remote's `partialCloneFilter` and `token` when they are set. Protocol v0 and v1 never carry the capability.

```text
promisor-remote=name=lop,url=https://lop.example.com/project.git,partialCloneFilter=blob:limit=1m
```

A client that accepts some of these remotes says so with a `promisor-remote=<names>` line in the capabilities of its command requests. The server keeps only the names it advertised. In a stateful session (SSH, `git://`, a local pipe) the acceptance lasts until the connection closes, so a reply sent with `ls-refs` covers the `fetch` that follows. Over smart HTTP each request stands alone: only a reply in the `fetch` request itself counts. `grit` clients send it with both commands; `git` clients send it only with `ls-refs`, so over smart HTTP their acceptance never reaches the fetch. A `promisor-remote` line with no names is a protocol error.

### Serving a repository whose large blobs live elsewhere

A repository with promisor remotes of its own may lack some objects: after [`grit gc offload`](https://grit-scm.com/docs/gc/index.md#grit-gc-offload) its large blobs live only on a large-object promisor (LOP), and its other objects sit in a `.promisor` pack. Such a repository is *partial*, and upload-pack serves it by Git's rules:

- When the client accepted at least one advertised promisor remote, a promised blob the repository does not have is left out of the pack. The client fetches it from the LOP. A blob is promised when an object in a promisor pack refers to it.
- A client whose own filter leaves those blobs out gets the same pack without accepting anything. That holds when every promisor remote of the repository has a blob `partialCloneFilter` (`blob:none`, or `blob:limit=<n>`) and the fetch is filtered with `blob:none`, or with `blob:limit=<m>` where `m` is at most the smallest `n`: it would not have been sent those blobs anyway. Git's upload-pack has no such rule. Blobs the client wants by id are sent whatever its filter says, so a want of a promised blob still needs acceptance.
- Otherwise the request fails. The server first fetches the missing blobs from its own promisor remotes only if lazy fetch is on. That takes `uploadpack.lazyFetch = true` (a grit setting) or `GIT_NO_LAZY_FETCH=0` in the environment of `grit upload-pack` or `grit serve`. Git's upload-pack has the same `GIT_NO_LAZY_FETCH=0` switch. The fetched blobs go into a new `.promisor` pack in the served repository, and the client's filter still applies to them: a `blob:limit` client is not sent the large blobs the server fetched.
- A missing object that nothing promises is an error in every case.

The pack is planned before anything is sent, so a refusal reaches the client as a clean error, not a broken pack. Protocol v2 clients get an `ERR` line, which Git prints as `fatal: remote error: …`. The message names the blob and the advertised promisor remotes, and suggests `promisor.acceptFromServer` on the client or `uploadpack.lazyFetch` on the server. Protocol v0 clients get the same text on side band 3, or as an `ERR` line when they want the promised blob itself. Wants for a promised blob itself (a client's lazy fetch) follow the same rule; an accepting client gets an empty pack and asks the LOP next.

This applies only to repositories with a promisor remote (`remote.<name>.promisor = true` or `extensions.partialClone`). For those, the pack is chosen with the object walk instead of bitmaps or verbatim pack reuse; other repositories keep the fast path. Only blobs can be left out. A missing commit, tree or tag still fails the request; `grit gc offload` only ever removes blobs.

Over smart HTTP, each request carries its own acceptance (see above). Git clients accept only on `ls-refs`, so their `fetch` arrives without it. Their partial clone still works when its filter is no looser than the promisor remotes' `partialCloneFilter` (for example `git clone --filter=blob:limit=1m` against a LOP advertised with `blob:limit=1m`). For a looser filter, a large-object setup served over HTTP to Git clients needs lazy fetch on the server, or a stateful transport (SSH, `git://`).

## Options

| Option | Description |
| --- | --- |
| `<directory>` | The repository to serve. |
| `--stateless-rpc` | Answer a single request and exit, without advertising refs first. Used for smart HTTP. |
| `--advertise-refs` | Print the ref advertisement and exit. Used for the first request of smart HTTP. Also accepted as `--http-backend-info-refs`. |

## Examples

Clone over SSH from a server that has `grit` but not `git` installed:

```console
$ git clone --upload-pack='grit upload-pack' ssh://example.com/srv/git/project.git
```

Set it for a remote you already have:

```console
$ git config remote.origin.uploadpack 'grit upload-pack'
```

## JSON output

None. `--json` has no effect, since stdout carries the Git protocol.


## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[grit receive-pack](https://grit-scm.com/docs/receive-pack/index.md), [grit clone](https://grit-scm.com/docs/clone/index.md), [grit fetch](https://grit-scm.com/docs/fetch/index.md)

# https://grit-scm.com/docs/patch-id/index.md

# grit patch-id

> Stable patch-IDs for commits (cherry-pick equivalence).

## Synopsis

```text
grit patch-id <REV|RANGE>...
grit patch-id --unstable <REV|RANGE>...
```

## Description

Prints one line per commit that has a defined patch-ID: `<patch-id> <commit>`, matching `git show --format= --no-ext-diff -U3 <REV> | git patch-id --stable` on the commit's tree diff. Text hunks include three unchanged context lines on each side; nearby context contributes to the ID, while unchanged lines outside the hunks do not. Hunks come from the same diff as `grit diff` and Git's default (Myers with the indent heuristic), so an insertion or deletion that could slide to several equally short positions is hashed where Git places it; a final line without a newline never counts as equal to the same text with one. In stable and unstable modes spaces, tabs, carriage returns and newlines are dropped before hashing, while other control characters such as form feed still count, as in Git. A submodule pointer (gitlink) is hashed as its `Subproject commit <oid>` line, so the submodule's commit never has to exist in this repository, and a path that changes type (for example a file replaced by a symlink or a submodule) is hashed as a deletion plus an addition, as `git show` prints it. Merge commits and commits with no file changes are omitted.

A range argument expands to one line per commit, in the same order as [`grit revs`](https://grit-scm.com/docs/revs/index.md):

- `A..B` lists the commits reachable from `B` but not from `A`, such as the commits of a branch since it left `main`.
- `A...B` lists the commits on both sides of the symmetric difference as one sequence, without saying which side each came from. To compare two versions of a rewritten branch, use [`grit revs --cherry-mark A...B`](https://grit-scm.com/docs/revs/index.md), which pairs the sides by patch-ID.

Any other argument names one commit. Output follows argument order, so a commit named twice is printed twice.

Uses [`Repository::patch_ids_for_revs`](https://grit-scm.com/docs/library/maintenance.md/index.md) with stable accumulation (file order independent). Pass `--unstable` for the legacy Git 1.9 algorithm.

### Benchmarking

Compare the same commit with the installed system Git:

```bash
/usr/bin/time -v grit patch-id HEAD --json
/usr/bin/time -v sh -c 'git show --format= --no-ext-diff -U3 HEAD | git patch-id --stable'
```

Use a large text file with sparse edits to measure hunk traversal rather than only process startup. Record wall time and peak resident memory with warm object caches; use the `dist` profile when building grit locally.

Measured on 2026-10-26 on Linux x86_64 (4 vCPUs, AMD EPYC 9V74), using a 14 MB file with 200,000 unique lines and ten replacements spaced 20,000 lines apart. Both grit binaries use the `dist` profile. Results are medians of 21 interleaved warm-cache runs per command after one warm-up; peak RSS comes from `/usr/bin/time -v` for each invocation.

| Implementation | Wall time | Median peak RSS | Peak RSS range |
| --- | ---: | ---: | ---: |
| System Git 2.55.0 | 62.91 ms | 62,604 KiB | 61,696–63,240 KiB |
| Grit before fix (`fa6a9fd55`) | 175.43 ms | 100,732 KiB | 100,008–101,892 KiB |
| Grit with three context lines | 146.02 ms | 101,632 KiB | 100,800–101,988 KiB |

The fix reduces median wall time by 17%. Median peak RSS differs by 900 KiB (0.9%), with overlapping observed ranges. The fixed result matches system Git's patch-ID for a normal unified diff on this fixture.

Ranges hash their commits on worker threads. Measured on 2026-10-27 on Linux x86_64 (4 vCPUs) with system Git 2.43.0 and a `release` build of grit, in a packed repository with a commit-graph: 5,000 base commits, a 100-commit branch rebased onto 200 new upstream commits (`old...new` has 400 commits). Means of 30 warm runs (hyperfine):

| Command | Wall time | Peak RSS |
| --- | ---: | ---: |
| `git rev-list old...new \| git diff-tree --stdin -p \| git patch-id --stable` | 20.3 ms | — |
| `grit patch-id old...new` | 17.6 ms | 23,576 KiB |
| `git rev-list --left-right --cherry-mark old...new` | 10.2 ms | 8,392 KiB |
| `grit revs --cherry-mark old...new` | 22.9 ms | 26,444 KiB |

Git's cherry-mark compares a cheap file-header id before computing a full patch-ID; grit computes the full ID for every commit, which accounts for most of the remaining gap.

## Options

| Option | Description |
| --- | --- |
| `--unstable` | Use unstable patch-ID hashing instead of stable (default). |

## Examples

```console
$ grit patch-id HEAD~2 HEAD~1 HEAD
a1b2c3d4e5f6789012345678901234567890abcd 0123456789abcdef0123456789abcdef01234567
fedcba0987654321fedcba0987654321fedcba09 abcdef0123456789abcdef0123456789abcdef01
```

Patch-IDs of a branch's commits since it left `main`, newest first (a rebase or a reworded message keeps each ID):

```console
$ grit patch-id main..feature
bbbce41090c2fd38689e39dda9f033194ea6b8cb 09d5318d2c9bb2881fd2b503861aadf43737463e
efc092c14f58acc31f0e129f61815ec4caccc849 a41d2d81bcbea60b67ac7f6c530d71bea889b628
9b734e090c6e3f7098bbf1fb6129bc3eeefb785b e778fe04f49705176ea24d7fa28182952a835187
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/patch-id/schemas/patch-id/v1.json/index.md)

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `entries` | array | Each item has `patch_id` and `commit` (full hex object ids), in argument order with ranges expanded. |

Example:

```json
{
  "entries": [
    {
      "patch_id": "a1b2c3d4e5f6789012345678901234567890abcd",
      "commit": "0123456789abcdef0123456789abcdef01234567"
    }
  ]
}
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/patch-id/schemas/patch-id/v1.json/index.md)

`--markdown` prints a table of patch IDs and commits.

```text
## Patch IDs

| Patch ID | Commit |
| --- | --- |
| `db20cbf19404d5a762136b964e1df57a06af6104` | `83352a61f6715ec3f0a297c6d6150725154fb833` |
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.

## See also

- [Library maintenance — patch IDs](https://grit-scm.com/docs/library/maintenance.md/index.md)
- [`grit revs --cherry-mark`](https://grit-scm.com/docs/patch-id/revs.md/index.md)
- [`grit pick`](https://grit-scm.com/docs/patch-id/pick.md/index.md)

# https://grit-scm.com/docs/receive-pack/index.md

# grit receive-pack

> Accept a push to a repository over stdin and stdout.

## Synopsis

```text
grit receive-pack [--stateless-rpc] [--advertise-refs] <directory>
```

## Description

The server side of push. It speaks the Git wire protocol on stdin and stdout, receives the objects a client sends, and updates the repository's refs. You don't normally run it yourself: an SSH server runs it when a client pushes, and `grit-http-server` answers smart HTTP requests by calling the same logic in `grit-lib` in-process (no separate `grit` binary next to the server). It doesn't appear in `grit --help`.

`<directory>` is the repository to push to: a bare repository, a working tree, or a path that names one once `.git` is added. It doesn't search parent directories.

Every ref update is checked before it's applied, and the client is told which updates were accepted and why any were refused. These settings in the served repository's config control what's allowed:

| Setting | Effect |
| --- | --- |
| `receive.denyNonFastForwards` | Refuse updates that would discard commits from a branch (`refs/heads/*`). Fast-forwards are accepted, and other refs, such as tags, are not checked. |
| `receive.denyDeletes` | Refuse to delete refs. |
| `receive.denyCurrentBranch` | What to do when a push updates the branch checked out in a non-bare worktree. `refuse` or unset (default) rejects the update. `ignore` and `false` move the ref without touching the worktree. `warn` does the same and may log a warning. `updateInstead` moves the ref and runs the `push-to-checkout` hook when present, otherwise checks that the worktree is clean and checks out the new commit's tree into the index and working tree (without moving `HEAD`). A dirty worktree or a failed checkout refuses the push with the same messages as Git. |
| `receive.denyDeleteCurrent` | Refuse to delete the branch `HEAD` points at, in a bare repository too. On by default; set it to `ignore` or `warn` to allow it. |
| `receive.hideRefs`, `transfer.hideRefs` | Hide refs from pushing clients and refuse updates to them. |
| `receive.maxInputSize` | Refuse pushes whose pack is larger than this many bytes. Unlimited by default. |
| `receive.unpackLimit`, `transfer.unpackLimit` | Store pushes with fewer objects than this as loose objects; keep larger ones as a pack with an index. 100 by default. |
| `receive.fsckObjects` | Check every pushed commit, tree and tag before any of them is stored. One malformed object refuses the whole push: the client sees `[remote rejected] ... (unpacker error)`, no ref changes, and nothing from the push enters the repository. Off by default. |
| `transfer.fsckObjects` | Used when `receive.fsckObjects` is unset. |
| `receive.fsck.<msg-id>` | Set one check to `error`, `warn` or `ignore`, for example `receive.fsck.missingEmail=warn`. The check after an accepted problem still runs, so ignoring one problem doesn't let another through. `nulInHeader` and `unterminatedHeader` are always errors. |
| `receive.fsck.skipList` | A file of object ids, one per line (`#` starts a comment), that are never checked. A relative path is relative to the repository's git directory. If the file can't be read, every push is refused. |
| `receive.shallowUpdate` | Accept pushes from a shallow clone that would make this repository shallow, and record the client's boundaries in its `shallow` file. Off by default: such an update is refused with `[remote rejected] ... (shallow update not allowed)`. A shallow clone pushing onto history this repository already has never needs it. |

The pushed pack is streamed to a temp file in a quarantine directory inside the repository's object store, so memory use stays flat however large the push is. Its objects become visible in the repository only after the `pre-receive` hook accepts the push.

Every pushed history is checked to be complete, as `git receive-pack` checks it (`rev-list --objects <new tips> --not --all`), however the push was stored: unpacked into loose objects below `receive.unpackLimit`, installed as a pack above it, or with no objects at all. Each new ref tip is walked down to what the repository's refs and `HEAD` already reach, and every object on the way must be there. An object the repository has is not enough by itself: a ref refused for missing objects leaves the objects that did arrive behind (the push is stored for the refs that were accepted, as Git stores it), and a later push naming that commit again is refused too. The commit walk paints the new tips against the commits the refs point at, newest first, using the commit-graph where there is one, and stops once no queued commit is new; each new commit's tree is then compared with its parents' trees, and only the entries that differ are followed. So the check costs about as much as the history the push adds, not the repository's. A ref whose tip reaches a missing object is refused with `[remote rejected] ... (missing necessary objects)`, as Git refuses it, and the other refs of the push are applied as usual. Objects a promisor remote of the repository promises (blobs offloaded with [`grit gc offload`](https://grit-scm.com/docs/gc/index.md#grit-gc-offload), say) may be missing, and so may the parents of the pushing client's shallow boundaries and of the repository's own.

There is no other limit on push size. `grit-http-server` streams a push body straight into receive-pack instead of buffering it, so a push of any size works over smart HTTP, as with `git http-backend`. Fetch requests, which are small, are capped at 32 MiB (after gzip decoding). Git doesn't gzip push bodies, but if another client does, the decoded body may reach 32 MiB and beyond that at most 32 times the compressed bytes received; a body that expands further is refused with `413`, and one that isn't valid gzip with `400`.

In a repository with [snapshot checkouts](https://grit-scm.com/docs/checkout/index.md) (once [`grit serve`](https://grit-scm.com/docs/serve/index.md#snapshot-checkouts) has made one), pushes that create, update or delete the target branch, the one `HEAD` names, are refused whatever these settings say, as `grit serve` refuses them: that branch changes only through [`grit integrate`](https://grit-scm.com/docs/integrate/index.md) and [`grit slice`](https://grit-scm.com/docs/slice/index.md). The refused client is told to push another branch and integrate it.

Pushes from a shallow clone work, such as a CI job that cloned with `--depth 1` and pushes a new branch back. Git sends the clone's shallow boundaries along with the push. When this repository already has the history below them, the push is applied as usual and the repository stays complete.

Pushes that ask for an atomic update are applied all or nothing. The served repository's `pre-receive`, `update`, `post-receive` and `post-update` hooks run as they do under Git: from the repository directory with `GIT_DIR=.`, with the quarantine variables during `pre-receive`, and with push options in `GIT_PUSH_OPTION_*`. Under `receive.shallowUpdate`, a push from a shallow clone also sets `GIT_SHALLOW_FILE` to a file listing the client's boundaries, so hooks can walk the pushed history. A hook may exit without reading its stdin (for example a CI notifier); the push still succeeds and `grit serve` keeps running.

Pushed objects are checked as strictly as `git receive-pack` checks them: problems a local `git fsck` only warns about, such as zero-padded file modes or `.git` tree entries, refuse the push unless `receive.fsck.<msg-id>` says otherwise. Problems that are only informational, such as `badFilemode`, are accepted.

## Options

| Option | Description |
| --- | --- |
| `<directory>` | The repository to push to. |
| `--stateless-rpc` | Answer a single request and exit, without advertising refs first. Used for smart HTTP. |
| `--advertise-refs` | Print the ref advertisement and exit. Used for the first request of smart HTTP. Also accepted as `--http-backend-info-refs`. |

## Examples

Push over SSH to a server that has `grit` but not `git` installed:

```console
$ git push --receive-pack='grit receive-pack' origin main
```

Set it for a remote you already have:

```console
$ git config remote.origin.receivepack 'grit receive-pack'
```

## JSON output

None. `--json` has no effect, since stdout carries the Git protocol.


## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[grit upload-pack](https://grit-scm.com/docs/upload-pack/index.md), [grit push](https://grit-scm.com/docs/push/index.md)

# https://grit-scm.com/docs/manager/index.md

# grit manager

> A credential helper that stores passwords and tokens in the Windows Credential Manager.

## Synopsis

```text
grit manager (get | store | erase)
```

## Description

A Git credential helper backed by the Windows Credential Manager. You don't run it yourself: Git and `grit` run it when they need a password or token. It speaks Git's [credential helper protocol](https://git-scm.com/docs/gitcredentials), reading the request on stdin and, for `get`, writing the credentials it found on stdout.

[`grit auth`](https://grit-scm.com/docs/auth/index.md) sets `credential.helper` to `grit manager` on Windows when no other helper is configured. It writes the absolute path of `grit.exe` with forward slashes, then `manager`, and escapes spaces and other shell characters with a backslash:

```text
[credential]
	helper = C:/Users/jane/bin/grit.exe manager
```

`git` runs a `credential.helper` value as a command only when it starts with an absolute path (or `!`). A bare `grit manager` would make `git` look for a `git-credential-grit` program, so to set it up yourself, use the full path:

```text
> grit config --global credential.helper "C:/Users/jane/bin/grit.exe manager"
```

If the path contains a space, escape it with a backslash (`C:/Program\ Files/grit/grit.exe manager`) rather than quoting it: a value that starts with a quote is not an absolute path to `git`.

It works only on Windows. On other systems it exits with an error.

## Options

| Option | Description |
| --- | --- |
| `get` | Look up stored credentials for the request. |
| `store` | Save the credentials in the request. |
| `erase` | Remove the credentials matching the request. |

## Examples

```text
> echo "protocol=https`nhost=github.com`n" | grit manager get
protocol=https
host=github.com
username=x-access-token
password=gho_...
```

## JSON output

None. `grit manager` always speaks the credential helper protocol.


## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

[grit auth](https://grit-scm.com/docs/auth/index.md), [grit config](https://grit-scm.com/docs/config/index.md)

# https://grit-scm.com/docs/resolve/index.md

# grit resolve

> Resolve revision specs to object ids and types.

## Synopsis

```text
grit resolve [--short] [--abbrev-ref | --symbolic-full-name] [--verify <SPEC> [-q]] <SPEC>...
```

## Description

Resolves one or more revision specs to an object id, plus the object type and uncompressed size. Type and size follow `git cat-file` semantics, including `refs/replace` when replace refs are enabled (honor `GIT_NO_REPLACE_OBJECTS` to read the stored object instead). Supported forms match the library rev-parse surface: branches and tags, `HEAD~n`, peel suffixes such as `^{tree}`, path suffixes such as `main:path/file`, reflog selectors like `main@{1}` or `HEAD@{yesterday}` (date text uses the same relaxed grammar as `grit log --since`, for example `yesterday`, `last week`, `noon yesterday`, `Oct 27`, `10/27/2026`), abbreviated object ids, and **change ids** (reverse-hex tokens in `k`–`z`, 4–32 characters — stored header or derived id). See [Change ids — Revisions](https://grit-scm.com/docs/library/change-ids.md/index.md#revisions). When a date selector is older than every reflog entry, grit resolves to the oldest entry and emits a warning (same behavior as Git).

Each spec prints on its own line as `OID TYPE` (full hex by default). With `--short`, oids are abbreviated using the same uniqueness rules as elsewhere in grit.

The `:/<text>` message search resolves to the **youngest** matching commit by committer date among all commits reachable from any ref (including `HEAD`), not merely the first match walking back from one branch tip.

With `--abbrev-ref` or `--symbolic-full-name`, output switches to ref names (one line per spec): the shortest unambiguous short name, or the full symbolic ref name, matching `git rev-parse` for the same flags. Specs that are not refs (commit oids, peeled objects, unknown names) produce no line for that spec; exit status stays `0` unless a spec fails for another reason (for example `@{u}` with no upstream).

With `--verify <SPEC>`, exactly one spec is resolved strictly (like `git rev-parse --verify`): revision ranges (`A..B`, `A...B`), revision-set excludes (`^ref`), and other multi-revision forms are rejected with a typed error. Full hex ids must exist in the object database, and peel suffixes such as `^{commit}` are honored. Clap rejects extra positional specs when `--verify` is used (usage exit `2`). Success prints one object id line (abbreviated when `--short` is set). Combine with `-q` / `--quiet` to suppress all stdout and stderr and answer with exit status only (`0` = exists, `1` = not). `--json --quiet` prints nothing; the exit code alone answers.

## Options

| Option | Description |
| --- | --- |
| `<SPEC>…` | One or more revision specs to resolve (required). |
| `--short` | Print abbreviated object ids instead of full hex. |
| `--abbrev-ref` | Print the shortest unambiguous ref name for each spec (conflicts with default oid output). |
| `--symbolic-full-name` | Print the full symbolic ref name for each spec. |
| `--verify <SPEC>` | Resolve one spec strictly (`git rev-parse --verify`); conflicts with ref-name modes and extra positionals. |
| `-q`, `--quiet` | With `--verify`, suppress stdout and stderr; exit `0` or `1` only. |

## Examples

Resolve `HEAD` and its tree:

```console
$ grit resolve HEAD HEAD^{tree}
92501f188ae0815af09a0cef6e121eddda4113cf commit
a1b2c3d4e5f6789012345678901234567890abcd tree
```

Short ids:

```console
$ grit resolve --short main
92501f1 commit
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/resolve/schemas/resolve/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `warnings` | array | Non-fatal warnings collected while resolving. |
| `results` | array | One entry per input spec. |
| `results[].spec` | string | Input spec. |
| `results[].oid` | string | Resolved object id (abbreviated when `--short` is set). |
| `results[].kind` | string | `blob`, `tree`, `commit`, or `tag`. |
| `results[].size` | number | Uncompressed object size in bytes. |
| `results[].ref_name` | string | In oid mode: short ref name when the spec named a ref (for example `main` for `HEAD`). In ref-name modes: the printed ref line (abbrev or full, matching the active flag). |
| `results[].full_ref` | string | Full symbolic ref when the spec named a ref (for example `refs/heads/main`). |
| `results[].ref_display` | string | Same as `ref_name` in ref-name modes (stable alias for scripts). |
| `results[].oid` / `kind` / `size` | | Required in default oid mode; omitted in ref-name modes. |

Example:

```json
{
  "results": [
    {
      "spec": "HEAD",
      "oid": "92501f188ae0815af09a0cef6e121eddda4113cf",
      "kind": "commit",
      "size": 234,
      "ref_name": "main",
      "full_ref": "refs/heads/main"
    }
  ]
}
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/resolve/schemas/resolve/v1.json/index.md)

Pass `--markdown` for a table of resolved specs, oids, kinds, and sizes.



```text
## Resolve

| Spec | OID | Kind | Size | Ref |
| --- | --- | --- | ---: | --- |
| `HEAD` | `83352a61f6715ec3f0a297c6d6150725154fb833` | commit | 244 | HEAD |
| `HEAD^{tree}` | `cc5dd251b2645c614c83ffc5402450dfe72cedfd` | tree | 77 | HEAD |
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Every spec resolved (default mode), or `--verify` / `--verify --quiet` resolved the spec. |
| `1` | At least one spec failed, or `--verify` / `--verify --quiet` could not resolve the spec. |
| `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)), or `--verify` with zero or multiple specs. |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md).


## See also

- [`grit cat`](https://grit-scm.com/docs/resolve/cat.md/index.md) — show object contents for a spec
- [`grit show`](https://grit-scm.com/docs/resolve/show.md/index.md) — commit-oriented summary with diffstat

# https://grit-scm.com/docs/cat/index.md

# grit cat

> Show blob, tree, commit, or tag contents for a revision spec.

## Synopsis

```text
grit cat <SPEC>
```

## Description

Shows the contents of the object named by a revision spec:

- **Blob** — raw bytes written to stdout (no extra framing). Large blobs stream from the object database with bounded memory.
- **Tree** — one line per entry like `git cat-file -p` (six-digit directory modes such as `040000`, then a type word from the mode bits, oid, tab, path — same rule as Git, without reading each entry's object).
- **Commit** or **tag** — the canonical object payload (same bytes as `git cat-file -p`).

Object bytes and metadata honor `refs/replace` the same way as Git (unless `GIT_NO_REPLACE_OBJECTS` is set). Supported specs are the same as [`grit resolve`](https://grit-scm.com/docs/cat/resolve.md/index.md): peeled tips, `rev:path`, short oids, and reflog selectors.

## Options

| Option | Description |
| --- | --- |
| `<SPEC>` | Object or revision spec to display (required). |

## Examples

Show a tracked file at `HEAD`:

```console
$ grit cat HEAD:README.md
# hello
```

Show a commit payload:

```console
$ grit cat HEAD^{commit}
tree a1b2c3d4e5f6789012345678901234567890abcd
parent 919c45f33de5e5c0bd05f8ffb089f697f4644976
author Ada Lovelace <ada@example.com> 1700000000 +0000
committer Ada Lovelace <ada@example.com> 1700000000 +0000

initial
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/cat/schemas/cat/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `warnings` | array | Non-fatal warnings while resolving or reading. |
| `spec` | string | Input spec. |
| `oid` | string | Resolved object id (full hex). |
| `kind` | string | `blob`, `tree`, `commit`, or `tag`. |
| `size` | number | Uncompressed object size in bytes. |
| `content` | object | Tagged payload; shape depends on `kind`. |
| `content.kind` | string | Discriminator: `blob`, `tree`, `commit`, or `tag`. |
| `content.encoding` | string | For blobs: `utf-8` or `base64`. |
| `content.text` | string | UTF-8 blob or commit/tag body when applicable. |
| `content.data_base64` | string | Blob bytes when not UTF-8 (omitted when the blob is ≥ 1 MiB). |
| `content.omitted_inline` | boolean | When `true`, the blob is too large to embed; human mode streams bytes to stdout. |
| `content.entries` | array | Tree lines with `mode`, `type`, `oid`, and `path`. |

Blobs of at least 1 MiB omit both `text` and `data_base64` and set
`omitted_inline` to `true`. Use human output redirected to a file to retrieve
their bytes. Commit and tag payloads remain inline regardless of size.

Example (blob):

```json
{
  "spec": "HEAD:README.md",
  "oid": "6ff87c695474aa159952762750a82000",
  "kind": "blob",
  "size": 8,
  "content": {
    "kind": "blob",
    "encoding": "utf-8",
    "text": "# hello\n"
  }
}
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/cat/schemas/cat/v1.json/index.md)

Pass `--markdown` for a short summary and a fenced block (or table for trees) of the object contents. Binary blobs are summarized in Markdown; use `--json` for base64 payloads smaller than 1 MiB. Larger blobs include metadata and an omission notice.



```text
## Cat

- **spec:** `HEAD:tracked.txt`
- **oid:** `b641243fee370fbfe093daae08234ecc4b993d52`
- **kind:** blob
- **size:** 11

Blob body follows in a `text` code fence when stdout is a file.
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). |
| `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values.


## See also

- [`grit resolve`](https://grit-scm.com/docs/cat/resolve.md/index.md) — resolve specs to ids and types without printing contents
- [`grit show`](https://grit-scm.com/docs/cat/show.md/index.md) — human-oriented commit and tag summaries

# https://grit-scm.com/docs/ignore/index.md

# grit ignore

> Query whether paths match exclude (gitignore) rules.

## Synopsis

```text
grit ignore check <PATH>...
grit ignore check --all <PATH>...
```

## Description

The `check` subcommand reports whether paths are ignored by `.gitignore`, `.git/info/exclude`, and `core.excludesfile`, using the same precedence as Git. Tracked index entries are never treated as ignored. When `core.ignorecase` is `true` (`grit init` sets it on case-insensitive filesystems, such as the Windows and macOS defaults), patterns match without regard to ASCII case, as in Git: `Build/` ignores `build/x.o` and `*.LOG` ignores `debug.log`. [`grit status`](https://grit-scm.com/docs/ignore/status.md/index.md), [`grit add`](https://grit-scm.com/docs/ignore/add.md/index.md), [`grit commit`](https://grit-scm.com/docs/ignore/commit.md/index.md) and [`grit clean`](https://grit-scm.com/docs/ignore/clean.md/index.md) use the same rules.

By default only **ignored** paths are printed. Pass `--all` to also list paths that are not ignored.

Paths are resolved from the current directory and normalized within the worktree. They do not need to exist; a trailing `/` marks a directory query. Batch queries reuse the resolved worktree root when normalizing paths.

The command exits with status **0** when at least one path is ignored, and **1** when none are. Scripts can branch on this exit code.

Human output uses a verbose-style line per ignored path:

```text
path  ← .gitignore:3 *.log
```

## Options

| Option | Description |
| --- | --- |
| `--all` | Also print paths that are not ignored. |
| `<PATH>` | One or more paths (from the current directory or repository-relative). |

## Examples

Query a single ignored file:

```console
$ grit ignore check build/output.log
build/output.log  ← .gitignore:1 *.log
```

List ignored and non-ignored paths:

```console
$ grit ignore check --all src/main.rs tmp/cache/
src/main.rs
tmp/cache/  ← .gitignore:2 tmp/
```

Exit status when nothing matches:

```console
$ grit ignore check tracked.txt; echo $?
1
```

## JSON output

Schema: [v1](https://grit-scm.com/docs/ignore/schemas/ignore.check/v1.json/index.md)

Pass `--json` for stable, scripting-friendly output:

| Field | Type | Meaning |
| ----- | ---- | ------- |
| `any_ignored` | boolean | `true` when at least one queried path is ignored. |
| `entries` | array | Filtered results (ignored only unless `--all`). |
| `entries[].path` | string | Repository-relative path. |
| `entries[].ignored` | boolean | Whether the path is ignored. |
| `entries[].matched` | object or omitted | Verbose match metadata when present. |
| `entries[].matched.source` | object | Typed source (`per_directory`, `info_exclude`, or `core_excludes_file`). |
| `entries[].matched.line_number` | number | 1-based line in the source file. |
| `entries[].matched.pattern_text` | string | Pattern text as written in the file. |
| `entries[].matched.negative` | boolean | Whether the rule is negated (`!pattern`). |

Example:

```json
{
  "any_ignored": true,
  "entries": [
    {
      "path": "build/output.log",
      "ignored": true,
      "matched": {
        "source": {
          "kind": "per_directory",
          "path": ".gitignore"
        },
        "line_number": 1,
        "pattern_text": "*.log",
        "negative": false
      }
    }
  ]
}
```

## Markdown output

Schema: [v1](https://grit-scm.com/docs/ignore/schemas/ignore.check/v1.json/index.md)

Pass `--markdown` for agent-friendly output with the same fields summarized in prose and lists.




```text
## Ignore check

- **any_ignored:** true

- `noise.log` ← `.gitignore:1` `*.log`
```

## Exit status

| Code | Meaning |
| ---: | --- |
| `0` | At least one path is ignored (`ignore check`). |
| `1` | No matching ignored paths. |
| `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). |

See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md).


## See also

- [`grit clean`](https://grit-scm.com/docs/ignore/clean.md/index.md) — remove untracked files (optionally including ignored paths with `--ignored`).
- [`grit status`](https://grit-scm.com/docs/ignore/status.md/index.md) — working tree summary.

# https://grit-scm.com/docs/performance-overview/index.md

# Performance overview (daily matrix)

> Factory daily census — grit vs git time and peak memory across functional areas.

The factory runs a **daily census** of common `grit` workflows against the **system** `git` binary on fixed repository shapes. Results land in committed JSON (`grit-daily-bench/1`) and on the [cooking bench dashboard](https://maint.grit-scm.com/cooking/bench). This page renders the latest committed baseline as a per-area matrix aligned with [`grit-utils/MATRIX.md`](https://github.com/gitbutlerapp/grit/blob/main/grit-utils/MATRIX.md).

## Methodology

### Repository shapes

Scenarios use prepared fixtures under **`GRIT_BENCH_CACHE`** (see [Benchmarks](https://grit-scm.com/docs/performance-overview/benchmarks.md/index.md)). Shapes include:

| Shape | Role |
| --- | --- |
| `small` | Tiny synthetic repo for cheap init/commit checks |
| `synth-10k` / `synth-100k` | Large synthetic trees (10k / 100k files) with controlled dirty/clean states |
| `git-git` | Bare and working copies of upstream **git.git** (tag pinned in the fixture registry) |
| `many-refs` / `many-refs-loose` | Many branches/tags for ref-list and pack-refs workloads |
| `big-blobs` | Few paths with very large blobs (sparse worktree for daily capture on low-memory VMs) |
| `deep-tree` | Deep directory nesting for status/diff on deep paths |

Optional **`GRIT_BENCH_DAILY_LOW_MEMORY=1`** selects smoke-sized special fixtures while keeping the same scenario ids; the committed **`latest.json`** baseline on this page was captured with **full-size** fixtures (see [Benchmarking harness](https://grit-scm.com/docs/performance-overview/benchmarking.md/index.md) for smoke vs full runs).

### Run policy

`grit-bench daily` uses the **direct-spawn runner**: each timed sample spawns `git` or `grit` as a child process, measures **wall time** for the process lifetime, and records **peak resident set size (RSS)** for that child and its descendants. On Linux, the monitor polls **`/proc`** for the process tree during the run and also reads **`getrusage(RUSAGE_CHILDREN)`** when the child exits; the reported peak is the maximum of those observations (bytes). Each tool reports the **median** wall time and **median** peak RSS over successful timed runs (default policy: warmups plus at least five timed samples and a minimum aggregated timed window per scenario).

Headline scenarios (`headline: true` in the report) are the **17 cooking-page rows**; they are highlighted in the tables below.

### Invocation

```bash
cargo build --release -p grit-cli -p grit-utils
./target/release/grit-bench fixtures prepare --only synth-10k-smoke,many-refs-smoke,git-git-wt,git-git
./target/release/grit-bench daily --output grit-utils/baselines/daily/latest.json
./target/release/grit-bench daily validate grit-utils/baselines/daily/latest.json
```

Regenerate the committed census with a full **`grit-bench daily`** run (all matrix ids, release binaries, fixtures prepared) and validate before updating **`grit-utils/baselines/daily/latest.json`**.

Rows marked **Pending** or **Not in committed daily baseline** are exemptions: either blocked on roadmap CLI (see **Gaps** in MATRIX.md) or not yet present in the committed census file.

## Daily matrix (committed baseline)

| | |
| --- | --- |
| Git | git version 2.43.0 |
| Grit | grit 0.5.14 |
| CPU | Intel(R) Xeon(R) Processor |
| OS | linux (Linux 6.12.94+) |
| Recorded | 2026-10-21 13:08:19.302252211 |

## Summary by area

| Area | Scenarios | Median Grit / Git (time) | Worst Grit / Git (time) | Median memory ratio |
| --- | ---: | ---: | ---: | ---: |
| odb | 0 | — | — | — |
| packs | 0 | — | — | — |
| refs | 1 | — | — | — |
| index | 2 | 1.00× | 1.00× | **2.08×** |
| worktree | 52 | 1.00× | 1.40× | **2.26×** |
| diff | 5 | 1.00× | 1.00× | **2.41×** |
| revwalk | 24 | 1.00× | **16.32×** | **2.44×** |
| blame | 2 | 1.83× | **2.66×** | **2.18×** |
| branching | 27 | **4.66×** | **4.99×** | **2.75×** |
| remotes | 30 | **6.79×** | **35.61×** | **1.83×** |
| maintenance | 5 | — | — | — |
| config | 3 | — | — | — |
| ignore | 1 | — | — | — |
| hooks | 1 | — | — | — |
| notes | 3 | — | — | — |
| bundles | 3 | — | — | — |
| worktrees | 3 | — | — | — |

### odb

| Scenario | Git median (ms) | Grit median (ms) | Time | Git peak RSS | Grit peak RSS | Memory | Notes |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |

### packs

| Scenario | Git median (ms) | Grit median (ms) | Time | Git peak RSS | Grit peak RSS | Memory | Notes |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |

### refs

| Scenario | Git median (ms) | Grit median (ms) | Time | Git peak RSS | Grit peak RSS | Memory | Notes |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |
| `gc/pack-refs@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |

### index

| Scenario | Git median (ms) | Grit median (ms) | Time | Git peak RSS | Grit peak RSS | Memory | Notes |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |
| `diff/staged@deep-tree` | 50.7 | 50.7 | 1.00× | 7.1 MiB | 13.3 MiB | **1.86×** | |
| `diff/staged@synth-100k` | 50.6 | 50.7 | 1.00× | 6.1 MiB | 14.0 MiB | **2.31×** | |

### worktree

| Scenario | Git median (ms) | Grit median (ms) | Time | Git peak RSS | Grit peak RSS | Memory | Notes |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |
| `add/all@synth-100k` | 50.7 | 50.7 | 1.00× | 6.0 MiB | 15.2 MiB | **2.53×** | |
| `add/update@synth-100k` | — | — | — | — | — | — | Not in committed daily baseline |
| `add/all-ignorecase@synth-100k` | — | — | — | — | — | — | Not in committed daily baseline |
| `add/update-ignorecase@synth-100k` | — | — | — | — | — | — | Not in committed daily baseline |
| `add/dry-run@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `add/patch-file@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `add/hunks@large-file` | — | — | — | — | — | — | Not in committed daily baseline |
| `add/patch-file@large-file` | — | — | — | — | — | — | Not in committed daily baseline |
| `add/lines@large-file` | — | — | — | — | — | — | Not in committed daily baseline |
| `add/modified@big-blobs` | 50.7 | 50.7 | 1.00× | 5.1 MiB | 11.5 MiB | **2.24×** | |
| **add/modified@synth-10k** | 50.7 | 50.7 | 1.00× | 5.1 MiB | 12.3 MiB | **2.40×** | |
| `clean/only-ignored@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `clean/untracked@synth-10k` | 50.7 | 50.7 | 1.00× | 5.2 MiB | 10.8 MiB | **2.06×** | |
| `commit/small@small` | 50.7 | 50.7 | 1.00× | 5.3 MiB | 12.1 MiB | **2.29×** | |
| `commit/small@synth-100k` | 50.7 | 50.7 | 1.00× | 6.1 MiB | 16.2 MiB | **2.64×** | |
| **commit/small@synth-10k** | 50.6 | 50.6 | 1.00× | 5.3 MiB | 12.6 MiB | **2.40×** | |
| `commit/staged@synth-100k` | — | — | — | — | — | — | Not in committed daily baseline |
| `commit/dry-run@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `commit/paths@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `init/branch@small` | — | — | — | — | — | — | Not in committed daily baseline |
| `init/empty@small` | 50.7 | 50.7 | 1.00× | 5.1 MiB | 9.1 MiB | **1.77×** | |
| `mv/file@synth-10k` | 50.8 | 50.7 | 1.00× | 5.2 MiB | 10.5 MiB | **2.00×** | |
| `reset/hard@synth-10k` | 50.7 | 50.7 | 1.00× | 5.3 MiB | 12.7 MiB | **2.41×** | |
| `reset/hard-delete-heavy@wide-48k` | — | — | — | — | — | — | Not in committed daily baseline |
| `reset/keep@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `reset/mixed@synth-10k` | 50.7 | 50.7 | 1.00× | 5.2 MiB | 12.7 MiB | **2.43×** | |
| `reset/sparse@sparse-120k` | — | — | — | — | — | — | Not in committed daily baseline |
| `reset/sparse@sparse-240k` | — | — | — | — | — | — | Not in committed daily baseline |
| `reset/sparse@sparse-unique-120k` | — | — | — | — | — | — | Not in committed daily baseline |
| `reset/undo-commit@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `restore/hunks@large-file` | — | — | — | — | — | — | Not in committed daily baseline |
| `restore/paths@synth-10k` | 50.7 | 50.6 | 1.00× | 5.2 MiB | 11.6 MiB | **2.24×** | |
| `rm/dir@synth-10k` | 50.7 | 50.7 | 1.00× | 5.3 MiB | 11.9 MiB | **2.26×** | |
| `rm/dry-run@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `stash/pop-sparse@wide-120k` | — | — | — | — | — | — | Not in committed daily baseline |
| `stash/pop-index@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `stash/push-paths@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| **stash/push-pop@synth-10k** | 251 | 352 | 1.40× | 16.6 MiB | 25.3 MiB | **1.52×** | |
| `status/clean@deep-tree` | 101 | 101 | 1.00× | 8.6 MiB | 17.3 MiB | **2.00×** | |
| `status/clean@small` | 50.7 | 50.7 | 1.00× | 5.2 MiB | 11.6 MiB | **2.21×** | |
| `status/clean@synth-100k` | 50.7 | 50.7 | 1.00× | 6.0 MiB | 14.9 MiB | **2.46×** | |
| **status/clean@synth-10k** | 50.7 | 50.7 | 1.00× | 5.2 MiB | 12.1 MiB | **2.31×** | |
| `status/dirty@deep-tree` | 101 | 101 | 1.00× | 8.7 MiB | 17.3 MiB | **1.98×** | |
| `status/dirty@small` | 50.7 | 50.7 | 1.00× | 5.2 MiB | 11.7 MiB | **2.23×** | |
| `status/dirty@synth-100k` | 50.7 | 50.7 | 1.00× | 6.1 MiB | 14.9 MiB | **2.43×** | |
| **status/dirty@synth-10k** | 50.7 | 50.7 | 1.00× | 5.3 MiB | 12.3 MiB | **2.33×** | |
| `status/paths@synth-100k` | — | — | — | — | — | — | Not in committed daily baseline |
| `status/renamed@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| **switch/branch@synth-10k** | 50.7 | 50.6 | 1.00× | 7.9 MiB | 15.3 MiB | **1.95×** | |
| `switch/sparse@sparse-120k` | — | — | — | — | — | — | Not in committed daily baseline |
| `switch/sparse@sparse-240k` | — | — | — | — | — | — | Not in committed daily baseline |
| `switch/sparse@sparse-unique-120k` | — | — | — | — | — | — | Not in committed daily baseline |

### diff

| Scenario | Git median (ms) | Grit median (ms) | Time | Git peak RSS | Grit peak RSS | Memory | Notes |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |
| `diff/worktree@big-blobs` | 50.7 | 50.7 | 1.00× | 5.2 MiB | 11.8 MiB | **2.26×** | |
| `diff/worktree@deep-tree` | 50.8 | 50.7 | 1.00× | 6.5 MiB | 14.8 MiB | **2.27×** | |
| `diff/worktree@synth-100k` | 50.6 | 50.6 | 1.00× | 6.0 MiB | 15.5 MiB | **2.59×** | |
| **diff/worktree@synth-10k** | 50.7 | 50.7 | 1.00× | 7.3 MiB | 18.6 MiB | **2.56×** | |
| `diff/stat@synth-100k` | — | — | — | — | — | — | Not in committed daily baseline |

### revwalk

| Scenario | Git median (ms) | Grit median (ms) | Time | Git peak RSS | Grit peak RSS | Memory | Notes |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |
| `cat/blob@git-git` | 50.7 | 50.7 | 1.00× | 5.2 MiB | 29.9 MiB | **5.70×** | |
| `log/all@git-git` | 50.8 | 829 | **16.32×** | 17.9 MiB | 121.4 MiB | **6.80×** | |
| **log/oneline-100@git-git** | 50.7 | 50.7 | 1.00× | 12.2 MiB | 31.2 MiB | **2.55×** | |
| `log/json-100@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `log/json-filter@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `log/json-n10-loose-tags@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `log/json-n10-packed-tags@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `log/stat-n50@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `log/oneline-100@synth-100k` | 50.7 | 50.7 | 1.00× | 5.4 MiB | 12.5 MiB | **2.33×** | |
| `log/limit-path@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `log/path@git-git` | 352 | 2,510 | **7.14×** | 247.2 MiB | 309.1 MiB | 1.25× | |
| `merge-base/branches@git-git` | 50.8 | 653 | **12.85×** | 16.8 MiB | 59.0 MiB | **3.51×** | |
| `patch-id/commit@git-git` | 50.6 | 50.6 | 1.00× | 6.6 MiB | 31.1 MiB | **4.73×** | |
| `reflog/list@synth-10k` | 50.7 | 50.7 | 1.00× | 5.2 MiB | 9.5 MiB | **1.82×** | |
| `resolve/head-n@git-git` | 50.7 | 50.7 | 1.00× | 5.2 MiB | 31.0 MiB | **5.94×** | |
| `resolve/change-id@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `revs/count@git-git` | 552 | 753 | 1.36× | 59.2 MiB | 119.3 MiB | **2.02×** | |
| `revs/count-path@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `revs/count-range-commit-graph@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `shortlog/ahead@git-git` | 50.7 | 50.7 | 1.00× | 16.9 MiB | 9.9 MiB | 0.59× | |
| `shortlog/behind@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `show/head@big-blobs` | 50.7 | 50.6 | 1.00× | 10.6 MiB | 16.2 MiB | **1.52×** | |
| **show/head@git-git** | 50.6 | 50.6 | 1.00× | 6.6 MiB | 31.0 MiB | **4.69×** | |
| `show/head@synth-10k` | 50.7 | 50.7 | 1.00× | 6.5 MiB | 14.3 MiB | **2.20×** | |

### blame

| Scenario | Git median (ms) | Grit median (ms) | Time | Git peak RSS | Grit peak RSS | Memory | Notes |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |
| `blame/file@deep-tree` | 50.7 | 50.7 | 1.00× | 7.5 MiB | 13.3 MiB | **1.77×** | |
| **blame/file@git-git** | 302 | 804 | **2.66×** | 231.1 MiB | 599.1 MiB | **2.59×** | |

### branching

| Scenario | Git median (ms) | Grit median (ms) | Time | Git peak RSS | Grit peak RSS | Memory | Notes |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |
| `branch/create@many-refs` | — | — | — | — | — | — | Not in committed daily baseline |
| `branch/delete@many-refs` | — | — | — | — | — | — | Not in committed daily baseline |
| `branch/rename@many-refs` | — | — | — | — | — | — | Not in committed daily baseline |
| **branch/list@many-refs** | 50.7 | 50.6 | 1.00× | 5.1 MiB | 9.7 MiB | **1.90×** | |
| `branch/list-json@many-refs` | — | — | — | — | — | — | Not in committed daily baseline |
| `branch/list@many-refs-loose` | — | — | — | — | — | — | Not in committed daily baseline |
| `branch/merged@many-refs` | — | — | — | — | — | — | Not in committed daily baseline |
| `branch/contains@git-git-10k-refs` | — | — | — | — | — | — | Not in committed daily baseline |
| `branch/contains-json@git-git-10k-refs` | — | — | — | — | — | — | Not in committed daily baseline |
| `branch/merged-ref@many-refs` | — | — | — | — | — | — | Not in committed daily baseline |
| `history/reword@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `merge/content-both-sides@wide-20k` | — | — | — | — | — | — | Not in committed daily baseline |
| `merge/clean@synth-100k` | — | — | — | — | — | — | Not in committed daily baseline |
| **merge/clean@synth-10k** | 151 | 753 | **4.99×** | 8.7 MiB | 24.1 MiB | **2.75×** | |
| `pick/one@synth-100k` | — | — | — | — | — | — | Not in committed daily baseline |
| **pick/one@synth-10k** | 151 | 704 | **4.66×** | 8.8 MiB | 24.5 MiB | **2.80×** | |
| `rebase/onto@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `rebase/onto@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `revert/one@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `stash/list@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `switch/branch@synth-100k` | — | — | — | — | — | — | Not in committed daily baseline |
| `switch/delete-heavy@wide-48k` | — | — | — | — | — | — | Not in committed daily baseline |
| `switch/large-blob@big-asset` | — | — | — | — | — | — | Not in committed daily baseline |
| `tag/contains@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `tag/create@many-refs` | — | — | — | — | — | — | Not in committed daily baseline |
| `tag/list-sort-version@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `tag/list@many-refs` | — | — | — | — | — | — | Not in committed daily baseline |

### remotes

| Scenario | Git median (ms) | Grit median (ms) | Time | Git peak RSS | Grit peak RSS | Memory | Notes |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |
| `clone/http@synth-10k` | 1,609 | 2,011 | 1.25× | 34.6 MiB | 51.2 MiB | 1.48× | |
| **clone/local@synth-10k** | 1,005 | 6,824 | **6.79×** | 69.3 MiB | 114.4 MiB | **1.65×** | |
| `clone/full@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `clone/bare@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `clone/checkout@synth-100k` | — | — | — | — | — | — | Not in committed daily baseline |
| `clone/shallow@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `clone/blobless@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `reset/blobless@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `clone/shallow-depth1@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `clone/shallow-depth1-http@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `fetch/incremental-http@git-git` | 76,754 | 78,655 | 1.02× | 134.4 MiB | 82.2 MiB | 0.61× | |
| `fetch/deepen@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `fetch/dry-run@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| **fetch/incremental@git-git** | 151 | 1,807 | **11.96×** | 52.9 MiB | 125.1 MiB | **2.37×** | |
| `fetch/one-branch@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `fetch/noop@git-git` | 50.7 | 1,807 | **35.61×** | 32.8 MiB | 103.7 MiB | **3.16×** | |
| `fetch/noop-local@many-refs` | — | — | — | — | — | — | Not in committed daily baseline |
| `fetch/noop-local-no-tags@many-refs` | — | — | — | — | — | — | Not in committed daily baseline |
| `ls-remote/all@many-refs` | 50.7 | 50.7 | 1.00× | 8.4 MiB | 15.3 MiB | **1.83×** | |
| `remote/show@many-refs` | — | — | — | — | — | — | Not in committed daily baseline |
| `remote/rename@many-refs` | — | — | — | — | — | — | Not in committed daily baseline |
| **pull/fast-forward@git-git** | 151 | 1,907 | **12.63×** | 57.2 MiB | 145.3 MiB | **2.54×** | |
| `pull/rebase@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `pull/check@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `push/incremental-http@git-git` | 1,708 | 12,748 | **7.46×** | 305.6 MiB | 2022.4 MiB | **6.62×** | |
| `push/refspec@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| **push/incremental@git-git** | 1,607 | 50.7 | 0.03× | 184.3 MiB | 40.8 MiB | 0.22× | |
| `push/force-with-lease@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `remote/list@small` | — | — | — | — | — | — | Not in committed daily baseline |
| `remote/remove@many-refs` | — | — | — | — | — | — | Not in committed daily baseline |

### maintenance

| Scenario | Git median (ms) | Grit median (ms) | Time | Git peak RSS | Grit peak RSS | Memory | Notes |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |
| `fsck/full@big-blobs` | — | — | — | — | — | — | Not in committed daily baseline |
| `fsck/full@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `gc/default@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `repack/commit-graph@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `repack/full@git-git` | — | — | — | — | — | — | Not in committed daily baseline |

### config

| Scenario | Git median (ms) | Grit median (ms) | Time | Git peak RSS | Grit peak RSS | Memory | Notes |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |
| `config/get@small` | — | — | — | — | — | — | Not in committed daily baseline |
| `config/get-origin@small` | — | — | — | — | — | — | Not in committed daily baseline |
| `config/set@small` | — | — | — | — | — | — | Not in committed daily baseline |

### ignore

| Scenario | Git median (ms) | Grit median (ms) | Time | Git peak RSS | Grit peak RSS | Memory | Notes |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |
| `ignore/check-1000@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |

### hooks

| Scenario | Git median (ms) | Grit median (ms) | Time | Git peak RSS | Grit peak RSS | Memory | Notes |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |
| `hooks/list@small` | — | — | — | — | — | — | Not in committed daily baseline |

### notes

| Scenario | Git median (ms) | Grit median (ms) | Time | Git peak RSS | Grit peak RSS | Memory | Notes |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |
| `notes/add@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `notes/list@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `notes/list-n100@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |

### bundles

| Scenario | Git median (ms) | Grit median (ms) | Time | Git peak RSS | Grit peak RSS | Memory | Notes |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |
| `bundle/create@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `bundle/create-all@git-git` | — | — | — | — | — | — | Not in committed daily baseline |
| `bundle/verify@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |

### worktrees

| Scenario | Git median (ms) | Grit median (ms) | Time | Git peak RSS | Grit peak RSS | Memory | Notes |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |
| `worktree/add@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `worktree/list@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |
| `worktree/remove@synth-10k` | — | — | — | — | — | — | Not in committed daily baseline |

# https://grit-scm.com/docs/benchmarking/index.md

# Harness (make bench-lib / bench-scenarios)

# Benchmark harness (`make bench-lib` / `make bench-scenarios`)

Grit compares library micro-benchmarks (Criterion) and command-level scenarios (`grit-bench` + hyperfine) against the system **`git`** binary on the same machine. Two Make targets run the full suites from a clean checkout after building release binaries.

## `make bench-lib`

Runs every Criterion bench under `grit-lib/benches/` (with the `test-support` feature where a bench needs fixtures or hooks), then writes a JSON summary:

| Output | Description |
| --- | --- |
| `target/criterion/` | Raw Criterion results (`estimates.json` per benchmark) |
| `target/bench/criterion-summary.json` | Aggregated summary produced by `grit-bench criterion-summary` |

```bash
make bench-lib
```

### Criterion summary JSON (`criterion-summary.json`)

| Field | Type | Meaning |
| --- | --- | --- |
| `schema_version` | `1` | Summary schema version |
| `timestamp` | RFC3339 string | Capture time (UTC) |
| `machine` | object | CPU, RAM, kernel, `rustc`, cargo profile (same shape as grit-bench v1) |
| `tools` | object | `git` is `n/a (criterion micro-benchmarks)`; `grit` identifies the library build |
| `scenarios[]` | array | One row per Criterion `new/estimates.json` |
| `scenarios[].driver` | `"criterion"` | Not a git vs grit hyperfine row |
| `scenarios[].grit` | timing block | Mean/median/stddev in **milliseconds** (converted from Criterion nanoseconds) |

Each scenario `id` is derived from the path under `target/criterion/` (for example `criterion-hash_sha1-4KiB`).

### Patch parsing and staging

`apply_blob` includes `parse_patch_small`, which parses a valid traditional unified diff and fails if parsing fails. It measures parsing independently of repository discovery, object writes, and index updates:

```bash
cargo bench --profile dist -p grit-lib --bench apply_blob -- parse_patch_small
```

For a command-level comparison with system Git, `add/patch-file@synth-10k` applies a worktree patch to the index with `grit add --patch-file` and `git apply --cached`:

```bash
cargo build --profile dist -p grit-cli -p grit-utils
./target/dist/grit-bench daily --only add/patch-file@synth-10k --output target/bench/patch-file.json
```

Use the same fixture, build profile, and system Git for before/after comparisons. Each timed mutation must start with the same index and worktree state; preparation runs outside the timed region.

## `make bench-scenarios`

Prepares registry fixtures, runs **every grit-bench scenario group** for the chosen synthetic tier, and writes both JSON and a markdown table:

| Output | Description |
| --- | --- |
| `target/bench/scenarios-<host>.json` | Merged grit-bench report (`schema_version: 1`) |
| `target/bench/scenarios-<host>.md` | Human-readable ratio table |

```bash
# Default tier M (full hyperfine samples)
make bench-scenarios TIER=M

# Small fixtures + one timed iteration per scenario (CI smoke)
make bench-scenarios TIER=S SMOKE=1
```

### Tier (`TIER=S|M|L`)

| Tier | Registry fixture | Typical use |
| --- | --- | --- |
| **S** | `synth-s` | CI smoke, fast local checks |
| **M** | `synth-m` | Default local run |
| **L** | `synth-l` | Large synthetic repo (long run) |

`SMOKE=1` sets `--smoke` on `grit-bench scenarios`: warmup `0`, exactly **one** hyperfine run per scenario, tiny network/parallel fixtures, and skips heavy groups (ODB backend, bitmaps, refs). CI uses `TIER=S SMOKE=1`; **timings are not gated**—the job fails only if a scenario errors.

### Scenario report JSON (`scenarios-<host>.json`)

Uses the same **grit-bench v1** schema as individual subcommands (`schema_version`, `machine`, `tools`, `fixtures`, `scenarios`). Each scenario includes `git` and `grit` timing blocks (milliseconds) and `ratio` (`grit_median_ms / git_median_ms`).

Groups included in the merged report:

| Group | Source |
| --- | --- |
| `worktree` | status / add / commit / diff on the tier fixture |
| `history` | log, show, rev-list, blame, cat-file batch |
| `rewrite-history` | `grit history` reword/drop/fixup/squash vs git history / git rebase |
| `network` | clone, fetch, push, ls-remote (file + smart HTTP) |
| `parallel` | threads=1 vs auto on the 100k-class fixture |
| `revwalk`, `fsck`, `maintenance` | porcelain vs git |
| `resolve-cat`, `ignore`, `local-clone`, `hot-paths` | CLI hot paths |
| `deep-leaf`, `dense-leaf` | smoke layout only when `SMOKE=1` |
| `odb-backend`, `bitmaps`, `refs` | full runs only (`SMOKE=0`) |

`grit-bench partial-clone [--files N] [--packs N]` runs on its own, outside the merged report: a `blob:none` `file://` clone of a source holding `--packs` packs (50 by default, one incremental repack per batch of files), the same clone with its checkout, and the `reset --hard` in a blobless clone, the last two lazily fetching every `HEAD` blob in one request, all against Git.

Equivalent CLI:

```bash
cargo build --release -p grit-cli -p grit-http-server -p grit-utils
./target/release/grit-bench scenarios --tier S --smoke --format json --output target/bench/scenarios-smoke.json
./target/release/grit-bench criterion-summary --criterion-dir target/criterion --format json --output target/bench/criterion-summary.json
```

See also [Benchmarks](https://grit-scm.com/docs/benchmarking/benchmarks.md/index.md) for committed baselines and acceptance ratios.

## `grit-bench daily` (factory census)

Use `--min-runs 10` for performance investigations that require at least ten
samples per tool. Daily runs honor this common option, raising the usual run cap
when the requested minimum is larger. `--smoke` still uses one sample, and the
scenario time budget can stop expensive scenarios early; inspect each row's `runs`.
Daily reports reject a plan whose two commands are placeholders instead of an
operation. Reword uses a scripted editor with `git history` on supporting Git
versions; deepen starts from one branch boundary with tags excluded and checks
that Git and grit produce identical new shallow boundaries.


Headline scenarios compare **`grit`** and system **`git`** with the direct-spawn runner (wall time + peak RSS per run). Reports use the [`grit-daily-bench/1`](https://grit-scm.com/docs/grit-utils/DAILY-SCHEMA.md/index.md) schema (distinct from hyperfine v1).

Published daily numbers (the [factory dashboard](https://maint.grit-scm.com/cooking/bench) and the [Performance overview](https://grit-scm.com/docs/benchmarking/performance-overview.md/index.md)) measure the **`dist`** profile, the fat-LTO build that releases ship. Build `grit-bench` in the same profile: it then times `target/dist/grit` by default and records `"cargo_profile": "dist"` in the report.

```bash
cargo build --profile dist -p grit-cli -p grit-utils
./target/dist/grit-bench fixtures prepare --only synth-10k-smoke,many-refs-smoke,git-git-wt,git-git
./target/dist/grit-bench daily --smoke --offline --output target/bench/daily-smoke.json
./target/dist/grit-bench daily validate target/bench/daily-smoke.json
```

The daily census switched from `release` to `dist` on 2026-10-28. That one-time switch moves the baseline of **every** scenario: short commands drop by roughly 10–15% in time and 20% in peak RSS (`show/head@git-git` went from 3.08 to 2.70 ms and from 16.1 to 13.1 MB on the same VM), because LTO packs the code a run touches into fewer pages. Read the step at that date as a build change, not a run of wins, and compare reports only within one profile (check `machine.cargo_profile`).

A `release` build stays fine for iterating on a change (it rebuilds about three times faster), as long as the before and after binaries use the same profile. Code-layout noise is larger in `release`: any change to `grit-lib` reshuffles its 16 codegen units, which can move a 2–3 ms command by ±50 µs and its peak RSS by ±1 MB with no change in the work done. Confirm small differences on `dist`.

| Flag | Meaning |
| --- | --- |
| `--smoke` | Smoke fixtures, **0** warmups, **1** timed run per tool |
| `--only id,...` | Run a subset of scenario ids |
| `--area <area>` | Filter by functional area (`worktree`, `branching`, `remotes`, …) |
| `--baseline-grit <path>` | Also time a second grit binary on headline rows |
| `--offline` | Do not clone `git.git` (fixtures must already be cached) |

All **17 headline** ids run in **`--smoke`** mode (including the four **remote** headlines on cached `git-git` bare and synth-10k bare remotes). Additional **remote matrix** rows (`fetch/noop`, `ls-remote/all`, HTTP clone/fetch/push) run on full daily reports and in `grit-utils` remote e2e tests. CI job **`bench-daily-smoke`** runs the smoke command above; timings are not gated.

## Blobless hard reset (#2054)

Measured on 2026-10-26 with the stock system Git 2.43.0, Rust 1.99.0, release-profile grit 0.5.21, four Intel Xeon vCPUs and 16 GiB RAM on Linux/ext4. The main baseline is `fa6a9fd559b2b5e0ac4779f1d2b4c115f70c24f0`; the comparison is the `factory/batch-reset-blobs` change. Both binaries were retained and measured in the same session, with no concurrent builds or tests.

Wall times below are **median milliseconds**, and RSS is the **maximum KiB** across samples. GNU `/usr/bin/time -v` measured peak client RSS; Python `time.monotonic()` bracketed the complete command. Clone preparation, object counting, byte/symlink verification, clean `git status --porcelain` and `git fsck --strict` ran outside the timed region. Every materialization used a fresh `--no-checkout` client. The 200-file case has three runs per tool; Cargo and HTTP blobless cases have one.

| Blobless materialization | Git: ms / KiB | Main: ms / KiB | Fixed: ms / KiB |
| --- | ---: | ---: | ---: |
| 200 files, file transport | 30.24 / 5,704 | 1,394.26 / 21,792 | 33.03 / 17,504 |
| 200 files, smart HTTP | 161.84 / 9,584 | 1,804.66 / 23,968 | 69.63 / 18,112 |
| Cargo, file transport | 678.57 / 45,136 | 72,193.59 / 41,644 | 757.40 / 45,344 |

| Case | Data fetches: Git / main / fixed | Total packs: Git / main / fixed | HTTP requests: Git / main / fixed |
| --- | ---: | ---: | ---: |
| 200 files | 1 / 200 / 1 | 2 / 201 / 2 | — |
| 200 files, HTTP | 1 / 200 / 1 | 2 / 201 / 2 | 2 / 400 / 2 |
| Cargo | 1 / 2,022 / 1 | 3 / 2,023 / 2 | — |

The local HTTP server was the same debug-build `grit-http-server` for all three clients, with `--log-headers` enabled. HTTP is a single sample and includes server warmup effects; request counts are the regression gate. File-transport fetch counts come from system-Git upload-pack traces. A second reset downloads nothing, as covered by library and CLI tests.

Cargo was cloned from `https://github.com/rust-lang/cargo.git` and its source branch/worktree reset to `b57863321f8d0a0f76fcf9ad636b6e39b024d0c0` before client creation. All three blobless clients started with **59,756 missing history blobs** and identical target contents; the current source tag set differs from the original issue reproduction. The verifier compares symlink targets without following directory symlinks.

Cargo blobless checkout improves about **95×**. Its peak RSS increases by about **3.6 MiB** relative to main and is close to system Git. The larger single fetch replaces thousands of tiny packs; this measured memory cost is retained in the baseline rather than hidden by the speedup. The 200-file and HTTP blobless cases use less peak memory than main.

Ordinary full-clone resets check the common path separately. Cargo values use four fresh clients per tool; each clean reset follows successful full materialization.

| Full-clone reset | Git: ms / KiB | Main: ms / KiB | Fixed: ms / KiB |
| --- | ---: | ---: | ---: |
| 200 files, materialize | 5.49 / 5,672 | 9.82 / 13,880 | 9.58 / 15,464 |
| 200 files, clean | 5.19 / 5,416 | 6.35 / 14,544 | 5.97 / 15,900 |
| Cargo, materialize | 149.66 / 46,100 | 180.57 / 56,740 | 178.71 / 56,860 |
| Cargo, clean | 14.03 / 15,300 | 17.92 / 20,384 | 17.35 / 19,976 |

Full Cargo materialization stays within the observed run-to-run range; clean Cargo resets improve slightly and use slightly less peak RSS. Tiny full-clone cases show about 1.3–1.6 MiB more peak RSS, so the results do not claim a universal memory reduction. The raw samples and environment are committed in `grit-utils/baselines/blobless-reset-before.json` and `grit-utils/baselines/blobless-reset-after.json`.

To reproduce the small input repository:

```bash
case_root=$(mktemp -d)
git init -q -b main "$case_root/source"
for i in $(seq 1 200); do
  { printf 'file %s\n' "$i"; for j in $(seq 1 100); do printf 'build payload\n'; done; } > "$case_root/source/file-$i.txt"
done
git -C "$case_root/source" add .
git -C "$case_root/source" -c user.name=CI -c user.email=ci@example.test commit -qm inputs
git -C "$case_root/source" config uploadpack.allowFilter true
grit clone --blobs none --no-checkout "file://$case_root/source" "$case_root/client"
/usr/bin/time -v grit -C "$case_root/client" reset --hard HEAD
git -C "$case_root/client" fsck --strict
```

Use a fresh destination for each Git/main/fixed sample, substituting `git clone --filter=blob:none --no-checkout` for Git. Omit the blob filter for full materialization; run reset again on the resulting clean worktree for the clean case. For Cargo, substitute the pinned source above. Keep the source upload-pack executable as the stock system Git.

The daily remotes matrix also measures materialization separately from clone time:

```bash
grit-bench daily --only reset/blobless@git-git --output target/bench/blobless-reset.json
grit-bench daily validate target/bench/blobless-reset.json
```

Its prepare hook creates fresh blobless clients outside each timed iteration. Correctness checks enforce clean worktrees, strict fsck and a bounded pack count.

`gc/default@synth-10k` works the same way: before each timed run, its prepare hook resets synth-10k to the fixture's base commit and adds 40 empty commits as loose objects. Each prepare puts a fresh nonce in those commit messages. Without it, a prepare that runs within a second of the previous one recreates byte-identical commits that the last `gc` already packed, git writes nothing loose, and the timed run measures a gc with nothing to do (about 13 ms instead of about 140 ms). The prepare fails when the newest seeded commit is not stored loose.

## Startup relocation comparison

Startup changes need separate `release` and shipping `dist` measurements. Keep
PIE, ASLR, LTO, codegen units and panic policy unchanged. A CLI-only RELR probe
changes the final link, without rebuilding dependencies with workspace-wide flags:

```bash
mkdir -p /tmp/grit-startup/{release,dist}/{stock,relr}
cargo build --release -p grit-cli --locked
cp target/release/grit /tmp/grit-startup/release/stock/grit
cargo rustc --release -p grit-cli --locked --bin grit -- \
  -C link-arg=-Wl,-z,pack-relative-relocs \
  -C link-arg=-Wl,-Map=/tmp/grit-startup/release-relr.map
cp target/release/grit /tmp/grit-startup/release/relr/grit
cargo build --profile dist -p grit-cli --locked
cp target/dist/grit /tmp/grit-startup/dist/stock/grit
cargo rustc --profile dist -p grit-cli --locked --bin grit -- \
  -C link-arg=-Wl,-z,pack-relative-relocs \
  -C link-arg=-Wl,-Map=/tmp/grit-startup/dist-relr.map
cp target/dist/grit /tmp/grit-startup/dist/relr/grit
cargo build -p grit-utils --bin grit-bench --example startup_compare
cc -O2 grit-utils/examples/startup_measure.c -o /tmp/grit-startup/measure
```

Stop builds and tests before timing. The focused example uses the daily runner's
`measure-direct-run` helper and statistics, with five warmups and **60 measured
runs per tool** (minimum 30), rotating stock/candidate/system-Git order. The daily
default policy caps at 20 and is insufficient for this investigation.

```bash
./target/debug/examples/startup_compare \
  --stock /tmp/grit-startup/dist/stock/grit \
  --candidate /tmp/grit-startup/dist/relr/grit \
  --helper "$PWD/target/debug/grit-bench" \
  --native-helper /tmp/grit-startup/measure \
  --fixtures /tmp/grit-startup/fixtures --profile dist \
  --output /tmp/grit-startup/dist.json
```

Repeat with the frozen `release` binaries and `--profile release`. Fixtures cover
one local branch, 20,000 refs, 20,000 tracked paths, and 20,000 commits. Every
fixture passes system `git fsck --strict`; each candidate command must preserve
stock stdout/stderr. Branch, status, resolve, help and a 1,000-entry log run on
all four shapes. Git's branch list is unbounded while grit's default list is
bounded; the comparison reports the actual argv and does not equate their output
volume on the many-ref fixture.

Reports retain individual wall-time samples, medians, standard deviations and
per-child peak RSS. The existing helper measures after spawn, through child
exit; the small C parent records full fork/exec/wait times, per-child RSS and page faults in the `native` block for startup conclusions.
Cross-check RSS with `/usr/bin/time -v`, using a fresh small parent per child;
a long-lived Python parent's inherited RSS can swamp short-command measurements.
Record minor/major page faults separately, and keep `LD_DEBUG=statistics` loader
cycles apart from end-to-end wall time. Neither loader cycles nor relocation
metadata bytes measure heap use.

Inspect `readelf -hW -lW -dW -rW -VW`, `nm -S -n`, and the linker maps. RELR
compresses relative relocation metadata; it still writes the same pointer slots.
Dependency tables, including regex Unicode tables, contribute relocations even
when their code executes lazily. Preserve Unicode matching, filtering, schemas
and tracing when considering source changes.

The release workflow packages the original glibc 2.34 x86_64 GNU asset before
performing this CLI-only RELR link for a separate `-gnu-relr` asset. The latter
requires glibc 2.36+ and remains a manual download. Stable/nightly installers
always use the original GNU asset on glibc systems: the final-tip review found
a 1–2% startup regression, despite earlier gains. Before enabling automatic
selection, benchmark stock and RELR from the exact release source again with
builds/tests stopped; require a demonstrated benefit rather than inferring one
from compressed metadata or loader support. This preserves the existing loader
minimum and leaves other targets unchanged. Run both ELF/runtime checks and the
pinned 2.34/2.36 container smokes in `.github/workflows/release.yml`; see
[TESTING.md](https://github.com/gitbutlerapp/grit/blob/main/TESTING.md#linux-gnu-startup-and-loader-contract).
The initial measured dist gain is 5–8% for tiny commands. The earlier Xeon
shipping follow-up measured 4–5% for branch/status/resolve, with help within
its sample spread. Both reports retain variance and independent RSS; layout
changes mean metadata compression is not a general memory reduction. The
shipping JSON also records 30 loader-only observations and ten GNU-time peak
RSS samples per tiny command/tool.

The final-tip follow-up in `startup-relocations-review-{release,dist}.json`
records exact `3fcfb24e9` CLI/library source, frozen binary hashes and the actual
AMD EPYC 7763 host. Tiny dist commands regress 0.88–2.07%; release changes are
near zero. The native block includes paired-bootstrap 95% intervals from 5,000
resamples of the 60 round indices (reset RNG seed 4626 per case), taking
`median(candidate) - median(stock)`. Loader-only and GNU-time cross-checks use
the runner's isolated environment, recorded in `isolated_env_overrides`.

## Hot text layout

Short commands' peak RSS is mostly the binary's own code: the kernel maps file-backed text
in 64 KB fault-around windows, so a function run once makes its whole window resident, and
the library functions an operation runs are otherwise scattered over the whole `.text`.
`grit-lib`'s `hot-text-layout` feature lays the library's hot code path out contiguously in
every binary that links it; `grit` enables it and lays out its own hot code the same way
(see [Benchmarks](https://grit-scm.com/docs/benchmarking/benchmarks.md/index.md#status-memory-is-code-layout-2026-10-31) and
[Benchmarks](https://grit-scm.com/docs/benchmarking/benchmarks.md/index.md#the-cli-joins-the-hot-text-layout-2026-10-31)).

- [`grit-lib/hot-text.ld`](https://github.com/gitbutlerapp/grit/blob/main/grit-lib/hot-text.ld)
  lists the functions of grit-lib, the Rust runtime and grit-lib's own dependencies that the
  library's common operations run. Anything that names another crate, such as a CLI type
  or clap, is left out.
- `grit-lib/build.rs` publishes the fragment as a native library. LLD reads it as an
  implicit linker script and places the listed functions in one `.text.grit_hot` output
  section ahead of `.text`.
- [`grit-cli/hot-text.ld`](https://github.com/gitbutlerapp/grit/blob/main/grit-cli/hot-text.ld)
  lists everything else the same workloads run in the `grit` binary: the CLI's own code,
  clap, and library generics the CLI instantiates. `grit-cli/build.rs` passes it to the
  final link of `grit` only, which places those functions in `.text.grit_cli_hot`, also
  ahead of `.text`. Every command runs argument parsing and CLI start-up first, so this
  half matters as much as the library's for short commands.
- GNU ld rejects `SECTIONS` in implicit scripts, so both fragments only act on
  `x86_64-unknown-linux-gnu`, where rustc links with LLD by default. Set
  `GRIT_HOT_TEXT_LAYOUT=0` to turn them off, for example when linking with another linker.
- Patterns glob input-section names with crate hashes wildcarded, so version bumps keep
  them matching. A function that is renamed or no longer runs simply stays in `.text`.
- Every function matches with and without a local-copy suffix. ThinLTO in the `release`
  profile renames a function it shares between codegen units to `name.llvm.<n>`, while the
  single-unit `dist` build keeps most names bare, so a list that pinned either form would
  miss much of the other build.
- The instantiating crate at the end of a generic's symbol is wildcarded as well. LLVM
  merges identical instantiations from different crates into one copy, and which crate's
  name the survivor keeps changes between builds: the stripped `dist` binary can name
  `<String as Display>::fmt` after `serde_json` where the profiled unstripped one named it
  after `grit`. About one pattern in eight names an instantiating crate; with it pinned,
  `grit branch` on the shipped build still faulted in 12 windows of plain `.text`, against
  5 with the wildcard.
- Every alias of an executed function is listed. LLVM merges functions with identical code
  (`RawVec<T>::grow_one` for every same-sized `T`) into one body and keeps the other names
  as aliases at the same address. The body's input section is named after one of them,
  while callgrind reports whichever name it picks for the address, so listing only that
  name left 15 such bodies in `.text` on a `release` build of `grit status`.
- Impl disambiguators (`Ms<n>_`) are kept, and they depend on grit-lib's features. Building
  `grit` together with `grit-utils`, as the daily census does, turns on `serde-models`,
  whose extra impls renumber them, while shipped binaries build `grit-cli` alone. The
  generator profiles both builds of both profiles, so the lists match either one (see
  [Benchmarks](https://grit-scm.com/docs/benchmarking/benchmarks.md/index.md#pick-revert-and-merge-join-the-hot-text-layout-2026-11-02)).
- The `hot_text_layout` test fails if either section is missing, smaller than its floor
  (256 KiB for the library, 128 KiB for the CLI, the sign that most patterns stopped
  matching), or not ahead of `.text`.

Regenerate both lists after large library or CLI changes, from an unstripped `dist` build
and a `release` build:

```bash
CARGO_PROFILE_DIST_STRIP=false CARGO_TARGET_DIR=target/hot-text \
  cargo build --profile dist -p grit-cli
CARGO_TARGET_DIR=target/hot-text cargo build --release -p grit-cli
python3 scripts/gen_hot_text_layout.py \
  --grit target/hot-text/dist/grit --grit target/hot-text/release/grit
```

The script needs `valgrind`. It builds a 10,000-file clone (packed objects and refs, tags,
an upstream) and runs the library's common operations through each binary, so inlining
matches what is linked: status, diff, log (one page and a streamed `--json` listing), show,
revision walks, blame, refs, branch listing and edits, config, add, commit, stash, and
switch twice: to a branch about 300 files away (the parallel checkout) and to one 50 files
away, below `checkout.thresholdForParallelism`, which writes files on the serial path every
small switch takes. Each workload starts right after a reset, so its first step also takes the
index-refresh path. Callgrind records every function each step runs; the script merges what
the builds ran and splits it into the library's functions and the rest. Each list keeps the
functions that the same set of workloads runs together, and orders those groups in reflected
binary (Gray code) order over the workloads, status first: neighbouring groups differ in as
few workloads as possible, so each command's code forms a few long runs. Sorting by how many
workloads share a function, as the lists did before, cut a command's code into one slice per
sharing count. The order of `WORKLOADS` matters: the first two workloads' code is one run
each, and the further down the list a workload is, the more runs its code splits into, so
the commands whose memory matters most come first. The CLI's list keeps the older sort by
sharing count and uses the Gray order only between equally shared functions: every command
runs the CLI's start-up and argument parsing, so that shared core stays dense at the front,
and the full Gray order there cost config and ref listings a window each.

Both orders are then refined by a search: it moves whole groups and keeps a move when the
64 KB windows all workloads touch, counted with each build's code sizes and averaged over
four section start offsets, do not rise in total and no workload's own count rises above
what the starting order gave it. The search is seeded, so a regeneration from the same
builds is reproducible; `--search-iterations 0` keeps the plain Gray order. Both builds
matter: the shipped `dist` binary inlines more under fat LTO, while the `release` build that
development and local benchmarking use keeps functions such as clap's command construction
separate, and those are cold in a list taken from `dist` alone.

To see where a run's resident pages are, stop the process at `exit_group` under `gdb` and
read `/proc/<pid>/smaps` (per mapping) or `/proc/<pid>/pagemap` (per page, to map back to
symbols with `nm`).
