Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

git-gud (gg) is a stacked-diffs CLI for GitHub and GitLab.

It helps you split large changes into a sequence of small commits that reviewers can understand quickly. In git-gud, each commit in your stack maps to its own PR/MR, and dependencies are wired automatically.

Why this workflow exists

Stacked diffs solve a common problem: features are often too large for a single review, but splitting work manually into many dependent branches is painful.

With git-gud, you can:

  • Keep reviews small and focused
  • Keep moving while earlier changes are in review
  • Preserve clean, logical commit history
  • Land big projects incrementally without long-lived feature branches

Learn more about stacked diffs

Provider support

git-gud supports:

  • GitHub through gh
  • GitLab through glab

Provider selection is auto-detected from your remote URL (github.com / gitlab.com). For self-hosted instances, run gg setup and select the provider explicitly.

Prefer a GUI?

Alas is the GUI for git-gud. It’s a native macOS app from the same author for running coding agents across worktrees, and it uses gg for stacks. You can publish a whole stack, or hold back the top, and Alas follows every PR/MR through CI and review, then lands the stack one entry at a time.

brew install --cask mrmans0n/tap/alas

Alas needs macOS 15 Sequoia or later. The source is at mrmans0n/alas.

Getting Started

Installation

Homebrew (macOS/Linux)

brew install mrmans0n/tap/gg-stack

crates.io

cargo install gg-stack

From source

cargo install --path .

Prerequisites

Before using git-gud, make sure you have:

gh is required for GitHub PR creation and ordinary gg sync. The optional github/gh-stack extension adds the native GitHub Stacked PRs map and UI; it is not required for PR creation or ordinary sync.

gh extension install github/gh-stack

Authentication

Authenticate with your provider CLI first:

# GitHub
gh auth login

# GitLab
glab auth login

If authentication is missing, gg sync and gg land cannot create or merge PRs/MRs.

Note: If the auth check fails due to a network error (e.g., DNS resolution failure, connection timeout), gg will print a warning and continue. The operation may still fail later if authentication is actually required.

Initial setup

After installing, run the setup wizard in any git repository to configure git-gud:

gg setup

This interactively sets your base branch, username for branch naming, provider (auto-detected for github.com/gitlab.com), and optional lint commands. Configuration is stored per-repo in .git/gg/config.json.

Tip: gg setup is optional — git-gud auto-detects sensible defaults. But it’s useful for setting lint commands, customizing your username prefix, or configuring self-hosted GitHub Enterprise / GitLab instances.

See Configuration for all available options.

Quick start: first stack in 2 minutes

# 1) Create a stack
gg co my-feature

# 2) Commit in small slices
git add . && git commit -m "Add data model"
git add . && git commit -m "Add API endpoint"
git add . && git commit -m "Add UI"

# 3) Inspect current stack
gg ls

# 4) Push branches and create PRs/MRs
gg sync --draft

# 5) Navigate to edit an earlier commit
gg mv 1
# ...make changes...
gg sc

# 6) Re-sync after changes
gg sync

# 7) Land approved changes
gg land --all

# 8) Clean merged stack
gg clean

For a full walkthrough with expected outputs and decision points, see Your First Stack.

Core Concepts

Stacked diffs in one sentence

A stack is a series of commits where each commit is reviewed as its own PR/MR, and each PR/MR depends on the previous one.

The git-gud model: one commit = one PR/MR

In git-gud, each commit is an “entry” in the stack:

  • Entry 1 targets your base branch (for example, main)
  • Entry 2 targets entry 1’s branch
  • Entry 3 targets entry 2’s branch
  • …and so on

That gives reviewers small units, while preserving execution order.

GG metadata trailers

Each stack commit carries stable trailers, for example:

GG-ID: c-abc1234
GG-Parent: c-1234567
  • GG-ID identifies the commit itself.
  • GG-Parent points to the previous stack entry’s GG-ID.
  • The first stack entry has no GG-Parent.

Why this matters:

  • Commit-to-PR/MR mappings stay stable across rebases
  • Stack topology is recoverable from commit-local metadata
  • gg sync and gg reconcile can auto-heal metadata drift after history edits

Branch naming convention

git-gud uses predictable branch names:

  • Stack branch: <username>/<stack-name>
  • Entry branch: <username>/<stack-name>--<gg-id>

Example:

  • nacho/user-auth
  • nacho/user-auth--c-abc1234

This convention is what makes remote discovery (gg ls --remote) and reconciliation possible. If a stack-shaped branch uses a different prefix than defaults.branch_username, commands such as gg sync, gg log, and gg ls warn that discovery and saved PR/MR mappings may be inaccurate. Rename the branch to the configured prefix to keep stack metadata aligned.

PR/MR dependency chains

Dependency chaining is automatic during gg sync:

  • First PR/MR targets main (or your configured base)
  • Next PR/MR targets previous entry branch
  • This continues until stack head

Result: reviewers can review from bottom to top, and gg land can merge safely in order.

Immutable commits

Some commits should not be casually rewritten. History-rewriting commands — gg squash, gg drop, gg reorder, gg split, gg unstack, gg absorb, and gg rebase — refuse to touch the following by default:

  • Merged PR/MR commits. If an entry’s PR/MR state is Merged, rewriting it locally produces a duplicate of something already upstream. This is the only rule that catches squash-merged PRs, because their merge commit on origin/<base> has a brand-new SHA that doesn’t share ancestry with your local commit.
  • Base-ancestor commits. Any commit already reachable from origin/<base> via plain merge or rebase falls in the same bucket. When no origin/<base> ref exists, gg falls back to the local base branch.

Exception: gg rebase silently skips both merged-PR commits and base-ancestor commits instead of blocking, because git rebase naturally drops them via patch-id matching. An info line (→ Skipping N merged commit(s) already on <base>) is printed when this happens.

Running one of those commands on an immutable target prints a clear error like:

error: cannot rewrite immutable commits (pass --force / --ignore-immutable to override):
  #2  abc1234  Fix typo in parser  (merged as !123)
  #3  def5678  Bump dependency     (already in origin/main)

If you genuinely want to rewrite history anyway, pass --force (or --ignore-immutable if you prefer the longer, self-describing name). Every rewrite command accepts both spellings. The guard still emits a warning so scripts see that they are bypassing a safety check.

When the guard is hit by gg sync while it is auto-rebasing before push, the override belongs to the rebase step, not sync’s push --force. Run gg rebase --force or gg rebase --ignore-immutable, then rerun gg sync.

Keeping PR state fresh

Each rewrite command runs a best-effort PR-state refresh against the configured provider just before the immutability check, so the merged-PR rule fires even when nothing in the session has touched provider state yet. The refresh is silent when offline / no auth is configured, in which case the base-ancestor rule remains the only protection. Note that base-ancestor does not catch squash-merges (those produce a new SHA on origin/<base>), so working offline against a repo that uses squash-merge is the one case where you can still rewrite a “merged” commit without --force. A working provider closes that gap automatically.

Guides

This section is practical and task-oriented.

If you’re new to stacked diffs, start with Your First Stack. If you’re already using git-gud day-to-day, jump to the workflow you need (editing, remote collaboration, worktrees, landing, linting, reconcile).

Your First Stack

This walkthrough covers the full lifecycle: create → commit → sync → edit → land → clean.

1) Create a stack

gg co user-auth

This creates/switches to stack branch your-user/user-auth.

2) Build the feature in reviewable commits

git add . && git commit -m "Add user model"
git add . && git commit -m "Add auth endpoints"
git add . && git commit -m "Add login UI"

Keep each commit small and self-contained.

3) Inspect stack structure

gg ls

You should see ordered entries, each with a GG-ID.

4) Publish review chain

gg sync --draft

This pushes one branch per entry and creates one PR/MR per commit, chained by dependencies.

5) Address feedback in an older commit

gg mv 1
# edit files
git add .
gg sc

gg sc amends the current entry and rebases subsequent entries automatically.

6) Update remote PRs/MRs

gg sync

If your stack base is behind origin/<base>, gg sync warns and suggests running gg rebase first. Use --no-rebase-check to skip this check once. After a bottom entry lands, use gg sync --rebase-if-needed to retarget the next review without rewriting branches that still merge cleanly.

7) Land approved entries

gg land --all

Use --wait if you want git-gud to wait for CI/approvals:

gg land --all --wait

8) Cleanup

gg clean

Editing Commits in a Stack

The most common stacked-diff operation is “change commit N without losing N+1, N+2…”.

gg mv 2
# or use gg first / gg next / gg prev / gg last

Make changes and fold them in

# after editing files
git add .
gg sc

Use gg sc --all to include unstaged changes too.

Reorder commits

Interactive:

gg reorder

Explicit order:

gg reorder --order "3,1,2"

Absorb scattered staged edits automatically

gg absorb

Useful flags:

  • --dry-run: preview only
  • --and-rebase: absorb and rebase in one step
  • --whole-file: match whole-file changes instead of hunks
  • --squash: squash fixups directly

After major edits, run:

gg sync

Insert a commit in the middle of a stack

Sometimes you realize a commit is missing between two existing ones. Use gg mv to navigate there, make a normal git commit, then run gg restack to fold it in.

gg co testing
git commit -m "one"
git commit -m "two"

# navigate to position 1 (HEAD detaches)
gg mv 1

# make the new commit
git add <files>
git commit -m "inserted"

# gg ls shows the un-integrated commit rather than losing it:
#   ⚠ Un-integrated commit at HEAD (detached):
#       3fb873d inserted  — sits on top of [1]
#     Run `gg restack` to fold it into the stack.
gg ls

# fold it in — stack becomes: one, inserted, two
# HEAD stays on the inserted commit when restack finishes
gg restack

gg ls is read-only: it never mutates the stack. The “un-integrated commit” callout is purely informational — the commit is not lost, it just isn’t part of the stack yet. gg restack is what integrates it.

The same flow works when you git commit --amend the navigated commit instead of creating a new one. In that case gg restack rewrites the commit in place and replays everything above it on top.

Working with Remote Stacks

Use this when a stack exists on origin but not in your local checkout (new machine, pairing, takeover).

Discover remote-only stacks

gg ls --remote

Active stacks are shown first. Stacks whose PRs/MRs have all been merged appear in a separate “Landed” section at the bottom, so you can focus on work that still needs attention.

Check out a remote stack

gg co user-auth

If a local stack doesn’t exist, git-gud uses the remote stack branch when present. Otherwise, it reconstructs the stack from remote entry branches named <username>/<stack-name>--<gg-id> and imports available PR/MR mappings. Checkout selects the tip by Git ancestry, so the local branch includes all entries even when GG-IDs sort in a different order. The selected stack history above its configured base must be linear.

If checkout reports that entry branches have diverged, no single linear tip contains all entries; joining divergent entries with a merge commit is not a supported stack. Inspect the remote branches and resolve the divergence before retrying. It leaves your current checkout unchanged and does not create a partial local stack.

Typical collaboration loop

gg co teammate-feature
gg ls
# make changes
gg sync

Tips:

Using Worktrees

Worktrees let you keep your main checkout clean while developing a stack in a dedicated directory.

Create stack in a managed worktree

gg co user-auth --worktree

To move your shell into the worktree automatically after checkout, enable shell integration:

# zsh
eval "$(gg init zsh)"

# bash
eval "$(gg init bash)"

# fish
gg init fish | source

Without shell integration, gg co --worktree prints the worktree path and leaves your shell in the original checkout.

Short flag:

gg co user-auth -w

Why use worktrees

  • Keep stack changes separate from your main checkout
  • Work on multiple stacks side by side
  • Avoid stashing/switching overhead
  • Run gg on another stack while gg land --wait polls in a different worktree

Waiting does not reserve the stack being landed. If that stack changes before the next merge, gg land --wait stops and must be rerun.

gg rebase, including auto-rebase during gg sync, also fast-forwards a clean base checkout. If that checkout has uncommitted changes, git-gud leaves it alone, warns with its path, and rebases the stack onto origin/<base>. gg sync --rebase-if-needed uses a per-stack base snapshot instead. Even when it must rebase the stack, it does not move the base branch or touch its checkout.

Default path behavior

By default git-gud creates:

../<repo-name>.<stack-name>

You can change this with defaults.worktree_base_path in .git/gg/config.json.

Cleanup behavior

gg clean removes merged stacks and associated managed worktrees.

Landing and Cleanup

Use gg land to merge entries in order, from the bottom of the stack upward.

Land one approved entry

gg land

Land the whole stack

gg land --all

Approval is checked again for each entry immediately before its final queue or merge request. This prevents --all from landing an entry whose approval was dismissed while earlier entries were being processed. GitHub’s explicit admin override is the only exception; GitLab always requires approval.

Direct merges perform this final check in both normal and --wait mode, including every entry selected by --all or --until.

GitLab auto-merge performs the same final check in --wait mode before queueing the selected MR. A refusal creates no landing recovery state.

Wait for CI and approvals

gg land --all --wait

Land only part of a stack

gg land --until 2
# or by GG-ID / SHA

Merge strategy and provider-specific behavior

gg land --no-squash

On GitLab, a non-wait --no-squash run checks approval again immediately before turning off the MR’s squash setting. If that approval has been dismissed, the command refuses before changing the MR or creating landing recovery state.

By default, landing several entries rebases and force-pushes the remaining branches after every merge, which re-triggers CI on each of them. A GitHub native stack is the exception: GitHub retargets and restacks the remaining PRs itself, so gg neither retargets nor pushes them and only waits for GitHub before landing the next PR. On large stacks, land with merge commits and --rebase-if-needed. After each merge, gg checks that the landed commit reached the base branch unchanged and that the forge says the next PR/MR still merges cleanly. When both hold, the remaining branches stay as they are; otherwise gg rebases them as usual:

gg land --all --wait --no-squash --rebase-if-needed

On GitLab projects with merge trains, --wait starts a required MR pipeline if retargeting leaves the next MR without one. You don’t need to push a new commit or click Run pipeline. Approval is refreshed after confirming that the pipeline is still missing and immediately before the creation request. If approval was dismissed while waiting, no pipeline request or later queue mutation is sent.

Before the initial merge-train queue request, gg validates the final MR or pipeline handoff and refreshes approval again. If approval was dismissed, it creates no queue attempt or landing recovery state and sends no queue request; GitLab --admin does not bypass this check.

If a later push cancels that queued merge, --wait treats the requeue as a new authorization boundary. gg validates the MR’s current head and approval before creating requeue recovery state or sending another request. A lost response or post-POST durability-checkpoint failure leaves the action-specific recovery marker in place, so a restart stops before provider access instead of risking a duplicate POST. Inspect the reported MR and operation ID before changing recovery data or retrying manually.

gg land stops before changing the remote if it cannot read a valid merge-train setting. It also revalidates each MR immediately before mutation and requires an explicit open, non-draft state with the expected target branch. Retry only after direct provider inspection confirms those values.

The initial merge-train queue request is recovery-safe. gg records the request before sending it. If GitLab accepts the request but the response is lost, later Land runs stop before provider access instead of queueing the MR again. Inspect the reported MR and operation ID in GitLab and the local operation log before changing recovery data. A completed pipeline handoff is kept separately, so investigating the queue request does not discard that evidence.

--no-rebase skips the rebase without checking. Use it only when you know the base branch keeps original commits.

GitLab auto-merge queue:

gg land --auto-merge

Auto-clean after landing

One-off:

gg land --all --clean

Or make it default with land_auto_clean in config.

Auto-clean (--clean, land_auto_clean or the prompt) runs only after an error-free landing; if landing stops with an error, gg keeps the stack. When --clean or land_auto_clean requested cleanup and every entry merged before the error, the summary includes a warning explaining why cleanup was skipped.

Manual cleanup remains available:

gg clean

Linting Your Stack

gg lint runs your configured lint commands commit-by-commit across the stack.

Configure lint commands

In .git/gg/config.json:

{
  "defaults": {
    "lint": [
      "cargo fmt --check",
      "cargo clippy -- -D warnings"
    ]
  }
}

Run lint manually

gg lint

Run only up to a specific entry:

gg lint --until 2

When lint rewrites commits in sequential mode, --until freezes the originally selected entries before the first rewrite. If a rewrite drops one, an entry that shifts into the same stack position does not replace it.

A stable, unique GG-ID or title lets an originally selected entry continue across OID-changing rewrites. If an earlier rewrite makes a selected commit’s OID unresolvable and it has no unique GG-ID or title, lint fails closed with a validation could not be completed error instead of reporting success.

Inspect the rewritten current stack and rerun gg lint. Before retrying broader mutating validation, make commit identity unambiguous: prefer unique GG-IDs, otherwise use unique titles. Already-applied rewrites remain in place under the existing restoration behavior.

You can run lint after navigating to a detached position with gg mv. If lint rewrites that commit, git-gud leaves HEAD detached at the rewritten logical entry when it can identify the entry uniquely. If it cannot, git-gud safely restores the exact commit you started from rather than selecting a branch or a different stack entry.

Run lint during sync

gg sync --lint

If lint fails during gg sync --lint, sync is aborted and git-gud restores repository state to the pre-sync snapshot.

Skip lint for one sync (even if enabled by default):

gg sync --no-lint

Reconciling Out-of-Sync Stacks

Use reconcile when stack metadata and remote state diverge.

Common causes:

  • Someone pushed with git push instead of gg sync
  • A stack was edited across machines and mappings got stale
  • Commits exist without GG-ID trailers

Preview changes safely

gg reconcile --dry-run

Apply reconciliation

gg reconcile

Reconcile can:

  1. Add missing GG-IDs to stack commits (via rebase)
  2. Map existing PRs/MRs to the right GG-IDs in config

After reconciling, run:

gg ls --refresh
gg sync

Agent Skills

git-gud follows the open Agent Skills standard. AI coding agents with shell access — including Codex, Claude Code, Cursor, Gemini CLI, VS Code integrations, and others — can use gg for stacked-diff workflows.

What’s included

The integration provides one unified skill:

SkillDescription
ggUse gg with GitHub PRs (gh CLI) or GitLab MRs (glab CLI, merge trains)

The gg skill is a compact, CLI-first intent router. It keeps the agent’s authority and safety boundaries close at hand, then routes each goal to only the operational guidance needed for that phase.

Each skill includes:

  • SKILL.md — compact CLI-first intent router, agent rules, and safety boundaries
  • references/ — phase-specific operational guidance loaded on demand

CLI help (gg <command> --help) is the source of truth for installed flags. For exhaustive user documentation and command examples, use the mdBook command pages.

Installation

npx skills add mrmans0n/git-gud

The skills CLI installs the skill into the agent setup it detects. If it cannot decide, it prompts you to choose where to install it.

2) Install for a specific agent

Use --agent when you already know the host you want to target:

npx skills add mrmans0n/git-gud --agent codex
npx skills add mrmans0n/git-gud --agent claude-code
npx skills add mrmans0n/git-gud --agent cursor
npx skills add mrmans0n/git-gud --agent gemini-cli

For a shared repository setup, run the command from the project root. For a user-level install, add --global.

3) Claude Code marketplace

Claude Code users can also install git-gud as a plugin:

claude plugin marketplace add https://github.com/mrmans0n/git-gud
claude plugin install git-gud

4) Claude Code local checkout

Use this when launching Claude Code directly from a local git-gud checkout:

claude --plugin-dir /path/to/git-gud

5) Claude Code project-level config (.claude/settings.json)

Use this when you want the local checkout enabled by default for a repository:

{
  "plugins": [
    {
      "name": "git-gud",
      "path": "/path/to/git-gud"
    }
  ]
}

6) Manual setup for compatible tools

Tools that support Agent Skills can also load the repo’s skills/gg/ directory directly. Use this fallback if your agent does not use the skills CLI yet, or if you want to manage skill files yourself.

How agents typically use gg

A practical AI-assisted stacked-diff workflow looks like this:

  1. Agent creates or switches to a stack (gg co ..., ideally with a worktree)
  2. Agent makes small commits and keeps each commit focused
  3. Agent syncs the stack (gg sync) so PRs/MRs are created/updated in order
  4. Agent iterates on review feedback (amend/reorder/re-sync)
  5. Agent asks for explicit user confirmation before gg land

This keeps work reviewable while preserving user control over merges.

JSON output for tool-driven agents

For machine-readable parsing, gg supports --json on key commands:

  • gg ls --json
  • gg sync --json
  • gg land --json
  • gg clean --json
  • gg lint --json

Use these outputs in agents and automation for reliable state checks and decisions. Use CLI help and the mdBook command pages for complete user-facing command documentation.

Safety model (required behavior)

When using AI agents with gg, keep these rules:

  1. Never land without explicit user confirmation
  2. Never run git add -A blindly (stage only reviewed/intended files)
  3. Prefer worktrees for isolation (gg co --wt)
  4. Use structured output (--json) when automation must parse command results

Skill references

For the compact router and phase-specific operational guidance:

File structure

skills/
  gg/
    SKILL.md
    references/
      setup-and-inspection.md
      editing-stacks.md
      syncing-and-reviews.md
      landing-and-cleanup.md
      recovery.md
      native-clients.md

Command Reference

This section is a command-by-command reference based on gg --help and gg <command> --help.

Unlike the guides, this section is organized by command surface and flags. Each page still includes practical examples.

Command groups

  • Stack lifecycle: co, ls, sync, land, clean
  • Editing: mv, first, last, prev, next, sc, absorb, reorder, split, unstack, rebase
  • Utilities: lint, setup, reconcile, continue, abort, init, completions

gg co

Create a new stack, switch to an existing local stack, or check out a remote stack by name.

gg co [OPTIONS] [STACK_NAME]

Options

  • -b, --base <BASE>: Base branch to use (default auto-detected: main/master/trunk)
  • -w, --worktree: Create or reuse a managed worktree for this stack

Remote stacks

If the stack is not available locally, gg co fetches from origin. It uses origin/<username>/<stack-name> when that branch exists. Otherwise, it rebuilds the local stack from <username>/<stack-name>--<gg-id> entry branches, choosing the commit that contains every entry in a linear history above the explicit --base, stack-configured base, or auto-detected base, in that order. GG-ID sorting does not determine stack order.

If the entry branches have diverged, including when a merge commit joins them, checkout fails without creating the local stack branch. Resolve the divergent remote branches into a linear stack, then retry. The same selection applies with --worktree.

Examples

# Create/switch stack
gg co user-auth

# Create stack based on a specific branch
gg co user-auth --base develop

# Create stack in worktree
gg co user-auth --worktree

With shell integration enabled, gg co user-auth --worktree also changes your current shell directory to the stack worktree after the command succeeds:

eval "$(gg init zsh)"  # or bash
gg init fish | source # fish

Without shell integration, git-gud prints the worktree path and leaves your shell in the original checkout.

gg ls

List the current stack, all local stacks, or remote-only stacks.

When the stack base is behind origin/<base>, output includes a ↓N indicator (N = commits behind).

When showing the current stack, if the current branch has a valid stack shape but uses a different prefix than defaults.branch_username, gg ls warns that stack discovery, listing, and saved PR/MR mappings may be inaccurate. Rename the branch to the configured prefix to keep stack metadata aligned. gg ls --all and gg ls --remote do not show this warning.

gg ls [OPTIONS]

Options

  • -a, --all: Show all local stacks
  • -r, --refresh: Refresh PR/MR status from remote
  • --no-refresh: Skip the provider API and return local stack data immediately. Conflicts with --refresh and --remote; listing all stacks also requires defaults.branch_username to be configured. Intended for local-only JSON consumers.
  • --remote: List remote stacks not checked out locally. Stacks whose PRs/MRs are all merged are shown in a separate “Landed” section at the bottom with a ✓ marker
  • --json: Print structured JSON output (for scripts and automation). Automatically performs a best-effort refresh of PR/MR state from the provider API, so pr_state and ci_status fields are populated without needing --refresh.

Examples

# Current stack status
gg ls

# All local stacks
gg ls --all

# Remote stacks (active first, then landed)
gg ls --remote

# Refresh status badges from provider
gg ls --refresh

# Structured JSON for automation
gg ls --json
gg ls --all --json
gg ls --remote --json

# Local-only JSON without waiting for the provider API
gg ls --json --no-refresh

Queued merges in JSON output

Each stack entry in gg ls --json has an auto_merge boolean. It is true when the forge already has a merge queued for that entry: GitHub auto-merge is enabled, or a GitLab MR is set to auto-merge or sits on a merge train. Pushing to such a branch makes GitLab cancel the queued merge, so automation should avoid rebasing or syncing the stack while an open entry reports auto_merge: true.

Errors in JSON output

When gg ls --json fails, for example outside a Git repository or when the provider cannot be reached for a remote listing, it prints {"version": 1, "error": "..."} and exits 1. Commands that report progress, such as gg sync and gg land, use this bare shape only for failures before they start; after that they keep their own sync or land object with an error field, so the work done before the failure stays visible.

auto_merge comes from the provider refresh. With --no-refresh it is always false, like the other provider-backed fields.

Un-integrated commits at HEAD

gg ls is read-only — it never mutates the stack. When you navigate to a mid-stack commit with gg mv and make a git commit (or git commit --amend) there, HEAD becomes detached with a commit that isn’t part of the stack yet. gg ls detects this and shows a callout instead of silently losing the commit:

⚠ Un-integrated commit at HEAD (detached):
    3fb873d inserted  — sits on top of [1]
  Run `gg restack` to fold it into the stack.

The commit is not lost — run gg restack to fold it into the stack.

unintegrated_commits in JSON output

When gg ls --json is called for the current stack, an unintegrated_commits array is included on the stack object when there are commits at a detached HEAD that haven’t been integrated yet. The array is omitted entirely when empty.

{
  "version": 1,
  "stack": {
    "name": "my-feature",
    "entries": [...],
    "unintegrated_commits": [
      {
        "sha": "3fb873d",
        "subject": "inserted",
        "sits_on_position": 1,
        "count": 1
      }
    ]
  }
}

Field types for each entry in unintegrated_commits:

  • sha: string — short SHA of the un-integrated commit
  • subject: string — first line of the commit message
  • sits_on_position: number — position of the stack entry that this commit sits directly on top of
  • count: number — total number of un-integrated commits at HEAD (useful when multiple commits were made before restacking)

Interrupted operation ID in JSON output

While a GG mutation is paused on the current Git rebase, gg ls --json includes its opaque operation-log ID at the top level:

{
  "version": 1,
  "operation_id": "op_...",
  "stack": {
    "name": "my-feature",
    "entries": []
  }
}

If the paused rebase leaves HEAD detached and no current-stack navigation state is available, the command returns the all-stacks envelope instead. Its top level still includes the same operation_id alongside current_stack and stacks.

Pass the value unchanged to gg undo <operation_id> --json after the operation has been completed or aborted. The field is omitted when no operation is paused.

If the rebase was ended with plain Git (git rebase --abort), the marker that named the operation is stale. gg ls clears it, prints a note on stderr, and lists the stack as usual. While a rebase is in progress, a marker that does not match it makes gg ls --json fail; see gg continue / gg abort for the way out.

gg log

Show a smartlog-style view of the current stack.

gg log is stack-scoped: it renders just the current stack as a tree, with each commit’s position, short SHA, title, PR/MR state, CI badge, and a <- HEAD marker on the currently-checked-out commit. For a cross-stack overview use gg ls --all.

If the current stack branch has a valid stack shape but uses a different prefix than defaults.branch_username, gg log warns that stack discovery, listing, and saved PR/MR mappings may be inaccurate. Rename the branch to the configured prefix to keep stack metadata aligned.

gg log [OPTIONS]

Options

  • -r, --refresh: Refresh PR/MR status from the remote before rendering.
  • --json: Print structured JSON output (for scripts and automation). Automatically performs a best-effort refresh of PR/MR state from the provider API, so pr_state and ci_status fields are populated without needing --refresh.

Example output

my-feature (3 commits, base: main)

  ├── [1] abc1234 feat: add parser open #101 ✓
  │        #101
  ├── [2] def5678 feat: wire CLI flag open #102 ●
  │        #102
  └── [3] 9abcdef test: coverage for edge cases not pushed  <- HEAD

JSON shape

{
  "version": 1,
  "log": {
    "stack": "my-feature",
    "base": "main",
    "current_position": 3,
    "entries": [
      {
        "position": 1,
        "sha": "abc1234",
        "title": "feat: add parser",
        "gg_id": "c-abc1234",
        "gg_parent": null,
        "pr_number": 101,
        "pr_state": "open",
        "approved": false,
        "ci_status": "success",
        "is_current": false,
        "in_merge_train": false,
        "merge_train_position": null,
        "auto_merge": false
      }
    ]
  }
}

Entry fields match gg ls --json so consumers can share parsers across both commands.

See also

  • gg ls — current stack details with more summary metrics, plus --all and --remote modes.

gg inbox

gg inbox shows an actionable repository-wide triage view for all local stacks. Instead of inspecting stacks one by one, it groups PRs or MRs by what they need right now.

Use it when you want quick answers to questions like:

  • which PRs are ready to land
  • which ones are blocked on CI
  • where changes were requested
  • which stacks have fallen behind their base

Usage

gg inbox
gg inbox --all
gg inbox --json
gg inbox --jsonl

Buckets

gg inbox classifies each PR or MR into exactly one bucket, in priority order:

  1. refresh_failed
  2. ready_to_land
  3. changes_requested
  4. blocked_on_ci
  5. awaiting_review
  6. behind_base
  7. draft
  8. merged (only with --all)

Classification notes

  • A canceled CI run counts as blocked_on_ci.
  • If remote refresh fails transiently, the entry stays visible in refresh_failed instead of disappearing, so the inbox does not look empty because of a temporary provider error.
  • behind_base is computed from the real stack tip versus origin/<base>, not from the state of your local base branch.

Example human output

The labels and number prefixes adapt to the detected provider.

GitHub:

Inbox (3 items across 2 stacks)

Ready to land (1):
  auth #2  abc1234  Add login button  stack/auth  PR #41

Blocked on CI (1):
  auth #3  def5678  Add login API  stack/auth  PR #42 ⏳

Awaiting review (1):
  billing #1  9876abc  Add invoice export  stack/billing  PR #51

GitLab:

Inbox (2 items across 1 stack)

Ready to land (1):
  auth #2  abc1234  Add login button  stack/auth  MR !41

Awaiting review (1):
  auth #3  def5678  Add login API  stack/auth  MR !42

Live refresh

When both stdout and stderr are terminals, gg inbox renders one stable row per discovered PR or MR while remote state is refreshed. Rows stay in discovery order, the aggregate counter advances as refreshed N/M, and a completed row remains visible until the refresh finishes. The live display is cleared before the final grouped inbox is printed.

When output is redirected or piped, live progress is suppressed: stdout contains only the final grouped inbox and stderr contains no refresh progress.

JSON

With --json, gg inbox returns a versioned response designed for automation and MCP.

Example:

{
  "version": 1,
  "total_items": 2,
  "buckets": {
    "refresh_failed": [],
    "ready_to_land": [
      {
        "stack_name": "auth",
        "position": 1,
        "sha": "abc1234",
        "title": "Add login",
        "pr_number": 42,
        "pr_url": "https://github.com/org/repo/pull/42",
        "ci_status": "success",
        "behind_base": null
      }
    ],
    "blocked_on_ci": [
      {
        "stack_name": "auth",
        "position": 2,
        "sha": "def5678",
        "title": "Add login API",
        "pr_number": 43,
        "pr_url": "https://github.com/org/repo/pull/43",
        "ci_status": "running",
        "behind_base": 2
      }
    ]
  },
  "stack_errors": []
}

Per-entry fields

  • stack_name: stack name
  • position: commit position inside the stack
  • sha: short SHA
  • title: commit title
  • pr_number: PR or MR number
  • pr_url: PR or MR URL; empty for a refresh_failed entry when no URL was refreshed
  • ci_status: pending, running, success, failed, canceled, unknown, or null
  • behind_base: number of commits behind origin/<base>, or null
  • refresh_error: remote-refresh error text, present for entries in refresh_failed

Streaming NDJSON (--jsonl)

gg inbox --jsonl emits one flushed JSON object per line as discovery and refresh work completes. The first event is start; each discovery error emits stack_error; refresh completions emit entry or entry_error; and the final summary is the same deterministic payload as --json (apart from its event envelope). Consumers must wait for summary before making a complete-inbox claim. A fatal failure before the summary emits one error event and exits nonzero.

These representative lines use the exact serialized event shapes covered by the inbox output tests:

{"event":"start","total_candidates":2,"total_stack_errors":1,"version":1,"command":"inbox"}
{"event":"stack_error","stack_name":"stale","error":"missing base","version":1,"command":"inbox"}
{"event":"entry","completed":1,"total_candidates":2,"included":true,"bucket":"ready_to_land","remote_state":"open","entry":{"stack_name":"auth","position":1,"sha":"abc1234","title":"Add login","pr_number":42,"pr_url":"https://github.com/org/repo/pull/42","ci_status":"success","behind_base":null},"version":1,"command":"inbox"}
{"event":"entry_error","completed":1,"total_candidates":1,"included":true,"bucket":"refresh_failed","entry":{"stack_name":"auth","position":1,"sha":"abc1234","title":"Add login","pr_number":42,"behind_base":null},"error":"provider unavailable","version":1,"command":"inbox"}
{"event":"summary","total_items":1,"buckets":{"refresh_failed":[],"ready_to_land":[{"stack_name":"auth","position":1,"sha":"abc1234","title":"Add login","pr_number":42,"pr_url":"https://github.com/org/repo/pull/42","ci_status":"success","behind_base":null}],"changes_requested":[],"blocked_on_ci":[],"awaiting_review":[],"behind_base":[],"draft":[]},"stack_errors":[{"stack_name":"stale","error":"missing base"}],"version":1,"command":"inbox"}
{"version":1,"command":"inbox","status":"error","event":"error","message":"Not in a git repository"}

entry events are emitted in refresh-completion order. An entry omitted from the final inbox (for example, a merged entry without --all) has "included": false and "bucket": null.

--json vs --jsonl

  • Use --json for one final, structured cross-stack snapshot.
  • Use --jsonl when incremental results matter and a line-oriented consumer can process completion events before the final summary.

Partial failures

An individual remote refresh failure does not make gg inbox fail: the command exits zero and puts that entry in buckets.refresh_failed with a refresh_error. Discovery failures are reported in stack_errors and are also included in the JSONL stack_error events. Inspect both fields before treating the inbox as complete.

Flags

  • --all: include items already marked as merged
  • --json: emit structured output for tooling and MCP
  • --jsonl: emit flushed NDJSON events as refreshes complete; conflicts with --json

Relationship to other commands

  • gg ls shows detailed status for the current stack
  • gg log gives you a smartlog view of the current stack
  • gg inbox is for cross-stack triage across multiple stacks

gg sync

Push entry branches and create/update PRs/MRs for the current stack.

gg sync [OPTIONS]

Options

  • -d, --draft: Create new PRs/MRs as draft (does not affect existing PRs/MRs)
  • -f, --force: Force push even if remote is ahead
  • --update-descriptions: Update PR/MR descriptions from commit messages
  • --update-title: Update PR/MR titles from commit subjects. If the subject has no draft prefix, a GitLab draft MR keeps its existing prefix, such as [Draft].
  • -l, --lint: Run lint before sync (aborts sync on lint failure and restores repository state to the pre-sync snapshot)
  • --no-lint: Disable lint before sync (overrides config default)
  • --no-rebase-check: Skip checking whether your stack base is behind origin/<base>
  • --rebase-if-needed: After a parent lands, keep published branches at their existing SHAs when the next PR/MR can merge into the fetched base. Conflicts with --no-rebase-check.
  • --no-verify: Skip the pre-push hook for pushes performed by this sync (forwards git push --no-verify). Opt-in per invocation; does not affect other hooks.
  • -u, --until <UNTIL>: Sync up to target commit (position, GG-ID, or SHA) Lint fixes and order-preserving rebases keep the selected entry in scope even before it has a GG-ID. If a rebase drops entries and sync cannot identify the target, it stops rather than publishing a different commit.
  • --json: Output structured JSON for automation (suppresses human/progress output)
  • --jsonl: Output streaming NDJSON for automation (one JSON event per line, flushed after each; see Streaming Events below)

Before pushing, gg sync checks whether your stack base is behind origin/<base>. If it is behind by at least the configured threshold, git-gud warns and suggests rebasing first (gg rebase).

When you run gg sync --lint, lint runs before the first push or PR/MR update. A lint failure aborts sync and restores the checkout to its pre-lint state; it cannot undo a target change from a preceding successful lint pass.

Failure boundaries and safe retries

Before the per-entry sync loop mutates anything, gg sync reads every mapped PR/MR in scope. A failed lookup, missing or null review, or an unexpected source or state aborts before that loop starts mutating. An unexpected target does not: sync retargets the review (see Target Branch Resolution). This is a fail-closed preflight, not a transaction for the whole command.

Immediately before each remote mutation involving an existing mapped review, sync reads that review’s provider state again and authorizes that specific change. Unmapped branch pushes and initial review creation have no existing review to reread, but an ambiguous response leaves the same uncertainty. A race or lookup failure can stop the command after an earlier operation segment, branch push, or PR/MR creation or update succeeded. There is no automatic rollback. When sync creates a replacement for a review whose source branch changed, it persists the new review mapping immediately after successful creation, before attempting later updates or closing the old review.

Before any new PR/MR create request, sync durably records the source, target, pushed head commit, and owning operation ID in a repository-local creation intent. If the provider response is ambiguous (for example gh is killed after the PR was opened), sync retains that intent, commits the owning operation as remote-touched, emits an error checkpoint, and stops before any later create, prune, stack-link, replacement follow-up, or navigation mutation.

The next sync asks the provider what happened before it does anything else. It lists the open reviews from the intent’s source branch and keeps those into the saved target, opened by you (the authenticated gh/glab user), and at the saved head commit (intents written by v0.10.11 have no head, so that check is skipped). Then:

  • exactly one match: the create went through. Sync adopts that review, records it on the origin operation, and carries on without another create;
  • no match: the create never happened. Sync drops the intent and creates the review normally. A teammate’s review from the same branch is never adopted;
  • more than one match, one of your open reviews from that branch into another target or at another head (for example retargeted by hand), or the provider cannot be read: sync stops with an error that lists the reviews and names gg reconcile, rather than risk a duplicate. Inspect the reviews, then run gg reconcile --dry-run.

When the adopted review’s head differs from your local entry commit, sync prints a warning (on stderr, or in sync.warnings with --json/--jsonl) and carries on; the push that follows brings the review up to date.

Local branch tips and stack membership are not part of the match.

An explicit refusal is different from an ambiguous response. When GitHub or GitLab rejects the create (for example GraphQL: Draft pull requests are not supported in this repository, or an HTTP 4xx such as 422 Validation Failed), no review was created. Sync removes the creation intent, stops with an error that says the request “was rejected by the provider”, and the next gg sync creates the review normally once you have fixed the cause (here, syncing without --draft). A killed gh/glab, a network or TLS error, an HTTP 5xx, or output gg does not recognise is still treated as ambiguous.

Replaced-review follow-ups (the closing comment and close on a review whose source branch changed) and pending remote branch deletions are settled the same way at startup. A comment or close whose response was lost is checked on the old review: if it is there, sync moves on; if not, sync sends it again. A deletion whose branch is already gone is retired. A deletion whose branch is still at the expected commit is retried: sync sends the leased push again, first checking that no open review targets the branch. If the branch now points at another commit, sync stops and names gg reconcile.

A recovered intent deliberately uses its saved topology, even when gg unstack has since moved the entry. After recovery, normal sync topology handling can create a replacement review for the moved source branch. Successful gg land removes only the landed entry’s intent; unrelated unresolved intents remain. Creation intents and mappings live in gg/config.json under the directory reported by git rev-parse --git-common-dir.

Before retrying a failed sync, reconcile what actually happened:

  • inspect the mapped review number, state, source, and target on the provider;
  • compare the relevant remote branch tips with the intended local commits;
  • inspect gg/config.json under the directory reported by git rev-parse --git-common-dir for the current saved mapping;
  • enumerate all matching operation records with gg undo --list --json and check status, touched_remote, and remote_effects; and
  • if a rebase is paused, use gg ls --json to identify the owning operation before choosing gg continue or gg abort.

Do not blindly retry an uncertain push or remote deletion: an ambiguous response may hide a successful mutation. Retry only after provider state, remote refs, local config, and operation records agree on the current state. A request that “was rejected by the provider” is not uncertain: nothing was applied, and it is safe to retry once its cause is fixed.

Sync after a parent lands

Use gg sync --rebase-if-needed to publish the rest of a stack without restarting CI just because its bottom PR/MR merged. Sync fetches origin/<base>, excludes bottom entries reachable by their original SHA (even if their PR/MR mappings are gone), and retargets the next review to the base. It checks the forge’s mergeability on that target and source SHA. If the review can merge as-is, sync leaves the surviving branches alone. It neither merges nor queues a review.

If a mapped parent was squashed, sync checks that the forge’s merge result reached the base and that the original source matches the local entry. It rebases just the survivors in that case, or if the new target requires a rebase. A new entry without a published review has no mergeability verdict, so sync rebases it before publishing. If the review, source, or merge result cannot be verified, sync stops rather than guessing. A target edit can already have succeeded when this happens. Inspect the review and retry.

A sync that edits that target durably checkpoints the remote retarget in its operation record before it starts any later replay, lint, or publication work, and those later steps get checkpoints of their own. This keeps a completed remote mutation from being hidden inside a later local failure. A survivor rebase or replay is likewise checkpointed as soon as it completes, before sync prints lint or metadata progress. So the rewritten history is already recorded if that output fails, for example when stdout is a closed pipe. One gg sync is still one operation record (one row in gg undo --list), and because the retarget touched the remote, the whole sync refuses local undo. If a rebase is paused, confirm the exact operation_id reported by gg ls --json, then run the argument-free gg continue or gg abort; those commands recover the operation named by the saved marker.

--until still names the entry from before the fetch, not a different entry that inherited its position. Lint skips landed entries. If the retarget requires a rebase, --lint checks the rebased commits again before pushing. Lint that changes files can still amend commits. Later gg ls commands use the confirmed base for this stack without moving your local base branch or checking it out in another worktree. When no parent has landed, the ordinary behind-base threshold and auto-rebase setting still apply.

Before pushing, gg sync normalizes GG-ID and GG-Parent metadata for the stack. It keeps a surviving entry’s existing GG-Parent when it identifies the actual Git parent on the confirmed base. --rebase-if-needed stops if unrelated trailer repairs would rewrite an otherwise unchanged published branch.

After syncing the selected entries, gg sync consumes durable deletion intent created by a successful local gg drop. Each intent is bound to the exact remote-tracking OID known at Drop time; a fresh server tip is never adopted as deletion authority. If the remote branch changed, sync fails with the expected and current OIDs and leaves it intact. If no trusted remote version existed at Drop time, no intent is created and the branch is retained.

Intent is one-shot and independent of the 100-record undo journal. Confirmed deletion or observed remote absence consumes it, while gg undo of the Drop or recreation of the entry cancels it. Partial pruning persists confirmed progress per branch. A deletion the remote refused for that branch (a stale lease, a server hook or a protected branch) applied nothing: sync fails with that error and the entry goes back to pending for the next sync. Any other unsuccessful attempt is settled by reading the remote branch (see below). This also applies to --until: the complete local stack protects every retained or recreated entry. Before deleting, sync asks GitHub/GitLab whether any open PR/MR still targets the branch (for example, a later entry outside the --until range, or one whose base update failed). After persisting the deletion checkpoint, it immediately repeats that provider check before the exact-OID deletion push; the earlier classification is not deletion authority. If either check finds a dependent review, or either check fails, the branch is kept, the intent remains safely pending, and sync prints a warning (also in the JSON warnings). A sync that only deferred deletions changed nothing, so plain gg undo skips it and reverses an earlier record, such as the Drop. Retarget the review, usually with a full gg sync, and sync again. gg clean applies the same check and keeps the stack when it defers a deletion. Remote deletions make the sync operation ineligible for local gg undo. The deletion checkpoint is written in two steps: first the operation record notes possible remote uncertainty, then the config entry moves to deleting. Nothing is sent until both writes succeed. If either write fails, the entry stays pending, the operation is finalized without claiming a remote change, and the next sync or gg clean retries normally.

If a deletion attempt fails any other way (a lost response, a transport error), sync reads the remote branch straight away: gone means the deletion took effect and it is recorded; still at the expected commit means it did not apply (the push is leased on that commit), so the entry goes back to pending and sync fails with “Remote deletion of ‘’ did not apply: the push failed and the branch is still at the authorized commit. It stays queued; rerun to retry.” Nothing changed on the remote, so rerunning is safe. At another commit, someone may have republished the branch after the delete, so the outcome is unknown: sync stops with “Remote mutation outcome is uncertain” and the entry stays in deleting. The next sync (or gg clean) reads the branch again the same way, and stops rather than delete their work while it is still at another commit. Run gg reconcile --dry-run to see what each pending deletion resolves to, or gg reconcile --discard-pending to give up deleting a branch (the remote branch is then left in place).

If the current stack branch has a valid stack shape but uses a different prefix than defaults.branch_username, gg sync continues and warns that stack discovery, listing, and saved PR/MR mappings may be inaccurate. In --json mode, this message is included in sync.warnings.

If an existing mapped PR/MR is attached to the wrong source branch (for example after moving commits into a new stack with gg unstack), providers cannot retarget that source branch in place. gg sync creates a replacement PR/MR with the correct branch, updates the local mapping, comments on the old PR/MR, and closes it. In JSON output that entry uses action "recreated".

When gg sync creates the replacement, it saves the old and new reviews’ identities and how far it has got with the old review. That record is written in the same step that maps the entry to the replacement. If commenting on or closing the old review fails, or gg sync is interrupted, the next gg sync finishes the job before doing anything else. It never creates another replacement. If a comment or close request may have gone through but the response was lost, the next run checks the old review’s comments or state before sending anything again. It refuses to continue if the old review’s source or target branch has changed in the meantime. While that work is unfinished, gg land refuses to land the stack and gg clean keeps it. Run gg sync first.

Replacement requires proof that the old review really belongs to this entry: its source must be the same entry ID, under your username, on the old stack recorded in config, and the old stack must no longer map that entry. Its target does not matter, so amending or dropping entries of the lower stack after gg unstack does not block the replacement. A mapped review whose source branch is anything else, for example a stale or reused mapping or a stack gg no longer records, stops sync before any push, create, comment, close, or mapping change.

You can control this behavior with config:

  • defaults.sync_auto_rebase (sync.auto_rebase): automatically run gg rebase before sync when behind threshold is reached
  • defaults.sync_behind_threshold (sync.behind_threshold): minimum number of commits behind before warning/rebase logic applies (0 disables the check)

Examples

# First publish as drafts
gg sync --draft

# Sync only first two entries
gg sync --until 2

# Refresh PR/MR descriptions after commit message edits
gg sync --update-descriptions

# Also update PR/MR titles to match commit subjects
gg sync --update-title

# Run lint as part of sync
gg sync --lint

# Skip behind-base check once
gg sync --no-rebase-check

# Machine-readable output
# (useful in scripts/agents)
gg sync --json

# Skip pre-push hooks for this sync only
gg sync --no-verify

Target Branch Resolution

When computing the target branch for each PR/MR, gg sync walks backwards through predecessor entries and skips any that are already merged or closed. If all predecessors have been merged, the target falls back to stack.base. This ensures downstream MRs are correctly retargeted after an upstream MR is merged — whether merged via gg land or directly in the provider UI.

Only a review’s source branch decides whether it belongs to the entry. Its target is whatever the stack needs now: when a review targets anything else, sync retargets it to the computed branch and reports it: a “Retargeted” line in human output, a pr_updated event with action retargeted with --jsonl, and "action": "retargeted" on the entry in --json output and the final summary. A retarget wins over updated: an entry that was also pushed or edited still says retargeted, and its pushed field tells you whether the branch was pushed too. That heals the chain after you:

  • drop or fix up a published commit with plain git rebase -i, so the review above it still targets the removed commit’s branch;
  • retarget a PR/MR by hand, even to a branch outside the stack;
  • amend or drop entries in the lower stack after gg unstack.

Sync sends a base, title, or description edit only when the review’s fresh state differs from what the stack needs. A re-sync with nothing to change sends no edits, so it also works on PRs linked into GitHub Stacked PRs, which reject every base edit. Commits added on the forge (“Update branch”, accepted suggestions) are still protected by the leased push; gg sync --force overrides that.

GitHub Stacked PRs (public preview)

For a full GitHub gg sync (without --until), git-gud collects the current stack’s active open and draft PR numbers in bottom-to-top order. When there are at least two resolved PRs and defaults.github.stacks_integration is not off, it can reconcile GitHub’s native Stacked PRs map through the optional official gh stack extension. This does not replace or change git-gud’s local stack metadata, and GitLab sync never uses this integration. Landing a linked stack works differently: see gg land on GitHub native stacks.

Install the extension yourself if you want the native UI:

gh extension install github/gh-stack

git-gud never installs or upgrades it automatically. The minimum supported extension version is 0.1.0.

Eligibility and safe outcomes

The integration is skipped when it is disabled, the sync is partial, fewer than two active PRs are available, or an active PR cannot be resolved. Full syncs create GitHub Stacked PRs when none of the active PRs is already associated, and append only new top PRs when the native active sequence is an exact ordered prefix of git-gud’s sequence. Appending by stack number preserves a merged prefix; git-gud does not relink merged PRs or retarget a PR onto a merged branch.

If the native and local sequences diverge, git-gud performs no mutation and returns a warning. Inspect the GitHub Stacked PRs map, explicitly unstack or repair it with GitHub’s tools, then rerun gg sync. Version one never removes, reorders, unlinks, or recreates GitHub Stacked PRs.

GitHub refuses every base change on a PR linked into GitHub Stacked PRs, so gg sync only edits a review’s base when it actually changes. When a linked PR genuinely needs a new base, for example after a local reorder, sync stops and asks you to run gh stack unstack <stack-number> and retry. PRs queued for merge or with auto-merge enabled stay stacked until you take them out of the queue.

auto silently records a skipped result when the extension is missing or outdated, or the repository does not support the public preview. force uses the same create/append-only safety checks but surfaces those capability states as warnings. Divergence, malformed responses, authentication or network errors, and a failed gh stack link are warnings in both modes. Every native-integration failure is non-fatal to an otherwise successful gg sync.

JSON and JSONL output

Atomic gg sync --json includes a sync.github_stack object for GitHub syncs (and null when the provider is not GitHub or provider detection did not complete). It always contains mode, action, reason, stack_number, pr_numbers, and message:

{
  "version": 1,
  "sync": {
    "stack": "feature",
    "base": "main",
    "github_stack": {
      "mode": "auto",
      "action": "created",
      "reason": null,
      "stack_number": 7,
      "pr_numbers": [41, 42],
      "message": null
    }
  }
}

action is one of created, appended, unchanged, skipped, or warning. Stable reasons include disabled, partial_sync, insufficient_prs, unresolved_prs, missing_extension, outdated_extension, unsupported_repository, diverged, and backend_failed.

gg sync --jsonl emits a line-delimited github_stack event immediately after reconciliation and repeats the same result in the deterministic final summary event. Its status is ok for created, appended, unchanged, and skipped results, and warning for warning results. For example, a divergence event is:

{"version":1,"command":"sync","status":"warning","event":"github_stack","mode":"auto","action":"warning","reason":"diverged","stack_number":null,"pr_numbers":[41,42],"message":"Local pull requests do not match the native stack active sequence"}

PR/MR Body Ownership

When gg sync creates a new PR/MR, the generated description is wrapped in invisible HTML comment markers:

<!-- gg:managed:start -->
(generated content from commit message / template)
<!-- gg:managed:end -->

On subsequent syncs with --update-descriptions (or when sync_update_descriptions is enabled in config), only the content inside the managed block is regenerated. Any text you add above or below the markers on GitHub/GitLab is preserved across syncs.

This means you can safely:

  • Add review checklists above or below the managed block
  • Write reviewer notes that survive re-syncs
  • Check/uncheck task boxes outside the managed section

Content inside the managed block (the generated description) is regenerated on every sync. If your PR template includes a checklist, place persistent checklists outside the markers after creation.

Legacy PRs (created before this feature) have no managed markers. gg sync will skip body updates for these PRs and log a warning, to avoid overwriting manual edits.

Stack navigation comments

If defaults.stack_nav_comments is enabled in gg/config.json under the directory reported by git rev-parse --git-common-dir, every full gg sync (no --until) reconciles a managed comment on each PR/MR in the stack. The comment shows all entries in the stack in bottom-up order, with a 👉 marker on the entry that PR corresponds to — letting reviewers see where they are in the chain and click through to siblings.

The comment is identified by a hidden HTML marker (<!-- gg:stack-nav -->) and never touches comments git-gud didn’t create. Disabling the setting and re-syncing cleans up any previously-posted comments automatically.

Merged or closed PRs are left alone — gg sync never modifies comments on historical PRs.

When running with --json or --jsonl, each entry includes an optional nav_comment_action field (one of "created", "updated", "unchanged", "deleted", "error") when a reconcile decision was made.

Streaming NDJSON (--jsonl)

gg sync --jsonl emits one compact JSON object per line on stdout and flushes after each line. Human/progress output is suppressed on stdout but diagnostics may still appear on stderr. This mode is intended for agents and long-running pipelines that want incremental updates instead of waiting for a final aggregate payload.

Every line is a valid JSON object with at least:

  • version: output schema version (1)
  • command: always "sync"
  • event: event kind (see below)

Event kinds:

EventFieldsEmitted when
startstack, base, total_entriesSync begins
lint_startedtotal_entries, commandsLint begins (only when lint runs; follows start)
lint_entry_startedposition, sha, titleLint begins on a commit
lint_command_doneposition, command, passed, duration_ms, outputOne lint command finished; output (last 8 KB) only on failure
lint_entry_doneposition, sha, passed, amendedLint finished on a commit; amended: true means its SHA changed (sha is the new one)
lint_doneall_passedLint phase finished; on failure sync stops with an error event naming the first failing commit and command, then the summary
entry_startedposition, sha, title, gg_id, branchProcessing begins for a stack entry
push_startedposition, branchA push is about to start
push_doneposition, branch, forcedPush succeeded
push_errorposition, branch, errorPush failed; sync stops because the remote result may be ambiguous
pr_createdposition, pr_number, pr_url, draftNew PR/MR created
pr_create_errorposition, branch, errorPR/MR creation failed; sync stops because the remote result may be ambiguous
pr_commentposition, pr_number, action, errorReplacement notice comment checkpointed (action is created or error)
pr_closedposition, pr_number, errorReplaced PR/MR close attempted
pr_updatedposition, pr_number, actionExisting PR/MR processed. One granular event per edit actually sent (title_updated, description_updated, or retargeted), then always one aggregate event with the publication action (updated or up_to_date). A replaced review (recreated) emits pr_created, pr_comment and pr_closed instead
pr_skipped_closedposition, pr_numberExisting PR/MR is merged/closed and skipped
nav_commentposition, pr_number, action, errorManaged nav comment reconciled (created/updated/unchanged/deleted/error/skip)
github_stackmode, action, reason, stack_number, pr_numbers, messageGitHub Stacked PRs reconciliation completed; status is ok or warning
errormessageFatal error; once sync has started, a summary follows
summarysame shape as --json sync objectSync finished, or stopped on an error (status: "error", error set)

Once sync has started (its provider check passed), the last event is always summary, so consumers can detect completion without reconstructing state. If sync stops on an error, it emits error and then a summary with "status": "error", an error field, and the entries finished so far, and exits 1. Only a failure before sync starts ends with a lone error event: for example not a repository, the gg lock is held, a rebase is in progress, an unknown --until target, failed provider authentication, or repository state written by a newer gg.

For an entry whose review already exists, the aggregate pr_updated event carries the publication action, while the entry in the summary uses retargeted when this sync changed the review’s base (see Target Branch Resolution):

{"version":1,"command":"sync","status":"ok","event":"pr_updated","position":3,"pr_number":103,"action":"retargeted"}
{"version":1,"command":"sync","status":"ok","event":"pr_updated","position":3,"pr_number":103,"action":"updated"}

Example --jsonl output

{"version":1,"command":"sync","event":"start","stack":"my-stack","base":"main","total_entries":2}
{"version":1,"command":"sync","event":"entry_started","position":1,"sha":"abc1234","title":"Add feature","gg_id":"c-abc1234","branch":"user/my-stack--c-abc1234"}
{"version":1,"command":"sync","event":"push_started","position":1,"branch":"user/my-stack--c-abc1234"}
{"version":1,"command":"sync","event":"push_done","position":1,"branch":"user/my-stack--c-abc1234","forced":false}
{"version":1,"command":"sync","event":"pr_created","position":1,"pr_number":42,"pr_url":"https://github.com/org/repo/pull/42","draft":false}
{"version":1,"command":"sync","event":"summary","stack":"my-stack","base":"main","rebased_before_sync":false,"warnings":[],"metadata":{"gg_ids_added":0,"gg_parents_updated":0,"gg_parents_removed":0},"entries":[{"position":1,"sha":"abc1234","title":"Add feature","gg_id":"c-abc1234","branch":"user/my-stack--c-abc1234","action":"created","pr_number":42,"pr_url":"https://github.com/org/repo/pull/42","draft":false,"pushed":true,"error":null}]}

When to use --json vs --jsonl

  • Use --json when you want a single, complete aggregate payload at the end and do not need progress while the command runs.
  • Use --jsonl when you want to stream events as they happen, monitor progress, or pipe the output to a line-oriented consumer. Every line is self-contained.

Example JSON (shape):

{
  "version": 1,
  "sync": {
    "stack": "my-stack",
    "base": "main",
    "rebased_before_sync": false,
    "metadata": {
      "gg_ids_added": 0,
      "gg_parents_updated": 1,
      "gg_parents_removed": 0
    },
    "entries": [
      {
        "position": 1,
        "sha": "abc1234",
        "title": "Add feature",
        "gg_id": "c-abc1234",
        "branch": "user/my-stack--c-abc1234",
        "action": "created",
        "pr_number": 42,
        "pr_url": "https://github.com/org/repo/pull/42",
        "draft": false,
        "pushed": true,
        "error": null
      }
    ]
  }
}

When sync stops on an error

Sync stops at the first entry it cannot publish and exits 1, because the remote result of a failed push or create may be ambiguous. The sync object is still printed: entries finished before the failure keep their actions, the entry that failed has "action": "error" and its own error, and sync.error says why sync stopped. If the failed entry’s review already exists, including one created by this run before a later step failed, the entry carries its pr_number and pr_url; the next gg sync adopts that review rather than creating another. Entries after the failure are not listed. github_stack is null when sync stopped before GitHub stack reconciliation. On success the error key is absent.

{
  "version": 1,
  "sync": {
    "stack": "my-stack",
    "base": "main",
    "rebased_before_sync": false,
    "warnings": [],
    "github_stack": null,
    "metadata": { "gg_ids_added": 0, "gg_parents_updated": 0, "gg_parents_removed": 0 },
    "entries": [
      { "position": 1, "sha": "abc1234", "title": "Add a", "gg_id": "c-abc1234", "branch": "user/my-stack--c-abc1234", "action": "created", "pr_number": 41, "pr_url": "https://github.com/org/repo/pull/41", "draft": false, "pushed": true, "error": null },
      { "position": 2, "sha": "def5678", "title": "Add b", "gg_id": "c-def5678", "branch": "user/my-stack--c-def5678", "action": "error", "pr_number": null, "pr_url": null, "draft": false, "pushed": true, "error": "Push failed for branch user/my-stack--c-def5678" }
    ],
    "error": "Push failed for branch user/my-stack--c-def5678"
  }
}

Only a failure before sync starts prints the bare {"version": 1, "error": "..."} object without sync.

Navigation (mv, first, last, prev, next)

These commands move HEAD within your stack without manual rebase gymnastics.

gg mv <TARGET>

Move to a specific entry by:

  • Position (1-indexed)
  • GG-ID (c-...)
  • Commit SHA
gg mv 1
gg mv c-abc1234
gg mv a1b2c3d

Relative navigation

gg first   # first entry
gg last    # stack head
gg prev    # previous entry
gg next    # next entry

gg sc

Squash local changes into the current stack commit.

gg sc [OPTIONS]

Options

  • -a, --all: Include staged and unstaged changes
  • --staged-only: Include staged changes only and ignore defaults.unstaged_action. Unstaged and untracked files are never staged or stashed. Conflicts with --all. A mid-stack amend refuses before mutation when tracked changes are unstaged or any untracked files are present, since either can prevent rebasing descendants safely.
  • -f, --force (alias --ignore-immutable): Override the immutability guard. By default gg sc refuses to amend a commit whose PR is merged or which is already reachable from origin/<base>. See Core concepts · Immutable commits.

When unstaged changes are present, behavior is controlled by defaults.unstaged_action in .git/gg/config.json:

  • ask (default): prompt to stage all, stash, continue, or abort
  • add: auto-stage all changes (git add -A) and continue
  • stash: auto-stash and continue
  • continue: continue without including unstaged changes
  • abort: fail immediately

Examples

# Standard amend-like flow
git add .
gg sc

# Include unstaged changes too
gg sc --all

# Native-client flow: amend only the prepared index
gg sc --staged-only

gg absorb

Automatically distribute staged changes to the most appropriate commits in your stack.

gg absorb [OPTIONS]

Options

  • --dry-run: Preview actions without changing commits
  • -a, --and-rebase: Rebase automatically after creating fixups
  • -w, --whole-file: Match and absorb by whole file rather than hunks
  • --one-fixup-per-commit: At most one fixup per commit
  • -n, --no-limit: Search all commits in the stack (not just last 10)
  • -s, --squash: Squash directly instead of creating fixup! commits
  • -f, --force (alias --ignore-immutable): Override the immutability guard. By default, gg absorb refuses to run if any commit in the stack is merged or reachable from origin/<base> — because it cannot tell ahead of time whether git-absorb will target those commits. --dry-run skips the guard so you can preview safely. See Core concepts · Immutable commits.

Examples

# Preview before applying
gg absorb --dry-run

# Absorb and finish with rebase
gg absorb --and-rebase

# Heavy refactor across many files
gg absorb --whole-file --no-limit

gg drop

Remove one or more commits from the stack.

For a published entry, running gg drop also authorizes a later gg sync to delete that entry’s remote branch. The Drop itself remains local: it records deferred deletion intent, and Sync performs the remote deletion.

Alias: gg abandon

gg drop <TARGET>... [OPTIONS]

Arguments

  • <TARGET>...: One or more commits to drop. Each target can be:
    • Position (1-indexed): 1, 3
    • Short SHA: abc1234
    • GG-ID: c-abc1234

Options

  • -f, --force (alias --ignore-immutable): Skip the confirmation prompt and override the immutability guard. gg drop refuses by default to drop or rewrite commits whose PR is merged or which are already reachable from origin/<base>; this flag bypasses both safeties. See Core concepts · Immutable commits.
  • --json: Output result as JSON

Behavior

  1. Validates the working directory is clean
  2. Resolves each target to a commit in the stack
  3. Shows which commits will be dropped and asks for confirmation (unless --force)
  4. Performs a git rebase -i that omits the dropped commits
  5. Cleans up local per-commit branches for dropped commits
  6. Records deferred remote-branch deletion authority for published entries
  7. Prints a summary of what was dropped

At least one commit must remain in the stack after dropping.

Deferred deletion authority is bound to the exact remote-tracking OID known when Drop runs. If no trusted remote version is known, Drop records no authority and Sync keeps the remote branch. Sync also refuses deletion if the live branch has moved to another OID; it never adopts that newer version as authority.

gg undo of the Drop restores the local entry and cancels any unconsumed deletion intent. Undoing that Undo (redoing the Drop) restores the exact saved intent, including its OID and lifecycle state. Intent already consumed by a completed Sync is never recreated. An intent left in deleting after an uncertain remote outcome stays uncertain across undo/redo and is not retried automatically.

When Sync reports a changed branch or uncertain deletion, inspect the named remote ref and .git/gg/config.json before reconciling manually. GG cannot determine whether an ambiguous server response applied the deletion, and it will not authorize a retry or a newer branch version on your behalf.

Examples

# Drop the second commit in the stack
gg drop 2

# Drop multiple commits at once
gg drop 1 3

# Drop by GG-ID, skip confirmation
gg drop c-abc1234 --force

# Drop with JSON output
gg drop 2 --force --json

# Use the 'abandon' alias (inspired by jj)
gg abandon 2

JSON Output

{
  "version": 1,
  "drop": {
    "dropped": [
      {"position": 2, "sha": "abc1234", "title": "Fix typo"}
    ],
    "remaining": 3
  }
}

Edge Cases

  • Dropping all commits produces an error — at least one commit must remain
  • Invalid position shows the valid range
  • Rebase conflicts are handled the same as gg reorder — resolve with gg continue or gg abort

gg reorder / gg arrange

Reorder and/or drop commits in your stack.

gg arrange is an alias for gg reorder — they share the same implementation.

gg reorder [OPTIONS]
gg arrange [OPTIONS]

Options

  • -o, --order <ORDER>: New order as positions/SHAs ("3,1,2" or "3 1 2")
  • --no-tui: Disable the interactive TUI and use a text editor instead
  • -f, --force (alias --ignore-immutable): Override the immutability guard. Reordering or dropping a commit that is already merged or reachable from origin/<base> is refused by default. See Core concepts · Immutable commits.

Interactive TUI

When run without --order, opens an interactive TUI where you can visually rearrange and drop commits:

┌─ Arrange Stack ──────────────────────────────────┐
│  1  abc1234  feat: add login page                │
│▸ 2  def5678  fix: handle empty input     ↕       │
│  [DROP] 3  ghi9012  refactor: extract validator   │
│  4  jkl3456  test: add integration tests          │
└──────────────────────────────────────────────────┘
 j/k:navigate  J/K:move commit  d:drop/undrop  Enter/s:confirm  q/Esc:cancel

Keyboard shortcuts

KeyAction
j / ↓Move cursor down
k / ↑Move cursor up
J / Shift+↓Move commit down
K / Shift+↑Move commit up
d / DeleteToggle drop mark on commit
Enter / sConfirm new order
q / EscCancel (no changes)

Position 1 is the bottom of the stack (closest to the base branch).

Dropped commits appear in red with strikethrough and a [DROP] prefix. You can still move dropped commits (e.g., to undrop them later). At least one commit must remain — you cannot drop all commits.

The TUI requires a TTY. In non-interactive environments (pipes, CI), gg reorder falls back to the text editor automatically. Use --no-tui to force the editor fallback.

Editor Fallback

When using the editor fallback (--no-tui or non-TTY), you can:

  • Reorder commits by rearranging lines
  • Drop commits by deleting their lines

At least one commit must remain.

Examples

# Interactive reorder/drop with TUI
gg reorder
gg arrange

# Explicit reorder by position (no dropping)
gg reorder --order "3,1,2"

# Use text editor instead of TUI
gg arrange --no-tui

gg split

Split a commit in the stack into two commits. The selected hunks become a new commit inserted before the original in the stack, while the remaining changes stay in the original commit.

gg split [OPTIONS] [FILES...]

Options

  • -c, --commit <TARGET>: Target commit — position (1-indexed), short SHA, or GG-ID. Defaults to the current commit (HEAD).
  • -m, --message <MESSAGE>: Commit message for the new (first) commit. Skips the editor prompt.
  • --no-edit: Keep the original message for the remainder commit without prompting.
  • --no-tui: Disable TUI, use sequential prompt instead (legacy git add -p style).
  • --describe: Describe the target and its textual hunks as protocol v1 JSON. Requires --json and cannot be combined with interactive selection or file arguments.
  • --plan-json <PATH>: Apply a protocol v1 plan read from PATH. Requires --json and cannot be combined with --describe, interactive selection, or file arguments.
  • --json: Emit machine-readable output for structured Describe or Apply. Requires either --describe or --plan-json; ordinary interactive and file-based Split do not have a structured response.
  • -f, --force (alias --ignore-immutable): Override the immutability guard for interactive and file-based Split. Structured Describe/Apply always uses the guard without an override. Splitting a merged or base-ancestor commit is refused by default. See Core concepts · Immutable commits.
  • FILES...: Files to include in the new commit. When provided, all hunks from those files are auto-selected (skips the interactive picker).

How It Works

When you split commit K into two:

  1. New commit (K’) — Contains only the selected hunks. Inserted before K in the stack. Gets a new GG-ID.
  2. Remainder (K’’) — Contains the remaining hunks. Stays in K’s original position. Keeps the original GG-ID (preserving PR association).

All descendant commits are automatically rebased onto the remainder.

BEFORE                    AFTER
  4: "Fix tests"            5: "Fix tests"       (rebased)
  3: "Add auth+logging"     4: "Add logging"      ← remainder (keeps GG-ID)
  2: "Setup DB"             3: "Add auth"         ← NEW commit (selected changes)
  1: "Init project"         2: "Setup DB"
                             1: "Init project"

Interactive Hunk Selection

Running gg split without file arguments opens the interactive hunk picker:

# Split the current commit — opens hunk selector
gg split

# Split a specific commit in the stack
gg split -c 3

TUI Mode (Default)

When run with a TTY, gg split opens a two-panel TUI for hunk selection:

┌── Files (1/3 width) ──┬── Diff (2/3 width) ──────────────┐
│ [✓] src/auth.rs (3)   │ @@ -10,6 +10,12 @@               │
│ [ ] src/logging.rs (1)│ +  // Validate token              │
│ [~] src/tests.rs (2)  │ +  if token.is_empty() {          │
│                        │ +      return false;               │
│                        │ +  }                               │
├────────────────────────┴────────────────────────────────────┤
│ 5/12 hunks selected │ [Space] toggle · [Tab] switch panel │
└─────────────────────────────────────────────────────────────┘

TUI Keyboard Shortcuts

KeyIn File PanelIn Diff Panel
↑/↓ or j/kNavigate filesNavigate hunks
SpaceToggle all hunks for fileToggle current hunk
aSelect all hunks (all files)Select all hunks (this file)
nDeselect all hunks (all files)Deselect all hunks (this file)
s—Split current hunk into sub-hunks
Tab / ← / →Switch to diff panelSwitch to file panel
EnterEnter commit messageEnter commit message
q / EscAbort (cancel split)Abort (cancel split)

Inline Commit Message

After pressing Enter to confirm your hunk selection, an inline text input appears at the bottom of the TUI for the commit message. It’s pre-filled with Split from: <original commit title>.

KeyAction
EnterConfirm message and create the split
EscGo back to hunk selection
← / →Move cursor
Home / EndJump to beginning/end
Backspace / DeleteDelete characters
Ctrl+A / Ctrl+EJump to beginning/end (emacs-style)
Ctrl+UClear from cursor to beginning
Ctrl+KClear from cursor to end

After confirming the new commit message, a second inline input appears for the remainder commit message (pre-filled with the original commit’s message). This replaces the external editor for both messages, keeping the entire split workflow inside the TUI.

KeyAction
EnterConfirm remainder message and complete the split
EscGo back to the new commit message input

The -m flag still works and bypasses the TUI input for the new commit. The --no-edit flag skips the remainder message input entirely, keeping the original message as-is.

File Panel Indicators

  • [✓] — All hunks selected (green)
  • [~] — Some hunks selected (yellow)
  • [ ] — No hunks selected

Sequential Prompt Mode (--no-tui)

Use --no-tui to fall back to the legacy git add -p style sequential prompt:

gg split --no-tui

This mode is automatically used when no TTY is available (e.g., in CI pipelines or when piping).

For each hunk, you’ll see the diff with colored output and a prompt:

--- a/src/auth.rs
+++ b/src/auth.rs
@@ -10,6 +10,12 @@ fn authenticate(user: &str) -> bool {
+    // Validate token
+    if token.is_empty() {
+        return false;
+    }

Include this hunk? [y]es/[n]o/[a]ll file/[d]one file/[s]plit/[q]uit/?help:

Sequential Mode Actions

KeyActionDescription
yYesInclude this hunk in the new commit
nNoSkip this hunk (stays in remainder)
aAll fileInclude all remaining hunks from this file
dDone fileSkip all remaining hunks from this file
sSplitSplit this hunk into smaller hunks
qQuitStop; all remaining hunks stay in remainder
?HelpShow this help

File-Based Splitting

When file arguments are provided, all hunks from those files are auto-selected without opening the interactive picker:

# Move auth files to a new commit before the current one
gg split -m "Add authentication" src/auth.rs src/auth_test.rs

# Split a specific commit with explicit files
gg split -c 3 src/config.rs

# Non-interactive with both messages
gg split -c 2 -m "Extract helpers" --no-edit helpers.rs utils.rs

# Split by GG-ID
gg split -c c-abc1234 src/config.rs

Hunk Splitting

If a hunk contains multiple logical changes separated by unchanged lines, pressing s will break it into smaller hunks. You can then select each sub-hunk individually. If the hunk is already atomic (contiguous changes), you’ll see “This hunk cannot be split further.”

Structured Clients

Native clients that provide their own hunk-selection UI can use a versioned, two-step protocol. Ordinary terminal use should keep the default TUI.

First, describe the current target without changing refs, requiring a clean worktree, or creating an operation record:

gg split --describe --commit c-abc1234 --json > split-description.json

The response contains the exact target, an opaque plan_token, selectable textual hunks, non_textual_files, and default messages. Copy target and plan_token unchanged, choose at least one returned hunk ID while leaving some textual, non-textual, or metadata change for the remainder, and supply both non-empty messages:

jq '{
  version,
  plan_token,
  target,
  selected_hunk_ids: [.hunks[0].id],
  first_message: "Extract validation",
  remainder_message: "Finish authentication"
}' split-description.json > split-plan.json

gg split --plan-json split-plan.json --json > split-result.json

The remainder must contain at least one change. It can be an unselected textual hunk, a file listed in non_textual_files, or a regular-file mode change such as an executable-bit update. Non-textual files and metadata are not selectable in protocol v1 and always remain in the remainder commit. Treat hunk IDs, plan tokens, GG-IDs, and operation IDs as opaque values; do not parse, construct, or remap them.

Apply re-resolves the target, checks its GG-ID/SHA/tree and the current ordered hunks, and rejects stale plans before moving refs or adding an operation-log record. After any stale-plan error, run Describe again and ask the user to review a new selection. Describe and Apply both refuse immutable targets, and structured Apply has no force field or force override.

Structured failures are written to stdout as JSON:

{
  "version": 1,
  "error": "stale split plan: target identity changed"
}

Once rewriting starts, a descendant rebase conflict returns the same JSON error envelope but leaves the operation paused. Resolve and stage the conflict, then run gg continue, or run gg abort to cancel it.

A successful Apply returns an operation_id. Use that exact ID to undo this split rather than assuming it is still the most recent operation:

operation_id=$(jq -r '.operation_id' split-result.json)
gg undo "$operation_id" --json

Edge Cases

  • All textual hunks selected — Structured Apply accepts the plan only when a non-textual file or regular-file mode change remains for the remainder.
  • No changes selected — Error in every mode.
  • Dirty working directory — Interactive Split and structured Apply error. Describe remains read-only and is allowed.
  • Merge conflicts during rebase — Resolve and stage the conflict, then run gg continue; use gg abort to cancel the paused operation.

gg unstack

Split the current stack into two independent stacks.

gg unstack [--target <TARGET>] [--name <STACK_NAME>] [--no-tui] [-f] [--json] [-w | --keep-current]

The selected entry becomes the root of a new stack, and all entries above it move with it. Entries below the selected point remain in the original stack.

The command is called unstack because gg split already means splitting one commit into two commits.

Examples

# Pick the split point interactively
gg unstack

# Move entries 3 and above into a new stack named auth-followup
gg unstack --target 3 --name auth-followup --no-tui

# Use a GG-ID or SHA prefix instead of a position
gg unstack --target c-abc1234 --name auth-followup --no-tui

# Machine-readable output
gg unstack --target 3 --json --no-tui

# Put the new upper stack in a managed worktree
gg unstack --target 3 --name upper-auth --wt

# Keep this worktree on the lower stack without creating another worktree
gg unstack --target 3 --name upper-auth --keep-current --json

Behavior

Given a stack:

1  Add schema
2  Add API
3  Add UI
4  Add tests

Running gg unstack --target 3 --name ui-work leaves:

original stack: 1 Add schema, 2 Add API
new stack:      1 Add UI, 2 Add tests

GG-ID trailers are preserved. GG-Parent trailers are rewritten so the first entry in each resulting stack has no parent and later entries point at the previous entry in that same stack.

Local PR/MR mappings in .git/gg/config.json move with their entries. Stale local entry branches under the old stack name are removed for moved entries. If moved entries had review mappings, run gg sync afterwards to recreate or update review branches for the new stack.

Placement depends on the selected mode:

ModeInvoking worktree after successAdditional upper worktreeJSON current_stack
defaultupper stacknot creatednew upper stack name
--worktree / --wtlower stackcreated or reusedoriginal lower stack name
--keep-currentlower stacknot createdoriginal lower stack name

--keep-current is intended for native clients that must keep using the invoking worktree but do not want another worktree. It conflicts with --worktree/--wt.

With --json, unstack.current_stack always reports the stack left in the invoking worktree. unstack.worktree_path is present only when --worktree created or reused the upper managed worktree.

Options

  • --target <TARGET>: first entry for the new stack. Accepts a 1-indexed position, GG-ID, or SHA prefix.
  • --name <STACK_NAME>: name for the new stack. If omitted, gg generates a unique name such as <old-stack>-2.
  • --no-tui: disable the interactive picker. Use this with --target in scripts and tests.
  • -f, --force: bypass the immutability guard for merged/base commits.
  • --json: emit structured JSON.
  • -w, --worktree: create or reuse a managed worktree for the new stack (--wt also works).
  • --keep-current: leave the invoking worktree on the lower stack without creating an upper worktree. Conflicts with --worktree/--wt.

Position 1 is rejected because it would leave the original stack empty. The last position is allowed and creates a one-entry new stack.

gg rebase

Rebase the current stack onto an updated branch.

gg rebase [TARGET]
  • If TARGET is omitted, git-gud uses the stack base branch.

The local base branch is fast-forwarded to origin/<base>. If it is checked out in a worktree, that checkout’s index and files are updated together. If the checkout has uncommitted changes, git-gud warns with its path and skips the local base update. The stack still rebases onto origin/<base>. This also applies when gg sync auto-rebases.

Options

  • -f, --force (alias --ignore-immutable): Override the immutability guard. Rebase rewrites the parent of every commit in the stack; merged commits (including squash-merged PRs) and commits already reachable from origin/<base> are silently skipped — git rebase drops them automatically via patch-id matching, so --force is not required for these. See Core concepts · Immutable commits.

Examples

# Rebase onto configured base
gg rebase

# Rebase onto specific branch
gg rebase main

gg land

Merge approved PRs/MRs from the bottom of your stack upward.

gg land [OPTIONS]

Options

  • -a, --all: Land all approved entries in sequence
  • --auto-merge: (GitLab only) Request auto-merge instead of immediate merge
  • --no-squash: Disable squash merge (squash is default). On GitLab, gg also turns off the MR’s own squash setting before merging or queueing it, and refuses up front when the project requires squashing
  • --no-rebase: Don’t rebase and force-push the remaining stack branches after each merge. Avoids re-triggering CI on every remaining PR/MR; intended for --no-squash, where original commit SHAs stay reachable from the base branch
  • --rebase-if-needed: After each merge, rebase the remaining branches only when needed (see Rebasing remaining branches). Conflicts with --no-rebase
  • -w, --wait: Wait for CI and approvals before merging
  • -u, --until <UNTIL>: Land up to a target entry (position, GG-ID, SHA)
  • -c, --clean: Clean stack automatically after landing all. Auto-clean (--clean, land_auto_clean or the prompt) runs only after an error-free landing
  • --no-clean: Disable auto-clean for this run
  • --admin: (GitHub only) Use admin privileges to bypass branch protection requirements (see Admin Override below)
  • --json: Emit machine-readable JSON output (no human logs)
  • --jsonl: Emit flushed NDJSON events as landing and polling progress; conflicts with --json

A plain gg land (one PR, without --all, --wait, --json or --jsonl) asks “Merge PR #N?” before merging. Without a terminal to answer it (a script, CI, an agent), it merges nothing and exits with an error; pass --json (or --all) to land without the prompt.

For non-wait landing, gg refreshes approval for each entry immediately before its final queue or merge request. If approval was dismissed after the initial stack refresh, that entry is refused without starting the landing mutation. Only the explicit GitHub admin override bypasses this check; GitLab still requires approval when --admin is supplied.

Wait-mode direct merges use the same final approval refresh. This includes each entry selected by --all or --until, so a missing or dismissed approval stops the command before it creates landing recovery state or sends the merge request.

GitLab auto-merge queueing also refreshes approval in wait mode, immediately before creating recovery state and asking GitLab to merge when the pipeline succeeds. GitLab admin settings do not bypass this check.

The initial GitLab merge-train queue request has the same boundary: after the final MR or pipeline-handoff validation, gg refreshes approval before creating queue recovery state or sending the queue request. A refusal leaves neither an initial queue attempt nor landing recovery state, even with --admin.

If a push cancels auto-merge while --wait is tracking the train, the requeue has its own authorization and recovery boundary. gg re-reads and validates the MR, requires its current head SHA, and refreshes approval before recording or sending the requeue. GitLab --admin does not bypass this check.

For every GitLab landing with --no-squash, including --wait, gg also refreshes approval inside the durable squash segment immediately before changing the MR’s setting. This happens after the final identity and policy checks. If the setting is already disabled, gg skips both approval lookup and the PUT. If approval was dismissed or cannot be read, gg leaves the setting unchanged, records the segment as a committed untouched no-op, clears its attempt marker, and stops before any later landing mutation.

In GitLab merge-train wait mode, gg refreshes approval after validating that a pipeline is still missing and immediately before asking GitLab to create it. If approval was dismissed while waiting, gg sends no pipeline request and records the prepared operation as a proven no-op.

Landing only the reviewed commit

When gg decides a PR/MR is ready to land, it records exactly what it checked: the PR/MR number, source branch, head commit, and target branch. Right before each merge, merge-train queue, requeue, or auto-merge request, it reads the PR/MR again and compares. If anything changed, gg refuses to land, so a push after approval is never merged unreviewed. Only after that check does it confirm approval for that exact commit.

The request also carries the expected head commit, so the forge itself rejects it if the branch moves in the last moment: GitHub merges use --match-head-commit, and GitLab merge, merge-train, and auto-merge requests pass sha. If the forge reports no head commit, gg refuses to land.

Resuming after an interrupted land

Before each remote request (a direct merge, a GitLab merge-train queue or requeue, an auto-merge queue, a post-merge retarget or push) gg saves a small attempt marker in .git/gg/config.json. A marker that is still there when gg land starts means an earlier run did not see how its request ended: the process was killed, the network dropped, or a later step failed.

gg land does not compare your local branches with a snapshot to decide what happened. It asks GitHub or GitLab, identifying the review by its number and, when the marker recorded one, by its head commit:

MarkerThe provider showsResult
Direct mergemerged at the recorded head (or the operation already recorded the merge)Completed: the entry is finished as already merged
Direct mergeopen at the recorded head and not queuedNot applied: marker removed, gg merges normally
Direct mergeopen at another head, closed, or merged at another headNot applied: the old attempt is moot (for example you amended and synced)
Direct mergemerged at the recorded head into another target, or queued to mergeUndetermined
Merge-train queue or requeuemerged, on the train, or set to auto-merge, at the recorded headCompleted
Merge-train queue or requeueopen and not queued, or open at another head, or closedNot applied
Auto-merge queuemerged, or open with auto-merge set, at the recorded headCompleted
Auto-merge queueanything elseNot applied
Post-merge retargetthe review already targets the new baseCompleted
Post-merge retargetany other baseNot applied: gg retargets it again
Post-merge pushthe remote branch holds the pushed commitCompleted
Post-merge pushanything elseNot applied: gg pushes again, with the branch’s pre-rebase commit as the lease
Local downstream rebasethe branch is still at its pre-rebase commitNot applied: gg rebases it again
Local downstream rebasethe branch moved and no rebase of it is in progressCompleted
Completed local rebasethe branch was rewritten since (for example amended and synced)dropped with its push; gg works from the branch as it is now
Merge-train queue or requeuean idle car (still waiting for its pipeline) on the trainCompleted
GitLab pipeline creationa head pipeline exists at the recorded headCompleted: kept as the pipeline hand-off
GitLab pipeline creationthe MR is at the recorded head with no pipelineNot applied
GitLab squash updatethe MR’s squash setting is offCompleted: kept as the squash hand-off
GitLab squash updatesquash is still onNot applied: turning it off again is harmless
Anythe provider or remote cannot be read, the MR moved to another head (pipeline), or a rebase is still in progressUndetermined

A marker whose operation record proves the request was never sent is removed without asking the provider. Markers written by v0.10.11 resolve the same way; when they lack the head commit, the review number alone identifies them.

For a local rebase gg looks only at the rewritten branch’s tip and at whether a rebase of that branch is still in progress (in this worktree, or in another linked worktree that is rebasing the same branch). Moving an unrelated branch, amending a commit, or a commit added to the PR/MR on the forge (“Update branch”, an accepted suggestion) does not block recovery. When the forge head differs from your local entry branch, gg land prints a note on stderr and lands the forge head, which is the one that was reviewed and approved.

Undetermined keeps the marker and stops gg land for that stack only. Other stacks still land. The error lists each pending marker and ends with:

Run `gg reconcile --dry-run` to inspect, or `gg reconcile --discard-pending` to abandon them.

A resumed gg land without --all finishes the interrupted entry and stops, exactly as the interrupted run would have.

After a merge: retargets, rebases, and pushes

Once a PR/MR merges, gg records the merge and finalizes it before it prints anything or touches the rest of the stack. Each follow-up step then runs and is recorded on its own: retargeting each remaining active PR/MR to the base branch, then rebasing and force-pushing each remaining active review branch with an exact lease. Reviews observed merged or closed are skipped by all three steps. gg refuses to rebase the remaining branches while tracked files have uncommitted changes, staged or not, and never overwrites them when it restores your checkout; commit or stash them, then rerun gg land to finish the rebases. Before each request, gg saves that it is about to happen. After a success, it records exactly what changed before it moves on or prints the next line. gg undo never reverses these records, not even a local rebase step.

A failed retarget or push is reported as a gg land error, not as a warning followed by success. Before retargeting, gg saves the review’s source branch, its current base and the intended base, then re-reads the review immediately before the update and requires the same review number, an open state, source and current base. A mismatch sends no retarget. A draft review is retargeted like any other and stays a draft: retargeting is not merging, and gg land still skips the draft when it reaches it. The next gg land resolves any pending retarget, push, or local rebase from the provider and the branches it rewrote, as described in Resuming after an interrupted land.

When a remaining entry has no local branch (for example in a fresh clone), gg creates it from origin/<branch> before rebasing it. An existing local branch is always used as it is. If neither exists, gg land stops and names the branch; run git fetch origin or gg sync, then rerun it.

Reviews at the bottom of the stack that were merged on the forge, outside gg, are completed the same way before gg lands the next one, with or without --clean: their downstream reviews are retargeted and rebased first, so the next merge goes into the base branch rather than into the merged predecessor’s branch.

Direct merges, retargets, and pushes change no local branch. If HEAD, the stack branch, or one of its entry branches moves while a direct merge is in flight, gg stops before completing that review; the next gg land resolves the merge from the provider and finishes it.

Remote entry branches after landing

Each merged entry’s remote branch is queued for deletion at the merged commit, with or without --clean, even when no local entry branch exists. When the whole stack lands and --clean cleanup runs, gg drains the queue right away; otherwise the next gg clean deletes the branches.

The whole stack does not have to land in one run. An entry an earlier gg land merged counts as landed when the commit it merged is still the one in your local stack, so gg land --all --clean also cleans up after you landed the bottom of the stack with plain gg land runs, after a rerun following a rejected merge of the second entry, or after one merge-train run per MR. An entry that land rebased before merging it (the lower entries of a multi-entry run, such as #102 when #101 and #102 merged and #103’s merge was rejected) is not counted yet: the rerun lands the rest, keeps the stack and reports cleaned: false, and gg clean finishes the cleanup. When the stack is already empty and only its queued deletions are left (for example after a deferred deletion), gg land --clean drains them and removes the stack instead of printing “Stack is empty. Nothing to land.” A commit you added to the stack with plain git and never landed still keeps the stack: gg does not clean it up. A branch is kept while an open review from outside the stack still targets it (--clean then warns, reports cleaned: false and keeps its exit code), and a branch that moved since the merge is never deleted. See gg clean for the deferred and blocked outcomes and for deleting branches older versions left behind.

Landing request outcomes

Every landing request (a direct merge, a GitLab auto-merge queue, or a merge-train queue or requeue) has two results: what the provider answered, and whether gg durably finalized the Land operation afterwards. gg reports both, so neither can hide the other, and it never prints a success result before the operation is durable:

  • Provider succeeded, checkpoint failed: the command fails with a durability-checkpoint error that says the request succeeded remotely. It names the operation ID and the recovery authority (the saved attempt marker, or for a direct merge the Land operation record). Do not resend the request.
  • Provider rejected the request: an explicit refusal from GitHub or GitLab (for example GraphQL: Required status check "ci" is expected, an HTTP 4xx such as 422 Unprocessable Entity, or Pull request is not mergeable) proves nothing was applied. The entry is reported as an error that says the request “was rejected by the provider”, gg removes the attempt marker, and it is safe to fix the cause (wait for checks, amend and gg sync, get the approval) and run gg land again.
  • Provider failed otherwise, checkpoint succeeded: a killed gh/glab, a network or TLS error, an HTTP 5xx, or output gg does not recognise leaves the outcome unknown, so gg reads the PR/MR once more. If it shows the merge or queue took effect, gg carries on as if the request had succeeded. If it shows nothing happened, gg removes the attempt marker and reports the error; it is safe to rerun gg land. Only when that read also fails or is contradictory does the marker stay, and the error names gg reconcile.
  • Both failed: the command fails with a remote-uncertainty error that carries both the provider error and the checkpoint error.

For a checkpoint failure, inspect the review in GitHub or GitLab and the named operation in .git/gg/operations/ before rerunning gg land.

Examples

# Land one approved entry
gg land

# Land complete stack, waiting for readiness
gg land --all --wait

# Land part of stack
gg land --until 2

# GitLab auto-merge queue
gg land --all --auto-merge

# Land with merge commits; rebase remaining branches only when needed
gg land --all --wait --no-squash --rebase-if-needed

# JSON output for automation
gg land --all --json

# Stream landing progress and wait heartbeats
gg land --all --wait --jsonl

# Bypass approval requirements (GitHub admin)
gg land --admin

# Land full stack with admin override
gg land --all --wait --admin

Admin Override

The --admin flag (or land_admin config default) passes --admin to gh pr merge, which uses GitHub’s API-level admin merge. This bypasses all branch protection rules the merging user has permission to override, which may include both review approvals and required status checks depending on your repository settings.

Use --wait --admin if you want to wait for CI to pass before merging while still bypassing approval requirements. Without --wait, no client-side CI validation is performed.

On GitLab, --admin is a no-op — glab mr merge has no equivalent flag. A warning is printed and the merge proceeds normally.

A warning (⚠ Merging with admin override) is printed before each admin-elevated merge.

Downstream MR Retargeting

After landing an entry, gg land automatically retargets active downstream reviews so they no longer point at the now-merged intermediate branch:

  • Single entry (gg land): retargets the immediate next MR to stack.base.
  • All entries (gg land --all): retargets all remaining MRs to stack.base as each entry is landed.

Downstream reviews observed as merged or closed at command entry are left untouched by retargeting; the scanner still handles those terminal states normally. This applies to both GitHub PRs and GitLab MRs. No manual retargeting in the provider UI is needed for active downstream reviews after landing.

In a GitHub native stack GitHub retargets and restacks the downstream PRs itself, so gg skips this step and the rebase below.

Rebasing remaining branches

When you land several entries (--all or --until), gg land by default rebases every remaining active review branch onto the updated base and force-pushes it after each merge; reviews already observed as merged or closed at command entry are skipped. That keeps squash merges working, but every force-push re-runs CI on every remaining active PR/MR.

With --rebase-if-needed, gg checks two things after each merge and skips the rebase when both hold:

  1. The landed commit itself is reachable from the freshly fetched origin/<base>, so it landed through a merge commit rather than as a squashed or rebased copy.
  2. The forge reports that the next PR/MR, already retargeted to the base, can merge as-is. On GitHub that means mergeable is not CONFLICTING and mergeStateStatus is not DIRTY or BEHIND. On GitLab it means no conflicts and a detailed_merge_status other than conflict or need_rebase.

Forges compute mergeability in the background after a retarget, so gg polls for up to a minute. If the answer is still unknown, or either check fails, gg rebases exactly as it does by default. Only the next entry is checked: the entries above it target its branch, and that branch stays untouched when it isn’t rebased.

--no-rebase skips the rebase unconditionally. Prefer --rebase-if-needed unless you know the base branch keeps original commits.

GitHub native stacks

With GitHub stacks integration on (defaults.github.stacks_integration is auto, the default, or force), gg sync can link a stack’s PRs into a GitHub native stack. GitHub then refuses gh pr merge and any base change on those PRs, and after a merge it retargets the next PR to the base branch and rebases (restacks) the PRs above it itself. Before it lands anything, gg land asks GitHub once whether the stack’s first open PR is in a native stack, and if it is:

  • Each PR merges through GitHub’s asynchronous merge endpoint, still bound to the head gg validated and after the same approval and base checks. gg waits for GitHub to finish the merge (up to about a minute and a half). If GitHub is still working on it, gg land stops with “GitHub is still merging PR #N”; rerun it and gg follows the request GitHub already holds instead of starting a second merge. If the base branch uses a merge queue and GitHub only adds the PR to the queue, gg does not count it as landed (the queue may still reject it): gg land stops with “GitHub added PR #N to its merge queue”, keeps the PR in the stack, and a rerun after it merges completes it.
  • gg does not retarget, rebase or force-push the remaining PRs; that is GitHub’s restack. Right before it lands a PR, gg waits (up to about a minute) for GitHub to have retargeted that PR to the base branch, so it only ever waits for a PR this run lands: --until and a plain gg land never wait for the PRs above. If GitHub has not retargeted it by then, gg land stops with an error naming the PR and changes nothing on it; entries merged earlier are already recorded, so rerun gg land later.
  • --rebase-if-needed and --no-rebase have nothing to do here. Cleanup (--clean, queued branch deletions) works as for any other stack.
# Land a whole native stack and clean up
gg land --all --clean

To keep the classic flow (gg retargets and rebases the remaining PRs), set defaults.github.stacks_integration to off and do not link the PRs into a native stack.

Merge Trains (GitLab)

When merge trains are enabled on the target branch, gg land adds MRs to the merge train instead of merging directly. It uses GitLab’s auto-merge: if the MR pipeline is still pending or running, GitLab marks the MR “set to be added to the merge train” and adds it once the pipeline passes. You don’t have to wait for CI before queueing, and the MR still joins the train if gg exits. The squash setting (--no-squash to disable) is sent with the request.

After a preceding MR merges, GitLab can retarget the next MR without starting a new pipeline. With --wait, if GitLab reports that the next MR needs CI and has no head pipeline, gg starts the MR pipeline before requesting auto-merge. An existing pipeline is left alone.

Before processing a GitLab stack, gg land reads the project’s merge-train setting and stops without mutating the remote if that setting is unavailable or malformed. Immediately before every MR squash update, merge, queue, or pipeline request, it re-reads the MR through the GitLab API and requires an explicit open, non-draft state with the expected target branch.

Pipeline creation recovery (GitLab)

Pipeline creation is a durable operation. Before the POST, gg records the target project, MR IID, source project and branch, current source commit, and target branch, then revalidates that immutable identity immediately before the request. If the POST response is ambiguous, the attempt remains durably Attempted, the command stops with an error that names gg reconcile, and gg never resends the POST blindly, because that could create a duplicate pipeline. The next gg land reads the MR: a head pipeline at the recorded head commit means the POST took effect and the attempt becomes the completed hand-off; an MR at the recorded head with no pipeline means it did not, and the attempt is cleared. If the MR moved to another head or cannot be read, the attempt stays and gg land stops with the gg reconcile error. If GitLab explicitly rejects the POST (an HTTP 4xx), no pipeline was created: gg commits the segment as a no-op, clears the attempt, and reports the rejection, so you can fix the cause and rerun gg land.

Once GitLab returns a pipeline ID, gg durably records a Completed handoff. It retains that handoff across restarts and stale provider reads until the matching MR is observed merged or closed, then clears it transactionally before continuing to another entry.

The handoff belongs to the MR head the pipeline was started for. If that head moves (for example, the pipeline failed and you amended the entry and ran gg sync), the next gg land drops the handoff and handles the new head as usual: it starts a pipeline if GitLab reports none, rechecks approval, and binds the queue request to the head it validated then. If the MR cannot be read, or the handoff’s operation record is missing or does not match it, gg land stops with the gg reconcile error; gg reconcile --dry-run lists the handoff and gg reconcile --discard-pending drops it. Inside one run, a head that moves after the pipeline was started still stops that run; rerun gg land.

For --auto-merge without merge trains, an ambiguous queue response is resolved by reading the MR once more: auto-merge set means it was queued, anything else means it was not and the marker is removed. gg never sends the queue request twice for one attempt.

GitLab only applies a squash flag that is true when queueing or merging, so an MR created while the project’s squash option is “Encourage” (default_on) would still be squashed. With --no-squash, gg therefore turns off the MR’s squash setting in its own durable Land segment. It rechecks project policy and the complete MR identity, then refreshes approval immediately before one PUT. An initially disabled setting is an unjournaled no-op; if the setting becomes disabled during final revalidation, gg instead commits the opened segment as untouched and clears its marker without consulting approval. Approval refusal or lookup failure does the same proven-no-op cleanup and stops downstream work. After a successful PUT, gg records pr_squash_updated and emits squash_checkpoint before any merge or queue request. If the project’s squash option is “Require” (always), gg land --no-squash fails before touching any MR.

If the PUT response is ambiguous, the command stops with an error that names gg reconcile. The next gg land reads the MR’s squash setting: off means the PUT took effect and the completed attempt is resumed; still on means it did not, and the attempt is cleared, so Land disables squash again (which is harmless to repeat). If the MR cannot be read, the attempt stays and gg land stops. A failed squash_checkpoint write also stops downstream work; the completed record is emitted and cleared on restart.

Approval is always required before an MR can enter the merge train queue — even with --all. If using --wait, the command will show “Waiting for approval…” until a reviewer approves the MR. A pipeline that has already failed or been canceled stops the command instead of queueing.

After queueing, GitLab can take time to report the MR in the merge train listing. With --wait, gg keeps polling until the configured land_wait_timeout_minutes instead of failing after a short not-found window. It still stops promptly if the MR is closed, GitLab reports it was skipped from the train, the MR pipeline fails before the MR joins the train, or repeated API errors occur.

If GitLab accepts the initial queue request but the response is lost, gg reads the MR and its merge-train entry once more. If the MR is on the train (or set to auto-merge, or merged), gg reports it queued and carries on; if not, it removes the attempt marker and reports the error, and rerunning gg land queues it. It never sends the queue request twice for one attempt. The completed pipeline handoff is kept either way.

GitLab cancels auto-merge when the MR’s source branch is pushed, and it does not add the MR back by itself. gg records the MR’s head commit when it queues the MR. When --wait sees the MR still open, off the train, and no longer set to auto-merge, it compares heads. If the head moved, a push cancelled the merge: gg queues the MR again with the same squash choice, records the new head, reports this in a wait event with status: "warning", and keeps polling. If the head did not move, the train pipeline failed or someone cancelled auto-merge by hand, so gg stops waiting with an error instead of queueing the MR again.

The requeue request is journaled separately from the initial queue. Before the POST, gg durably records both the requeue owner and that remote work may begin. It clears that recovery marker after GitLab confirms success, or explicitly rejects the request, and the Land operation is finalized. After an ambiguous response gg reads the MR once more: on the train means the requeue took effect and the wait continues; off the train means it did not, the marker is removed and the error is reported. A failed post-POST durability checkpoint keeps the marker, and the next gg land resolves it from GitLab the same way, without sending the requeue again. After a known success, the waiter tracks the head SHA from the final MR validation rather than the earlier polling snapshot.

Every GitLab queue action (the initial merge-train queue, a requeue, or an auto-merge queue) follows the same order. gg first records in the operation that remote work may begin, then saves the action’s attempt marker, and only then sends the request. If the first write fails, nothing else happened. If the marker cannot be saved, gg clears that first write again and commits the operation as a no-op. Either way, no request was sent and you can simply rerun gg land. If an older version left a marker whose operation never recorded possible remote work, gg treats it as proof the request was never sent, retires it without contacting GitLab, and continues.

Each GitLab queue or auto-merge operation records which action it is (merge-train queue, requeue, or auto-merge) and the exact MR it acts on: stack, MR number, target branch, source project and branch, source commit, and target project. Before recovering a saved attempt, and before contacting GitLab or clearing anything, gg checks that the operation names exactly one GitLab action, that it matches the saved attempt, and that the recorded MR identity matches too. Pipeline and squash recovery apply the same check. Any missing, duplicate, or conflicting entry stops gg land and leaves the evidence untouched.

CI Failure Details

When using --wait, if CI fails on an MR the command stops and shows which jobs failed:

OK Landed 1 MR(s)

⚠ Landed 1 MR(s), but encountered an error:

Error: MR !7621 CI failed
  Failed jobs: lint (stage: test), build-android (stage: build)

This helps diagnose CI issues without having to open the GitLab UI. Failed job names and stages are fetched from the MR’s head pipeline.

Concurrent commands while waiting

gg land --wait releases the repository-wide gg lock while it polls CI, approvals, or merge-train state. You can run commands such as gg sync for a different stack in another worktree during that time. Landing reacquires the lock before every merge, rebase, push, cleanup, or config update. After reacquiring it, Land resolves any merge-train queue marker left by another process from GitLab before it continues, and stops (naming gg reconcile) only if GitLab cannot tell what happened.

Do not change the stack being landed while it waits. If its commits, GG-IDs, or PR/MR mappings change, landing stops before the next merge and asks you to rerun the command with the latest stack state.

JSON Output

Example JSON response:

{
  "version": 1,
  "land": {
    "stack": "my-stack",
    "base": "main",
    "landed": [
      {
        "position": 1,
        "sha": "abc1234",
        "title": "feat: add parser",
        "gg_id": "c-abc1234",
        "pr_number": 42,
        "action": "merged",
        "error": null
      }
    ],
    "remaining": 0,
    "cleaned": false,
    "warnings": [],
    "error": null
  }
}

If Land stops on a fatal error after it started, it still prints the land object, with the entries landed before the failure, the remaining count, and error, and exits 1. The entry Land was working on is listed last with "action": "error": its merge or queue request may already have reached the forge (the error says “succeeded remotely” when it did), so it still counts in remaining until the next gg land settles it from the provider:

{
  "version": 1,
  "land": {
    "stack": "my-stack",
    "base": "main",
    "landed": [
      { "position": 1, "sha": "abc1234", "title": "feat: add parser", "gg_id": "c-abc1234", "pr_number": 42, "action": "merged", "error": null },
      { "position": 2, "sha": "def5678", "title": "feat: add printer", "gg_id": "c-def5678", "pr_number": 43, "action": "error", "error": "Durability checkpoint error: direct merge for PR #43 succeeded remotely, but ..." }
    ],
    "remaining": 1,
    "cleaned": false,
    "warnings": [],
    "error": "Durability checkpoint error: direct merge for PR #43 succeeded remotely, but ..."
  }
}

landed is not a list of merges. It can hold an entry with "action": "error", which is not a merge, so filter on action (merged, already_merged, …) instead of counting its length.

When --clean drained queued remote branch deletions, the land object also has remote_deletions: {"deleted": ["<branch>"], "deferred": [{"branch": "...", "reason": "..."}], "blocked": [{"branch": "...", "reason": "..."}]}. It is omitted when all three lists are empty. cleaned: false together with deferred entries means a later gg clean finishes the job, not that landing failed.

Only a failure before Land starts prints the bare {"version": 1, "error": "..."} object without land.

Streaming NDJSON (--jsonl)

gg land --jsonl emits one compact JSON object per line and flushes each line. Every event has version, command, status, and event. Human output is suppressed. Use this mode to monitor a long-running --wait invocation.

Event kinds:

EventFieldsEmitted when
startstack, base, total_entriesA non-empty landing run begins
pipeline_checkpointpr_numberA GitLab pipeline result and its operation finalization are durable
squash_checkpointpr_number, squashA GitLab squash update, exact effect, and operation finalization are durable
waitposition, pr_number, phase, poll, elapsed_seconds, ci_status, approved, merge_train_status, merge_train_position, pipeline_running, errorEach readiness or merge-train provider poll completes
entrySame fields as an item in landedAn entry reaches an outcome
summarySame fields as the land object from --jsonLanding finishes, including partial and fatal failures
errormessageA fatal error; once Land has started, a summary follows

phase is readiness while checking CI and approval, or merge_train after queueing an MR. Fields that the current phase did not check are null. Transient provider errors appear in a wait event with status: "warning" and the command keeps polling. Unchanged states still emit a heartbeat on the existing 10-second polling cadence.

For a recovered or newly completed pipeline operation, pipeline_checkpoint is emitted only after the durable state is complete. If writing or flushing that event fails, including a broken output pipe, landing stops before queueing the MR or taking the next action.

Once Land has started (its provider check passed), the final event is always summary. Consumers should inspect its error field: a landing failure Land reports itself (for example an unapproved PR/MR, failed CI, or a failed downstream push) keeps the existing exit status 0, while a fatal failure (for example a merge that succeeded remotely but could not be recorded) emits error, then the summary with "status": "error", and exits 1. Only a failure before Land starts ends with a lone error event: for example not a repository, the gg lock is held, unfinished replacement follow-ups, failed provider authentication, or repository state written by a newer gg.

{"version":1,"command":"land","status":"ok","event":"start","stack":"my-stack","base":"main","total_entries":1}
{"version":1,"command":"land","status":"ok","event":"wait","position":1,"pr_number":42,"phase":"readiness","poll":1,"elapsed_seconds":0,"ci_status":"running","approved":true,"merge_train_status":null,"merge_train_position":null,"pipeline_running":null,"error":null}
{"version":1,"command":"land","status":"ok","event":"entry","position":1,"sha":"abc1234","title":"feat: add parser","gg_id":"c-abc1234","pr_number":42,"action":"merged","error":null}
{"version":1,"command":"land","status":"ok","event":"summary","stack":"my-stack","base":"main","landed":[{"position":1,"sha":"abc1234","title":"feat: add parser","gg_id":"c-abc1234","pr_number":42,"action":"merged","error":null}],"remaining":0,"cleaned":false,"warnings":[],"error":null}

gg clean

Delete merged stacks (and associated managed worktrees).

gg clean [OPTIONS]

Options

  • -a, --all: Clean all merged stacks without prompting
  • --json: Emit machine-readable JSON output

Worktrees and incomplete cleanup

Clean never removes the worktree you run it from. If your current branch is one of the stack’s branches, Clean first switches to the stack’s base branch, or detaches HEAD when the base is checked out elsewhere, and then deletes the branch.

A stack’s managed worktree is removed only after you confirm the prompt. The same goes for any other linked worktree that has one of the stack’s branches checked out. With --json, or without an interactive terminal, Clean never removes those worktrees. It skips the stack instead and reports why. Declining also skips the stack, because its branches cannot be deleted while a worktree holds them.

Deleting the stack’s local branches is required, not best-effort. If any branch cannot be deleted, Clean reports the failure, exits with an error, and keeps the stack’s configuration so you can fix the cause and run gg clean again.

Queued remote deletions after gg land

gg land merges an entry and removes its PR/MR mapping, so the stack no longer remembers which remote branch belonged to it. To keep that branch deletable, land queues a deletion for it at the commit that was merged, in the same config write that removes the mapping. This happens with or without --clean, and it works when no local entry branch exists.

Every gg clean (with or without --all) first drains the queued deletions for your entry branches, from any stack, even one whose configuration is already gone. gg land --clean does the same when the whole stack lands and cleanup runs. Each branch ends in one of three ways:

  • deleted: the branch was still at the merged commit and no open review targets it, so it was deleted from origin.
  • deferred: an open review targets it, there is no provider, or the remote could not be read. Clean prints a warning, keeps the queued deletion and exits 0. Retarget or close the review, then run gg clean again.
  • blocked: the branch moved since it was merged, the remote refused the delete (a server hook or protected branch; the deletion stays queued), the delete push failed and the branch is still at the merged commit (nothing changed; the deletion stays queued and the next gg clean retries it), or an earlier delete with an unknown outcome needs a decision. Clean prints one message for that branch and carries on with the others, then exits non-zero. Delete the branch yourself if the new commits are not needed, or keep it with gg reconcile --discard-pending.

gg land --clean keeps its exit code in these cases, but prints a warning and reports cleaned: false. If gg clean verifies a stack is merged but has to skip or defer its remote delete, it queues the deletion before dropping the stack configuration, so a later gg clean still finishes it. gg sync never runs or drops these deletions.

For example, an outside review still targets a landed entry:

$ gg land --all --clean
! Kept remote branch 'alice/feat--c-abc1234': open PR #103 still targets it. Retarget or close it, then run `gg clean` again; or keep the branch with `gg reconcile --discard-pending`.
$ gg clean --all     # after closing #103

Branches that older versions (v0.10.10 and earlier) left behind have no queued deletion. After confirming the review is merged, delete them by hand:

git push origin --delete <user>/<stack>--<gg-id>

Examples

gg clean
gg clean --all
gg clean --json

--json prints:

  • version: output schema version
  • clean.cleaned: stacks that were cleaned
  • clean.skipped: stacks skipped (unmerged or declined in interactive mode)
  • clean.remote_deletions: only when queued deletions were drained or kept: {"deleted": ["<branch>"], "deferred": [{"branch": "...", "reason": "..."}], "blocked": [{"branch": "...", "reason": "..."}]}. Omitted when all three lists are empty.

When merge verification allows Clean to delete an entry branch from origin, the Clean operation records a branch_deleted remote effect with the branch’s exact server-side OID. Deletion uses a matching force-with-lease so a concurrent server update is never deleted or misreported. Before deleting, Clean asks the provider for open PRs/MRs whose target is that branch, both before saving the deletion and again immediately before the push. That applies to gg clean and to gg land --clean. If a review still targets the branch, or the lookup is impossible because no provider is detected, the request fails, or the output is malformed, Clean keeps the remote branch, the local entry branch, and the stack configuration. It reports the blocking review and leaves the deletion retryable. Retarget the review, for example with a full gg sync, then run gg clean again. Each remote branch deletion has its own durable checkpoint in the clean’s operation record: uncertainty is saved before the request, and the exact effect is saved and checkpointed before Clean reports success or starts the next deletion. The whole gg clean is one record, so once it deleted a remote branch none of it is locally undoable. Clean also saves the branch and expected OID as a remote deletion entry in the config’s pending_remote_changes journal before a direct request. If the request outcome is ambiguous, Clean leaves that entry attempted and stops. The next gg clean checks the remote first. If the branch is gone, the deletion took effect and the entry is retired. If it is still at the expected commit, the deletion is retried: Clean sends the leased push again through the same open-review check. If it now points at another commit, Clean keeps that stack, reports it as skipped with an error naming gg reconcile, and still cleans the other stacks. Managed worktree removal clears and durably saves its configured path, then finalizes its local checkpoint before printing the unchanged Removed worktree success message. A retry reconciles an already removed, unregistered worktree after a failed config save. gg undo refuses local replay for a completed remote deletion and prints the exact git push origin <prior_oid>:refs/heads/<branch> recovery command.

gg lint

Run configured lint commands on stack commits.

gg lint [OPTIONS]

Options

  • -u, --until <UNTIL>: Stop at target entry (position, GG-ID, SHA)
  • --json: Emit structured JSON output

Examples

# Lint from bottom to current
gg lint

# Lint only a subset
gg lint --until 2

Mutating --until runs

When lint rewrites commits in sequential mode, --until freezes the originally selected entries before the first rewrite. If a rewrite drops one, an entry that shifts into the same stack position does not replace it.

A stable, unique GG-ID or title lets an originally selected entry continue across OID-changing rewrites. If an earlier rewrite makes a selected commit’s OID unresolvable and it has no unique GG-ID or title, lint fails closed with a validation could not be completed error instead of reporting success.

Inspect the rewritten current stack and rerun gg lint. Before retrying broader mutating validation, make commit identity unambiguous: prefer unique GG-IDs, otherwise use unique titles. Already-applied rewrites remain in place under the existing restoration behavior.

When lint starts from a detached stack position (for example, after gg mv 2), it keeps HEAD detached at that logical position. If lint rewrites the commit, HEAD follows the rewritten entry when its GG-ID identifies it uniquely. If the identity is missing or ambiguous, HEAD returns to the exact original commit instead of attaching to or guessing a stack branch.

gg run

Run an arbitrary command on each commit in the stack. Like jj run in Jujutsu — useful for validating changes (build, test), applying auto-fixers (formatters, codemods), or any per-commit shell command.

gg run [OPTIONS] -- <COMMAND>...

Arguments after -- are passed through as-is. Use -- whenever your command has its own flags so clap knows where gg run’s options end.

Modes

gg run has three modes that control what happens to files the command modifies:

  • Read-only (default): if the command modifies tracked files, the commit is marked failed. Ideal for build/test/lint validation.
  • --amend: stage and fold any modifications into the current commit, then rebase the rest of the stack on top. Ideal for formatters and codemods (cargo fmt, prettier, ruff --fix).
  • --discard: revert any working-tree changes after each commit. Ideal for commands with known side effects you want to ignore.

Options

  • -u, --until <UNTIL>: stop at this commit position (default: current).
  • --amend: fold file changes into each commit (see above).
  • --discard: discard file changes after each commit.
  • --keep-going: continue on command failure instead of stopping at the first failed commit (default is to stop).
  • -j, --jobs <N>: number of parallel workers. 0 = auto-detect CPUs, 1 = sequential (default). Parallel mode only applies to read-only runs and uses isolated temporary worktrees, one per commit.
  • --json: emit structured JSON output instead of human-readable text.

Examples

# Read-only validation across the whole stack
gg run -- cargo test

# Apply a formatter and fold changes into each commit
gg run --amend -- cargo fmt

# Run across up to commit 2 only
gg run --until 2 -- cargo check

# Parallel read-only run with 4 workers
gg run -j 4 -- cargo test

# Continue past failing commits (useful for auditing)
gg run --keep-going -- cargo clippy

# Pass a command with quoted arguments — argv boundaries are preserved
gg run -- sh -c 'echo "$GG_CURRENT_COMMIT" && cargo test --test integration'

Mutating --until runs

With --amend in sequential mode, --until freezes the originally selected entries before the first rewrite. If a rewrite drops one, an entry that shifts into the same stack position does not replace it.

A stable, unique GG-ID or title lets an originally selected entry continue across OID-changing rewrites. If an earlier rewrite makes a selected commit’s OID unresolvable and it has no unique GG-ID or title, the command fails closed with a validation could not be completed error instead of reporting success.

Inspect the rewritten current stack and rerun the command. Before retrying broader mutating validation, make commit identity unambiguous: prefer unique GG-IDs, otherwise use unique titles. Already-applied amendments remain in place under the existing restoration behavior.

JSON output

With --json, gg run emits a RunResponse:

{
  "version": 1,
  "run": {
    "results": [
      {
        "position": 1,
        "sha": "abc1234",
        "title": "Add feature",
        "passed": true,
        "commands": [
          {"command": "cargo test", "passed": true, "output": null}
        ]
      }
    ],
    "all_passed": true
  }
}

The command field is a copy-pasteable shell form: arguments containing whitespace or special characters are single-quoted. It reflects your input, not the actual argv.

Notes

  • Shell aliases (alias gw=./gradlew) are not expanded. Use the real command path.
  • .git/ paths in the command (e.g. .git/gg/lint.sh) are rewritten to the real git commondir so they resolve inside linked worktrees and inside parallel worker worktrees.
  • Parallel mode creates temporary worktrees under $TMPDIR/gg-run-<pid>/, cleaned up automatically when the run finishes.
  • Under --amend + default stop-on-error, if a later commit fails, the already-amended commits above are preserved — the branch is not force-reset. Use gg continue / gg abort to resume if a rebase conflict happened instead.
  • When --amend starts from a detached stack position (for example, after gg mv 2), gg run keeps HEAD detached at that logical position. If the commit is rewritten, HEAD follows the rewritten entry when its GG-ID identifies it uniquely. If the identity is missing or ambiguous, HEAD returns to the exact original commit instead of attaching to or guessing a stack branch.

gg setup

Interactive setup for .git/gg/config.json.

gg setup        # Quick mode: essential settings only
gg setup --all  # Full mode: all settings organized by category

Use this when:

  • Starting git-gud in a new repository
  • Working with self-hosted GitHub/GitLab
  • Updating defaults (base branch, username, lint config)

Quick Mode (default)

Quick mode prompts for only the essential settings:

  • Provider: GitHub or GitLab
  • Base branch: Default base branch (main/master/trunk)
  • Username: Username for branch naming

After completing quick setup, you’ll see:

Tip: Run 'gg setup --all' to configure advanced options (sync, land, lint, etc.)

Full Mode (--all)

Full mode organizes all settings into logical groups:

General

FieldTypeDefaultDescription
providerselectauto-detectGitHub or GitLab (auto-detects github.com and gitlab.com remotes; self-hosted instances require manual selection)
basestringauto-detectDefault base branch (main/master/trunk)
branch_usernamestringfrom CLI authUsername for branch naming
unstaged_actionselectaskAction for gg amend with unstaged changes

Sync

FieldTypeDefaultDescription
sync_auto_rebaseboolfalseAuto-rebase when base is behind origin
sync_behind_thresholdnumber1Commits behind origin before warning/rebase
sync_draftboolfalseCreate new PRs/MRs as drafts by default
sync_update_descriptionsbooltrueUpdate PR/MR descriptions on re-sync
sync_update_titleboolfalseUpdate PR/MR titles on re-sync. A GitLab draft keeps its existing prefix if the commit subject has none.
stack_nav_commentsboolfalsePost a managed navigation comment linking all PRs/MRs in the stack

Land

FieldTypeDefaultDescription
land_auto_cleanboolfalseAuto-clean stack after landing all
land_wait_timeout_minutesnumber30Timeout for gg land --wait

Lint

FieldTypeDefaultDescription
lintlistemptyLint commands to run per commit
sync_auto_lintboolfalseRun lint automatically before sync

Worktrees

FieldTypeDefaultDescription
worktree_base_pathstringemptyTemplate for stack worktrees ({repo}, {stack})

GitHub (only shown if provider is GitHub)

FieldTypeDefaultDescription
github.stacks_integrationselect (off, auto, force)autoGitHub Stacked PRs public-preview integration. auto is best effort with the optional gh stack extension; force reports unavailable capabilities as warnings; off disables it.

The GitHub Stacked PRs selector appears only when GitHub is selected as the effective provider. GitLab setup does not prompt for it and preserves any existing GitHub setting.

GitLab (only shown if provider is GitLab)

FieldTypeDefaultDescription
gitlab.auto_merge_on_landboolfalseUse “merge when pipeline succeeds”

Global Config

git-gud supports global configuration at ~/.config/gg/config.json. When running gg setup:

  • If no local config exists, global defaults are shown in prompts
  • Local config always takes precedence over global config

This allows you to set organization-wide defaults while allowing per-repo overrides.

All fields are written to config.json after setup, making it easy to review and edit configuration manually.

Note: auto_add_gg_ids is deprecated. Existing configs that include it are still read, but setup no longer prompts for it and runtime behavior always treats it as enabled.

gg continue / gg abort

Control paused operations (typically rebases with conflicts).

gg continue
gg abort

Use gg continue after resolving conflicts and staging files. Use gg abort when you want to stop and roll back the in-progress operation.

When a recorded gg operation stops on a rebase conflict, gg continue finalizes that original operation in the undo log after the rebase completes. That means the completed operation can still be reversed with gg undo.

gg records which operation owns a paused rebase in the worktree’s git directory (gg/interrupted-rebase-operation.json; each linked worktree has its own).

If you end the rebase with plain Git instead (git rebase --abort), the marker is left behind with no rebase to belong to. That marker is stale: gg ls, gg continue, gg abort, gg sync and gg land clear it and say so on stderr, for example:

Note: Cleared a stale interrupted-rebase marker for operation op_...: no rebase is in progress in this worktree.

gg continue and gg abort then report No rebase in progress, as there is nothing left to continue or abort.

While a rebase is in progress, the marker must match it. If it is malformed, cites a missing or already-finished operation, cites a command that never pauses on a rebase, or no longer matches the rebase in progress, gg continue and gg ls --json refuse to run and leave both the marker and the rebase untouched, so nothing finalizes the wrong operation. Then either:

  • gg abort to end the rebase; the marker is cleared with it; or
  • gg reconcile --dry-run to see the problem, then gg reconcile --discard-pending to drop the marker and keep the rebase, and gg continue to finish it. The operation that started the rebase is then not finalized in the undo log.

gg reconcile

Repair gg’s state when things happened outside gg: an interrupted command left a recovery marker behind, or branches and PRs were pushed without gg sync.

gg reconcile [OPTIONS]

Options

  • -n, --dry-run: Preview only; make no changes. Lists every leftover marker and what it resolves to. A dry run writes nothing, not even an entry in gg undo --list.
  • -y, --yes: Skip the confirmation prompt. On its own it approves metadata normalization (which rebases the stack). With --discard-pending it confirms only the discard. Use for non-interactive callers such as agents, MCP, or CI when you intentionally want reconciliation to proceed.
  • --discard-pending: Also remove the markers gg cannot settle, after printing what each one abandons: markers whose outcome the forge cannot determine, and pending branch deletions that no stack owns any more. Nothing remote is changed. Metadata normalization is not applied in the same run; it is reported, and a plain gg reconcile applies it. Cannot be combined with --dry-run. With --json it requires --yes.
  • --json: Print one JSON document instead of human output. A JSON caller cannot answer the normalization prompt, so without --yes the stack is not rebased (normalized: false).

What it does

  1. Settles leftover recovery markers. When a command such as gg sync or gg land sends a request and never sees the answer (the process was killed, the network dropped), it leaves a marker in gg/config.json so the next run does not repeat the request blindly. gg reconcile reads the forge for every marker, across all stacks (including stacks you have since removed and pending remote-branch deletions), and acts on what it finds:

    • completed: the request took effect. gg finishes its bookkeeping (for example, maps a review that was created) and clears the marker.
    • not applied: the request did not happen or no longer matters. The marker is cleared, so the next gg sync or gg land redoes the step if it still applies. A replaced-review follow-up or a pending branch deletion is kept for gg sync/gg clean to retry; reconcile itself never comments, closes, merges or deletes anything.
    • undetermined: the forge could not be read, or its answer is ambiguous (for example, two open reviews from the same branch). The marker is kept. Retry once the forge is reachable, or abandon it with --discard-pending.

    A land intent is a queued remote branch deletion that gg land left for a merged entry. --dry-run lists it as a remote deletion together with its review (for example PR #101), and gg clean normally deletes the branch. --discard-pending drops it and keeps the remote branch.

    A pending branch deletion whose stack was removed (or renamed, or whose branch_username changed) has no owner: no gg sync or gg clean will retry it. Reconcile says so, and --discard-pending drops it.

    A completed GitLab pipeline handoff (the pipeline gg land started for an MR) is not a pending marker and is not listed while it still applies. Reconcile lists it as completed and clears it once the MR is merged, closed or at another head, and as undetermined when the MR cannot be read or the handoff’s operation record is missing or does not back it.

    It also handles this worktree’s interrupted-rebase marker: a stale one (the rebase was ended with plain git rebase --abort) is cleared, and one that contradicts the rebase in progress can be discarded with --discard-pending, which keeps the rebase itself. See gg continue / gg abort.

  2. Normalizes GG metadata trailers on the current stack’s commits (GG-ID + GG-Parent). This rebases the stack, so it asks first unless you pass --yes.

  3. Maps existing remote PRs/MRs back to the current stack’s entries.

Without a usable provider (none detected, its CLI missing, or not authenticated), reconcile still settles the markers that need none: pending remote branch deletions, which it reads from the remote, and this worktree’s interrupted-rebase marker. Every other marker is listed as unknown and kept (even with --discard-pending), steps 2 and 3 are skipped, and the human output says they need the provider. It exits 0. When there is nothing of that kind to settle, a run without --dry-run fails with the provider error, as before.

When HEAD is not on a stack, only the marker step runs; if there are no markers either, reconcile stops with the usual “not on a stack” error. While a rebase is in progress, steps 2 and 3 are skipped, so reconcile never starts a rebase on top of a paused one.

An error from gg sync, gg land or gg clean that names gg reconcile means one of these markers could not be settled automatically. Start with gg reconcile --dry-run.

Discarding a marker

--discard-pending gives up on what the marker tracked. Each line says what that means, so check the forge before the next command:

  • a lost review creation: a review may exist on the forge for that branch. If none is mapped, the next gg sync opens a new one.
  • a direct merge, merge-train queue or GitLab landing request: the review may already be merged or queued.
  • a replaced-review follow-up: gg no longer comments on or closes the old review.
  • post-merge maintenance: the attempted retargets, pushes or local rebases are forgotten, and the next gg land redoes them.
  • a land intent (the queued deletion of a landed entry’s branch): gg stops trying to delete it, and the remote branch stays. Delete it yourself with git push origin --delete <branch> if you no longer need it.
  • a remote branch deletion (undetermined, or owned by no stack): gg gives up its authority to delete the branch, so the remote branch is left in place. Delete it yourself if it is no longer needed.

Examples

# See every leftover marker and what it resolves to; nothing changes
gg reconcile --dry-run

# Apply what the forge settles; undetermined markers stay
gg reconcile

# Also abandon what the forge cannot settle
gg reconcile --discard-pending

# Non-interactive / agent usage
gg reconcile --dry-run --json
gg reconcile --discard-pending --yes --json

A dry run with one marker of each outcome:

→ 3 pending recovery markers (dry run: nothing changed):
  • feat: review creation for alice/feat--c-2222222 into main: undetermined (open PRs from alice/feat--c-2222222 could not be listed (...: connection refused))
  • feat: direct merge of #41 at 1111111: not applied (the marker would be cleared)
  • deletion of origin/alice/gone--c-3333333 at 1111111…: completed (the marker would be cleared)
  Run `gg reconcile` to apply; undetermined markers stay until the forge can answer, or `gg reconcile --discard-pending` abandons them.

Discarding the undetermined one:

! Discarding pending markers gg cannot settle:
  • feat: review creation for alice/feat--c-2222222 into main: a review may exist on the forge for this branch; check it before the next `gg sync`, which opens a new one if none is mapped
OK Discarded 1 marker.

JSON output

{
  "version": 1,
  "dry_run": false,
  "markers": [
    {
      "stack": "feat",
      "kind": "review_creation",
      "key": "c-2222222",
      "review": null,
      "summary": "review creation for alice/feat--c-2222222 into main",
      "resolution": "undetermined",
      "reason": "open PRs from alice/feat--c-2222222 could not be listed (...)",
      "consequence": "a review may exist on the forge for this branch; check it before the next `gg sync`, which opens a new one if none is mapped",
      "discarded": true
    }
  ],
  "stack": "feat",
  "commits_needing_ids": [],
  "reviews_to_map": [],
  "normalized": false
}
  • markers[].kind: review_creation, direct_merge, gitlab_landing, gitlab_train_queue, replacement_followup, land_maintenance, remote_deletion, or interrupted_rebase. stack is empty for repository-wide markers (remote deletions, this worktree’s rebase marker).
  • markers[].resolution: completed, not_applied, undetermined, unknown (the provider cannot be detected or its CLI is missing or not authenticated; reason says provider unavailable; remote deletions are still read from the remote), or in_progress (a paused rebase gg still owns; finish it with gg continue or gg abort).
  • markers[].consequence: what discarding the marker abandons (the line printed before discarding). Set when --discard-pending would remove the marker or did; null otherwise.
  • markers[].discarded: whether --discard-pending removed it.
  • stack, commits_needing_ids, reviews_to_map, normalized: the stack step. stack is null when HEAD is not on a stack.

gg reconcile exits 0 when undetermined markers remain; check resolution.

gg restack

Repair stack ancestry after manual history changes (amend, cherry-pick, upstream rebase).

gg restack [OPTIONS]

Options

  • -n, --dry-run: Show what would be done without making changes
  • --from <TARGET>: Repair only from this commit upward (position, SHA, or GG-ID)
  • --json: Output result as JSON

Behavior

  1. Validates no rebase is already in progress
  2. Validates the working directory is clean
  3. Requires all commits to have GG-IDs (directs to gg reconcile if missing)
  4. Compares each entry’s GG-Parent trailer against the expected parent
  5. If all parents match, reports “Stack is already consistent”
  6. If --dry-run, displays the plan and exits
  7. Performs a single git rebase -i to realign the chain
  8. Normalizes GG metadata after rebase
  9. Prints a summary with a hint to run gg sync

Examples

# Check if the stack needs restacking (no changes)
gg restack --dry-run

# Repair the full stack
gg restack

# Repair only from position 3 upward
gg restack --from 3

# Repair from a specific GG-ID upward
gg restack --from c-abc1234

# Get JSON output
gg restack --json

# Combine dry-run and JSON
gg restack --dry-run --json

JSON Output

{
  "version": 1,
  "restack": {
    "stack_name": "my-feature",
    "total_entries": 4,
    "entries_restacked": 2,
    "entries_ok": 2,
    "dry_run": false,
    "steps": [
      {
        "position": 1,
        "gg_id": "c-abc1234",
        "title": "Add login form",
        "action": "ok",
        "current_parent": null,
        "expected_parent": null
      },
      {
        "position": 2,
        "gg_id": "c-def5678",
        "title": "Add validation",
        "action": "reattach",
        "current_parent": "c-old1111",
        "expected_parent": "c-abc1234"
      }
    ]
  }
}

Inserting a commit mid-stack

gg restack also integrates commits you make at a detached HEAD after navigating to a mid-stack position with gg mv:

gg mv 1             # detach HEAD at position 1
git commit -m "inserted"
gg restack          # folds "inserted" into the stack; HEAD stays on it

After gg restack completes, HEAD is left on the just-inserted (or just-amended) commit. Run gg sync to push the updated stack.

Note: If folding the commit in hits a conflict, resolve it (stage the fixes with git add) and run gg continue — or gg abort to cancel the fold-in entirely. gg continue finishes the integration just like the non-conflict path: it normalizes the metadata (assigning the inserted commit its GG-ID/GG-Parent) and leaves HEAD on the integrated commit.

Edge Cases

  • Empty stack produces an error
  • Missing GG-IDs directs to gg reconcile
  • Rebase in progress blocks with a clear error message
  • Rebase conflicts are handled the same as gg reorder — resolve with gg continue or gg abort
  • --from 1 is equivalent to a full restack
  • Detached HEAD with un-integrated commits — gg restack detects and folds them in automatically

gg undo

Reverse the local ref/HEAD effects of the most recent mutating gg command, backed by a per-repo operation log.

gg undo [OPERATION_ID] [--json]
gg undo --list [--limit N] [--json]

gg undo only moves refs and HEAD — it never modifies your working tree, working-copy files, or the index. The log lives at <commondir>/gg/operations/*.json and keeps the last 100 commands (one record per command); Pending records (operations interrupted by a crash, Ctrl-C, or a long-running conflict) are never pruned, and a record that a pending remote-branch deletion still cites is kept until that deletion is resolved.

Options

  • OPERATION_ID: Target a specific record (op_…). When omitted, undoes the most recent locally-undoable operation that changed something. It skips records that moved no ref and touched no remote, such as a no-op gg sync; --list still marks those undoable, and passing the ID targets one explicitly. It also skips every command that touched the remote.
  • --list: Show recent operations, one row per command, with id, kind, status, timestamp, and undoability marker.
  • --limit N: Cap --list output (default: 20).
  • --json: Emit machine-readable JSON.

How it works

Every mutating gg command (sc, drop, split, unstack, rebase, reorder, absorb, reconcile, checkout, mv/first/last/prev/next, clean, sync, land, and run --amend) now snapshots the refs it will touch before mutating and finalises the record on success. gg undo replays the refs_before snapshot of the target record, moving refs back to where they were.

Each command writes one operation record, so gg undo --list shows one row per command. Commands that mutate the remote in several steps (gg sync, gg land, gg clean) save a checkpoint inside that record after each step, durably and before the next remote mutation starts, so a crash or an uncertain provider response always leaves an exact trail for gg reconcile. The checkpoints are listed under checkpoints in the record’s JSON file; they are not separate undo targets.

gg undo treats a command as one unit: if any step of it touched the remote, none of it is locally undoable. A gg clean that deleted remote branches, or a gg sync that pushed one branch and then rebased locally, is refused as a whole (reason remote) instead of reverting only its local part. A command that crashed in the middle of a step shows as a single interrupted row; one that stopped between steps shows as committed with the steps it completed.

gg land records are never locally undoable, including a land whose only step was a local rebase: plain gg undo skips them, gg undo <id> refuses them with reason remote, and --list reports them as not undoable.

Records written by earlier releases keep their shape: a v0.10.11 command may appear as several rows (one per segment), and those rows still list, undo, and settle exactly as before. A single-step command is still written in that plain shape (schema 2), so older releases undo it normally; only multi-step commands use the newer schema (see Configuration).

If one of those operations pauses on a rebase conflict, resolving the conflict and running gg continue finalises the original operation record. The completed operation then appears as undoable in gg undo --list, unless it is a gg land record.

A second gg undo redoes the first — because undo is itself recorded as an operation, running it twice reverses the reversal. For a published gg drop, this also replays the exact deferred remote-branch deletion-intent change: undo cancels unconsumed authority and redo restores the same OID-bound state. It does not recreate authority already consumed by Sync or turn an uncertain deleting state back into retryable authority. Entries created by gg undo appear in --list with a ↶ marker and an undoes field pointing at the original operation id.

Native-client correlation

All gg commands accept the global --client-operation-id <ID> option. A native client can assign a unique token to a mutation and then identify the operation record created by that invocation without relying on timestamps or newest-record ordering:

gg drop 3 --yes --client-operation-id alas:018f84c0-3a14-7b45-a397-93c87266391d
gg undo --list --json

The operation record’s args array preserves the exact adjacent "--client-operation-id", "alas:..." pair. Match that pair, then pass the record’s opaque op_... id to gg undo <OPERATION_ID> --json. The client token is correlation metadata only: it never replaces or influences GG’s operation ID.

Client operation IDs must be 1–128 characters of ASCII letters, digits, -, _, ., or :. Generate a unique token for every attempted mutation and do not reuse one across concurrent requests.

Refusal modes

gg undo refuses (exit 1, no refs touched) when:

ReasonConditionWhat to do
remoteThe target op pushed, deleted a remote branch, or created/merged/closed a PR or MR, or it is a gg land record.Use the printed recovery hint. Deleted branches include an exact git push origin <prior_oid>:refs/heads/<branch> command when GG captured the prior OID. Local state is unchanged.
interruptedThe op crashed, was Ctrl-C’d, or was aborted before completion and has status: Interrupted.Fix the underlying state manually; the stale Pending record is swept into Interrupted on the next lock-acquiring op.
staleRefs have moved since the target op finalised.Run gg undo --list and target a more recent record instead. The error names the ref, the expected OID, and the actual OID.
unsupported_schemaThe record was written by a newer gg with a schema version this binary does not understand.Upgrade gg. This gg also refuses to overwrite such a record (see Configuration).

Examples

# Reverse the last local operation
gg undo

# See what's on the log (newest first)
gg undo --list
gg undo --list --limit 5

# Target a specific record from --list
gg undo op_0000001750000000_018f…

# Redo: undo twice in a row
gg undo
gg undo

# Scripting
gg undo --list --json | jq '.operations[] | select(.is_undoable)'

JSON output

Schema versioning: all gg JSON responses share the top-level version field (OUTPUT_VERSION). The undo types are additive — new optional fields may be added in future releases without bumping the version. Forward-compatible consumers should ignore unknown fields.

gg undo --json

{
  "version": 1,
  "status": "succeeded",
  "undone": {
    "id": "op_0000001750000000_018f…",
    "kind": "drop",
    "status": "committed",
    "created_at_ms": 1750000000000,
    "args": ["drop", "3"],
    "stack_name": "feat/login",
    "touched_remote": false,
    "is_undoable": true,
    "is_undo": false,
    "remote_effects": []
  }
}

On refusal:

{
  "version": 1,
  "status": "refused",
  "refusal": {
    "reason": "remote",
    "message": "Cannot locally undo 'sync': it touched a remote.",
    "target": { "id": "op_…", "kind": "sync", "touched_remote": true, "…": "…" },
    "hints": [
      "Close PR #42: gh pr close 42",
      "Delete remote branch: git push --delete origin nacho/feat/1"
    ]
  }
}

refusal.reason is one of remote, interrupted, stale, unsupported_schema.

gg undo --list --json

{
  "version": 1,
  "operations": [
    {
      "id": "op_…",
      "kind": "undo",
      "status": "committed",
      "created_at_ms": 1750000100000,
      "args": ["undo"],
      "stack_name": "feat/login",
      "touched_remote": false,
      "is_undoable": true,
      "is_undo": true,
      "undoes": "op_previous…"
    },
    { "…": "…" }
  ]
}

Operations are returned newest-first. Use is_undoable to gate UI/agent actions; use is_undo + undoes to render redo markers.

What gg undo does NOT do

  • It does not restore working-tree files or the index. If you amended a commit and want the old source back, use git reflog or git stash.
  • It does not touch remotes. Operations that pushed, deleted a remote branch, or created/merged/closed PRs/MRs are recorded (so you can see them in --list) but refused for local replay.
  • It does not guarantee atomicity of the replay. If the process dies mid-replay, inspect the interrupted operation, refs, and any queued remote deletions (gg reconcile --dry-run) before reconciling manually. The working tree remains untouched, but refs or recorded deletion intent may already have changed.
  • It does not support an --all / --range mode. Each call reverses exactly one operation.

See also

  • gg log — smartlog view of the current stack
  • MCP server — stack_undo and stack_undo_list tools for agentic workflows

MCP Server

git-gud includes an MCP (Model Context Protocol) server that allows AI assistants like Claude Desktop, Cursor, and other MCP-compatible tools to interact with your stacked-diffs workflows programmatically.

Installation

The gg-mcp binary is distributed alongside gg. If you installed via Homebrew or cargo-dist, it should already be available.

Configuration

Claude Desktop

Add this to your Claude Desktop MCP configuration (~/Library/Application Support/Claude/claude_desktop_config.json):

{
  "mcpServers": {
    "git-gud": {
      "command": "gg-mcp",
      "env": {
        "GG_REPO_PATH": "/path/to/your/repo"
      }
    }
  }
}

Cursor / Other MCP Clients

Configure gg-mcp as a stdio-based MCP server. Set GG_REPO_PATH to point to your repository.

Environment Variables

VariableDescriptionDefault
GG_REPO_PATHPath to the git repositoryCurrent working directory

Available Tools

stack_list

List the current stack with commit entries and PR/MR status.

Parameters:

  • refresh (boolean, optional): Refresh PR/MR status from remote before listing. Default: false.

Returns: Stack name, base branch, commit entries with positions, SHAs, titles, GG-IDs, PR numbers, states, CI status, and approval status.

stack_log

Render the current stack as a smartlog-style view (stack-scoped). Mirrors the CLI gg log --json output.

Parameters:

  • refresh (boolean, optional): Refresh PR/MR status from remote before rendering. Default: false.

Returns: { stack, base, current_position, entries: [...] }. Entry fields match stack_list. Use stack_list_all when you need a cross-stack overview.

stack_list_all

List all stacks in the repository with summary information.

Parameters: None.

Returns: Current stack name and a list of all stacks with name, base branch, commit count, and whether each is the current stack.

stack_inbox

Show actionable triage across local stacks. Mirrors the atomic gg inbox --json snapshot and groups PRs/MRs into action buckets like refresh failed, ready to land, blocked on CI, awaiting review, behind base, draft, and optionally merged.

Parameters:

  • all (boolean, optional): Include merged items as well.

Returns: A versioned JSON payload with total_items, buckets, and stack_errors, where each bucket contains entries with stack name, position, SHA, title, PR/MR number, URL, CI status, and optional behind-base count. stack_inbox remains atomic; it does not stream JSONL events. A successful tool call can still contain refresh_failed entries with refresh_error, so callers must inspect those fields (and stack_errors) before treating the inbox as complete.

stack_status

Get a quick status summary of the current stack.

Parameters: None.

Returns: Stack name, base branch, total commits, synced commits, current position, and how many commits behind the base branch.

pr_info

Get detailed information about a specific PR/MR by number.

Parameters:

  • number (integer, required): The PR/MR number to look up.

Returns: PR number, title, state (open/merged/closed/draft), URL, draft status, approval status, mergeability, and CI status.

config_show

Show the current git-gud configuration for this repository.

Parameters: None.

Returns: Provider, base branch, branch username, lint commands, and boolean settings (including compatibility field auto_add_gg_ids, which is always returned as true).

Write Tools

stack_checkout

Create a new stack or switch to an existing one.

Parameters:

  • name (string, optional): Stack name.
  • base (string, optional): Base branch (default: main/master).
  • worktree (boolean, optional): Use a git worktree for isolation.

stack_sync

Push branches and create/update PRs/MRs for the current stack.

Parameters:

  • draft (boolean, optional): Create PRs as draft.
  • force (boolean, optional): Force-push branches.
  • update_descriptions (boolean, optional): Update PR descriptions from commit messages.
  • update_title (boolean, optional): Update PR titles from commit messages.
  • no_rebase_check (boolean, optional): Skip rebase-needed check.
  • lint (boolean, optional): Run lint before syncing.
  • until (string, optional): Only sync up to this position/GG-ID/SHA.

stack_land

Merge approved PRs/MRs from the current stack.

Parameters:

  • all (boolean, optional): Land all approved PRs.
  • squash (boolean, optional): Use squash merge.
  • auto_clean (boolean, optional): Auto-clean the stack after landing.
  • until (string, optional): Only land up to this position/GG-ID/SHA.

stack_clean

Clean up stacks whose PRs have been merged.

Parameters:

  • all (boolean, optional): Clean all merged stacks.

stack_rebase

Rebase the current stack onto the latest base branch.

Parameters:

  • target (string, optional): Target branch to rebase onto.

stack_squash

Squash (amend) staged changes into the current commit.

Parameters:

  • all (boolean, optional): Stage all changes first.

stack_absorb

Auto-absorb staged changes into the correct commits.

Parameters:

  • dry_run (boolean, optional): Show what would be absorbed.
  • and_rebase (boolean, optional): Rebase after absorbing.
  • whole_file (boolean, optional): Absorb whole files.
  • one_fixup_per_commit (boolean, optional): One fixup per target commit.
  • squash (boolean, optional): Squash fixups immediately.

stack_reconcile

Reconcile out-of-sync branches pushed outside of gg.

Parameters:

  • dry_run (boolean, optional): Show what would change.

stack_move

Move to a specific commit in the stack.

Parameters:

  • target (string, required): Position number, GG-ID, or SHA prefix.

stack_navigate

Navigate within the stack.

Parameters:

  • direction (string, required): "first", "last", "prev", or "next".

stack_lint

Run configured lint commands on each commit.

Parameters:

  • until (integer, optional): Only lint up to this position.

stack_drop

Remove commits from the stack.

Parameters:

  • targets (array of strings, required): Commits to drop—positions (1-indexed), short SHAs, or GG-IDs.

Notes: Always uses --force (the agent is expected to confirm with the user before calling). Returns JSON with dropped commits.

stack_split

Split a commit into two by moving specified files to a new commit.

Parameters:

  • commit (string, optional): Target commit—position (1-indexed), short SHA, or GG-ID. Defaults to the current commit.
  • files (array of strings, required): Files to include in the new commit.
  • message (string, optional): Message for the new (first) commit.
  • no_edit (boolean, optional): Don’t prompt for the remainder commit message.

Notes: File-level only (no hunk selection via MCP). The new commit is inserted before the original.

stack_reorder

Reorder commits in the stack with an explicit order.

Parameters:

  • order (string, required): New order as positions (1-indexed), e.g., "3,1,2" or "3 1 2".

Notes: No TUI via MCP. The order specifies the new bottom-to-top arrangement of commits.

stack_undo

Reverse the local ref/HEAD effects of the most recent mutating gg command (or a specific operation by id). Shell-out wrapper around gg undo --json.

Parameters:

  • operation_id (string, optional): Target a specific record (see stack_undo_list). Defaults to the most-recent-undoable operation.

Notes: Refuses on remote-touching operations (sync, land) — the returned payload includes a refusal.reason of remote plus a provider-specific revert hint (e.g. gh pr close <n>, git push --delete …). Agents must surface the hint to the user rather than attempt silent remote rollback. Also refuses on interrupted, stale, and unsupported_schema records; the working tree is never modified.

stack_undo_list

List recent operations from the per-repo operation log (newest-first). Shell-out wrapper around gg undo --list --json.

Parameters:

  • limit (integer, optional): Cap the number of records returned (default: 20).

Notes: Each entry carries is_undoable (gate for safe local replay) and, for undo records, is_undo + undoes (the operation id being reversed). Remote-touching ops appear with is_undoable: false and touched_remote: true.

Transport

The MCP server uses stdio transport (JSON-RPC over stdin/stdout), which is the standard for local MCP tools. No network configuration is needed.

Configuration

git-gud uses a layered configuration system:

  1. Global config: ~/.config/gg/config.json — shared defaults across all repos
  2. Local config: .git/gg/config.json — per-repository settings

Local config always takes precedence over global config.

Setup

Initialize or update local config with:

gg setup        # Quick mode: essential settings only
gg setup --all  # Full mode: all settings organized by category

For global config, manually create ~/.config/gg/config.json with your preferred defaults.

Example config

{
  "defaults": {
    "provider": "gitlab",
    "base": "main",
    "branch_username": "your-username",
    "lint": [
      "cargo fmt --check",
      "cargo clippy -- -D warnings"
    ],
    "auto_add_gg_ids": true,
    "unstaged_action": "ask",
    "land_wait_timeout_minutes": 30,
    "land_admin": false,
    "land_auto_clean": false,
    "sync_auto_lint": false,
    "sync_auto_rebase": false,
    "sync_behind_threshold": 1,
    "sync_draft": false,
    "sync_update_descriptions": true,
    "sync_update_title": false,
    "worktree_base_path": "/tmp/gg-worktrees",
    "github": {
      "stacks_integration": "auto"
    },
    "gitlab": {
      "auto_merge_on_land": false
    }
  }
}

defaults options

OptionTypeWhat it controlsDefault
providerstringProvider (github/gitlab) for self-hosted or explicit overrideAuto-detected
basestringDefault base branch for new stacksAuto-detected
branch_usernamestringUsername prefix in stack/entry branch namesAuto-detected
lintstring[]Commands used by gg lint / gg sync --lint[]
auto_add_gg_idsbooleanDeprecated compatibility field. gg always enforces GG metadata normalization, regardless of this value.true
unstaged_actionstringDefault behavior for gg sc/gg amend when unstaged changes exist: ask, add, stash, continue, or abortask
land_wait_timeout_minutesnumberTimeout for gg land --wait polling30
land_adminbooleanUse admin privileges to bypass approval requirements on land (GitHub only)false
land_auto_cleanbooleanAuto-run cleanup after full landingfalse
sync_auto_lintbooleanAutomatically run gg lint before gg syncfalse
sync_auto_rebasebooleanAutomatically run gg rebase before gg sync when behind threshold is reachedfalse
sync_behind_thresholdnumberWarn/rebase in gg sync when base is at least this many commits behind origin/<base> (0 disables check)1
sync_draftbooleanCreate new PRs/MRs as drafts by defaultfalse
sync_update_descriptionsbooleanUpdate PR/MR descriptions on re-synctrue
sync_update_titlebooleanUpdate PR/MR titles on re-sync. A GitLab draft keeps its existing prefix if the commit subject has none.false
stack_nav_commentsbooleanPost a managed navigation comment on each open PR/MR in a multi-entry stack, listing all entries with a 👉 marker on the current one. When set back to false, the next gg sync removes any previously-posted managed comments. Skipped for single-entry stacks and when --until limits a sync.false
worktree_base_pathstringBase directory for managed worktreesParent of repo
github.stacks_integrationoff | auto | forceGitHub Stacked PRs public-preview integration. off never inspects or updates it; auto attempts it when the optional gh stack extension and repository support are available; force uses the same safe behavior but reports unavailable capabilities as warnings. Ordinary GitHub sync works without the extension.auto
gitlab.auto_merge_on_landbooleanDefault GitLab auto-merge behavior for gg landfalse

Global Config

Store shared defaults in ~/.config/gg/config.json. This is useful for:

  • Organization-wide settings (e.g., always use drafts)
  • Personal preferences that apply to all your repos
  • Reducing repetitive setup across multiple repositories

Example global config:

{
  "defaults": {
    "sync_draft": true,
    "land_auto_clean": true,
    "sync_behind_threshold": 5
  }
}

When gg setup runs in a new repo, these global defaults will be shown in prompts. You can accept them or override per-repo.

Stack state

git-gud also stores stack-specific state in the local config file (for example PR/MR mappings by GG-ID). This is how it remembers which commit corresponds to which PR/MR over time.

Schema versions

gg versions the state it writes so that mixing binaries never silently drops data:

  • .git/gg/config.json carries a top-level schema_version: 2, or 3 while a remote change is pending (for example a queued branch deletion). A config without one is version 1 and is upgraded on the next save. gg v0.10.13 and older refuse to rewrite a version-3 config. A queued deletion is cleared when it finishes or proves unnecessary: gg clean runs the deletions gg land queued, gg sync or gg clean of the stack runs the ones gg drop queued, and gg reconcile --discard-pending drops one you no longer want (the remote branch is then left in place).
  • Each operation record in .git/gg/operations/ carries its own schema_version, and each record is written at the lowest version its content needs: 2 for a single-step command (gg co, gg drop, …), which older releases read and undo normally, and 3 for a command recorded in several checkpoints (a multi-step gg sync, gg land or gg clean) or one that records a review retarget or squash-setting change.

The versions change only when an older gg would lose or misread what a newer one writes, not on every release; patch releases that share a schema work together freely.

If a file was written by a newer gg than the one you are running, commands that only read state (gg ls, gg log, gg undo --list, gg reconcile --dry-run) still work, but any command that would rewrite that file stops before changing anything, with:

.git/gg/config.json was written by a newer gg (schema 3, this gg supports 2). Upgrade gg to modify this repository.

Upgrade gg (on every machine and tool that shares the repository) before running mutating commands again. Releases before v0.10.12 do not perform this check. They list schema-3 records but treat them as not undoable, so a plain gg undo run by an older release skips a newer multi-step command and reverts the newest record it does understand.

PR/MR templates

You can customize descriptions by creating .git/gg/pr_template.md.

Supported placeholders:

  • {{title}}
  • {{description}}
  • {{stack_name}}
  • {{commit_sha}}

Example:

## Summary

{{description}}

---

**Stack:** `{{stack_name}}`
**Commit:** `{{commit_sha}}`

Shell Integration and Completions

Shell integration

Shell integration enables parent-shell features. Today that means gg co <stack> --wt can move your shell into the created or reused worktree after the command succeeds.

Add the matching line to your shell config:

# Bash
eval "$(gg init bash)"

# Zsh
eval "$(gg init zsh)"

# Fish
gg init fish | source

Without shell integration, gg co --wt still creates or reuses the worktree and prints its path, but your shell stays in the original checkout.

Shell completions

Generate completions with:

gg completions <shell>

Supported shells include: bash, zsh, fish, elvish, powershell.

Bash

mkdir -p ~/.local/share/bash-completion/completions
gg completions bash > ~/.local/share/bash-completion/completions/gg

Zsh

mkdir -p ~/.zfunc
gg completions zsh > ~/.zfunc/_gg

Then in ~/.zshrc:

fpath=(~/.zfunc $fpath)
autoload -Uz compinit && compinit

Fish

mkdir -p ~/.config/fish/completions
gg completions fish > ~/.config/fish/completions/gg.fish

Troubleshooting / FAQ

gh or glab is missing

Install the provider CLI:

Not authenticated with provider

gh auth login
glab auth login

“Not on a stack branch”

You’re on a branch that doesn’t match the stack naming scheme, <username>/<stack-name>. If branch_username is configured, gg prints a rename hint like git branch -m <username>/<stack-name>.

gg co <stack-name>

I pushed with git push and now mappings are wrong

Run reconcile:

gg reconcile --dry-run
gg reconcile

A command stopped and says to run gg reconcile

An earlier gg sync, gg land or gg clean sent a request and never saw the answer, and the forge could not tell gg what happened. See what is pending and what each marker resolves to, then apply it:

gg reconcile --dry-run
gg reconcile

If a marker stays undetermined after the forge is reachable again, check the review on the forge and abandon it with gg reconcile --discard-pending. See gg reconcile.

Merge commits are not supported

Stacks require linear history. Rebase your branch:

git rebase main

gg land --wait times out

Increase timeout in config:

{
  "defaults": {
    "land_wait_timeout_minutes": 60
  }
}

For GitLab merge trains, gg land --wait may show that GitLab has not reported an MR in the train yet. That is a polling state after queueing, not an immediate failure. gg keeps waiting until this timeout unless GitLab reports a terminal state such as closed, skipped, or failed CI.

When should I use gg absorb vs gg sc?

  • Use gg sc when you’re on the exact commit you want to modify.
  • Use gg absorb when staged edits belong to multiple commits and you want git-gud to distribute them.

How do I undo a gg command?

Run gg undo. It reverses the local ref/HEAD effects of the most recent mutating gg command (drop, squash, split, unstack, rebase, reorder, absorb, reconcile, checkout, nav, clean, sync, land, or run --amend). Working-tree changes are not touched.

gg undo              # reverse the last local operation
gg undo --list       # see the recent operation log
gg undo <op_id>      # target a specific record
gg undo; gg undo     # undo then redo — a second undo reverses the first

Remote-touching operations (sync, land) are recorded but refused for local replay. gg undo prints a provider-specific revert hint (e.g. gh pr close <n>, git push --delete …) instead of silently rewriting published history. See gg undo for the full refusal matrix and JSON schema.