# Beads Documentation (Complete)

> This file contains the complete beads documentation for LLM consumption.
> Generated automatically from the documentation source files.
> For the web version, visit: https://steveyegge.github.io/beads/

---

<document path="docs/intro.md">


# Beads Documentation

**Beads** (`bd`) is a git-backed issue tracker designed for AI-supervised coding workflows.

## Why Beads?

Traditional issue trackers (Jira, GitHub Issues) weren't designed for AI agents. Beads was built from the ground up for:

- **AI-native workflows** - Hash-based IDs prevent collisions when multiple agents work concurrently
- **Git-backed storage** - Issues sync via JSONL files, enabling collaboration across branches
- **Dependency-aware execution** - `bd ready` shows only unblocked work
- **Formula system** - Declarative templates for repeatable workflows
- **Multi-agent coordination** - Routing, gates, and molecules for complex workflows

## Quick Start

```bash
# Install via Homebrew (macOS/Linux)
brew tap steveyegge/beads
brew install bd

# Or quick install (macOS/Linux/FreeBSD)
curl -fsSL https://raw.githubusercontent.com/steveyegge/beads/main/scripts/install.sh | bash

# Initialize in your project
cd your-project
bd init --quiet

# Create your first issue
bd create "Set up database" -p 1 -t task

# See ready work
bd ready
```

## Core Concepts

| Concept | Description |
|---------|-------------|
| **Issues** | Work items with priorities, types, labels, and dependencies |
| **Dependencies** | `blocks`, `parent-child`, `discovered-from`, `related` |
| **Daemon** | Background process for auto-sync and performance |
| **Formulas** | Declarative workflow templates (TOML or JSON) |
| **Molecules** | Work graphs with parent-child relationships |
| **Gates** | Async coordination primitives (human, timer, GitHub) |

## For AI Agents

Beads is optimized for AI coding agents:

```bash
# Always use --json for programmatic access
bd list --json
bd show bd-42 --json

# Track discovered work during implementation
bd create "Found bug in auth" --description="Details..." \
  --deps discovered-from:bd-100 --json

# Sync at end of session
bd sync
```

See the [Claude Code integration](/integrations/claude-code) for detailed agent instructions.

## Architecture

```
SQLite DB (.beads/beads.db, gitignored)
    ↕ auto-sync (5s debounce)
JSONL (.beads/issues.jsonl, git-tracked)
    ↕ git push/pull
Remote JSONL (shared across machines)
```

The magic is automatic synchronization between a local SQLite database and git-tracked JSONL files.

## Next Steps

- [Installation](/getting-started/installation) - Get bd installed
- [Quick Start](/getting-started/quickstart) - Create your first issues
- [CLI Reference](/cli-reference) - All available commands
- [Workflows](/workflows) - Formulas, molecules, and gates

</document>

<document path="docs/getting-started/ide-setup.md">


# IDE Setup for AI Agents

Configure your IDE for optimal beads integration.

## Claude Code

The recommended approach for Claude Code:

```bash
# Setup Claude Code integration
bd setup claude
```

This installs:
- **SessionStart hook** - Runs `bd prime` when Claude Code starts
- **PreCompact hook** - Ensures `bd sync` before context compaction

**How it works:**
1. SessionStart hook runs `bd prime` automatically
2. `bd prime` injects ~1-2k tokens of workflow context
3. You use `bd` CLI commands directly
4. Git hooks auto-sync the database

**Verify installation:**
```bash
bd setup claude --check
```

### Manual Setup

If you prefer manual configuration, add to your Claude Code hooks:

```json
{
  "hooks": {
    "SessionStart": ["bd prime"],
    "PreCompact": ["bd sync"]
  }
}
```

## Cursor IDE

```bash
# Setup Cursor integration
bd setup cursor
```

This creates `.cursor/rules/beads.mdc` with beads-aware rules.

**Verify:**
```bash
bd setup cursor --check
```

## Aider

```bash
# Setup Aider integration
bd setup aider
```

This creates/updates `.aider.conf.yml` with beads context.

**Verify:**
```bash
bd setup aider --check
```

## Context Injection with `bd prime`

All integrations use `bd prime` to inject context:

```bash
bd prime
```

This outputs a compact (~1-2k tokens) workflow reference including:
- Available commands
- Current project status
- Workflow patterns
- Best practices

**Why context efficiency matters:**
- Compute cost scales with tokens
- Latency increases with context size
- Models attend better to smaller, focused contexts

## MCP Server (Alternative)

For MCP-only environments (Claude Desktop, no shell access):

```bash
# Install MCP server
pip install beads-mcp
```

Add to Claude Desktop config:
```json
{
  "mcpServers": {
    "beads": {
      "command": "beads-mcp"
    }
  }
}
```

**Trade-offs:**
- Works in MCP-only environments
- Higher context overhead (10-50k tokens for tool schemas)
- Additional latency from MCP protocol

See [MCP Server](/integrations/mcp-server) for detailed configuration.

## Git Hooks

Ensure git hooks are installed for auto-sync:

```bash
bd hooks install
```

This installs:
- **pre-commit** - Validates changes before commit
- **post-merge** - Imports changes after pull
- **pre-push** - Ensures sync before push

**Check hook status:**
```bash
bd info  # Shows warnings if hooks are outdated
```

## Verifying Your Setup

Run a complete health check:

```bash
# Check version
bd version

# Check daemon
bd info

# Check hooks
bd hooks status

# Check editor integration
bd setup claude --check   # or cursor, aider
```

</document>

<document path="docs/getting-started/installation.md">


# Installing bd

Complete installation guide for all platforms.

## Quick Install (Recommended)

### Homebrew (macOS/Linux)

```bash
brew tap steveyegge/beads
brew install bd
```

**Why Homebrew?**
- Simple one-command install
- Automatic updates via `brew upgrade`
- No need to install Go
- Handles PATH setup automatically

### Quick Install Script (All Platforms)

```bash
curl -fsSL https://raw.githubusercontent.com/steveyegge/beads/main/scripts/install.sh | bash
```

The installer will:
- Detect your platform (macOS/Linux/FreeBSD, amd64/arm64)
- Install via `go install` if Go is available
- Fall back to building from source if needed
- Guide you through PATH setup if necessary

## Platform-Specific Installation

### macOS

**Via Homebrew** (recommended):
```bash
brew tap steveyegge/beads
brew install bd
```

**Via go install**:
```bash
go install github.com/steveyegge/beads/cmd/bd@latest
```

**From source**:
```bash
git clone https://github.com/steveyegge/beads
cd beads
go build -o bd ./cmd/bd
sudo mv bd /usr/local/bin/
```

### Linux

**Via Homebrew** (works on Linux too):
```bash
brew tap steveyegge/beads
brew install bd
```

**Arch Linux** (AUR):
```bash
# Install from AUR
yay -S beads-git
# or
paru -S beads-git
```

**Via go install**:
```bash
go install github.com/steveyegge/beads/cmd/bd@latest
```

### FreeBSD

**Via quick install script**:
```bash
curl -fsSL https://raw.githubusercontent.com/steveyegge/beads/main/scripts/install.sh | bash
```

**Via go install**:
```bash
go install github.com/steveyegge/beads/cmd/bd@latest
```

### Windows 11

Beads ships with native Windows support—no MSYS or MinGW required.

**Prerequisites:**
- [Go 1.24+](https://go.dev/dl/) installed (add `%USERPROFILE%\go\bin` to your `PATH`)
- Git for Windows

**Via PowerShell script**:
```pwsh
irm https://raw.githubusercontent.com/steveyegge/beads/main/install.ps1 | iex
```

**Via go install**:
```pwsh
go install github.com/steveyegge/beads/cmd/bd@latest
```

## IDE and Editor Integrations

### CLI + Hooks (Recommended)

The recommended approach for Claude Code, Cursor, Windsurf, and other editors with shell access:

```bash
# 1. Install bd CLI (see Quick Install above)
brew install bd

# 2. Initialize in your project
cd your-project
bd init --quiet

# 3. Setup editor integration (choose one)
bd setup claude   # Claude Code - installs SessionStart/PreCompact hooks
bd setup cursor   # Cursor IDE - creates .cursor/rules/beads.mdc
bd setup aider    # Aider - creates .aider.conf.yml
```

**How it works:**
- Editor hooks/rules inject `bd prime` automatically on session start
- `bd prime` provides ~1-2k tokens of workflow context
- You use `bd` CLI commands directly
- Git hooks (installed by `bd init`) auto-sync the database

**Why this is recommended:**
- **Context efficient** - ~1-2k tokens vs 10-50k for MCP tool schemas
- **Lower latency** - Direct CLI calls, no MCP protocol overhead
- **Universal** - Works with any editor that has shell access

### MCP Server (Alternative)

Use MCP only when CLI is unavailable (Claude Desktop, Sourcegraph Amp without shell):

```bash
# Using uv (recommended)
uv tool install beads-mcp

# Or using pip
pip install beads-mcp
```

**Configuration for Claude Desktop** (macOS):

Add to `~/Library/Application Support/Claude/claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "beads": {
      "command": "beads-mcp"
    }
  }
}
```

## Verifying Installation

After installing, verify bd is working:

```bash
bd version
bd help
```

## Troubleshooting

### `bd: command not found`

bd is not in your PATH:

```bash
# Check if installed
go list -f {{.Target}} github.com/steveyegge/beads/cmd/bd

# Add Go bin to PATH (add to ~/.bashrc or ~/.zshrc)
export PATH="$PATH:$(go env GOPATH)/bin"
```

### `zsh: killed bd` or crashes on macOS

This is typically caused by CGO/SQLite compatibility issues:

```bash
# Build with CGO enabled
CGO_ENABLED=1 go install github.com/steveyegge/beads/cmd/bd@latest
```

## Updating bd

### Homebrew

```bash
brew upgrade bd
```

### go install

```bash
go install github.com/steveyegge/beads/cmd/bd@latest
```

## Next Steps

After installation:

1. **Initialize a project**: `cd your-project && bd init`
2. **Learn the basics**: See [Quick Start](/getting-started/quickstart)
3. **Configure your agent**: See [IDE Setup](/getting-started/ide-setup)

</document>

<document path="docs/getting-started/quickstart.md">


# Beads Quick Start

Get up and running with Beads in 2 minutes.

## Initialize

First time in a repository:

```bash
# Basic setup
bd init

# For AI agents (non-interactive)
bd init --quiet

# OSS contributor (fork workflow)
bd init --contributor

# Team member (branch workflow)
bd init --team

# Protected main branch (GitHub/GitLab)
bd init --branch beads-sync
```

The wizard will:
- Create `.beads/` directory and database
- Import existing issues from git (if any)
- Prompt to install git hooks (recommended)
- Prompt to configure git merge driver (recommended)
- Auto-start daemon for sync

## Your First Issues

```bash
# Create a few issues
bd create "Set up database" -p 1 -t task
bd create "Create API" -p 2 -t feature
bd create "Add authentication" -p 2 -t feature

# List them
bd list
```

**Note:** Issue IDs are hash-based (e.g., `bd-a1b2`, `bd-f14c`) to prevent collisions when multiple agents/branches work concurrently.

## Hierarchical Issues (Epics)

For large features, use hierarchical IDs to organize work:

```bash
# Create epic (generates parent hash ID)
bd create "Auth System" -t epic -p 1
# Returns: bd-a3f8e9

# Create child tasks (automatically get .1, .2, .3 suffixes)
bd create "Design login UI" -p 1       # bd-a3f8e9.1
bd create "Backend validation" -p 1    # bd-a3f8e9.2
bd create "Integration tests" -p 1     # bd-a3f8e9.3

# View hierarchy
bd dep tree bd-a3f8e9
```

Output:
```
Dependency tree for bd-a3f8e9:

> bd-a3f8e9: Auth System [epic] [P1] (open)
  > bd-a3f8e9.1: Design login UI [P1] (open)
  > bd-a3f8e9.2: Backend validation [P1] (open)
  > bd-a3f8e9.3: Integration tests [P1] (open)
```

## Add Dependencies

```bash
# API depends on database
bd dep add bd-2 bd-1

# Auth depends on API
bd dep add bd-3 bd-2

# View the tree
bd dep tree bd-3
```

Output:
```
Dependency tree for bd-3:

> bd-3: Add authentication [P2] (open)
  > bd-2: Create API [P2] (open)
    > bd-1: Set up database [P1] (open)
```

## Find Ready Work

```bash
bd ready
```

Output:
```
Ready work (1 issues with no blockers):

1. [P1] bd-1: Set up database
```

Only bd-1 is ready because bd-2 and bd-3 are blocked!

## Work the Queue

```bash
# Start working on bd-1
bd update bd-1 --status in_progress

# Complete it
bd close bd-1 --reason "Database setup complete"

# Check ready work again
bd ready
```

Now bd-2 is ready!

## Track Progress

```bash
# See blocked issues
bd blocked

# View statistics
bd stats
```

## Database Location

By default, the database is in `.beads/beads.db` (gitignored).

The JSONL file `.beads/issues.jsonl` is git-tracked and syncs automatically.

## Next Steps

- Add labels: `bd create "Task" -l "backend,urgent"`
- Filter ready work: `bd ready --priority 1`
- Search issues: `bd list --status open`
- Detect cycles: `bd dep cycles`
- See [CLI Reference](/cli-reference) for all commands

</document>

<document path="docs/getting-started/upgrading.md">


# Upgrading bd

How to upgrade bd and keep your projects in sync.

## Checking for Updates

```bash
# Current version
bd version

# What's new in recent versions
bd info --whats-new
bd info --whats-new --json  # Machine-readable
```

## Upgrading

### Homebrew

```bash
brew upgrade bd
```

### go install

```bash
go install github.com/steveyegge/beads/cmd/bd@latest
```

### From Source

```bash
cd beads
git pull
go build -o bd ./cmd/bd
sudo mv bd /usr/local/bin/
```

## After Upgrading

**Important:** After upgrading, update your hooks and restart daemons:

```bash
# 1. Check what changed
bd info --whats-new

# 2. Update git hooks to match new version
bd hooks install

# 3. Restart all daemons
bd daemons killall

# 4. Check for any outdated hooks
bd info  # Shows warnings if hooks are outdated
```

**Why update hooks?** Git hooks are versioned with bd. Outdated hooks may miss new auto-sync features or bug fixes.

## Database Migrations

After major upgrades, check for database migrations:

```bash
# Inspect migration plan (AI agents)
bd migrate --inspect --json

# Preview migration changes
bd migrate --dry-run

# Apply migrations
bd migrate

# Migrate and clean up old files
bd migrate --cleanup --yes
```

## Daemon Version Mismatches

If you see daemon version mismatch warnings:

```bash
# List all running daemons
bd daemons list --json

# Check for version mismatches
bd daemons health --json

# Restart all daemons with new version
bd daemons killall --json
```

## Troubleshooting Upgrades

### Old daemon still running

```bash
bd daemons killall
```

### Hooks out of date

```bash
bd hooks install
```

### Database schema changed

```bash
bd migrate --dry-run
bd migrate
```

### Import errors after upgrade

Check the import configuration:

```bash
bd config get import.orphan_handling
bd import -i .beads/issues.jsonl --orphan-handling allow
```

</document>

<document path="docs/core-concepts/index.md">


# Core Concepts

Understanding the fundamental concepts behind beads.

## Design Philosophy

Beads was built with these principles:

1. **Git as source of truth** - Issues sync via JSONL files, enabling collaboration across branches
2. **AI-native workflows** - Hash-based IDs, JSON output, dependency-aware execution
3. **Local-first operation** - SQLite database for fast queries, background sync
4. **Declarative workflows** - Formulas define repeatable patterns

## Key Components

### Issues

Work items with:
- **ID** - Hash-based (e.g., `bd-a1b2`) or hierarchical (e.g., `bd-a1b2.1`)
- **Type** - `bug`, `feature`, `task`, `epic`, `chore`
- **Priority** - 0 (critical) to 4 (backlog)
- **Status** - `open`, `in_progress`, `closed`
- **Labels** - Flexible tagging
- **Dependencies** - Blocking relationships

### Dependencies

Four types of relationships:

| Type | Description | Affects Ready Queue |
|------|-------------|---------------------|
| `blocks` | Hard dependency (X blocks Y) | Yes |
| `parent-child` | Epic/subtask relationship | No |
| `discovered-from` | Track issues found during work | No |
| `related` | Soft relationship | No |

### Daemon

Background process per workspace:
- Auto-starts on first command
- Handles auto-sync with 5s debounce
- Socket at `.beads/bd.sock`
- Manage with `bd daemons` commands

### JSONL Sync

The synchronization mechanism:

```
SQLite DB (.beads/beads.db)
    ↕ auto-sync
JSONL (.beads/issues.jsonl)
    ↕ git
Remote repository
```

### Formulas

Declarative workflow templates:
- Define steps with dependencies
- Variable substitution
- Gates for async coordination
- Aspect-oriented transformations

## Navigation

- [Issues & Dependencies](/core-concepts/issues)
- [Daemon Architecture](/core-concepts/daemon)
- [JSONL Sync](/core-concepts/jsonl-sync)
- [Hash-based IDs](/core-concepts/hash-ids)

</document>

<document path="docs/core-concepts/daemon.md">


# Daemon Architecture

Beads runs a background daemon for auto-sync and performance.

## Overview

Each workspace gets its own daemon process:
- Auto-starts on first `bd` command
- Handles database ↔ JSONL synchronization
- Listens on `.beads/bd.sock` (Unix) or `.beads/bd.pipe` (Windows)
- Version checking prevents mismatches after upgrades

## How It Works

```
CLI Command
    ↓
RPC to Daemon
    ↓
Daemon executes
    ↓
Auto-sync to JSONL (5s debounce)
```

Without daemon, commands access the database directly (slower, no auto-sync).

## Managing Daemons

```bash
# List all running daemons
bd daemons list
bd daemons list --json

# Check health and version mismatches
bd daemons health
bd daemons health --json

# View daemon logs
bd daemons logs . -n 100

# Restart all daemons
bd daemons killall
bd daemons killall --json
```

## Daemon Info

```bash
bd info
```

Shows:
- Daemon status (running/stopped)
- Daemon version vs CLI version
- Socket location
- Auto-sync status

## Disabling Daemon

Use `--no-daemon` flag to bypass the daemon:

```bash
bd --no-daemon ready
bd --no-daemon list
```

**When to disable:**
- Git worktrees (required)
- CI/CD pipelines
- Resource-constrained environments
- Debugging sync issues

## Event-Driven Mode (Experimental)

Event-driven mode replaces 5-second polling with instant reactivity:

```bash
# Enable globally
export BEADS_DAEMON_MODE=events
bd daemons killall  # Restart to apply
```

**Benefits:**
- Less than 500ms latency (vs 5s polling)
- ~60% less CPU usage
- Instant sync after changes

**How to verify:**
```bash
bd info | grep "daemon mode"
```

## Troubleshooting

### Daemon not starting

```bash
# Check if socket exists
ls -la .beads/bd.sock

# Try direct mode
bd --no-daemon info

# Restart daemon
bd daemons killall
bd info
```

### Version mismatch

After upgrading bd:

```bash
bd daemons killall
bd info  # Should show matching versions
```

### Sync not happening

```bash
# Force sync
bd sync

# Check daemon logs
bd daemons logs . -n 50

# Verify git status
git status .beads/
```

### Port/socket conflicts

```bash
# Kill all daemons
bd daemons killall

# Remove stale socket
rm -f .beads/bd.sock

# Restart
bd info
```

## Configuration

Daemon behavior can be configured:

```bash
# Set sync debounce interval
bd config set daemon.sync_interval 10s

# Disable auto-start
bd config set daemon.auto_start false

# Set log level
bd config set daemon.log_level debug
```

See [Configuration](/reference/configuration) for all options.

</document>

<document path="docs/core-concepts/hash-ids.md">


# Hash-based IDs

Understanding beads' collision-resistant ID system.

## The Problem

Traditional sequential IDs (`#1`, `#2`, `#3`) break when:
- Multiple agents create issues simultaneously
- Different branches have independent numbering
- Forks diverge and later merge

## The Solution

Beads uses hash-based IDs:

```
bd-a1b2c3    # Short hash
bd-f14c      # Even shorter
bd-a3f8e9.1  # Hierarchical (child of bd-a3f8e9)
```

**Properties:**
- Globally unique (content-based hash)
- No coordination needed between creators
- Merge-friendly across branches
- Predictable length (configurable)

## How Hashes Work

IDs are generated from:
- Issue title
- Creation timestamp
- Random salt

```bash
# Create issue - ID assigned automatically
bd create "Fix authentication bug"
# Returns: bd-7x2f

# The ID is deterministic for same content+timestamp
```

## Hierarchical IDs

For epics and subtasks:

```bash
# Parent epic
bd create "Auth System" -t epic
# Returns: bd-a3f8e9

# Children auto-increment
bd create "Design UI" --parent bd-a3f8e9    # bd-a3f8e9.1
bd create "Backend" --parent bd-a3f8e9      # bd-a3f8e9.2
bd create "Tests" --parent bd-a3f8e9        # bd-a3f8e9.3
```

Benefits:
- Clear parent-child relationship
- No namespace collision (parent hash is unique)
- Up to 3 levels of nesting

## ID Configuration

Configure ID prefix and length:

```bash
# Set prefix (default: bd)
bd config set id.prefix myproject

# Set hash length (default: 4)
bd config set id.hash_length 6

# New issues use new format
bd create "Test"
# Returns: myproject-a1b2c3
```

## Collision Handling

While rare, collisions are handled automatically:

1. On import, if hash collision detected
2. Beads appends disambiguator
3. Both issues preserved

```bash
# Check for collisions
bd info --schema --json | jq '.collision_count'
```

## Working with IDs

```bash
# Partial ID matching
bd show a1b2     # Finds bd-a1b2...
bd show auth     # Fuzzy match by title

# Full ID required for ambiguous cases
bd show bd-a1b2c3d4

# List with full IDs
bd list --full-ids
```

## Migration from Sequential IDs

If migrating from a system with sequential IDs:

```bash
# Import preserves original IDs in metadata
bd import -i old-issues.json

# View original ID
bd show bd-new --json | jq '.original_id'
```

## Best Practices

1. **Use short references** - `bd-a1b2` is usually unique enough
2. **Use `--json` for scripts** - Parse full ID programmatically
3. **Reference by hash in commits** - `Fixed bd-a1b2` in commit messages
4. **Let hierarchies form naturally** - Create epics, add children as needed

</document>

<document path="docs/core-concepts/issues.md">


# Issues & Dependencies

Understanding the issue model in beads.

## Issue Structure

Every issue has:

```bash
bd show bd-42 --json
```

```json
{
  "id": "bd-42",
  "title": "Implement authentication",
  "description": "Add JWT-based auth",
  "type": "feature",
  "status": "open",
  "priority": 1,
  "labels": ["backend", "security"],
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-15T10:30:00Z"
}
```

## Issue Types

| Type | Use Case |
|------|----------|
| `bug` | Something broken that needs fixing |
| `feature` | New functionality |
| `task` | Work item (tests, docs, refactoring) |
| `epic` | Large feature with subtasks |
| `chore` | Maintenance (dependencies, tooling) |

## Priorities

| Priority | Level | Examples |
|----------|-------|----------|
| 0 | Critical | Security, data loss, broken builds |
| 1 | High | Major features, important bugs |
| 2 | Medium | Nice-to-have features, minor bugs |
| 3 | Low | Polish, optimization |
| 4 | Backlog | Future ideas |

## Creating Issues

```bash
# Basic issue
bd create "Fix login bug" -t bug -p 1

# With description
bd create "Add password reset" \
  --description="Users need to reset forgotten passwords via email" \
  -t feature -p 2

# With labels
bd create "Update dependencies" -t chore -l "maintenance,security"

# JSON output for agents
bd create "Task" -t task --json
```

## Dependencies

### Blocking Dependencies

The `blocks` relationship affects the ready queue:

```bash
# Add dependency: bd-2 depends on bd-1
bd dep add bd-2 bd-1

# View dependencies
bd dep tree bd-2

# See blocked issues
bd blocked

# See ready work (not blocked)
bd ready
```

### Structural Relationships

These don't affect the ready queue:

```bash
# Parent-child (epic subtasks)
bd create "Epic" -t epic
bd create "Subtask" --parent bd-42

# Discovered-from (found during work)
bd create "Found bug" --deps discovered-from:bd-42

# Related (soft link)
bd relate bd-1 bd-2
```

### Dependency Types

| Type | Description | Ready Queue Impact |
|------|-------------|-------------------|
| `blocks` | Hard dependency | Yes - blocked items not ready |
| `parent-child` | Epic/subtask hierarchy | No |
| `discovered-from` | Tracks origin of discovery | No |
| `related` | Soft relationship | No |

## Hierarchical Issues

For large features, use hierarchical IDs:

```bash
# Create epic
bd create "Auth System" -t epic -p 1
# Returns: bd-a3f8e9

# Child tasks auto-number
bd create "Design login UI" --parent bd-a3f8e9     # bd-a3f8e9.1
bd create "Backend validation" --parent bd-a3f8e9  # bd-a3f8e9.2

# View hierarchy
bd dep tree bd-a3f8e9
```

## Updating Issues

```bash
# Change status
bd update bd-42 --status in_progress

# Change priority
bd update bd-42 --priority 0

# Add labels
bd update bd-42 --add-label urgent

# Multiple changes
bd update bd-42 --status in_progress --priority 1 --add-label "in-review"
```

## Closing Issues

```bash
# Simple close
bd close bd-42

# With reason
bd close bd-42 --reason "Implemented in PR #123"

# JSON output
bd close bd-42 --json
```

## Searching and Filtering

```bash
# By status
bd list --status open
bd list --status in_progress

# By priority
bd list --priority 1
bd list --priority 0,1  # Multiple

# By type
bd list --type bug
bd list --type feature,task

# By label
bd list --label-any urgent,critical
bd list --label-all backend,security

# Combined filters
bd list --status open --priority 1 --type bug --json
```

</document>

<document path="docs/core-concepts/jsonl-sync.md">


# JSONL Sync

How beads synchronizes issues across git.

## The Magic

Beads uses a dual-storage architecture:

```
SQLite DB (.beads/beads.db, gitignored)
    ↕ auto-sync (5s debounce)
JSONL (.beads/issues.jsonl, git-tracked)
    ↕ git push/pull
Remote JSONL (shared across machines)
```

**Why this design?**
- SQLite for fast local queries
- JSONL for git-friendly versioning
- Automatic sync keeps them aligned

## Auto-Sync Behavior

### Export (SQLite → JSONL)

Triggers:
- Any database change
- After 5 second debounce (batches multiple changes)
- Manual `bd sync`

```bash
# Force immediate export
bd sync

# Check what would be exported
bd export --dry-run
```

### Import (JSONL → SQLite)

Triggers:
- After `git pull` (via git hooks)
- When JSONL is newer than database
- Manual `bd import`

```bash
# Force import
bd import -i .beads/issues.jsonl

# Preview import
bd import -i .beads/issues.jsonl --dry-run
```

## Git Hooks

Install hooks for seamless sync:

```bash
bd hooks install
```

Hooks installed:
- **pre-commit** - Exports to JSONL before commit
- **post-merge** - Imports from JSONL after pull
- **pre-push** - Ensures sync before push

## Manual Sync

```bash
# Full sync cycle: export + commit + push
bd sync

# Just export
bd export

# Just import
bd import -i .beads/issues.jsonl
```

## Conflict Resolution

When JSONL conflicts occur during git merge:

### With Merge Driver (Recommended)

The beads merge driver handles JSONL conflicts automatically:

```bash
# Install merge driver
bd init  # Prompts for merge driver setup
```

The driver:
- Merges non-conflicting changes
- Preserves both sides for real conflicts
- Uses latest timestamp for same-issue edits

### Without Merge Driver

Manual resolution:

```bash
# After merge conflict
git checkout --ours .beads/issues.jsonl   # or --theirs
bd import -i .beads/issues.jsonl
bd sync
```

## Orphan Handling

When importing issues with missing parents:

```bash
# Configure orphan handling
bd config set import.orphan_handling allow     # Import anyway (default)
bd config set import.orphan_handling resurrect # Restore deleted parents
bd config set import.orphan_handling skip      # Skip orphans
bd config set import.orphan_handling strict    # Fail on orphans
```

Per-command override:

```bash
bd import -i issues.jsonl --orphan-handling resurrect
```

## Deletion Tracking

Deleted issues are tracked in `.beads/deletions.jsonl`:

```bash
# Delete issue (records to manifest)
bd delete bd-42

# View deletions
bd deleted
bd deleted --since=30d

# Deletions propagate via git
git pull  # Imports deletions from remote
```

## Troubleshooting Sync

### JSONL out of sync

```bash
# Force full sync
bd sync

# Check sync status
bd info
```

### Import errors

```bash
# Check import status
bd import -i .beads/issues.jsonl --dry-run

# Allow orphans if needed
bd import -i .beads/issues.jsonl --orphan-handling allow
```

### Duplicate detection

```bash
# Find duplicates after import
bd duplicates

# Auto-merge duplicates
bd duplicates --auto-merge
```

</document>

<document path="docs/architecture/index.md">


# Architecture Overview

This document explains how Beads' three-layer architecture works: Git, JSONL, and SQLite.

## The Three Layers

Beads uses a layered architecture where each layer serves a specific purpose:

```mermaid
flowchart TD
    subgraph GIT["🗂️ Layer 1: Git Repository"]
        G[(".beads/*.jsonl<br/><i>Historical Source of Truth</i>")]
    end

    subgraph JSONL["📄 Layer 2: JSONL Files"]
        J[("issues.jsonl<br/><i>Operational Source of Truth</i>")]
    end

    subgraph SQL["⚡ Layer 3: SQLite"]
        D[("beads.db<br/><i>Fast Queries / Derived State</i>")]
    end

    G <-->|"bd sync"| J
    J -->|"rebuild"| D
    D -->|"append"| J

    U((👤 User)) -->|"bd create<br/>bd update"| D
    D -->|"bd list<br/>bd show"| U

    style GIT fill:#2d5a27,stroke:#4a9c3e,color:#fff
    style JSONL fill:#1a4a6e,stroke:#3a8ac4,color:#fff
    style SQL fill:#6b3a6b,stroke:#a45ea4,color:#fff
```

:::info Historical vs Operational Truth
**Git** is the *historical* source of truth—commits preserve the full history of your issues and can be recovered from any point in time.

**JSONL** is the *operational* source of truth—when recovering from database corruption, Beads rebuilds SQLite from JSONL files, not directly from Git commits.

This layered model enables recovery: if SQLite is corrupted but JSONL is intact, run `bd sync --import-only` to rebuild. If JSONL is corrupted, recover it from Git history first.
:::

### Layer 1: Git Repository

Git is the *historical* source of truth. All issue data lives in the repository alongside your code, with full history preserved in commits.

**Why Git?**
- Issues travel with the code
- No external service dependency
- Full history via Git log (recover any point in time)
- Works offline
- Enables multi-machine and multi-agent workflows

### Layer 2: JSONL Files

JSONL (JSON Lines) files store issue data in an append-only format. This is the *operational* source of truth—SQLite databases are rebuilt from JSONL.

**Location:** `.beads/*.jsonl`

**Why JSONL?**
- Human-readable and inspectable
- Git-mergeable (append-only reduces conflicts)
- Portable across systems
- Can be recovered from Git history
- **Recovery source**: `bd sync --import-only` rebuilds SQLite from JSONL

### Layer 3: SQLite Database

SQLite provides fast local queries without network latency. This is *derived state*—it can always be rebuilt from JSONL.

**Location:** `.beads/beads.db`

**Why SQLite?**
- Instant queries (no network)
- Complex filtering and sorting
- Derived from JSONL (always rebuildable)
- Safe to delete and rebuild: `rm .beads/beads.db* && bd sync --import-only`

## Data Flow

### Write Path
```text
User runs bd create
    → SQLite updated
    → JSONL appended
    → Git commit (on sync)
```

### Read Path
```text
User runs bd list
    → SQLite queried
    → Results returned immediately
```

### Sync Path
```text
User runs bd sync
    → Git pull
    → JSONL merged
    → SQLite rebuilt if needed
    → Git push
```

### Sync Modes

Beads provides specialized sync modes for different recovery scenarios:

#### Standard Sync
```bash
bd sync
```
Normal bidirectional sync: pulls remote changes, merges JSONL, rebuilds SQLite if needed, pushes local changes.

#### Import-Only Mode
```bash
bd sync --import-only
```
Rebuilds the SQLite database from JSONL without pushing changes. Use this when:
- SQLite is corrupted or missing
- Recovering from a fresh clone
- Rebuilding after database migration issues

This is the safest recovery option when JSONL is intact.

#### Force Rebuild Mode
```bash
bd sync --force-rebuild
```
Forces complete SQLite rebuild from JSONL, discarding any SQLite-only state. Use with caution:
- More aggressive than `--import-only`
- May lose any uncommitted database state
- Recommended when standard sync fails repeatedly

### Multi-Machine Sync Considerations

When working across multiple machines or clones:

1. **Always sync before switching machines**
   ```bash
   bd sync  # Push changes before leaving
   ```

2. **Pull before creating new issues**
   ```bash
   bd sync  # Pull changes first on new machine
   bd create "New issue"
   ```

3. **Avoid parallel edits** - If two machines create issues simultaneously without syncing, conflicts may occur

See [Sync Failures Recovery](/recovery/sync-failures) for data loss prevention in multi-machine workflows (Pattern A5/C3).

## The Daemon

The Beads daemon (`bd daemon`) handles background synchronization:

- Watches for file changes
- Triggers sync on changes
- Keeps SQLite in sync with JSONL
- Manages lock files

:::tip
The daemon is optional but recommended for multi-agent workflows.
:::

### Running Without the Daemon

For CI/CD pipelines, containers, and single-use scenarios, run commands without spawning a daemon:

```bash
bd --no-daemon create "CI-generated issue"
bd --no-daemon sync
```

**When to use `--no-daemon`:**
- CI/CD pipelines (Jenkins, GitHub Actions)
- Docker containers
- Ephemeral environments
- Scripts that should not leave background processes
- Debugging daemon-related issues

### Daemon in Multi-Clone Scenarios

:::warning Race Conditions in Multi-Clone Workflows
When multiple git clones of the same repository run daemons simultaneously, race conditions can occur during push/pull operations. This is particularly common in:
- Multi-agent AI workflows (multiple Claude/GPT instances)
- Developer workstations with multiple checkouts
- Worktree-based development workflows

**Prevention:**
1. Use `bd daemons killall` before switching between clones
2. Ensure only one clone's daemon is active at a time
3. Consider `--no-daemon` mode for automated workflows
:::

See [Sync Failures Recovery](/recovery/sync-failures) for daemon race condition troubleshooting (Pattern B2).

## Recovery Model

The three-layer architecture makes recovery straightforward because each layer can rebuild from the one above it:

1. **Lost SQLite?** → Rebuild from JSONL: `bd sync --import-only`
2. **Lost JSONL?** → Recover from Git history: `git checkout HEAD~1 -- .beads/issues.jsonl`
3. **Conflicts?** → Git merge, then rebuild

### Universal Recovery Sequence

The following sequence demonstrates how the architecture enables quick recovery. For detailed procedures, see [Recovery Runbooks](/recovery).

This sequence resolves the majority of reported issues:

```bash
bd daemons killall           # Stop daemons (prevents race conditions)
git worktree prune           # Clean orphaned worktrees
rm .beads/beads.db*          # Remove potentially corrupted database
bd sync --import-only        # Rebuild from JSONL source of truth
```

:::danger Never Use `bd doctor --fix`
Analysis of 54 GitHub issues revealed that `bd doctor --fix` frequently causes **more damage** than the original problem:

- Deletes "circular" dependencies that are actually valid parent-child relationships
- False positive detection removes legitimate issue links
- Recovery after `--fix` is harder than recovery from the original issue

**Safe alternatives:**
- `bd doctor` — Diagnostic only, no changes made
- `bd blocked` — Check which issues are blocked and why
- `bd show <issue-id>` — Inspect a specific issue's state

If `bd doctor` reports problems, investigate each one manually before taking any action.
:::

See [Recovery](/recovery) for specific procedures and [Database Corruption Recovery](/recovery/database-corruption) for `bd doctor --fix` recovery (Pattern D4).

## Design Decisions

### Why not just SQLite?

SQLite alone doesn't travel with Git or merge well across branches. Binary database files create merge conflicts that are nearly impossible to resolve.

### Why not just JSONL?

JSONL is slow for complex queries. Scanning thousands of lines for filtering and sorting is inefficient. SQLite provides indexed lookups in milliseconds.

### Why append-only JSONL?

Append-only format minimizes Git merge conflicts. When two branches add issues, Git can cleanly merge by concatenating the additions. Edit operations append new records rather than modifying existing lines.

### Why not a server?

Beads is designed for offline-first, local-first development. No server means no downtime, no latency, no vendor lock-in, and full functionality on airplanes or in restricted networks.

### Trade-offs

| Benefit | Trade-off |
|---------|-----------|
| Works offline | No real-time collaboration |
| Git-native history | Requires Git knowledge |
| No server dependency | No web UI or mobile app |
| Local-first speed | Manual sync required |
| Append-only merging | JSONL files grow over time |

### When NOT to use Beads

Beads is not suitable for:

- **Large teams (10+)** — Git-based sync doesn't scale well for high-frequency concurrent edits
- **Non-developers** — Requires Git and command-line familiarity
- **Real-time collaboration** — No live updates; requires explicit sync
- **Cross-repository tracking** — Issues are scoped to a single repository
- **Rich media attachments** — Designed for text-based issue tracking

For these use cases, consider GitHub Issues, Linear, or Jira.

## Related Documentation

- [Recovery Runbooks](/recovery) — Step-by-step procedures for common issues
- [CLI Reference](/cli-reference) — Complete command documentation
- [Getting Started](/) — Installation and first steps

</document>

<document path="docs/cli-reference/index.md">


# CLI Reference

Complete reference for all `bd` commands.

## Command Structure

```bash
bd [global-flags] <command> [command-flags] [arguments]
```

### Global Flags

| Flag | Description |
|------|-------------|
| `--db <path>` | Use specific database file |
| `--no-daemon` | Bypass daemon, direct database access |
| `--json` | Output in JSON format |
| `--quiet` | Suppress non-essential output |
| `--verbose` | Verbose output |
| `--version` | Show version |
| `--help` | Show help |

## Command Categories

### Essential Commands

Most frequently used:

| Command | Description |
|---------|-------------|
| `bd create` | Create new issue |
| `bd list` | List issues with filters |
| `bd show` | Show issue details |
| `bd update` | Update issue fields |
| `bd close` | Close an issue |
| `bd ready` | Show unblocked work |
| `bd sync` | Force sync to git |

### Issue Management

| Command | Description |
|---------|-------------|
| `bd create` | Create issue |
| `bd show` | Show details |
| `bd update` | Update fields |
| `bd close` | Close issue |
| `bd delete` | Delete issue |
| `bd reopen` | Reopen closed issue |

### Dependencies

| Command | Description |
|---------|-------------|
| `bd dep add` | Add dependency |
| `bd dep remove` | Remove dependency |
| `bd dep tree` | Show dependency tree |
| `bd dep cycles` | Detect circular dependencies |
| `bd blocked` | Show blocked issues |
| `bd ready` | Show unblocked issues |

### Labels & Comments

| Command | Description |
|---------|-------------|
| `bd label add` | Add label to issue |
| `bd label remove` | Remove label |
| `bd label list` | List all labels |
| `bd comment add` | Add comment |
| `bd comment list` | List comments |

### Sync & Export

| Command | Description |
|---------|-------------|
| `bd sync` | Full sync cycle |
| `bd export` | Export to JSONL |
| `bd import` | Import from JSONL |
| `bd migrate` | Migrate database schema |

### System

| Command | Description |
|---------|-------------|
| `bd init` | Initialize beads in project |
| `bd info` | Show system info |
| `bd version` | Show version |
| `bd config` | Manage configuration |
| `bd daemons` | Manage daemons |
| `bd hooks` | Manage git hooks |

### Workflows

| Command | Description |
|---------|-------------|
| `bd pour` | Instantiate formula as molecule |
| `bd wisp` | Create ephemeral wisp |
| `bd mol` | Manage molecules |
| `bd pin` | Pin work to agent |
| `bd hook` | Show pinned work |

## Quick Reference

### Creating Issues

```bash
# Basic
bd create "Title" -t task -p 2

# With description
bd create "Title" --description="Details here" -t bug -p 1

# With labels
bd create "Title" -l "backend,urgent"

# As child of epic
bd create "Subtask" --parent bd-42

# With discovered-from link
bd create "Found bug" --deps discovered-from:bd-42

# JSON output
bd create "Title" --json
```

### Querying Issues

```bash
# All open issues
bd list --status open

# High priority bugs
bd list --status open --priority 0,1 --type bug

# With specific labels
bd list --label-any urgent,critical

# JSON output
bd list --json
```

### Working with Dependencies

```bash
# Add: bd-2 depends on bd-1
bd dep add bd-2 bd-1

# View tree
bd dep tree bd-2

# Find cycles
bd dep cycles

# What's ready to work?
bd ready

# What's blocked?
bd blocked
```

### Syncing

```bash
# Full sync (export + commit + push)
bd sync

# Force export
bd export

# Import from file
bd import -i .beads/issues.jsonl
```

## See Also

- [Essential Commands](/cli-reference/essential)
- [Issue Commands](/cli-reference/issues)
- [Dependency Commands](/cli-reference/dependencies)
- [Label Commands](/cli-reference/labels)
- [Sync Commands](/cli-reference/sync)

</document>

<document path="docs/cli-reference/dependencies.md">


# Dependency Commands

Commands for managing issue dependencies.

## bd dep add

Add a dependency between issues.

```bash
bd dep add <dependent> <dependency> [flags]
```

**Semantics:** `<dependent>` depends on `<dependency>` (dependency blocks dependent).

**Flags:**
```bash
--type    Dependency type (blocks|related|discovered-from)
--json    JSON output
```

**Examples:**
```bash
# bd-2 depends on bd-1 (bd-1 blocks bd-2)
bd dep add bd-2 bd-1

# Soft relationship
bd dep add bd-2 bd-1 --type related

# JSON output
bd dep add bd-2 bd-1 --json
```

## bd dep remove

Remove a dependency.

```bash
bd dep remove <dependent> <dependency> [flags]
```

**Examples:**
```bash
bd dep remove bd-2 bd-1
bd dep remove bd-2 bd-1 --json
```

## bd dep tree

Display dependency tree.

```bash
bd dep tree <id> [flags]
```

**Flags:**
```bash
--depth    Maximum depth to display
--json     JSON output
```

**Examples:**
```bash
bd dep tree bd-42
bd dep tree bd-42 --depth 3
bd dep tree bd-42 --json
```

**Output:**
```
Dependency tree for bd-42:

> bd-42: Add authentication [P2] (open)
  > bd-41: Create API [P2] (open)
    > bd-40: Set up database [P1] (closed)
```

## bd dep cycles

Detect circular dependencies.

```bash
bd dep cycles [flags]
```

**Flags:**
```bash
--json    JSON output
```

**Examples:**
```bash
bd dep cycles
bd dep cycles --json
```

## bd ready

Show issues with no blockers.

```bash
bd ready [flags]
```

**Flags:**
```bash
--priority    Filter by priority
--type        Filter by type
--label       Filter by label
--json        JSON output
```

**Examples:**
```bash
bd ready
bd ready --priority 1
bd ready --type bug
bd ready --json
```

**Output:**
```
Ready work (3 issues with no blockers):

1. [P1] bd-40: Set up database
2. [P2] bd-45: Write tests
3. [P3] bd-46: Update docs
```

## bd blocked

Show blocked issues and their blockers.

```bash
bd blocked [flags]
```

**Flags:**
```bash
--json    JSON output
```

**Examples:**
```bash
bd blocked
bd blocked --json
```

**Output:**
```
Blocked issues (2 issues):

bd-42: Add authentication
  Blocked by: bd-41 (open)

bd-41: Create API
  Blocked by: bd-40 (in_progress)
```

## bd relate

Create a soft relationship between issues.

```bash
bd relate <id1> <id2> [flags]
```

**Examples:**
```bash
bd relate bd-42 bd-43
bd relate bd-42 bd-43 --json
```

## bd duplicate

Mark an issue as duplicate.

```bash
bd duplicate <id> --of <canonical> [flags]
```

**Examples:**
```bash
bd duplicate bd-43 --of bd-42
bd duplicate bd-43 --of bd-42 --json
```

## bd supersede

Mark an issue as superseding another.

```bash
bd supersede <old> --with <new> [flags]
```

**Examples:**
```bash
bd supersede bd-42 --with bd-50
bd supersede bd-42 --with bd-50 --json
```

## Understanding Dependencies

### Blocking vs Non-blocking

| Type | Blocks Ready Queue | Use Case |
|------|-------------------|----------|
| `blocks` | Yes | Hard dependency |
| `parent-child` | No | Epic/subtask hierarchy |
| `discovered-from` | No | Track origin |
| `related` | No | Soft link |
| `duplicates` | No | Mark duplicate |
| `supersedes` | No | Version chain |

### Dependency Direction

```bash
# bd-2 depends on bd-1
# Meaning: bd-1 must complete before bd-2 can start
bd dep add bd-2 bd-1

# After bd-1 closes:
bd close bd-1
bd ready  # bd-2 now appears
```

### Avoiding Cycles

```bash
# Check before adding complex dependencies
bd dep cycles

# If cycle detected, remove one dependency
bd dep remove bd-A bd-B
```

</document>

<document path="docs/cli-reference/essential.md">


# Essential Commands

The most important commands for daily use.

## bd create

Create a new issue.

```bash
bd create <title> [flags]
```

**Flags:**
| Flag | Short | Description |
|------|-------|-------------|
| `--type` | `-t` | Issue type: bug, feature, task, epic, chore |
| `--priority` | `-p` | Priority: 0-4 (0=critical, 4=backlog) |
| `--description` | `-d` | Detailed description |
| `--labels` | `-l` | Comma-separated labels |
| `--parent` | | Parent issue ID (for hierarchical) |
| `--deps` | | Dependencies (e.g., `discovered-from:bd-42`) |
| `--json` | | JSON output |

**Examples:**
```bash
bd create "Fix login bug" -t bug -p 1
bd create "Add dark mode" -t feature -p 2 --description="User requested"
bd create "Subtask" --parent bd-42 -p 2
bd create "Found during work" --deps discovered-from:bd-42 --json
```

## bd list

List issues with filters.

```bash
bd list [flags]
```

**Flags:**
| Flag | Description |
|------|-------------|
| `--status` | Filter by status: open, in_progress, closed |
| `--priority` | Filter by priority (comma-separated) |
| `--type` | Filter by type (comma-separated) |
| `--label-any` | Issues with any of these labels |
| `--label-all` | Issues with all of these labels |
| `--json` | JSON output |

**Examples:**
```bash
bd list --status open
bd list --priority 0,1 --type bug
bd list --label-any urgent,critical --json
```

## bd show

Show issue details.

```bash
bd show <id> [flags]
```

**Examples:**
```bash
bd show bd-42
bd show bd-42 --json
bd show bd-42 bd-43 bd-44  # Multiple issues
```

## bd update

Update issue fields.

```bash
bd update <id> [flags]
```

**Flags:**
| Flag | Description |
|------|-------------|
| `--status` | New status |
| `--priority` | New priority |
| `--title` | New title |
| `--description` | New description |
| `--add-label` | Add label |
| `--remove-label` | Remove label |
| `--json` | JSON output |

**Examples:**
```bash
bd update bd-42 --status in_progress
bd update bd-42 --priority 0 --add-label urgent
bd update bd-42 --title "Updated title" --json
```

## bd close

Close an issue.

```bash
bd close <id> [flags]
```

**Flags:**
| Flag | Description |
|------|-------------|
| `--reason` | Closure reason |
| `--json` | JSON output |

**Examples:**
```bash
bd close bd-42
bd close bd-42 --reason "Fixed in PR #123"
bd close bd-42 --json
```

## bd ready

Show issues ready to work on (no blockers).

```bash
bd ready [flags]
```

**Flags:**
| Flag | Description |
|------|-------------|
| `--priority` | Filter by priority |
| `--type` | Filter by type |
| `--json` | JSON output |

**Examples:**
```bash
bd ready
bd ready --priority 1
bd ready --json
```

## bd blocked

Show blocked issues and their blockers.

```bash
bd blocked [flags]
```

**Examples:**
```bash
bd blocked
bd blocked --json
```

## bd sync

Force immediate sync to git.

```bash
bd sync [flags]
```

Performs:
1. Export database to JSONL
2. Git add `.beads/issues.jsonl`
3. Git commit
4. Git push

**Examples:**
```bash
bd sync
bd sync --json
```

## bd info

Show system information.

```bash
bd info [flags]
```

**Flags:**
| Flag | Description |
|------|-------------|
| `--whats-new` | Show recent version changes |
| `--schema` | Show database schema |
| `--json` | JSON output |

**Examples:**
```bash
bd info
bd info --whats-new
bd info --json
```

## bd stats

Show project statistics.

```bash
bd stats [flags]
```

**Examples:**
```bash
bd stats
bd stats --json
```

</document>

<document path="docs/cli-reference/issues.md">


# Issue Commands

Commands for managing issues.

## bd create

Create a new issue.

```bash
bd create <title> [flags]
```

**All flags:**
```bash
--type, -t        Issue type (bug|feature|task|epic|chore)
--priority, -p    Priority 0-4
--description, -d Detailed description
--design          Design notes
--acceptance      Acceptance criteria
--notes           Additional notes
--labels, -l      Comma-separated labels
--parent          Parent issue ID
--deps            Dependencies (type:id format)
--assignee        Assigned user
--json            JSON output
```

**Examples:**
```bash
# Bug with high priority
bd create "Login fails with special chars" -t bug -p 1

# Feature with description
bd create "Add export to PDF" -t feature -p 2 \
  --description="Users want to export reports as PDF files"

# Feature with design, acceptance, and notes
bd create "Implement user authentication" -t feature -p 1 \
  --description="Add JWT-based authentication" \
  --design="Use bcrypt for password hashing, JWT for sessions" \
  --acceptance="All tests pass, security audit complete" \
  --notes="Consider rate limiting for login attempts"

# Task with labels
bd create "Update CI config" -t task -l "ci,infrastructure"

# Epic with children
bd create "Auth System" -t epic -p 1
bd create "Design login UI" --parent bd-42
bd create "Implement backend" --parent bd-42

# Discovered issue
bd create "Found SQL injection" -t bug -p 0 \
  --deps discovered-from:bd-42 --json
```

## bd show

Display issue details.

```bash
bd show <id>... [flags]
```

**Flags:**
```bash
--full        Show all fields including comments
--json        JSON output
```

**Examples:**
```bash
bd show bd-42
bd show bd-42 --full
bd show bd-42 bd-43 bd-44 --json
```

## bd update

Update issue fields.

```bash
bd update <id> [flags]
```

**All flags:**
```bash
--status          New status (open|in_progress|closed)
--priority        New priority (0-4)
--title           New title
--description     New description
--type            New type
--add-label       Add label(s)
--remove-label    Remove label(s)
--assignee        New assignee
--json            JSON output
```

**Examples:**
```bash
# Start work
bd update bd-42 --status in_progress

# Escalate priority
bd update bd-42 --priority 0 --add-label urgent

# Change title and description
bd update bd-42 --title "New title" --description="Updated description"

# Multiple changes
bd update bd-42 --status in_progress --priority 1 --add-label "in-review" --json
```

## bd close

Close an issue.

```bash
bd close <id> [flags]
```

**Flags:**
```bash
--reason    Closure reason (stored in comment)
--json      JSON output
```

**Examples:**
```bash
bd close bd-42
bd close bd-42 --reason "Fixed in commit abc123"
bd close bd-42 --reason "Duplicate of bd-43" --json
```

## bd reopen

Reopen a closed issue.

```bash
bd reopen <id> [flags]
```

**Examples:**
```bash
bd reopen bd-42
bd reopen bd-42 --json
```

## bd delete

Delete an issue.

```bash
bd delete <id> [flags]
```

**Flags:**
```bash
--force, -f    Skip confirmation
--json         JSON output
```

**Examples:**
```bash
bd delete bd-42
bd delete bd-42 -f --json
```

**Note:** Deletions are tracked in `.beads/deletions.jsonl` for sync.

## bd search

Search issues by text.

```bash
bd search <query> [flags]
```

**Flags:**
```bash
--status    Filter by status
--type      Filter by type
--json      JSON output
```

**Examples:**
```bash
bd search "authentication"
bd search "login bug" --status open
bd search "API" --type feature --json
```

## bd duplicates

Find and manage duplicate issues.

```bash
bd duplicates [flags]
```

**Flags:**
```bash
--auto-merge    Automatically merge all duplicates
--dry-run       Preview without changes
--json          JSON output
```

**Examples:**
```bash
bd duplicates
bd duplicates --auto-merge
bd duplicates --dry-run --json
```

## bd merge

Merge duplicate issues.

```bash
bd merge <source>... --into <target> [flags]
```

**Flags:**
```bash
--into      Target issue to merge into
--dry-run   Preview without changes
--json      JSON output
```

**Examples:**
```bash
bd merge bd-42 bd-43 --into bd-41
bd merge bd-42 bd-43 --into bd-41 --dry-run --json
```

</document>

<document path="docs/cli-reference/labels.md">


# Labels & Comments

Commands for managing labels and comments.

## Labels

### Adding Labels

```bash
# During creation
bd create "Task" -l "backend,urgent"

# To existing issue
bd update bd-42 --add-label urgent
bd update bd-42 --add-label "backend,security"
```

### Removing Labels

```bash
bd update bd-42 --remove-label urgent
```

### Listing Labels

```bash
# All labels in use
bd label list
bd label list --json

# Issues with specific labels
bd list --label-any urgent,critical
bd list --label-all backend,security
```

### Label Conventions

Suggested label categories:

| Category | Examples | Purpose |
|----------|----------|---------|
| Type | `bug`, `feature`, `docs` | Issue classification |
| Priority | `urgent`, `critical` | Urgency markers |
| Area | `backend`, `frontend`, `api` | Code area |
| Status | `blocked`, `needs-review` | Workflow state |
| Size | `small`, `medium`, `large` | Effort estimate |

## Comments

### Adding Comments

```bash
bd comment add bd-42 "Working on this now"
bd comment add bd-42 --message "Found the bug in auth.go:45"
```

### Listing Comments

```bash
bd comment list bd-42
bd comment list bd-42 --json
```

### Viewing with Issue

```bash
bd show bd-42 --full  # Includes comments
```

## Filtering by Labels

### Any Match (OR)

```bash
# Issues with urgent OR critical
bd list --label-any urgent,critical
```

### All Match (AND)

```bash
# Issues with BOTH backend AND security
bd list --label-all backend,security
```

### Combined Filters

```bash
# Open bugs with urgent label
bd list --status open --type bug --label-any urgent --json
```

## Bulk Operations

### Add Label to Multiple Issues

```bash
# Using shell
for id in bd-42 bd-43 bd-44; do
  bd update $id --add-label "sprint-1"
done
```

### Find and Label

```bash
# Label all open bugs as needs-triage
bd list --status open --type bug --json | \
  jq -r '.[].id' | \
  xargs -I {} bd update {} --add-label needs-triage
```

## Best Practices

1. **Keep labels lowercase** - `backend` not `Backend`
2. **Use hyphens for multi-word** - `needs-review` not `needs_review`
3. **Be consistent** - Establish team conventions
4. **Don't over-label** - 2-4 labels per issue is typical
5. **Review periodically** - Remove unused labels

</document>

<document path="docs/cli-reference/sync.md">


# Sync & Export Commands

Commands for synchronizing with git.

## bd sync

Full sync cycle: export, commit, push.

```bash
bd sync [flags]
```

**What it does:**
1. Exports database to `.beads/issues.jsonl`
2. Stages the JSONL file
3. Commits with auto-generated message
4. Pushes to remote

**Flags:**
```bash
--json     JSON output
--dry-run  Preview without changes
```

**Examples:**
```bash
bd sync
bd sync --json
```

**When to use:**
- End of work session
- Before switching branches
- After significant changes

## bd export

Export database to JSONL.

```bash
bd export [flags]
```

**Flags:**
```bash
--output, -o    Output file (default: .beads/issues.jsonl)
--dry-run       Preview without writing
--json          JSON output
```

**Examples:**
```bash
bd export
bd export -o backup.jsonl
bd export --dry-run
```

## bd import

Import from JSONL file.

```bash
bd import -i <file> [flags]
```

**Flags:**
```bash
--input, -i           Input file (required)
--dry-run             Preview without changes
--orphan-handling     How to handle missing parents
--dedupe-after        Run duplicate detection after import
--json                JSON output
```

**Orphan handling modes:**
| Mode | Behavior |
|------|----------|
| `allow` | Import orphans without validation (default) |
| `resurrect` | Restore deleted parents as tombstones |
| `skip` | Skip orphaned children with warning |
| `strict` | Fail if parent missing |

**Examples:**
```bash
bd import -i .beads/issues.jsonl
bd import -i backup.jsonl --dry-run
bd import -i issues.jsonl --orphan-handling resurrect
bd import -i issues.jsonl --dedupe-after --json
```

## bd migrate

Migrate database schema.

```bash
bd migrate [flags]
```

**Flags:**
```bash
--inspect    Show migration plan (for agents)
--dry-run    Preview without changes
--cleanup    Remove old files after migration
--yes        Skip confirmation
--json       JSON output
```

**Examples:**
```bash
bd migrate --inspect --json
bd migrate --dry-run
bd migrate
bd migrate --cleanup --yes
```

## bd hooks

Manage git hooks.

```bash
bd hooks <subcommand> [flags]
```

**Subcommands:**
| Command | Description |
|---------|-------------|
| `install` | Install git hooks |
| `uninstall` | Remove git hooks |
| `status` | Check hook status |

**Examples:**
```bash
bd hooks install
bd hooks status
bd hooks uninstall
```

## Auto-Sync Behavior

### With Daemon (Default)

The daemon handles sync automatically:
- Exports to JSONL after changes (5s debounce)
- Imports from JSONL when newer

### Without Daemon

Use `--no-daemon` flag:
- Changes only written to SQLite
- Must manually export/sync

```bash
bd --no-daemon create "Task"
bd export  # Manual export needed
```

## Conflict Resolution

### Merge Driver (Recommended)

Install the beads merge driver:

```bash
bd init  # Prompts for merge driver setup
```

The driver automatically:
- Merges non-conflicting changes
- Preserves both sides for real conflicts
- Uses latest timestamp for same-issue edits

### Manual Resolution

```bash
# After merge conflict
git checkout --ours .beads/issues.jsonl
bd import -i .beads/issues.jsonl
bd sync
```

## Deletion Tracking

Deletions sync via `.beads/deletions.jsonl`:

```bash
# Delete issue
bd delete bd-42

# View deletions
bd deleted
bd deleted --since=30d

# Deletions propagate via git
git pull  # Imports deletions from remote
```

## Best Practices

1. **Always sync at session end** - `bd sync`
2. **Install git hooks** - `bd hooks install`
3. **Use merge driver** - Avoids manual conflict resolution
4. **Check sync status** - `bd info` shows daemon/sync state

</document>

<document path="docs/workflows/index.md">


# Workflows

Beads provides powerful workflow primitives for complex, multi-step processes.

## Chemistry Metaphor

Beads uses a molecular chemistry metaphor:

| Phase | Storage | Synced | Use Case |
|-------|---------|--------|----------|
| **Proto** (solid) | Built-in | N/A | Reusable templates |
| **Mol** (liquid) | `.beads/` | Yes | Persistent work |
| **Wisp** (vapor) | `.beads-wisp/` | No | Ephemeral operations |

## Core Concepts

### Formulas

Declarative workflow templates in TOML or JSON:

```toml
formula = "feature-workflow"
version = 1
type = "workflow"

[[steps]]
id = "design"
title = "Design the feature"
type = "human"

[[steps]]
id = "implement"
title = "Implement the feature"
needs = ["design"]
```

### Molecules

Work graphs with parent-child relationships:
- Created by instantiating formulas with `bd pour`
- Steps have dependencies (`needs`)
- Progress tracked via issue status

### Gates

Async coordination primitives:
- **Human gates** - Wait for human approval
- **Timer gates** - Wait for duration
- **GitHub gates** - Wait for PR merge, CI, etc.

### Wisps

Ephemeral operations that don't sync to git:
- Created with `bd wisp`
- Stored in `.beads-wisp/` (gitignored)
- Auto-expire after completion

## Workflow Commands

| Command | Description |
|---------|-------------|
| `bd pour` | Instantiate formula as molecule |
| `bd wisp` | Create ephemeral wisp |
| `bd mol list` | List molecules |
| `bd pin` | Pin work to agent |
| `bd hook` | Show pinned work |

## Simple Example

```bash
# Create a release workflow
bd pour release --var version=1.0.0

# View the molecule
bd mol show release-1.0.0

# Work through steps
bd update release-1.0.0.1 --status in_progress
bd close release-1.0.0.1
# Next step becomes ready...
```

## Navigation

- [Molecules](/workflows/molecules) - Work graphs and execution
- [Formulas](/workflows/formulas) - Declarative templates
- [Gates](/workflows/gates) - Async coordination
- [Wisps](/workflows/wisps) - Ephemeral operations

</document>

<document path="docs/workflows/formulas.md">


# Formulas

Formulas are declarative workflow templates.

## Formula Format

Formulas can be written in TOML (preferred) or JSON:

### TOML Format

```toml
formula = "feature-workflow"
description = "Standard feature development workflow"
version = 1
type = "workflow"

[vars.feature_name]
description = "Name of the feature"
required = true

[[steps]]
id = "design"
title = "Design {{feature_name}}"
type = "human"
description = "Create design document"

[[steps]]
id = "implement"
title = "Implement {{feature_name}}"
needs = ["design"]

[[steps]]
id = "review"
title = "Code review"
needs = ["implement"]
type = "human"

[[steps]]
id = "merge"
title = "Merge to main"
needs = ["review"]
```

### JSON Format

```json
{
  "formula": "feature-workflow",
  "description": "Standard feature development workflow",
  "version": 1,
  "type": "workflow",
  "vars": {
    "feature_name": {
      "description": "Name of the feature",
      "required": true
    }
  },
  "steps": [
    {
      "id": "design",
      "title": "Design {{feature_name}}",
      "type": "human"
    },
    {
      "id": "implement",
      "title": "Implement {{feature_name}}",
      "needs": ["design"]
    }
  ]
}
```

## Formula Types

| Type | Description |
|------|-------------|
| `workflow` | Standard step sequence |
| `expansion` | Template for expansion operator |
| `aspect` | Cross-cutting concerns |

## Variables

Define variables with defaults and constraints:

```toml
[vars.version]
description = "Release version"
required = true
pattern = "^\\d+\\.\\d+\\.\\d+$"

[vars.environment]
description = "Target environment"
default = "staging"
enum = ["staging", "production"]
```

Use variables in steps:

```toml
[[steps]]
title = "Deploy {{version}} to {{environment}}"
```

## Step Types

| Type | Description |
|------|-------------|
| `task` | Normal work step (default) |
| `human` | Requires human action |
| `gate` | Async coordination point |

## Dependencies

### Sequential

```toml
[[steps]]
id = "step1"
title = "First step"

[[steps]]
id = "step2"
title = "Second step"
needs = ["step1"]
```

### Parallel then Join

```toml
[[steps]]
id = "test-unit"
title = "Unit tests"

[[steps]]
id = "test-integration"
title = "Integration tests"

[[steps]]
id = "deploy"
title = "Deploy"
needs = ["test-unit", "test-integration"]  # Waits for both
```

## Gates

Add gates for async coordination:

```toml
[[steps]]
id = "approval"
title = "Manager approval"
type = "human"

[steps.gate]
type = "human"
approvers = ["manager"]

[[steps]]
id = "deploy"
title = "Deploy to production"
needs = ["approval"]
```

## Aspects (Cross-cutting)

Apply transformations to matching steps:

```toml
formula = "security-scan"
type = "aspect"

[[advice]]
target = "*.deploy"  # Match all deploy steps

[advice.before]
id = "security-scan-{step.id}"
title = "Security scan before {step.title}"
```

## Formula Locations

Formulas are searched in order:
1. `.beads/formulas/` (project-level)
2. `~/.beads/formulas/` (user-level)
3. Built-in formulas

## Using Formulas

```bash
# List available formulas
bd mol list

# Pour formula into molecule
bd pour <formula-name> --var key=value

# Preview what would be created
bd pour <formula-name> --dry-run
```

## Creating Custom Formulas

1. Create file: `.beads/formulas/my-workflow.formula.toml`
2. Define structure (see examples above)
3. Use with: `bd pour my-workflow`

## Example: Release Formula

```toml
formula = "release"
description = "Standard release workflow"
version = 1

[vars.version]
required = true
pattern = "^\\d+\\.\\d+\\.\\d+$"

[[steps]]
id = "bump-version"
title = "Bump version to {{version}}"

[[steps]]
id = "changelog"
title = "Update CHANGELOG"
needs = ["bump-version"]

[[steps]]
id = "test"
title = "Run full test suite"
needs = ["changelog"]

[[steps]]
id = "build"
title = "Build release artifacts"
needs = ["test"]

[[steps]]
id = "tag"
title = "Create git tag v{{version}}"
needs = ["build"]

[[steps]]
id = "publish"
title = "Publish release"
needs = ["tag"]
type = "human"
```

</document>

<document path="docs/workflows/gates.md">


# Gates

Gates are async coordination primitives for workflow orchestration.

## What are Gates?

Gates block step progression until a condition is met:
- Human approval
- Timer expiration
- External event (GitHub PR, CI, etc.)

## Gate Types

### Human Gate

Wait for human approval:

```toml
[[steps]]
id = "deploy-approval"
title = "Approval for production deploy"
type = "human"

[steps.gate]
type = "human"
approvers = ["team-lead", "security"]
require_all = false  # Any approver can approve
```

### Timer Gate

Wait for a duration:

```toml
[[steps]]
id = "cooldown"
title = "Wait for cooldown period"

[steps.gate]
type = "timer"
duration = "24h"
```

Durations: `30m`, `2h`, `24h`, `7d`

### GitHub Gate

Wait for GitHub events:

```toml
[[steps]]
id = "wait-for-ci"
title = "Wait for CI to pass"

[steps.gate]
type = "github"
event = "check_suite"
status = "success"
```

```toml
[[steps]]
id = "wait-for-merge"
title = "Wait for PR merge"

[steps.gate]
type = "github"
event = "pull_request"
action = "closed"
merged = true
```

## Gate States

| State | Description |
|-------|-------------|
| `pending` | Waiting for condition |
| `open` | Condition met, can proceed |
| `closed` | Step completed |

## Using Gates in Workflows

### Approval Flow

```toml
formula = "production-deploy"

[[steps]]
id = "build"
title = "Build production artifacts"

[[steps]]
id = "staging"
title = "Deploy to staging"
needs = ["build"]

[[steps]]
id = "qa-approval"
title = "QA sign-off"
needs = ["staging"]
type = "human"

[steps.gate]
type = "human"
approvers = ["qa-team"]

[[steps]]
id = "production"
title = "Deploy to production"
needs = ["qa-approval"]
```

### Scheduled Release

```toml
formula = "scheduled-release"

[[steps]]
id = "prepare"
title = "Prepare release"

[[steps]]
id = "wait-window"
title = "Wait for release window"
needs = ["prepare"]

[steps.gate]
type = "timer"
duration = "2h"

[[steps]]
id = "deploy"
title = "Deploy release"
needs = ["wait-window"]
```

### CI Integration

```toml
formula = "ci-gated-deploy"

[[steps]]
id = "create-pr"
title = "Create pull request"

[[steps]]
id = "wait-ci"
title = "Wait for CI"
needs = ["create-pr"]

[steps.gate]
type = "github"
event = "check_suite"
status = "success"

[[steps]]
id = "merge"
title = "Merge PR"
needs = ["wait-ci"]
type = "human"
```

## Gate Operations

### Check Gate Status

```bash
bd show bd-xyz.3  # Shows gate state
bd show bd-xyz.3 --json | jq '.gate'
```

### Manual Gate Override

For human gates:

```bash
bd gate approve bd-xyz.3 --approver "team-lead"
```

### Skip Gate (Emergency)

```bash
bd gate skip bd-xyz.3 --reason "Emergency deploy"
```

## waits-for Dependency

The `waits-for` dependency type creates fan-in patterns:

```toml
[[steps]]
id = "test-a"
title = "Test suite A"

[[steps]]
id = "test-b"
title = "Test suite B"

[[steps]]
id = "integration"
title = "Integration tests"
waits_for = ["test-a", "test-b"]  # Fan-in: waits for all
```

## Best Practices

1. **Use human gates for critical decisions** - Don't auto-approve production
2. **Add timeout to timer gates** - Prevent indefinite blocking
3. **Document gate requirements** - Make approvers clear
4. **Use CI gates for quality** - Block on test failures

</document>

<document path="docs/workflows/molecules.md">


# Molecules

Molecules are work graphs created from formulas.

## What is a Molecule?

A molecule is a persistent instance of a formula:
- Contains steps with dependencies
- Tracked in `.beads/` (syncs with git)
- Steps map to issues with parent-child relationships

## Creating Molecules

### From Formula

```bash
# Pour a formula into a molecule
bd pour <formula-name> [--var key=value]
```

**Example:**
```bash
bd pour release --var version=1.0.0
```

This creates:
- Parent issue: `bd-xyz` (the molecule root)
- Child issues: `bd-xyz.1`, `bd-xyz.2`, etc. (the steps)

### Listing Molecules

```bash
bd mol list
bd mol list --json
```

### Viewing a Molecule

```bash
bd mol show <molecule-id>
bd dep tree <molecule-id>  # Shows full hierarchy
```

## Working with Molecules

### Step Dependencies

Steps have `needs` dependencies:

```toml
[[steps]]
id = "implement"
title = "Implement feature"
needs = ["design"]  # Must complete design first
```

The `bd ready` command respects these:

```bash
bd ready  # Only shows steps with completed dependencies
```

### Progressing Through Steps

```bash
# Start a step
bd update bd-xyz.1 --status in_progress

# Complete a step
bd close bd-xyz.1 --reason "Done"

# Check what's ready next
bd ready
```

### Viewing Progress

```bash
# See blocked steps
bd blocked

# See molecule stats
bd stats
```

## Molecule Lifecycle

```
Formula (template)
    ↓ bd pour
Molecule (instance)
    ↓ work steps
Completed Molecule
    ↓ optional cleanup
Archived
```

## Advanced Features

### Bond Points

Formulas can define bond points for composition:

```toml
[compose]
[[compose.bond_points]]
id = "entry"
step = "design"
position = "before"
```

### Hooks

Execute actions on step completion:

```toml
[[steps]]
id = "build"
title = "Build project"

[steps.on_complete]
run = "make build"
```

### Pinning Work

Assign molecules to agents:

```bash
# Pin to current agent
bd pin bd-xyz --start

# Check what's pinned
bd hook
```

## Example Workflow

```bash
# 1. Create molecule from formula
bd pour feature-workflow --var name="dark-mode"

# 2. View structure
bd dep tree bd-xyz

# 3. Start first step
bd update bd-xyz.1 --status in_progress

# 4. Complete and progress
bd close bd-xyz.1
bd ready  # Shows next steps

# 5. Continue until complete
```

## See Also

- [Formulas](/workflows/formulas) - Creating templates
- [Gates](/workflows/gates) - Async coordination
- [Wisps](/workflows/wisps) - Ephemeral workflows

</document>

<document path="docs/workflows/wisps.md">


# Wisps

Wisps are ephemeral workflows that don't sync to git.

## What are Wisps?

Wisps are "vapor phase" molecules:
- Stored in `.beads-wisp/` (gitignored)
- Don't sync with git
- Auto-expire after completion
- Perfect for temporary operations

## Use Cases

| Scenario | Why Wisp? |
|----------|-----------|
| Local experiments | No need to pollute git history |
| CI/CD pipelines | Ephemeral by nature |
| Scratch workflows | Quick throwaway work |
| Agent coordination | Local-only coordination |

## Creating Wisps

```bash
# Create wisp from formula
bd wisp create <formula> [--var key=value]

# Example
bd wisp create quick-check --var target=auth-module
```

## Wisp Commands

```bash
# List wisps
bd wisp list
bd wisp list --json

# Show wisp details
bd wisp show <wisp-id>

# Delete wisp
bd wisp delete <wisp-id>

# Delete all completed wisps
bd wisp cleanup
```

## Wisp vs Molecule

| Aspect | Molecule | Wisp |
|--------|----------|------|
| Storage | `.beads/` | `.beads-wisp/` |
| Git sync | Yes | No |
| Persistence | Permanent | Ephemeral |
| Use case | Tracked work | Temporary ops |

## Phase Control

Use `bd mol bond` to control phase:

```bash
# Force liquid (persistent molecule)
bd mol bond <formula> <target> --pour

# Force vapor (ephemeral wisp)
bd mol bond <formula> <target> --wisp
```

## Example: Quick Check Workflow

Create a wisp for running checks:

```toml
# .beads/formulas/quick-check.formula.toml
formula = "quick-check"
description = "Quick local checks"

[[steps]]
id = "lint"
title = "Run linter"

[[steps]]
id = "test"
title = "Run tests"
needs = ["lint"]

[[steps]]
id = "build"
title = "Build project"
needs = ["test"]
```

Use as wisp:

```bash
bd wisp create quick-check
# Work through steps...
bd wisp cleanup  # Remove when done
```

## Auto-Expiration

Wisps can auto-expire:

```toml
[wisp]
expires_after = "24h"  # Auto-delete after 24 hours
```

Or cleanup manually:

```bash
bd wisp cleanup --all  # Remove all wisps
bd wisp cleanup --completed  # Remove only completed
```

## Best Practices

1. **Use wisps for local-only work** - Don't sync to git
2. **Clean up regularly** - `bd wisp cleanup`
3. **Use molecules for tracked work** - Wisps are ephemeral
4. **Consider CI/CD wisps** - Perfect for pipeline steps

</document>

<document path="docs/multi-agent/index.md">


# Multi-Agent Coordination

Beads supports coordination between multiple AI agents and repositories.

## Overview

Multi-agent features enable:
- **Routing** - Automatic issue routing to correct repositories
- **Cross-repo dependencies** - Dependencies across repository boundaries
- **Agent coordination** - Work assignment and handoff between agents

## Key Concepts

### Routes

Routes define which repository handles which issues:

```jsonl
{"pattern": "frontend/*", "target": "frontend-repo"}
{"pattern": "backend/*", "target": "backend-repo"}
{"pattern": "*", "target": "main-repo"}
```

### Work Assignment

Pin work to specific agents:

```bash
bd pin bd-42 --for agent-1 --start
bd hook --agent agent-1  # Show pinned work
```

### Cross-repo Dependencies

Track dependencies across repositories:

```bash
bd dep add bd-42 external:other-repo/bd-100
```

## Architecture

```
┌─────────────────┐
│   Main Repo     │
│   (coordinator) │
└────────┬────────┘
         │ routes
    ┌────┴────┐
    │         │
┌───▼───┐ ┌───▼───┐
│Frontend│ │Backend│
│ Repo   │ │ Repo  │
└────────┘ └────────┘
```

## Getting Started

1. **Single repo**: Standard beads workflow
2. **Multi-repo**: Configure routes and cross-repo deps
3. **Multi-agent**: Add work assignment and handoff

## Navigation

- [Routing](/multi-agent/routing) - Auto-routing configuration
- [Coordination](/multi-agent/coordination) - Agent coordination patterns

</document>

<document path="docs/multi-agent/coordination.md">


# Agent Coordination

Patterns for coordinating work between multiple AI agents.

## Work Assignment

### Pinning Work

Assign work to a specific agent:

```bash
# Pin issue to agent
bd pin bd-42 --for agent-1

# Pin and start work
bd pin bd-42 --for agent-1 --start

# Unpin work
bd unpin bd-42
```

### Checking Pinned Work

```bash
# What's on my hook?
bd hook

# What's on agent-1's hook?
bd hook --agent agent-1

# JSON output
bd hook --json
```

## Handoff Patterns

### Sequential Handoff

Agent A completes work, hands off to Agent B:

```bash
# Agent A
bd close bd-42 --reason "Ready for review"
bd pin bd-42 --for agent-b

# Agent B picks up
bd hook  # Sees bd-42
bd update bd-42 --status in_progress
```

### Parallel Work

Multiple agents work on different issues:

```bash
# Coordinator
bd pin bd-42 --for agent-a --start
bd pin bd-43 --for agent-b --start
bd pin bd-44 --for agent-c --start

# Each agent works independently
# Coordinator monitors progress
bd list --status in_progress --json
```

### Fan-Out / Fan-In

Split work, then merge:

```bash
# Fan-out
bd create "Part A" --parent bd-epic
bd create "Part B" --parent bd-epic
bd create "Part C" --parent bd-epic

bd pin bd-epic.1 --for agent-a
bd pin bd-epic.2 --for agent-b
bd pin bd-epic.3 --for agent-c

# Fan-in: wait for all parts
bd dep add bd-merge bd-epic.1 bd-epic.2 bd-epic.3
```

## Agent Discovery

Find available agents:

```bash
# List known agents (if using agent registry)
bd agents list

# Check agent status
bd agents status agent-1
```

## Conflict Prevention

### File Reservations

Prevent concurrent edits:

```bash
# Reserve files before editing
bd reserve auth.go --for agent-1

# Check reservations
bd reservations list

# Release when done
bd reserve --release auth.go
```

### Issue Locking

```bash
# Lock issue for exclusive work
bd lock bd-42 --for agent-1

# Unlock when done
bd unlock bd-42
```

## Communication Patterns

### Via Comments

```bash
# Agent A leaves note
bd comment add bd-42 "Completed API, needs frontend integration"

# Agent B reads
bd show bd-42 --full
```

### Via Labels

```bash
# Mark for review
bd update bd-42 --add-label "needs-review"

# Agent B filters
bd list --label-any needs-review
```

## Best Practices

1. **Clear ownership** - Always pin work to specific agent
2. **Document handoffs** - Use comments to explain context
3. **Use labels for status** - `needs-review`, `blocked`, `ready`
4. **Avoid conflicts** - Use reservations for shared files
5. **Monitor progress** - Regular status checks

</document>

<document path="docs/multi-agent/routing.md">


# Multi-Repo Routing

Automatic issue routing across repositories.

## Overview

Routing enables:
- Issues created in one repo routed to another
- Pattern-based routing rules
- Fallback to default repository

## Configuration

Create `.beads/routes.jsonl`:

```jsonl
{"pattern": "frontend/**", "target": "frontend-repo", "priority": 10}
{"pattern": "backend/**", "target": "backend-repo", "priority": 10}
{"pattern": "docs/**", "target": "docs-repo", "priority": 5}
{"pattern": "*", "target": "main-repo", "priority": 0}
```

## Route Fields

| Field | Description |
|-------|-------------|
| `pattern` | Glob pattern to match |
| `target` | Target repository |
| `priority` | Higher = checked first |

## Pattern Matching

Patterns match against:
- Issue title
- Labels
- Explicit path prefix

**Examples:**
```jsonl
{"pattern": "frontend/*", "target": "frontend"}
{"pattern": "*api*", "target": "backend"}
{"pattern": "label:docs", "target": "docs-repo"}
```

## Commands

```bash
# Show routing table
bd routes list
bd routes list --json

# Test routing
bd routes test "Fix frontend button"
bd routes test --label frontend

# Add route
bd routes add "frontend/**" --target frontend-repo --priority 10

# Remove route
bd routes remove "frontend/**"
```

## Auto-Routing

When creating issues, beads checks routes:

```bash
bd create "Fix frontend button alignment" -t bug
# Auto-routed to frontend-repo based on title match
```

Override with explicit target:

```bash
bd create "Fix button" --repo backend-repo
```

## Cross-Repo Dependencies

Track dependencies across repos:

```bash
# In frontend-repo
bd dep add bd-42 external:backend-repo/bd-100

# View cross-repo deps
bd dep tree bd-42 --cross-repo
```

## Hydration

Pull related issues from other repos:

```bash
# Hydrate issues from related repos
bd hydrate

# Preview hydration
bd hydrate --dry-run

# Hydrate specific repo
bd hydrate --from backend-repo
```

## Best Practices

1. **Use specific patterns** - Avoid overly broad matches
2. **Set priorities** - Ensure specific patterns match first
3. **Default fallback** - Always have a `*` pattern with lowest priority
4. **Test routes** - Use `bd routes test` before committing

</document>

<document path="docs/integrations/aider.md">


# Aider Integration

How to use beads with Aider.

## Setup

### Quick Setup

```bash
bd setup aider
```

This creates/updates `.aider.conf.yml` with beads context.

### Verify Setup

```bash
bd setup aider --check
```

## Configuration

The setup adds to `.aider.conf.yml`:

```yaml
# Beads integration
read:
  - .beads/issues.jsonl

# Optional: Auto-run bd prime
auto-commits: false
```

## Workflow

### Start Session

```bash
# Aider will have access to issues via .aider.conf.yml
aider

# Or manually inject context
bd prime | aider --message-file -
```

### During Work

Use bd commands alongside aider:

```bash
# In another terminal or after exiting aider
bd create "Found bug during work" --deps discovered-from:bd-42 --json
bd update bd-42 --status in_progress
bd ready
```

### End Session

```bash
bd sync
```

## Best Practices

1. **Keep issues visible** - Aider reads `.beads/issues.jsonl`
2. **Sync regularly** - Run `bd sync` after significant changes
3. **Use discovered-from** - Track issues found during work
4. **Document context** - Include descriptions in issues

## Example Workflow

```bash
# 1. Check ready work
bd ready

# 2. Start aider with issue context
aider --message "Working on bd-42: Fix auth bug"

# 3. Work in aider...

# 4. Create discovered issues
bd create "Found related bug" --deps discovered-from:bd-42 --json

# 5. Complete and sync
bd close bd-42 --reason "Fixed"
bd sync
```

## Troubleshooting

### Config not loading

```bash
# Check config exists
cat .aider.conf.yml

# Regenerate
bd setup aider
```

### Issues not visible

```bash
# Check JSONL exists
ls -la .beads/issues.jsonl

# Export if missing
bd export
```

## See Also

- [Claude Code](/integrations/claude-code)
- [IDE Setup](/getting-started/ide-setup)

</document>

<document path="docs/integrations/claude-code.md">


# Claude Code Integration

How to use beads with Claude Code.

## Setup

### Quick Setup

```bash
bd setup claude
```

This installs:
- **SessionStart hook** - Runs `bd prime` on session start
- **PreCompact hook** - Runs `bd sync` before context compaction

### Manual Setup

Add to your Claude Code hooks configuration:

```json
{
  "hooks": {
    "SessionStart": ["bd prime"],
    "PreCompact": ["bd sync"]
  }
}
```

### Verify Setup

```bash
bd setup claude --check
```

## How It Works

1. **Session starts** → `bd prime` injects ~1-2k tokens of context
2. **You work** → Use `bd` CLI commands directly
3. **Session compacts** → `bd sync` saves work to git
4. **Session ends** → Changes synced via git

## Essential Commands for Agents

### Creating Issues

```bash
# Always include description for context
bd create "Fix authentication bug" \
  --description="Login fails with special characters in password" \
  -t bug -p 1 --json

# Link discovered issues
bd create "Found SQL injection" \
  --description="User input not sanitized in query builder" \
  --deps discovered-from:bd-42 --json
```

### Working on Issues

```bash
# Find ready work
bd ready --json

# Start work
bd update bd-42 --status in_progress --json

# Complete work
bd close bd-42 --reason "Fixed in commit abc123" --json
```

### Querying

```bash
# List open issues
bd list --status open --json

# Show issue details
bd show bd-42 --json

# Check blocked issues
bd blocked --json
```

### Syncing

```bash
# ALWAYS run at session end
bd sync
```

## Best Practices

### Always Use `--json`

```bash
bd list --json          # Parse programmatically
bd create "Task" --json # Get issue ID from output
bd show bd-42 --json    # Structured data
```

### Always Include Descriptions

```bash
# Good
bd create "Fix auth bug" \
  --description="Login fails when password contains quotes" \
  -t bug -p 1 --json

# Bad - no context for future work
bd create "Fix auth bug" -t bug -p 1 --json
```

### Link Related Work

```bash
# When you discover issues during work
bd create "Found related bug" \
  --deps discovered-from:bd-current --json
```

### Sync Before Session End

```bash
# ALWAYS run before ending
bd sync
```

## Plugin (Optional)

For enhanced UX with slash commands:

```bash
# In Claude Code
/plugin marketplace add steveyegge/beads
/plugin install beads
# Restart Claude Code
```

Adds slash commands:
- `/beads:ready` - Show ready work
- `/beads:create` - Create issue
- `/beads:show` - Show issue
- `/beads:update` - Update issue
- `/beads:close` - Close issue

## Troubleshooting

### Context not injected

```bash
# Check hook setup
bd setup claude --check

# Manually prime
bd prime
```

### Changes not syncing

```bash
# Force sync
bd sync

# Check daemon
bd info
bd daemons health
```

### Database not found

```bash
# Initialize beads
bd init --quiet
```

## See Also

- [MCP Server](/integrations/mcp-server) - For MCP-only environments
- [IDE Setup](/getting-started/ide-setup) - Other editors

</document>

<document path="docs/integrations/mcp-server.md">


# MCP Server

Use beads in MCP-only environments.

## When to Use MCP

Use MCP server when CLI is unavailable:
- Claude Desktop (no shell access)
- Sourcegraph Amp without shell
- Other MCP-only environments

**Prefer CLI + hooks** when shell is available - it's more context efficient.

## Installation

### Using uv (Recommended)

```bash
uv tool install beads-mcp
```

### Using pip

```bash
pip install beads-mcp
```

## Configuration

### Claude Desktop (macOS)

Add to `~/Library/Application Support/Claude/claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "beads": {
      "command": "beads-mcp"
    }
  }
}
```

### Claude Desktop (Windows)

Add to `%APPDATA%\Claude\claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "beads": {
      "command": "beads-mcp"
    }
  }
}
```

### Sourcegraph Amp

Add to MCP settings:

```json
{
  "beads": {
    "command": "beads-mcp",
    "args": []
  }
}
```

## Available Tools

The MCP server exposes these tools:

| Tool | Description |
|------|-------------|
| `beads_create` | Create new issue |
| `beads_list` | List issues |
| `beads_show` | Show issue details |
| `beads_update` | Update issue |
| `beads_close` | Close issue |
| `beads_ready` | Show ready work |
| `beads_sync` | Sync to git |
| `beads_dep_add` | Add dependency |
| `beads_dep_tree` | Show dependency tree |

## Usage

Once configured, use naturally:

```
Create an issue for fixing the login bug with priority 1
```

The MCP server translates to appropriate `bd` commands.

## Trade-offs

| Aspect | CLI + Hooks | MCP Server |
|--------|-------------|------------|
| Context overhead | ~1-2k tokens | 10-50k tokens |
| Latency | Direct calls | MCP protocol |
| Setup | Hooks config | MCP config |
| Availability | Shell required | MCP environments |

## Troubleshooting

### Server won't start

Check if `beads-mcp` is in PATH:

```bash
which beads-mcp
```

If not found:

```bash
# Reinstall
pip uninstall beads-mcp
pip install beads-mcp
```

### Tools not appearing

1. Restart Claude Desktop
2. Check MCP config JSON syntax
3. Verify server path

### Permission errors

```bash
# Check directory permissions
ls -la .beads/

# Initialize if needed
bd init --quiet
```

## See Also

- [Claude Code](/integrations/claude-code) - CLI integration
- [Installation](/getting-started/installation) - Full install guide

</document>

<document path="docs/recovery/index.md">


# Recovery Overview

This section provides step-by-step recovery procedures for common Beads issues. Each runbook follows a consistent format: Symptoms, Diagnosis, Solution (5 steps max), and Prevention.

## Common Issues

| Issue | Symptoms | Runbook |
|-------|----------|---------|
| Database Corruption | SQLite errors, missing data | [Database Corruption](/recovery/database-corruption) |
| Merge Conflicts | JSONL conflicts during sync | [Merge Conflicts](/recovery/merge-conflicts) |
| Circular Dependencies | Cycle detection errors | [Circular Dependencies](/recovery/circular-dependencies) |
| Sync Failures | `bd sync` errors | [Sync Failures](/recovery/sync-failures) |

## Quick Diagnostic

Before diving into specific runbooks, try these quick checks:

```bash
# Check Beads status
bd status

# Verify daemon is running
bd daemon status

# Check for blocked issues
bd blocked
```

:::tip
Most issues can be diagnosed with `bd status`. Start there before following specific runbooks.
:::

## Getting Help

If these runbooks don't resolve your issue:

1. Check the [FAQ](/reference/faq)
2. Search [existing issues](https://github.com/steveyegge/beads/issues)
3. Open a new issue with diagnostic output

</document>

<document path="docs/recovery/circular-dependencies.md">


# Circular Dependencies Recovery

This runbook helps you detect and break circular dependency cycles in your issues.

## Symptoms

- "circular dependency detected" errors
- `bd blocked` shows unexpected results
- Issues that should be ready appear blocked

## Diagnosis

```bash
# Check for blocked issues
bd blocked

# View dependencies for a specific issue
bd show <issue-id>

# List all dependencies
bd dep tree
```

## Solution

**Step 1:** Identify the cycle
```bash
bd blocked --verbose
```

**Step 2:** Map the dependency chain
```bash
bd show <issue-a>
bd show <issue-b>
# Follow the chain until you return to <issue-a>
```

**Step 3:** Determine which dependency to remove
Consider: Which dependency is least critical to the workflow?

**Step 4:** Remove the problematic dependency
```bash
bd dep remove <dependent-issue> <blocking-issue>
```

**Step 5:** Verify the cycle is broken
```bash
bd blocked
bd ready
```

## Prevention

- Think "X needs Y" not "X before Y" when adding dependencies
- Use `bd blocked` after adding dependencies to check for cycles
- Keep dependency chains shallow when possible

</document>

<document path="docs/recovery/database-corruption.md">


# Database Corruption Recovery

This runbook helps you recover from SQLite database corruption in Beads.

## Symptoms

- SQLite error messages during `bd` commands
- "database is locked" errors that persist
- Missing issues that should exist
- Inconsistent state between JSONL and database

## Diagnosis

```bash
# Check database integrity
bd status

# Look for corruption indicators
ls -la .beads/beads.db*
```

If you see `-wal` or `-shm` files alongside `beads.db`, a transaction may have been interrupted.

## Solution

:::warning
Back up your `.beads/` directory before proceeding.
:::

**Step 1:** Stop the daemon
```bash
bd daemon stop
```

**Step 2:** Back up current state
```bash
cp -r .beads .beads.backup
```

**Step 3:** Rebuild from JSONL (source of truth)
```bash
bd doctor --fix
```

**Step 4:** Verify recovery
```bash
bd status
bd list
```

**Step 5:** Restart daemon
```bash
bd daemon start
```

## Prevention

- Avoid interrupting `bd sync` operations
- Let the daemon handle synchronization
- Use `bd daemon stop` before system shutdown

</document>

<document path="docs/recovery/merge-conflicts.md">


# Merge Conflicts Recovery

This runbook helps you resolve JSONL merge conflicts that occur during Git operations.

## Symptoms

- Git merge conflicts in `.beads/*.jsonl` files
- `bd sync` fails with conflict errors
- Different issue states between clones

## Diagnosis

```bash
# Check for conflicted files
git status

# Look for conflict markers
grep -l "<<<<<<" .beads/*.jsonl
```

## Solution

:::warning
JSONL files are append-only logs. Manual editing requires care.
:::

**Step 1:** Identify conflicted files
```bash
git diff --name-only --diff-filter=U
```

**Step 2:** For each conflicted JSONL file, keep both versions
```bash
# Accept both changes (append-only is safe)
git checkout --ours .beads/issues.jsonl
git add .beads/issues.jsonl
```

**Step 3:** Force rebuild to reconcile
```bash
bd doctor --fix
```

**Step 4:** Verify state
```bash
bd list
bd status
```

**Step 5:** Complete the merge
```bash
git commit -m "Resolved beads merge conflicts"
```

## Prevention

- Sync before and after Git operations
- Use `bd sync` regularly
- Avoid concurrent modifications from multiple clones

</document>

<document path="docs/recovery/sync-failures.md">


# Sync Failures Recovery

This runbook helps you recover from `bd sync` failures.

## Symptoms

- `bd sync` hangs or times out
- Network-related error messages
- "failed to push" or "failed to pull" errors
- Daemon not responding

## Diagnosis

```bash
# Check daemon status
bd daemon status

# Check sync state
bd status

# View daemon logs
cat .beads/daemon.log | tail -50
```

## Solution

**Step 1:** Stop the daemon
```bash
bd daemon stop
```

**Step 2:** Check for lock files
```bash
ls -la .beads/*.lock
# Remove stale locks if daemon is definitely stopped
rm -f .beads/*.lock
```

**Step 3:** Force a fresh sync
```bash
bd doctor --fix
```

**Step 4:** Restart daemon
```bash
bd daemon start
```

**Step 5:** Verify sync works
```bash
bd sync
bd status
```

## Common Causes

| Cause | Solution |
|-------|----------|
| Network timeout | Retry with better connection |
| Stale lock file | Remove lock after stopping daemon |
| Corrupted state | Use `bd doctor --fix` |
| Git conflicts | See [Merge Conflicts](/recovery/merge-conflicts) |

## Prevention

- Ensure stable network before sync
- Let sync complete before closing terminal
- Use `bd daemon stop` before system shutdown

</document>

<document path="docs/reference/advanced.md">


# Advanced Features

Advanced beads functionality.

## Issue Rename

Rename issues while preserving references:

```bash
bd rename bd-42 bd-new-id
bd rename bd-42 bd-new-id --dry-run  # Preview
```

Updates:
- All dependencies pointing to old ID
- All references in other issues
- Comments and descriptions

## Issue Merge

Merge duplicate issues:

```bash
bd merge bd-42 bd-43 --into bd-41
bd merge bd-42 bd-43 --into bd-41 --dry-run
```

What gets merged:
- Dependencies → target
- Text references updated across all issues
- Source issues closed with merge reason

## Database Compaction

Reduce database size by compacting old issues:

```bash
# View compaction statistics
bd admin compact --stats

# Preview candidates (30+ days closed)
bd admin compact --analyze --json

# Apply agent-generated summary
bd admin compact --apply --id bd-42 --summary summary.txt

# Immediate deletion (CAUTION!)
bd admin cleanup --force
```

**When to compact:**
- Database > 10MB with old closed issues
- After major milestones
- Before archiving project phase

## Restore from History

View deleted or compacted issues from git:

```bash
bd restore bd-42 --show
bd restore bd-42 --to-file issue.json
```

## Database Inspection

```bash
# Schema info
bd info --schema --json

# Raw database query (advanced)
sqlite3 .beads/beads.db "SELECT * FROM issues LIMIT 5"
```

## Custom Tables

Extend the database with custom tables:

```go
// In Go code using beads as library
storage.UnderlyingDB().Exec(`
  CREATE TABLE IF NOT EXISTS custom_table (...)
`)
```

See [EXTENDING.md](https://github.com/steveyegge/beads/blob/main/docs/EXTENDING.md).

## Event System

Subscribe to beads events:

```bash
# View recent events
bd events list --since 1h

# Watch events in real-time
bd events watch
```

Events:
- `issue.created`
- `issue.updated`
- `issue.closed`
- `dependency.added`
- `sync.completed`

## Batch Operations

### Create Multiple

```bash
cat issues.jsonl | bd import -i -
```

### Update Multiple

```bash
bd list --status open --priority 4 --json | \
  jq -r '.[].id' | \
  xargs -I {} bd update {} --priority 3
```

### Close Multiple

```bash
bd list --label "sprint-1" --status open --json | \
  jq -r '.[].id' | \
  xargs -I {} bd close {} --reason "Sprint complete"
```

## API Access

Use beads as a Go library:

```go
import "github.com/steveyegge/beads/internal/storage"

db, _ := storage.NewSQLite(".beads/beads.db")
issues, _ := db.ListIssues(storage.ListOptions{
    Status: "open",
})
```

## Performance Tuning

### Large Databases

```bash
# Enable WAL mode
bd config set database.wal_mode true

# Increase cache
bd config set database.cache_size 10000
```

### Many Concurrent Agents

```bash
# Use event-driven daemon
export BEADS_DAEMON_MODE=events
bd daemons killall
```

### CI/CD Optimization

```bash
# Disable daemon in CI
export BEADS_NO_DAEMON=true
bd --no-daemon list
```

</document>

<document path="docs/reference/configuration.md">


# Configuration

Complete configuration reference for beads.

## Configuration Locations

1. **Project config**: `.beads/config.toml` (highest priority)
2. **User config**: `~/.beads/config.toml`
3. **Environment variables**: `BEADS_*`
4. **Command-line flags**: (highest priority)

## Managing Configuration

```bash
# Get config value
bd config get import.orphan_handling

# Set config value
bd config set import.orphan_handling allow

# List all config
bd config list

# Reset to default
bd config reset import.orphan_handling
```

## Configuration Options

### Database

```toml
[database]
path = ".beads/beads.db"     # Database file location
```

### ID Generation

```toml
[id]
prefix = "bd"                 # Issue ID prefix
hash_length = 4               # Hash length in IDs
```

### Import

```toml
[import]
orphan_handling = "allow"     # allow|resurrect|skip|strict
dedupe_on_import = false      # Run duplicate detection after import
```

| Mode | Behavior |
|------|----------|
| `allow` | Import orphans without validation (default) |
| `resurrect` | Restore deleted parents as tombstones |
| `skip` | Skip orphaned children with warning |
| `strict` | Fail if parent missing |

### Export

```toml
[export]
path = ".beads/issues.jsonl"  # Export file location
auto_export = true            # Auto-export on changes
debounce_seconds = 5          # Debounce interval
```

### Daemon

```toml
[daemon]
auto_start = true             # Auto-start daemon
sync_interval = "5s"          # Sync check interval
log_level = "info"            # debug|info|warn|error
mode = "poll"                 # poll|events (experimental)
```

### Git

```toml
[git]
auto_commit = true            # Auto-commit on sync
auto_push = true              # Auto-push on sync
commit_message = "bd sync"    # Default commit message
```

### Hooks

```toml
[hooks]
pre_commit = true             # Enable pre-commit hook
post_merge = true             # Enable post-merge hook
pre_push = true               # Enable pre-push hook
```

### Deletions

```toml
[deletions]
retention_days = 30           # Keep deletion records for N days
prune_on_sync = true          # Auto-prune old records
```

## Environment Variables

| Variable | Description |
|----------|-------------|
| `BEADS_DB` | Database path |
| `BEADS_NO_DAEMON` | Disable daemon |
| `BEADS_DAEMON_MODE` | Daemon mode (poll/events) |
| `BEADS_LOG_LEVEL` | Log level |
| `BEADS_CONFIG` | Config file path |

## Per-Command Override

```bash
# Override database
bd --db /tmp/test.db list

# Disable daemon for single command
bd --no-daemon create "Task"
```

## Example Configuration

`.beads/config.toml`:

```toml
[id]
prefix = "myproject"
hash_length = 6

[import]
orphan_handling = "resurrect"
dedupe_on_import = true

[daemon]
auto_start = true
sync_interval = "10s"
mode = "events"

[git]
auto_commit = true
auto_push = true

[deletions]
retention_days = 90
```

## Viewing Active Configuration

```bash
bd info --json | jq '.config'
```

</document>

<document path="docs/reference/faq.md">


# Frequently Asked Questions

## General

### Why beads instead of GitHub Issues or Jira?

Beads was designed specifically for AI-supervised coding workflows:
- **Hash-based IDs** prevent collisions with concurrent agents
- **Git-backed storage** enables branch-based workflows
- **Dependency-aware** ready queue for automated work selection
- **Formula system** for declarative workflow templates

### What does "beads" stand for?

Nothing specific - it's a metaphor for linked work items (like beads on a string).

### Is beads production-ready?

Yes, beads is used in production for AI-assisted development. The API is stable with semantic versioning.

## Architecture

### Why SQLite + JSONL instead of just one?

- **SQLite** for fast local queries and complex filtering
- **JSONL** for git-friendly versioning and sync
- Auto-sync keeps them aligned

### Why hash-based IDs instead of sequential?

Sequential IDs (`#1`, `#2`) break when:
- Multiple agents create issues simultaneously
- Different branches have independent numbering
- Forks diverge and merge

Hash-based IDs are globally unique without coordination.

### Why a daemon?

The daemon provides:
- Auto-sync with 5-second debounce
- Batched operations for performance
- Background monitoring

Use `--no-daemon` when not needed (CI, worktrees).

## Usage

### How do I sync issues to git?

```bash
# Auto-sync via daemon (default)
# Or manual sync:
bd sync
```

### How do I handle merge conflicts?

Install the beads merge driver:
```bash
bd init  # Prompts for merge driver
```

Or manually resolve and reimport.

### Can multiple agents work on the same repo?

Yes! That's what beads was designed for:
- Hash IDs prevent collisions
- Pin work to specific agents
- Track who's working on what

### How do I use beads in CI/CD?

```bash
# Disable daemon in CI
export BEADS_NO_DAEMON=true

# Or per-command
bd --no-daemon list
```

## Workflows

### What are formulas?

Declarative workflow templates in TOML or JSON. Pour them to create molecules (instances).

### What are gates?

Async coordination primitives:
- Human gates wait for approval
- Timer gates wait for duration
- GitHub gates wait for CI/PR events

### What's the difference between molecules and wisps?

- **Molecules** persist in `.beads/` and sync with git
- **Wisps** are ephemeral in `.beads-wisp/` and don't sync

## Integration

### Should I use CLI or MCP?

**Use CLI + hooks** when shell is available (Claude Code, Cursor, etc.):
- Lower context overhead (~1-2k vs 10-50k tokens)
- Faster execution
- Universal across editors

**Use MCP** when CLI unavailable (Claude Desktop).

### How do I integrate with my editor?

```bash
bd setup claude   # Claude Code
bd setup cursor   # Cursor
bd setup aider    # Aider
```

### Can beads import from GitHub Issues?

Yes:
```bash
bd import --from github --repo owner/repo
```

## Troubleshooting

### Why is the daemon not starting?

```bash
# Remove stale socket
rm -f .beads/bd.sock

# Restart
bd daemons killall
bd info
```

### Why aren't my changes syncing?

```bash
# Check daemon status
bd info

# Force sync
bd sync

# Check hooks
bd hooks status
```

### How do I report a bug?

1. Check existing issues: https://github.com/steveyegge/beads/issues
2. Include: `bd version`, `bd info --json`, reproduction steps
3. File at: https://github.com/steveyegge/beads/issues/new

</document>

<document path="docs/reference/git-integration.md">


# Git Integration

How beads integrates with git.

## Overview

Beads uses git for:
- **JSONL sync** - Issues stored in `.beads/issues.jsonl`
- **Deletion tracking** - `.beads/deletions.jsonl`
- **Conflict resolution** - Custom merge driver
- **Hooks** - Auto-sync on git operations

## File Structure

```
.beads/
├── beads.db           # SQLite database (gitignored)
├── issues.jsonl       # Issue data (git-tracked)
├── deletions.jsonl    # Deletion manifest (git-tracked)
├── config.toml        # Project config (git-tracked)
└── bd.sock            # Daemon socket (gitignored)
```

## Git Hooks

### Installation

```bash
bd hooks install
```

Installs:
- **pre-commit** - Exports database to JSONL
- **post-merge** - Imports from JSONL after pull
- **pre-push** - Ensures sync before push

### Status

```bash
bd hooks status
```

### Uninstall

```bash
bd hooks uninstall
```

## Merge Driver

### Purpose

The beads merge driver handles JSONL conflicts automatically:
- Merges non-conflicting changes
- Uses latest timestamp for same-issue edits
- Preserves both sides for real conflicts

### Installation

```bash
bd init  # Prompts for merge driver setup
```

Or manually add to `.gitattributes`:

```gitattributes
.beads/issues.jsonl merge=beads
.beads/deletions.jsonl merge=beads
```

And `.git/config`:

```ini
[merge "beads"]
    name = Beads JSONL merge driver
    driver = bd merge-driver %O %A %B
```

## Protected Branches

For protected main branches:

```bash
bd init --branch beads-sync
```

This:
- Creates a separate `beads-sync` branch
- Syncs issues to that branch
- Avoids direct commits to main

## Git Worktrees

Beads requires `--no-daemon` in git worktrees:

```bash
# In worktree
bd --no-daemon create "Task"
bd --no-daemon list
```

Why: Daemon uses `.beads/bd.sock` which conflicts across worktrees.

## Branch Workflows

### Feature Branch

```bash
git checkout -b feature-x
bd create "Feature X" -t feature
# Work...
bd sync
git push
```

### Fork Workflow

```bash
# In fork
bd init --contributor
# Work in separate planning repo...
bd sync
```

### Team Workflow

```bash
bd init --team
# All team members share issues.jsonl
git pull  # Auto-imports via hook
```

## Conflict Resolution

### With Merge Driver

Automatic - driver handles most conflicts.

### Manual Resolution

```bash
# After conflict
git checkout --ours .beads/issues.jsonl
bd import -i .beads/issues.jsonl
bd sync
git add .beads/
git commit
```

### Duplicate Detection

After merge:

```bash
bd duplicates --auto-merge
```

## Best Practices

1. **Install hooks** - `bd hooks install`
2. **Use merge driver** - Avoid manual conflict resolution
3. **Sync regularly** - `bd sync` at session end
4. **Pull before work** - Get latest issues
5. **Use `--no-daemon` in worktrees**

</document>

<document path="docs/reference/troubleshooting.md">


# Troubleshooting

Common issues and solutions.

## Installation Issues

### `bd: command not found`

```bash
# Check if installed
which bd
go list -f {{.Target}} github.com/steveyegge/beads/cmd/bd

# Add Go bin to PATH
export PATH="$PATH:$(go env GOPATH)/bin"

# Or reinstall
go install github.com/steveyegge/beads/cmd/bd@latest
```

### `zsh: killed bd` on macOS

CGO/SQLite compatibility issue:

```bash
CGO_ENABLED=1 go install github.com/steveyegge/beads/cmd/bd@latest
```

### Permission denied

```bash
chmod +x $(which bd)
```

## Database Issues

### Database not found

```bash
# Initialize beads
bd init --quiet

# Or specify database
bd --db .beads/beads.db list
```

### Database locked

```bash
# Stop daemon
bd daemons killall

# Try again
bd list
```

### Corrupted database

```bash
# Restore from JSONL
rm .beads/beads.db
bd import -i .beads/issues.jsonl
```

## Daemon Issues

### Daemon not starting

```bash
# Check status
bd info

# Remove stale socket
rm -f .beads/bd.sock

# Restart
bd daemons killall
bd info
```

### Version mismatch

After upgrading bd:

```bash
bd daemons killall
bd info
```

### High CPU usage

```bash
# Switch to event-driven mode
export BEADS_DAEMON_MODE=events
bd daemons killall
```

## Sync Issues

### Changes not syncing

```bash
# Force sync
bd sync

# Check daemon
bd info | grep daemon

# Check hooks
bd hooks status
```

### Import errors

```bash
# Allow orphans
bd import -i .beads/issues.jsonl --orphan-handling allow

# Check for duplicates after
bd duplicates
```

### Merge conflicts

```bash
# Use merge driver
bd init  # Setup merge driver

# Or manual resolution
git checkout --ours .beads/issues.jsonl
bd import -i .beads/issues.jsonl
bd sync
```

## Git Hook Issues

### Hooks not running

```bash
# Check if installed
ls -la .git/hooks/

# Reinstall
bd hooks install
```

### Hook errors

```bash
# Check hook script
cat .git/hooks/pre-commit

# Run manually
.git/hooks/pre-commit
```

## Dependency Issues

### Circular dependencies

```bash
# Detect cycles
bd dep cycles

# Remove one dependency
bd dep remove bd-A bd-B
```

### Missing dependencies

```bash
# Check orphan handling
bd config get import.orphan_handling

# Allow orphans
bd config set import.orphan_handling allow
```

## Performance Issues

### Slow queries

```bash
# Check database size
ls -lh .beads/beads.db

# Compact if large
bd admin compact --analyze
```

### High memory usage

```bash
# Reduce cache
bd config set database.cache_size 1000
```

## Getting Help

### Debug output

```bash
bd --verbose list
```

### Logs

```bash
bd daemons logs . -n 100
```

### System info

```bash
bd info --json
```

### File an issue

```bash
# Include this info
bd version
bd info --json
uname -a
```

Report at: https://github.com/steveyegge/beads/issues

</document>

---

# End of Documentation

For updates and contributions, visit: https://github.com/steveyegge/beads
