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
Who's talking about github/gh-stack
- ggml-org/llama.cpp“RPC: add `-sm tensor`”GitHub · Aug 5, 2026 · 11 reactions
- isledecomp/isle“ReproBit: certified byte-identical reproduction”GitHub · Aug 31, 2026 · 4 reactions
- voidzero-dev/vite-plus“feat: ship a Renovate preset and dependency-bot docs for lockstep updates”GitHub · Aug 16, 2026 · 4 reactions
- FrancisDeea/pocketool“chore: refresh favicon and app icon branding”GitHub · Aug 13, 2026 · 4 reactions
- anchildress1/supascribe-notes-mcp“docs(agents): rewrite all AGENTS.md files for AI-only consumption”GitHub · Aug 13, 2026 · 4 reactions
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
- Aug 5, 2026RPC: add `-sm tensor` — ggml-org/llama.cpp11 reactions · 38 comments
- Aug 31, 2026ReproBit: certified byte-identical reproduction — isledecomp/isle4 reactions · 1 comment
- Aug 16, 2026feat: ship a Renovate preset and dependency-bot docs for lockstep updates — voidzero-dev/vite-plus4 reactions · 3 comments
- Aug 13, 2026chore: refresh favicon and app icon branding — FrancisDeea/pocketool4 reactions · 2 comments
- Aug 13, 2026docs(agents): rewrite all AGENTS.md files for AI-only consumption — anchildress1/supascribe-notes-mcp4 reactions · 1 comment
36 more on GitHub
- Sep 21, 2026agent/parakeet perf resident — joshuaswarren/ane-linux-experiments3 reactions · 2 comments
- Aug 30, 2026test(shm): prove bounded peer reclamation — ahrav/magic-context3 reactions · 4 comments
- Aug 30, 2026feat(e2e): wire metamorphic evaluation CI — ahrav/magic-context3 reactions · 3 comments
- Aug 30, 2026feat(e2e): add metamorphic invariant transforms — ahrav/magic-context3 reactions · 3 comments
- Aug 29, 2026ci: add Dreamer eval lane and harden evidence — ahrav/magic-context3 reactions · 3 comments
- Aug 27, 2026feat(memory): warn before repeating rejected approaches — ahrav/magic-context3 reactions · 3 comments
- Aug 27, 2026feat(memory): capture rejected approaches — ahrav/magic-context3 reactions · 7 comments
- Aug 27, 2026fix(memory): exclude rejected approaches from native memory — ahrav/magic-context3 reactions · 3 comments
- Aug 26, 2026feat(module): stage and mirror canonical claim operations — ahrav/magic-context3 reactions · 6 comments
- Aug 26, 2026feat(claims): establish the direct claim contract — ahrav/magic-context3 reactions · 5 comments
- Aug 19, 2026fix(ssr): rewrite computed key of destructing parameter — vitejs/vite3 reactions
- Aug 6, 2026[LoopVectorize] Support vectorization of compressing patterns — llvm/llvm-project3 reactions · 39 comments
- Jul 20, 2026docs: finish demo stack README (layer 3) — e2b-dev/runtime3 reactions
- Jul 20, 2026docs: extend demo stack README (layer 2) — e2b-dev/runtime3 reactions
- Jul 20, 2026docs: add demo stack README (layer 1) — e2b-dev/runtime3 reactions
- Oct 4, 2026fix(policy): refuse project-scope policy check and apply from home — kenryu42/cc-safety-net2 reactions · 4 comments
- Oct 3, 2026Improve LocalExecutor bookkeeping: correctly add tasks to the `running` list — apache/airflow2 reactions · 1 comment
- Oct 3, 2026ci: start packed-runtime with the source checks and audit dependencies last — kenryu42/cc-safety-net2 reactions · 4 comments
- Oct 3, 2026fix(gate): unwrap caffeinate as a built-in exec wrapper — kenryu42/cc-safety-net2 reactions · 4 comments
- Oct 2, 2026更新资源包到 3.1.41 — YUCLing/open-orpheus2 reactions · 2 comments
- Sep 29, 2026docs 483/filter chatlogs/dr and options — aglabo/chatlog-exporter2 reactions
- Sep 29, 2026fix: fail OpenCode v2 install on a failed plugin, protect v1 config.json, settle the OpenClaw enable race — kenryu42/cc-safety-net2 reactions · 4 comments
- Sep 29, 2026fix(detect): follow relocated config homes and report Codex trust, Copilot repo overrides, and OpenCode v2 failures — kenryu42/cc-safety-net2 reactions · 4 comments
- Sep 29, 2026fix(openclaw): re-enable the plugin a reinstall after uninstall leaves disabled, and honor OPENCLAW_HOME — kenryu42/cc-safety-net2 reactions · 6 comments
- Sep 29, 2026fix(hermes): analyze file tools in Hermes' directory and install into the active profile — kenryu42/cc-safety-net2 reactions · 4 comments
- Sep 29, 2026fix(hosts): analyze commands from the Monitor, monitor and powershell shell tools — kenryu42/cc-safety-net2 reactions · 4 comments
- Sep 20, 2026fix(test): prevent orphaned fixture process trees — prvious/pv2 reactions · 3 comments
- Sep 20, 2026fix(test): prevent daemon fixture failures from hanging CI — prvious/pv2 reactions · 3 comments
- Sep 17, 2026chore(dev): ignore extra env files in worktrees — saldanaj97/atlaris2 reactions · 5 comments
- Sep 17, 2026feat(ui): refine maintenance page to match design — saldanaj97/atlaris2 reactions · 6 comments
- Sep 10, 2026Publish the Lister program pattern rename — asimov-specs/asimov-specs.github.io2 reactions
- Sep 10, 2026Publish the Matcher program pattern — asimov-specs/asimov-specs.github.io2 reactions
- Sep 5, 2026feat(cli): show reconciliation queue and phase progress — prvious/pv2 reactions · 7 comments
- Sep 4, 2026perf(daemon): isolate blocking reconciliation operations — prvious/pv2 reactions · 6 comments
- Sep 4, 2026perf(resources): share manifest snapshot and bound artifact downloads — prvious/pv2 reactions · 3 comments
- Aug 29, 2026fix: show account import verification errors — near/near-cli-rs2 reactions · 2 comments
On Bluesky · 4
- Aug 20, 2026gh-stack : une extension GitHub CLI pour gérer les stacked PRs, découper un gros changement en une chaîne de petites PRs liées, avec rebase… — @camilleroux.com2 likes and reposts · 3 replies
- Aug 15, 2026Native stacked PR support plus a CLI workflow removes a lot of day-to-day branch friction. https://github.com/github/gh-stack — @u11g.com2 likes and reposts
- Aug 15, 2026gh-stack : extension GitHub CLI pour gérer les stacked PRs — @news.humancoders.com2 likes and reposts
- Aug 6, 2026מעניין שגיטאהב נכנסו חזק לעניין הזה של Stacked PR, עכשיו גם CLI+Skill, זה בטח קשור לAI איכשהו. אבל ממה שניסיתי, הם מתייחסים לכל הStack כאל… — @baruchiro.com1 likes and repost
On Hacker News · 1
- Aug 3, 2026GitHub/gh-stack: GitHub Stacked PRs1 point
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.
- .github/copilot-instructions.mdCopilot instructions
- gh-stackSkill
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
- Very specific: line 16
Always run go vet before go test.
- Very specific: line 80
Use typed exit codes defined in cmd/utils.go:
- Very specific: line 106
Config: Use config.NewTestConfig() which returns (*Config, stdoutReader, stderrReader) with captured I/O and no-op color functions.
- Very specific: line 107
Git mocking: Call git.SetOps(&git.MockOps{...}).
- Very specific: line 110
Stack file setup: Use stack.Load(dir) after writing a stack file to get correct checksums for Save.
≈ “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.
Files
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 detectionAlways 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)
| Group | Commands |
| Stack management | init, add, view, checkout, modify, unstack |
| Remote operations | submit, sync, rebase, push, link, merge |
| Navigation | switch, up, down, top, bottom, trunk |
| Utilities | alias, feedback |
Coding patterns
Command structure
Each command lives in its own file (cmd/<name>.go) and follows this pattern:
- Define an
<name>Optionsstruct for flags/args. - Export a
<Name>Cmd(cfg *config.Config) *cobra.Commandconstructor. - Implement logic in a private
run<Name>(cfg, opts, args)function. - The
RunEfield on the command callsrun<Name>.
Error handling
Use typed exit codes defined in cmd/utils.go:
| Code | Sentinel | Meaning |
| 1 | ErrSilent | Error already printed |
| 2 | ErrNotInStack | Branch/stack not found |
| 3 | ErrConflict | Rebase conflict |
| 4 | ErrAPIFailure | GitHub API error |
| 5 | ErrInvalidArgs | Invalid arguments or flags |
| 6 | ErrDisambiguate | Multiple stacks/remotes, can't auto-select |
| 7 | ErrRebaseActive | Rebase already in progress |
| 8 | ErrLockFailed | Stack file lock contention |
| 9 | ErrStacksUnavailable | Stacked PRs not enabled for repository |
| 10 | ErrModifyRecovery | Modify 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.gofor 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. Alwaysdefer restore()to prevent test pollution. - GitHub mocking: Set
cfg.GitHubClientOverride = &github.MockClient{...}. - Prompt mocking: Set
cfg.SelectFn,cfg.ConfirmFn, orcfg.InputFnon the config to simulate interactive input. - Stack file setup: Use
stack.Load(dir)after writing a stack file to get correct checksums forSave.
Key interfaces
git.Ops(internal/git/gitops.go): wraps git CLI calls. Package-level functions (e.g.,git.CurrentBranch()) delegate to a swappable package-levelopsvariable.git.ForWorktree(path)returns an explicitly scoped executor for HEAD/index/working-file operations. Never switch production context withos.Chdirorgit.SetOps; reserveSetOpsfor 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, andIsCherryPickInProgressreturn(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 useRepoMergeConfig(GraphQL: allowed merge methods + viewer's default),BaseBranchUsesMergeQueue(GraphQL: detects a base-branch merge queue to select the explicitmerge_action),MergeStackAsync, andGetAsyncMergeResult(/repos/{owner}/{repo}/pulls/{n}/merge-async). Injected viacfg.GitHubClientOverridein 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. UsestackStateDir(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-scopednumber(int, shown in the GitHub UI and used as the primary way to reference a stack, e.g.gh stack checkout <number>).numbermay be0for stack files created before it was tracked; it is backfilled from the API on the next stack operation. - Locking:
<common-dir>/gh-stack.lockprotects short catalog saves;<common-dir>/gh-stack-operation.lockserializes clone-wide mutations. AcquirebeginStackMutationbefore snapshots/preflight and defer its cleanup. Never hold a catalog lock across Git operations or call lock-takingstack.Savewhile already holding that lock. Errors surface asLockError. - 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 lastContext.TouchedSHA 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.worktreebacklinks, including the mainconfig.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/)
| Workflow | Trigger | What it does |
test.yml | push to main, PRs | go vet + go test -race -count=1 ./... on 3 OS matrix |
release.yml | v* tags | Cross-platform precompiled binaries via cli/gh-extension-precompile |
docs.yml | push to main (docs/**) | Builds Astro/Starlight docs, deploys to GitHub Pages |
Non-obvious things
- The
Queuedfield onBranchRefis transient (populated from GitHub API, never persisted to the stack JSON file). git.SetOps()replaces the package-level ops variable. Forgettingdefer restore()in a test will break every subsequent test in the package.- Interrupt detection: Ctrl+C is caught as
terminal.InterruptErr, wrapped into anerrInterruptsentinel, 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 gccannot 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
.gitignoreignores/gh-stackand/gh-stack.exe(the built binary).
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
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.

