44 "errors"
55 "fmt"
66 "net/url"
7+ "slices"
78 "strconv"
89 "strings"
910 "sync"
@@ -1229,7 +1230,7 @@ const (
12291230// a missing client, stacked PRs being unavailable, or any API error causes it
12301231// to skip so the rest of sync still runs. Untracked stacks (s.ID == "") are
12311232// left to the syncStack/reconcileUntrackedStack path.
1232- func reconcileRemoteStack (cfg * config.Config , sf * stack.StackFile , s * stack.Stack , gitDir , remote string ) (remoteReconcileResult , error ) {
1233+ func reconcileRemoteStack (cfg * config.Config , sf * stack.StackFile , s * stack.Stack , currentBranch , gitDir , remote string ) (remoteReconcileResult , error ) {
12331234 var res remoteReconcileResult
12341235
12351236 if s .ID == "" {
@@ -1276,7 +1277,7 @@ func reconcileRemoteStack(cfg *config.Config, sf *stack.StackFile, s *stack.Stac
12761277 case remoteStackCleanAhead :
12771278 return pullRemoteAdditions (cfg , sf , s , gitDir , remote , prs )
12781279 default :
1279- return resolveStackDivergence (cfg , client , sf , s , gitDir , remote , prs , remoteActive )
1280+ return resolveStackDivergence (cfg , client , sf , s , currentBranch , gitDir , remote , prs , remoteActive )
12801281 }
12811282}
12821283
@@ -1414,7 +1415,7 @@ func pullRemoteAdditions(cfg *config.Config, sf *stack.StackFile, s *stack.Stack
14141415// from the remote (neither is a prefix of the other). In an interactive
14151416// terminal it prompts the user to resolve it; otherwise (or when the user
14161417// cancels) it aborts the sync so nothing is pushed or updated.
1417- func resolveStackDivergence (cfg * config.Config , client github.ClientOps , sf * stack.StackFile , s * stack.Stack , gitDir , remote string , prs []* github.PullRequest , remoteActive []string ) (remoteReconcileResult , error ) {
1418+ func resolveStackDivergence (cfg * config.Config , client github.ClientOps , sf * stack.StackFile , s * stack.Stack , currentBranch , gitDir , remote string , prs []* github.PullRequest , remoteActive []string ) (remoteReconcileResult , error ) {
14181419 cfg .Printf ("" )
14191420 cfg .Warningf ("Your local stack has diverged from the stack on GitHub" )
14201421 cfg .Printf (" Local: %s" , s .DisplayChain ())
@@ -1454,7 +1455,7 @@ func resolveStackDivergence(cfg *config.Config, client github.ClientOps, sf *sta
14541455
14551456 switch selected {
14561457 case 0 :
1457- return resolveDivergenceUseRemote (cfg , sf , s , gitDir , remote , prs )
1458+ return resolveDivergenceUseRemote (cfg , sf , s , currentBranch , gitDir , remote , prs )
14581459 case 1 :
14591460 return resolveDivergenceUseLocal (cfg , client , sf , s , gitDir )
14601461 case 2 :
@@ -1470,7 +1471,7 @@ func resolveStackDivergence(cfg *config.Config, client github.ClientOps, sf *sta
14701471// destructive to stack tracking). Local-only branches remain as git refs but
14711472// are no longer part of the stack. Returns the rebuilt stack pointer so the
14721473// caller can continue with it (importRemoteStack reslices StackFile.Stacks).
1473- func resolveDivergenceUseRemote (cfg * config.Config , sf * stack.StackFile , s * stack.Stack , gitDir , remote string , prs []* github.PullRequest ) (remoteReconcileResult , error ) {
1474+ func resolveDivergenceUseRemote (cfg * config.Config , sf * stack.StackFile , s * stack.Stack , currentBranch , gitDir , remote string , prs []* github.PullRequest ) (remoteReconcileResult , error ) {
14741475 var res remoteReconcileResult
14751476
14761477 if dirty , err := git .HasUncommittedChanges (); err == nil && dirty {
@@ -1481,13 +1482,26 @@ func resolveDivergenceUseRemote(cfg *config.Config, sf *stack.StackFile, s *stac
14811482
14821483 trunk := s .Trunk .Branch
14831484 remoteStackID := s .ID
1485+ oldBranches := s .BranchNames ()
14841486
14851487 removeLocalStack (sf , s )
14861488 newStack , err := importRemoteStack (cfg , sf , gitDir , remote , trunk , prs , remoteStackID )
14871489 if err != nil {
14881490 res .skipStackObjectSync = true
14891491 return res , err
14901492 }
1493+
1494+ // If the user was on a branch that the remote stack no longer contains,
1495+ // move them to the nearest surviving branch so they don't end up detached
1496+ // from the stack.
1497+ if target := nearestBranchAfterReplace (oldBranches , currentBranch , newStack ); target != currentBranch {
1498+ if err := git .CheckoutBranch (target ); err != nil {
1499+ cfg .Warningf ("Failed to switch from %s to %s: %v" , currentBranch , target , err )
1500+ } else {
1501+ cfg .Printf ("Switched to %s (original branch %s is no longer in the stack)" , target , currentBranch )
1502+ }
1503+ }
1504+
14911505 if err := stack .Save (gitDir , sf ); err != nil {
14921506 res .skipStackObjectSync = true
14931507 return res , handleSaveError (cfg , err )
@@ -1498,6 +1512,33 @@ func resolveDivergenceUseRemote(cfg *config.Config, sf *stack.StackFile, s *stac
14981512 return res , nil
14991513}
15001514
1515+ // nearestBranchAfterReplace decides which branch to check out after the local
1516+ // stack has been replaced with the remote version. If currentBranch still
1517+ // exists in newStack (or the user was on the trunk / a non-stack branch), it is
1518+ // returned unchanged. Otherwise it delegates to stack.NearestSurvivingBranch to
1519+ // pick the nearest branch from the pre-replacement ordering (neighbor above,
1520+ // then below), falling back to the top of the new stack, or the trunk if the new
1521+ // stack has no branches. Mirrors the checkout behavior of `gh stack modify`.
1522+ func nearestBranchAfterReplace (oldBranches []string , currentBranch string , newStack * stack.Stack ) string {
1523+ // Still in the new stack, or never a stack branch (e.g. the trunk): stay put.
1524+ if newStack .IndexOf (currentBranch ) >= 0 || slices .Index (oldBranches , currentBranch ) < 0 {
1525+ return currentBranch
1526+ }
1527+
1528+ if nearest := stack .NearestSurvivingBranch (oldBranches , currentBranch , func (name string ) bool {
1529+ return newStack .IndexOf (name ) >= 0
1530+ }); nearest != "" {
1531+ return nearest
1532+ }
1533+
1534+ // A dropped stack branch with no surviving neighbor — fall back to the top
1535+ // of the new stack, then the trunk.
1536+ if len (newStack .Branches ) > 0 {
1537+ return newStack .Branches [len (newStack .Branches )- 1 ].Branch
1538+ }
1539+ return newStack .Trunk .Branch
1540+ }
1541+
15011542// resolveDivergenceUseLocal makes the remote match the local stack by deleting
15021543// the diverged remote stack object and clearing the local ID. The normal
15031544// syncStack step then recreates the stack from the local PR list (when two or
0 commit comments