How Worktrunk Caches Read-Only Git State for High-Performance CLI Operations
Worktrunk caches immutable Git metadata—branch names, remotes, and configuration—behind an Arc<RepoCache> to eliminate redundant subprocess calls and share state efficiently across worktree operations.
Worktrunk is a Git worktree management tool designed to minimize command latency by maintaining an in-memory, read-only cache of repository state. Instead of invoking git branch or git config repeatedly, Worktrunk loads this immutable data once and shares it across all operations. This article examines the caching implementation found in the max-sixty/worktrunk repository, specifically how the RepoCache struct optimizes performance.
The Core Caching Architecture
The caching mechanism centers on the RepoCache struct, defined at line 229 in src/git/repository/mod.rs. This structure acts as a centralized store for Git metadata that does not change during the lifetime of a repository session.
The Repository type owns this cache through an Arc<RepoCache>, specifically a field named repo_cache. Using an atomic reference counter allows multiple Repository clones—created when Worktrunk operates across several worktrees—to share the same cached data without duplication.
What Gets Cached?
RepoCache stores several categories of immutable Git state:
- Branch metadata – including branch names, upstream tracking information, and HEAD OIDs.
- Remote definitions – URLs and fetch specifications parsed from the repository configuration.
- Git configuration values – Settings inherited from
.git/configand system-level Git configuration. - Reference snapshots – Lightweight views of the ref namespace enabling fast lookups without repeated disk access.
Shared State Across Worktrees
Because the cache lives behind an Arc, every clone of the Repository struct points to the same underlying RepoCache. This design is critical for Worktrunk's performance when managing multiple worktrees, as it prevents redundant parsing of the same Git data for each worktree instance.
Lazy Loading and Accessor Methods
Worktrunk employs a lazy loading strategy to populate the cache. The first request for a specific piece of information triggers a Git subprocess, stores the result in the cache, and returns the data. All subsequent requests retrieve the value directly from memory.
The Repository struct provides several accessor methods:
Repository::branches()– Returns a reference to the cached branch map.Repository::remotes()– Returns the cached remote list.Repository::config()– Returns the parsed Git configuration.
These methods rely on internal helper functions such as load_branches(), load_remotes(), and load_config(). These helpers execute the actual Git commands—git branch --format=…, git remote -v, and git config --list—only on the first invocation. After the initial population, the helpers return the stored values without spawning new processes.
// Create a Repository – it lazily builds the read-only cache.
let repo = Repository::discover(".")?;
// First call loads branches from Git (expensive).
let branches = repo.branches()?; // Internally calls `git branch …`
// Subsequent calls are cheap – the data comes from the cache.
let same_branches = repo.branches()?; // No Git process spawned.
Why Read-Only Caching Is Safe
Worktrunk never modifies Git data directly through the cache. All mutating operations—such as creating branches or deleting worktrees—execute via standard Git commands that update the on-disk repository. Because the cache contains only snapshots of the on-disk state, the data remains immutable after construction.
This immutability makes the cache thread-safe without requiring additional synchronization primitives. When a command does mutate the repository, Worktrunk invalidates the relevant cache entries by either creating a fresh Repository instance or explicitly clearing the affected fields. Dropping the old Repository forces a new cache build on the next operation.
// When a command mutates the repo, drop the old Repository
// to force a fresh cache on the next operation.
drop(repo);
let repo = Repository::discover(".")?; // New cache built.
Performance Impact and Benchmarks
By avoiding repeated Git subprocess calls for data that rarely changes, Worktrunk significantly reduces CLI latency. For example, the wt list command displays branch and remote information instantly because the heavy-weight git branch and git remote commands execute only once per repository session.
The performance benefits are measurable and documented in benches/time_to_first_output.rs. These benchmarks demonstrate the speedup gained by eliminating redundant Git invocations, particularly when operations must reference the same metadata multiple times.
Key Implementation Files
The read-only caching layer spans several source files in the max-sixty/worktrunk repository:
src/git/repository/mod.rs– Contains theRepoCachestruct definition at line 229 and theArc<RepoCache>integration.src/git/repository/branches.rs– Implements lazy loading of branch data into the cache.src/git/repository/remotes.rs– Handles population of the remote cache.src/git/repository/config.rs– Parses and caches Git configuration values.src/git/repository/sha_cache.rs– Provides a secondary cache for object-ID lookups.benches/time_to_first_output.rs– Contains performance benchmarks validating the caching optimization.
Summary
- Worktrunk caches immutable Git state—branches, remotes, and configuration—in a
RepoCachestruct wrapped in anArcfor shared ownership. - The cache populates lazily: the first access executes Git commands, while subsequent reads return cached data instantly.
- Located in
src/git/repository/mod.rsat line 229,RepoCacheenables thread-safe, read-only access to repository metadata. - Cache invalidation occurs by dropping the
Repositoryinstance or clearing specific fields when mutations occur. - Performance benchmarks in
benches/time_to_first_output.rsdemonstrate measurable latency reductions for CLI commands.
Frequently Asked Questions
What specific Git data does Worktrunk cache?
Worktrunk caches branch metadata (names, upstream tracking, and HEAD OIDs), remote definitions (URLs and fetch specifications), parsed configuration values from .git/config, and reference snapshots. These data structures remain immutable while the repository is open, making them safe to cache.
How does Worktrunk share the cache across multiple worktrees?
The Repository struct holds the cache behind an Arc<RepoCache>. When Worktrunk clones the Repository instance to work with different worktrees, all instances share the same underlying cache through the atomic reference counter, preventing memory duplication and repeated Git calls.
When does Worktrunk invalidate the read-only cache?
Worktrunk invalidates the cache when Git operations modify the repository state. Because the cache is read-only, the system cannot update individual entries in place. Instead, Worktrunk either drops the existing Repository instance to create a fresh one with a new cache, or explicitly clears the affected cache fields to force reloading on the next access.
Where is the cache implementation located in the source code?
The primary cache definition resides in src/git/repository/mod.rs at line 229, where the RepoCache struct is defined. Supporting implementations for branches, remotes, and configuration exist in src/git/repository/branches.rs, src/git/repository/remotes.rs, and src/git/repository/config.rs respectively. Performance validation lives in benches/time_to_first_output.rs.
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 →