Default Branch Detection in Worktrunk: A Three-Stage Caching Strategy
Worktrunk detects the default branch through a three-stage pipeline—checking an in-process cache, executing local Git commands, and finally issuing a single timeout-bound remote query—to ensure the CLI remains responsive even in offline or high-latency environments.
Worktrunk, the worktree management CLI by max-sixty, relies on accurate default branch detection to power commands like wt list and wt switch. Understanding how this open-source tool balances accuracy against network constraints reveals a carefully architected caching system designed for speed and offline resilience.
The Three-Stage Default Branch Detection Pipeline
Worktrunk implements default branch detection in src/git/repository/config.rs through the Repository::default_branch() method. This function orchestrates a three-tier fallback system that minimizes I/O and network overhead.
Stage 1: In-Process Cache Lookup
The Repository struct maintains a OnceCell<Option<String>> named default_branch (defined at line 249 of src/git/repository/config.rs) that serves as a process-local cache. On the first call to default_branch(), Worktrunk stores the result in this cell, ensuring subsequent calls within the same process return immediately without spawning Git commands or network requests.
Stage 2: Local Git Inspection
If the cache is empty, Worktrunk attempts to resolve the default branch using only local repository data. This stage invokes two Git commands sequentially:
git symbolic-ref refs/remotes/<remote>/HEAD— via thelocal_default_branchhelper at line 726git remote show <remote>— as a fallback mechanism
Both commands read exclusively from the repository's .git directory, requiring zero network round-trips and executing in milliseconds regardless of connectivity.
Stage 3: Bounded Remote Query
When local inference fails—for example, in freshly cloned repositories or when remote symbolic refs are missing—Worktrunk executes a single network-bound fallback implemented in query_remote_default_branch at line 732:
git ls-remote --symref <remote> HEAD
This command is wrapped with two critical safeguards:
- Timeout protection: The
REMOTE_DETECTION_TIMEOUTconstant (approximately 2 seconds) aborts the Git process if the remote fails to respond - Result caching: Successful results populate the
OnceCellcache, ensuring the network request executes at most once per repository per process
Network Limitations and Safeguards
Worktrunk's default branch detection is explicitly designed to operate under strict network constraints to prevent the CLI from hanging.
Single Remote Request Guarantee
The architecture enforces that git ls-remote executes only when both the cache is empty and local detection fails. Once populated, the OnceCell prevents repeated network traffic during operations that query the default branch multiple times, such as rendering the default-branch column in wt list or resolving targets in src/commands/worktree/resolve.rs.
Graceful Degradation
If the remote query times out or returns malformed data, default_branch() returns None rather than panicking or blocking indefinitely. Call sites handle this Option by either defaulting to the current branch or omitting default-branch information from UI output, ensuring commands remain usable in completely offline environments.
Cache Invalidation and Testing
Worktrunk exposes Repository::clear_default_branch_cache() (defined at line 755 of src/git/repository/config.rs) to force cache eviction. This API enables unit tests in src/git/repository/tests.rs and integration tests in tests/integration_tests/default_branch.rs to verify detection behavior across multiple scenarios without restarting the process.
Example usage in test contexts:
// Force re-detection on next call
repo.clear_default_branch_cache();
let branch = repo.default_branch();
Summary
- Worktrunk detects default branches through a three-stage pipeline: in-process caching, local Git inspection, and timeout-bound remote queries
- The
Repositorystruct uses aOnceCell<Option<String>>to cache results and eliminate redundant I/O within a single process - Local detection relies on
git symbolic-refandgit remote show, requiring no network connectivity - Remote fallback uses
git ls-remote --symrefwith a 2-second timeout to prevent CLI hangs - Failed detection returns
None, allowing commands to degrade gracefully in offline environments - The cache can be manually cleared via
clear_default_branch_cache()for testing and configuration changes
Frequently Asked Questions
What happens when Worktrunk cannot reach the remote?
When the network is unreachable or the remote hangs, the REMOTE_DETECTION_TIMEOUT (approximately 2 seconds) aborts the git ls-remote process. Worktrunk returns None from default_branch(), and commands like wt switch fall back to treating the current branch as the target or omitting default-branch columns from output.
How does Worktrunk prevent repeated network requests?
The Repository struct stores detection results in a OnceCell<Option<String>> named default_branch. This ensures that within a single process lifetime, the expensive remote query executes at most once per repository, with subsequent calls returning the cached value immediately without spawning Git commands.
Can I force Worktrunk to re-detect the default branch?
Yes. The Repository type exposes clear_default_branch_cache(), which resets the internal OnceCell. The next call to default_branch() will re-run the full detection pipeline, including local inspection and the remote fallback if necessary. This is primarily used in the test suite and when users explicitly change remote configurations.
Which Git commands does Worktrunk use for local detection?
Worktrunk attempts local resolution using git symbolic-ref refs/remotes/<remote>/HEAD first, followed by git remote show <remote> as a secondary check. Both commands inspect only the local .git directory and complete without network access, making them suitable for offline environments.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →