Skip to content

feat: add wt sync command to rebase stacked worktree branches - #2053

Closed
pablospe wants to merge 23 commits into
max-sixty:mainfrom
pablospe:task/8aef9d67-wt-sync
Closed

pablospe wants to merge 23 commits into
max-sixty:mainfrom
pablospe:task/8aef9d67-wt-sync

Conversation

@pablospe

@pablospe pablospe commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Add wt sync — auto-detects the branch dependency tree from git history and rebases each branch onto its parent in topological order
  • No configuration needed — dependencies are inferred from pairwise merge-base analysis
  • Handles integrated (squash-merged) branches by reparenting children with rebase --onto
  • Stack file (.git/wt/stack) is auto-created on every sync for reliable parent tracking and non-default branch integration detection

Scenarios

1. Main advances — all stacked branches rebase in order

main ─ A ─ X (new)
       └── PR1 ─ D
                  └── PR2 ─ F
                             └── PR3 ─ H

wt sync rebases PR1 onto main, PR2 onto PR1, PR3 onto PR2.

2. Mid-stack change — downstream branches update

main ─ A
       └── PR1 ─ D ─ Z (new fix)
                  └── PR2 ─ F  (stale)
                             └── PR3 ─ H

wt sync detects PR2 is behind PR1, rebases PR2 and PR3.

3. PR squash-merged to main — children reparent with rebase --onto

main ─ A ─ [PR1 squashed]
       └── PR1 ─ D  (integrated)
                  └── PR2 ─ F
                             └── PR3 ─ H

wt sync detects PR1 is integrated (reuses wt list's ⊂ detection), reparents PR2 onto main via rebase --onto, then rebases PR3 onto PR2.

4. PR squash-merged into non-default parent — stack file enables detection

Stack: main ← PR1 ← PR2 ← PR3
PR2 gets squash-merged into PR1 (not main):
  PR1 now contains PR2's changes
  PR3 should reparent onto PR1

Without a stack file, integration_reason(PR2, main) returns nothing — PR2 isn't merged into main. With the stack file, sync knows PR2's parent is PR1 and checks integration_reason(PR2, PR1), detecting the integration and reparenting PR3 onto PR1.

5. Cascading merges — multiple levels collapse correctly

Stack: main ← PR1 ← PR2 ← PR3
Step 1: squash-merge PR2 into PR1 → sync detects, reparents PR3 onto PR1
Step 2: squash-merge PR1 into main → sync detects, reparents PR3 onto main

The reparenting logic walks up the parent chain to find the first non-integrated ancestor, handling arbitrary nesting depth.

The --stack flag

By default, wt sync syncs all stacks. With --stack, only the current stack is synced.

Say you have two independent stacks:

main
├── pr-auth → pr-auth-tests       (stack A — you're here)
└── pr-refactor → pr-cleanup      (stack B — unrelated work)

If main advances:

wt sync (default — syncs everything):

Rebasing pr-auth onto main...         ✓
Rebasing pr-auth-tests onto pr-auth...✓
Rebasing pr-refactor onto main...     ✓
Rebasing pr-cleanup onto pr-refactor..✓
Sync complete: 4 rebased

wt sync --stack (from pr-auth's worktree — only stack A):

Rebasing pr-auth onto main...         ✓
Rebasing pr-auth-tests onto pr-auth...✓
Sync complete: 2 rebased

Why not git rebase --update-refs?

Git 2.38 added --update-refs for stacked branches, but it explicitly skips branches checked out in worktrees:

"Any branches that are checked out in a worktree are not updated in this way."

Git silently skips those refs without warning. Since worktrees are the core of worktrunk, wt sync rebases each branch individually in its own worktree, in topological order.

Stack file (.git/wt/stack)

The dependency tree is persisted to .git/wt/stack on every sync. The format is git-machete compatible (indentation-based, one branch per line):

pr1
	pr2
		pr3

The stack file is central to sync's reliability. It enables three things:

  1. Stable parent tracking — after rebasing + mid-stack commits, the parent branch becomes "diverged" from the commit graph's perspective and merge-base inference may pick the wrong parent. The stack file preserves the correct parent relationships across syncs.

  2. Non-default branch integration detection — when a stacked PR is squash-merged into another stacked branch (not main), integration_reason(branch, main) returns nothing. The stack file tells sync to also check integration_reason(branch, parent), catching these merges.

  3. Reparenting with parent chain walking — when an integrated branch's parent is also integrated (cascading merges), sync walks up the stack file's parent chain to find the first non-integrated ancestor, rather than always falling back to main.

The file is human-editable — adjust indentation to change the tree. After a PR merges, sync automatically removes integrated branches from the file.

CLI

wt sync              # Sync all stacks (default)
wt sync --stack      # Sync current stack only
wt sync --dry-run    # Preview the plan
wt sync --fetch      # git fetch --prune before syncing
wt sync --push       # git push --force-with-lease after syncing
wt sync --prune      # Remove integrated worktrees and remote branches

All flags have config equivalents in [sync]:

[sync]
fetch = false    # Fetch from remote before syncing
push = false     # Force-push rebased branches after syncing
prune = false    # Remove integrated worktrees and remote branches
all = true       # Sync all stacks (false = current stack only)

Conflict handling

On conflict, sync stops at the failing branch with a hint:

✗ Rebase conflict while rebasing pr2 onto pr1
  Resolve conflicts in /path/to/pr2, then run:
  cd /path/to/pr2
  git rebase --continue
  wt sync

Algorithm

Parent detection (first sync or no stack file)

For each branch, find the closest parent via pairwise merge-base + count_commits:

  1. Compute merge_base(candidate, branch) for every other branch
  2. Measure branch_depth = commits from merge-base to branch tip
  3. Measure candidate_depth = commits from merge-base to candidate tip
  4. True ancestors (candidate_depth == 0, meaning the candidate's tip is reachable from the branch): pick the one with smallest branch_depth
  5. Diverged candidates (only if no true ancestors): pick by smallest branch_depth, then smallest candidate_depth
  6. Tie-breaking: when multiple candidates have equal depth, pick the one with the most recent merge-base timestamp

True ancestors are preferred over diverged candidates to prevent cycles in stacked branches.

Integration detection (two-phase)

  1. Phase 1: Check every branch against the default branch (main) — catches PRs squash-merged to main
  2. Phase 2: With a stack file, also check every branch against its explicit parent — catches PRs squash-merged into non-default parent branches

Subsequent syncs (stack file exists)

Parents are read from the stack file instead of inferred. The stack file is updated after every sync to reflect the current tree (integrated branches removed, new worktrees added).

Test plan

  • 19 integration tests covering all five scenarios, dry-run, dirty worktree abort, --stack flag, default-syncs-all, up-to-date detection, --fetch, --push, --push with deleted remote, --prune
  • Stack file tests: auto-creation, stack file fixes scenario 2, non-default branch integration
  • Mid-stack parent merge and cascading merge tests
  • E2E tested against a real GitHub repo with 5-PR stacked workflow (temporary test-sync-e2e.sh)
  • Config doc sync and help snapshot tests pass

Comment thread test-sync-e2e.sh

ghost Apr 10, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will remove this before merging, but it helps me to run some tests with github.

@max-sixty

ghost commented Apr 10, 2026

Copy link
Copy Markdown
Owner

thanks for the effort

are there ways we could break this up? it's not really viable to review 3.5K lines of code!

what benefits could we see from more incremental changes, at first?

Pablo Speciale added 15 commits April 10, 2026 16:07
Detects the branch dependency tree from git's commit graph using
pairwise merge-base analysis, then rebases each branch onto its
parent in topological order.

Key behaviors:
- No configuration needed — dependencies are inferred from git history
- By default, only syncs the stack containing the current branch
- `--all` syncs all worktree branches
- `--dry-run` shows the dependency tree and planned rebases
- Detects integrated (squash-merged) branches and reparents children
  using `rebase --onto`
- Dirty worktree pre-check prevents partial sync failures
Flip the default: `wt sync` now syncs all worktree branches across all
stacks. Use `--stack` to limit to the current stack only.

Also improve the after_long_help documentation with a visual example
showing the difference between default and --stack behavior.
Add optional phases to `wt sync`:
- --fetch: run `git fetch --prune` before syncing
- --push: force-push rebased branches with --force-with-lease
- --prune: remove integrated worktrees (worktree + local branch + remote)

All phases configurable via [sync] section in user/project config:

  [sync]
  fetch = false
  all = true
  push = false
  prune = false

CLI flags override config: --fetch/--no-fetch, --push/--no-push,
--prune/--no-prune, --stack/--all.
Add explicit stack definition via `.git/wt/stack` file (git-machete
compatible format) to solve the mid-stack commit parent detection
limitation. When this file exists, `wt sync` reads parents from it
instead of inferring from the commit graph.

- `wt sync --save` persists the inferred dependency tree
- Stack file uses indentation-based tree format (tabs or spaces)
- Supports comments (#) and annotations after branch names
- Add [sync] config section documentation
- Fix test_valid_user_config_keys_all_deserialize for sync section
When a stack file exists, `wt sync` now checks integration against each
branch's explicit parent (not just main). This detects merges between
stacked branches — e.g., PR2 squash-merged into PR1.

Children of integrated branches are reparented by walking up the stack
file's parent chain to find the first non-integrated ancestor, instead
of always falling back to the default branch.
The stack file (.git/wt/stack) is now always persisted after building
the dependency tree. This ensures parent-based integration detection
(e.g., PR merged into non-default branch) works from the first sync
without requiring the user to remember --save.
Add two integration tests covering scenarios previously only tested E2E:

- test_sync_mid_stack_pr_merged_into_parent: PR3 squash-merged into its
  parent PR2 (mid-stack, not main). Verifies PR4 reparents onto PR2.

- test_sync_cascading_merges: PR2 merged into PR1, then PR1 merged into
  main. Verifies PR3 correctly reparents through both merges.
Includes a self-contained E2E test that creates a real GitHub repo,
builds a 5-PR stack, and validates sync scenarios (rebase, squash-merge
reparenting, non-default branch integration detection, push with
pruned remotes). Will be removed before merging.
Add remove_fixture_worktrees() and worktree prune to all sync tests.
The standard TestRepo fixture includes feature-a/b/c worktrees that
caused spurious "equidistant parents" warnings and "Failed to execute:
git status --porcelain" errors in sync test snapshots.
Covers the gap where --push skips branches whose remote was deleted
(e.g., after a PR merge on GitHub). Previously only tested in E2E.
- Fix stale --save references in module docstring and comments (removed
  in earlier commit, but references remained)
- Fix module docstring claiming default is current-stack-only (actual
  default is all stacks)
- Remove dead code: empty if-block and unused line_num suppression
- Add visited set to reparenting loop to prevent infinite loops from
  cycles in hand-edited stack files
- Update --prune help text to mention remote branch deletion

Skipped: parse_stack_file indent handling (tabs vs spaces) — edge case
with hand-edited files, format_stack_file always writes tabs. Conflict
handling, push failure, prune failure test coverage — straightforward
print-and-continue error paths, not worth the test complexity.
- Remove unused line_num from parse_stack_file enumerate loop
- On cycle detection in reparenting, fall back to default branch
  instead of leaving new_parent pointing at an integrated branch
Squash-merges PR2 via GitHub, then syncs with --fetch --prune --push.
Verifies worktree removal, stack file update, remote branch deletion,
and correct reparenting of downstream branches.
The prune phase was deleting the local branch with `branch -D` before
checking for an upstream tracking branch. This meant the upstream check
always returned None, so remote branches were never cleaned up.

Found by E2E Test 7 (--prune with real GitHub repo).
Resolve snapshot conflict from {{ owner }} template variable added in main.
@pablospe
pablospe force-pushed the task/8aef9d67-wt-sync branch from a64bd9c to cfee132 Compare April 10, 2026 14:11
@pablospe

ghost commented Apr 10, 2026

Copy link
Copy Markdown
Contributor Author

I am primarily seeking feedback on this because it involves several design decisions. I've been experimenting with the new wt sync, and I find it very useful for my workflow. It has potential.

are there ways we could break this up? it's not really viable to review 3.5K lines of code!

Yes, if you exclude the tests, it is a "reasonable" size, except for sync.rs (I guess the core component).
image

I can address some of the cases in separate PRs, not sure how to split it, need to think. One thing I need to remove is the test-sync-e2e.sh, so please don't review it. I included temporarily so you could also run it and see how I'm testing this. Perhaps you have other ideas there too, besides the unit tests I addeed.

1 similar comment
@pablospe

ghost commented Apr 10, 2026

Copy link
Copy Markdown
Contributor Author

I am primarily seeking feedback on this because it involves several design decisions. I've been experimenting with the new wt sync, and I find it very useful for my workflow. It has potential.

are there ways we could break this up? it's not really viable to review 3.5K lines of code!

Yes, if you exclude the tests, it is a "reasonable" size, except for sync.rs (I guess the core component).
image

I can address some of the cases in separate PRs, not sure how to split it, need to think. One thing I need to remove is the test-sync-e2e.sh, so please don't review it. I included temporarily so you could also run it and see how I'm testing this. Perhaps you have other ideas there too, besides the unit tests I addeed.

ghost left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few notes from a fresh read.

CI is failing on three fixable items — all from this PR, none flaky:

  1. Three clippy errors in src/commands/sync.rs (let_and_return at L182, two collapsible_if at L318 and L422). Inline suggestions below.
  2. Four shell-completion snapshots are missing the new sync subcommand (bash_completion_subcommands, zsh_completion_subcommands, fish_completion_subcommands, nushell_completion_subcommands under tests/integration_tests/snapshots/). They each list switch / list / remove / merge / step / hook / config; sync needs to slot in between remove and merge to match the Commands enum order in src/cli/mod.rs:578. cargo insta test --accept will regenerate them.

Data-safety question on --prune. src/commands/sync.rs:826 calls git worktree remove --force, which silently deletes any untracked files in the integrated worktree (build artifacts, scratch notes, an unrelated .env, etc.). CLAUDE.md says: "Prefer failure over silent data loss" and "Operations that force-remove data (like --force on remove) require the user to explicitly request that behavior". --prune is opt-in, but it doesn't read like "also discard untracked files" — and wt remove itself requires an explicit --force for that. Worth either dropping --force here (let prune fail loudly when a worktree has untracked files, with a hint to clean it up) or wiring through a separate --prune-force so the destructive variant is named.

Same spot: L843 and L846 swallow errors with let _ = for branch -D and push --delete. If the local branch delete fails (e.g., still checked out somewhere unexpected), the user gets a misleading "Removed integrated worktree" success message. Worth at least logging the error.

Stack-file write happens before the dirty-worktree check (L582 vs L624). Aborting on a dirty worktree still leaves a freshly written .git/wt/stack behind. Probably benign (the file reflects the current tree either way), but moving the write below the safety checks would make it less surprising.

(Acknowledging test-sync-e2e.sh is already noted for removal.)

Comment thread src/commands/sync.rs Resolved
Comment thread src/commands/sync.rs Resolved
Comment thread src/commands/sync.rs Resolved
Pablo Speciale added 2 commits April 10, 2026 16:38
- Inline `let_and_return` in stack file parser
- Collapse nested `if let` + `if` into `if let &&` (two instances)
Drop --force to avoid silently deleting untracked files in integrated
worktrees. Without --force, git worktree remove fails loudly when the
worktree has uncommitted changes, with a hint to clean up manually.
@pablospe

ghost commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor Author

there ways we could break this up?

@max-sixty I am fixing some errors from the bot, that I will include here, but what about this split:

  • PR 1: Stack file parsing/writing, dependency tree, parent detection algorithm
  • PR 2: The sync command — CLI, rebase loop, conflict handling
  • PR 3: Integration detection (non-default parent, reparenting)
  • PR 4: Optional flags (--fetch, --push, --prune) + config

Note: I got inspired by git machete, but this is tailored to the worktree workflow that wt offers.

@max-sixty

ghost commented Apr 10, 2026

Copy link
Copy Markdown
Owner

my main claims are:

  • stacked branches could be really powerful
  • it's a big design space with many options, and so difficult to get right

I personally don't use stacked branches, though I would a bit if there were better approaches

I think two possible approaches from here:

  • someone builds an add-on; I'd be happy to link it from the docs
  • we go incrementally, experiment with small additions, see what works, iterate our way to fuller support

Pablo Speciale added 2 commits April 10, 2026 16:40
Replace `let _ =` on branch -D and push --delete with proper warning
messages so users know when cleanup partially fails.
Move the stack file write to after dirty-worktree and rebase-in-progress
checks so aborting on dirty worktrees doesn't leave a side-effect.
Dry-run still writes the stack file since it reflects the current tree.
@pablospe

ghost commented Apr 10, 2026

Copy link
Copy Markdown
Contributor Author

I personally don't use stacked branches, though I would a bit if there were better approaches

Notice if I split this PR then I will need to use stacked PRs :) and possibly have a chance to test wt sync more.

One question, what do you mean with "builds an add-on"? How would it work?

Add sync to bash, fish, zsh, and nushell completion subcommand snapshots.
@pablospe

ghost commented Apr 10, 2026

Copy link
Copy Markdown
Contributor Author

Addressed all points:

  • Clippy: Fixed let_and_return and both collapsible_if warnings (0b54cc0)
  • Data safety: Removed --force from git worktree remove during prune — now fails loudly with a hint if the worktree has untracked files (15ff34d)
  • Swallowed errors: branch -D and push --delete failures now emit warnings instead of being silently discarded (4d1b36c)
  • Stack file ordering: Moved stack file write to after dirty-worktree and rebase-in-progress checks (87f1b4a)
  • Completion snapshots: Updated bash, fish, zsh, and nushell completion subcommand snapshots to include sync (a97e076)

@max-sixty

ghost commented Apr 10, 2026

Copy link
Copy Markdown
Owner

you release something wt-sync and then wt sync calls it, same as git's approach (not built but would be an easy addition)

@worktrunk-bot please add this generic functionality in a new PR

@pablospe

ghost commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor Author

I split it into three PRs:

PR Branch Base Tests
A - #2059 sync-core main 10 integration + 3 unit
B - #2060 sync-stack-file sync-core 5 integration
C - #2061 sync-flags sync-stack-file 4 integration

@max-sixty Let me know your preference. Do you think we can merge this, or would you prefer to keep it separate from the main repository? Should I close this and the other PRs?

@max-sixty

ghost commented Apr 10, 2026

Copy link
Copy Markdown
Owner

I had meant: what is something incremental — but still useful — that we can merge on our way to something more complete?

There's a huge space of possibilities with stacked branches, so we want to avoid choosing a single point in the space and releasing that immediately, because the first point we think of is unlikely to be the best one. Releasing things incrementally lets us experiment with it, get feedback from others, etc

(Similarly: we wouldn't add a top-level command, it would be a wt step command)

If you think we need the full solution to get value, then releasing worktrunk-sync, which would install a wt-sync binary, is the way to go; I'd be happy to link to it.

does that make sense? sorry if I was unclear above

@pablospe

ghost commented Apr 10, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for clarifying — that makes sense. I agree iterating is better than committing to a big design upfront.

I want to finish addressing a few review fixes on the current PRs first, then I'll mark them as draft or close them (#2059, #2060, #2061). After that, I'll ship this as a separate wt-sync binary that users can install independently — that way I can iterate on the design without blocking the main project, and you can link to it from the docs when it's ready.

A couple of questions:

  • Would you prefer it as a workspace member in this repo (like wt-perf, so it can reuse the existing git/config/styling crates), or as a fully separate repo?
  • For the wt <external-command> dispatch — I saw you asked the bot to add that. Should I wait for that PR, or can I just have users install wt-sync and run it directly for now?

@max-sixty

ghost commented Apr 10, 2026

Copy link
Copy Markdown
Owner

Would you prefer it as a workspace member in this repo (like wt-perf, so it can reuse the existing git/config/styling crates), or as a fully separate repo?

yes, it would be your project; I'd be happy to look if you wanted any help, but your repo etc!

For the wt <external-command> dispatch — I saw you asked the bot to add that. Should I wait for that PR, or can I just have users install wt-sync and run it directly for now?

it merged!

@pablospe

ghost commented Apr 10, 2026

Copy link
Copy Markdown
Contributor Author

yes, it would be your project; I'd be happy to look if you wanted any help, but your repo etc!

Ok, let me close the PRs then. Thanks!
(I still want to finish some issues, and then I close it, hope it is fine and apologies the noise)

@pablospe pablospe closed this Apr 10, 2026
@pablospe

ghost commented Apr 10, 2026

Copy link
Copy Markdown
Contributor Author

A few questions on the wt <external-command> dispatch that just merged:

  1. Does the binary need to be named exactly wt-sync, or is there a
    different naming convention?
  2. Does it receive the same arguments the user typed after wt sync,
    or does wt do any preprocessing?
  3. Can it depend on the worktrunk crate from crates.io to reuse
    Repository, styling, config, etc.? The lib API says "not stable"
    but it would save a lot of reimplementation.
  4. For --prune, I need execute_removal from commands::worktree
    (handles fsmonitor cleanup, trash-path safety, safe branch deletion),
    but commands isn't exported from the library. Would you be open to
    making it public, or should I reimplement the removal logic with raw
    git commands?

I'll finish addressing the review fixes on the current PRs (the CI
feedback has been useful), then convert them to draft and start building
worktrunk-sync as a standalone crate.

@pablospe

ghost commented Apr 14, 2026

Copy link
Copy Markdown
Contributor Author

If you think we need the full solution to get value, then releasing worktrunk-sync, which would install a wt-sync binary, is the way to go; I'd be happy to link to it.

@max-sixty I was wondering how you would link it. In the documentation?

yes, it would be your project; I'd be happy to look if you wanted any help, but your repo etc!

If you'd like to take a look, here's the link:
https://github.com/pablospe/worktrunk-sync

Thanks for the help!

@max-sixty

ghost commented Apr 14, 2026

Copy link
Copy Markdown
Owner

excellent! nice work!

@worktrunk-bot where could this go in the docs? let's put a link in Extending Worktrunk as an example. Maybe also as a Q&A?

@max-sixty

ghost commented Apr 14, 2026

Copy link
Copy Markdown
Owner

@pablospe I'm very sorry I just saw your questions from a few days ago. Which of those are still outstanding? Do you need anything adjusted in this repo? Happy to make items public etc.

@worktrunk-bot

ghost commented Apr 14, 2026

Copy link
Copy Markdown
Collaborator

Opened #2225 with both — an ### Examples entry under External subcommands in docs/content/extending.md, and a "Does Worktrunk support stacked branches?" Q&A in the FAQ after the git-machete / git-town comparison. Both point to https://github.com/pablospe/worktrunk-sync with the cargo install worktrunk-sync + wt sync invocation.

@pablospe

ghost commented Apr 14, 2026

Copy link
Copy Markdown
Contributor Author

Which of those are still outstanding? Do you need anything adjusted in this repo?

Thanks! Here's where things stand:

  1. Binary naming — Resolved, wt-sync works with the external subcommand dispatch.
  2. Argument passing — Resolved, tested and working.
  3. worktrunk crate dependency — Using it already for Repository, works well.
  4. --prune / execute_removal — I reimplemented the removal logic with raw git commands (git worktree remove, git branch -D, git push --delete). It works but doesn't have the fsmonitor cleanup and trash-path safety from the internal execute_removal. If you're open to exporting that from the library at some point, I'd happily switch to it — but no rush, the current approach is functional.

Also, thanks for the docs link in #2225!

@max-sixty

ghost commented Apr 14, 2026

Copy link
Copy Markdown
Owner

@worktrunk-bot please make the changes in #4 so those are public. list options we should consider in refactors. this doesn't have to be the final interface we ever choose, but it shouldn't be a mess; and we are fine to do some refactors now in order to make the interface nicer.

if you feel confident, also open a PR in wt-sync with the changes to use our interface; test they work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants