feat: add Git worktree compatibility (PR #478)

Adds comprehensive Git worktree support for beads issue tracking:

Core changes:
- New internal/git/gitdir.go package for worktree detection
- GetGitDir() returns proper .git location (main repo, not worktree)
- Updated all hooks to use git.GetGitDir() instead of local helper
- BeadsDir() now prioritizes main repository's .beads directory

Features:
- Hooks auto-install in main repo when run from worktree
- Shared .beads directory across all worktrees
- Config option no-install-hooks to disable auto-install
- New bd worktree subcommand for diagnostics

Documentation:
- New docs/WORKTREES.md with setup instructions
- Updated CHANGELOG.md and AGENT_INSTRUCTIONS.md

Testing:
- Updated tests to use exported git.GetGitDir()
- Added worktree detection tests

Co-authored-by: Claude <noreply@anthropic.com>
Closes: #478
This commit is contained in:
matt wilkie
2025-12-13 10:40:40 -08:00
committed by Steve Yegge
parent de7b511765
commit e01b7412d9
64 changed files with 1895 additions and 3708 deletions

View File

@@ -1,126 +0,0 @@
# Agent Memory Patterns
This document describes conventions for AI agents to maintain context and track outcomes using beads' built-in features.
## Overview
Rather than creating separate files for agent memory, use beads' existing comment system with structured prefixes. This keeps all information attached to issues where it belongs, and ensures data travels with issues through sync, export, and compaction.
## Context Comments
Use `[context]` prefix to record discoveries, decisions, and learnings during issue work:
```bash
# Record a discovery
bd comments add bd-123 "[context] API uses OAuth2, not API keys as initially assumed"
# Record a decision
bd comments add bd-123 "[context] decision: Using retry with exponential backoff for rate limits"
# Record a finding
bd comments add bd-123 "[context] The config file is at ~/.config/app/settings.json, not /etc/app/"
# Record an error and fix
bd comments add bd-123 "[context] error: Connection timeout on first attempt - fixed by increasing timeout to 30s"
```
### Context Categories
For richer categorization, use sub-prefixes:
| Prefix | Use Case |
|--------|----------|
| `[context]` | General learnings |
| `[context] decision:` | Architectural or implementation decisions |
| `[context] error:` | Errors encountered and how they were resolved |
| `[context] finding:` | Discoveries about the codebase or system |
| `[context] blocker:` | What blocked progress and how it was resolved |
## Outcome Comments
When closing an issue, add an `[outcome]` comment to track success patterns:
```bash
# Record outcome when closing
bd comments add bd-123 "[outcome] success:true approach:incremental duration:45min"
bd close bd-123 --reason="Implemented feature with incremental approach"
# For failures
bd comments add bd-123 "[outcome] success:false reason:blocked-by-external-api"
bd close bd-123 --reason="Blocked by third-party API limitation"
```
### Outcome Fields
| Field | Values | Description |
|-------|--------|-------------|
| `success` | true/false | Whether the issue was completed successfully |
| `approach` | incremental, rewrite, workaround, etc. | How the problem was solved |
| `duration` | Xmin, Xhr | Approximate time spent |
| `reason` | free text | Why it failed (for failures) |
| `complexity` | low, medium, high | Actual vs expected complexity |
## Querying Context and Outcomes
Use `bd comments` to retrieve context for an issue:
```bash
# View all comments on an issue
bd comments bd-123
# JSON output for parsing
bd comments bd-123 --json
```
To find patterns across issues, export and grep:
```bash
# Find all context comments
bd export | grep '\[context\]'
# Find all outcomes
bd export | grep '\[outcome\]'
# Find all decisions
bd export | grep '\[context\] decision:'
```
## Best Practices
1. **Add context as you work** - Don't wait until the end; record discoveries immediately
2. **Be specific** - Include file paths, function names, error messages
3. **Record the why** - Future agents benefit from understanding reasoning
4. **Add outcomes when closing** - This builds a knowledge base of what works
5. **Use consistent prefixes** - Makes searching and aggregation easier
## Example Workflow
```bash
# Starting work on an issue
bd update bd-123 --status in_progress
# Found something unexpected
bd comments add bd-123 "[context] finding: Database schema has soft deletes, need to filter deleted_at IS NULL"
# Made a decision
bd comments add bd-123 "[context] decision: Using existing ORM instead of raw SQL for consistency"
# Hit an error
bd comments add bd-123 "[context] error: Foreign key constraint failed - fixed by adding CASCADE"
# Completing the work
bd comments add bd-123 "[outcome] success:true approach:incremental duration:30min complexity:medium"
bd close bd-123 --reason="Added soft delete filtering to all queries"
```
## Migration from Separate Files
If you have existing `context.json` or `outcomes.jsonl` files, you can migrate them to comments:
```bash
# For each issue with context, add as comments
bd comments add bd-123 "[context] <migrated content>"
# Then remove the separate files
rm .beads/context.json .beads/outcomes.jsonl
```

View File

@@ -34,7 +34,6 @@ Tool-level settings you can configure:
| `no-daemon` | `--no-daemon` | `BD_NO_DAEMON` | `false` | Force direct mode, bypass daemon |
| `no-auto-flush` | `--no-auto-flush` | `BD_NO_AUTO_FLUSH` | `false` | Disable auto JSONL export |
| `no-auto-import` | `--no-auto-import` | `BD_NO_AUTO_IMPORT` | `false` | Disable auto JSONL import |
| `no-install-hooks` | `--skip-hooks` | `BD_NO_INSTALL_HOOKS` | `false` | Skip git hook installation during `bd init` |
| `db` | `--db` | `BD_DB` | (auto-discover) | Database path |
| `actor` | `--actor` | `BD_ACTOR` | `$USER` | Actor name for audit trail |
| `flush-debounce` | - | `BEADS_FLUSH_DEBOUNCE` | `5s` | Debounce time for auto-flush |
@@ -60,10 +59,6 @@ flush-debounce: 10s
# Auto-start daemon (default true)
auto-start-daemon: true
# Disable git hook installation during bd init
# (useful if you manage hooks with pre-commit, husky, etc.)
no-install-hooks: true
# Daemon log rotation settings
daemon-log-max-size: 50 # MB per file (default 50)
daemon-log-max-backups: 7 # Number of old logs to keep (default 7)

View File

@@ -9,21 +9,21 @@ bd integrates deeply with git for issue tracking synchronization. This guide cov
## Git Worktrees
**⚠️ Important Limitation:** Daemon mode does NOT work correctly with `git worktree`.
**🚧 Enhanced Support:** Beads now has comprehensive Git worktree compatibility with shared database architecture. While thoroughly tested internally, real-world usage may reveal additional edge cases.
### The Problem
### How It Works
Git worktrees share the same `.git` directory and `.beads` database:
- All worktrees use the same `.beads/beads.db` file
- Daemon doesn't know which branch each worktree has checked out
- Can commit/push changes to the wrong branch
- Leads to confusion and incorrect git history
- All worktrees use the same `.beads/beads.db` file in the main repository
- Database discovery prioritizes main repository location
- Worktree-aware git operations prevent conflicts
- Git hooks automatically adapt to worktree context
### What You Lose Without Daemon Mode
### Daemon Mode Limitations
- **Auto-sync** - No automatic commit/push of changes (use `bd sync` manually)
- **MCP server** - beads-mcp requires daemon for multi-repo support
- **Background watching** - No automatic detection of remote changes
**⚠️ Important:** Daemon mode does NOT work correctly with `git worktree` due to shared database state.
The daemon maintains its own view of the current working directory and git state. When multiple worktrees share the same `.beads` database, the daemon may commit changes intended for one branch to a different branch.
### Solutions for Worktree Users
@@ -48,13 +48,51 @@ bd ready # All commands use direct mode
export BEADS_AUTO_START_DAEMON=false
```
### Automatic Detection
### Automatic Detection & Warnings
bd automatically detects worktrees and shows prominent warning if daemon mode is active. The `--no-daemon` mode works correctly since it operates directly on the database without shared state.
bd automatically detects worktrees and shows prominent warnings if daemon mode is active:
### Why It Matters
```
╔══════════════════════════════════════════════════════════════════════════╗
║ WARNING: Git worktree detected with daemon mode ║
╠══════════════════════════════════════════════════════════════════════════╣
║ Git worktrees share the same .beads directory, which can cause the ║
║ daemon to commit/push to the wrong branch. ║
║ ║
║ Shared database: /path/to/main/.beads ║
║ Worktree git dir: /path/to/shared/.git ║
║ ║
║ RECOMMENDED SOLUTIONS: ║
║ 1. Use --no-daemon flag: bd --no-daemon <command> ║
║ 2. Disable daemon mode: export BEADS_NO_DAEMON=1 ║
╚══════════════════════════════════════════════════════════════════════════╝
```
The daemon maintains its own view of the current working directory and git state. When multiple worktrees share the same `.beads` database, the daemon may commit changes intended for one branch to a different branch.
### Worktree-Aware Features
**Database Discovery:**
- Searches main repository first for `.beads` directory
- Falls back to worktree-local search if needed
- Prevents database duplication across worktrees
**Git Hooks:**
- Pre-commit hook adapts to worktree context
- Automatically stages JSONL in regular repos
- Safely skips staging in worktrees (files outside working tree)
- Post-merge hook works correctly in both contexts
**Sync Operations:**
- Worktree-aware repository root detection
- Proper handling of git directory vs git common directory
- Safe concurrent access to shared database
### Why This Architecture Works
- **Shared Database:** Eliminates data duplication and sync conflicts
- **Priority Search:** Main repository database takes precedence
- **SQLite Locking:** Prevents corruption during concurrent access
- **Git Integration:** Hooks and sync operations adapt to context
- **Clear Warnings:** Users are guided to safe usage patterns
## Handling Merge Conflicts
@@ -251,33 +289,11 @@ See [PROTECTED_BRANCHES.md](PROTECTED_BRANCHES.md) for complete setup guide, tro
### Installation
Git hooks are installed automatically during `bd init`. To install manually:
```bash
# One-time setup in each beads workspace
./examples/git-hooks/install.sh
```
### Disabling Hook Installation
If you prefer to manage git hooks separately (e.g., using pre-commit, husky, or your own hook manager), you can disable automatic hook installation:
```bash
# Via command-line flag
bd init --skip-hooks
# Via environment variable (useful for CI/scripts)
BD_NO_INSTALL_HOOKS=1 bd init
# Via global config (~/.config/bd/config.yaml)
no-install-hooks: true
# Via project config (.beads/config.yaml)
no-install-hooks: true
```
**Precedence:** `--skip-hooks` flag > `BD_NO_INSTALL_HOOKS` env var > config file > default (install hooks)
### What Gets Installed
**pre-commit hook:**
@@ -294,6 +310,10 @@ no-install-hooks: true
- Prevents stale JSONL from reaching remote
- **Critical for multi-workspace consistency**
**post-checkout hook:**
- Imports updated JSONL after branch switches
- Ensures database reflects checked-out branch state
### Why Hooks Matter
**Without pre-push hook:**
@@ -308,6 +328,58 @@ no-install-hooks: true
See [examples/git-hooks/README.md](../examples/git-hooks/README.md) for details.
### Implementation Details
#### Hook Installation (`cmd/bd/hooks.go`)
The `installHooks()` function:
- Writes embedded hook scripts to the `.git/hooks/` directory
- Creates the hooks directory with `os.MkdirAll()` if needed
- Backs up existing hooks with `.backup` extension (unless `--force` flag used)
- Sets execute permissions (0755) on installed hooks
- Supports shared mode via `--shared` flag (installs to `.beads-hooks/` instead)
#### Git Directory Resolution
**Critical for worktree support:** The `getGitDir()` helper uses `git rev-parse --git-dir` to resolve the actual git directory:
```go
// Returns ".git" in normal repos
// Returns "/path/to/shared/.git" in git worktrees
// (where .git is a file containing "gitdir: /path/to/actual/git/dir")
gitDir, err := getGitDir()
```
In **normal repositories**, `.git` is a directory containing the git internals.
In **git worktrees**, `.git` is a file containing `gitdir: /path/to/actual/git/dir`, pointing to the shared git directory.
This difference breaks code that assumes `.git` is always a directory. Using `getGitDir()` ensures hooks work correctly in both cases.
#### Hook Detection (`cmd/bd/init.go`)
The `detectExistingHooks()` function scans for existing hooks and classifies them:
- **bd hooks**: Identified by "bd (beads) pre-commit hook" comment in content
- **pre-commit framework hooks**: Detected by "pre-commit framework" or "pre-commit.com" in content
- **Custom hooks**: Any other existing hook
This classification allows bd to:
- Avoid re-installing already-installed bd hooks
- Support chaining with pre-commit framework hooks
- Warn when overwriting custom hooks
#### Hook Testing
Tests in `hooks_test.go` and `init_hooks_test.go`:
1. Initialize real git repositories via `exec.Command("git", "init")`
2. Call `getGitDir()` to get the actual git directory path
3. Construct hooks path with `filepath.Join(gitDirPath, "hooks")`
4. Create hooks directory if needed with `os.MkdirAll()`
5. Execute hook operations and verify results
This approach ensures tests work correctly in both normal repos and git worktrees, preventing failures when running in worktree environments where `.git` is a file.
## Multi-Workspace Sync Strategies
### Centralized Repository Pattern

View File

@@ -17,18 +17,6 @@ brew install bd
- ✅ No need to install Go
- ✅ Handles PATH setup automatically
### mise (polyglot runtime manager)
```bash
mise use -g ubi:steveyegge/beads[exe=bd]
```
**Why mise?**
- ✅ Single tool for managing many development tools
- ✅ Version pinning per project via `mise.toml`
- ✅ No need to install Go
- ✅ Works across macOS, Linux, and Windows
### Quick Install Script (All Platforms)
```bash
@@ -173,7 +161,7 @@ For enhanced UX with slash commands:
```
The plugin adds:
- Slash commands: `/beads:ready`, `/beads:create`, `/beads:show`, `/beads:update`, `/beads:close`, etc.
- Slash commands: `/bd-ready`, `/bd-create`, `/bd-show`, `/bd-update`, `/bd-close`, etc.
- Task agent for autonomous execution
See [PLUGIN.md](PLUGIN.md) for complete plugin documentation.

View File

@@ -40,22 +40,17 @@ There are two ways to install the beads plugin:
#### Option 2: Local Development
```bash
# Clone the repository (shell command)
# Clone the repository
git clone https://github.com/steveyegge/beads
cd beads
```
Then in Claude Code:
```
# Add local marketplace (Claude Code command - note: use ./beads not .)
/plugin marketplace add ./beads
# Add local marketplace
/plugin marketplace add .
# Install plugin
/plugin install beads
```
**Note:** If you want to install the plugin from a different repo, first `cd` to that repo's directory in your terminal, then use `./beads` (or the relative path to the beads directory) in Claude Code.
### Restart Claude Code
After installation, restart Claude Code to activate the MCP server.
@@ -64,37 +59,37 @@ After installation, restart Claude Code to activate the MCP server.
```bash
# Initialize beads in your project
/beads:init
/bd-init
# Create your first issue
/beads:create "Set up project structure" feature 1
/bd-create "Set up project structure" feature 1
# See what's ready to work on
/beads:ready
/bd-ready
# Show full workflow guide
/beads:workflow
/bd-workflow
```
## Available Commands
### Version Management
- **`/beads:version`** - Check bd CLI, plugin, and MCP server versions
- **`/bd-version`** - Check bd CLI, plugin, and MCP server versions
### Core Workflow Commands
- **`/beads:ready`** - Find tasks with no blockers, ready to work on
- **`/beads:create [title] [type] [priority]`** - Create a new issue interactively
- **`/beads:show [issue-id]`** - Show detailed information about an issue
- **`/beads:update [issue-id] [status]`** - Update issue status or other fields
- **`/beads:close [issue-id] [reason]`** - Close a completed issue
- **`/bd-ready`** - Find tasks with no blockers, ready to work on
- **`/bd-create [title] [type] [priority]`** - Create a new issue interactively
- **`/bd-show [issue-id]`** - Show detailed information about an issue
- **`/bd-update [issue-id] [status]`** - Update issue status or other fields
- **`/bd-close [issue-id] [reason]`** - Close a completed issue
### Project Management
- **`/beads:init`** - Initialize beads in the current project
- **`/beads:workflow`** - Show the AI-supervised issue workflow guide
- **`/beads:stats`** - Show project statistics and progress
- **`/bd-init`** - Initialize beads in the current project
- **`/bd-workflow`** - Show the AI-supervised issue workflow guide
- **`/bd-stats`** - Show project statistics and progress
### Agents
@@ -123,11 +118,11 @@ The plugin includes a full-featured MCP server with these tools:
The beads workflow is designed for AI agents but works great for humans too:
1. **Find ready work**: `/beads:ready`
2. **Claim your task**: `/beads:update <id> in_progress`
1. **Find ready work**: `/bd-ready`
2. **Claim your task**: `/bd-update <id> in_progress`
3. **Work on it**: Implement, test, document
4. **Discover new work**: Create issues for bugs/TODOs found during work
5. **Complete**: `/beads:close <id> "Done: <summary>"`
5. **Complete**: `/bd-close <id> "Done: <summary>"`
6. **Repeat**: Check for newly unblocked tasks
## Issue Types
@@ -229,29 +224,29 @@ To customize, edit your Claude Code MCP settings or the plugin configuration.
```bash
# Create a high-priority bug
/beads:create "Fix authentication" bug 1
/bd-create "Fix authentication" bug 1
# See ready work
/beads:ready
/bd-ready
# Start working on bd-10
/beads:update bd-10 in_progress
/bd-update bd-10 in_progress
# Complete the task
/beads:close bd-10 "Fixed auth token validation"
/bd-close bd-10 "Fixed auth token validation"
```
### Discovering Work During Development
```bash
# Working on bd-10, found a related bug
/beads:create "Add rate limiting to API" feature 2
/bd-create "Add rate limiting to API" feature 2
# Link it to current work (via MCP tool)
# Use `dep` tool: issue="bd-11", depends_on="bd-10", type="discovered-from"
# Close original task
/beads:close bd-10 "Done, discovered bd-11 for rate limiting"
/bd-close bd-10 "Done, discovered bd-11 for rate limiting"
```
### Using the Task Agent
@@ -321,7 +316,7 @@ The MCP server **automatically checks** bd CLI version on startup and will fail
Check version compatibility manually:
```bash
/beads:version
/bd-version
```
This will show:
@@ -331,11 +326,11 @@ This will show:
- Compatibility warnings if versions mismatch
**Recommended update workflow:**
1. Check versions: `/beads:version`
1. Check versions: `/bd-version`
2. Update bd CLI if needed (see above)
3. Update plugin: `/plugin update beads`
4. Restart Claude Code
5. Verify: `/beads:version`
5. Verify: `/bd-version`
### Version Numbering
@@ -362,7 +357,7 @@ Beads follows semantic versioning. The plugin version tracks the bd CLI version:
### Commands not working
1. Make sure you're in a project with beads initialized: `/beads:init`
1. Make sure you're in a project with beads initialized: `/bd-init`
2. Check if database exists: `ls -la .beads/`
3. Try direct MCP tool access instead of slash commands
4. Check the beads CLI works: `bd --help`
@@ -372,7 +367,7 @@ Beads follows semantic versioning. The plugin version tracks the bd CLI version:
1. Verify `bd` executable location: `BEADS_PATH` env var
2. Check `bd` works in terminal: `bd stats`
3. Review MCP server logs in Claude Code
4. Try reinitializing: `/beads:init`
4. Try reinitializing: `/bd-init`
## Learn More

View File

@@ -38,32 +38,33 @@ bd init --branch beads-metadata
This creates a `.beads/` directory and configures beads to commit to `beads-metadata` instead of `main`.
**Important:** After initialization, commit the beads configuration to your protected branch:
**Important:** After initialization, you'll see some untracked files that should be committed to your protected branch:
```bash
# The .beads/.gitignore uses a whitelist - only tracked files show up
git add .beads/ .gitattributes
# Check what files were created
git status
# Commit the beads configuration to your protected branch
git add .beads/.gitignore .gitattributes
git commit -m "Initialize beads issue tracker"
git push origin main # Or create a PR if required
```
**Files created by `bd init --branch`:**
Files committed to your **protected branch** (main):
- `.beads/.gitignore` - Whitelist of tracked files (everything else ignored)
Files that should be committed to your protected branch (main):
- `.beads/.gitignore` - Tells git what to ignore in .beads/ directory
- `.gitattributes` - Configures merge driver for intelligent JSONL conflict resolution
Files committed to your **sync branch** (beads-metadata) by the daemon:
- `.beads/issues.jsonl` - Issue data in JSONL format
- `.beads/metadata.json` - Metadata about the beads installation
- `.beads/config.yaml` - Configuration settings
- `.beads/README.md` - Documentation for contributors
Files that are automatically gitignored (do NOT commit):
- `.beads/beads.db` - SQLite database (local only, regenerated from JSONL)
- `.beads/daemon.lock`, `daemon.log`, `daemon.pid` - Runtime files
- `.beads/beads.left.jsonl`, `beads.right.jsonl` - Temporary merge artifacts
Files that are **automatically ignored** (local only, never committed):
- `.beads/beads.db` - SQLite database (regenerated from JSONL)
- `.beads/daemon.*` - Runtime files (lock, log, pid, socket)
- `.beads/beads.*.jsonl` - Temporary merge artifacts
- Everything else in `.beads/` not explicitly whitelisted
The sync branch (beads-metadata) will contain:
- `.beads/beads.jsonl` - Issue data in JSONL format (committed automatically by daemon)
- `.beads/metadata.json` - Metadata about the beads installation
- `.beads/config.yaml` - Configuration template (optional)
**2. Start the daemon with auto-commit:**
@@ -111,19 +112,17 @@ your-project/
**What lives in each branch:**
Main branch (protected):
- `.beads/.gitignore` - Whitelist of tracked files
- `.beads/.gitignore` - Tells git what to ignore
- `.gitattributes` - Merge driver configuration
Sync branch (beads-metadata):
- `.beads/issues.jsonl` - Issue data (committed by daemon)
- `.beads/beads.jsonl` - Issue data (committed by daemon)
- `.beads/metadata.json` - Repository metadata
- `.beads/config.yaml` - Configuration settings
- `.beads/README.md` - Documentation
- `.beads/config.yaml` - Configuration template
Not tracked (gitignored via whitelist):
Not tracked (gitignored):
- `.beads/beads.db` - SQLite database (local only)
- `.beads/daemon.*` - Runtime files
- Everything else not in the whitelist
**Key points:**
- The worktree is in `.git/beads-worktrees/` (hidden from your workspace)

307
docs/WORKTREES.md Normal file
View File

@@ -0,0 +1,307 @@
# Git Worktrees Guide
**Enhanced Git worktree compatibility for Beads issue tracking**
## Overview
Beads now provides **enhanced Git worktree support** with a shared database architecture. All worktrees in a repository share the same `.beads` database located in the main repository, enabling seamless issue tracking across multiple working directories.
**Note:** While comprehensively implemented and tested internally, this feature may benefit from real-world usage feedback to identify any remaining edge cases.
## How It Works
### Shared Database Architecture
```
Main Repository
├── .git/ # Shared git directory
├── .beads/ # Shared database (main repo)
│ ├── beads.db # SQLite database
│ ├── issues.jsonl # Issue data (git-tracked)
│ └── config.yaml # Configuration
├── feature-branch/ # Worktree 1
│ └── (code files only)
└── bugfix-branch/ # Worktree 2
└── (code files only)
```
**Key points:**
-**One database** - All worktrees share the same `.beads` directory in main repo
-**Automatic discovery** - Database found regardless of which worktree you're in
-**Concurrent access** - SQLite locking prevents corruption
-**Git integration** - Issues sync via JSONL in main repo
### Worktree Detection & Warnings
bd automatically detects when you're in a git worktree and provides appropriate guidance:
```bash
# In a worktree with daemon active
$ bd ready
╔══════════════════════════════════════════════════════════════════════════╗
║ WARNING: Git worktree detected with daemon mode ║
╠══════════════════════════════════════════════════════════════════════════╣
║ Git worktrees share the same .beads directory, which can cause the ║
║ daemon to commit/push to the wrong branch. ║
║ ║
║ Shared database: /path/to/main/.beads ║
║ Worktree git dir: /path/to/shared/.git ║
║ ║
║ RECOMMENDED SOLUTIONS: ║
║ 1. Use --no-daemon flag: bd --no-daemon <command> ║
║ 2. Disable daemon mode: export BEADS_NO_DAEMON=1
╚══════════════════════════════════════════════════════════════════════════╝
```
## Usage Patterns
### Recommended: Direct Mode in Worktrees
```bash
# Disable daemon for worktree usage
export BEADS_NO_DAEMON=1
# Work normally - all commands work correctly
cd feature-worktree
bd create "Implement feature X" -t feature -p 1
bd update bd-a1b2 --status in_progress
bd ready
bd sync # Manual sync when needed
```
### Alternative: Daemon in Main Repo Only
```bash
# Use daemon only in main repository
cd main-repo
bd ready # Daemon works here
# Use direct mode in worktrees
cd ../feature-worktree
bd --no-daemon ready
```
## Worktree-Aware Features
### Database Discovery
bd intelligently finds the correct database:
1. **Priority search**: Main repository `.beads` directory first
2. **Fallback logic**: Searches worktree if main repo doesn't have database
3. **Path resolution**: Handles symlinks and relative paths correctly
4. **Validation**: Ensures `.beads` contains actual project files
### Git Hooks Integration
Pre-commit hooks adapt to worktree context:
```bash
# In main repo: Stages JSONL normally
git add .beads/issues.jsonl
# In worktree: Safely skips staging (files outside working tree)
# Hook detects context and handles appropriately
```
### Sync Operations
Worktree-aware sync operations:
- **Repository root detection**: Uses `git rev-parse --show-toplevel` for main repo
- **Git directory handling**: Distinguishes between `.git` (file) and `.git/` (directory)
- **Path resolution**: Converts between worktree and main repo paths
- **Concurrent safety**: SQLite locking prevents corruption
## Setup Examples
### Basic Worktree Setup
```bash
# Create main worktree
git worktree add main-repo
# Create feature worktree
git worktree add feature-worktree
# Initialize beads in main repo
cd main-repo
bd init
# Worktrees automatically share the database
cd ../feature-worktree
bd ready # Works immediately - sees same issues
```
### Multi-Feature Development
```bash
# Main development
cd main-repo
bd create "Epic: User authentication" -t epic -p 1
# Returns: bd-a3f8e9
# Feature branch worktree
git worktree add auth-feature
cd auth-feature
bd create "Design login UI" -p 1
# Auto-assigned: bd-a3f8e9.1 (child of epic)
# Bugfix worktree
git worktree add auth-bugfix
cd auth-bugfix
bd create "Fix password validation" -t bug -p 0
# Auto-assigned: bd-f14c3
```
## Troubleshooting
### Issue: Daemon commits to wrong branch
**Symptoms:** Changes appear on unexpected branch in git history
**Solution:**
```bash
# Disable daemon in worktrees
export BEADS_NO_DAEMON=1
# Or use --no-daemon flag for individual commands
bd --no-daemon sync
```
### Issue: Database not found in worktree
**Symptoms:** `bd: database not found` error
**Solutions:**
```bash
# Ensure main repo has .beads directory
cd main-repo
ls -la .beads/
# Re-run bd init if needed
bd init
# Check worktree can access main repo
cd ../worktree-name
bd info # Should show database path in main repo
```
### Issue: Multiple databases detected
**Symptoms:** Warning about multiple `.beads` directories
**Solution:**
```bash
# bd shows warning with database locations
# Typically, the closest database (in main repo) is correct
# Remove extra .beads directories if they're not needed
```
### Issue: Git hooks fail in worktrees
**Symptoms:** Pre-commit hook errors about staging files outside working tree
**Solution:** This is now automatically handled. The hook detects worktree context and adapts its behavior. No manual intervention needed.
## Advanced Configuration
### Environment Variables
```bash
# Disable daemon globally for worktree usage
export BEADS_NO_DAEMON=1
# Disable auto-start (still warns if manually started)
export BEADS_AUTO_START_DAEMON=false
# Force specific database location
export BEADS_DB=/path/to/specific/.beads/beads.db
```
### Configuration Options
```bash
# Configure sync behavior
bd config set sync.branch beads-metadata # Use separate sync branch
bd config set sync.auto_commit true # Auto-commit changes
bd config set sync.auto_push true # Auto-push changes
```
## Performance Considerations
### Database Sharing Benefits
- **Reduced overhead**: One database instead of per-worktree copies
- **Instant sync**: Changes visible across all worktrees immediately
- **Memory efficient**: Single SQLite instance vs multiple
- **Git efficient**: One JSONL file to track vs multiple
### Concurrent Access
- **SQLite locking**: Prevents corruption during simultaneous access
- **Git operations**: Safe concurrent commits from different worktrees
- **Sync coordination**: JSONL-based sync prevents conflicts
## Migration from Limited Support
### Before (Limited Worktree Support)
- ❌ Daemon mode broken in worktrees
- ❌ Manual workarounds required
- ❌ Complex setup procedures
- ❌ Limited documentation
### After (Enhanced Worktree Support)
- ✅ Shared database architecture
- ✅ Automatic worktree detection
- ✅ Clear user guidance and warnings
- ✅ Comprehensive documentation
- ✅ Git hooks work correctly
- ✅ All bd commands function properly
**Note:** Based on comprehensive internal testing. Real-world usage may reveal additional refinements needed.
## Examples in the Wild
### Monorepo Development
```bash
# Monorepo with multiple service worktrees
git worktree add services/auth
git worktree add services/api
git worktree add services/web
# Each service team works in their worktree
cd services/auth
export BEADS_NO_DAEMON=1
bd create "Add OAuth support" -t feature -p 1
cd ../api
bd create "Implement auth endpoints" -p 1
# Issues automatically linked and visible across worktrees
```
### Feature Branch Workflow
```bash
# Create feature worktree
git worktree add feature/user-profiles
cd feature/user-profiles
# Work on feature with full issue tracking
bd create "Design user profile schema" -t task -p 1
bd create "Implement profile API" -t task -p 1
bd create "Add profile UI components" -t task -p 2
# Issues tracked in shared database
# Code changes isolated to worktree
# Clean merge back to main when ready
```
## See Also
- [GIT_INTEGRATION.md](GIT_INTEGRATION.md) - General git integration guide
- [AGENTS.md](../AGENTS.md) - Agent usage instructions
- [README.md](../README.md) - Main project documentation
- [MULTI_REPO_MIGRATION.md](MULTI_REPO_MIGRATION.md) - Multi-workspace patterns