[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6BV61QY9QTR657TD062FHYQ":3,"skill-same:01M6BV61QY9QTR657TD062FHYQ":81},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":8,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":18,"categories":19,"keywords":30,"publishedAt":53,"linkOnly":54,"markdownContent":55,"markdownBody":56,"frontMatter":57,"refName":61,"commitSha":62,"skillDirectory":63,"forksCount":15,"repositoryHtmlUrl":64,"repositoryHomepageUrl":17,"ownerHtmlUrl":65,"ownerBlogUrl":17,"ownerDescription":17,"updatedAt":66,"install":67,"resources":80},"01M6BV61QY9QTR657TD062FHYQ","gh-stack","GitHub 堆叠分支与 PR 管理","Manage stacked branches and pull requests with the gh-stack GitHub CLI extension. Use when the user wants to create, push, rebase, sync, navigate, or view stacks of dependent PRs. Triggers on tasks involving stacked diffs, dependent pull requests, branch chains, or incremental code review workflows.","使用 gh-stack GitHub CLI 扩展管理堆叠的分支和拉取请求。当用户想要创建、推送、变基、同步、导航或查看相互依赖的 PR 栈时使用。适用于涉及堆叠 diff、依赖型拉取请求、分支链或增量代码审查工作流的任务。","bnferguson\u002Fdotfiles","bnferguson","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F47749?v=4","01M6BV4H2TJKK8P14W86V1ZCPP","Brandon Ferguson","01M6BV4H7GJWTZJ1BVHQ1TX11Y",0,"MIT",null,"https:\u002F\u002Fgithub.com\u002Fbnferguson\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgh-stack\u002FSKILL.md",[20,25],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BQ6TQZN6R52WBJ9H8NRMQM","软件开发工程师","PROFESSION","适用职业",{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BR5V701HCN066VEP7H4812","代码仓库协作管理","SCENARIO","使用场景",[31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52],"gh","stack","gh stack","pull","when","navigate","github cli","branches","branch","rebase","push","code review","code","create","tasks","sync","pull requests","workflows","github","diffs","cli","review","2026-11-10 10:12:30",false,"---\nname: gh-stack\ndescription: >\n  Manage stacked branches and pull requests with the gh-stack GitHub CLI extension.\n  Use when the user wants to create, push, rebase, sync, navigate, or view stacks of\n  dependent PRs. Triggers on tasks involving stacked diffs, dependent pull requests,\n  branch chains, or incremental code review workflows.\nmetadata:\n  author: github\n  version: \"0.0.8\"\n---\n\n# gh-stack\n\n`gh stack` is a [GitHub CLI](https:\u002F\u002Fcli.github.com\u002F) extension for managing **stacked branches and pull requests**. A stack is an ordered list of branches where each branch builds on the one below it, rooted on a trunk branch (typically the repo's default branch). Each branch maps to one PR whose base is the branch below it, so reviewers see only the diff for that layer.\n\n```\nmain (trunk)\n └── auth-layer     → PR #1 (base: main)            - bottom (closest to trunk)\n  └── api-endpoints → PR #2 (base: auth-layer)\n   └── frontend     → PR #3 (base: api-endpoints)   - top (furthest from trunk)\n```\n\nThe **bottom** of the stack is the branch closest to the trunk, and the **top** is the branch furthest from the trunk. Each branch inherits from the one below it. Navigation commands (`up`, `down`, `top`, `bottom`) follow this model: `up` moves away from trunk, `down` moves toward it.\n\n## When to use this skill\n\nUse this skill when the user wants to:\n\n- Break a large change into a chain of small, reviewable PRs\n- Create, rebase, push, or sync a stack of dependent branches\n- Navigate between layers of a branch stack\n- View the status of stacked PRs\n- Tear down and rebuild a stack to remove, reorder, or rename branches\n\n## Prerequisites\n\nThe GitHub CLI (`gh`) v2.0+ must be installed and authenticated. Install the extension with:\n\n```bash\ngh extension install github\u002Fgh-stack\n```\n\nBefore using `gh stack`, configure git to prevent interactive prompts:\n\n```bash\ngit config rerere.enabled true           # remember conflict resolutions (skips prompt on init)\ngit config remote.pushDefault origin     # if multiple remotes exist (skips remote picker)\n```\n\n## Agent rules\n\n**All `gh stack` commands must be run non-interactively.** Every command invocation must include the flags and positional arguments needed to avoid prompts, TUIs, and interactive menus. If a command would prompt for input, it will hang indefinitely.\n\n1. **Always supply branch names as positional arguments** to `init`, `add`, and `checkout`. Running these commands without arguments triggers interactive prompts. Branch names are used exactly as given — a name is never prefixed or transformed, so `gh stack add refactor\u002Ffoo` creates a branch named `refactor\u002Ffoo`.\n2. **Always use `--auto` with `gh stack submit`** to auto-generate PR titles. Without `--auto`, `submit` prompts for a title for each new PR.\n3. **Always use `--json` with `gh stack view`.** Without `--json`, the command launches an interactive TUI that cannot be operated by agents. There is no other appropriate flag — always pass `--json`.\n4. **Use `--remote \u003Cname>` when multiple remotes are configured**, or pre-configure `git config remote.pushDefault origin`. Without this, `push`, `submit`, `sync`, `link`, and `checkout` trigger an interactive remote picker.\n5. **Avoid branches shared across multiple stacks.** If a branch belongs to multiple stacks, commands exit with code 6. Check out a non-shared branch first.\n6. **Plan your stack layers by dependency order before writing code.** Foundational changes (models, APIs, shared utilities) go in lower branches; dependent changes (UI, consumers) go in higher branches. Think through the dependency chain before running `gh stack init`.\n7. **Use standard `git add` and `git commit` for staging and committing.** This gives you full control over which changes go into each branch. The `-Am` shortcut is available but should not be the default approach—stacked PRs are most effective when each branch contains a deliberate, logical set of changes.\n8. **Navigate down the stack when you need to change a lower layer.** If you're working on a frontend branch and realize you need API changes, don't hack around it at the current layer. Navigate to the appropriate branch (`gh stack down`, `gh stack checkout`, or `gh stack bottom`), make and commit the changes there, run `gh stack rebase --upstack`, then navigate back up to continue.\n9. **Use `gh stack link` for external tool workflows.** When branches are managed by an external tool (jj, Sapling, etc.), use `gh stack link branch-a branch-b`. `link` does not rely on local tracking state and is intended for API-driven PR and stack management. Provide at least two branches\u002FPRs to create or update a stack, or a stack number followed by the new branches\u002FPRs to append them to the top of an existing stack (e.g. `gh stack link 7 branch-c`).\n\n**Never do any of the following — each triggers an interactive prompt or TUI that will hang:**\n- ❌ `gh stack view` or `gh stack view --short` — always use `gh stack view --json`\n- ❌ `gh stack submit` without `--auto` — always use `gh stack submit --auto`\n- ❌ `gh stack init` without branch arguments — always provide branch names\n- ❌ `gh stack add` without a branch name — always provide a branch name\n- ❌ `gh stack checkout` without an argument — always provide a PR number or branch name\n- ❌ `gh stack checkout \u003Cpr-number>` when a different local stack already exists on those branches — this triggers an unbypassable conflict resolution prompt; use `gh stack unstack` first to remove the local stack, then retry the checkout\n\n## Thinking about stack structure\n\nEach branch in a stack should represent a **discrete, logical unit of work** that can be reviewed independently. The changes within a branch should be cohesive—they belong together and make sense as a single PR.\n\n### Dependency chain\n\nStacked branches form a dependency chain: each branch builds on the one below it. This means **foundational changes must go in lower (earlier) branches**, and code that depends on them goes in higher (later) branches.\n\n**Plan your layers before writing code.** For example, a full-stack feature might be structured like this (use branch names relevant to your actual task, not these generic ones):\n\n```\nmain (trunk)\n └── data-models    ← shared types, database schema\n  └── api-endpoints ← API routes that use the models\n   └── frontend-ui  ← UI components that call the APIs\n    └── integration ← tests that exercise the full stack\n```\n\nThis is illustrative — choose branch names and layer boundaries that reflect the specific work you're doing. The key principle is: if code in one layer depends on code in another, the dependency must be in the same branch or a lower one.\n\n### Branch naming\n\nChoose a clear, descriptive branch name for each layer that reflects the concern it contains (e.g., `auth`, `api-routes`, `frontend`). Branch names are used exactly as you provide them to `init` and `add` — nothing is prepended or transformed. Slashes are allowed and are treated as part of the name (e.g., `gh stack add refactor\u002Ffoo` creates a branch named `refactor\u002Ffoo`).\n\n### Staging changes deliberately\n\nThe main reason to use `git add` and `git commit` directly is to control **which changes go into which branch**. When you have multiple files in your working tree, you can stage a subset for the current branch, commit them, then create a new branch and stage the rest there:\n\n```bash\n# You're on data-models with several new files in your working tree.\n# Stage only the model files for this branch:\ngit add internal\u002Fmodels\u002Fuser.go internal\u002Fmodels\u002Fsession.go\ngit commit -m \"Add user and session models\"\n\ngit add db\u002Fmigrations\u002F001_create_users.sql\ngit commit -m \"Add user table migration\"\n\n# Now create a new branch for the API layer and stage the API files there:\ngh stack add api-routes # created & switched to the api-routes branch\ngit add internal\u002Fapi\u002Froutes.go internal\u002Fapi\u002Fhandlers.go\ngit commit -m \"Add user API routes\"\n```\n\nThis keeps each branch focused on one concern. Multiple commits per branch are fine — the key is that all commits in a branch relate to the same logical concern, and changes that belong to a different concern go in a different branch.\n\n### When to create a new branch\n\nCreate a new branch (`gh stack add`) when you're starting a **different concern** that depends on what you've built so far. Signs it's time for a new branch:\n\n- You're switching from backend to frontend work\n- You're moving from core logic to tests or documentation\n- The next set of changes has a different reviewer audience\n- The current branch's PR is already large enough to review\n\n### One stack, one story\n\nThink of a stack from the reviewer's perspective: the stack of PRs should **tell a cohesive story** about a feature or project. A reviewer should be able to read the PRs in sequence and understand the progression of changes, with each PR being a small, logical piece of the whole.\n\n**When to use a single stack:** All the branches are part of the same feature, project, or closely related effort. Even if the work spans multiple concerns (models, API, frontend), they're all building toward the same goal.\n\n**When to create a separate stack:** The work is unrelated to your current stack — a different feature, a bug fix in an unrelated area, or an independent refactor. Don't mix unrelated work into a single stack just because you happen to be working on both. Start a new stack with `gh stack init` or switch to an existing stack with `gh stack checkout` for each distinct effort.\n\nSmall, incidental fixes (e.g., fixing a typo you noticed) can go in the current stack if they're trivial. But if a change grows into its own project, it deserves its own stack.\n\n## Quick reference\n\n| Task | Command |\n|------|---------|\n| Create a stack | `gh stack init auth` |\n| Create a stack of multiple branches | `gh stack init auth api frontend` |\n| Adopt existing branches | `gh stack init existing-branch-a existing-branch-b` |\n| Set custom trunk | `gh stack init --base develop branch-a` |\n| Add a branch to stack | `gh stack add api-routes` |\n| Add branch + stage all + commit | `gh stack add -Am \"message\" api-routes` |\n| Push branches to remote | `gh stack push` |\n| Push to specific remote | `gh stack push --remote origin` |\n| Push branches + create draft PRs | `gh stack submit --auto` |\n| Create PRs as ready for review | `gh stack submit --auto --open` |\n| Sync (fetch, rebase, push) | `gh stack sync` |\n| Sync with specific remote | `gh stack sync --remote origin` |\n| Sync and prune merged branches | `gh stack sync --prune` |\n| Rebase entire stack | `gh stack rebase` |\n| Rebase upstack only | `gh stack rebase --upstack` |\n| Rebase without trunk | `gh stack rebase --no-trunk` |\n| Continue after conflict | `gh stack rebase --continue` |\n| Abort rebase | `gh stack rebase --abort` |\n| View stack details (JSON) | `gh stack view --json` |\n| Switch branches up\u002Fdown in stack | `gh stack up [n]` \u002F `gh stack down [n]` |\n| Switch to top\u002Fbottom branch | `gh stack top` \u002F `gh stack bottom` |\n| Check out by stack number | `gh stack checkout 7` |\n| Check out by PR | `gh stack checkout 42` |\n| Check out by branch (local only) | `gh stack checkout feature-auth` |\n| Tear down the current stack to restructure it | `gh stack unstack` |\n| Tear down a specific stack by number | `gh stack unstack 7` |\n\n---\n\n## Workflows\n\n### End-to-end: create a stack from scratch\n\n```bash\n# 1. Initialize a stack with the first branch\ngh stack init auth\n# → creates auth and checks it out\n\n# 2. Write code for the first layer (auth)\ncat > auth.go \u003C\u003C 'EOF'\npackage auth\n\nfunc Middleware(next http.Handler) http.Handler {\n    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n        \u002F\u002F verify token\n        next.ServeHTTP(w, r)\n    })\n}\nEOF\n\n# 3. Stage and commit using standard git commands\ngit add auth.go\ngit commit -m \"Add auth middleware\"\n\n# You can make multiple commits on the same branch\ncat > auth_test.go \u003C\u003C 'EOF'\npackage auth\n\nfunc TestMiddleware(t *testing.T) {\n    \u002F\u002F test auth middleware\n}\nEOF\ngit add auth_test.go\ngit commit -m \"Add auth middleware tests\"\n\n# 4. When you're ready for a new concern, add the next branch\ngh stack add api-routes\n# → creates api-routes\n\n# 5. Write code for the API layer\ncat > api.go \u003C\u003C 'EOF'\npackage api\n\nfunc RegisterRoutes(mux *http.ServeMux) {\n    mux.HandleFunc(\"\u002Fusers\", handleUsers)\n}\nEOF\ngit add api.go\ngit commit -m \"Add API routes\"\n\n# 6. Add a third layer for frontend\ngh stack add frontend\n# → creates frontend\n\ncat > frontend.go \u003C\u003C 'EOF'\npackage frontend\n\nfunc RenderDashboard(w http.ResponseWriter) {\n    \u002F\u002F calls the API endpoints from the layer below\n}\nEOF\ngit add frontend.go\ngit commit -m \"Add frontend dashboard\"\n\n# ── Stack complete: auth → api-routes → frontend ──\n\n# 7. Push everything and create PRs (drafts by default)\ngh stack submit --auto\n\n# 8. Verify the stack\ngh stack view --json\n```\n\n> **Shortcut:** If you prefer a faster flow, `gh stack add -Am \"message\" branch-name` combines staging, committing, and branch creation into one command. This is useful for single-commit layers but bypasses deliberate staging.\n\n### Making mid-stack changes\n\nThis is a critical workflow for agents. When you're working on a higher layer and realize you need to change something in a lower layer (e.g., you're building frontend components but need to add an API endpoint), **navigate down to the correct branch, make the change there, and rebase**.\n\n```bash\n# You're on frontend but need to add an API endpoint\n\n# 1. Navigate to the API branch\ngh stack down\n# or: gh stack checkout api-routes\n\n# 2. Make the change where it belongs\ncat > users_api.go \u003C\u003C 'EOF'\npackage api\n\nfunc handleGetUser(w http.ResponseWriter, r *http.Request) {\n    \u002F\u002F new endpoint the frontend needs\n}\nEOF\ngit add users_api.go\ngit commit -m \"Add get-user endpoint\"\n\n# 3. Rebase everything above to pick up the change\ngh stack rebase --upstack\n\n# 4. Navigate back to where you were working\ngh stack top\n# or: gh stack checkout frontend\n\n# 5. Continue working — the API changes are now available\n```\n\n**Why this matters:** If you make API changes on the frontend branch, those changes will end up in the wrong PR. The API PR won't include them, and the frontend PR will have unrelated API diffs mixed in. Always put changes in the branch where they logically belong.\n\n### Modify a mid-stack branch and sync\n\nWhen you need to revisit a branch after the initial creation (e.g., responding to review feedback):\n\n```bash\n# 1. Navigate to the branch that needs changes\ngh stack bottom\n# or: gh stack checkout auth\n# or: gh stack checkout 42  (by PR number)\n\n# 2. Make changes and commit\ncat > auth.go \u003C\u003C 'EOF'\npackage auth\n\u002F\u002F updated implementation\nEOF\ngit add auth.go\ngit commit -m \"Fix auth token validation\"\n\n# 3. Rebase everything above this branch\ngh stack rebase --upstack\n\n# 4. Push the updated stack\ngh stack push\n```\n\n### Routine sync after merges\n\n```bash\n# Single command: fetch, rebase, push, sync PR and stack state\ngh stack sync\n\n# Sync and automatically clean up local branches for merged PRs\ngh stack sync --prune\n```\n\n> **Note for agents:** In non-interactive environments, the prune prompt is not shown. Use `--prune` explicitly to delete local branches for merged PRs.\n\n> **Note for agents:** `sync` also mirrors the stack on GitHub locally. If PRs were added to the stack on github.com, their branches are pulled down and appended to the local stack automatically. If the local and remote stacks have **diverged** (you changed the local stack while the remote stack changed differently), sync can only prompt to resolve it in an interactive terminal — in non-interactive environments it aborts the sync (nothing is pushed or updated) and exits successfully with `ℹ Sync aborted`. Resolve a divergence by unstacking and recreating the stack.\n\n### Squash-merge recovery\n\nWhen a PR is squash-merged on GitHub, the original branch's commits no longer exist in the trunk history. `gh stack` detects this automatically and uses `git rebase --onto` to correctly replay remaining commits.\n\n```bash\n# After PR #1 (auth) is squash-merged on GitHub:\ngh stack sync\n# → fetches latest, detects the merge, fast-forwards trunk\n# → rebases api-routes onto updated trunk (skips merged branch)\n# → rebases frontend onto api-routes\n# → pushes updated branches\n# → reports: \"Merged: #1\"\n\n# Verify the result\ngh stack view --json\n# → auth shows \"isMerged\": true, \"state\": \"MERGED\"\n# → api-routes and frontend show updated heads\n```\n\nIf `sync` hits a conflict during this process, it restores all branches to their pre-rebase state and exits with code 3. See [Handle rebase conflicts](#handle-rebase-conflicts-agent-workflow) for the resolution workflow.\n\n### Handle rebase conflicts (agent workflow)\n\n```bash\n# 1. Start the rebase\ngh stack rebase\n\n# 2. If exit code 3 (conflict):\n#    - Parse stderr for conflicted file paths\n#    - Read those files to find \u003C\u003C\u003C\u003C\u003C\u003C\u003C \u002F ======= \u002F >>>>>>> markers\n#    - Edit files to resolve conflicts\n#    - Stage resolved files:\ngit add path\u002Fto\u002Fresolved-file.go\n\n# 3. Continue the rebase\ngh stack rebase --continue\n\n# 4. If another conflict occurs, repeat steps 2-3\n\n# 5. If unable to resolve, abort to restore everything\ngh stack rebase --abort\n```\n\n### Parsing `--json` output\n\n```bash\n# Get stack state as JSON\noutput=$(gh stack view --json)\n\n# Check if any branch needs a rebase, and rebase if so\nneeds_rebase=$(echo \"$output\" | jq '[.branches[] | select(.needsRebase == true)] | length')\nif [ \"$needs_rebase\" -gt 0 ]; then\n  echo \"Branches need rebase, rebasing stack...\"\n  gh stack rebase\nfi\n\n# Get all open PR URLs\necho \"$output\" | jq -r '.branches[] | select(.pr.state == \"OPEN\") | .pr.url'\n\n# Find merged branches\necho \"$output\" | jq -r '.branches[] | select(.isMerged == true) | .name'\n\n# Get the current branch\necho \"$output\" | jq -r '.currentBranch'\n\n# Check if the stack is fully merged (all branches merged)\necho \"$output\" | jq '[.branches[] | .isMerged] | all'\n```\n\n### Restructure a stack (remove a branch, reorder, or rename)\n\nUse `unstack` to tear down the stack, make structural changes, then re-init:\n\n```bash\n# 1. Remove the stack (locally and on GitHub)\ngh stack unstack\n\n# 2. Make structural changes — e.g. delete a branch, reorder, rename\ngit branch -m old-branch-1 new-branch-1\n\n# 3. Re-create the stack with the new structure\ngh stack init --base main new-branch-1 new-branch-2 new-branch-3\n```\n\n---\n\n## Commands\n\n### Initialize a stack — `gh stack init`\n\nCreates a new stack. **Always provide at least one branch name as a positional argument** — running without branch arguments triggers interactive prompts that agents cannot use.\n\n```\ngh stack init [flags] \u003Cbranches...>\n```\n\n```bash\n# Create a stack with a new branch\ngh stack init auth\n# → creates auth and checks it out\n\n# Create a stack with new branches\ngh stack init branch-a branch-b branch-c\n\n# Use a different trunk branch\ngh stack init --base develop branch-a branch-b\n\n# Adopt existing branches into a stack (handled automatically if the branches exist)\ngh stack init branch-a branch-b branch-c\n```\n\n| Flag | Description |\n|------|-------------|\n| `-b, --base \u003Cbranch>` | Trunk branch (defaults to the repo's default branch) |\n\n**Behavior:**\n\n- Branch names are created exactly as given (slashes are allowed and kept as-is)\n- Creates any branches that don't already exist (branching from the trunk branch)\n- Existing branches are adopted automatically; missing branches are created from the trunk\n- Checks out the last branch in the list\n- Enables `git rerere` so conflict resolutions are remembered across rebases. On first run in a repo, this may trigger a confirmation prompt — pre-configure with `git config rerere.enabled true` to avoid it\n\n---\n\n### Add a branch — `gh stack add`\n\nAdd a new branch on top of the current stack. Must be run while on the topmost branch (or the trunk if the stack has no branches yet). **Always provide a branch name** — running without one triggers an interactive prompt.\n\n```\ngh stack add [flags] \u003Cbranch>\n```\n\n**Recommended workflow — create the branch, then use standard git:**\n\n```bash\n# Create a new branch and switch to it\ngh stack add api-routes\n\n# Write code, stage deliberately, and commit\ngit add internal\u002Fapi\u002Froutes.go internal\u002Fapi\u002Fhandlers.go\ngit commit -m \"Add user API routes\"\n\n# Make more commits on the same branch as needed\ngit add internal\u002Fapi\u002Fmiddleware.go\ngit commit -m \"Add rate limiting middleware\"\n```\n\n**Shortcut — stage, commit, and branch in one command:**\n\n```bash\n# Create a new branch, stage all changes, and commit\ngh stack add -Am \"Add API routes\" api-routes\n\n# Create a new branch, stage tracked files only, and commit\ngh stack add -um \"Fix auth bug\" auth-fix\n```\n\n| Flag | Description |\n|------|-------------|\n| `-m, --message \u003Cstring>` | Create a commit with this message |\n| `-A, --all` | Stage all changes including untracked files (requires `-m`) |\n| `-u, --update` | Stage tracked files only (requires `-m`) |\n\n**Behavior notes:**\n\n- `-A` and `-u` are mutually exclusive.\n- When the current branch has no commits (e.g., right after `init`), `add -Am` commits directly on the current branch instead of creating a new one.\n- **Branch names are used verbatim.** `gh stack add refactor\u002Ffoo` creates a branch named `refactor\u002Ffoo` — names are never prefixed or transformed. When `-m` is given without a branch name, the name is auto-generated from the commit message in date+slug format (e.g., `03-24-add_api_routes`).\n- If called from a branch that is not the topmost in the stack, exits with code 5: `\"can only add branches on top of the stack\"`. Use `gh stack top` to switch first.\n- **Uncommitted changes:** When using `gh stack add branch-name` without `-Am`, any uncommitted changes (staged or unstaged) in your working tree carry over to the new branch. This is standard git behavior — the working tree is not touched. Commit or stash changes on the current branch before running `add` if you want a clean starting point on the new branch.\n\n---\n\n### Push branches to remote — `gh stack push`\n\nPush all stack branches to the remote.\n\n```\ngh stack push [flags]\n```\n\n```bash\n# Push all branches\ngh stack push\n\n# Push to specific remote\ngh stack push --remote upstream\n```\n\n| Flag | Description |\n|------|-------------|\n| `--remote \u003Cname>` | Remote to push to (use if multiple remotes exist) |\n\n**Behavior:**\n\n- Pushes all active (non-merged) branches atomically (`--force-with-lease --atomic`)\n- Does **not** create or update pull requests — use `gh stack submit` for that\n\n**Output (stderr):**\n\n- `Pushed N branches` summary\n\n---\n\n### Submit branches and create PRs — `gh stack submit`\n\nPush all stack branches and create PRs on GitHub. **Always pass `--auto`** — without it, `submit` prompts for a PR title for each new branch.\n\n```bash\n# Submit and auto-title new PRs (required for non-interactive use)\ngh stack submit --auto\n\n# Submit and create PRs as ready for review (not drafts)\ngh stack submit --auto --open\n```\n\n| Flag | Description |\n|------|-------------|\n| `--auto` | Auto-generate PR titles without prompting (**required** for non-interactive use) |\n| `--open` | Mark new and existing PRs as ready for review |\n| `--remote \u003Cname>` | Remote to push to (use if multiple remotes exist) |\n\n**Behavior:**\n\n- Pushes all active (non-merged) branches atomically (`--force-with-lease --atomic`)\n- Creates a new PR for each branch that doesn't have one (base set to the first non-merged ancestor branch)\n- After creating PRs, links them together as a **Stack** on GitHub (requires the repository to have stacks enabled)\n- If every PR in the stack has already been merged, the stack is complete and can't be extended. `submit` automatically forks your unmerged branches into a **new** stack rooted at the trunk and creates it on GitHub, leaving the merged stack untouched.\n- If stacks are not available (exit code 9), the repository does not have stacked PRs enabled. In interactive mode, `submit` offers to create regular (unstacked) PRs instead. In non-interactive mode, it exits with code 9.\n- Syncs PR metadata for branches that already have PRs\n\n**PR title auto-generation (`--auto`):**\n\n- Single commit on branch → uses the commit subject as the PR title, commit body as PR body\n- Multiple commits on branch → humanizes the branch name (hyphens\u002Funderscores → spaces) as the title\n\n**Output (stderr):**\n\n- `Created PR #N for \u003Cbranch>` for each newly created PR\n- `PR #N for \u003Cbranch> is up to date` for existing PRs\n- `Pushed and synced N branches` summary\n\n---\n\n### Link branches as a stack (no local tracking) — `gh stack link`\n\nLink PRs into a stack on GitHub without creating any local tracking state. This is the recommended approach if you are managing stacked branches with other tools (jj, Sapling, git-town) and want to simply create GitHub Stacked PRs via an API.\n\n```\ngh stack link [flags] \u003Cstack-number | branch-or-pr> \u003Cbranch-or-pr> [...]\n```\n\n```bash\n# Link branches into a stack (pushes, creates PRs, creates stack)\ngh stack link branch-a branch-b branch-c\n\n# Use a different base branch and mark PRs as ready for review\ngh stack link --base develop --open branch-a branch-b branch-c\n\n# Link existing PRs by number\ngh stack link 10 20 30\n\n# Add branches to an existing stack of PRs\ngh stack link 42 43 feature-auth feature-ui\n\n# Append to the top of an existing stack by its stack number\n# (7 is a stack number; only the new PRs\u002Fbranches are listed)\ngh stack link 7 48 feature-auth\n```\n\nWhen the first argument is a stack number, the remaining arguments are appended to the top of that stack, so you don't have to re-list its current PRs. Arguments already in the stack are skipped; arguments in a different stack are rejected. A numeric first argument is treated as a stack only when it matches an existing stack — otherwise it is a PR or branch.\n\n| Flag | Description |\n|------|---------|\n| `--base \u003Cbranch>` | Base branch for the bottom of the stack (default: `main`) |\n| `--open` | Mark new and existing PRs as ready for review |\n| `--remote \u003Cname>` | Remote to push to (use if multiple remotes exist) |\n\n**Behavior:**\n\n- Arguments are provided in stack order (bottom to top)\n- Each argument can be a branch name or a PR number. Numeric arguments are tried as PR numbers first; if no PR with that number exists, the argument is treated as a branch name\n- Branch arguments are pushed to the remote automatically (non-force, atomic)\n- For branches without open PRs, new PRs are created with auto-generated titles and the correct base branch chaining (first branch uses `--base`, subsequent branches use the previous branch)\n- Existing PRs whose base branch doesn't match the expected chain are corrected automatically\n- If the PRs are not yet in a stack, a new stack is created. If some PRs are already in a stack, the stack is updated (additive only — existing PRs are never removed)\n- Does **not** create or modify any local state\n\n**Output (stderr):**\n\n- `Pushing N branches to \u003Cremote>...`\n- `Found PR #N for branch \u003Cname>` for branches with existing PRs\n- `Created PR #N for \u003Cbranch> (base: \u003Cbase>)` for newly created PRs\n- `Updated base branch for PR #N to \u003Cbase>` when base branches are corrected\n- `Created stack with N PRs` or `Updated stack to N PRs`\n\n---\n\n### Sync the stack — `gh stack sync`\n\nFetch, rebase, push, and sync PR state in a single command. This is the recommended command for routine synchronization.\n\n```\ngh stack sync [flags]\n```\n\n| Flag | Description |\n|------|-------------|\n| `--remote \u003Cname>` | Remote to fetch from and push to (use if multiple remotes exist) |\n| `--prune` | Delete local branches for merged PRs |\n\n**What it does (in order):**\n\n1. **Fetch** latest changes from the remote\n2. **Reconcile the remote stack** — mirror the GitHub stack locally. If PRs were added to the stack on GitHub, pull their branches down and append them to the local stack. If the local and remote stacks have diverged, aborts the sync in a non-interactive terminal. In an interactive terminal, offers prompts to resolve any divergence (replace local stack with remote version, delete stack on GitHub so it can be recreated, or cancel).\n3. **Fast-forward trunk** to match remote (skips if already up to date, warns if diverged)\n4. **Cascade rebase** all stack branches onto their updated parents (only if trunk moved). Handles merged PRs automatically. If a conflict is detected, **all branches are restored** to their pre-rebase state and the command exits with code 3 — see [Handle rebase conflicts](#handle-rebase-conflicts-agent-workflow) for the resolution workflow\n5. **Push** all active branches atomically\n6. **Sync PR state** from GitHub and report the status of each PR\n7. **Sync the stack object** — link the open PRs into a stack on GitHub. If the PRs are not yet in a stack, a new stack is created; if some PRs are already in a stack, it is updated (additive only). This only happens when two or more PRs exist. Sync **never opens PRs** — use `gh stack submit` for that\n8. **Prune** — in interactive terminals, prompts to delete local branches for merged PRs. Use `--prune` to skip the prompt. In non-interactive environments, pruning only happens when `--prune` is passed explicitly\n\n**Output (stderr):**\n\n- `✓ Fetched latest changes from origin`\n- `Pulling N new branches from the remote stack ...` then `✓ Pulled N new branches into the stack from the remote` (when the remote stack is ahead)\n- `⚠ Your local stack has diverged from the stack on GitHub` (with `Local:` \u002F `Remote:` chains) when the stacks have diverged\n- `ℹ Sync aborted — no changes were made` when a sync is cancelled\n- `✓ Trunk main fast-forwarded to \u003Csha>` or `✓ Trunk main is already up to date`\n- `✓ Rebased \u003Cbranch> onto \u003Cbase>` per branch (if base moved)\n- `✓ Pushed N branches`\n- `✓ PR #N (\u003Cbranch>) — Open` per branch\n- `Merged: #N, #M` for merged branches\n- `✓ Stack created on GitHub with N PRs` \u002F `✓ Stack updated on GitHub with N PRs` \u002F `✓ Linked to the existing stack on GitHub` (when two or more PRs exist)\n- `✓ Pruned \u003Cbranch> (merged)` per pruned branch (when pruning)\n- `✓ Stack synced` when the stack object on GitHub was created\u002Fupdated to match local, or `✓ Branches synced` when only the branches were synced (fewer than two PRs or stacked PRs unavailable)\n\n---\n\n### Rebase the stack — `gh stack rebase`\n\nPull from remote and cascade-rebase stack branches. Use this when `sync` reports a conflict or when you need finer control (e.g., rebase only part of the stack).\n\n```\ngh stack rebase [flags] [branch]\n```\n\n```bash\n# Rebase the entire stack\ngh stack rebase\n\n# Rebase only branches from trunk to current branch\ngh stack rebase --downstack\n\n# Rebase only branches from current branch to top\ngh stack rebase --upstack\n\n# Rebase stack branches without pulling from or rebasing with trunk\ngh stack rebase --no-trunk\n\n# After resolving a conflict: stage files with `git add`, then:\ngh stack rebase --continue\n\n# Abort and restore all branches to pre-rebase state\ngh stack rebase --abort\n```\n\n| Flag | Description |\n|------|-------------|\n| `--downstack` | Only rebase branches from trunk to the current branch |\n| `--upstack` | Only rebase branches from the current branch to the top |\n| `--no-trunk` | Skip trunk — only rebase stack branches onto each other (no fetch, no trunk rebase) |\n| `--continue` | Continue after resolving conflicts |\n| `--abort` | Abort and restore all branches |\n| `--remote \u003Cname>` | Remote to fetch from (use if multiple remotes exist) |\n\n| Argument | Description |\n|----------|-------------|\n| `[branch]` | Target branch (defaults to the current branch) |\n\n**Conflict handling:** See [Handle rebase conflicts](#handle-rebase-conflicts-agent-workflow) in the Workflows section for the full resolution workflow.\n\n**Merged PR detection:** If a branch's PR was merged on GitHub, the rebase automatically handles this using `--onto` mode and correctly replays commits on top of the merge target.\n\n**Rerere (conflict memory):** `git rerere` is enabled by `init` so previously resolved conflicts are auto-resolved in future rebases.\n\n**No-trunk mode:** Use `--no-trunk` to skip fetching from the remote and rebasing with the trunk branch. Only inter-branch rebases are performed (branch 2 onto branch 1, branch 3 onto branch 2, etc.). Useful when you only need to align stack branches with each other without pulling upstream changes.\n\n---\n\n### View the stack — `gh stack view`\n\nDisplay the current stack's branches, PR status, and recent commits. **Always pass `--json`** — without it, this command launches an interactive TUI that agents cannot operate.\n\n```bash\n# Always use --json\ngh stack view --json\n```\n\n| Flag | Description |\n|------|-------------|\n| `--json` | Output stack data as JSON to stdout (**required** for non-interactive use) |\n\n**`--json` output format:**\n\n```json\n{\n  \"trunk\": \"main\",\n  \"currentBranch\": \"api-routes\",\n  \"branches\": [\n    {\n      \"name\": \"auth\",\n      \"head\": \"abc1234...\",\n      \"base\": \"def5678...\",\n      \"isCurrent\": false,\n      \"isMerged\": true,\n      \"needsRebase\": false,\n      \"pr\": {\n        \"number\": 42,\n        \"url\": \"https:\u002F\u002Fgithub.com\u002Fowner\u002Frepo\u002Fpull\u002F42\",\n        \"state\": \"MERGED\"\n      }\n    },\n    {\n      \"name\": \"api-routes\",\n      \"head\": \"789abcd...\",\n      \"base\": \"abc1234...\",\n      \"isCurrent\": true,\n      \"isMerged\": false,\n      \"needsRebase\": false,\n      \"pr\": {\n        \"number\": 43,\n        \"url\": \"https:\u002F\u002Fgithub.com\u002Fowner\u002Frepo\u002Fpull\u002F43\",\n        \"state\": \"OPEN\"\n      }\n    }\n  ]\n}\n```\n\nFields per branch:\n- `name` — branch name\n- `head` — current HEAD SHA\n- `base` — parent branch's HEAD SHA at last sync\n- `isCurrent` — whether this is the checked-out branch\n- `isMerged` — whether the PR has been merged\n- `needsRebase` — whether the base branch is not an ancestor (non-linear history)\n- `pr` — PR metadata (omitted if no PR exists). `state` is `\"OPEN\"` or `\"MERGED\"`.\n\n---\n\n### Navigate the stack\n\nMove between branches without remembering branch names. These commands are fully non-interactive.\n\n```bash\ngh stack up          # Move up one branch (further from trunk)\ngh stack up 3        # Move up three branches\ngh stack down        # Move down one branch (closer to trunk)\ngh stack down 2      # Move down two branches\ngh stack top         # Jump to the top of the stack (furthest from trunk)\ngh stack bottom      # Jump to the bottom (first non-merged branch above trunk)\n```\n\nNavigation clamps to stack bounds. Merged branches are skipped when navigating from active branches.\n\n---\n\n### Check out a stack — `gh stack checkout`\n\nCheck out a stack from a pull request number or branch name. **Always provide an argument** — running `gh stack checkout` without arguments triggers an interactive selection menu.\n\n```\ngh stack checkout \u003Cpr-number | branch>\n```\n\n```bash\n# By PR number (pulls from GitHub)\ngh stack checkout 42\n\n# By branch name (local only)\ngh stack checkout feature-auth\n```\n\nWhen a PR number is provided (e.g. `123`), the command fetches the stack on GitHub, pulls the branches, and sets up the stack locally. If the stack already exists locally and matches, it switches to the branch.\n\n> **⚠️ Agent warning:** If the local and remote stacks have different branch compositions, this command triggers an interactive conflict-resolution prompt that cannot be bypassed with a flag. To avoid this: run `gh stack unstack` first to remove the conflicting local stack, then retry `gh stack checkout \u003Cpr-number>`.\n\nWhen a branch name is provided, the command resolves it against locally tracked stacks only. This is always safe for non-interactive use.\n\n---\n\n### Remove a stack — `gh stack unstack`\n\nTear down a stack so you can restructure it — remove a branch, reorder branches, rename branches, or make other large changes. After unstacking, use `gh stack init` to re-create the stack with the desired structure.\n\nWith no argument, the command targets the active stack — the one containing the currently checked out branch — unstacking it on GitHub and removing local tracking.\n\nProvide a stack number to unstack a specific stack on GitHub. This works from anywhere in the repository, whether or not the stack is checked out locally — the number is unstacked directly through the GitHub API (like `gh stack link`, no local tracking required). If the stack is also tracked locally, its local tracking is removed as well.\n\n```\ngh stack unstack [\u003Cstack-number>] [flags]\n```\n\n```bash\n# Tear down the current stack (locally and on GitHub), then rebuild\ngh stack unstack\ngh stack init --base main branch-2 branch-1 branch-3 # reordered\n\n# Unstack a specific stack by its number, from anywhere in the repo\ngh stack unstack 7\n\n# Only remove local tracking (keep the stack on GitHub)\ngh stack unstack --local\n```\n\n| Flag | Description |\n|------|-------------|\n| `--local` | Only remove the stack locally (keep it on GitHub); never contacts GitHub |\n\n> **Note for agents:** `gh stack unstack \u003Cnumber>` is a remote-first API wrapper — it unstacks on GitHub by number from anywhere in the repo, tracked locally or not, and is safe for non-interactive use. `--local` never contacts GitHub; combining `--local` with a number that isn't tracked locally is an error. An unknown stack number returns a \"not found on GitHub\" error (exit code 2).\n\n---\n\n## Output conventions\n\n- **Status messages** go to **stderr** with emoji prefixes: `✓` (success), `✗` (error), `⚠` (warning), `ℹ` (info).\n- **Data output** (e.g., `view --json`) goes to **stdout**.\n- When piping output, use `2>\u002Fdev\u002Fnull` to suppress status messages if only data output is needed.\n\n## Exit codes and error recovery\n\n| Code | Meaning | Agent action |\n|------|---------|-------------|\n| 0 | Success | Proceed normally |\n| 1 | Generic error | Read stderr for details; may indicate commit\u002Fpush failure |\n| 2 | Not in a stack | Run `gh stack init` to create a stack first |\n| 3 | Rebase conflict | Parse stderr for conflicted file paths, resolve conflicts, run `gh stack rebase --continue` |\n| 4 | GitHub API failure | Check `gh auth status`, retry the command |\n| 5 | Invalid arguments | Fix the command invocation (check flags and arguments) |\n| 6 | Disambiguation required | A branch belongs to multiple stacks. Run `gh stack checkout \u003Cspecific-branch>` to switch to a non-shared branch first |\n| 7 | Rebase already in progress | Run `gh stack rebase --continue` (after resolving conflicts) or `gh stack rebase --abort` to start over |\n| 8 | Stack is locked | Another `gh stack` process is writing the stack file. Wait and retry — the lock times out after 5 seconds |\n| 9 | Stacked PRs unavailable | The repository does not have stacked PRs enabled. `submit` will offer to create regular (unstacked) PRs in interactive mode |\n\n## Known limitations\n\n1. **Stacks are strictly linear.** Branching stacks (multiple children on a single parent) are not supported. Each branch has exactly one parent and at most one child. If you need parallel workstreams, use separate stacks.\n2. **Stack disambiguation cannot be bypassed.** If the current branch is the trunk of multiple stacks, commands error with code 6. Check out a non-shared branch first.\n3. **Multiple remotes require `--remote` or config.** If more than one remote is configured, pass `--remote \u003Cname>` or set `remote.pushDefault` in git config before running `push`, `sync`, or `rebase`.\n4. **Merging PRs:** Merging Stacked PRs from the CLI is not supported yet. Direct users to open the PR URL in a browser to merge PRs.\n5. **Remote stack checkout requires a PR number.** `checkout` with a branch name only works with locally tracked stacks. Use a PR number (e.g. `gh stack checkout 123`) to pull stacks from GitHub.\n6. **PR title and body are auto-generated.** There is no flag to set a custom PR title or body during `submit`. The title and body are generated from commit messages plus a footer. Use `gh pr edit` to modify PR title and body after creation.\n","# gh-stack\n\n`gh stack` is a [GitHub CLI](https:\u002F\u002Fcli.github.com\u002F) extension for managing **stacked branches and pull requests**. A stack is an ordered list of branches where each branch builds on the one below it, rooted on a trunk branch (typically the repo's default branch). Each branch maps to one PR whose base is the branch below it, so reviewers see only the diff for that layer.\n\n```\nmain (trunk)\n └── auth-layer     → PR #1 (base: main)            - bottom (closest to trunk)\n  └── api-endpoints → PR #2 (base: auth-layer)\n   └── frontend     → PR #3 (base: api-endpoints)   - top (furthest from trunk)\n```\n\nThe **bottom** of the stack is the branch closest to the trunk, and the **top** is the branch furthest from the trunk. Each branch inherits from the one below it. Navigation commands (`up`, `down`, `top`, `bottom`) follow this model: `up` moves away from trunk, `down` moves toward it.\n\n## When to use this skill\n\nUse this skill when the user wants to:\n\n- Break a large change into a chain of small, reviewable PRs\n- Create, rebase, push, or sync a stack of dependent branches\n- Navigate between layers of a branch stack\n- View the status of stacked PRs\n- Tear down and rebuild a stack to remove, reorder, or rename branches\n\n## Prerequisites\n\nThe GitHub CLI (`gh`) v2.0+ must be installed and authenticated. Install the extension with:\n\n```bash\ngh extension install github\u002Fgh-stack\n```\n\nBefore using `gh stack`, configure git to prevent interactive prompts:\n\n```bash\ngit config rerere.enabled true           # remember conflict resolutions (skips prompt on init)\ngit config remote.pushDefault origin     # if multiple remotes exist (skips remote picker)\n```\n\n## Agent rules\n\n**All `gh stack` commands must be run non-interactively.** Every command invocation must include the flags and positional arguments needed to avoid prompts, TUIs, and interactive menus. If a command would prompt for input, it will hang indefinitely.\n\n1. **Always supply branch names as positional arguments** to `init`, `add`, and `checkout`. Running these commands without arguments triggers interactive prompts. Branch names are used exactly as given — a name is never prefixed or transformed, so `gh stack add refactor\u002Ffoo` creates a branch named `refactor\u002Ffoo`.\n2. **Always use `--auto` with `gh stack submit`** to auto-generate PR titles. Without `--auto`, `submit` prompts for a title for each new PR.\n3. **Always use `--json` with `gh stack view`.** Without `--json`, the command launches an interactive TUI that cannot be operated by agents. There is no other appropriate flag — always pass `--json`.\n4. **Use `--remote \u003Cname>` when multiple remotes are configured**, or pre-configure `git config remote.pushDefault origin`. Without this, `push`, `submit`, `sync`, `link`, and `checkout` trigger an interactive remote picker.\n5. **Avoid branches shared across multiple stacks.** If a branch belongs to multiple stacks, commands exit with code 6. Check out a non-shared branch first.\n6. **Plan your stack layers by dependency order before writing code.** Foundational changes (models, APIs, shared utilities) go in lower branches; dependent changes (UI, consumers) go in higher branches. Think through the dependency chain before running `gh stack init`.\n7. **Use standard `git add` and `git commit` for staging and committing.** This gives you full control over which changes go into each branch. The `-Am` shortcut is available but should not be the default approach—stacked PRs are most effective when each branch contains a deliberate, logical set of changes.\n8. **Navigate down the stack when you need to change a lower layer.** If you're working on a frontend branch and realize you need API changes, don't hack around it at the current layer. Navigate to the appropriate branch (`gh stack down`, `gh stack checkout`, or `gh stack bottom`), make and commit the changes there, run `gh stack rebase --upstack`, then navigate back up to continue.\n9. **Use `gh stack link` for external tool workflows.** When branches are managed by an external tool (jj, Sapling, etc.), use `gh stack link branch-a branch-b`. `link` does not rely on local tracking state and is intended for API-driven PR and stack management. Provide at least two branches\u002FPRs to create or update a stack, or a stack number followed by the new branches\u002FPRs to append them to the top of an existing stack (e.g. `gh stack link 7 branch-c`).\n\n**Never do any of the following — each triggers an interactive prompt or TUI that will hang:**\n- ❌ `gh stack view` or `gh stack view --short` — always use `gh stack view --json`\n- ❌ `gh stack submit` without `--auto` — always use `gh stack submit --auto`\n- ❌ `gh stack init` without branch arguments — always provide branch names\n- ❌ `gh stack add` without a branch name — always provide a branch name\n- ❌ `gh stack checkout` without an argument — always provide a PR number or branch name\n- ❌ `gh stack checkout \u003Cpr-number>` when a different local stack already exists on those branches — this triggers an unbypassable conflict resolution prompt; use `gh stack unstack` first to remove the local stack, then retry the checkout\n\n## Thinking about stack structure\n\nEach branch in a stack should represent a **discrete, logical unit of work** that can be reviewed independently. The changes within a branch should be cohesive—they belong together and make sense as a single PR.\n\n### Dependency chain\n\nStacked branches form a dependency chain: each branch builds on the one below it. This means **foundational changes must go in lower (earlier) branches**, and code that depends on them goes in higher (later) branches.\n\n**Plan your layers before writing code.** For example, a full-stack feature might be structured like this (use branch names relevant to your actual task, not these generic ones):\n\n```\nmain (trunk)\n └── data-models    ← shared types, database schema\n  └── api-endpoints ← API routes that use the models\n   └── frontend-ui  ← UI components that call the APIs\n    └── integration ← tests that exercise the full stack\n```\n\nThis is illustrative — choose branch names and layer boundaries that reflect the specific work you're doing. The key principle is: if code in one layer depends on code in another, the dependency must be in the same branch or a lower one.\n\n### Branch naming\n\nChoose a clear, descriptive branch name for each layer that reflects the concern it contains (e.g., `auth`, `api-routes`, `frontend`). Branch names are used exactly as you provide them to `init` and `add` — nothing is prepended or transformed. Slashes are allowed and are treated as part of the name (e.g., `gh stack add refactor\u002Ffoo` creates a branch named `refactor\u002Ffoo`).\n\n### Staging changes deliberately\n\nThe main reason to use `git add` and `git commit` directly is to control **which changes go into which branch**. When you have multiple files in your working tree, you can stage a subset for the current branch, commit them, then create a new branch and stage the rest there:\n\n```bash\n# You're on data-models with several new files in your working tree.\n# Stage only the model files for this branch:\ngit add internal\u002Fmodels\u002Fuser.go internal\u002Fmodels\u002Fsession.go\ngit commit -m \"Add user and session models\"\n\ngit add db\u002Fmigrations\u002F001_create_users.sql\ngit commit -m \"Add user table migration\"\n\n# Now create a new branch for the API layer and stage the API files there:\ngh stack add api-routes # created & switched to the api-routes branch\ngit add internal\u002Fapi\u002Froutes.go internal\u002Fapi\u002Fhandlers.go\ngit commit -m \"Add user API routes\"\n```\n\nThis keeps each branch focused on one concern. Multiple commits per branch are fine — the key is that all commits in a branch relate to the same logical concern, and changes that belong to a different concern go in a different branch.\n\n### When to create a new branch\n\nCreate a new branch (`gh stack add`) when you're starting a **different concern** that depends on what you've built so far. Signs it's time for a new branch:\n\n- You're switching from backend to frontend work\n- You're moving from core logic to tests or documentation\n- The next set of changes has a different reviewer audience\n- The current branch's PR is already large enough to review\n\n### One stack, one story\n\nThink of a stack from the reviewer's perspective: the stack of PRs should **tell a cohesive story** about a feature or project. A reviewer should be able to read the PRs in sequence and understand the progression of changes, with each PR being a small, logical piece of the whole.\n\n**When to use a single stack:** All the branches are part of the same feature, project, or closely related effort. Even if the work spans multiple concerns (models, API, frontend), they're all building toward the same goal.\n\n**When to create a separate stack:** The work is unrelated to your current stack — a different feature, a bug fix in an unrelated area, or an independent refactor. Don't mix unrelated work into a single stack just because you happen to be working on both. Start a new stack with `gh stack init` or switch to an existing stack with `gh stack checkout` for each distinct effort.\n\nSmall, incidental fixes (e.g., fixing a typo you noticed) can go in the current stack if they're trivial. But if a change grows into its own project, it deserves its own stack.\n\n## Quick reference\n\n| Task | Command |\n|------|---------|\n| Create a stack | `gh stack init auth` |\n| Create a stack of multiple branches | `gh stack init auth api frontend` |\n| Adopt existing branches | `gh stack init existing-branch-a existing-branch-b` |\n| Set custom trunk | `gh stack init --base develop branch-a` |\n| Add a branch to stack | `gh stack add api-routes` |\n| Add branch + stage all + commit | `gh stack add -Am \"message\" api-routes` |\n| Push branches to remote | `gh stack push` |\n| Push to specific remote | `gh stack push --remote origin` |\n| Push branches + create draft PRs | `gh stack submit --auto` |\n| Create PRs as ready for review | `gh stack submit --auto --open` |\n| Sync (fetch, rebase, push) | `gh stack sync` |\n| Sync with specific remote | `gh stack sync --remote origin` |\n| Sync and prune merged branches | `gh stack sync --prune` |\n| Rebase entire stack | `gh stack rebase` |\n| Rebase upstack only | `gh stack rebase --upstack` |\n| Rebase without trunk | `gh stack rebase --no-trunk` |\n| Continue after conflict | `gh stack rebase --continue` |\n| Abort rebase | `gh stack rebase --abort` |\n| View stack details (JSON) | `gh stack view --json` |\n| Switch branches up\u002Fdown in stack | `gh stack up [n]` \u002F `gh stack down [n]` |\n| Switch to top\u002Fbottom branch | `gh stack top` \u002F `gh stack bottom` |\n| Check out by stack number | `gh stack checkout 7` |\n| Check out by PR | `gh stack checkout 42` |\n| Check out by branch (local only) | `gh stack checkout feature-auth` |\n| Tear down the current stack to restructure it | `gh stack unstack` |\n| Tear down a specific stack by number | `gh stack unstack 7` |\n\n---\n\n## Workflows\n\n### End-to-end: create a stack from scratch\n\n```bash\n# 1. Initialize a stack with the first branch\ngh stack init auth\n# → creates auth and checks it out\n\n# 2. Write code for the first layer (auth)\ncat > auth.go \u003C\u003C 'EOF'\npackage auth\n\nfunc Middleware(next http.Handler) http.Handler {\n    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n        \u002F\u002F verify token\n        next.ServeHTTP(w, r)\n    })\n}\nEOF\n\n# 3. Stage and commit using standard git commands\ngit add auth.go\ngit commit -m \"Add auth middleware\"\n\n# You can make multiple commits on the same branch\ncat > auth_test.go \u003C\u003C 'EOF'\npackage auth\n\nfunc TestMiddleware(t *testing.T) {\n    \u002F\u002F test auth middleware\n}\nEOF\ngit add auth_test.go\ngit commit -m \"Add auth middleware tests\"\n\n# 4. When you're ready for a new concern, add the next branch\ngh stack add api-routes\n# → creates api-routes\n\n# 5. Write code for the API layer\ncat > api.go \u003C\u003C 'EOF'\npackage api\n\nfunc RegisterRoutes(mux *http.ServeMux) {\n    mux.HandleFunc(\"\u002Fusers\", handleUsers)\n}\nEOF\ngit add api.go\ngit commit -m \"Add API routes\"\n\n# 6. Add a third layer for frontend\ngh stack add frontend\n# → creates frontend\n\ncat > frontend.go \u003C\u003C 'EOF'\npackage frontend\n\nfunc RenderDashboard(w http.ResponseWriter) {\n    \u002F\u002F calls the API endpoints from the layer below\n}\nEOF\ngit add frontend.go\ngit commit -m \"Add frontend dashboard\"\n\n# ── Stack complete: auth → api-routes → frontend ──\n\n# 7. Push everything and create PRs (drafts by default)\ngh stack submit --auto\n\n# 8. Verify the stack\ngh stack view --json\n```\n\n> **Shortcut:** If you prefer a faster flow, `gh stack add -Am \"message\" branch-name` combines staging, committing, and branch creation into one command. This is useful for single-commit layers but bypasses deliberate staging.\n\n### Making mid-stack changes\n\nThis is a critical workflow for agents. When you're working on a higher layer and realize you need to change something in a lower layer (e.g., you're building frontend components but need to add an API endpoint), **navigate down to the correct branch, make the change there, and rebase**.\n\n```bash\n# You're on frontend but need to add an API endpoint\n\n# 1. Navigate to the API branch\ngh stack down\n# or: gh stack checkout api-routes\n\n# 2. Make the change where it belongs\ncat > users_api.go \u003C\u003C 'EOF'\npackage api\n\nfunc handleGetUser(w http.ResponseWriter, r *http.Request) {\n    \u002F\u002F new endpoint the frontend needs\n}\nEOF\ngit add users_api.go\ngit commit -m \"Add get-user endpoint\"\n\n# 3. Rebase everything above to pick up the change\ngh stack rebase --upstack\n\n# 4. Navigate back to where you were working\ngh stack top\n# or: gh stack checkout frontend\n\n# 5. Continue working — the API changes are now available\n```\n\n**Why this matters:** If you make API changes on the frontend branch, those changes will end up in the wrong PR. The API PR won't include them, and the frontend PR will have unrelated API diffs mixed in. Always put changes in the branch where they logically belong.\n\n### Modify a mid-stack branch and sync\n\nWhen you need to revisit a branch after the initial creation (e.g., responding to review feedback):\n\n```bash\n# 1. Navigate to the branch that needs changes\ngh stack bottom\n# or: gh stack checkout auth\n# or: gh stack checkout 42  (by PR number)\n\n# 2. Make changes and commit\ncat > auth.go \u003C\u003C 'EOF'\npackage auth\n\u002F\u002F updated implementation\nEOF\ngit add auth.go\ngit commit -m \"Fix auth token validation\"\n\n# 3. Rebase everything above this branch\ngh stack rebase --upstack\n\n# 4. Push the updated stack\ngh stack push\n```\n\n### Routine sync after merges\n\n```bash\n# Single command: fetch, rebase, push, sync PR and stack state\ngh stack sync\n\n# Sync and automatically clean up local branches for merged PRs\ngh stack sync --prune\n```\n\n> **Note for agents:** In non-interactive environments, the prune prompt is not shown. Use `--prune` explicitly to delete local branches for merged PRs.\n\n> **Note for agents:** `sync` also mirrors the stack on GitHub locally. If PRs were added to the stack on github.com, their branches are pulled down and appended to the local stack automatically. If the local and remote stacks have **diverged** (you changed the local stack while the remote stack changed differently), sync can only prompt to resolve it in an interactive terminal — in non-interactive environments it aborts the sync (nothing is pushed or updated) and exits successfully with `ℹ Sync aborted`. Resolve a divergence by unstacking and recreating the stack.\n\n### Squash-merge recovery\n\nWhen a PR is squash-merged on GitHub, the original branch's commits no longer exist in the trunk history. `gh stack` detects this automatically and uses `git rebase --onto` to correctly replay remaining commits.\n\n```bash\n# After PR #1 (auth) is squash-merged on GitHub:\ngh stack sync\n# → fetches latest, detects the merge, fast-forwards trunk\n# → rebases api-routes onto updated trunk (skips merged branch)\n# → rebases frontend onto api-routes\n# → pushes updated branches\n# → reports: \"Merged: #1\"\n\n# Verify the result\ngh stack view --json\n# → auth shows \"isMerged\": true, \"state\": \"MERGED\"\n# → api-routes and frontend show updated heads\n```\n\nIf `sync` hits a conflict during this process, it restores all branches to their pre-rebase state and exits with code 3. See [Handle rebase conflicts](#handle-rebase-conflicts-agent-workflow) for the resolution workflow.\n\n### Handle rebase conflicts (agent workflow)\n\n```bash\n# 1. Start the rebase\ngh stack rebase\n\n# 2. If exit code 3 (conflict):\n#    - Parse stderr for conflicted file paths\n#    - Read those files to find \u003C\u003C\u003C\u003C\u003C\u003C\u003C \u002F ======= \u002F >>>>>>> markers\n#    - Edit files to resolve conflicts\n#    - Stage resolved files:\ngit add path\u002Fto\u002Fresolved-file.go\n\n# 3. Continue the rebase\ngh stack rebase --continue\n\n# 4. If another conflict occurs, repeat steps 2-3\n\n# 5. If unable to resolve, abort to restore everything\ngh stack rebase --abort\n```\n\n### Parsing `--json` output\n\n```bash\n# Get stack state as JSON\noutput=$(gh stack view --json)\n\n# Check if any branch needs a rebase, and rebase if so\nneeds_rebase=$(echo \"$output\" | jq '[.branches[] | select(.needsRebase == true)] | length')\nif [ \"$needs_rebase\" -gt 0 ]; then\n  echo \"Branches need rebase, rebasing stack...\"\n  gh stack rebase\nfi\n\n# Get all open PR URLs\necho \"$output\" | jq -r '.branches[] | select(.pr.state == \"OPEN\") | .pr.url'\n\n# Find merged branches\necho \"$output\" | jq -r '.branches[] | select(.isMerged == true) | .name'\n\n# Get the current branch\necho \"$output\" | jq -r '.currentBranch'\n\n# Check if the stack is fully merged (all branches merged)\necho \"$output\" | jq '[.branches[] | .isMerged] | all'\n```\n\n### Restructure a stack (remove a branch, reorder, or rename)\n\nUse `unstack` to tear down the stack, make structural changes, then re-init:\n\n```bash\n# 1. Remove the stack (locally and on GitHub)\ngh stack unstack\n\n# 2. Make structural changes — e.g. delete a branch, reorder, rename\ngit branch -m old-branch-1 new-branch-1\n\n# 3. Re-create the stack with the new structure\ngh stack init --base main new-branch-1 new-branch-2 new-branch-3\n```\n\n---\n\n## Commands\n\n### Initialize a stack — `gh stack init`\n\nCreates a new stack. **Always provide at least one branch name as a positional argument** — running without branch arguments triggers interactive prompts that agents cannot use.\n\n```\ngh stack init [flags] \u003Cbranches...>\n```\n\n```bash\n# Create a stack with a new branch\ngh stack init auth\n# → creates auth and checks it out\n\n# Create a stack with new branches\ngh stack init branch-a branch-b branch-c\n\n# Use a different trunk branch\ngh stack init --base develop branch-a branch-b\n\n# Adopt existing branches into a stack (handled automatically if the branches exist)\ngh stack init branch-a branch-b branch-c\n```\n\n| Flag | Description |\n|------|-------------|\n| `-b, --base \u003Cbranch>` | Trunk branch (defaults to the repo's default branch) |\n\n**Behavior:**\n\n- Branch names are created exactly as given (slashes are allowed and kept as-is)\n- Creates any branches that don't already exist (branching from the trunk branch)\n- Existing branches are adopted automatically; missing branches are created from the trunk\n- Checks out the last branch in the list\n- Enables `git rerere` so conflict resolutions are remembered across rebases. On first run in a repo, this may trigger a confirmation prompt — pre-configure with `git config rerere.enabled true` to avoid it\n\n---\n\n### Add a branch — `gh stack add`\n\nAdd a new branch on top of the current stack. Must be run while on the topmost branch (or the trunk if the stack has no branches yet). **Always provide a branch name** — running without one triggers an interactive prompt.\n\n```\ngh stack add [flags] \u003Cbranch>\n```\n\n**Recommended workflow — create the branch, then use standard git:**\n\n```bash\n# Create a new branch and switch to it\ngh stack add api-routes\n\n# Write code, stage deliberately, and commit\ngit add internal\u002Fapi\u002Froutes.go internal\u002Fapi\u002Fhandlers.go\ngit commit -m \"Add user API routes\"\n\n# Make more commits on the same branch as needed\ngit add internal\u002Fapi\u002Fmiddleware.go\ngit commit -m \"Add rate limiting middleware\"\n```\n\n**Shortcut — stage, commit, and branch in one command:**\n\n```bash\n# Create a new branch, stage all changes, and commit\ngh stack add -Am \"Add API routes\" api-routes\n\n# Create a new branch, stage tracked files only, and commit\ngh stack add -um \"Fix auth bug\" auth-fix\n```\n\n| Flag | Description |\n|------|-------------|\n| `-m, --message \u003Cstring>` | Create a commit with this message |\n| `-A, --all` | Stage all changes including untracked files (requires `-m`) |\n| `-u, --update` | Stage tracked files only (requires `-m`) |\n\n**Behavior notes:**\n\n- `-A` and `-u` are mutually exclusive.\n- When the current branch has no commits (e.g., right after `init`), `add -Am` commits directly on the current branch instead of creating a new one.\n- **Branch names are used verbatim.** `gh stack add refactor\u002Ffoo` creates a branch named `refactor\u002Ffoo` — names are never prefixed or transformed. When `-m` is given without a branch name, the name is auto-generated from the commit message in date+slug format (e.g., `03-24-add_api_routes`).\n- If called from a branch that is not the topmost in the stack, exits with code 5: `\"can only add branches on top of the stack\"`. Use `gh stack top` to switch first.\n- **Uncommitted changes:** When using `gh stack add branch-name` without `-Am`, any uncommitted changes (staged or unstaged) in your working tree carry over to the new branch. This is standard git behavior — the working tree is not touched. Commit or stash changes on the current branch before running `add` if you want a clean starting point on the new branch.\n\n---\n\n### Push branches to remote — `gh stack push`\n\nPush all stack branches to the remote.\n\n```\ngh stack push [flags]\n```\n\n```bash\n# Push all branches\ngh stack push\n\n# Push to specific remote\ngh stack push --remote upstream\n```\n\n| Flag | Description |\n|------|-------------|\n| `--remote \u003Cname>` | Remote to push to (use if multiple remotes exist) |\n\n**Behavior:**\n\n- Pushes all active (non-merged) branches atomically (`--force-with-lease --atomic`)\n- Does **not** create or update pull requests — use `gh stack submit` for that\n\n**Output (stderr):**\n\n- `Pushed N branches` summary\n\n---\n\n### Submit branches and create PRs — `gh stack submit`\n\nPush all stack branches and create PRs on GitHub. **Always pass `--auto`** — without it, `submit` prompts for a PR title for each new branch.\n\n```bash\n# Submit and auto-title new PRs (required for non-interactive use)\ngh stack submit --auto\n\n# Submit and create PRs as ready for review (not drafts)\ngh stack submit --auto --open\n```\n\n| Flag | Description |\n|------|-------------|\n| `--auto` | Auto-generate PR titles without prompting (**required** for non-interactive use) |\n| `--open` | Mark new and existing PRs as ready for review |\n| `--remote \u003Cname>` | Remote to push to (use if multiple remotes exist) |\n\n**Behavior:**\n\n- Pushes all active (non-merged) branches atomically (`--force-with-lease --atomic`)\n- Creates a new PR for each branch that doesn't have one (base set to the first non-merged ancestor branch)\n- After creating PRs, links them together as a **Stack** on GitHub (requires the repository to have stacks enabled)\n- If every PR in the stack has already been merged, the stack is complete and can't be extended. `submit` automatically forks your unmerged branches into a **new** stack rooted at the trunk and creates it on GitHub, leaving the merged stack untouched.\n- If stacks are not available (exit code 9), the repository does not have stacked PRs enabled. In interactive mode, `submit` offers to create regular (unstacked) PRs instead. In non-interactive mode, it exits with code 9.\n- Syncs PR metadata for branches that already have PRs\n\n**PR title auto-generation (`--auto`):**\n\n- Single commit on branch → uses the commit subject as the PR title, commit body as PR body\n- Multiple commits on branch → humanizes the branch name (hyphens\u002Funderscores → spaces) as the title\n\n**Output (stderr):**\n\n- `Created PR #N for \u003Cbranch>` for each newly created PR\n- `PR #N for \u003Cbranch> is up to date` for existing PRs\n- `Pushed and synced N branches` summary\n\n---\n\n### Link branches as a stack (no local tracking) — `gh stack link`\n\nLink PRs into a stack on GitHub without creating any local tracking state. This is the recommended approach if you are managing stacked branches with other tools (jj, Sapling, git-town) and want to simply create GitHub Stacked PRs via an API.\n\n```\ngh stack link [flags] \u003Cstack-number | branch-or-pr> \u003Cbranch-or-pr> [...]\n```\n\n```bash\n# Link branches into a stack (pushes, creates PRs, creates stack)\ngh stack link branch-a branch-b branch-c\n\n# Use a different base branch and mark PRs as ready for review\ngh stack link --base develop --open branch-a branch-b branch-c\n\n# Link existing PRs by number\ngh stack link 10 20 30\n\n# Add branches to an existing stack of PRs\ngh stack link 42 43 feature-auth feature-ui\n\n# Append to the top of an existing stack by its stack number\n# (7 is a stack number; only the new PRs\u002Fbranches are listed)\ngh stack link 7 48 feature-auth\n```\n\nWhen the first argument is a stack number, the remaining arguments are appended to the top of that stack, so you don't have to re-list its current PRs. Arguments already in the stack are skipped; arguments in a different stack are rejected. A numeric first argument is treated as a stack only when it matches an existing stack — otherwise it is a PR or branch.\n\n| Flag | Description |\n|------|---------|\n| `--base \u003Cbranch>` | Base branch for the bottom of the stack (default: `main`) |\n| `--open` | Mark new and existing PRs as ready for review |\n| `--remote \u003Cname>` | Remote to push to (use if multiple remotes exist) |\n\n**Behavior:**\n\n- Arguments are provided in stack order (bottom to top)\n- Each argument can be a branch name or a PR number. Numeric arguments are tried as PR numbers first; if no PR with that number exists, the argument is treated as a branch name\n- Branch arguments are pushed to the remote automatically (non-force, atomic)\n- For branches without open PRs, new PRs are created with auto-generated titles and the correct base branch chaining (first branch uses `--base`, subsequent branches use the previous branch)\n- Existing PRs whose base branch doesn't match the expected chain are corrected automatically\n- If the PRs are not yet in a stack, a new stack is created. If some PRs are already in a stack, the stack is updated (additive only — existing PRs are never removed)\n- Does **not** create or modify any local state\n\n**Output (stderr):**\n\n- `Pushing N branches to \u003Cremote>...`\n- `Found PR #N for branch \u003Cname>` for branches with existing PRs\n- `Created PR #N for \u003Cbranch> (base: \u003Cbase>)` for newly created PRs\n- `Updated base branch for PR #N to \u003Cbase>` when base branches are corrected\n- `Created stack with N PRs` or `Updated stack to N PRs`\n\n---\n\n### Sync the stack — `gh stack sync`\n\nFetch, rebase, push, and sync PR state in a single command. This is the recommended command for routine synchronization.\n\n```\ngh stack sync [flags]\n```\n\n| Flag | Description |\n|------|-------------|\n| `--remote \u003Cname>` | Remote to fetch from and push to (use if multiple remotes exist) |\n| `--prune` | Delete local branches for merged PRs |\n\n**What it does (in order):**\n\n1. **Fetch** latest changes from the remote\n2. **Reconcile the remote stack** — mirror the GitHub stack locally. If PRs were added to the stack on GitHub, pull their branches down and append them to the local stack. If the local and remote stacks have diverged, aborts the sync in a non-interactive terminal. In an interactive terminal, offers prompts to resolve any divergence (replace local stack with remote version, delete stack on GitHub so it can be recreated, or cancel).\n3. **Fast-forward trunk** to match remote (skips if already up to date, warns if diverged)\n4. **Cascade rebase** all stack branches onto their updated parents (only if trunk moved). Handles merged PRs automatically. If a conflict is detected, **all branches are restored** to their pre-rebase state and the command exits with code 3 — see [Handle rebase conflicts](#handle-rebase-conflicts-agent-workflow) for the resolution workflow\n5. **Push** all active branches atomically\n6. **Sync PR state** from GitHub and report the status of each PR\n7. **Sync the stack object** — link the open PRs into a stack on GitHub. If the PRs are not yet in a stack, a new stack is created; if some PRs are already in a stack, it is updated (additive only). This only happens when two or more PRs exist. Sync **never opens PRs** — use `gh stack submit` for that\n8. **Prune** — in interactive terminals, prompts to delete local branches for merged PRs. Use `--prune` to skip the prompt. In non-interactive environments, pruning only happens when `--prune` is passed explicitly\n\n**Output (stderr):**\n\n- `✓ Fetched latest changes from origin`\n- `Pulling N new branches from the remote stack ...` then `✓ Pulled N new branches into the stack from the remote` (when the remote stack is ahead)\n- `⚠ Your local stack has diverged from the stack on GitHub` (with `Local:` \u002F `Remote:` chains) when the stacks have diverged\n- `ℹ Sync aborted — no changes were made` when a sync is cancelled\n- `✓ Trunk main fast-forwarded to \u003Csha>` or `✓ Trunk main is already up to date`\n- `✓ Rebased \u003Cbranch> onto \u003Cbase>` per branch (if base moved)\n- `✓ Pushed N branches`\n- `✓ PR #N (\u003Cbranch>) — Open` per branch\n- `Merged: #N, #M` for merged branches\n- `✓ Stack created on GitHub with N PRs` \u002F `✓ Stack updated on GitHub with N PRs` \u002F `✓ Linked to the existing stack on GitHub` (when two or more PRs exist)\n- `✓ Pruned \u003Cbranch> (merged)` per pruned branch (when pruning)\n- `✓ Stack synced` when the stack object on GitHub was created\u002Fupdated to match local, or `✓ Branches synced` when only the branches were synced (fewer than two PRs or stacked PRs unavailable)\n\n---\n\n### Rebase the stack — `gh stack rebase`\n\nPull from remote and cascade-rebase stack branches. Use this when `sync` reports a conflict or when you need finer control (e.g., rebase only part of the stack).\n\n```\ngh stack rebase [flags] [branch]\n```\n\n```bash\n# Rebase the entire stack\ngh stack rebase\n\n# Rebase only branches from trunk to current branch\ngh stack rebase --downstack\n\n# Rebase only branches from current branch to top\ngh stack rebase --upstack\n\n# Rebase stack branches without pulling from or rebasing with trunk\ngh stack rebase --no-trunk\n\n# After resolving a conflict: stage files with `git add`, then:\ngh stack rebase --continue\n\n# Abort and restore all branches to pre-rebase state\ngh stack rebase --abort\n```\n\n| Flag | Description |\n|------|-------------|\n| `--downstack` | Only rebase branches from trunk to the current branch |\n| `--upstack` | Only rebase branches from the current branch to the top |\n| `--no-trunk` | Skip trunk — only rebase stack branches onto each other (no fetch, no trunk rebase) |\n| `--continue` | Continue after resolving conflicts |\n| `--abort` | Abort and restore all branches |\n| `--remote \u003Cname>` | Remote to fetch from (use if multiple remotes exist) |\n\n| Argument | Description |\n|----------|-------------|\n| `[branch]` | Target branch (defaults to the current branch) |\n\n**Conflict handling:** See [Handle rebase conflicts](#handle-rebase-conflicts-agent-workflow) in the Workflows section for the full resolution workflow.\n\n**Merged PR detection:** If a branch's PR was merged on GitHub, the rebase automatically handles this using `--onto` mode and correctly replays commits on top of the merge target.\n\n**Rerere (conflict memory):** `git rerere` is enabled by `init` so previously resolved conflicts are auto-resolved in future rebases.\n\n**No-trunk mode:** Use `--no-trunk` to skip fetching from the remote and rebasing with the trunk branch. Only inter-branch rebases are performed (branch 2 onto branch 1, branch 3 onto branch 2, etc.). Useful when you only need to align stack branches with each other without pulling upstream changes.\n\n---\n\n### View the stack — `gh stack view`\n\nDisplay the current stack's branches, PR status, and recent commits. **Always pass `--json`** — without it, this command launches an interactive TUI that agents cannot operate.\n\n```bash\n# Always use --json\ngh stack view --json\n```\n\n| Flag | Description |\n|------|-------------|\n| `--json` | Output stack data as JSON to stdout (**required** for non-interactive use) |\n\n**`--json` output format:**\n\n```json\n{\n  \"trunk\": \"main\",\n  \"currentBranch\": \"api-routes\",\n  \"branches\": [\n    {\n      \"name\": \"auth\",\n      \"head\": \"abc1234...\",\n      \"base\": \"def5678...\",\n      \"isCurrent\": false,\n      \"isMerged\": true,\n      \"needsRebase\": false,\n      \"pr\": {\n        \"number\": 42,\n        \"url\": \"https:\u002F\u002Fgithub.com\u002Fowner\u002Frepo\u002Fpull\u002F42\",\n        \"state\": \"MERGED\"\n      }\n    },\n    {\n      \"name\": \"api-routes\",\n      \"head\": \"789abcd...\",\n      \"base\": \"abc1234...\",\n      \"isCurrent\": true,\n      \"isMerged\": false,\n      \"needsRebase\": false,\n      \"pr\": {\n        \"number\": 43,\n        \"url\": \"https:\u002F\u002Fgithub.com\u002Fowner\u002Frepo\u002Fpull\u002F43\",\n        \"state\": \"OPEN\"\n      }\n    }\n  ]\n}\n```\n\nFields per branch:\n- `name` — branch name\n- `head` — current HEAD SHA\n- `base` — parent branch's HEAD SHA at last sync\n- `isCurrent` — whether this is the checked-out branch\n- `isMerged` — whether the PR has been merged\n- `needsRebase` — whether the base branch is not an ancestor (non-linear history)\n- `pr` — PR metadata (omitted if no PR exists). `state` is `\"OPEN\"` or `\"MERGED\"`.\n\n---\n\n### Navigate the stack\n\nMove between branches without remembering branch names. These commands are fully non-interactive.\n\n```bash\ngh stack up          # Move up one branch (further from trunk)\ngh stack up 3        # Move up three branches\ngh stack down        # Move down one branch (closer to trunk)\ngh stack down 2      # Move down two branches\ngh stack top         # Jump to the top of the stack (furthest from trunk)\ngh stack bottom      # Jump to the bottom (first non-merged branch above trunk)\n```\n\nNavigation clamps to stack bounds. Merged branches are skipped when navigating from active branches.\n\n---\n\n### Check out a stack — `gh stack checkout`\n\nCheck out a stack from a pull request number or branch name. **Always provide an argument** — running `gh stack checkout` without arguments triggers an interactive selection menu.\n\n```\ngh stack checkout \u003Cpr-number | branch>\n```\n\n```bash\n# By PR number (pulls from GitHub)\ngh stack checkout 42\n\n# By branch name (local only)\ngh stack checkout feature-auth\n```\n\nWhen a PR number is provided (e.g. `123`), the command fetches the stack on GitHub, pulls the branches, and sets up the stack locally. If the stack already exists locally and matches, it switches to the branch.\n\n> **⚠️ Agent warning:** If the local and remote stacks have different branch compositions, this command triggers an interactive conflict-resolution prompt that cannot be bypassed with a flag. To avoid this: run `gh stack unstack` first to remove the conflicting local stack, then retry `gh stack checkout \u003Cpr-number>`.\n\nWhen a branch name is provided, the command resolves it against locally tracked stacks only. This is always safe for non-interactive use.\n\n---\n\n### Remove a stack — `gh stack unstack`\n\nTear down a stack so you can restructure it — remove a branch, reorder branches, rename branches, or make other large changes. After unstacking, use `gh stack init` to re-create the stack with the desired structure.\n\nWith no argument, the command targets the active stack — the one containing the currently checked out branch — unstacking it on GitHub and removing local tracking.\n\nProvide a stack number to unstack a specific stack on GitHub. This works from anywhere in the repository, whether or not the stack is checked out locally — the number is unstacked directly through the GitHub API (like `gh stack link`, no local tracking required). If the stack is also tracked locally, its local tracking is removed as well.\n\n```\ngh stack unstack [\u003Cstack-number>] [flags]\n```\n\n```bash\n# Tear down the current stack (locally and on GitHub), then rebuild\ngh stack unstack\ngh stack init --base main branch-2 branch-1 branch-3 # reordered\n\n# Unstack a specific stack by its number, from anywhere in the repo\ngh stack unstack 7\n\n# Only remove local tracking (keep the stack on GitHub)\ngh stack unstack --local\n```\n\n| Flag | Description |\n|------|-------------|\n| `--local` | Only remove the stack locally (keep it on GitHub); never contacts GitHub |\n\n> **Note for agents:** `gh stack unstack \u003Cnumber>` is a remote-first API wrapper — it unstacks on GitHub by number from anywhere in the repo, tracked locally or not, and is safe for non-interactive use. `--local` never contacts GitHub; combining `--local` with a number that isn't tracked locally is an error. An unknown stack number returns a \"not found on GitHub\" error (exit code 2).\n\n---\n\n## Output conventions\n\n- **Status messages** go to **stderr** with emoji prefixes: `✓` (success), `✗` (error), `⚠` (warning), `ℹ` (info).\n- **Data output** (e.g., `view --json`) goes to **stdout**.\n- When piping output, use `2>\u002Fdev\u002Fnull` to suppress status messages if only data output is needed.\n\n## Exit codes and error recovery\n\n| Code | Meaning | Agent action |\n|------|---------|-------------|\n| 0 | Success | Proceed normally |\n| 1 | Generic error | Read stderr for details; may indicate commit\u002Fpush failure |\n| 2 | Not in a stack | Run `gh stack init` to create a stack first |\n| 3 | Rebase conflict | Parse stderr for conflicted file paths, resolve conflicts, run `gh stack rebase --continue` |\n| 4 | GitHub API failure | Check `gh auth status`, retry the command |\n| 5 | Invalid arguments | Fix the command invocation (check flags and arguments) |\n| 6 | Disambiguation required | A branch belongs to multiple stacks. Run `gh stack checkout \u003Cspecific-branch>` to switch to a non-shared branch first |\n| 7 | Rebase already in progress | Run `gh stack rebase --continue` (after resolving conflicts) or `gh stack rebase --abort` to start over |\n| 8 | Stack is locked | Another `gh stack` process is writing the stack file. Wait and retry — the lock times out after 5 seconds |\n| 9 | Stacked PRs unavailable | The repository does not have stacked PRs enabled. `submit` will offer to create regular (unstacked) PRs in interactive mode |\n\n## Known limitations\n\n1. **Stacks are strictly linear.** Branching stacks (multiple children on a single parent) are not supported. Each branch has exactly one parent and at most one child. If you need parallel workstreams, use separate stacks.\n2. **Stack disambiguation cannot be bypassed.** If the current branch is the trunk of multiple stacks, commands error with code 6. Check out a non-shared branch first.\n3. **Multiple remotes require `--remote` or config.** If more than one remote is configured, pass `--remote \u003Cname>` or set `remote.pushDefault` in git config before running `push`, `sync`, or `rebase`.\n4. **Merging PRs:** Merging Stacked PRs from the CLI is not supported yet. Direct users to open the PR URL in a browser to merge PRs.\n5. **Remote stack checkout requires a PR number.** `checkout` with a branch name only works with locally tracked stacks. Use a PR number (e.g. `gh stack checkout 123`) to pull stacks from GitHub.\n6. **PR title and body are auto-generated.** There is no flag to set a custom PR title or body during `submit`. The title and body are generated from commit messages plus a footer. Use `gh pr edit` to modify PR title and body after creation.\n",{"name":5,"metadata":58,"description":60},{"author":49,"version":59},"0.0.8","Manage stacked branches and pull requests with the gh-stack GitHub CLI extension. Use when the user wants to create, push, rebase, sync, navigate, or view stacks of dependent PRs. Triggers on tasks involving stacked diffs, dependent pull requests, branch chains, or incremental code review workflows.\n","main","e63965e4644984470d4cc8b3014a8b001f0c2666",".agents\u002Fskills\u002Fgh-stack","https:\u002F\u002Fgithub.com\u002Fbnferguson\u002Fdotfiles","https:\u002F\u002Fgithub.com\u002Fbnferguson","2026-11-11 03:04:59",{"source":9,"skillName":5,"commands":68,"prompt":78,"zipAvailable":79},[69,72,75],{"tool":70,"command":71},"npx","npx skills add bnferguson\u002Fdotfiles --skill gh-stack",{"tool":73,"command":74},"bunx","bunx skills add bnferguson\u002Fdotfiles --skill gh-stack",{"tool":76,"command":77},"pnpm","pnpm dlx skills add bnferguson\u002Fdotfiles --skill gh-stack","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbnferguson\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgh-stack\u002FSKILL.md",true,[],[82,115,132,165,182,198],{"skillNo":83,"name":84,"nameZh":85,"description":86,"descriptionZh":87,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":88,"licenseFileUrl":89,"sourceHtmlUrl":90,"categories":91,"keywords":98,"publishedAt":53},"01M6BVA3RS3M016FANZ6792F9H","skill-creator","Claude 技能创建指南","Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that extends Claude's capabilities with specialized knowledge, workflows, or tool integrations.","创建有效技能的指南。当用户想要创建新技能（或更新现有技能），以通过专业知识、工作流或工具集成来扩展 Claude 的能力时，应使用此技能。","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fbnferguson\u002Fdotfiles\u002Fblob\u002Fmain\u002Fclaude\u002Fconfig\u002Fskills\u002Fskill-creator\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fbnferguson\u002Fdotfiles\u002Fblob\u002Fmain\u002Fclaude\u002Fconfig\u002Fskills\u002Fskill-creator\u002FSKILL.md",[92,95],{"categoryNo":93,"categoryName":94,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BRN0CV1NMDZ5TEJX1GVM29","插件与技能管理",{"categoryNo":96,"categoryName":97,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BRZZF9D7PVFN5MXSPWWD61","AI 工程师",[99,100,101,48,44,102,103,104,105,106,107,108,109,110,111,112,113,35,114],"creator","skill creator","specialized","update","capabilities","knowledge","tool","integrations","guide","new skill","existing skill","users","with","for","Existing","new",{"skillNo":116,"name":117,"nameZh":118,"description":119,"descriptionZh":120,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":121,"categories":122,"keywords":129,"publishedAt":53},"01M6BV94WN2RPYM8N6PN8TBNT8","writing-shape","素材成文逐段撰写","Writing, exploit: shape raw material into an article, paragraph by paragraph.","写作，利用（exploit）：将原始素材逐段塑造成一篇文章。","https:\u002F\u002Fgithub.com\u002Fbnferguson\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwriting-shape\u002FSKILL.md",[123,126],{"categoryNo":124,"categoryName":125,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8C55A3R2M9C8CAKG3W16HTA","内容创作者",{"categoryNo":127,"categoryName":128,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8CA3WT74BY17JY9YCJY42FJ","创意写作与内容编排",[130,131],"writing shape","writing",{"skillNo":133,"name":134,"nameZh":135,"description":136,"descriptionZh":137,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":88,"licenseFileUrl":138,"sourceHtmlUrl":139,"categories":140,"keywords":147,"publishedAt":53},"01M6BV8QDFJ6PXBVK5NFBZT5M7","webapp-testing","Playwright 网页应用测试","Test local web applications using Playwright. Use when verifying frontend functionality, debugging UI behavior, capturing browser screenshots, or viewing browser logs.","使用 Playwright 测试本地 Web 应用。适用于验证前端功能、调试 UI 行为、截取浏览器截图或查看浏览器日志。","https:\u002F\u002Fgithub.com\u002Fbnferguson\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fbnferguson\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwebapp-testing\u002FSKILL.md",[141,144],{"categoryNo":142,"categoryName":143,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BQGD5WG86P4AQ5GPSSKBFR","测试工程师",{"categoryNo":145,"categoryName":146,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BQJH394GT47X57A9Q8G7HX","测试与质量保障",[148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,35],"webapp","webapp testing","testing","browser","frontend","screenshots","playwright","test","web","debugging","ui","logs","applications","behavior","use","local","test local",{"skillNo":166,"name":167,"nameZh":168,"description":169,"descriptionZh":170,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":171,"categories":172,"keywords":179,"publishedAt":53},"01M6BV8MDXKXNVHKS3QF3YDFTF","wait-what","消息重述","Stop. That last message did not land: re-pitch it.","停。上一条消息没有被理解（没说清楚）：换一种方式重新表述。","https:\u002F\u002Fgithub.com\u002Fbnferguson\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwait-what\u002FSKILL.md",[173,176],{"categoryNo":174,"categoryName":175,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BS5011KJDVSRXG1DC4P666","普通用户",{"categoryNo":177,"categoryName":178,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8C1YEW2680C003GGBD6QCKB","回复风格与输出控制",[180,181],"wait what","land",{"skillNo":183,"name":184,"nameZh":185,"description":186,"descriptionZh":187,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":188,"categories":189,"keywords":194,"publishedAt":53},"01M6BV756DJHT5BDA1HVRVHJJ7","prototype","快速原型构建","Build a throwaway prototype to answer a design question. Use when the user wants to sanity-check whether a state model or logic feels right, or explore what a UI should look like.","构建一个一次性原型来回答设计问题。当用户想要验证某个状态模型或逻辑是否合理，或探索 UI 应该是什么样子时使用。","https:\u002F\u002Fgithub.com\u002Fbnferguson\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fprototype\u002FSKILL.md",[190,191],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":192,"categoryName":193,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BT7QTSZKB08EAW9P9ZCDNQ","设计评审与架构优化",[184,195,196,158,197],"design","explore","state",{"skillNo":199,"name":200,"nameZh":201,"description":202,"descriptionZh":203,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":204,"categories":205,"keywords":210,"publishedAt":53},"01M6BV6SBW166685KVBPWM2K4N","improve-codebase-architecture","代码库架构优化分析","Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you pick.","扫描代码库以发现可深化改进的机会，将其以可视化 HTML 报告的形式呈现，然后对你选中的某一项进行深入质询。","https:\u002F\u002Fgithub.com\u002Fbnferguson\u002Fdotfiles\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fimprove-codebase-architecture\u002FSKILL.md",[206,207],{"categoryNo":192,"categoryName":193,"taxonomyType":28,"taxonomyTypeDesc":29},{"categoryNo":208,"categoryName":209,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8C4ZVS0ZJKF2T2G58PW5VR2","系统架构师",[211,212,213,214],"architecture","improve","improve codebase architecture","report"]