agentleFS
GitHubKnown publishergithub/gh-stack/AGENTS.md

gh-stack

AGENTS.md1.6k starsChanged 59 days agoMITView on GitHub

A GitHub CLI (gh) extension for managing stacked branches and pull requests. Written in Go, it automates creating branches, keeping them rebased, setting PR base branches, and navigating between stack layers. Repository operations require Git 2.36 or later. Always run go vet before go test. CI runs both on every push/PR across ubuntu, windows, and macOS (test.yml). There is no Makefile, linter config, or code generation step. The standard Go toolchain is all that's needed. Each command lives in its…

Trending

Less talk lately.about the whole repository

Dec 2025: 0 mentionsJan 2026: 0 mentionsFeb 2026: 0 mentionsMar 2026: 0 mentionsApr 2026: 0 mentionsMay 2026: 0 mentionsJun 2026: 0 mentionsJul 2026: 3 mentionsAug 2026: 22 mentionsSep 2026: 16 mentionsOct 2026: 5 mentionsNov 2026: 0 mentions
Dec 2025Jun 2026Nov 2026
Mentions a month of the github/gh-stack repository that our weekly crawl found. There is no adoption data for this file yet.

Who's talking about github/gh-stack

The biggest 5 of 46 mentions linking to the repository that our crawl found. Each line is their own headline.

See all 46

Talked about on GitHub, Bluesky and Hacker News (46 times).

On GitHub · 41

36 more on GitHub

On Hacker News · 1

  • Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.

    Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

  • In this repository2 other files it gives its agents.

The file

We split this AGENTS.md into the rules it gives an agent

5 rules. About 0 are common, 0 are distinctive, and 5 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 5

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Always run go vet before go test.

    line 16
  2. Very specific:

    Use typed exit codes defined in cmd/utils.go:

    line 80
  3. Very specific:

    Config: Use config.NewTestConfig() which returns (*Config, stdoutReader, stderrReader) with captured I/O and no-op color functions.

    line 106
  4. Very specific:

    Git mocking: Call git.SetOps(&git.MockOps{...}).

    line 107
  5. Very specific:

    Stack file setup: Use stack.Load(dir) after writing a stack file to get correct checksums for Save.

    line 110

≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

gh-stack: Agent Instructions

A GitHub CLI (gh) extension for managing stacked branches and pull requests. Written in Go, it automates creating branches, keeping them rebased, setting PR base branches, and navigating between stack layers.

Repository operations require Git 2.36 or later.

Build, test, and validate

go mod download                  # install dependencies
go build -o gh-stack .           # build (produces ./gh-stack binary)
go vet ./...                     # static analysis. Run before tests.
go test -race -count=1 ./...     # all tests with race detection

Always run go vet before go test. CI runs both on every push/PR across ubuntu, windows, and macOS (test.yml).

There is no Makefile, linter config, or code generation step. The standard Go toolchain is all that's needed.

Install locally as a gh extension

go build -o gh-stack .
gh extension remove stack 2>/dev/null
gh extension install .

Project structure

main.go                      # entrypoint. Calls cmd.Execute().
cmd/                         # Cobra commands (one file per command + tests)
  root.go                    # registers all subcommands in four groups
  utils.go                   # shared helpers, ExitError types, exit codes
internal/
  git/                       # git.Ops interface + defaultOps (exec-based)
    gitops.go                # Ops interface, including scoped worktree execution
    mock_ops.go              # MockOps. Each method has a corresponding *Fn field.
  github/                    # github.ClientOps interface + real Client
    client_interface.go      # ClientOps interface (18 methods)
    mock_client.go           # MockClient. Uses function-pointer fields for testing.
  stack/                     # common-directory catalog, JSON schema, migration, locking
    schema.json              # JSON Schema for the stack file format
  config/                    # Config struct (I/O, colors, test overrides)
    testing.go               # NewTestConfig(). Returns *Config + stdout/stderr pipes.
  branch/                    # branch naming (Slugify, DateSlug)
  modify/                    # interactive stack modification state machine
  worktree/                  # operation-owned worktree identities and ref recovery
  pr/                        # PR template discovery
  tui/                       # bubbletea/bubbles/lipgloss terminal UI
    stackview/               # interactive stack visualization
    modifyview/              # interactive modify session UI
    shared/                  # shared TUI types
docs/                        # Astro + Starlight documentation site
skills/                      # AI agent skill definition (SKILL.md)

Command groups (registered in cmd/root.go)

GroupCommands
Stack managementinit, add, view, checkout, modify, unstack
Remote operationssubmit, sync, rebase, push, link, merge
Navigationswitch, up, down, top, bottom, trunk
Utilitiesalias, feedback

Coding patterns

Command structure

Each command lives in its own file (cmd/<name>.go) and follows this pattern:

  1. Define an <name>Options struct for flags/args.
  2. Export a <Name>Cmd(cfg *config.Config) *cobra.Command constructor.
  3. Implement logic in a private run<Name>(cfg, opts, args) function.
  4. The RunE field on the command calls run<Name>.

Error handling

Use typed exit codes defined in cmd/utils.go:

CodeSentinelMeaning
1ErrSilentError already printed
2ErrNotInStackBranch/stack not found
3ErrConflictRebase conflict
4ErrAPIFailureGitHub API error
5ErrInvalidArgsInvalid arguments or flags
6ErrDisambiguateMultiple stacks/remotes, can't auto-select
7ErrRebaseActiveRebase already in progress
8ErrLockFailedStack file lock contention
9ErrStacksUnavailableStacked PRs not enabled for repository
10ErrModifyRecoveryModify session interrupted

Return these from RunE. Never call os.Exit() directly from commands. Check with:

var exitErr *ExitError
if errors.As(err, &exitErr) { ... }

Testing patterns

  • Framework: stretchr/testify (assert, require) for assertions.
  • Table-driven tests are the norm. See cmd/utils_test.go for examples.
  • Config: Use config.NewTestConfig() which returns (*Config, stdoutReader, stderrReader) with captured I/O and no-op color functions.
  • Git mocking: Call git.SetOps(&git.MockOps{...}). It returns a restore function. Always defer restore() to prevent test pollution.
  • GitHub mocking: Set cfg.GitHubClientOverride = &github.MockClient{...}.
  • Prompt mocking: Set cfg.SelectFn, cfg.ConfirmFn, or cfg.InputFn on the config to simulate interactive input.
  • Stack file setup: Use stack.Load(dir) after writing a stack file to get correct checksums for Save.

Key interfaces

  • git.Ops (internal/git/gitops.go): wraps git CLI calls. Package-level functions (e.g., git.CurrentBranch()) delegate to a swappable package-level ops variable. git.ForWorktree(path) returns an explicitly scoped executor for HEAD/index/working-file operations. Never switch production context with os.Chdir or git.SetOps; reserve SetOps for tests. GitDir() remains per-worktree; CommonDir() is repository-wide.
  • Scoped Git errors: ForWorktree(path) returns (Ops, error) and no executor for invalid contexts. Each scoped operation rechecks directory identity. BranchExists, HasStagedChanges, IsRebaseInProgress, and IsCherryPickInProgress return (bool, error); callers must handle lookup failures before mutating Git or recovery state, not treat them as absence.
  • github.ClientOps (internal/github/client_interface.go): 18 methods for GitHub API (PRs, stacks, merges). Stack operations use the public Stacks REST API (/repos/{owner}/{repo}/stacks): ListStacks, FindStackForPR, GetStack, CreateStack, AddToStack (delta append), Unstack. Async stack merges use RepoMergeConfig (GraphQL: allowed merge methods + viewer's default), BaseBranchUsesMergeQueue (GraphQL: detects a base-branch merge queue to select the explicit merge_action), MergeStackAsync, and GetAsyncMergeResult (/repos/{owner}/{repo}/pulls/{n}/merge-async). Injected via cfg.GitHubClientOverride in tests.
  • config.Config (internal/config/config.go): Central configuration passed to all commands. Holds I/O streams, color functions, and test hook fields (SelectFn, ConfirmFn, InputFn, RepoOverride).

Stack file

  • Location: <common-dir>/gh-stack (JSON format, schema version 1), shared by all linked worktrees. Use stackStateDir(cfg) for app storage; it also selects original-worktree catalogs during legacy recovery.
  • Schema: internal/stack/schema.json.
  • Identity: each stack stores GitHub's global id (string) and repo-scoped number (int, shown in the GitHub UI and used as the primary way to reference a stack, e.g. gh stack checkout <number>). number may be 0 for stack files created before it was tracked; it is backfilled from the API on the next stack operation.
  • Locking: <common-dir>/gh-stack.lock protects short catalog saves; <common-dir>/gh-stack-operation.lock serializes clone-wide mutations. Acquire beginStackMutation before snapshots/preflight and defer its cleanup. Never hold a catalog lock across Git operations or call lock-taking stack.Save while already holding that lock. Errors surface as LockError.
  • Staleness: Concurrent modifications detected via StaleError.
  • Migration: Consolidate only nonconflicting legacy catalogs and preserve originals. Stop on conflicting definitions; finish legacy recovery in its original worktree before migrating. Do not mix old and new writers.
  • Recovery: gh-stack journals live in the common directory and record origin/owner identities, original refs, and progress. Native Git markers remain per-worktree. Continue/abort must use recorded scoped executors, match stack identity (not catalog array position), and retain state on any partial restore or save failure.
  • External changes: Mutation locks coordinate gh-stack, not arbitrary Git commands or editors. Keep affected worktrees quiescent during rewrites, except for requested conflict resolution while paused. Call Context.Start(branch, expectedSHA) before ref mutations: use the original snapshot SHA, or the last Context.Touched SHA for a branch already changed by this operation. Do not adopt a freshly read tip as this operation's baseline during continuation.
  • Separate Git directories: Main-worktree invocation and existing absolute/relative core.worktree backlinks, including the main config.worktree, are supported. The discovery caveat is only linked invocation without a main-worktree backlink: fail actionably if that owner is required, but allow unaffected worktrees to proceed. Never infer a working directory from an administration path, emit it as a successful navigation target, or add a private registry/config mutation to guess ownership.
  • Distributed modify: Preflight the staged actions and surviving cascade branches before mutation. Run renames and history rewrites in recorded owners, using the origin only for unoccupied branches. Persist execution progress, rename aliases, created refs, and last-written heads. Before native continuation, preflight other target worktrees; the pending worktree is intentionally busy and its later branches are checked after continuation. Never switch a foreign owner to another branch, reset external commits, delete a preserved source branch/worktree, or clear a partially restored journal.
  • Journal transition: Complete paused operations before switching preview stages or versions. Unmarked rebase/sync journals with a worktree context use distributed recovery. Reject executionMode: "origin-only" before context-based routing or mutation; preserve its bytes and require the matching layer3 build in the recorded origin. Unknown nonempty modes also fail closed. Empty-mode journals without a context retain the legacy original-catalog route.

CI workflows (.github/workflows/)

WorkflowTriggerWhat it does
test.ymlpush to main, PRsgo vet + go test -race -count=1 ./... on 3 OS matrix
release.ymlv* tagsCross-platform precompiled binaries via cli/gh-extension-precompile
docs.ymlpush to main (docs/**)Builds Astro/Starlight docs, deploys to GitHub Pages

Non-obvious things

  • The Queued field on BranchRef is transient (populated from GitHub API, never persisted to the stack JSON file).
  • git.SetOps() replaces the package-level ops variable. Forgetting defer restore() in a test will break every subsequent test in the package.
  • Interrupt detection: Ctrl+C is caught as terminal.InterruptErr, wrapped into an errInterrupt sentinel, and printed with a friendly message before a silent exit.
  • Rerere: on first rebase conflict, the user is prompted to enable git rerere. If declined, a flag file prevents future prompts. tryAutoResolveRebase() loops up to 1000 times auto-continuing when rerere resolves conflicts.
  • Rebase commands disable automatic maintenance through command-local configuration so detached rerere gc cannot race conflict handling. Repository settings and unrelated Git commands are unchanged.
  • Date-preserving rebase starts use the merge backend so Git persists the date setting across conflicts. Continuations use native saved settings, not start-only date flags.
  • The .gitignore ignores /gh-stack and /gh-stack.exe (the built binary).

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.