Project 12: Git Worktree Manager — Work on Multiple Branches Simultaneously

A TUI (text UI) tool for managing Git worktrees—allowing you to have multiple branches checked out simultaneously in separate directories, with easy creation, switching, and cleanup.

Quick Reference

Attribute Value
Difficulty Intermediate
Time Estimate 1-2 weeks
Main Programming Language Go
Alternative Programming Languages Rust, Python, Bash
Coolness Level Level 3: Genuinely Clever
Business Potential 2. The “Micro-SaaS / Pro Tool”
Prerequisites Understanding of Git branches, basic TUI or CLI experience
Key Topics Worktree Mechanics, Branch Locking, TUI Development

1. Learning Objectives

By completing this project, you will:

  1. Implement a working version of: A TUI (text UI) tool for managing Git worktrees—allowing you to have multiple branches checked out simultaneously in separate directories, with easy creation, switching, and cleanup..
  2. Explain the core Git workflow tradeoff this project is designed to surface.
  3. Design deterministic checks so results can be verified and reproduced.
  4. Document operational failure modes and safe recovery actions.

2. All Theory Needed (Per-Concept Breakdown)

Worktree Mechanics

Fundamentals This concept matters in this project because your implementation will fail or become non-deterministic without a precise model of Worktree Mechanics. You should define what the concept controls, what invariants must hold, and which actions are safe versus destructive. Treat this concept as a production concern, not a tutorial checkbox.

Deep Dive into the concept When applying Worktree Mechanics in this project, reason in three passes: data shape, state transitions, and enforcement. First, identify which artifacts are authoritative (commit objects, refs, metadata, policy config, CI status, or scan findings). Second, map how those artifacts change when your tool runs. Third, define failure behavior explicitly. In Git tooling, silent partial success is dangerous: you need either complete success with evidence or an explicit failure state with remediation guidance. Also account for scale behavior. A workflow that works on a toy repo may fail on large history depth, concurrent updates, or mixed branch policies. Include trace logs for every irreversible action, and separate simulation mode from write mode. For interview readiness, be able to explain how this concept protects delivery speed while reducing operational risk.

How this fit on projects In this project, Worktree Mechanics is directly used in design decisions, implementation constraints, and verification criteria.

Definitions & key terms

  • Worktree Mechanics invariant: A condition that must remain true before and after every operation.
  • Safety boundary: The point where actions become destructive unless guarded.
  • Verification signal: Evidence proving the action behaved as expected.

Mental model diagram

Input state -> Validate invariant -> Apply change -> Verify output -> Record evidence

How it works

  1. Capture current state and constraints.
  2. Evaluate whether Worktree Mechanics preconditions are satisfied.
  3. Execute the minimal safe transition.
  4. Verify postconditions and publish an auditable result.

Failure modes: stale state, partial writes, race conditions, ambiguous output contracts.

Minimal concrete example

Plan -> dry-run -> execute -> verify -> rollback/forward-fix decision

Common misconceptions

  • Assuming local success implies team-safe behavior.
  • Treating policy violations as warnings instead of merge blockers.
  • Skipping deterministic verification because the output appears correct.

Check-your-understanding questions

  1. Which invariant is most likely to break first under concurrency?
  2. What output proves your tool handled an edge case correctly?
  3. Where should enforcement happen: local hook, CI, or protected branch gate?

Check-your-understanding answers

  1. The invariant tied to mutable refs or policy-dependent merge eligibility.
  2. A deterministic transcript showing both success and controlled failure behavior.
  3. Layered enforcement: fast local checks plus non-bypassable server-side gates.

Real-world applications

  • Change-management tooling for fast-moving teams.
  • Incident-safe release workflows with traceable rollback paths.
  • Compliance-ready source-control automation.

Where you’ll apply it This project and its immediate adjacent projects in this sprint.

References

  • https://git-scm.com/docs
  • https://dora.dev/capabilities/trunk-based-development/

Key insights Worktree Mechanics is only valuable when its invariants are encoded into tooling and checks.

Summary Mastering Worktree Mechanics here gives you transferable patterns for larger workflow systems.

Homework/Exercises to practice the concept

  1. Write one failing scenario and expected detection output.
  2. Define one invariant and one explicit violation test.

Solutions to the homework/exercises

  1. Use a stale branch or invalid metadata case and assert deterministic error reporting.
  2. Invariant: protected branch must not accept unchecked changes; violation test: bypass attempt should fail fast.

Branch Locking

Fundamentals This concept matters in this project because your implementation will fail or become non-deterministic without a precise model of Branch Locking. You should define what the concept controls, what invariants must hold, and which actions are safe versus destructive. Treat this concept as a production concern, not a tutorial checkbox.

Deep Dive into the concept When applying Branch Locking in this project, reason in three passes: data shape, state transitions, and enforcement. First, identify which artifacts are authoritative (commit objects, refs, metadata, policy config, CI status, or scan findings). Second, map how those artifacts change when your tool runs. Third, define failure behavior explicitly. In Git tooling, silent partial success is dangerous: you need either complete success with evidence or an explicit failure state with remediation guidance. Also account for scale behavior. A workflow that works on a toy repo may fail on large history depth, concurrent updates, or mixed branch policies. Include trace logs for every irreversible action, and separate simulation mode from write mode. For interview readiness, be able to explain how this concept protects delivery speed while reducing operational risk.

How this fit on projects In this project, Branch Locking is directly used in design decisions, implementation constraints, and verification criteria.

Definitions & key terms

  • Branch Locking invariant: A condition that must remain true before and after every operation.
  • Safety boundary: The point where actions become destructive unless guarded.
  • Verification signal: Evidence proving the action behaved as expected.

Mental model diagram

Input state -> Validate invariant -> Apply change -> Verify output -> Record evidence

How it works

  1. Capture current state and constraints.
  2. Evaluate whether Branch Locking preconditions are satisfied.
  3. Execute the minimal safe transition.
  4. Verify postconditions and publish an auditable result.

Failure modes: stale state, partial writes, race conditions, ambiguous output contracts.

Minimal concrete example

Plan -> dry-run -> execute -> verify -> rollback/forward-fix decision

Common misconceptions

  • Assuming local success implies team-safe behavior.
  • Treating policy violations as warnings instead of merge blockers.
  • Skipping deterministic verification because the output appears correct.

Check-your-understanding questions

  1. Which invariant is most likely to break first under concurrency?
  2. What output proves your tool handled an edge case correctly?
  3. Where should enforcement happen: local hook, CI, or protected branch gate?

Check-your-understanding answers

  1. The invariant tied to mutable refs or policy-dependent merge eligibility.
  2. A deterministic transcript showing both success and controlled failure behavior.
  3. Layered enforcement: fast local checks plus non-bypassable server-side gates.

Real-world applications

  • Change-management tooling for fast-moving teams.
  • Incident-safe release workflows with traceable rollback paths.
  • Compliance-ready source-control automation.

Where you’ll apply it This project and its immediate adjacent projects in this sprint.

References

  • https://git-scm.com/docs
  • https://dora.dev/capabilities/trunk-based-development/

Key insights Branch Locking is only valuable when its invariants are encoded into tooling and checks.

Summary Mastering Branch Locking here gives you transferable patterns for larger workflow systems.

Homework/Exercises to practice the concept

  1. Write one failing scenario and expected detection output.
  2. Define one invariant and one explicit violation test.

Solutions to the homework/exercises

  1. Use a stale branch or invalid metadata case and assert deterministic error reporting.
  2. Invariant: protected branch must not accept unchecked changes; violation test: bypass attempt should fail fast.

TUI Development

Fundamentals This concept matters in this project because your implementation will fail or become non-deterministic without a precise model of TUI Development. You should define what the concept controls, what invariants must hold, and which actions are safe versus destructive. Treat this concept as a production concern, not a tutorial checkbox.

Deep Dive into the concept When applying TUI Development in this project, reason in three passes: data shape, state transitions, and enforcement. First, identify which artifacts are authoritative (commit objects, refs, metadata, policy config, CI status, or scan findings). Second, map how those artifacts change when your tool runs. Third, define failure behavior explicitly. In Git tooling, silent partial success is dangerous: you need either complete success with evidence or an explicit failure state with remediation guidance. Also account for scale behavior. A workflow that works on a toy repo may fail on large history depth, concurrent updates, or mixed branch policies. Include trace logs for every irreversible action, and separate simulation mode from write mode. For interview readiness, be able to explain how this concept protects delivery speed while reducing operational risk.

How this fit on projects In this project, TUI Development is directly used in design decisions, implementation constraints, and verification criteria.

Definitions & key terms

  • TUI Development invariant: A condition that must remain true before and after every operation.
  • Safety boundary: The point where actions become destructive unless guarded.
  • Verification signal: Evidence proving the action behaved as expected.

Mental model diagram

Input state -> Validate invariant -> Apply change -> Verify output -> Record evidence

How it works

  1. Capture current state and constraints.
  2. Evaluate whether TUI Development preconditions are satisfied.
  3. Execute the minimal safe transition.
  4. Verify postconditions and publish an auditable result.

Failure modes: stale state, partial writes, race conditions, ambiguous output contracts.

Minimal concrete example

Plan -> dry-run -> execute -> verify -> rollback/forward-fix decision

Common misconceptions

  • Assuming local success implies team-safe behavior.
  • Treating policy violations as warnings instead of merge blockers.
  • Skipping deterministic verification because the output appears correct.

Check-your-understanding questions

  1. Which invariant is most likely to break first under concurrency?
  2. What output proves your tool handled an edge case correctly?
  3. Where should enforcement happen: local hook, CI, or protected branch gate?

Check-your-understanding answers

  1. The invariant tied to mutable refs or policy-dependent merge eligibility.
  2. A deterministic transcript showing both success and controlled failure behavior.
  3. Layered enforcement: fast local checks plus non-bypassable server-side gates.

Real-world applications

  • Change-management tooling for fast-moving teams.
  • Incident-safe release workflows with traceable rollback paths.
  • Compliance-ready source-control automation.

Where you’ll apply it This project and its immediate adjacent projects in this sprint.

References

  • https://git-scm.com/docs
  • https://dora.dev/capabilities/trunk-based-development/

Key insights TUI Development is only valuable when its invariants are encoded into tooling and checks.

Summary Mastering TUI Development here gives you transferable patterns for larger workflow systems.

Homework/Exercises to practice the concept

  1. Write one failing scenario and expected detection output.
  2. Define one invariant and one explicit violation test.

Solutions to the homework/exercises

  1. Use a stale branch or invalid metadata case and assert deterministic error reporting.
  2. Invariant: protected branch must not accept unchecked changes; violation test: bypass attempt should fail fast.

3. Project Specification

3.1 What You Will Build

A TUI (text UI) tool for managing Git worktrees—allowing you to have multiple branches checked out simultaneously in separate directories, with easy creation, switching, and cleanup.

3.2 Functional Requirements

  1. Scope control: Deliver a deterministic and testable implementation.
  2. Correctness: Preserve Git invariants and policy constraints.

3.3 Non-Functional Requirements

  • Performance: Deterministic execution with documented runtime behavior on representative history sizes.
  • Reliability: Repeated runs on the same input produce identical outputs.
  • Usability: Clear CLI or report output for both success and failure cases.

3.4 Example Usage / Output

You’ll have a TUI for managing worktrees:

Example Output:

$ wt

┌─ Git Worktree Manager ─────────────────────────────────┐
│                                                        │
│  Repository: my-project                                │
│  Main worktree: /Users/dev/my-project                  │
│                                                        │
│  Worktrees:                                            │
│  ┌────────────────────────────────────────────────────┐│
│  │ ● main         /Users/dev/my-project           [M] ││
│  │   feature/auth /Users/dev/my-project-auth          ││
│  │   hotfix/bug   /Users/dev/my-project-hotfix        ││
│  │   experiment   /Users/dev/my-project-exp       [*] ││
│  └────────────────────────────────────────────────────┘│
│                                                        │
│  [M] = main worktree  [*] = current                    │
│                                                        │
│  Commands:                                             │
│  [n] New worktree  [d] Delete  [o] Open in editor      │
│  [c] Clean up      [r] Refresh [q] Quit                │
│                                                        │
└────────────────────────────────────────────────────────┘

> n (new worktree)

Branch name (or new branch): feature/new-api
Directory (default: ../my-project-new-api):

Creating worktree...
✓ Created worktree at /Users/dev/my-project-new-api
✓ Checked out branch feature/new-api

Open in editor? [y/N]: y
✓ Opened in VS Code

$ wt status
3 worktrees active:
  main         → /Users/dev/my-project (main worktree)
  feature/auth → /Users/dev/my-project-auth (2 days old, 5 commits)
  feature/new  → /Users/dev/my-project-new-api (just created)

$ wt clean
Scanning for orphaned worktrees...
Found 1 orphaned worktree:
  /Users/dev/my-project-old-feature (branch deleted)

Remove orphaned worktrees? [y/N]: y
✓ Removed 1 orphaned worktree

3.5 Data Formats / Schemas / Protocols

Describe input repository assumptions, output report shape, and any policy/config schema consumed by the tool.

3.6 Edge Cases

  • Empty repository or shallow clone state.
  • Detached HEAD or rewritten history during execution.
  • Invalid metadata/policy configuration.

3.7 Real World Outcome

You’ll have a TUI for managing worktrees:

Example Output:

$ wt

┌─ Git Worktree Manager ─────────────────────────────────┐
│                                                        │
│  Repository: my-project                                │
│  Main worktree: /Users/dev/my-project                  │
│                                                        │
│  Worktrees:                                            │
│  ┌────────────────────────────────────────────────────┐│
│  │ ● main         /Users/dev/my-project           [M] ││
│  │   feature/auth /Users/dev/my-project-auth          ││
│  │   hotfix/bug   /Users/dev/my-project-hotfix        ││
│  │   experiment   /Users/dev/my-project-exp       [*] ││
│  └────────────────────────────────────────────────────┘│
│                                                        │
│  [M] = main worktree  [*] = current                    │
│                                                        │
│  Commands:                                             │
│  [n] New worktree  [d] Delete  [o] Open in editor      │
│  [c] Clean up      [r] Refresh [q] Quit                │
│                                                        │
└────────────────────────────────────────────────────────┘

> n (new worktree)

Branch name (or new branch): feature/new-api
Directory (default: ../my-project-new-api):

Creating worktree...
✓ Created worktree at /Users/dev/my-project-new-api
✓ Checked out branch feature/new-api

Open in editor? [y/N]: y
✓ Opened in VS Code

$ wt status
3 worktrees active:
  main         → /Users/dev/my-project (main worktree)
  feature/auth → /Users/dev/my-project-auth (2 days old, 5 commits)
  feature/new  → /Users/dev/my-project-new-api (just created)

$ wt clean
Scanning for orphaned worktrees...
Found 1 orphaned worktree:
  /Users/dev/my-project-old-feature (branch deleted)

Remove orphaned worktrees? [y/N]: y
✓ Removed 1 orphaned worktree


4. Solution Architecture

4.1 High-Level Design

Inputs -> Validation -> Core Engine -> Output Formatter -> Verification Report

4.2 Key Components

Component Responsibility Key Decisions
Input loader Discover commits/refs/config inputs Deterministic ordering and clear failure messages
Core engine Compute project-specific logic Separate read-only simulation from mutating actions
Reporter Produce user-facing output and evidence Include machine-readable and human-readable forms

4.4 Data Structures (No Full Code)

ProjectState { refs, commits, policy, findings, metrics }
Result { status, evidence, warnings, next_actions }

4.4 Algorithm Overview

  1. Collect state from repository and configuration.
  2. Evaluate invariants and policy preconditions.
  3. Execute core transformation or analysis logic.
  4. Verify postconditions and emit deterministic report.

Complexity Analysis:

  • Time: O(history + affected scope)
  • Space: O(active graph window + report size)

5. Implementation Guide

5.1 Development Environment Setup

Use the environment defined in the main guide. Pin tool versions and fixture data to keep outputs reproducible.

5.2 Project Structure

project-root/
├── fixtures/
├── src/
├── tests/
├── docs/
└── README.md

5.3 The Core Question You’re Answering

“How do you work on multiple branches simultaneously without constant switching?”

Before you write any code, sit with this question. Worktrees let you have multiple working directories sharing one .git database. Each worktree is an independent checkout—you can build one branch while testing another.


5.4 Concepts You Must Understand First

Stop and research these before coding:

  1. Worktree Mechanics
    • How does a worktree relate to the main .git directory?
    • Why can’t two worktrees have the same branch checked out?
    • Where does Git store worktree metadata?
    • Book Reference: “Pro Git” Ch. 7.11 — Chacon
  2. Branch Locking
    • What error do you get when trying to checkout a branch that’s in another worktree?
    • How do you find which worktree has a branch?
    • What happens when you delete a branch that’s checked out in a worktree?
    • Resource: git worktree --help
  3. TUI Development
    • How do you handle keyboard input in a terminal?
    • How do you draw boxes and update the screen?
    • What libraries exist for your language?
    • Resource: Bubble Tea (Go), ratatui (Rust), or curses (Python)

5.5 Questions to Guide Your Design

Before implementing, think through these:

  1. Worktree Creation
    • Should you create a new branch or checkout an existing one?
    • What’s a sensible naming convention for worktree directories?
    • How do you handle creation in a specific path vs. automatic path?
  2. Navigation
    • How do you switch between worktrees (cd, open editor, etc.)?
    • How do you show which worktree is “current”?
    • How do you handle worktrees on remote branches?
  3. Cleanup
    • How do you detect orphaned worktrees (deleted branch, missing directory)?
    • Should cleanup be automatic or manual?
    • How do you handle worktrees with uncommitted changes?

5.6 Thinking Exercise

Explore Worktrees Manually

Set up worktrees and explore:

git init worktree-test && cd worktree-test
echo "main" > file.txt && git add . && git commit -m "initial"
git branch feature-a
git branch feature-b

# Create worktrees
git worktree add ../test-feature-a feature-a
git worktree add ../test-feature-b feature-b

# Explore
git worktree list
ls -la .git/worktrees/
cat .git/worktrees/test-feature-a/HEAD

Questions while exploring:

  • What’s in .git/worktrees/?
  • What happens if you try git checkout feature-a in the main worktree?
  • If you delete ../test-feature-a/, what does git worktree list show?
  • What does git worktree prune do?

5.7 The Interview Questions They’ll Ask

Prepare to answer these:

  1. “What are Git worktrees and when would you use them?”
  2. “How do worktrees differ from just cloning the repository again?”
  3. “What happens to a worktree when its branch is deleted?”
  4. “How would you use worktrees in a CI/CD pipeline?”
  5. “What’s the relationship between the main .git directory and worktree checkouts?”

5.8 Hints in Layers

Hint 1: Starting Point git worktree list --porcelain gives machine-parseable output. Start by parsing this.

Hint 2: Worktree Info The porcelain output has worktree, HEAD, branch lines for each worktree. Parse into structs.

Hint 3: Creation git worktree add <path> <branch> creates a worktree. Add -b <branch> to create a new branch.

Hint 4: TUI Framework Use a framework rather than raw terminal codes. In Go, Bubble Tea is excellent. In Rust, ratatui.


5.9 Books That Will Help

Topic Book Chapter
Git worktrees “Pro Git” by Chacon Ch. 7.11
TUI development Bubble Tea documentation Getting started
CLI design “The Linux Command Line” by Shotts Ch. 30

5.10 Implementation Phases

Phase 1: Foundation (1-2 sessions)

  • Define fixtures, expected outputs, and invariant checks.
  • Build read-only analysis path.

Phase 2: Core Functionality (2-4 sessions)

  • Implement project-specific core logic and deterministic reporting.
  • Add policy and edge-case handling.

Phase 3: Polish and Edge Cases (1-2 sessions)

  • Add failure demos, performance notes, and usability improvements.
  • Finalize docs and validation transcripts.

5.11 Key Implementation Decisions

Decision Options Recommendation Rationale
Execution mode direct write vs dry-run+write dry-run+write Safer and easier to debug
Output contract free text vs structured+text structured+text Better automation and readability
Enforcement location local only vs local+CI local+CI Prevents bypass in shared branches

6. Testing Strategy

6.1 Test Categories

  • Unit tests for parsing and policy logic.
  • Integration tests on fixture repositories.
  • Edge-case tests for stale refs, malformed metadata, and large histories.

6.2 Critical Test Cases

  1. Deterministic golden-path scenario.
  2. Policy violation hard-fail scenario.
  3. Recovery path after partial or conflicting state.

6.3 Test Data

Use fixed repository fixtures with known commit graphs and expected outputs stored under version control.


7. Common Pitfalls & Debugging

Problem 1: “Output looks correct but history or metadata is inconsistent”

  • Why: Validation happens after mutation, not before.
  • Fix: Add a preflight invariant check and a post-write verification step.
  • Quick test: Run the same command twice on the same fixture and verify identical results.

Problem 2: “Tool works on small repo but times out on larger history”

  • Why: Full traversal is performed where selective traversal is possible.
  • Fix: Cache intermediate graph lookups and scope analysis to affected commits/paths.
  • Quick test: Compare runtime on small and large fixtures with a clear budget target.

Problem 3: “Policy check can be bypassed by local-only behavior”

  • Why: Enforcement is advisory, not server-authoritative.
  • Fix: Mirror critical checks in CI and protected branch rules.
  • Quick test: Attempt merge with failing policy in CI and confirm hard block.

8. Extensions & Challenges

8.1 Beginner Extensions

  • Add richer error messages with remediation hints.
  • Add fixture generation helpers for repeatable demos.

8.2 Intermediate Extensions

  • Add performance instrumentation and budget assertions.
  • Add policy configuration profiles by repository type.

8.3 Advanced Extensions

  • Add distributed execution support for large repositories.
  • Add signed evidence exports for compliance workflows.

9. Real-World Connections

9.1 Industry Applications

  • Internal developer portals.
  • Enterprise repository governance systems.
  • Release safety and incident diagnostics tooling.
  • Git core: https://git-scm.com/
  • GitHub CLI: https://github.com/cli/cli
  • pre-commit framework: https://pre-commit.com/

9.3 Interview Relevance

This project prepares you for architecture and debugging interviews that focus on merge policy, CI gates, and workflow reliability tradeoffs.


10. Resources

10.1 Essential Reading

  • Pro Git (Internals and Workflows chapters)
  • Software Engineering at Google (Version control and build chapters)
  • Accelerate (delivery performance practices)

10.2 Video Resources

  • Git internals talks from Git Merge conference archives.
  • DORA and delivery metrics conference sessions.

10.3 Tools and Documentation

  • https://git-scm.com/docs
  • https://docs.github.com/
  • https://dora.dev/

11. Self-Assessment Checklist

11.1 Understanding

  • I can explain the primary invariant this project enforces.
  • I can explain one failure mode and one safe recovery path.

11.2 Implementation

  • Functional requirements are met on deterministic fixtures.
  • Critical edge cases are tested and documented.

11.3 Growth

  • I can describe tradeoffs in an interview setting.
  • I documented what I would change in a production version.

12. Submission / Completion Criteria

Minimum Viable Completion:

  • Deterministic golden-path output exists.
  • One failure scenario is handled with clear output.
  • Core workflow objective is demonstrably met.

Full Completion:

  • Minimum criteria plus policy validation, structured reporting, and edge-case coverage.

Excellence:

  • Full completion plus measurable performance budget and production-hardening notes.