# Beads Documentation (Complete)

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

---

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


# Beads Documentation

**Beads** (`bd`) is a Dolt-powered 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
- **Dolt-backed storage** - Issues stored in a version-controlled SQL database, enabling collaboration via Dolt-native replication
- **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 install beads

# Or quick install (macOS/Linux/FreeBSD)
curl -fsSL https://raw.githubusercontent.com/gastownhall/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` |
| **Dolt Server** | Database server for multi-writer access 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

# Push changes at end of session
bd dolt push
```

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

## Architecture

```
Dolt DB (.beads/dolt/, gitignored)
    ↕ dolt commit
Local Dolt history
    ↕ dolt push/pull
Remote Dolt repository (shared across machines)
```

The magic is automatic synchronization via Dolt's version-controlled database with built-in replication.

## 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
- **SessionStart compact refresh** - Runs `bd prime` after 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 refresh exports and legacy fallbacks; Dolt remotes handle sync

**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"],
    "SessionStart": ["bd prime"]
  }
}
```

## 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
```

## GitHub Copilot

For VS Code with GitHub Copilot, use the MCP server:

```bash
# Install MCP server
uv tool install beads-mcp
```

Create `.vscode/mcp.json` in your project:

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

**For all projects:** Add to VS Code user-level MCP config:

| Platform | Path |
|----------|------|
| macOS | `~/Library/Application Support/Code/User/mcp.json` |
| Linux | `~/.config/Code/User/mcp.json` |
| Windows | `%APPDATA%\Code\User\mcp.json` |

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

Initialize beads and reload VS Code:

```bash
bd init --quiet
```

See [GitHub Copilot Integration](/integrations/github-copilot) for detailed setup.

## 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
- Persistent memories from `bd remember`

`bd prime` prints memories near the top and starts with a truncation warning. If your host stores the full hook output in a file and only shows a preview, have the agent read the full file before continuing.

For memory-only hooks:

```bash
bd prime --memories-only
```

**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 export refresh and legacy fallback behavior:

```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 project health
bd doctor

# 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

<!-- This website install page and the GitHub-rendered docs/INSTALLING.md are
     deliberate parallel docs for different audiences. When you change platform
     commands or install methods here, update docs/INSTALLING.md too so they do
     not drift. -->

Complete installation guide for all platforms.

## Quick Install (Recommended)

### Homebrew (macOS/Linux)

```bash
brew install beads
```

Homebrew core's `beads` formula is the supported Homebrew package. If you
previously installed the old tap formula as `bd`, see
[Migrating from the old Homebrew tap](/getting-started/upgrading#homebrew) to
switch to the core formula.

**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/gastownhall/beads/main/scripts/install.sh | bash
```

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

## Go Install and Build Dependencies

Use Homebrew, npm, or the install script if you do not specifically need `go install`.

`go install` has two supported modes:

- **Server-mode only:** `CGO_ENABLED=0 go install github.com/steveyegge/beads/cmd/bd@latest`
- **Embedded-capable:** `CGO_ENABLED=1 GOFLAGS=-tags=gms_pure_go go install github.com/steveyegge/beads/cmd/bd@latest`

ICU headers are not required. The embedded-capable command uses `gms_pure_go` so go-mysql-server uses Go's stdlib regexp instead of ICU.

Use the `github.com/steveyegge/beads` path for `go install`. The repository now lives under `gastownhall/beads`, but released Go modules still declare `github.com/steveyegge/beads` for compatibility.

## Platform-Specific Installation

### macOS

**Via Homebrew** (recommended):
```bash
brew install beads
```

**Via go install** (server-mode only):
```bash
CGO_ENABLED=0 go install github.com/steveyegge/beads/cmd/bd@latest
```

**Via go install** (embedded-capable):
```bash
CGO_ENABLED=1 GOFLAGS=-tags=gms_pure_go go install github.com/steveyegge/beads/cmd/bd@latest
```

**From source**:
```bash
git clone https://github.com/gastownhall/beads
cd beads
make build
sudo mv bd /usr/local/bin/
```

### Linux

**Via Homebrew** (works on Linux too):
```bash
brew install beads
```

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

**Via go install** (server-mode only):
```bash
CGO_ENABLED=0 go install github.com/steveyegge/beads/cmd/bd@latest
```

**Via go install** (embedded-capable):
```bash
CGO_ENABLED=1 GOFLAGS=-tags=gms_pure_go go install github.com/steveyegge/beads/cmd/bd@latest
```

### FreeBSD

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

**Via go install** (server-mode only):
```bash
CGO_ENABLED=0 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/gastownhall/beads/main/install.ps1 | iex
```

The script installs a prebuilt Windows release if available. Go is only required for `go install` or building from source.

**Via go install** (server-mode only):
```pwsh
$env:CGO_ENABLED="0"; go install github.com/steveyegge/beads/cmd/bd@latest
```

**Via go install** (embedded-capable):
```pwsh
$env:CGO_ENABLED="1"; $env:GOFLAGS="-tags=gms_pure_go"; 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 beads

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

# 3. Setup editor integration (choose one)
bd setup claude   # Claude Code - installs SessionStart hooks
bd setup cursor   # Cursor IDE - creates .cursor/rules/beads.mdc
bd setup aider    # Aider - creates .aider.conf.yml
bd setup codex    # Codex CLI - installs Beads skill, AGENTS.md guidance, and native hooks
bd setup factory  # Factory.ai Droid - creates/updates AGENTS.md
bd setup mux      # Mux - creates/updates AGENTS.md
```

**How it works:**
- `bd init` creates or updates `AGENTS.md` and installs project Claude/Codex integrations by default unless you use `--skip-agents` or `--stealth`
- Editor hooks/rules inject `bd prime` automatically on session start
- Codex 0.129.0+ uses native `/hooks` for startup and compaction-aware context refresh
- `bd prime` provides ~1-2k tokens of workflow context
- You use `bd` CLI commands directly
- Git hooks (installed by `bd init`) refresh exports and legacy fallbacks; `bd dolt push/pull` syncs the database
- `bd onboard` prints the small manual snippet for unsupported agents or custom instruction files

**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"

# Or reinstall with the recommended installer
curl -fsSL https://raw.githubusercontent.com/gastownhall/beads/main/scripts/install.sh | bash
```

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

This is typically caused by CGO/SQLite compatibility issues:

```bash
# Install an embedded-capable build
CGO_ENABLED=1 GOFLAGS=-tags=gms_pure_go go install github.com/steveyegge/beads/cmd/bd@latest
```

## Updating bd

### Quick install script (macOS/Linux/FreeBSD)

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

### PowerShell installer (Windows)

```pwsh
irm https://raw.githubusercontent.com/gastownhall/beads/main/install.ps1 | iex
```

### Homebrew

```bash
brew upgrade beads
```

### go install

```bash
# Server-mode only
CGO_ENABLED=0 go install github.com/steveyegge/beads/cmd/bd@latest

# Embedded-capable
CGO_ENABLED=1 GOFLAGS=-tags=gms_pure_go go install github.com/steveyegge/beads/cmd/bd@latest
```

For post-upgrade steps (hooks, migrations), see [Upgrading](/getting-started/upgrading).

## 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), or run `bd setup --list`

</document>

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


# Beads Quick Start

Get up and running with Beads in a few minutes.

## Why Beads?

Flat issue trackers (GitHub Issues, Jira, etc.) show you a list of open items. You pick one. But if that item depends on something else that isn't done yet, you've wasted time. Multiply this across a team of AI agents and humans, and you get thrashing.

Beads tracks **dependencies between issues** and computes a **ready queue** — only items with no active blockers appear. Here's the difference:

**Flat tracker (GitHub Issues):**
```
Open issues: Set up database, Create API, Add authentication
→ An agent picks "Add authentication" and gets stuck immediately
```

**Beads:**
```bash
$ bd ready
1. [P1] [task] bd-1: Set up database

$ bd ready --explain --json | jq '.blocked[0]'
{
  "id": "bd-3",
  "title": "Add authentication",
  "blocked_by": [{"id": "bd-2", "title": "Create API", "status": "open"}]
}
```

The agent picks the right task every time. No wasted cycles.

## Installation

Install `bd` using [the full installation guide](/getting-started/installation) (Homebrew, install script, npm, or `go install`).

**Developing in a clone of this repository:** use `make install` so the binary gets correct build metadata and a consistent install path. Avoid ad-hoc `go build` / `go install` without the Makefile unless you know what you are doing — see the repository `README` and `AGENTS.md`.

```bash
bd --help
```

## Initialize

First time in a repository:

```bash
# Basic setup (prompts for contributor mode)
bd init

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

# OSS contributor (fork workflow with separate planning repo)
bd init --contributor

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

# Protected main branch (GitHub/GitLab)
# Note: Dolt stores data under refs/dolt/data, separate from
# Git refs, so no --branch flag is needed.
```

The wizard will:
- Create `.beads/` directory and embedded Dolt database
- **Prompt for your role** (maintainer or contributor) unless a flag is provided
- Import existing issues from git (if any)
- Prompt to install git hooks (recommended)
- Prompt to configure git merge driver (recommended)

Notes:
- Dolt is the default (and only) storage backend. Data is stored in `.beads/embeddeddolt/`.
- By default, Dolt runs in **embedded mode** (in-process, no server needed).
- For multi-writer setups, use `bd init --server` to connect to a `dolt sql-server` instead.
- To import issues from an older installation, run `bd init --from-jsonl`.

### Role configuration

During `bd init`, you'll be asked: "Contributing to someone else's repo? [y/N]"

- Answer **Y** if you're contributing to a fork (runs contributor wizard)
- Answer **N** if you're the maintainer or have push access

This sets `git config beads.role` which determines how beads routes issues:

| Role | Use case | Issue storage |
|------|----------|---------------|
| `maintainer` | Repo owner, team with push access | In-repo `.beads/` |
| `contributor` | Fork contributor, OSS contributor | Separate planning repo |

You can also configure manually:

```bash
# Set as contributor
git config beads.role contributor

# Set as maintainer
git config beads.role maintainer

# Check current role
git config --get beads.role
```

**Note:** If `beads.role` is not configured, beads falls back to URL-based detection (deprecated). Run `bd doctor` to check configuration status.

## 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 (use --parent to attach to the epic)
bd create "Design login UI" -p 1 --parent bd-a3f8e9       # bd-a3f8e9.1
bd create "Backend validation" -p 1 --parent bd-a3f8e9    # bd-a3f8e9.2
bd create "Integration tests" -p 1 --parent bd-a3f8e9     # 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)
```

**Dependency visibility:** `bd list` shows blocking dependencies inline:
```
○ bd-a1b2 [P1] [task] - Set up database
○ bd-f14c [P2] [feature] - Create API (blocked by: bd-a1b2)
○ bd-g25d [P2] [feature] - Add authentication (blocked by: bd-f14c)
```

## 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.

**Understanding why:** Use `--explain` to see the full graph reasoning:

```bash
bd ready --explain
```

Output:
```
Ready Work Explanation

● Ready (1 issues):

  bd-1 [P1] Set up database
    Reason: no blocking dependencies
    Unblocks: 1 issue(s)

● Blocked (2 issues):

  bd-2 [P2] Create API
    ← blocked by bd-1: Set up database [open]

  bd-3 [P2] Add authentication
    ← blocked by bd-2: Create API [open]

─ Summary: 1 ready, 2 blocked
```

**Note:** `bd ready` is not the same as `bd list --status open`. The `list` command shows all open issues regardless of blockers. The `ready` command computes the dependency graph and only shows truly unblocked work.

## Work the queue

```bash
# Start working on bd-1
bd update bd-1 --claim

# 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
```

## Team sync

Share issues with your team using Dolt remotes. Dolt stores data under `refs/dolt/data` on the same Git remote, separate from standard Git refs. In repos with `origin`, `bd init` configures that Dolt remote automatically.

```bash
# Verify the remote, or add one if the repo had no origin during init
bd dolt remote list
bd dolt remote add origin git+ssh://git@github.com/org/repo.git  # if needed

# Push your issues
bd dolt push

# Pull teammates' changes
bd dolt pull
```

When a teammate clones the repo, `bd bootstrap` auto-detects the existing database on `refs/dolt/data`, clones it, and wires `origin` for future `bd dolt push` / `bd dolt pull`.

See [`bd dolt`](/cli-reference/dolt) for CLI details. For remote configuration and federation, see the repository docs [DOLT.md](https://github.com/gastownhall/beads/blob/main/docs/DOLT.md) and [FEDERATION-SETUP.md](https://github.com/gastownhall/beads/blob/main/FEDERATION-SETUP.md).

## Optional: Notion sync

If you keep project issues in Notion, save an integration token first:

```bash
bd config set notion.token <your-token>
```

Then either create a new Beads database under a parent page or connect to an existing target:

```bash
bd notion init --parent <page-id>
# or
bd notion connect --url <notion-database-or-data-source-url>
```

The same auth value can also come from `NOTION_TOKEN`. Directly setting `notion.data_source_id` remains available as an escape hatch for advanced setups.

Check which auth source is active and whether the target schema is ready:

```bash
bd notion status
bd notion status --json
```

Preview or run sync:

```bash
bd notion sync --dry-run
bd notion sync
bd notion sync --pull
bd notion sync --push
```

## Database location

By default (embedded mode), data is stored in `.beads/embeddeddolt/` within your repository.
In server mode, data is managed by the external `dolt sql-server`.

## Migrating databases

After upgrading bd, use `bd migrate` to check for and migrate old database files:

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

# Check schema and config
bd info --schema --json

# Preview migration changes
bd migrate --dry-run

# Migrate old databases to beads.db
bd migrate

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

**AI agents:** Use `--inspect` to analyze migration safety before running. The system verifies required config keys and data integrity invariants.

## Database maintenance

As your project accumulates closed issues, the database grows. Manage size with these commands:

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

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

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

# Immediately delete closed issues (CAUTION: permanent!)
bd admin cleanup --force
```

**When to compact:**
- Database file > 10MB with many old closed issues
- After major project milestones when old issues are no longer relevant
- Before archiving a project phase

**Note:** Compaction is permanent graceful decay. Original content is discarded but viewable via `bd restore <id>` from git history.

## Next steps

- Add labels: `bd create "Task" -l "backend,urgent"`
- Filter ready work: `bd ready --priority 1`
- Explain the graph: `bd ready --explain`
- Check graph integrity: `bd graph check`
- Search issues: `bd list --status open`
- Detect cycles: `bd dep cycles`
- Gates for PR/CI sync: [`bd gate`](/cli-reference/gate)
- More sync scenarios: [`bd dolt`](/cli-reference/dolt)
- Full command list: [CLI Reference](/cli-reference)

See the [repository README](https://github.com/gastownhall/beads/blob/main/README.md) for an overview and links to deeper docs.

</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

Use the command that matches your install method.

| Install method | Platforms | Command |
|---|---|---|
| Quick install script | macOS, Linux, FreeBSD | `curl -fsSL https://raw.githubusercontent.com/gastownhall/beads/main/scripts/install.sh \| bash` |
| PowerShell installer | Windows | `irm https://raw.githubusercontent.com/gastownhall/beads/main/install.ps1 \| iex` |
| Homebrew | macOS, Linux | `brew upgrade beads` |
| go install (server-mode only) | macOS, Linux, FreeBSD, Windows | `CGO_ENABLED=0 go install github.com/steveyegge/beads/cmd/bd@latest` |
| go install (embedded-capable) | macOS, Linux, Windows | `CGO_ENABLED=1 GOFLAGS=-tags=gms_pure_go go install github.com/steveyegge/beads/cmd/bd@latest` |
| npm | macOS, Linux, Windows | `npm update -g @beads/bd` |
| bun | macOS, Linux, Windows | `bun install -g --trust @beads/bd` |
| From source (Unix shell) | macOS, Linux, FreeBSD | `git pull && make build` |

### Quick install script (macOS/Linux/FreeBSD)

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

### PowerShell installer (Windows)

```pwsh
irm https://raw.githubusercontent.com/gastownhall/beads/main/install.ps1 | iex
```

### Homebrew

```bash
brew upgrade beads
```

<!-- Canonical Homebrew tap-migration snippet. The installation page links
     here; docs/INSTALLING.md mirrors this block. Keep all three in sync. -->
If you still have the old tap formula installed as `bd`, switch to the
Homebrew core formula:

```bash
brew uninstall bd
brew untap gastownhall/beads 2>/dev/null || true
brew untap steveyegge/beads 2>/dev/null || true
brew install beads
```

### go install

```bash
# Server-mode only
CGO_ENABLED=0 go install github.com/steveyegge/beads/cmd/bd@latest

# Embedded-capable
CGO_ENABLED=1 GOFLAGS=-tags=gms_pure_go go install github.com/steveyegge/beads/cmd/bd@latest
```

### From Source

```bash
cd beads
git pull
make build
sudo mv bd /usr/local/bin/
```

## After Upgrading

**Important:** After upgrading, update your hooks:

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

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

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

# 4. If using Dolt backend, restart the server
bd dolt stop && bd dolt start
```

**Why update hooks?** Git hooks are versioned with bd. Outdated hooks may miss export refresh, legacy fallback, or safety 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
```

### Remote-backed databases and multiple clones

`bd` refuses to silently apply pending schema migrations to a database that has
a Dolt remote configured. Migrating more than one clone of a shared remote
independently forks the schema, after which `bd dolt pull` can no longer merge —
the break is silent and, across a primary-key-reshaping migration, unrecoverable
([#4259](https://github.com/gastownhall/beads/issues/4259)). The supported flow
is: one machine migrates and publishes; every other clone re-clones the migrated
database.

This applies to **every** upgrade that crosses a pending migration on a
remote-backed database — the same procedure whether you are moving to a
prerelease or to a stable release.

The gate is **state-aware by default**
([#4516](https://github.com/gastownhall/beads/issues/4516)): before blocking,
`bd` consults the remote's *cached* schema state and

- **auto-migrates** when the remote is at the same schema version as this
  clone — no one has migrated yet, so this clone is a safe first-mover
  (concurrent first-movers converge to identical tables). It reminds you to
  `bd dolt push` afterwards.
- **stops and directs you to adopt** (`bd bootstrap`) when the remote has
  already been migrated by another clone.
- **stops for a human decision** when this clone and the remote applied
  different content for the same migration (a genuine fork), or when the
  remote's schema state cannot be read from the cached ref.

Set `BD_SMART_GATE=0` to opt out and make the gate block unconditionally.
The recipes below are the explicit path and work the same in either mode.

**Important ordering:** once the new binary is installed, a database with
pending migrations is gated on **every** open — `bd dolt push` and `bd dolt
pull` are refused too, not just `bd migrate`. So do all syncing with your
**current** binary, *before* you install the new one.

**Back up before you migrate.** Schema migrations assume the database matches
the shape the previous migrations left behind; real databases sometimes drift
(interrupted writes, tooling bugs, very old bootstraps). A JSONL export is
cheap, issue-complete, and importable by any bd version:

```bash
bd export --all -o .beads/backup/pre-migrate-$(date +%Y%m%d).jsonl
```

`bd export` captures issues, not Dolt history or config — for a full snapshot
also copy the `.beads` directory (or `dolt backup` in server mode) while no
`bd` command is running.

**Single clone (including a solo user with a remote):**

```bash
bd dolt push                              # 1. CURRENT binary: publish all local work
bd export --all -o .beads/backup/pre-migrate.jsonl   # 2. backup (see above)
# 3. install the new binary (see Upgrading above)
BD_ALLOW_REMOTE_MIGRATE=1 bd migrate      # 4. migrate as the designated migrator
bd dolt push                              # 5. publish the migrated schema
bd version                                # 6. confirm the new version is active
```

**Multiple clones sharing one remote:**

```bash
# 1. With your CURRENT (old) binary, on EVERY clone: publish all work and get in
#    sync, then stop editing until the upgrade is done.
bd dolt push
bd dolt pull

# 2. Designated migrator ONLY: back up, install the new binary, then migrate
#    and publish.
bd export --all -o .beads/backup/pre-migrate.jsonl
BD_ALLOW_REMOTE_MIGRATE=1 bd migrate
bd dolt push

# 3. Every OTHER clone: install the new binary, then ADOPT the migrated database.
#    (bd dolt pull is refused here — the clone still has pending migrations — so
#    re-clone instead. Safe because step 1 already pushed all work.)
bd bootstrap
```

`bd bootstrap` replaces the local database, so any work not pushed in step 1 is
lost — that is why step 1 publishes everything first. If a clone was instead
migrated independently and `bd dolt pull` later fails with `cannot merge because
table dependencies has different primary keys in its common ancestor`, the
schema has already forked — follow the recovery playbook:
[RECOVERY.md#pk-fork-refused](https://github.com/gastownhall/beads/blob/main/docs/RECOVERY.md#pk-fork-refused).

:::note
In **server mode**, `bd doctor` adds a migration-content-skew check that flags a
forked schema against the cached remote ref — a useful post-upgrade
verification. It is not available in embedded mode; there, confirm the upgrade
with `bd version` and a normal read such as `bd ready`.
:::

## Cross-era Upgrades

If you're upgrading from a much older version of bd, your project may use a different storage backend. bd has gone through several storage eras:

| Era | Versions | Storage | 
|---|---|---|
| SQLite | v0.30–v0.50 | `.beads/beads.db` |
| Dolt server | v0.50–v0.58 | `.beads/dolt/` (external server) |
| Embedded Dolt (old) | v0.59–v0.63.2 | `.beads/dolt/` (in-process) |
| Embedded Dolt (current) | v0.63.3+ | `.beads/embeddeddolt/` |

### From v0.63.3+ (current era)

Upgrade the binary and run:

```bash
bd migrate
```

If the project was initialized before `bd init` automatically wired git origin
as the Dolt remote, verify the remote after upgrading:

```bash
bd dolt remote list
```

When the list is empty, fix it on the machine whose local database is
authoritative:

```bash
bd export -o .beads/issues.pre-remote.jsonl   # optional issue audit export
bd dolt remote add origin git+ssh://git@github.com/org/repo.git
bd dolt push
```

Commit the resulting `.beads/config.yaml` change so other clones can run
`bd bootstrap` or `bd dolt pull`.

### From v0.59–v0.63.2 (old embedded)

Direct upgrade works automatically:

```bash
# Just use the new binary — it handles the conversion
bd list
```

### From v0.50–v0.58 (Dolt server era)

The old binary used an external Dolt SQL server. The new binary uses an embedded engine.

```bash
# 1. Export your data while the old binary still works
bd list --json -n 0 --all > .beads/issues.jsonl

# 2. Stop the Dolt server
dolt sql-server --stop  # or kill the process

# 3. Remove stale server metadata and old storage directories
rm -f .beads/metadata.json .beads/config.json
rm -rf .beads/dolt .beads/embeddeddolt

# 4. Initialize with the new binary
bd init --from-jsonl --quiet

# 5. Verify
bd list --all
```

### From v0.30–v0.50 (SQLite era)

The old binary stored data in SQLite. The new binary uses Dolt.

**Recommended: use the migration script** (requires `sqlite3` and `jq`):

```bash
# Download the script from the beads repo
curl -fsSLO https://raw.githubusercontent.com/gastownhall/beads/main/scripts/migrate-sqlite-to-current.sh
chmod +x migrate-sqlite-to-current.sh

# Run it in your project directory
./migrate-sqlite-to-current.sh
```

The script exports issues, dependencies, and labels from SQLite, handles type normalization, and imports everything into the new Dolt backend.

**Alternative: manual export with the old binary.** Old binaries are always available on [GitHub Releases](https://github.com/gastownhall/beads/releases). Download the version that matches your project, then:

```bash
# 1. Export with the old binary
./bd-old list --json -n 0 --all > .beads/issues.jsonl

# 2. Import with the current binary
bd init --from-jsonl --quiet

# 3. Verify
bd list --all
```

> **Note:** The manual export preserves issue content but not dependencies or labels. Use the migration script for a more complete transfer.

## Troubleshooting Upgrades

### Hooks out of date

```bash
bd hooks install
```

### Database schema changed

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

### Recovery after upgrade

If you need to restore from a backup:

```bash
bd init
bd backup restore [path] --force
```

Or pull from a Dolt remote:

```bash
bd dolt pull
```

</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. **Dolt as source of truth** - Issues stored in a version-controlled SQL database (Dolt), enabling collaboration via Dolt-native replication
2. **AI-native workflows** - Hash-based IDs, JSON output, dependency-aware execution
3. **Local-first operation** - Dolt 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 |

### Dolt Server Mode

Dolt provides the database backend for beads:
- Start with `bd dolt start`
- Handles auto-commit and sync
- Logs available at `.beads/dolt/sql-server.log`
- Check health with `bd doctor`

### Dolt Sync

The synchronization mechanism:

```
Dolt DB (.beads/dolt/)
    ↕ dolt commit
Local Dolt history
    ↕ dolt push/pull
Remote Dolt repository
```

### Formulas

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

## Navigation

- [Issues & Dependencies](/core-concepts/issues)
- [Dolt Server Mode](#dolt-server-mode)
- [Dolt Sync](#dolt-sync)
- [Hash-based IDs](/core-concepts/hash-ids)

</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
# Bootstrap from a JSONL export (preserves original IDs in metadata)
bd init --from-jsonl old-issues.jsonl

# 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 --claim

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

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

# Multiple changes
bd update bd-42 --claim --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/labels.md">


# Labels in Beads

Labels provide flexible, multi-dimensional categorization for issues beyond the structured fields (status, priority, type). Use labels for cross-cutting concerns, technical metadata, and contextual tagging without schema changes.

## Design Philosophy

**When to use labels vs. structured fields:**

- **Structured fields** (status, priority, type) → Core workflow state
  - Status: Where the issue is in the workflow (`open`, `in_progress`, `blocked`, `closed`)
  - Priority: How urgent (0-4)
  - Type: What kind of work (`bug`, `feature`, `task`, `epic`, `chore`)

- **Labels** → Everything else
  - Technical metadata (`backend`, `frontend`, `api`, `database`)
  - Domain/scope (`auth`, `payments`, `search`, `analytics`)
  - Effort estimates (`small`, `medium`, `large`)
  - Quality gates (`needs-review`, `needs-tests`, `breaking-change`)
  - Team/ownership (`team-infra`, `team-product`)
  - Release tracking (`v1.0`, `v2.0`, `backport-candidate`)

## Quick Start

```bash
# Add labels when creating issues
bd create "Fix auth bug" -t bug -p 1 -l auth,backend,urgent

# Add labels to existing issues
bd label add bd-42 security
bd label add bd-42 breaking-change

# List issue labels
bd label list bd-42

# Remove a label
bd label remove bd-42 urgent

# List all labels in use
bd label list-all

# Filter by labels (AND - must have ALL)
bd list --label backend,auth

# Filter by labels (OR - must have AT LEAST ONE)
bd list --label-any frontend,backend

# Combine filters
bd list --status open --priority 1 --label security
```

## Common Label Patterns

### 1. Technical Component Labels

Identify which part of the system:
```bash
backend
frontend
api
database
infrastructure
cli
ui
mobile
```

**Example:**
```bash
bd create "Add GraphQL endpoint" -t feature -p 2 -l backend,api
bd create "Update login form" -t task -p 2 -l frontend,auth,ui
```

### 2. Domain/Feature Area

Group by business domain:
```bash
auth
payments
search
analytics
billing
notifications
reporting
admin
```

**Example:**
```bash
bd list --label payments --status open  # All open payment issues
bd list --label-any auth,security       # Security-related work
```

### 3. Size/Effort Estimates

Quick effort indicators:
```bash
small     # < 1 day
medium    # 1-3 days
large     # > 3 days
```

**Example:**
```bash
# Find small quick wins
bd ready --json | jq '.[] | select(.labels[] == "small")'
```

### 4. Quality Gates

Track what's needed before closing:
```bash
needs-review
needs-tests
needs-docs
breaking-change
```

**Example:**
```bash
bd label add bd-42 needs-review
bd list --label needs-review --status in_progress
```

### 5. Release Management

Track release targeting:
```bash
v1.0
v2.0
backport-candidate
release-blocker
```

**Example:**
```bash
bd list --label v1.0 --status open    # What's left for v1.0?
bd label add bd-42 release-blocker
```

### 6. Team/Ownership

Indicate ownership or interest:
```bash
team-infra
team-product
team-mobile
needs-triage
help-wanted
```

**Example:**
```bash
bd list --assignee alice --label team-infra
bd create "Memory leak in cache" -t bug -p 1 -l team-infra,help-wanted
```

### 7. Special Markers

Process or workflow flags:
```bash
auto-generated     # Created by automation
discovered-from    # Found during other work (also a dep type)
technical-debt
good-first-issue
duplicate
wontfix
```

**Example:**
```bash
bd create "TODO: Refactor parser" -t chore -p 3 -l technical-debt,auto-generated
```

## Filtering by Labels

### AND Filtering (--label)
All specified labels must be present:

```bash
# Issues that are BOTH backend AND urgent
bd list --label backend,urgent

# Open bugs that need review AND tests
bd list --status open --type bug --label needs-review,needs-tests
```

### OR Filtering (--label-any)
At least one specified label must be present:

```bash
# Issues in frontend OR backend
bd list --label-any frontend,backend

# Security or auth related
bd list --label-any security,auth
```

### Combining AND/OR
Mix both filters for complex queries:

```bash
# Backend issues that are EITHER urgent OR a blocker
bd list --label backend --label-any urgent,release-blocker

# Frontend work that needs BOTH review and tests, but in any component
bd list --label needs-review,needs-tests --label-any frontend,ui,mobile
```

## Workflow Examples

### Triage Workflow
```bash
# Create untriaged issue
bd create "Crash on login" -t bug -p 1 -l needs-triage

# During triage, add context
bd label add bd-42 auth
bd label add bd-42 backend
bd label add bd-42 urgent
bd label remove bd-42 needs-triage

# Find untriaged issues
bd list --label needs-triage
```

### Quality Gate Workflow
```bash
# Start work
bd update bd-42 --claim

# Mark quality requirements
bd label add bd-42 needs-tests
bd label add bd-42 needs-docs

# Before closing, verify
bd label list bd-42
# ... write tests and docs ...
bd label remove bd-42 needs-tests
bd label remove bd-42 needs-docs

# Close when gates satisfied
bd close bd-42
```

### Release Planning
```bash
# Tag issues for v1.0
bd label add bd-42 v1.0
bd label add bd-43 v1.0
bd label add bd-44 v1.0

# Track v1.0 progress
bd list --label v1.0 --status closed    # Done
bd list --label v1.0 --status open      # Remaining
bd stats  # Overall progress

# Mark critical items
bd label add bd-45 v1.0
bd label add bd-45 release-blocker
```

### Component-Based Work Distribution
```bash
# Backend team picks up work
bd ready --json | jq '.[] | select(.labels[]? == "backend")'

# Frontend team finds small tasks
bd list --status open --label frontend,small

# Find help-wanted items for new contributors
bd list --label help-wanted,good-first-issue
```

## Label Management

### Listing Labels
```bash
# Labels on a specific issue
bd label list bd-42

# All labels in database with usage counts
bd label list-all

# JSON output for scripting
bd label list-all --json
```

Output:
```json
[
  {"label": "auth", "count": 5},
  {"label": "backend", "count": 12},
  {"label": "frontend", "count": 8}
]
```

### Bulk Operations

Add labels in batch during creation:
```bash
bd create "Issue" -l label1,label2,label3
```

Script to add label to multiple issues:
```bash
# Add "needs-review" to all in_progress issues
bd list --status in_progress --json | jq -r '.[].id' | while read id; do
  bd label add "$id" needs-review
done
```

Remove label from multiple issues:
```bash
# Remove "urgent" from closed issues
bd list --status closed --label urgent --json | jq -r '.[].id' | while read id; do
  bd label remove "$id" urgent
done
```

## Integration with Git Workflow

Labels are stored in the Dolt database and synced automatically with all issue data:

```bash
# Make changes
bd create "Fix bug" -l backend,urgent
bd label add bd-42 needs-review

# Changes are committed to Dolt history automatically
# Sync with remotes when ready:
bd dolt push

# After pulling changes:
bd dolt pull
bd list --label backend  # Fresh data including labels
```

## Markdown Import/Export

Labels are preserved when importing from markdown:

```markdown
# Fix Authentication Bug

### Type
bug

### Priority
1

### Labels
auth, backend, urgent, needs-review

### Description
Users can't log in after recent deployment.
```

```bash
bd create -f issue.md
# Creates issue with all four labels
```

## Best Practices

### 1. Establish Conventions Early
Document your team's label taxonomy:
```bash
# Add to project README or CONTRIBUTING.md
- Use lowercase, hyphen-separated (e.g., `good-first-issue`)
- Prefix team labels (e.g., `team-infra`, `team-product`)
- Use consistent size labels (`small`, `medium`, `large`)
```

### 2. Don't Overuse Labels
Labels are flexible, but too many can cause confusion. Prefer:
- 5-10 core technical labels (`backend`, `frontend`, `api`, etc.)
- 3-5 domain labels per project
- Standard process labels (`needs-review`, `needs-tests`)
- Release labels as needed

### 3. Clean Up Unused Labels
Periodically review:
```bash
bd label list-all
# Remove obsolete labels from issues
```

### 4. Use Labels for Filtering, Not Search
Labels are for categorization, not free-text search:
- ✅ Good: `backend`, `auth`, `urgent`
- ❌ Bad: `fix-the-login-bug`, `john-asked-for-this`

### 5. Combine with Dependencies
Labels + dependencies = powerful organization:
```bash
# Epic with labeled subtasks
bd create "Auth system rewrite" -t epic -p 1 -l auth,v2.0
bd create "Implement JWT" -t task -p 1 -l auth,backend --deps parent-child:bd-42
bd create "Update login UI" -t task -p 1 -l auth,frontend --deps parent-child:bd-42

# Find all v2.0 auth work
bd list --label auth,v2.0
```

## AI Agent Usage

Labels are especially useful for AI agents managing complex workflows:

```bash
# Auto-label discovered work
bd create "Found TODO in auth.go" -t task -p 2 -l auto-generated,technical-debt

# Filter for agent review
bd list --label needs-review --status in_progress --json

# Track automation metadata
bd label add bd-42 ai-generated
bd label add bd-42 needs-human-review
```

Example agent workflow:
```bash
# Agent discovers issues during refactor
bd create "Extract validateToken function" -t chore -p 2 \
  -l technical-debt,backend,auth,small \
  --deps discovered-from:bd-10

# Agent marks work for review
bd update bd-42 --claim
# ... agent does work ...
bd label add bd-42 needs-review
bd label add bd-42 ai-generated

# Human reviews and approves
bd label remove bd-42 needs-review
bd label add bd-42 approved
bd close bd-42
```

## Labels as State Cache

Labels can cache operational state for fast queries, enabling patterns where beads track both immutable history (events) and current state (labels).

### The Pattern

**Convention:** `<dimension>:<value>`

Examples:
- `patrol:muted` / `patrol:active` - patrol suppression state
- `mode:degraded` / `mode:normal` - operational mode
- `status:idle` / `status:working` - worker status
- `health:healthy` / `health:failing` - component health

**Implementation:**
1. Create an event bead (full context, immutable history)
2. Update the role bead's labels (current state cache)

```bash
# Event: Full record of what happened and why
bd create "Muted patrol: user requested during debugging" -t event \
  -l event-type:patrol-muted,actor:observer,reason:user-request

# State: Update the role bead's label to reflect current state
bd label remove beads/observer patrol:active
bd label add beads/observer patrol:muted
```

**Key principle:** Events are the source of truth. Labels are a cache for fast queries.

### Why This Pattern?

**Fast queries without event scanning:**
```bash
# Without labels-as-state: scan all events to find current patrol state
bd list --type event | grep "patrol" | tail -1  # Slow, fragile

# With labels-as-state: direct query
bd show beads/observer | grep "patrol:"  # Instant
```

**History preserved:**
```bash
# When was patrol muted? Why? Who did it?
bd list --label event-type:patrol-muted --type event
```

**State recovery:**
```bash
# If labels get corrupted, rebuild from events
bd list --type event --label event-type:patrol-muted | tail -1
# Then re-apply the label
```

### Common State Dimensions

| Dimension | Values | Use Case |
|-----------|--------|----------|
| `patrol:` | `active`, `muted` | Patrol cycle suppression |
| `mode:` | `normal`, `degraded`, `maintenance` | Operational mode |
| `status:` | `idle`, `working`, `blocked` | Worker activity |
| `health:` | `healthy`, `warning`, `failing` | Component health |
| `lock:` | `unlocked`, `locked` | Exclusive access control |

### State Transitions

Always create an event before changing state labels:

```bash
# Function to transition state with audit trail
transition_state() {
  local role="$1"
  local dimension="$2"
  local old_value="$3"
  local new_value="$4"
  local reason="$5"

  # Record the transition
  bd create "State change: $dimension $old_value → $new_value" -t event \
    -l "event-type:state-change,dimension:$dimension,from:$old_value,to:$new_value"

  # Update the cache
  bd label remove "$role" "$dimension:$old_value"
  bd label add "$role" "$dimension:$new_value"
}

# Usage
transition_state beads/observer patrol active muted "User debugging session"
```

### Querying State

```bash
# Current state of a role
bd label list beads/observer | grep ":"

# All roles in a specific state
bd list --label patrol:muted

# Roles NOT in expected state
bd list --label-any mode:degraded,health:failing

# History of state changes
bd list --type event --label event-type:state-change
```

### Best Practices

1. **Use namespaced dimensions** - Prefix with role type if ambiguous
2. **Keep value sets small** - 2-4 values per dimension
3. **Document valid values** - List allowed values in role docs
4. **Always create events first** - Never update labels without history
5. **Treat labels as ephemeral** - Rebuild from events if corrupted

### Future Helpers

The pattern suggests helper commands (see bd-7l67):
```bash
# Query current state
bd state beads/observer patrol     # → "muted"

# Transition with automatic event creation
bd set-state beads/observer patrol=active --reason "Debugging complete"
```

Until helpers exist, use the manual pattern above.

## Advanced Patterns

### Component Matrix
Track issues across multiple dimensions:
```bash
# Backend + auth + high priority
bd list --label backend,auth --priority 1

# Any frontend work that's small
bd list --label-any frontend,ui --label small

# Critical issues across all components
bd list --priority 0 --label-any backend,frontend,infrastructure
```

### Sprint Planning
```bash
# Label issues for sprint
for id in bd-42 bd-43 bd-44 bd-45; do
  bd label add "$id" sprint-12
done

# Track sprint progress
bd list --label sprint-12 --status closed    # Velocity
bd list --label sprint-12 --status open      # Remaining
bd stats | grep "In Progress"                # Current WIP
```

### Technical Debt Tracking
```bash
# Mark debt
bd create "Refactor legacy parser" -t chore -p 3 -l technical-debt,large

# Find debt to tackle
bd list --label technical-debt --label small
bd list --label technical-debt --priority 1  # High-priority debt
```

### Breaking Change Coordination
```bash
# Identify breaking changes
bd label add bd-42 breaking-change
bd label add bd-42 v2.0

# Find all breaking changes for next major release
bd list --label breaking-change,v2.0

# Ensure they're documented
bd list --label breaking-change --label needs-docs
```

## Operational State Pattern (Labels as Cache)

For orchestration systems, labels can cache the current operational state of "role beads" (issues representing agents or system components). This enables fast state queries without scanning event history.

### Convention: `<dimension>:<value>`

Use colon-separated labels with a dimension prefix and value suffix:

```
patrol:muted      patrol:active
mode:degraded     mode:normal
status:idle       status:working
health:healthy    health:failing
```

### The Pattern

1. **Create an event bead** with full context (immutable, audit trail)
2. **Update the role bead's labels** to reflect current state (fast lookup)

```bash
# 1. Record the event (source of truth)
bd create "Muted patrol for agent-abc" -t event \
  --parent agent-abc \
  -d "Reason: investigating stuck worker. Expected duration: 30m"

# 2. Update the cached state label
bd label remove agent-abc patrol:active
bd label add agent-abc patrol:muted
```

### Why This Pattern?

**Events are source of truth. Labels are cache.**

| Approach | Events Only | Labels as Cache |
|----------|-------------|-----------------|
| Query current state | Scan all events, find latest | `bd list --label patrol:muted` |
| Query state history | Natural (all events exist) | Query events |
| Audit trail | Complete | Complete (events still exist) |
| Performance | O(n) events | O(1) label lookup |

The pattern gives you both: complete history via events, fast queries via labels.

### Example: Agent Role States

```bash
# Create a role bead for an agent
bd create "witness-alpha" -t role -l patrol:active,mode:normal,health:healthy

# Agent enters degraded mode
bd create "Degraded: high error rate" -t event --parent witness-alpha \
  -d "Error rate exceeded 5%. Reducing poll frequency."
bd label remove witness-alpha mode:normal
bd label add witness-alpha mode:degraded

# Query current state
bd list --label mode:degraded --type role  # All degraded roles

# Agent recovers
bd create "Recovered: error rate normal" -t event --parent witness-alpha
bd label remove witness-alpha mode:degraded
bd label add witness-alpha mode:normal
```

### Common Dimensions

| Dimension | Values | Use Case |
|-----------|--------|----------|
| `patrol` | `active`, `muted`, `suspended` | Agent patrol cycles |
| `mode` | `normal`, `degraded`, `maintenance` | Operational modes |
| `status` | `idle`, `working`, `blocked` | Work state |
| `health` | `healthy`, `warning`, `failing` | Health checks |
| `sync` | `current`, `stale`, `syncing` | Sync state |

### Best Practices

1. **Always create the event first** - Labels are cache; events are truth
2. **Remove old value before adding new** - Prevents dimension:value1 + dimension:value2 conflicts
3. **Use consistent dimension names** - Establish team conventions early
4. **Keep dimensions orthogonal** - patrol and mode are independent concerns

### Querying State

```bash
# Find all muted patrols
bd list --label patrol:muted

# Find healthy agents in normal mode
bd list --label health:healthy,mode:normal

# Find any non-healthy agents
bd list --label-any health:warning,health:failing

# Get state for a specific role
bd label list witness-alpha
# Output: patrol:active, mode:normal, health:healthy
```

### Helper Commands

For convenience, use these helpers:

```bash
# Query a specific dimension
bd state witness-alpha patrol
# Output: active

# List all state dimensions
bd state list witness-alpha
# Output:
#   patrol: active
#   mode: normal
#   health: healthy

# Set state (creates event + updates label atomically)
bd set-state witness-alpha patrol=muted --reason "Investigating issue"
```

The `set-state` command atomically:
1. Creates an event bead with the reason (source of truth)
2. Removes the old dimension label if present
3. Adds the new dimension:value label (cache)

See [CLI_REFERENCE.md](/cli-reference/set-state) for full command reference.

## Troubleshooting

### Labels Not Showing in List
Labels require explicit fetching. The `bd list` command shows issues but not labels in human output (only in JSON).

```bash
# See labels in JSON
bd list --json | jq '.[] | {id, labels}'

# See labels for specific issue
bd show bd-42 --json | jq '.labels'
bd label list bd-42
```

### Label Filtering Not Working
Check label names for exact matches (case-sensitive):
```bash
# These are different labels:
bd label add bd-42 Backend    # Capital B
bd list --label backend       # Won't match

# List all labels to see exact names
bd label list-all
```

### Syncing Labels
Labels are stored in the Dolt database. If labels seem out of sync:
```bash
# Pull from Dolt remote
bd dolt pull

# Or run doctor to diagnose
bd doctor
```

## See Also

- [README.md](https://github.com/gastownhall/beads/blob/main/README.md) - Main documentation
- [AGENTS.md](https://github.com/gastownhall/beads/blob/main/AGENTS.md) - AI agent integration guide
- [ADVANCED.md](/reference/advanced) - Advanced features and configuration

</document>

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


# Issue Metadata

The `metadata` field on issues accepts arbitrary JSON. Any valid JSON value is stored as-is.

Metadata is the preferred extension point for data that is specific to an
integration, orchestrator, team workflow, or experimental automation. Before
adding first-class fields, commands, or schema changes, check the
[Project Charter](https://github.com/gastownhall/beads/blob/main/docs/PROJECT_CHARTER.md#schema-boundary).

## Example: Agent Execution Metadata

Agent execution hints are one example of using metadata to extend beads without
adding new native database fields. Automation may store these hints so agents
can make routing decisions without parsing prose. Agents enacting an issue
should read metadata first, then use description and notes for scope and
rationale:

```bash
bd show <id> --json | jq '.[0] | {id,title,metadata,description,notes}'
```

The current convention for execution hint keys is:

| Key | Meaning |
|-----|---------|
| `execution_agent_type` | Suggested worker class, such as `explorer`, `worker`, or `mixed`. |
| `execution_suggested_model` | Suggested model for the parent agent or spawned subagent. |
| `execution_reasoning_effort` | Suggested reasoning effort, such as `low`, `medium`, `high`, or `xhigh`. |
| `execution_mode` | Whether work should be local, delegated, or staged between delegated and local execution. |
| `execution_parallel_group` | Grouping hint for work that can run alongside related tasks. |

These keys are advisory metadata, not core issue fields. When a workflow uses
them, they take precedence over free-form notes for execution routing. Notes
remain useful for rationale, ownership, and exact prompts.

Parent/orchestrator agents must consume these keys before spawning subagents.
Model and reasoning effort are normally fixed at launch, so reading metadata
after delegation is too late.

Do not add a first-class helper such as `bd show <id> --execution` or
`bd plan <id> --json` yet. Keep using the JSON/JQ snippet until upstream
issue gh-3541 determines whether schedulers or runners need these fields as a
stable CLI surface.

## Example: Tracker Round-Trip Metadata

Tracker integrations map external issues into beads fields such as title,
status, priority, type, labels, dependencies, and `external_ref`. When an
integration needs to preserve tracker-specific fields that do not belong in the
native beads schema, it can store those fields in issue metadata:

```json
{
  "example_tracker": {
    "board_id": "ENG",
    "sprint_id": 42,
    "remote_type": "story"
  }
}
```

This keeps beads' core issue model stable while allowing the integration to
round-trip fields it understands. Prefer namespaced keys and keep
tracker-specific policy in the integration. If a value becomes broadly useful
to beads itself, revisit whether it deserves a native field.

## Reserved Key Prefixes

| Prefix | Reserved For |
|--------|------------|
| `bd:` | Beads internal use |
| `_` | Internal/private keys |

Avoid these prefixes in user-defined keys to prevent conflicts with future Beads features.

## Related

- [Project Charter](https://github.com/gastownhall/beads/blob/main/docs/PROJECT_CHARTER.md) - Product scope and schema boundary
- [#1416](https://github.com/gastownhall/beads/issues/1416) - Optional schema enforcement (future)

</document>

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


# Sync Concepts

Beads issue data lives in Dolt. The local Dolt database is the source of truth
for `bd list`, `bd show`, `bd ready`, and every write command.

## The Wire Format

Cross-machine sync uses Dolt remotes:

```bash
bd dolt push
bd dolt pull
```

For normal git-hosted projects, the Dolt remote can be the same `origin` URL
used for source code. Dolt stores issue history under `refs/dolt/data`, separate
from source branches such as `refs/heads/main`.

On new projects, `bd init` auto-detects `git remote get-url origin` and
configures a Dolt remote named `origin`. The first `bd dolt push` publishes
`refs/dolt/data`. Fresh clones should run `bd bootstrap` to clone that Dolt
history. When bootstrap finds `refs/dolt/data` on git origin, it also wires
that origin as the Dolt remote for future `bd dolt push` and `bd dolt pull`.

## What JSONL Is For

`.beads/issues.jsonl` is an export. It exists for viewers, interchange,
migration, and backup. It is not the canonical cross-machine sync channel.

Do not use routine `bd import .beads/issues.jsonl` as a replacement for
`bd dolt pull`. JSONL import is upsert-only; it cannot infer that records absent
from an export were deleted, pruned, or simply never exported.

## Hooks

The pre-commit hook refreshes `.beads/issues.jsonl` when `export.auto=true`.
That keeps the export current for tools, but it does not push Dolt history.

The post-merge and post-checkout hooks skip JSONL import when `sync.remote` is
configured. For old projects with no Dolt remote, they may import JSONL as a
compatibility fallback and print a warning that this is not durable sync.

## Repair

For projects initialized before automatic git-origin remote wiring, pick the
machine with the authoritative local Dolt database first. Then run:

```bash
bd dolt remote list
bd export -o .beads/issues.pre-remote.jsonl   # optional issue audit export
bd dolt remote add origin <git-origin-url>
bd dolt push
```

Use the Dolt-compatible git URL form when needed. For example,
`git+ssh://git@github.com/org/repo.git` or
`git+https://github.com/org/repo.git`. `bd dolt remote add origin ...`
persists `sync.remote` into `.beads/config.yaml`; commit and push that config
change so fresh clones can run `bd bootstrap`.

Other machines should then run:

```bash
bd dolt pull
# or, if the local database is stale or missing:
bd bootstrap
```

</document>

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


# Architecture Overview

This document explains how Beads' architecture works with Dolt as its storage backend.

## Architecture

Beads uses **Dolt** as its sole storage backend -- a version-controlled SQL database that provides git-like semantics (branch, merge, diff, push, pull) natively at the database level.

By default, Dolt runs in **embedded mode** (in-process, no separate server). For multi-writer
setups (multiple agents, orchestrator), switch to **server mode** which connects to a
running `dolt sql-server`. See the [Dolt Server Mode](#dolt-server-mode) section below for details.

```mermaid
flowchart TD
    subgraph DOLT["🗄️ Dolt Database"]
        D[(".beads/dolt/<br/><i>Version-Controlled SQL</i>")]
    end

    subgraph REMOTE["🌐 Dolt Remotes"]
        R[("DoltHub / S3 / GCS<br/><i>Sync & Backup</i>")]
    end

    D <-->|"bd dolt push/pull"| R

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

    style DOLT fill:#2d5a27,stroke:#4a9c3e,color:#fff
    style REMOTE fill:#1a4a6e,stroke:#3a8ac4,color:#fff
```

:::info Source of Truth
**Dolt** is the source of truth. Every write auto-commits to Dolt history, providing full version control, branching, and merge capabilities at the database level.

Recovery is straightforward: pull from a Dolt remote with `bd dolt pull`, or restore from a Dolt-native backup with `bd backup restore`.
:::

### Why Dolt?

- **Version-controlled SQL**: Full SQL queries with native version control
- **Cell-level merge**: Concurrent changes merge automatically at the field level
- **Multi-writer**: Server mode supports concurrent agents
- **Native branching**: Dolt branches independent of git branches
- **Works offline**: All queries run against local database
- **Portable**: `bd export` produces JSONL for migration and interoperability

## Data Flow

### Write Path
```text
User runs bd create
    → Dolt database updated
    → Auto-committed to Dolt history
```

### Read Path
```text
User runs bd list
    → Dolt SQL query
    → Results returned immediately
```

### Sync Path
```text
User runs bd dolt push
    → Commits pushed to Dolt remote

User runs bd dolt pull
    → Remote commits fetched and merged
```

### Multi-Machine Sync Considerations

When working across multiple machines or clones:

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

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

3. **Avoid parallel edits** - If two machines create issues simultaneously without syncing, Dolt's cell-level merge handles most conflicts automatically

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

## Dolt Server Mode

The Dolt server handles background synchronization and database operations:

- Manages the Dolt database backend
- Handles auto-commit for change tracking
- Provides concurrent access for multiple agents
- Logs available at `.beads/dolt/sql-server.log`

:::tip
Start the Dolt server with `bd dolt start`. Check health with `bd doctor`.
:::

### Embedded Mode (No Server)

For CI/CD pipelines, containers, and single-use scenarios, no server is needed. Beads operates in embedded mode automatically when no Dolt server is running:

```bash
bd create "CI-generated issue"
bd dolt push
```

**When embedded mode is appropriate:**
- CI/CD pipelines (Jenkins, GitHub Actions)
- Docker containers
- Ephemeral environments
- Scripts that should not leave background processes

### Multi-Clone Scenarios

:::warning Race Conditions in Multi-Clone Workflows
When multiple git clones of the same repository run sync operations 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. Stop the Dolt server (`bd dolt stop`) before switching between clones
2. Dolt handles worktrees natively in server mode
3. Use embedded mode for automated workflows
:::

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

## Recovery Model

Dolt's version control makes recovery straightforward:

1. **Lost database?** → Pull from Dolt remote: `bd dolt pull`
2. **Have a backup?** → Restore it: `bd backup restore [path] --force`
3. **Merge conflicts?** → Dolt handles cell-level merge natively

### Universal Recovery Sequence

The following sequence resolves the majority of reported issues. For detailed procedures, see [Recovery Runbooks](/recovery).

```bash
bd dolt stop                 # Stop Dolt server (prevents race conditions)
git worktree prune           # Clean orphaned worktrees
bd dolt pull                 # Pull from Dolt remote
bd dolt start                # Restart server
```

:::warning Use `bd doctor --fix` With Care
Always back up and preview before running `bd doctor --fix`:

1. **Back up first:** `cp -r .beads .beads.backup`
2. **Preview changes:** `bd doctor --dry-run` — shows what would be fixed without making changes
3. **Review diagnostics:** `bd doctor` (no flags) — diagnostic only, no changes made
4. **Then fix:** `bd doctor --fix` — or `bd doctor --fix -i` to confirm each fix individually

**Why caution?** The `--fix` flag may remove dependencies it flags as circular, including valid parent-child relationships. Use `--fix-child-parent` only if you're certain the flagged deps are invalid.

**Other diagnostic tools:**
- `bd blocked` — check which issues are blocked and why
- `bd show <issue-id>` — inspect a specific issue's state
:::

See [Recovery](/recovery) for specific procedures and [Database Corruption Recovery](/recovery/database-corruption) for Dolt recovery steps.

## Design Decisions

### Why Dolt?

Dolt is a version-controlled SQL database that provides git-like semantics natively. Unlike plain SQLite (binary merge conflicts) or JSONL (slow queries), Dolt gives you both fast SQL queries and proper merge semantics.

### Why not a cloud server?

Beads is designed for offline-first, local-first development. The Dolt server runs locally -- no cloud dependency, no downtime, no vendor lock-in, and full functionality on airplanes or in restricted networks.

### Trade-offs

| Benefit | Trade-off |
|---------|-----------|
| Works offline | No real-time collaboration |
| Version-controlled database | Requires Dolt server |
| Cell-level merge | Requires initial setup |
| Local-first speed | Manual sync to remotes |
| SQL queries | Dolt binary dependency |

### 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

<!-- AUTO-GENERATED: do not edit manually -->
Reference for bd Latest. Generated from `bd help --docs-root`.

This reference covers all 108 live top-level `bd` commands. Regenerate it with:

```bash
./scripts/generate-cli-docs.sh
```

## Commands

- [`bd admin`](./admin.md)
- [`bd ado`](./ado.md)
- [`bd assign`](./assign.md)
- [`bd audit`](./audit.md)
- [`bd backup`](./backup.md)
- [`bd batch`](./batch.md)
- [`bd blocked`](./blocked.md)
- [`bd bootstrap`](./bootstrap.md)
- [`bd branch`](./branch.md)
- [`bd children`](./children.md)
- [`bd close`](./close.md)
- [`bd comment`](./comment.md)
- [`bd comments`](./comments.md)
- [`bd compact`](./compact.md)
- [`bd completion`](./completion.md)
- [`bd config`](./config.md)
- [`bd context`](./context.md)
- [`bd cook`](./cook.md)
- [`bd count`](./count.md)
- [`bd create`](./create.md)
- [`bd create-form`](./create-form.md)
- [`bd defer`](./defer.md)
- [`bd delete`](./delete.md)
- [`bd dep`](./dep.md)
- [`bd diff`](./diff.md)
- [`bd doctor`](./doctor.md)
- [`bd dolt`](./dolt.md)
- [`bd duplicate`](./duplicate.md)
- [`bd duplicates`](./duplicates.md)
- [`bd edit`](./edit.md)
- [`bd epic`](./epic.md)
- [`bd export`](./export.md)
- [`bd federation`](./federation.md)
- [`bd find-duplicates`](./find-duplicates.md)
- [`bd flatten`](./flatten.md)
- [`bd forget`](./forget.md)
- [`bd formula`](./formula.md)
- [`bd gate`](./gate.md)
- [`bd gc`](./gc.md)
- [`bd github`](./github.md)
- [`bd gitlab`](./gitlab.md)
- [`bd graph`](./graph.md)
- [`bd history`](./history.md)
- [`bd hooks`](./hooks.md)
- [`bd human`](./human.md)
- [`bd import`](./import.md)
- [`bd info`](./info.md)
- [`bd init`](./init.md)
- [`bd init-safety`](./init-safety.md)
- [`bd jira`](./jira.md)
- [`bd kv`](./kv.md)
- [`bd label`](./label.md)
- [`bd linear`](./linear.md)
- [`bd link`](./link.md)
- [`bd lint`](./lint.md)
- [`bd list`](./list.md)
- [`bd mail`](./mail.md)
- [`bd memories`](./memories.md)
- [`bd merge-slot`](./merge-slot.md)
- [`bd metrics`](./metrics.md)
- [`bd migrate`](./migrate.md)
- [`bd mol`](./mol.md)
- [`bd note`](./note.md)
- [`bd notion`](./notion.md)
- [`bd onboard`](./onboard.md)
- [`bd orphans`](./orphans.md)
- [`bd ping`](./ping.md)
- [`bd preflight`](./preflight.md)
- [`bd prime`](./prime.md)
- [`bd priority`](./priority.md)
- [`bd promote`](./promote.md)
- [`bd prune`](./prune.md)
- [`bd purge`](./purge.md)
- [`bd q`](./q.md)
- [`bd query`](./query.md)
- [`bd quickstart`](./quickstart.md)
- [`bd ready`](./ready.md)
- [`bd recall`](./recall.md)
- [`bd recompute-blocked`](./recompute-blocked.md)
- [`bd remember`](./remember.md)
- [`bd rename`](./rename.md)
- [`bd rename-prefix`](./rename-prefix.md)
- [`bd reopen`](./reopen.md)
- [`bd repo`](./repo.md)
- [`bd restore`](./restore.md)
- [`bd rules`](./rules.md)
- [`bd search`](./search.md)
- [`bd set-state`](./set-state.md)
- [`bd setup`](./setup.md)
- [`bd ship`](./ship.md)
- [`bd show`](./show.md)
- [`bd sql`](./sql.md)
- [`bd stale`](./stale.md)
- [`bd state`](./state.md)
- [`bd status`](./status.md)
- [`bd statuses`](./statuses.md)
- [`bd supersede`](./supersede.md)
- [`bd swarm`](./swarm.md)
- [`bd tag`](./tag.md)
- [`bd todo`](./todo.md)
- [`bd types`](./types.md)
- [`bd undefer`](./undefer.md)
- [`bd update`](./update.md)
- [`bd upgrade`](./upgrade.md)
- [`bd vc`](./vc.md)
- [`bd version`](./version.md)
- [`bd where`](./where.md)
- [`bd worktree`](./worktree.md)

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc admin`

## bd admin

Administrative commands for beads database maintenance.

These commands are for advanced users and should be used carefully:
  cleanup   Delete closed issues (issue lifecycle)
  compact   Compact old closed issues to save space (storage optimization)
  reset     Remove all beads data and configuration (full reset)

For routine maintenance, prefer 'bd doctor --fix' which handles common repairs
automatically. Use these admin commands for targeted database operations.

```
bd admin [flags]
```

### bd admin cleanup

Delete closed issues to reduce database size.

This command permanently removes closed issues from the database.

NOTE: This command only manages issue lifecycle (closed -&gt; deleted). For general
health checks and automatic repairs, use 'bd doctor --fix' instead.

By default, deletes ALL closed issues. Use --older-than to only delete
issues closed before a certain date.

EXAMPLES:
  bd admin cleanup --force                          # Delete all closed issues
  bd admin cleanup --older-than 30 --force          # Only issues closed 30+ days ago
  bd admin cleanup --ephemeral --force              # Only closed wisps (transient molecules)
  bd admin cleanup --dry-run                        # Preview what would be deleted

SAFETY:
- Requires --force flag to actually delete (unless --dry-run)
- Supports --cascade to delete dependents
- Shows preview of what will be deleted
- Use --json for programmatic output

SEE ALSO:
  bd doctor --fix    Automatic health checks and repairs (recommended for routine maintenance)
  bd admin compact   Compact old closed issues to save space

```
bd admin cleanup [flags]
```

**Flags:**

```
      --cascade          Recursively delete all dependent issues
      --dry-run          Preview what would be deleted without making changes
      --ephemeral        Only delete closed wisps (transient molecules)
  -f, --force            Actually delete (without this flag, shows error)
      --older-than int   Only delete issues closed more than N days ago (0 = all closed issues)
```

### bd admin compact

Compact old closed issues using semantic summarization.

Compaction reduces database size by summarizing closed issues that are no longer
actively referenced. This is permanent graceful decay - original content is discarded.

Modes:
  - Analyze: Export candidates for agent review (no API key needed)
  - Apply: Accept agent-provided summary (no API key needed)
  - Auto: AI-powered compaction (requires ANTHROPIC_API_KEY or ai.api_key, legacy)
  - Dolt: Run Dolt garbage collection (for Dolt-backend repositories)

Tiers:
  - Tier 1: Semantic compression (30 days closed, 70% reduction)
  - Tier 2: Ultra compression (90 days closed) - planned, not yet implemented

Dolt Garbage Collection:
  With auto-commit per mutation, Dolt commit history grows over time. Use
  --dolt to run Dolt garbage collection and reclaim disk space.

  --dolt: Run Dolt GC on .beads/dolt directory to free disk space.
          This removes unreachable commits and compacts storage.

Examples:
  # Dolt garbage collection
  bd compact --dolt                        # Run Dolt GC
  bd compact --dolt --dry-run              # Preview without running GC

  # Agent-driven workflow (recommended)
  bd compact --analyze --json              # Get candidates with full content
  bd compact --apply --id bd-42 --summary summary.txt
  bd compact --apply --id bd-42 --summary - &lt; summary.txt

  # Legacy AI-powered workflow
  bd compact --auto --dry-run              # Preview candidates
  bd compact --auto --all                  # Compact all eligible issues
  bd compact --auto --id bd-42             # Compact specific issue

  # Statistics
  bd compact --stats                       # Show statistics


```
bd admin compact [flags]
```

**Flags:**

```
      --actor string     Actor name for audit trail (default "agent")
      --all              Process all candidates
      --analyze          Analyze mode: export candidates for agent review
      --apply            Apply mode: accept agent-provided summary
      --auto             Auto mode: AI-powered compaction (legacy)
      --batch-size int   Issues per batch (default 10)
      --dolt             Dolt mode: run Dolt garbage collection on .beads/dolt
      --dry-run          Preview without compacting
      --force            Force compact (bypass checks, requires --id)
      --id string        Compact specific issue
      --json             Output JSON format
      --limit int        Limit number of candidates (0 = no limit)
      --stats            Show compaction statistics
      --summary string   Path to summary file (use '-' for stdin)
      --tier int         Compaction tier (only tier 1 is implemented) (default 1)
      --workers int      Parallel workers (default 5)
```

### bd admin reset

Reset beads to an uninitialized state, removing all local data.

This command removes:
  - The .beads directory (database, JSONL, config)
  - Git hooks installed by bd
  - Sync branch worktrees

By default, shows what would be deleted (dry-run mode).
Use --force to actually perform the reset.

Examples:
  bd reset              # Show what would be deleted
  bd reset --force      # Actually delete everything

```
bd admin reset [flags]
```

**Flags:**

```
      --force   Actually perform the reset (required)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc ado`

## bd ado

Commands for syncing issues between beads and Azure DevOps.

Configuration can be set via 'bd config' or environment variables:
  ado.org / AZURE_DEVOPS_ORG              - Organization name
  ado.project / AZURE_DEVOPS_PROJECT      - Project name (single)
  ado.projects / AZURE_DEVOPS_PROJECTS    - Project names (comma-separated)
  ado.pat / AZURE_DEVOPS_PAT              - Personal access token
  ado.url / AZURE_DEVOPS_URL              - Custom base URL (on-prem)

```
bd ado [flags]
```

### bd ado projects

List Azure DevOps projects that the configured token has access to.

```
bd ado projects [flags]
```

### bd ado pull

Pull one or more items from Azure DevOps.

Accepts bead IDs or external references as positional arguments.
Equivalent to: bd ado sync --pull-only --issues &lt;refs&gt;

```
bd ado pull [refs...] [flags]
```

**Flags:**

```
      --dry-run   Preview pull without making changes
```

### bd ado push

Push one or more beads issues to Azure DevOps.

Accepts bead IDs as positional arguments.
Equivalent to: bd ado sync --push-only --issues &lt;ids&gt;

```
bd ado push [bead-ids...] [flags]
```

**Flags:**

```
      --dry-run   Preview push without making changes
```

### bd ado status

Display current Azure DevOps configuration and sync status.

```
bd ado status [flags]
```

### bd ado sync

Synchronize issues between beads and Azure DevOps.

By default, performs bidirectional sync:
- Pulls new/updated work items from Azure DevOps to beads
- Pushes local beads issues to Azure DevOps

Use --pull-only or --push-only to limit direction.

Filters (--area-path, --iteration-path, --types, --states) restrict
which work items are synced. On pull, they limit the WIQL query. On push,
--types and --states filter local beads before pushing to ADO. Use
--no-create with push to skip creating new ADO work items (only update
existing linked items). Filters can also be persisted via config:
  ado.filter.area_path, ado.filter.iteration_path,
  ado.filter.types, ado.filter.states
CLI flags override config values when both are set.

```
bd ado sync [flags]
```

**Flags:**

```
      --area-path string        Filter to ADO area path (e.g., "Project\Team")
      --bootstrap-match         Enable heuristic matching for first sync
      --dry-run                 Show what would be synced without making changes
      --issues string           Comma-separated bead IDs to sync selectively (e.g., bd-abc,bd-def). Mutually exclusive with --parent.
      --iteration-path string   Filter to ADO iteration path (e.g., "Project\Sprint 1")
      --no-create               Never create new items in either direction (pull or push)
      --parent string           Limit push to this bead and its descendants (push only). Mutually exclusive with --issues.
      --prefer-ado              On conflict, use Azure DevOps version
      --prefer-local            On conflict, keep local beads version
      --prefer-newer            On conflict, use most recent version (default)
      --project strings         Project name(s) to sync (overrides configured project/projects)
      --pull-only               Only pull issues from Azure DevOps
      --push-only               Only push issues to Azure DevOps
      --reconcile               Force reconciliation scan for deleted items
      --states string           Filter to ADO states, comma-separated (e.g., "New,Active,Resolved")
      --types string            Filter to work item types, comma-separated (e.g., "Bug,Task,User Story")
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc assign`

## bd assign

Assign an issue to someone.

Shorthand for 'bd update &lt;id&gt; --assignee &lt;name&gt;'.

Examples:
  bd assign bd-123 alice
  bd assign bd-123 ""      # unassign

```
bd assign <id> <name> [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc audit`

## bd audit

Audit log entries are appended to .beads/interactions.jsonl.

Each line is one event. This file is intended to be versioned in git and used for:
- auditing ("why did the agent do that?")
- dataset generation (SFT/RL fine-tuning)

Entries are append-only. Labeling creates a new "label" entry that references a parent entry.

```
bd audit [flags]
```

### bd audit label

Append a label entry referencing an existing interaction

```
bd audit label <entry-id> [flags]
```

**Flags:**

```
      --label string    Label value (e.g. "good" or "bad")
      --reason string   Reason for label
```

### bd audit record

Append an audit interaction entry

```
bd audit record [flags]
```

**Flags:**

```
      --error string       Error string (llm_call/tool_call)
      --exit-code int      Exit code (tool_call) (default -1)
      --issue-id string    Related issue id (bd-...)
      --kind string        Entry kind (e.g. llm_call, tool_call, label)
      --model string       Model name (llm_call)
      --prompt string      Prompt text (llm_call)
      --response string    Response text (llm_call)
      --stdin              Read a JSON object from stdin (must match audit.Entry schema)
      --tool-name string   Tool name (tool_call)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc backup`

## bd backup

Back up your beads database for off-machine recovery.

This is a Dolt-native database backup. It preserves the database state,
including tables, branches, commit history, and working-set data. This is
different from 'bd export', which writes issue records to JSONL for migration
and interoperability.

Commands:
  bd backup init &lt;path&gt;    Set up a backup destination (filesystem or DoltHub)
  bd backup sync           Push to configured backup destination
  bd backup restore [path] Restore from a backup directory
  bd backup remove         Remove backup destination
  bd backup status         Show backup status

DoltHub is recommended for cloud backup:
  bd backup init https://doltremoteapi.dolthub.com/&lt;user&gt;/&lt;repo&gt;
  Set DOLT_REMOTE_USER and DOLT_REMOTE_PASSWORD for authentication.

```
bd backup [flags]
```

### bd backup init

Configure a filesystem path or URL as a backup destination.

The path can be a local directory (external drive, NAS, Dropbox folder) or a
DoltHub remote URL. If the destination was previously configured, it is
updated to the new path.

Filesystem examples:
  bd backup add /mnt/usb/beads-backup
  bd backup add ~/Dropbox/beads-backup

DoltHub (recommended for cloud backup):
  bd backup add https://doltremoteapi.dolthub.com/myuser/beads-backup

After adding, run 'bd backup sync' to push your data.

```
bd backup init <path> [flags]
```

**Aliases:** add

### bd backup remove

Remove the configured backup destination.

This unregisters the backup remote from Dolt and removes the local
backup configuration. The backup data at the destination is not deleted.

```
bd backup remove [flags]
```

**Aliases:** rm

### bd backup restore

Restore the beads database from a Dolt-native backup.

By default, reads from .beads/backup/ (or the configured backup directory).
Optionally specify a path to a directory containing a Dolt backup.

This restores a full database backup created by 'bd backup sync' or an
equivalent Dolt backup. JSONL files produced by 'bd export' are issue exports,
not restore targets for this command.

Use --force to overwrite an existing database with the backup contents.

The database must already be initialized (run 'bd init' first if needed).
To initialize and restore in one step, use: bd init &amp;&amp; bd backup restore

```
bd backup restore [path] [flags]
```

**Flags:**

```
      --force   Overwrite existing database with backup contents
```

### bd backup status

Show last backup status

```
bd backup status [flags]
```

### bd backup sync

Sync the current beads database to the configured Dolt backup destination.

This pushes the entire database state (all branches, full history) to the
backup location configured with 'bd backup init'.

The backup is atomic — if the sync fails, the previous backup state is preserved.

Run 'bd backup init &lt;path&gt;' first to configure a destination.

```
bd backup sync [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc batch`

## bd batch

Run multiple write operations in a single database transaction.

Commands are read from stdin (one per line) or from a file via -f/--file.
All operations execute inside a single dolt transaction: on any error the
whole batch is rolled back, otherwise it is committed with one DOLT_COMMIT.

This is intended for shell scripts that currently invoke 'bd' many times in
a loop, which causes severe write amplification on a dolt sql-server backed
by btrfs+compression. Batching collapses N invocations into one transaction
and one dolt commit.

Grammar (one command per line):
  close &lt;id&gt; [reason...]
  update &lt;id&gt; &lt;key&gt;=&lt;value&gt; [&lt;key&gt;=&lt;value&gt; ...]
  create &lt;type&gt; &lt;priority&gt; &lt;title...&gt;
  dep add &lt;from-id&gt; &lt;to-id&gt; [type]
  dep remove &lt;from-id&gt; &lt;to-id&gt;
  #comment  (blank lines and '# ...' comments are ignored)

Supported 'update' keys: status, priority, title, assignee
Supported dependency types: see 'bd dep add --help' (default: blocks)

Tokens are whitespace-separated. Double-quoted strings ("like this") may
contain spaces; use \" to embed a quote and \\ for a backslash.

Examples:
  # From a pipe
  bd list --status stale -q | awk '&#123;print "close",$1," stale"&#125;' | bd batch

  # From a file
  bd batch -f operations.txt

  # Inline
  printf 'close bd-1 done\nupdate bd-2 status=in_progress\n' | bd batch

On success, exits 0 and prints a summary (or JSON with --json). On any error,
rolls back the entire transaction and exits non-zero with the failing line.

NOTE: This is a narrow subset. Commands like 'show', 'list', 'ready', 'sync',
complex create flows, or any flag not listed above are NOT accepted. Use
normal 'bd' subcommands for interactive/read operations.

```
bd batch [flags]
```

**Flags:**

```
      --dry-run          Parse input and echo commands without executing
  -f, --file string      Read commands from file instead of stdin
  -m, --message string   DOLT_COMMIT message (default: 'bd: batch N ops by <actor>')
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc blocked`

## bd blocked

Show blocked issues

```
bd blocked [flags]
```

**Flags:**

```
      --parent string   Filter to descendants of this bead/epic
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc bootstrap`

## bd bootstrap

Bootstrap sets up the beads database without destroying existing data.
Unlike 'bd init --force', bootstrap will never delete existing issues.

Bootstrap auto-detects the right action:
  • If sync.remote is configured: clones from the remote
  • If git origin has Dolt data (refs/dolt/data): clones from git and wires origin for future push/pull
  • If .beads/backup/*.jsonl exists: restores from backup
  • If .beads/issues.jsonl exists: imports from git-tracked JSONL
  • If no database exists: creates a fresh one
  • If database already exists: validates and reports status

This is the recommended command for:
  • Setting up beads on a fresh clone
  • Recovering after moving to a new machine
  • Repairing a broken database configuration

Non-interactive mode (--non-interactive, --yes/-y, or BD_NON_INTERACTIVE=1):
  Skips the confirmation prompt before executing the bootstrap plan.
  Also auto-detected when stdin is not a terminal or CI=true is set.

Examples:
  bd bootstrap              # Auto-detect and set up
  bd bootstrap --dry-run    # Show what would be done
  bd bootstrap --json       # Output plan as JSON
  bd bootstrap --yes        # Skip confirmation prompt


```
bd bootstrap [flags]
```

**Flags:**

```
      --dry-run           Show what would be done without doing it
      --non-interactive   Alias for --yes
  -y, --yes               Skip confirmation prompts (for CI/automation)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc branch`

## bd branch

List all branches or create a new branch.

This command requires the Dolt storage backend. Without arguments,
it lists all branches. With an argument, it creates a new branch.

Examples:
  bd branch                    # List all branches
  bd branch feature-xyz        # Create a new branch named feature-xyz

```
bd branch [name] [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc children`

## bd children

List all beads that are children of the specified parent bead.

This is a convenience alias for 'bd list --parent &lt;id&gt; --status all'.
Unlike plain 'bd list', children includes closed issues by default,
since the primary use case is inspecting all work under a parent.

Examples:
  bd children hq-abc123        # List all children of hq-abc123
  bd children hq-abc123 --json # List children in JSON format
  bd children hq-abc123 --pretty # Show children in tree format

```
bd children <parent-id> [flags]
```

**Flags:**

```
      --pretty   Show children in tree format
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc close`

## bd close

Close one or more issues.

If no issue ID is provided, closes the last touched issue (from most recent
create, update, show, or close operation).

When closing multiple issues, provide one --reason for all IDs or repeat
--reason once per ID. Reasons map positionally: the first --reason applies
to the first ID, the second --reason to the second ID, regardless of where
the flags appear in the command line.

```
bd close [id...] [flags]
```

**Aliases:** done

**Flags:**

```
      --claim-next           Automatically claim the next highest priority available issue
      --continue             Auto-advance to next step in molecule
  -f, --force                Force close pinned issues or unsatisfied gates
      --no-auto              With --continue, show next step but don't claim it
  -r, --reason string        Reason for closing
      --reason-file string   Read close reason from file (use - for stdin)
      --session string       Claude Code session ID (or set CLAUDE_SESSION_ID env var)
      --suggest-next         Show newly unblocked issues after closing
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc comment`

## bd comment

Add a comment to an issue.

Shorthand for 'bd comments add &lt;id&gt; "text"'.

Examples:
  bd comment bd-123 "Working on this now"
  bd comment bd-123 Working on this now
  echo "comment from pipe" | bd comment bd-123 --stdin
  bd comment bd-123 --file notes.txt

```
bd comment <id> [text...] [flags]
```

**Flags:**

```
      --file string   Read comment text from file
      --stdin         Read comment text from stdin
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc comments`

## bd comments

View or manage comments on an issue.

Examples:
  # List all comments on an issue (issue id is required — there is no "comments list")
  bd comments bd-123

  # List comments in JSON format
  bd comments bd-123 --json

  # Add a comment
  bd comments add bd-123 "This is a comment"

  # Add a comment from a file
  bd comments add bd-123 -f notes.txt

```
bd comments [issue-id] [flags]
```

**Flags:**

```
      --local-time   Show timestamps in local time instead of UTC
```

### bd comments add

Add a comment to an issue.

Examples:
  # Add a comment
  bd comments add bd-123 "Working on this now"

  # Add a comment from a file
  bd comments add bd-123 -f notes.txt

```
bd comments add [issue-id] [text] [flags]
```

**Flags:**

```
  -a, --author string   Add author to comment
  -f, --file string     Read comment text from file
```

### bd comments list

Invalid — use bd comments &lt;issue-id&gt; to list comments

```
bd comments list [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc compact`

## bd compact

Squash Dolt commits older than N days into a single commit.

Recent commits (within the retention window) are preserved via cherry-pick.
This reduces Dolt storage overhead from auto-commit history while keeping
recent change tracking intact.

For semantic issue compaction (summarizing closed issues), use 'bd admin compact'.
For full history squash, use 'bd flatten'.

How it works:
  1. Identifies commits older than --days threshold
  2. Creates a squashed base commit from all old history
  3. Cherry-picks recent commits on top
  4. Swaps main branch to the compacted version
  5. Runs Dolt GC to reclaim space

Examples:
  bd compact --dry-run               # Preview: show commit breakdown
  bd compact --force                 # Squash commits older than 30 days
  bd compact --days 7 --force        # Keep only last 7 days of history
  bd compact --days 90 --force       # Conservative: squash 90+ day old commits

```
bd compact [flags]
```

**Flags:**

```
      --days int   Keep commits newer than N days (default 30)
      --dry-run    Preview without making changes
  -f, --force      Confirm commit squash
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc completion`

## bd completion

Generate the autocompletion script for bd for the specified shell.
See each sub-command's help for details on how to use the generated script.


```
bd completion [flags]
```

### bd completion bash

Generate the autocompletion script for the bash shell.

This script depends on the 'bash-completion' package.
If it is not installed already, you can install it via your OS's package manager.

To load completions in your current shell session:

	source &lt;(bd completion bash)

To load completions for every new session, execute once:

#### Linux:

	bd completion bash &gt; /etc/bash_completion.d/bd

#### macOS:

	bd completion bash &gt; $(brew --prefix)/etc/bash_completion.d/bd

You will need to start a new shell for this setup to take effect.


```
bd completion bash
```

**Flags:**

```
      --no-descriptions   disable completion descriptions
```

### bd completion fish

Generate the autocompletion script for the fish shell.

To load completions in your current shell session:

	bd completion fish | source

To load completions for every new session, execute once:

	bd completion fish &gt; ~/.config/fish/completions/bd.fish

You will need to start a new shell for this setup to take effect.


```
bd completion fish [flags]
```

**Flags:**

```
      --no-descriptions   disable completion descriptions
```

### bd completion powershell

Generate the autocompletion script for powershell.

To load completions in your current shell session:

	bd completion powershell | Out-String | Invoke-Expression

To load completions for every new session, add the output of the above command
to your powershell profile.


```
bd completion powershell [flags]
```

**Flags:**

```
      --no-descriptions   disable completion descriptions
```

### bd completion zsh

Generate the autocompletion script for the zsh shell.

If shell completion is not already enabled in your environment you will need
to enable it.  You can execute the following once:

	echo "autoload -U compinit; compinit" &gt;&gt; ~/.zshrc

To load completions in your current shell session:

	source &lt;(bd completion zsh)

To load completions for every new session, execute once:

#### Linux:

	bd completion zsh &gt; "$&#123;fpath[1]&#125;/_bd"

#### macOS:

	bd completion zsh &gt; $(brew --prefix)/share/zsh/site-functions/_bd

You will need to start a new shell for this setup to take effect.


```
bd completion zsh [flags]
```

**Flags:**

```
      --no-descriptions   disable completion descriptions
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc config`

## bd config

Manage configuration settings for external integrations and preferences.

Configuration is stored per-project in the beads database and is version-control-friendly.

Common namespaces:
  - export.*          Auto-export settings (stored in config.yaml)
  - import.*          JSONL import settings (stored in config.yaml)
  - jira.*            Jira integration settings
  - linear.*          Linear integration settings
  - github.*          GitHub integration settings
  - custom.*          Custom integration settings
  - status.*          Issue status configuration
  - doctor.suppress.* Suppress specific bd doctor warnings (GH#1095)

Auto-Export (config.yaml):
  Optional JSONL export to .beads/issues.jsonl after write commands (throttled).
  Useful for viewers (bv), interchange, and issue-level migration; not a backup.
  It is not cross-machine sync; use bd dolt push/pull with a Dolt remote.
  Disabled by default. Enable only for integrations that need fresh JSONL.
  Auto-staging is separate and disabled by default.

  Keys:
    export.auto       Enable/disable auto-export (default: false)
    export.path       Output filename relative to .beads/ (default: issues.jsonl)
    export.interval   Minimum time between exports (default: 60s)
    export.git-add    Auto-stage the export file (default: false)

Auto-Import (config.yaml):
  Reads .beads/issues.jsonl by default when a JSONL import path is implied.
  Use a relative filename/path so the import stays within the project .beads/
  directory and remains portable across machines.

  Keys:
    import.path       Input filename relative to .beads/ (default: issues.jsonl)

Custom Status States:
  You can define custom status states for multi-step pipelines using the
  status.custom config key. Statuses should be comma-separated.

  Example:
    bd config set status.custom "awaiting_review,awaiting_testing,awaiting_docs"

  This enables issues to use statuses like 'awaiting_review' in addition to
  the built-in statuses (open, in_progress, blocked, deferred, closed).

Suppressing Doctor Warnings:
  Suppress specific bd doctor warnings by check name slug:
    bd config set doctor.suppress.pending-migrations true
    bd config set doctor.suppress.git-hooks true
  Check names are converted to slugs: "Git Hooks" → "git-hooks".
  Only warnings are suppressed (errors and passing checks always show).
  To unsuppress: bd config unset doctor.suppress.&lt;slug&gt;

Examples:
  bd config set export.auto true                       # Enable auto-export for viewer integrations
  bd config set export.path "beads.jsonl"              # Custom export filename
  bd config set import.path "beads.jsonl"              # Custom import filename
  bd config set export.git-add true                    # Also stage the export file
  bd config set jira.url "https://company.atlassian.net"
  bd config set jira.project "PROJ"
  bd config set status.custom "awaiting_review,awaiting_testing"
  bd config set doctor.suppress.pending-migrations true
  bd config set dolt.debug true                        # Enable Dolt sql-server debug mode (loglevel=debug, --prof cpu)
  bd config set dolt.local-only true                   # Skip wiring a Dolt sync remote during bd init
  bd config get export.auto
  bd config list
  bd config unset jira.url

```
bd config [flags]
```

### bd config apply

Reconcile actual system state to match declared configuration.

Runs drift detection and then fixes any mismatches it finds:

  - hooks     Reinstall git hooks if missing or outdated
  - remote    Add/update Dolt origin remote to match federation.remote
  - server    Start Dolt server if dolt.shared-server is enabled

This command is idempotent — safe to run multiple times. Use --dry-run
to preview what would change without making modifications.

Examples:
  bd config apply
  bd config apply --dry-run
  bd config apply --json

```
bd config apply [flags]
```

**Flags:**

```
      --dry-run   Show what would change without making modifications
```

### bd config drift

Detect drift between declared configuration and actual system state.

This is a read-only diagnostic that answers "is my environment consistent
with my config?" — no mutations are performed.

Checks:
  - hooks     Git hooks installed and up-to-date
  - remote    Dolt remote matches federation.remote config
  - server    Server state matches dolt.shared-server config

Exit codes:
  0  No drift detected (all checks ok/info/skipped)
  1  Drift detected (at least one check has status "drift")

Examples:
  bd config drift
  bd config drift --json

```
bd config drift [flags]
```

### bd config get

Get a configuration value

```
bd config get <key> [flags]
```

### bd config list

List all configuration

```
bd config list [flags]
```

### bd config set

Set a configuration value

```
bd config set <key> <value> [flags]
```

**Flags:**

```
      --force-git-tracked   Allow writing secret keys to git-tracked config files (use with caution)
```

### bd config set-many

Set multiple configuration values at once with a single auto-commit and auto-push.

Each argument must be in key=value format. All values are validated before
any writes occur. This is faster and less noisy than separate 'bd config set'
calls, especially in CI.

Examples:
  bd config set-many ado.state_map.open=New ado.state_map.closed=Closed
  bd config set-many jira.url=https://example.atlassian.net jira.project=PROJ

```
bd config set-many <key=value>... [flags]
```

**Flags:**

```
      --force-git-tracked   Allow writing secret keys to git-tracked config files (use with caution)
```

### bd config show

Display a unified view of all effective configuration across all sources
with annotations showing where each value comes from.

Sources (by precedence for Viper-managed keys):
  - env          Environment variable (BD_* or BEADS_*)
  - config.yaml  Project config file (.beads/config.yaml)
  - default      Built-in default value

Additional sources:
  - metadata     Connection settings from .beads/metadata.json
  - database     Integration config stored in the Dolt database
  - git          Git config (e.g., beads.role)

Examples:
  bd config show
  bd config show --json
  bd config show --source config.yaml

```
bd config show [flags]
```

**Flags:**

```
      --source string   Filter by source (e.g., config.yaml, env, default, metadata, database, git)
```

### bd config unset

Delete a configuration value

```
bd config unset <key> [flags]
```

### bd config validate

Validate sync-related configuration settings.

Checks:
  - federation.sovereignty is valid (T1, T2, T3, T4, or empty)
  - federation.remote is set for Dolt sync
  - Remote URL format is valid (dolthub://, gs://, s3://, az://, file://)
  - routing.mode is valid (auto, maintainer, contributor, explicit)

	Examples:
	  bd config validate
	  bd config validate --json

```
bd config validate [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc context`

## bd context

Show the effective backend identity information including repository paths,
backend configuration, and sync settings.

This command reads directly from config files and does not require the
database to be open, making it useful for diagnostics in degraded states.

Examples:
  bd context           # Show context information
  bd context --json    # Output in JSON format


```
bd context [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc cook`

## bd cook

Cook transforms a .formula.json file into a proto.

By default, cook outputs the resolved formula as JSON to stdout for
ephemeral use. The output can be inspected, piped, or saved to a file.

Two cooking modes are available:

  COMPILE-TIME (default, --mode=compile):
    Produces a proto with &#123;&#123;variable&#125;&#125; placeholders intact.
    Use for: modeling, estimation, contractor handoff, planning.
    Variables are NOT substituted - the output shows the template structure.

  RUNTIME (--mode=runtime or when --var flags provided):
    Produces a fully-resolved proto with variables substituted.
    Use for: final validation before pour, seeing exact output.
    Requires all variables to have values (via --var or defaults).

Formulas are high-level workflow templates that support:
  - Variable definitions with defaults and validation
  - Step definitions that become issue hierarchies
  - Composition rules for bonding formulas together
  - Inheritance via extends

The --persist flag enables the legacy behavior of writing the proto
to the database. This is useful when you want to reuse the same
proto multiple times without re-cooking.

For most workflows, prefer ephemeral protos: pour and wisp commands
accept formula names directly and cook inline.

Examples:
  bd cook mol-feature.formula.json                    # Compile-time: keep &#123;&#123;vars&#125;&#125;
  bd cook mol-feature --var name=auth                 # Runtime: substitute vars
  bd cook mol-feature --mode=runtime --var name=auth  # Explicit runtime mode
  bd cook mol-feature --dry-run                       # Preview steps
  bd cook mol-release.formula.json --persist          # Write to database
  bd cook mol-release.formula.json --persist --force  # Replace existing

Output (default):
  JSON representation of the resolved formula with all steps.

Output (--persist):
  Creates a proto bead in the database with:
  - ID matching the formula name (e.g., mol-feature)
  - The "template" label for proto identification
  - Child issues for each step
  - Dependencies matching depends_on relationships

```
bd cook <formula-file> [flags]
```

**Flags:**

```
      --dry-run               Preview what would be created
      --force                 Replace existing proto if it exists (requires --persist)
      --mode string           Cooking mode: compile (keep placeholders) or runtime (substitute vars)
      --persist               Persist proto to database (legacy behavior)
      --prefix string         Prefix to prepend to proto ID (e.g., 'gt-' creates 'gt-mol-feature')
      --search-path strings   Additional paths to search for formula inheritance
      --var stringArray       Variable substitution (key=value), enables runtime mode
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc count`

## bd count

Count issues matching the specified filters.

By default, returns the total count of issues matching the filters.
Use --by-* flags to group counts by different attributes.

Examples:
  bd count                          # Count all issues
  bd count --status open            # Count open issues
  bd count --by-status              # Group count by status
  bd count --by-priority            # Group count by priority
  bd count --by-type                # Group count by issue type
  bd count --by-assignee            # Group count by assignee
  bd count --by-label               # Group count by label
  bd count --assignee alice --by-status  # Count alice's issues by status
  bd count --include-infra          # Count issues + wisps tier (matches 'bd list --include-infra --all' cardinality)


```
bd count [flags]
```

**Flags:**

```
  -a, --assignee string         Filter by assignee
      --by-assignee             Group count by assignee
      --by-label                Group count by label
      --by-priority             Group count by priority
      --by-status               Group count by status
      --by-type                 Group count by issue type
      --closed-after string     Filter issues closed after date (YYYY-MM-DD or RFC3339)
      --closed-before string    Filter issues closed before date (YYYY-MM-DD or RFC3339)
      --created-after string    Filter issues created after date (YYYY-MM-DD or RFC3339)
      --created-before string   Filter issues created before date (YYYY-MM-DD or RFC3339)
      --desc-contains string    Filter by description substring
      --empty-description       Filter issues with empty description
      --id string               Filter by specific issue IDs (comma-separated)
      --include-infra           Include infrastructure beads and the wisps tier (matches 'bd list --include-infra --all' cardinality)
  -l, --label strings           Filter by labels (AND: must have ALL)
      --label-any strings       Filter by labels (OR: must have AT LEAST ONE)
      --no-assignee             Filter issues with no assignee
      --no-labels               Filter issues with no labels
      --notes-contains string   Filter by notes substring
  -p, --priority int            Filter by priority (0-4: 0=critical, 1=high, 2=medium, 3=low, 4=backlog)
      --priority-max int        Filter by maximum priority (inclusive)
      --priority-min int        Filter by minimum priority (inclusive)
  -s, --status string           Filter by stored status (open, in_progress, blocked, deferred, closed). Note: dependency-blocked issues use 'bd blocked'
      --title string            Filter by title text (case-insensitive substring match)
      --title-contains string   Filter by title substring
  -t, --type string             Filter by type (bug, feature, task, epic, chore, decision, merge-request, molecule, gate)
      --updated-after string    Filter issues updated after date (YYYY-MM-DD or RFC3339)
      --updated-before string   Filter issues updated before date (YYYY-MM-DD or RFC3339)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc create-form`

## bd create-form

Create a new issue using an interactive terminal form.

This command provides a user-friendly form interface for creating issues,
with fields for title, description, type, priority, labels, and more.

Use --parent to create a sub-issue under an existing parent issue.
The child will get an auto-generated hierarchical ID (e.g., parent-id.1).

The form uses keyboard navigation:
  - Tab/Shift+Tab: Move between fields
  - Enter: Submit the form (on the last field or submit button)
  - Ctrl+C: Cancel and exit
  - Arrow keys: Navigate within select fields

```
bd create-form [flags]
```

**Flags:**

```
      --parent string   Parent issue ID for creating a hierarchical child (e.g., 'bd-a3f8e9')
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc create`

## bd create

Create a new issue (or batch from markdown/graph JSON)

```
bd create [title] [flags]
```

**Aliases:** new

**Flags:**

```
      --acceptance string       Acceptance criteria
      --append-notes string     Append to existing notes (with newline separator)
  -a, --assignee string         Assignee
      --body-file string        Read description from file (use - for stdin)
      --context string          Additional context for the issue
      --defer string            Defer until date (issue hidden from bd ready until then). Same formats as --due
      --deps strings            Dependencies in format 'type:id' or 'id' (e.g., 'discovered-from:bd-20,blocks:bd-15' or 'bd-20')
  -d, --description string      Issue description
      --design string           Design notes
      --design-file string      Read design from file (use - for stdin)
      --dry-run                 Preview what would be created without actually creating
      --due string              Due date/time. Formats: +6h, +1d, +2w, tomorrow, next monday, 2025-01-15
      --ephemeral               Create as ephemeral (short-lived, subject to TTL compaction)
  -e, --estimate int            Time estimate in minutes (e.g., 60 for 1 hour)
      --event-actor string      Entity URI who caused this event (requires --type=event)
      --event-category string   Event category (e.g., patrol.muted, agent.started) (requires --type=event)
      --event-payload string    Event-specific JSON data (requires --type=event)
      --event-target string     Entity URI or bead ID affected (requires --type=event)
      --external-ref string     External reference (e.g., 'gh-9', 'jira-ABC', Linear URL)
  -f, --file string             Create multiple issues from markdown file
      --force                   Force creation even if prefix doesn't match database prefix
      --graph string            Create a graph of issues with dependencies from JSON plan file
      --id string               Explicit issue ID (e.g., 'bd-42' for partitioning)
  -l, --labels strings          Labels (comma-separated)
      --metadata string         Set custom metadata (JSON string or @file.json to read from file)
      --mol-type string         Molecule type: swarm (multi-agent), patrol (recurring ops), work (default)
      --no-history              Skip Dolt commit history without making GC-eligible (for permanent agent beads)
      --no-inherit-labels       Don't inherit labels from parent issue
      --notes string            Additional notes
      --parent string           Parent issue ID for hierarchical child (e.g., 'bd-a3f8e9')
  -p, --priority string         Priority (0-4 or P0-P4, 0=highest) (default "2")
      --repo string             Target repository for issue (overrides auto-routing)
      --silent                  Output only the issue ID (for scripting)
      --skills string           Required skills for this issue
      --spec-id string          Link to specification document
      --stdin                   Read description from stdin (alias for --body-file -)
      --title string            Issue title (alternative to positional argument)
  -t, --type string             Issue type (bug|feature|task|epic|chore|decision); custom types require types.custom config; aliases: enhancement/feat→feature, dec/adr→decision (default "task")
      --validate                Validate description contains required sections for issue type
      --waits-for string        Spawner issue ID to wait for (creates waits-for dependency for fanout gate)
      --waits-for-gate string   Gate type: all-children (wait for all) or any-children (wait for first) (default "all-children")
      --wisp-type string        Wisp type for TTL-based compaction: heartbeat, ping, patrol, gc_report, recovery, error, escalation
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc defer`

## bd defer

Defer issues to put them on ice for later.

Deferred issues are deliberately set aside - not blocked by anything specific,
just postponed for future consideration. Unlike blocked issues, there's no
dependency keeping them from being worked. Unlike closed issues, they will
be revisited.

Deferred issues don't show in 'bd ready' but remain visible in 'bd list'.

Examples:
  bd defer bd-abc                  # Defer a single issue (status-based)
  bd defer bd-abc --until=tomorrow # Defer until specific time
  bd defer bd-abc --reason="waiting on API access"
  bd defer bd-abc bd-def           # Defer multiple issues

```
bd defer [id...] [flags]
```

**Flags:**

```
      --reason string   Record why this issue is being deferred (appended to notes)
      --until string    Defer until specific time (e.g., +1h, tomorrow, next monday)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc delete`

## bd delete

Delete one or more issues and clean up all references to them.
This command will:
1. Remove all dependency links (any type, both directions) involving the issues
2. Update text references to "[deleted:ID]" in directly connected issues
3. Permanently delete the issues from the database

This is a destructive operation that cannot be undone. Use with caution.

BATCH DELETION:
Delete multiple issues at once:
  bd delete bd-1 bd-2 bd-3 --force

Delete from file (one ID per line):
  bd delete --from-file deletions.txt --force

Preview before deleting:
  bd delete --from-file deletions.txt --dry-run

DEPENDENCY HANDLING:
Default: Fails if any issue has dependents not in deletion set
  bd delete bd-1 bd-2

Cascade: Recursively delete all dependents
  bd delete bd-1 --cascade --force

Force: Delete and orphan dependents
  bd delete bd-1 --force

```
bd delete <issue-id> [issue-id...] [flags]
```

**Flags:**

```
      --cascade            Recursively delete all dependent issues
      --dry-run            Preview what would be deleted without making changes
  -f, --force              Actually delete (without this flag, shows preview)
      --from-file string   Read issue IDs from file (one per line)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc dep`

## bd dep

Manage dependencies between issues.

When called with an issue ID and --blocks flag, creates a blocking dependency:
  bd dep &lt;blocker-id&gt; --blocks &lt;blocked-id&gt;

This is equivalent to:
  bd dep add &lt;blocked-id&gt; &lt;blocker-id&gt;

Examples:
  bd dep bd-xyz --blocks bd-abc    # bd-xyz blocks bd-abc
  bd dep add bd-abc bd-xyz         # Same as above (bd-abc depends on bd-xyz)

```
bd dep [issue-id] [flags]
```

**Flags:**

```
  -b, --blocks string    Issue ID that this issue blocks (shorthand for: bd dep add <blocked> <blocker>)
      --no-cycle-check   Skip per-edge cycle checks for speed (bulk wiring); bulk --file adds still run one final whole-graph check before commit
```

### bd dep add

Add a dependency between two issues.

The depends-on-id can be provided as:
  - A positional argument: bd dep add issue-123 issue-456
  - A flag: bd dep add issue-123 --blocked-by issue-456
  - A flag: bd dep add issue-123 --depends-on issue-456

The --blocked-by and --depends-on flags are aliases and both mean "issue-123
depends on (is blocked by) the specified issue."

The depends-on-id can be:
  - A local issue ID (e.g., bd-xyz)
  - An external reference: external:&lt;project&gt;:&lt;capability&gt;

For bulk wiring, pass newline-delimited JSON with --file. Each line must be an
object with "from" and "to" fields, and may include "type". The aliases
"issue_id" and "depends_on_id" are also accepted. Use --file - to read stdin.

External references are stored as-is and resolved at query time using
the external_projects config. They block the issue until the capability
is "shipped" in the target project.

Examples:
  bd dep add bd-42 bd-41                              # Positional args
  bd dep add bd-42 --blocked-by bd-41                 # Flag syntax (same effect)
  bd dep add bd-42 --depends-on bd-41                 # Alias (same effect)
  bd dep add gt-xyz external:beads:mol-run-assignee   # Cross-project dependency
  bd dep add bd-42 bd-41 --no-cycle-check             # Skip cycle check (bulk wiring)
  bd dep add --file deps.jsonl                        # Bulk JSONL: &#123;"from":"bd-42","to":"bd-41"&#125;

```
bd dep add [issue-id] [depends-on-id] [flags]
```

**Flags:**

```
      --blocked-by string   Issue ID that blocks the first issue (alternative to positional arg)
      --depends-on string   Issue ID that the first issue depends on (alias for --blocked-by)
      --file string         Read dependency edges from JSONL file, or '-' for stdin
      --no-cycle-check      Skip per-edge cycle checks for speed (bulk wiring); bulk --file adds still run one final whole-graph check before commit
  -t, --type string         Dependency type (blocks|tracks|related|parent-child|discovered-from|until|caused-by|validates|relates-to|supersedes) (default "blocks")
```

### bd dep cycles

Detect dependency cycles

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

### bd dep list

List dependencies or dependents of one or more issues with optional type filtering.

By default shows dependencies (what issues depend on). Use --direction to control:
  - down: Show dependencies (what this issue depends on) - default
  - up:   Show dependents (what depends on this issue)

Multiple IDs can be provided for batch dep listing. With --json, the output
is a flat array of dependency records across all requested issues.

Use --type to filter by dependency type (e.g., tracks, blocks, parent-child).

Examples:
  bd dep list gt-abc                     # Show what gt-abc depends on
  bd dep list gt-abc gt-def              # Batch: deps for both issues
  bd dep list gt-abc --direction=up      # Show what depends on gt-abc
  bd dep list gt-abc --direction=up -t tracks  # Show what tracks gt-abc (convoy tracking)

```
bd dep list [issue-id...] [flags]
```

**Flags:**

```
      --direction string   Direction: 'down' (dependencies), 'up' (dependents) (default "down")
  -t, --type string        Filter by dependency type (e.g., tracks, blocks, parent-child)
```

### bd dep relate

Create a loose 'see also' relationship between two issues.

The relates_to link is bidirectional - both issues will reference each other.
This enables knowledge graph connections without blocking or hierarchy.

Examples:
  bd relate bd-abc bd-xyz    # Link two related issues
  bd relate bd-123 bd-456    # Create see-also connection

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

### bd dep remove

Remove a dependency

```
bd dep remove [issue-id] [depends-on-id] [flags]
```

**Aliases:** rm

### bd dep tree

Show dependency tree rooted at the given issue.

By default, shows dependencies (what blocks this issue). Use --direction to control:
  - down: Show dependencies (what blocks this issue) - default
  - up:   Show dependents (what this issue blocks)
  - both: Show full graph in both directions

Examples:
  bd dep tree gt-0iqq                    # Show what blocks gt-0iqq
  bd dep tree gt-0iqq --direction=up     # Show what gt-0iqq blocks
  bd dep tree gt-0iqq --status=open      # Only show open issues
  bd dep tree gt-0iqq --depth=3          # Limit to 3 levels deep

```
bd dep tree [issue-id] [flags]
```

**Flags:**

```
      --direction string   Tree direction: 'down' (dependencies), 'up' (dependents), or 'both'
      --format string      Output format: 'mermaid' for Mermaid.js flowchart
  -d, --max-depth int      Maximum tree depth to display (safety limit) (default 50)
      --reverse            Show dependent tree (deprecated: use --direction=up)
      --show-all-paths     Show all paths to nodes (no deduplication for diamond dependencies)
      --status string      Filter to only show issues with this status (open, in_progress, blocked, deferred, closed)
```

### bd dep unrelate

Remove a relates_to relationship between two issues.

Removes the link in both directions.

Example:
  bd unrelate bd-abc bd-xyz

```
bd dep unrelate <id1> <id2> [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc diff`

## bd diff

Show the differences in issues between two commits or branches.

The refs can be:
- Commit hashes (e.g., abc123def)
- Branch names (e.g., main, feature-branch)
- Special refs like HEAD, HEAD~1

Examples:
  bd diff main feature-branch   # Compare main to feature branch
  bd diff HEAD~5 HEAD           # Show changes in last 5 commits
  bd diff abc123 def456         # Compare two specific commits

```
bd diff <from-ref> <to-ref> [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc doctor`

## bd doctor

Sanity check the beads installation for the current directory or specified path.

This command checks:
  - If .beads/ directory exists
  - Database version and migration status
  - Schema compatibility (all required tables and columns present)
  - Whether using hash-based vs sequential IDs
  - If CLI version is current (checks GitHub releases)
  - If Claude plugin is current (when running in Claude Code)
  - File permissions
  - Circular dependencies
  - Git hooks (pre-commit, post-merge, pre-push)
  - .beads/.gitignore up to date
  - Metadata.json version tracking (LastBdVersion field)

Performance Mode (--perf):
  Run performance diagnostics on your database:
  - Times key operations (bd ready, bd list, bd show, etc.)
  - Collects system info (OS, arch, SQLite version, database stats)
  - Generates CPU profile for analysis
  - Outputs shareable report for bug reports

Export Mode (--output):
  Save diagnostics to a JSON file for historical analysis and bug reporting.
  Includes timestamp and platform info for tracking intermittent issues.

Specific Check Mode (--check):
  Run a specific check in detail. Available checks:
  - artifacts: Detect and optionally clean beads classic artifacts
    (stale JSONL, SQLite files, cruft .beads dirs). Use with --clean.
  - conventions: Check for convention drift (lint warnings, stale
    issues, orphaned issues). Advisory only - warns, never blocks.
  - pollution: Detect and optionally clean test issues from database
  - validate: Run focused data-integrity checks (duplicates, orphaned
    deps, test pollution, git conflicts). Use with --fix to auto-repair.

Deep Validation Mode (--deep):
  Validate full graph integrity. May be slow on large databases.
  Additional checks:
  - Parent consistency: All parent-child deps point to existing issues
  - Dependency integrity: All deps reference valid issues
  - Epic completeness: Find epics ready to close (all children closed)
  - Agent bead integrity: Agent beads have valid state values
  - Mail thread integrity: Thread IDs reference existing issues
  - Molecule integrity: Molecules have valid parent-child structures

Server Mode (--server):
  Run health checks for Dolt server mode connections (bd-dolt.2.3):
  - Server reachable: Can connect to configured host:port?
  - Dolt version: Is it a Dolt server (not vanilla MySQL)?
  - Database exists: Does the 'beads' database exist?
  - Schema compatible: Can query beads tables?
  - Connection pool: Pool health metrics

Migration Validation Mode (--migration):
  Run Dolt migration validation checks with machine-parseable output.
  Use --migration=pre before migration to verify readiness:
  - JSONL file exists and is valid (parseable, no corruption)
  - All JSONL issues are present in SQLite (or explains discrepancies)
  - No blocking issues prevent migration
  Use --migration=post after migration to verify completion:
  - Dolt database exists and is healthy
  - All issues from JSONL are present in Dolt
  - No data was lost during migration
  - Dolt database has no locks or uncommitted changes
  Combine with --json for machine-parseable output for automation.

Agent Mode (--agent):
  Output diagnostics designed for AI agent consumption. Instead of terse
  pass/fail messages, each issue includes:
  - Observed state: what the system actually looks like
  - Expected state: what it should look like
  - Explanation: full prose context about the issue and why it matters
  - Commands: exact remediation commands to run
  - Source files: where in the codebase to investigate further
  - Severity: blocking (prevents operation), degraded (partial function),
    or advisory (informational only)
  ZFC-compliant: Go observes and reports, the agent decides and acts.
  Combine with --json for structured agent-facing output.

Suppressing Warnings:
  Suppress specific warnings by setting doctor.suppress.&lt;check-slug&gt; config:
    bd config set doctor.suppress.pending-migrations true
    bd config set doctor.suppress.git-hooks true
  Check names are converted to slugs: "Git Hooks" → "git-hooks".
  Only warnings are suppressed; errors and passing checks always show.
  To unsuppress: bd config unset doctor.suppress.&lt;slug&gt;

Examples:
  bd doctor              # Check current directory
  bd doctor /path/to/repo # Check specific repository
  bd doctor --json       # Machine-readable output
  bd doctor --agent      # Agent-facing diagnostic output
  bd doctor --agent --json  # Structured agent diagnostics (JSON)
  bd doctor --fix        # Automatically fix issues (with confirmation)
  bd doctor --fix --yes  # Automatically fix issues (no confirmation)
  bd doctor --fix -i     # Confirm each fix individually
  bd doctor --fix --fix-child-parent  # Also fix child→parent deps (opt-in)
  bd doctor --fix --force # Force repair even when database can't be opened
  bd doctor --fix --source=jsonl # Rebuild database from a JSONL export
  bd doctor --dry-run    # Preview what --fix would do without making changes
  bd doctor --perf       # Performance diagnostics
  bd doctor --output diagnostics.json  # Export diagnostics to file
  bd doctor --check=artifacts           # Show classic artifacts (JSONL, SQLite, cruft dirs)
  bd doctor --check=artifacts --clean  # Delete safe-to-delete artifacts (with confirmation)
  bd doctor --check=conventions        # Convention drift check (lint, stale, orphans)
  bd doctor --check=pollution          # Show potential test issues
  bd doctor --check=pollution --clean  # Delete test issues (with confirmation)
  bd doctor --check=validate         # Data-integrity checks only
  bd doctor --check=validate --fix   # Auto-fix data-integrity issues
  bd doctor --deep             # Full graph integrity validation
  bd doctor --server           # Dolt server mode health checks
  bd doctor --migration=pre    # Validate readiness for Dolt migration
  bd doctor --migration=post   # Validate Dolt migration completed
  bd doctor --migration=pre --json  # Machine-parseable migration validation

```
bd doctor [path] [flags]
```

**Flags:**

```
      --agent                                   Agent-facing diagnostic mode: rich context for AI agents (ZFC-compliant)
      --check string                            Run specific check in detail (e.g., 'pollution')
      --check-health                            Quick health check for git hooks (silent on success)
      --clean                                   For pollution check: delete detected test issues
      --deep                                    Validate full graph integrity
      --dry-run                                 Preview fixes without making changes
      --fix                                     Automatically fix issues where possible
      --fix-child-parent                        Remove child→parent dependencies (opt-in)
  -i, --interactive                             Confirm each fix individually
      --migration string                        Run Dolt migration validation: 'pre' (before migration) or 'post' (after migration)
      --orchestrator                            Running in orchestrator multi-workspace mode (routes.jsonl is expected, higher duplicate tolerance)
      --orchestrator-duplicates-threshold int   Duplicate tolerance threshold for orchestrator mode (wisps are ephemeral) (default 1000)
  -o, --output string                           Export diagnostics to JSON file
      --perf                                    Run performance diagnostics and generate CPU profile
      --server                                  Run Dolt server mode health checks (connectivity, version, schema)
  -v, --verbose                                 Show all checks (default shows only warnings/errors)
  -y, --yes                                     Skip confirmation prompt (for non-interactive use)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc dolt`

## bd dolt

Configure and manage Dolt database settings and server lifecycle.

Beads uses a dolt sql-server for all database operations. The server is
auto-started transparently when needed. Use these commands for explicit
control or diagnostics.

Server lifecycle:
  bd dolt start        Start the Dolt server for this project
  bd dolt stop         Stop the Dolt server for this project
  bd dolt status       Show Dolt server status

Configuration:
  bd dolt show         Show current Dolt configuration with connection test
  bd dolt set &lt;k&gt; &lt;v&gt;  Set a configuration value
  bd dolt test         Test server connection

Version control:
  bd dolt commit       Commit pending changes
  bd dolt push         Push commits to Dolt remote
  bd dolt pull         Pull commits from Dolt remote

Remote management:
  bd dolt remote add &lt;name&gt; &lt;url&gt;   Add a Dolt remote
  bd dolt remote list                List configured remotes
  bd dolt remote remove &lt;name&gt;       Remove a Dolt remote

Configuration keys for 'bd dolt set':
  database  Database name (default: issue prefix or "beads")
  host      Server host (default: 127.0.0.1)
  port      Server port (auto-detected; override with bd dolt set port &lt;N&gt;)
  user      MySQL user (default: root)
  data-dir  Custom dolt data directory (absolute path; default: .beads/dolt)

Flags for 'bd dolt set':
  --update-config  Also write to config.yaml for team-wide defaults

Examples:
  bd dolt set database myproject
  bd dolt set host 192.168.1.100 --update-config
  bd dolt set data-dir /home/user/.beads-dolt/myproject
  bd dolt test

```
bd dolt [flags]
```

### bd dolt clean-databases

Identify and drop leftover test and agent databases that accumulate
on the shared Dolt server from interrupted test runs and terminated agents.

Stale database prefixes: testdb_*, doctest_*, doctortest_*, beads_pt*, beads_vr*, beads_t*

These waste server memory and can degrade performance under concurrent load.
Use --dry-run to see what would be dropped without actually dropping.

```
bd dolt clean-databases [flags]
```

**Flags:**

```
      --dry-run   Show what would be dropped without dropping
```

### bd dolt commit

Create a Dolt commit from any uncommitted changes in the working set.

This is the primary commit point for batch mode. When auto-commit is set to
"batch", changes accumulate in the working set across multiple bd commands and
are committed together here with a descriptive summary message.

Also useful before push operations that require a clean working set, or when
auto-commit was off or changes were made externally.

For more options (--stdin, custom messages), see: bd vc commit

```
bd dolt commit [flags]
```

**Flags:**

```
  -m, --message string   Commit message (default: auto-generated)
```

### bd dolt killall

Find and kill orphan dolt sql-server processes not tracked by the
canonical PID file for the current repo's Dolt data directory.

Under an orchestrator, the canonical server lives at $GT_ROOT/.beads/. Any other
dolt sql-server processes using that shared data directory are considered
orphans and will be killed.

In standalone mode, only dolt sql-server processes using the current
project's Dolt data directory are eligible for cleanup. Other projects'
servers are preserved.

```
bd dolt killall [flags]
```

### bd dolt pull

Pull commits from the configured Dolt remote into the local database.

Requires a Dolt remote to be configured in the database directory.
For Hosted Dolt, set DOLT_REMOTE_USER and DOLT_REMOTE_PASSWORD environment
variables for authentication.

Use --remote to pull from a specific named remote instead of the default.
The remote must already exist (see 'bd dolt remote add').

```
bd dolt pull [flags]
```

**Flags:**

```
      --remote string   Pull from a specific named remote instead of the default
```

### bd dolt push

Push local Dolt commits to the configured remote.

Requires a Dolt remote to be configured in the database directory.
For Hosted Dolt, set DOLT_REMOTE_USER and DOLT_REMOTE_PASSWORD environment
variables for authentication.

Use --force to overwrite remote changes (e.g., when the remote has
uncommitted changes in its working set).

Use --remote to push to a specific named remote instead of the default.
The remote must already exist (see 'bd dolt remote add').

```
bd dolt push [flags]
```

**Flags:**

```
      --force           Force push (overwrite remote changes)
      --remote string   Push to a specific named remote instead of the default
```

### bd dolt remote

Manage Dolt remotes for push/pull replication.

Subcommands:
  add &lt;name&gt; &lt;url&gt;   Add a new remote
  list               List all configured remotes
  remove &lt;name&gt;      Remove a remote

```
bd dolt remote [flags]
```

#### bd dolt remote add

Add a Dolt remote

```
bd dolt remote add <name> <url> [flags]
```

#### bd dolt remote list

List configured Dolt remotes

```
bd dolt remote list [flags]
```

#### bd dolt remote remove

Remove a Dolt remote

```
bd dolt remote remove <name> [flags]
```

### bd dolt set

Set a Dolt configuration value in metadata.json.

Keys:
  database  Database name (default: issue prefix or "beads")
  host      Server host (default: 127.0.0.1)
  port      Server port (auto-detected; override with bd dolt set port &lt;N&gt;)
  user      MySQL user (default: root)
  data-dir  Custom dolt data directory (absolute path; default: .beads/dolt)

Use --update-config to also write to config.yaml for team-wide defaults.

Examples:
  bd dolt set database myproject
  bd dolt set host 192.168.1.100
  bd dolt set port 3307 --update-config
  bd dolt set data-dir /home/user/.beads-dolt/myproject

```
bd dolt set <key> <value> [flags]
```

**Flags:**

```
      --update-config   Also write to config.yaml for team-wide defaults
```

### bd dolt show

Show current Dolt configuration with connection status

```
bd dolt show [flags]
```

### bd dolt start

Start a dolt sql-server for the current beads project.

The server runs in the background on a per-project port derived from the
project path. PID and logs are stored in .beads/.

The server auto-starts transparently when needed, so manual start is rarely
required. Use this command for explicit control or diagnostics.

```
bd dolt start [flags]
```

### bd dolt status

Show the status of the Dolt engine for the current project.

In embedded mode, reports that the Dolt engine runs in-process and shows
the on-disk data directory. For beads-managed (local) servers, displays
PID, port, and data directory from the local PID file. For externally-
managed servers — either a remote dolt_server_host or a local server
managed outside bd (dolt.auto-start: false, e.g. an orchestrator-shared
sql-server) — pings the configured endpoint via SQL and reports
reachability, server version, and database.

```
bd dolt status [flags]
```

### bd dolt stop

Stop the dolt sql-server managed by beads for the current project.

This sends a graceful shutdown signal. The server will restart automatically
on the next bd command unless auto-start is disabled.

```
bd dolt stop [flags]
```

**Flags:**

```
      --force   Force stop the server
```

### bd dolt test

Test the connection to the configured Dolt server.

This verifies that:
  1. The server is reachable at the configured host:port
  2. The connection can be established

Use this before switching to server mode to ensure the server is running.

```
bd dolt test [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc duplicate`

## bd duplicate

Mark an issue as a duplicate of a canonical issue.

The duplicate issue is automatically closed with a reference to the canonical.
This is essential for large issue databases with many similar reports.

Examples:
  bd duplicate bd-abc --of bd-xyz    # Mark bd-abc as duplicate of bd-xyz

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

**Flags:**

```
      --of string   Canonical issue ID (required)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc duplicates`

## bd duplicates

Find issues with identical content (title, description, design, acceptance criteria).
Groups issues by content hash and reports duplicates with suggested merge targets.
The merge target is chosen by:
1. Reference count (most referenced issue wins)
2. Lexicographically smallest ID if reference counts are equal
Only groups issues with matching status (open with open, closed with closed).
Example:
  bd duplicates                    # Show all duplicate groups
  bd duplicates --auto-merge       # Automatically merge all duplicates
  bd duplicates --dry-run          # Show what would be merged

```
bd duplicates [flags]
```

**Flags:**

```
      --auto-merge   Automatically merge all duplicates
      --dry-run      Show what would be merged without making changes
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc edit`

## bd edit

Edit an issue field using your configured $EDITOR.

By default, edits the description. Use flags to edit other fields.

Examples:
  bd edit bd-42                    # Edit description
  bd edit bd-42 --title            # Edit title
  bd edit bd-42 --design           # Edit design notes
  bd edit bd-42 --notes            # Edit notes
  bd edit bd-42 --acceptance       # Edit acceptance criteria

```
bd edit [id] [flags]
```

**Flags:**

```
      --acceptance    Edit the acceptance criteria
      --description   Edit the description (default)
      --design        Edit the design notes
      --notes         Edit the notes
      --title         Edit the title
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc epic`

## bd epic

Epic management commands

```
bd epic [flags]
```

### bd epic close-eligible

Close epics where all children are complete

```
bd epic close-eligible [flags]
```

**Flags:**

```
      --dry-run   Preview what would be closed without making changes
```

### bd epic status

Show epic completion status

```
bd epic status [flags]
```

**Flags:**

```
      --eligible-only   Show only epics eligible for closure
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc export`

## bd export

Export all issues to JSONL (newline-delimited JSON) format.

Each line is a complete JSON object representing one issue, including its
labels, dependencies, and comments.

This command is for issue export, migration, and interoperability. It exports
records from the issues table; it is not a full database backup and does not
capture Dolt branches, commit history, working-set state, or non-issue tables.
For supported full backup/restore flows, use 'bd backup init', 'bd backup sync',
and 'bd backup restore'.

By default, exports only regular issues (excluding infrastructure beads
like agents, roles, and messages). Use --all to include everything.

Memories (from 'bd remember') are excluded by default because they may
contain sensitive agent context. Use --include-memories or --all to
include them.

EXAMPLES:
  bd export                              # Export issues to stdout
  bd export -o issues.jsonl              # Export issues to file
  bd export --include-memories           # Export issues + memories
  bd export --all -o full.jsonl          # Include infra + templates + gates + memories
  bd export --scrub -o clean.jsonl       # Exclude test/pollution records

```
bd export [flags]
```

**Flags:**

```
      --all                Include all records (infra, templates, gates, memories)
      --include-infra      Include infrastructure beads (agents, roles, messages)
      --include-memories   Include persistent memories (from 'bd remember') in the export
  -o, --output string      Output file path (default: stdout)
      --scrub              Exclude test/pollution records
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc federation`

## bd federation

Federation commands require CGO and the Dolt storage backend.

This binary was built without CGO support. To use federation features:
  1. Use pre-built binaries from GitHub releases, or
  2. Build from source with CGO enabled

Federation enables synchronized issue tracking across multiple workspaces,
each maintaining their own Dolt database while sharing updates via remotes.

```
bd federation [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc find-duplicates`

## bd find-duplicates

Find issues that are semantically similar but not exact duplicates.

Unlike 'bd duplicates' which finds exact content matches, find-duplicates
uses text similarity or AI to find issues that discuss the same topic
with different wording.

Approaches:
  mechanical  Token-based text similarity (default, no API key needed)
  ai          LLM-based semantic comparison (requires ANTHROPIC_API_KEY or ai.api_key)

The mechanical approach tokenizes titles and descriptions, then computes
Jaccard similarity between all issue pairs. It's fast and free but may
miss semantically similar issues with very different wording.

The AI approach sends candidate pairs to Claude for semantic comparison.
It first uses mechanical pre-filtering to reduce the number of API calls,
then asks the LLM to judge whether the remaining pairs are true duplicates.

Examples:
  bd find-duplicates                       # Mechanical similarity (default)
  bd find-duplicates --threshold 0.4       # Lower threshold = more results
  bd find-duplicates --method ai           # Use AI for semantic comparison
  bd find-duplicates --status open         # Only check open issues
  bd find-duplicates --limit 20            # Show top 20 pairs
  bd find-duplicates --json                # JSON output

```
bd find-duplicates [flags]
```

**Aliases:** find-dups

**Flags:**

```
  -n, --limit int         Maximum number of pairs to show (default 50)
      --method string     Detection method: mechanical, ai (default "mechanical")
      --model string      AI model to use (only with --method ai; default from config ai.model)
  -s, --status string     Filter by status (default: non-closed)
      --threshold float   Similarity threshold (0.0-1.0, lower = more results) (default 0.5)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc flatten`

## bd flatten

Nuclear option: squash ALL Dolt commit history into a single commit.

This uses the Tim Sehn recipe:
  1. Create a new branch from the current state
  2. Soft-reset to the initial commit (preserving all data)
  3. Commit everything as a single snapshot
  4. Swap main branch to the new flattened branch
  5. Run Dolt GC to reclaim space from old history

This is irreversible — all commit history is lost. The resulting database
has exactly one commit containing all current data.

Use this when:
  - Your .beads/dolt directory has grown very large
  - You don't need commit-level history (time travel)
  - You want to start fresh with minimal storage

Examples:
  bd flatten --dry-run               # Preview: show commit count and disk usage
  bd flatten --force                 # Actually squash all history
  bd flatten --force --json          # JSON output

```
bd flatten [flags]
```

**Flags:**

```
      --dry-run   Preview without making changes
  -f, --force     Confirm irreversible history squash
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc forget`

## bd forget

Remove a memory by its key.

Use 'bd memories' to see available keys.

Examples:
  bd forget dolt-phantoms
  bd forget auth-jwt

```
bd forget <key> [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc formula`

## bd formula

Manage workflow formulas - the source layer for molecule templates.

Formulas are TOML/JSON files that define workflows with composition rules.
Define formulas, cook them into protos, then pour or wisp them into work.

Search paths (in order):
  1. &lt;resolved-beads-dir&gt;/formulas/ (active project)
  2. &lt;checkout-root&gt;/.beads/formulas/ (repo-local formulas)
  3. ~/.beads/formulas/ (user)
  4. $GT_ROOT/.beads/formulas/ (shared workspace root, if GT_ROOT set)

Commands:
  list   List available formulas from all search paths
  show   Show formula details, steps, and composition rules

```
bd formula [flags]
```

### bd formula convert

Convert formula files from JSON to TOML format.

TOML format provides better ergonomics:
  - Multi-line strings without \n escaping
  - Human-readable diffs
  - Comments allowed

The convert command reads a .formula.json file and outputs .formula.toml.
The original JSON file is preserved (use --delete to remove it).

Examples:
  bd formula convert shiny              # Convert shiny.formula.json to .toml
  bd formula convert ./my.formula.json  # Convert specific file
  bd formula convert --all              # Convert all JSON formulas
  bd formula convert shiny --delete     # Convert and remove JSON file
  bd formula convert shiny --stdout     # Print TOML to stdout

```
bd formula convert <formula-name|path> [--all] [flags]
```

**Flags:**

```
      --all      Convert all JSON formulas
      --delete   Delete JSON file after conversion
      --stdout   Print TOML to stdout instead of file
```

### bd formula list

List all formulas from search paths.

Search paths (in order of priority):
  1. &lt;resolved-beads-dir&gt;/formulas/ (active project - highest priority)
  2. &lt;checkout-root&gt;/.beads/formulas/ (repo-local formulas)
  3. ~/.beads/formulas/ (user)
  4. $GT_ROOT/.beads/formulas/ (shared workspace root, if GT_ROOT set)

Formulas in earlier paths shadow those with the same name in later paths.

Examples:
  bd formula list
  bd formula list --json
  bd formula list --type workflow
  bd formula list --type convoy

```
bd formula list [flags]
```

**Flags:**

```
      --type string   Filter by type (workflow, expansion, aspect, convoy)
```

### bd formula show

Show detailed information about a formula.

Displays:
  - Formula metadata (name, type, description)
  - Variables with defaults and constraints
  - Steps with dependencies
  - Composition rules (extends, aspects, expansions)
  - Bond points for external composition

Examples:
  bd formula show shiny
  bd formula show rule-of-five
  bd formula show security-audit --json

```
bd formula show <formula-name> [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc gate`

## bd gate

Gates are async wait conditions that block workflow steps.

Gates are created automatically when a formula step has a gate field.
They must be closed (manually or via watchers) for the blocked step to proceed.

Gate types:
  human   - Requires manual bd close (Phase 1)
  timer   - Expires after timeout (Phase 2)
  gh:run  - Waits for GitHub workflow (Phase 3)
  gh:pr   - Waits for PR merge (Phase 3)
  bead    - Waits for cross-rig bead to close (Phase 4)

For bead gates, await_id format is &lt;rig&gt;:&lt;bead-id&gt; (e.g., "other-project:op-abc123").

Examples:
  bd gate list           # Show all open gates
  bd gate list --all     # Show all gates including closed
  bd gate check          # Evaluate all open gates
  bd gate check --type=bead  # Evaluate only bead gates
  bd gate resolve &lt;id&gt;   # Close a gate manually

```
bd gate [flags]
```

### bd gate add-waiter

Register an agent as a waiter on a gate bead.

When the gate closes, the waiter will receive a wake notification via 'bd gate wake'.
The waiter is typically the worker's address (e.g., "my-project/workers/agent-1").

This is used by 'bd done --phase-complete' to register for gate wake notifications.

```
bd gate add-waiter <gate-id> <waiter> [flags]
```

### bd gate check

Evaluate gate conditions and automatically close resolved gates.

By default, checks all open gates. Use --type to filter by gate type.

Gate types:
  gh       - Check all GitHub gates (gh:run and gh:pr)
  gh:run   - Check GitHub Actions workflow runs
  gh:pr    - Check pull request merge status
  timer    - Check timer gates (auto-expire based on timeout)
  bead     - Check cross-rig bead gates
  all      - Check all gate types

GitHub gates use the 'gh' CLI to query status:
  - gh:run checks 'gh run view &lt;id&gt; --json status,conclusion'
  - gh:pr checks 'gh pr view &lt;id&gt; --json state,title'

A gate is resolved when:
  - gh:run: status=completed AND conclusion=success
  - gh:pr: state=MERGED
  - timer: current time &gt; created_at + timeout
  - bead: target bead status=closed

A gate is escalated when:
  - gh:run: status=completed AND conclusion in (failure, canceled)
  - gh:pr: state=CLOSED

Examples:
  bd gate check              # Check all gates
  bd gate check --type=gh    # Check only GitHub gates
  bd gate check --type=gh:run # Check only workflow run gates
  bd gate check --type=timer # Check only timer gates
  bd gate check --type=bead  # Check only cross-rig bead gates
  bd gate check --dry-run    # Show what would happen without changes
  bd gate check --escalate   # Escalate expired/failed gates

```
bd gate check [flags]
```

**Flags:**

```
      --dry-run       Show what would happen without making changes
  -e, --escalate      Escalate failed/expired gates
  -l, --limit int     Limit results (default 100) (default 100)
  -t, --type string   Gate type to check (gh, gh:run, gh:pr, timer, bead, all)
```

### bd gate create

Create an ad-hoc gate issue that blocks another issue until resolved.

The blocked issue will not appear in 'bd ready' until the gate is resolved
via 'bd gate resolve'.

Gate types:
  human   - Requires manual 'bd gate resolve' (default)
  timer   - Auto-resolves after --timeout duration
  gh:run  - Waits for GitHub Actions workflow
  gh:pr   - Waits for PR merge

Examples:
  bd gate create --blocks bd-abc
  bd gate create --type=human --blocks bd-abc --reason="Need design review"
  bd gate create --type=timer --blocks bd-abc --timeout=2h
  bd gate create --type=gh:pr --blocks bd-abc --await-id=42

```
bd gate create [flags]
```

**Flags:**

```
      --await-id string   Condition identifier (run ID, PR number, etc.)
      --blocks string     Issue ID to block (required)
  -r, --reason string     Reason for the gate
      --timeout string    Timeout duration (e.g., 2h, 30m)
  -t, --type string       Gate type (human, timer, gh:run, gh:pr) (default "human")
```

### bd gate discover

Discovers GitHub workflow run IDs for gates awaiting CI/CD completion.

This command finds open gates with await_type="gh:run" that don't have an await_id,
queries recent GitHub workflow runs, and matches them using heuristics:
  - Branch name matching
  - Commit SHA matching
  - Time proximity (runs within 5 minutes of gate creation)

Once matched, the gate's await_id is updated with the GitHub run ID, enabling
subsequent polling to check the run's status.

Examples:
  bd gate discover           # Auto-discover run IDs for all matching gates
  bd gate discover --dry-run # Preview what would be matched (no updates)
  bd gate discover --branch main --limit 10  # Only match runs on 'main' branch

```
bd gate discover [flags]
```

**Flags:**

```
  -b, --branch string      Filter runs by branch (default: current branch)
  -n, --dry-run            Preview mode: show matches without updating
  -l, --limit int          Max runs to query from GitHub (default 10)
  -a, --max-age duration   Max age for gate/run matching (default 30m0s)
```

### bd gate list

List all gate issues in the current beads database.

By default, shows only open gates. Use --all to include closed gates.

```
bd gate list [flags]
```

**Flags:**

```
  -a, --all         Show all gates including closed
  -n, --limit int   Limit results (default 50) (default 50)
```

### bd gate resolve

Close a gate issue to unblock the step waiting on it.

This is equivalent to 'bd close &lt;gate-id&gt;' but with a more explicit name.
Use --reason to provide context for why the gate was resolved.

```
bd gate resolve <gate-id> [flags]
```

**Flags:**

```
  -r, --reason string   Reason for resolving the gate
```

### bd gate show

Display details of a gate issue including its waiters.

This is similar to 'bd show' but validates that the issue is a gate.

```
bd gate show <gate-id> [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc gc`

## bd gc

Full lifecycle garbage collection for standalone Beads databases.

Runs three phases in sequence:
  1. DECAY   — Delete closed issues older than N days (default 90)
  2. COMPACT — Squash old Dolt commits into fewer commits (bd compact)
  3. GC      — Run Dolt garbage collection to reclaim disk space

Each phase can be skipped individually. Use --dry-run to preview all phases
without making changes.

Examples:
  bd gc                              # Full GC with defaults (90 day decay)
  bd gc --dry-run                    # Preview what would happen
  bd gc --older-than 30              # Decay issues closed 30+ days ago
  bd gc --skip-decay                 # Skip issue deletion, just compact+GC
  bd gc --skip-dolt                  # Skip Dolt GC, just decay+compact
  bd gc --force                      # Skip confirmation prompt

```
bd gc [flags]
```

**Flags:**

```
      --dry-run          Preview without making changes
  -f, --force            Skip confirmation prompts
      --older-than int   Delete closed issues older than N days (default 90)
      --skip-decay       Skip issue deletion phase
      --skip-dolt        Skip Dolt garbage collection phase
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc github`

## bd github

Commands for syncing issues between beads and GitHub.

Configuration can be set via 'bd config' or environment variables:
  github.token / GITHUB_TOKEN           - Personal access token
  github.owner / GITHUB_OWNER           - Repository owner
  github.repo / GITHUB_REPO             - Repository name
  github.repository / GITHUB_REPOSITORY - Combined "owner/repo" format
  github.url / GITHUB_API_URL           - Custom API URL (GitHub Enterprise)

```
bd github [flags]
```

### bd github pull

Pull one or more items from GitHub.

Accepts bead IDs or external references as positional arguments.
Equivalent to: bd github sync --pull-only --issues &lt;refs&gt;

```
bd github pull [refs...] [flags]
```

**Flags:**

```
      --dry-run   Preview pull without making changes
```

### bd github push

Push one or more beads issues to GitHub.

Accepts bead IDs as positional arguments.
Equivalent to: bd github sync --push-only --issues &lt;ids&gt;

```
bd github push [bead-ids...] [flags]
```

**Flags:**

```
      --dry-run   Preview push without making changes
```

### bd github repos

List GitHub repositories that the configured token has access to.

```
bd github repos [flags]
```

### bd github status

Display current GitHub configuration and sync status.

```
bd github status [flags]
```

### bd github sync

Synchronize issues between beads and GitHub.

By default, performs bidirectional sync:
- Pulls new/updated issues from GitHub to beads
- Pushes local beads issues to GitHub

Use --pull-only or --push-only to limit direction.

```
bd github sync [flags]
```

**Flags:**

```
      --dry-run         Show what would be synced without making changes
      --issues string   Comma-separated bead IDs to sync selectively (e.g., bd-abc,bd-def). Mutually exclusive with --parent.
      --parent string   Limit push to this bead and its descendants (push only). Mutually exclusive with --issues.
      --prefer-github   On conflict, use GitHub version
      --prefer-local    On conflict, keep local beads version
      --prefer-newer    On conflict, use most recent version (default)
      --pull-only       Only pull issues from GitHub
      --push-only       Only push issues to GitHub
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc gitlab`

## bd gitlab

Commands for syncing issues between beads and GitLab.

Configuration can be set via 'bd config' or environment variables:
  gitlab.url / GITLAB_URL                         - GitLab instance URL
  gitlab.token / GITLAB_TOKEN                     - Personal access token
  gitlab.project_id / GITLAB_PROJECT_ID           - Project ID or path
  gitlab.group_id / GITLAB_GROUP_ID               - Group ID for group-level sync
  gitlab.default_project_id / GITLAB_DEFAULT_PROJECT_ID - Project for creating issues in group mode

```
bd gitlab [flags]
```

### bd gitlab projects

List GitLab projects that the configured token has access to.

```
bd gitlab projects [flags]
```

### bd gitlab pull

Pull one or more items from GitLab.

Accepts bead IDs or external references as positional arguments.
Equivalent to: bd gitlab sync --pull-only --issues &lt;refs&gt;

```
bd gitlab pull [refs...] [flags]
```

**Flags:**

```
      --dry-run   Preview pull without making changes
```

### bd gitlab push

Push one or more beads issues to GitLab.

Accepts bead IDs as positional arguments.
Equivalent to: bd gitlab sync --push-only --issues &lt;ids&gt;

```
bd gitlab push [bead-ids...] [flags]
```

**Flags:**

```
      --dry-run   Preview push without making changes
```

### bd gitlab status

Display current GitLab configuration and sync status.

```
bd gitlab status [flags]
```

### bd gitlab sync

Synchronize issues between beads and GitLab.

By default, performs bidirectional sync:
- Pulls new/updated issues from GitLab to beads
- Pushes local beads issues to GitLab

Use --pull-only or --push-only to limit direction.

```
bd gitlab sync [flags]
```

**Flags:**

```
      --assignee string       Filter by assignee username
      --dry-run               Show what would be synced without making changes
      --exclude-type string   Exclude these issue types from sync (comma-separated)
      --issues string         Comma-separated bead IDs to sync selectively (e.g., bd-abc,bd-def). Mutually exclusive with --parent.
      --label string          Filter by labels (comma-separated, AND logic)
      --milestone string      Filter by milestone title
      --no-ephemeral          Exclude ephemeral/wisp issues from push (default: true) (default true)
      --parent string         Limit push to this bead and its descendants (push only). Mutually exclusive with --issues.
      --prefer-gitlab         On conflict, use GitLab version
      --prefer-local          On conflict, keep local beads version
      --prefer-newer          On conflict, use most recent version (default)
      --project string        Filter to issues from this project ID (group mode)
      --pull-only             Only pull issues from GitLab
      --push-only             Only push issues to GitLab
      --type string           Only sync these issue types (comma-separated, e.g. 'epic,feature,task')
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc graph`

## bd graph

Display a visualization of an issue's dependency graph.

For epics, shows all children and their dependencies.
For regular issues, shows the issue and its direct dependencies.

With --all, shows all open issues grouped by connected component.

Display formats:
  (default)        DAG with columns and box-drawing edges (terminal-native)
  --box            ASCII boxes showing layers, more detailed
  --compact        Tree format, one line per issue, more scannable
  --dot            Graphviz DOT format (pipe to dot -Tsvg &gt; graph.svg)
  --html           Self-contained interactive HTML with D3.js visualization

The graph shows execution order:
- Layer 0 / leftmost = no dependencies (can start immediately)
- Higher layers depend on lower layers
- Nodes in the same layer can run in parallel

Status icons: ○ open  ◐ in_progress  ● blocked  ✓ closed  ❄ deferred

Examples:
  bd graph issue-id              # Terminal DAG visualization (default)
  bd graph --box issue-id        # ASCII boxes with layer grouping
  bd graph --dot issue-id | dot -Tsvg &gt; graph.svg  # SVG via Graphviz
  bd graph --dot issue-id | dot -Tpng &gt; graph.png  # PNG via Graphviz
  bd graph --html issue-id &gt; graph.html  # Interactive browser view
  bd graph --all --html &gt; all.html       # All issues, interactive

```
bd graph [issue-id] [flags]
```

**Flags:**

```
      --all       Show graph for all open issues
      --box       ASCII boxes showing layers
      --compact   Tree format, one line per issue, more scannable
      --dot       Output Graphviz DOT format (pipe to: dot -Tsvg > graph.svg)
      --html      Output self-contained interactive HTML (redirect to file)
```

### bd graph check

Check the dependency graph for cycles, orphans, and other integrity issues.

Returns exit code 0 if the graph is clean, 1 if issues are found.

```
bd graph check [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc history`

## bd history

Show the complete version history of an issue, including all commits
where the issue was modified.

Examples:
  bd history bd-123           # Show all history for issue bd-123
  bd history bd-123 --limit 5 # Show last 5 changes

```
bd history <id> [flags]
```

**Flags:**

```
      --limit int   Limit number of history entries (0 = all)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc hooks`

## bd hooks

Install, uninstall, or list git hooks for beads integration.

The hooks provide:
- pre-commit: Run chained hooks before commit
- post-merge: Run chained hooks after pull/merge
- pre-push: Run chained hooks before push
- post-checkout: Run chained hooks after branch checkout
- prepare-commit-msg: Add agent identity trailers for forensics

```
bd hooks [flags]
```

### bd hooks install

Install git hooks for beads integration.

By default, hooks are installed to .git/hooks/ in the current repository.
Use --beads to install to .beads/hooks/ (recommended for Dolt backend).
Use --shared to install to a versioned directory (.beads-hooks/) that can be
committed to git and shared with team members.

Hooks use section markers to coexist with existing hooks — any user content
outside the markers is preserved across installs and upgrades.

Installed hooks:
  - pre-commit: Run chained hooks before commit
  - post-merge: Run chained hooks after pull/merge
  - pre-push: Run chained hooks before push
  - post-checkout: Run chained hooks after branch checkout
  - prepare-commit-msg: Add agent identity trailers (for orchestrator agents)

```
bd hooks install [flags]
```

**Flags:**

```
      --beads    Install hooks to .beads/hooks/ (recommended for Dolt backend)
      --chain    Chain with existing hooks (run them before bd hooks)
      --force    Overwrite existing hooks without backup
      --shared   Install hooks to .beads-hooks/ (versioned) instead of .git/hooks/
```

### bd hooks list

Show the status of bd git hooks (installed, outdated, missing).

```
bd hooks list [flags]
```

### bd hooks run

Execute the logic for a git hook. This command is typically called by
thin shim scripts installed in .git/hooks/.

Supported hooks:
  - pre-commit: Run chained hooks before commit
  - post-merge: Run chained hooks after pull/merge
  - pre-push: Run chained hooks before push
  - post-checkout: Run chained hooks after branch checkout
  - prepare-commit-msg: Add agent identity trailers for forensics

The thin shim pattern ensures hook logic is always in sync with the
installed bd version - upgrading bd automatically updates hook behavior.

```
bd hooks run <hook-name> [args...] [flags]
```

### bd hooks uninstall

Remove bd git hooks from .git/hooks/ directory.

```
bd hooks uninstall [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc human`

## bd human

Display a focused help menu showing only the most common commands.

bd has 70+ commands - many for AI agents, integrations, and advanced workflows.
This command shows the ~15 essential commands that human users need most often.

For the full command list, run: bd --help

SUBCOMMANDS:
  human list              List all human-needed beads (issues with 'human' label)
  human respond &lt;id&gt;      Respond to a human-needed bead (adds comment and closes)
  human dismiss &lt;id&gt;      Dismiss a human-needed bead permanently
  human stats             Show summary statistics for human-needed beads

```
bd human [flags]
```

### bd human dismiss

Dismiss a human-needed bead permanently without responding.

The issue is closed with a "Dismissed" reason and optional note.

Examples:
  bd human dismiss bd-123
  bd human dismiss bd-123 --reason "No longer applicable"

```
bd human dismiss <issue-id> [flags]
```

**Flags:**

```
      --reason string   Reason for dismissal (optional)
```

### bd human list

List all issues labeled with 'human' tag.

These are issues that require human intervention or input.

Examples:
  bd human list
  bd human list --status=open
  bd human list --json

```
bd human list [flags]
```

**Flags:**

```
  -s, --status string   Filter by status (open, closed, etc.)
```

### bd human respond

Respond to a human-needed bead by adding a comment and closing it.

The response is added as a comment and the issue is closed with reason "Responded".

Examples:
  bd human respond bd-123 --response "Use OAuth2 for authentication"
  bd human respond bd-123 -r "Approved, proceed with implementation"

```
bd human respond <issue-id> [flags]
```

**Flags:**

```
  -r, --response string   Response text (required)
```

### bd human stats

Display summary statistics for human-needed beads.

Shows counts for total, pending (open), responded (closed without dismiss),
and dismissed beads.

Example:
  bd human stats

```
bd human stats [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc import`

## bd import

Import issues from a JSONL file (newline-delimited JSON) into the database.

If no file is specified, imports from the configured import.path under .beads/
(default: issues.jsonl). Use "-" to read from stdin. This is the incremental counterpart to
'bd export': new issues are created and existing issues are updated (upsert
semantics).

Memory records (lines with "_type":"memory") are automatically detected and
imported as persistent memories (equivalent to 'bd remember'). This makes
'bd export | bd import' a full round-trip for both issues and memories.

Each JSONL line should map to an issue. The importer accepts every field
'bd export' emits — see 'bd export' output for the canonical schema. Only
"title" is required; everything else is optional.

Common fields:
  title                  Required. Short summary.
  description            Long-form body.
  design, notes,         Additional content sections.
    acceptance_criteria
  issue_type             bug | feature | task | epic | chore | ...
  priority               0-4 (0 = critical). 0 is preserved (no omitempty).
  status                 open | in_progress | blocked | closed | ...
                         (rows with status "tombstone" are skipped)
  assignee, owner,       Ownership metadata.
    created_by
  labels                 Array of strings.
  dependencies           Array of &#123;issue_id, depends_on_id, type, ...&#125;.
  comments               Array of comment objects.
  external_ref,          Cross-system identifiers (e.g. "gh-9").
    source_system
  due_at, defer_until    RFC3339 timestamps for scheduling.
  metadata               Arbitrary JSON object preserved verbatim.

Timestamps (created_at, updated_at, started_at, closed_at) are preserved
when present in the JSONL and otherwise filled in by the importer. The
legacy "wisp" boolean is accepted as an alias for "ephemeral".

By default a row only rewrites an existing local issue when its
updated_at is strictly newer. Older rows are skipped (reported as
stale_skipped_ids) and rows with the same updated_at keep every local
column — updated_at has second granularity, so a timestamp tie can be
two distinct same-second updates, and the local row wins the tie
(reported as tie_kept_local_ids; the row's labels/comments/dependencies
still merge). The guard is also enforced inside the upsert itself, so a
local update that lands while the import is running is preserved rather
than overwritten. Existing issues that the import did rewrite are listed
with a field-level summary (updated_issues), so local state changed by
an import is visible. To deliberately restore an older snapshot, pass
--allow-stale, which imports every row even when it overwrites newer
local state.

EXAMPLES:
  bd import                        # Import from configured import.path
  bd import backup.jsonl           # Import from a specific file
  bd import -i backup.jsonl        # Legacy alias for a specific file
  bd import -                      # Read JSONL from stdin
  cat issues.jsonl | bd import -   # Pipe JSONL from another tool
  bd import --dry-run              # Show what would be imported
  bd import --dedup                # Skip issues with duplicate titles
  bd import --allow-stale old.jsonl # Restore an older snapshot (overwrites newer local rows)
  bd import --json                 # Structured output with created and skipped IDs

```
bd import [file|-] [flags]
```

**Flags:**

```
      --allow-stale    Import rows even when older than the local issue (required to restore an older snapshot)
      --dedup          Skip lines whose title matches an existing open issue
      --dry-run        Show what would be imported without importing
  -i, --input string   Read JSONL from a specific file
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc info`

## bd info

Display information about the current database.

This command helps debug issues where bd is using an unexpected database. It shows:
  - The absolute path to the database file
  - Database statistics (issue count)
  - Schema information (with --schema flag)
  - What's new in recent versions (with --whats-new flag)

Examples:
  bd info
  bd info --json
  bd info --schema --json
  bd info --whats-new
  bd info --whats-new --json
  bd info --thanks

```
bd info [flags]
```

**Flags:**

```
      --json        Output in JSON format
      --schema      Include schema information in output
      --thanks      Show thank you page for contributors
      --whats-new   Show agent-relevant changes from recent versions
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc init-safety`

## bd init-safety

bd init flag safety contract.

Every bd init invocation resolves project_id from exactly one explicitly
named source (local reinit, remote adoption, or a fresh mint). When the
source is ambiguous, bd init refuses.

FLAG SURFACE

  bd init                       Mint a new identity. Bootstraps from
                                origin if it has refs/dolt/data.

  bd init --reinit-local        Re-initialize local .beads/ over existing
                                local data. Does NOT authorize discarding
                                remote history. If origin has Dolt data
                                this will refuse — pair with
                                --discard-remote to override.

  bd init --reinit-local \      Discard the remote's Dolt history and
      --discard-remote          replace it with the local reinit. First
                                bd dolt push after this will be a
                                history-replacing force-push.

  bd init --force               Deprecated alias for --reinit-local.
                                Kept working for ≥2 releases.

  bd init --from-jsonl          Import from configured import.path. If
                                origin has Dolt data, this refuses unless
                                --discard-remote authorizes replacing that
                                remote history.

ADOPTING A REMOTE

  If you want to use the remote's existing history, use:

      bd bootstrap

  bd init will automatically suggest this when a remote is detected.

DESTROY-TOKEN (non-interactive only)

  When running with no TTY (CI, agents, piped input), --discard-remote
  requires an explicit --destroy-token value. The token format is:

      DESTROY-&lt;issue-prefix&gt;

  For example, if your issue prefix is "bd", the token is "DESTROY-bd":

      bd init --reinit-local --discard-remote --destroy-token=DESTROY-bd

  In interactive (TTY) mode you confirm via a typed prompt instead. The
  token is not echoed by bd's runtime error messages — this is a
  deliberate guard against pattern-matched one-liners (see
  docs/adr/0002-init-safety-invariants.md).

EXIT CODES

  10    refused: remote has Dolt history and you selected local history
        without --discard-remote
  11    refused: existing local data and you declined the destroy confirm
  12    refused: --discard-remote passed without a valid --destroy-token
        (non-interactive mode)

RECOVERY

  If you hit a refusal, see docs/RECOVERY.md for step-by-step recovery
  playbooks for each exit code.


```
bd init-safety [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc init`

## bd init

Initialize bd in the current directory by creating a .beads/ directory
and Dolt database. Optionally specify a custom issue prefix.

Dolt is the default (and only supported) storage backend. The legacy SQLite
backend has been removed. Use --backend=sqlite to see migration instructions.

Use --database to specify an existing server database name, overriding the
default prefix-based naming. This is useful when an external tool (e.g. an orchestrator)
has already created the database.

With --stealth: configures per-repository git settings for invisible beads usage:
  • .git/info/exclude to prevent beads files from being committed
  Perfect for personal use without affecting repo collaborators.
  To set up a specific AI tool, run: bd setup &lt;claude|cursor|aider|...&gt; --stealth

By default, beads uses an embedded Dolt engine (no external server needed).
Pass --server to use an external dolt sql-server instead. In server mode,
set connection details with --server-host, --server-port, and --server-user.
Password should be set via BEADS_DOLT_PASSWORD environment variable.

Auto-export is optional. When enabled, bd exports issues to
.beads/issues.jsonl after write commands (throttled to once per 60s). This is
for viewers (bv), interchange, and issue-level migration; not backup.
Cross-machine sync and backups use Dolt remotes/backups, not JSONL import/export.
To enable: bd config set export.auto true

Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
  Skips all interactive prompts, using sensible defaults:
  • Role defaults to "maintainer" (override with --role)
  • Fork exclude auto-configured when fork detected
  • Auto-export left at default (disabled)
  • --contributor and --team flags are rejected (wizards require interaction)
  Also auto-detected when stdin is not a terminal or CI=true is set.

```
bd init [flags]
```

**Flags:**

```
      --agents-file string                             Custom filename for agent instructions (default: AGENTS.md)
      --agents-profile string                          AGENTS.md profile: 'minimal' (default, pointer to bd prime) or 'full' (complete command reference)
      --agents-template string                         Path to custom AGENTS.md template (overrides embedded default)
      --backend string                                 Storage backend (default: dolt). --backend=sqlite prints deprecation notice.
      --contributor                                    Run OSS contributor setup wizard
      --database string                                Use existing server database name (overrides prefix-based naming)
      --debug                                          Run the managed Dolt sql-server with --loglevel=debug and CPU profiling (--prof cpu). Persisted to config.yaml as dolt.debug. No effect on externally-managed servers.
      --destroy-token string                           Explicit confirmation token for destructive re-init in non-interactive mode (format: 'DESTROY-<prefix>')
      --discard-remote                                 Authorize discarding the configured remote's Dolt history when re-initializing. Requires --destroy-token in non-interactive mode; see 'bd help init-safety'.
      --external                                       Server is externally managed (skip server startup); use with --shared-server or --server
      --force                                          Deprecated alias for --reinit-local. Bypasses only the LOCAL data-safety guard; does NOT authorize remote divergence (see 'bd help init-safety').
      --from-jsonl                                     Import issues from configured import.path; refuses remote history unless --discard-remote authorizes replacement
      --init-if-missing                                If the workspace is already initialized, skip init and exit 0 instead of failing (idempotent init for scaffolds)
      --non-interactive                                Skip all interactive prompts (auto-detected in CI or non-TTY environments)
  -p, --prefix string                                  Issue prefix (default: current directory name)
      --proxied-server                                 [EXPERIMENTAL] Use a per-workspace proxied dolt sql-server (proxy + child dolt) rooted at .beads/proxieddb
      --proxied-server-config-path string              [EXPERIMENTAL] Absolute path to an existing dolt sql-server YAML config (proxied-server mode only). When set, bd uses this file instead of auto-generating one. Relative paths are rejected.
      --proxied-server-external-host string            [EXPERIMENTAL] Hostname or IP of an externally-managed dolt sql-server the proxy should front (proxied-server mode only). Mutually exclusive with --proxied-server-external-socket-path.
      --proxied-server-external-keep-alive duration    [EXPERIMENTAL] TCP keepalive period for the proxy→external connection. Zero uses the package default (30s).
      --proxied-server-external-port int               [EXPERIMENTAL] TCP port of the externally-managed dolt sql-server (proxied-server mode only). Required when --proxied-server-external-host is set.
      --proxied-server-external-socket-path string     [EXPERIMENTAL] Absolute unix socket path of the externally-managed dolt sql-server (proxied-server mode only). Mutually exclusive with --proxied-server-external-host. Relative paths are rejected.
      --proxied-server-external-tls                    [EXPERIMENTAL] Require TLS when connecting to the externally-managed dolt sql-server (proxied-server mode only).
      --proxied-server-external-tls-cert-path string   [EXPERIMENTAL] Absolute path to a client TLS certificate (for mTLS to the externally-managed dolt sql-server). Must be paired with --proxied-server-external-tls-key-path. Relative paths are rejected.
      --proxied-server-external-tls-key-path string    [EXPERIMENTAL] Absolute path to the client TLS private key (for mTLS to the externally-managed dolt sql-server). Must be paired with --proxied-server-external-tls-cert-path. Relative paths are rejected.
      --proxied-server-external-user string            [EXPERIMENTAL] MySQL user for the externally-managed dolt sql-server (proxied-server mode only). Defaults to "root" when empty. Password is read at runtime from $BEADS_PROXIED_SERVER_EXTERNAL_PASSWORD and is never persisted to disk.
      --proxied-server-log-path string                 [EXPERIMENTAL] Absolute path to the proxied dolt sql-server log file (proxied-server mode only). Default: <beadsDir>/proxieddb/server.log. Relative paths are rejected.
      --proxied-server-root-path string                [EXPERIMENTAL] Absolute directory holding the proxied dolt sql-server's lockfiles, pidfiles, and child .dolt repository (proxied-server mode only). Default: <beadsDir>/proxieddb. May not exist yet — bd will create it. Relative paths are rejected.
  -q, --quiet                                          Suppress output (quiet mode)
      --reinit-local                                   Re-initialize local .beads/ over existing local data. Does NOT authorize remote divergence; see --discard-remote.
      --remote string                                  Dolt remote URL to clone from and persist as sync.remote
      --role string                                    Set beads role without prompting: "maintainer" or "contributor"
      --server                                         Use external dolt sql-server instead of embedded engine
      --server-host string                             Dolt server host (default: 127.0.0.1)
      --server-port int                                Dolt server port (default: 3307)
      --server-socket string                           Unix domain socket path (overrides host/port)
      --server-user string                             Dolt server MySQL user (default: root)
      --setup-exclude                                  Configure .git/info/exclude to keep beads files local (for forks)
      --shared-server                                  Enable shared Dolt server mode (all projects share one server at ~/.beads/shared-server/)
      --skip-agents                                    Skip AGENTS.md and Claude/Codex setup generation
      --skip-hooks                                     Skip git hooks installation
      --stealth                                        Enable stealth mode: global gitattributes and gitignore, no local repo tracking
      --team                                           Run team workflow setup wizard
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc jira`

## bd jira

Synchronize issues between beads and Jira.

Configuration:
  bd config set jira.url "https://company.atlassian.net"
  bd config set jira.project "PROJ"
  bd config set jira.projects "PROJ1,PROJ2"   # Multiple projects
  bd config set jira.api_token "YOUR_TOKEN"
  bd config set jira.username "your_email@company.com"  # For Jira Cloud
  bd config set jira.push_prefix "hippo"       # Only push hippo-* issues to Jira
  bd config set jira.push_prefix "proj1,proj2" # Multiple prefixes (comma-separated)

Environment variables (alternative to config):
  JIRA_API_TOKEN  - Jira API token
  JIRA_USERNAME   - Jira username/email
  JIRA_PROJECTS   - Comma-separated project keys

Examples:
  bd jira sync --pull         # Import issues from Jira
  bd jira sync --push         # Export issues to Jira
  bd jira sync                # Bidirectional sync (pull then push)
  bd jira sync --dry-run      # Preview sync without changes
  bd jira status              # Show sync status

```
bd jira [flags]
```

### bd jira pull

Pull one or more items from Jira.

Accepts bead IDs or external references as positional arguments.
Equivalent to: bd jira sync --pull --issues &lt;refs&gt;

```
bd jira pull [refs...] [flags]
```

**Flags:**

```
      --dry-run   Preview pull without making changes
```

### bd jira push

Push one or more beads issues to Jira.

Accepts bead IDs as positional arguments.
Equivalent to: bd jira sync --push --issues &lt;ids&gt;

```
bd jira push [bead-ids...] [flags]
```

**Flags:**

```
      --dry-run   Preview push without making changes
```

### bd jira status

Show the current Jira sync status, including:
  - Last sync timestamp
  - Configuration status
  - Number of issues with Jira links
  - Issues pending push (no external_ref)

```
bd jira status [flags]
```

### bd jira sync

Synchronize issues between beads and Jira.

Modes:
  --pull         Import issues from Jira into beads
  --push         Export issues from beads to Jira
  (no flags)     Bidirectional sync: pull then push, with conflict resolution

Conflict Resolution:
  By default, newer timestamp wins. Override with:
  --prefer-local   Always prefer local beads version
  --prefer-jira    Always prefer Jira version

Examples:
  bd jira sync --pull                # Import from Jira
  bd jira sync --push --create-only  # Push new issues only
  bd jira sync --dry-run             # Preview without changes
  bd jira sync --prefer-local        # Bidirectional, local wins

```
bd jira sync [flags]
```

**Flags:**

```
      --create-only       Only create new issues, don't update existing
      --dry-run           Preview sync without making changes
      --issues string     Comma-separated bead IDs to sync selectively (e.g., bd-abc,bd-def). Mutually exclusive with --parent.
      --parent string     Limit push to this bead and its descendants (push only). Mutually exclusive with --issues.
      --prefer-jira       Prefer Jira version on conflicts
      --prefer-local      Prefer local version on conflicts
      --project strings   Project key(s) to sync (overrides configured project/projects)
      --pull              Pull issues from Jira
      --push              Push issues to Jira
      --state string      Issue state to sync: open, closed, all (default "all")
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc kv`

## bd kv

Commands for working with the beads key-value store.

The key-value store is useful for storing flags, environment variables,
or other user-defined data that persists across sessions.

Examples:
  bd kv set mykey myvalue    # Set a value
  bd kv get mykey            # Get a value
  bd kv clear mykey          # Delete a key
  bd kv list                 # List all key-value pairs

```
bd kv [flags]
```

### bd kv clear

Delete a key from the beads key-value store.

Examples:
  bd kv clear feature_flag
  bd kv clear api_endpoint

```
bd kv clear <key> [flags]
```

### bd kv get

Get a value from the beads key-value store.

Examples:
  bd kv get feature_flag
  bd kv get api_endpoint

```
bd kv get <key> [flags]
```

### bd kv list

List all key-value pairs in the beads key-value store.

Examples:
  bd kv list
  bd kv list --json

```
bd kv list [flags]
```

### bd kv set

Set a key-value pair in the beads key-value store.

This is useful for storing flags, environment variables, or other
user-defined data that persists across sessions.

Examples:
  bd kv set feature_flag true
  bd kv set api_endpoint https://api.example.com
  bd kv set max_retries 3

```
bd kv set <key> <value> [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc label`

## bd label

Manage issue labels

```
bd label [flags]
```

### bd label add

Add a label to one or more issues

```
bd label add [issue-id...] [label] [flags]
```

### bd label list

List labels for an issue

```
bd label list [issue-id] [flags]
```

### bd label list-all

List all unique labels in the database

```
bd label list-all [flags]
```

### bd label propagate

Push a label from a parent down to all direct children that don't already have it. Useful for applying branch: labels across an epic's subtasks.

```
bd label propagate [parent-id] [label] [flags]
```

### bd label remove

Remove a label from one or more issues

```
bd label remove [issue-id...] [label] [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc linear`

## bd linear

Synchronize issues between beads and Linear.

Configuration:
  bd config set linear.api_key "YOUR_API_KEY"
  bd config set linear.team_id "TEAM_ID"
  bd config set linear.team_ids "TEAM_ID1,TEAM_ID2"  # Multiple teams (comma-separated)
  bd config set linear.project_id "PROJECT_ID"  # Optional: sync only this project

Environment variables (alternative to config):
  LINEAR_API_KEY  - Linear API key (for individual developers)
  LINEAR_TEAM_ID  - Linear team ID (UUID, singular)
  LINEAR_TEAM_IDS - Linear team IDs (comma-separated UUIDs)

OAuth (for CI workers / automated sync):
  LINEAR_OAUTH_CLIENT_ID     - OAuth app client ID
  LINEAR_OAUTH_CLIENT_SECRET - OAuth app client secret

  When both OAuth env vars are set, OAuth client_credentials flow is used
  instead of the API key. This allows CI workers to authenticate as an
  application (actor=application) rather than impersonating a user.
  Precedence: OAuth &gt; LINEAR_API_KEY &gt; config file.

Data Mapping (optional, sensible defaults provided):
  Priority mapping (Linear 0-4 to Beads 0-4):
    bd config set linear.priority_map.0 4    # No priority -&gt; Backlog
    bd config set linear.priority_map.1 0    # Urgent -&gt; Critical
    bd config set linear.priority_map.2 1    # High -&gt; High
    bd config set linear.priority_map.3 2    # Medium -&gt; Medium
    bd config set linear.priority_map.4 3    # Low -&gt; Low

  State mapping (Linear state type to Beads status):
    bd config set linear.state_map.backlog open
    bd config set linear.state_map.unstarted open
    bd config set linear.state_map.started in_progress
    bd config set linear.state_map.completed closed
    bd config set linear.state_map.canceled closed
    bd config set linear.state_map.my_custom_state in_progress  # Custom state names

  Label to issue type mapping:
    bd config set linear.label_type_map.bug bug
    bd config set linear.label_type_map.feature feature
    bd config set linear.label_type_map.epic epic

  Relation type mapping (Linear relations to Beads dependencies):
    bd config set linear.relation_map.blocks blocks
    bd config set linear.relation_map.blockedBy blocks
    bd config set linear.relation_map.duplicate duplicates
    bd config set linear.relation_map.related related

  ID generation (optional, hash IDs to match bd/Jira hash mode):
    bd config set linear.id_mode "hash"      # hash (default)
    bd config set linear.hash_length "6"     # hash length 3-8 (default: 6)

Examples:
  bd linear sync --pull         # Import issues from Linear
  bd linear sync --push         # Export issues to Linear
  bd linear sync                # Bidirectional sync (pull then push)
  bd linear sync --dry-run      # Preview sync without changes
  bd create "Fix login" --external-ref https://linear.app/team/issue/TEAM-123
                              # Link a local issue to an existing Linear issue
  bd linear status              # Show sync status

```
bd linear [flags]
```

### bd linear pull

Pull one or more items from Linear.

Accepts bead IDs or external references as positional arguments.
Equivalent to: bd linear sync --pull --issues &lt;refs&gt;

```
bd linear pull [refs...] [flags]
```

**Flags:**

```
      --dry-run     Preview pull without making changes
      --relations   Import Linear relations as bd dependencies when pulling
```

### bd linear push

Push one or more beads issues to Linear.

Accepts bead IDs as positional arguments.
Equivalent to: bd linear sync --push --issues &lt;ids&gt;

```
bd linear push [bead-ids...] [flags]
```

**Flags:**

```
      --dry-run   Preview push without making changes
```

### bd linear status

Show the current Linear sync status, including:
  - Last sync timestamp
  - Configuration status
  - Number of issues with Linear links
  - Issues pending push (no external_ref)

```
bd linear status [flags]
```

### bd linear sync

Synchronize issues between beads and Linear.

Modes:
  --pull              Import issues from Linear into beads
  --push              Export issues from beads to Linear
  --pull-if-stale     Pull only if data is stale (skip if fresh)
  (no flags)          Bidirectional sync: pull then push, with conflict resolution

Staleness (--pull-if-stale):
  --threshold 20m     How old data must be before pulling (default 20m)
  A 5-minute debounce prevents agent loops: if a pull completed within 5 minutes,
  data is always treated as fresh regardless of the threshold.

Team Selection:
  --team ID1,ID2  Override configured team IDs for this sync
  Multiple teams can be configured via linear.team_ids (comma-separated).
  Falls back to linear.team_id for backward compatibility.
  Push requires explicit --team when multiple teams are configured.

Pull Options:
  --milestones       Reconstruct Linear project milestones as local epic parents

Type Filtering (--push only):
  --type task,feature       Only sync issues of these types
  --exclude-type wisp       Exclude issues of these types
  --include-ephemeral       Include ephemeral issues (wisps, etc.); default is to exclude
  --parent TICKET           Only push this ticket and its descendants
  --relations               Import Linear relations as bd dependencies on pull

Conflict Resolution:
  By default, newer timestamp wins. Override with:
  --prefer-local    Always prefer local beads version
  --prefer-linear   Always prefer Linear version

Examples:
  bd linear sync --pull                         # Import from Linear
  bd linear sync --pull-if-stale                # Pull only if data is stale
  bd linear sync --pull-if-stale --threshold 5m # Pull if older than 5 minutes
  bd linear sync --pull --relations             # Import Linear blocking relations as bd deps
  bd linear sync --push --create-only           # Push new issues only
  bd linear sync --push --type=task,feature     # Push only tasks and features
  bd linear sync --push --exclude-type=wisp     # Push all except wisps
  bd linear sync --push --parent=bd-abc123      # Push one ticket tree
  bd linear sync --dry-run                      # Preview without changes
  bd linear sync --prefer-local                 # Bidirectional, local wins

```
bd linear sync [flags]
```

**Flags:**

```
      --create-only            Only create new issues, don't update existing
      --dry-run                Preview sync without making changes
      --exclude-type strings   Exclude issues of these types (can be repeated)
      --include-ephemeral      Include ephemeral issues (wisps, etc.) when pushing to Linear
      --issues string          Comma-separated bead IDs to sync selectively (e.g., bd-abc,bd-def). Mutually exclusive with --parent.
      --milestones             Reconstruct Linear project milestones as local epic parents when pulling
      --no-wait                Fail immediately if another sync is running instead of waiting
      --parent string          Limit push to this beads ticket and its descendants
      --prefer-linear          Prefer Linear version on conflicts
      --prefer-local           Prefer local version on conflicts
      --pull                   Pull issues from Linear
      --pull-if-stale          Pull only if Linear data is stale (skip if fresh)
      --push                   Push issues to Linear
      --relations              Import Linear relations as bd dependencies when pulling
      --state string           Issue state to sync: open, closed, all (default "all")
      --team strings           Team ID(s) to sync (overrides configured team_id/team_ids)
      --threshold duration     Staleness threshold for --pull-if-stale (default 20m) (default 20m0s)
      --type strings           Only sync issues of these types (can be repeated)
      --update-refs            Update external_ref after creating Linear issues (default true)
```

### bd linear teams

List all teams accessible with your Linear API key.

Use this to find the team ID (UUID) needed for configuration.

Example:
  bd linear teams
  bd config set linear.team_id "12345678-1234-1234-1234-123456789abc"

```
bd linear teams [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc link`

## bd link

Link two issues with a dependency.

Shorthand for 'bd dep add &lt;id1&gt; &lt;id2&gt;'. By default creates a "blocks"
dependency (id2 blocks id1). Use --type to specify a different relationship.

Examples:
  bd link bd-123 bd-456                    # bd-456 blocks bd-123
  bd link bd-123 bd-456 --type related     # bd-123 related to bd-456
  bd link bd-123 bd-456 --type parent-child

```
bd link <id1> <id2> [flags]
```

**Flags:**

```
  -t, --type string   Dependency type (blocks|tracks|related|parent-child|discovered-from) (default "blocks")
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc lint`

## bd lint

Check issues for missing recommended sections based on issue type.

By default, lints all open issues. Specify issue IDs to lint specific issues.

Section requirements by type:
  bug:      Steps to Reproduce, Acceptance Criteria
  task:     Acceptance Criteria
  feature:  Acceptance Criteria
  epic:     Success Criteria
  chore:    (none)

Examples:
  bd lint                    # Lint all open issues
  bd lint bd-abc             # Lint specific issue
  bd lint bd-abc bd-def      # Lint multiple issues
  bd lint --type bug         # Lint only bugs
  bd lint --status all       # Lint all issues (including closed)


```
bd lint [issue-id...] [flags]
```

**Flags:**

```
  -s, --status string   Filter by status (default: open, use 'all' for all)
  -t, --type string     Filter by issue type (bug, task, feature, epic)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc list`

## bd list

List issues

```
bd list [flags]
```

**Flags:**

```
      --all                          Show all issues including closed (overrides default filter)
  -a, --assignee string              Filter by assignee
      --closed-after string          Filter issues closed after date (YYYY-MM-DD or RFC3339)
      --closed-before string         Filter issues closed before date (YYYY-MM-DD or RFC3339)
      --created-after string         Filter issues created after date (YYYY-MM-DD or RFC3339)
      --created-before string        Filter issues created before date (YYYY-MM-DD or RFC3339)
      --defer-after string           Filter issues deferred after date (supports relative: +6h, tomorrow)
      --defer-before string          Filter issues deferred before date (supports relative: +6h, tomorrow)
      --deferred                     Show only issues with defer_until set
      --desc-contains string         Filter by description substring (case-insensitive)
      --due-after string             Filter issues due after date (supports relative: +6h, tomorrow)
      --due-before string            Filter issues due before date (supports relative: +6h, tomorrow)
      --empty-description            Filter issues with empty or missing description
      --exclude-label strings        Exclude issues that have ANY of these labels
      --exclude-type strings         Exclude issue types from results (comma-separated or repeatable, e.g., --exclude-type=convoy,epic)
      --flat                         Disable tree format and use legacy flat list output
      --format string                Output format: 'digraph' (for golang.org/x/tools/cmd/digraph), 'dot' (Graphviz), or Go template
      --has-metadata-key string      Filter issues that have this metadata key set
      --id string                    Filter by specific issue IDs (comma-separated, e.g., bd-1,bd-5,bd-10)
      --include-gates                Include gate issues in output (normally hidden)
      --include-infra                Include infrastructure beads (agent/role/message) in output
      --include-templates            Include template molecules in output
  -l, --label strings                Filter by labels (AND: must have ALL). Can combine with --label-any
      --label-any strings            Filter by labels (OR: must have AT LEAST ONE). Can combine with --label
      --label-pattern string         Filter by label glob pattern (e.g., 'tech-*' matches tech-debt, tech-legacy)
      --label-regex string           Filter by label regex pattern (e.g., 'tech-(debt|legacy)')
  -n, --limit int                    Limit results (default 50, use 0 for unlimited) (default 50)
      --long                         Show detailed multi-line output for each issue
      --metadata-field stringArray   Filter by metadata field (key=value, repeatable)
      --mol-type string              Filter by molecule type: swarm, patrol, or work
      --no-assignee                  Filter issues with no assignee
      --no-labels                    Filter issues with no labels
      --no-pager                     Disable pager output
      --no-parent                    Exclude child issues (show only top-level issues)
      --no-pinned                    Exclude pinned issues
      --notes-contains string        Filter by notes substring (case-insensitive)
      --offset int                   Skip the first N matching results (0-based). Only supported under --proxied-server.
      --overdue                      Show only issues with due_at in the past (not closed)
      --parent string                Filter by parent issue ID (shows children of specified issue)
      --pinned                       Show only pinned issues
      --pretty                       Display issues in a tree format with status/priority symbols
  -p, --priority string              Priority (0-4 or P0-P4, 0=highest)
      --priority-max string          Filter by maximum priority (inclusive, 0-4 or P0-P4)
      --priority-min string          Filter by minimum priority (inclusive, 0-4 or P0-P4)
      --ready                        Show only ready issues (no active blockers, same semantics as bd ready)
  -r, --reverse                      Reverse sort order
      --skip-labels                  Skip label hydration. The labels field in output will be empty regardless of actual labels. Use only when the caller does not depend on label data. Cannot combine with --label, --label-any, --label-pattern, --label-regex, --exclude-label, or --no-labels.
      --sort string                  Sort by field: priority, created, updated, closed, status, id, title, type, assignee
      --spec string                  Filter by spec_id prefix
  -s, --status string                Filter by stored status (open, in_progress, blocked, deferred, closed). Comma-separated for multiple: --status open,in_progress. Note: repeating -s/--status silently overwrites the previous value — always use the comma-separated form for multi-status filters.
      --title string                 Filter by title text (case-insensitive substring match)
      --title-contains string        Filter by title substring (case-insensitive)
      --tree                         Hierarchical tree format (default: true; use --flat to disable) (default true)
  -t, --type string                  Filter by type (bug, feature, task, epic, chore, decision, merge-request, molecule, gate, convoy). Aliases: mr→merge-request, feat→feature, mol→molecule, dec/adr→decision
      --updated-after string         Filter issues updated after date (YYYY-MM-DD or RFC3339)
      --updated-before string        Filter issues updated before date (YYYY-MM-DD or RFC3339)
  -w, --watch                        Watch for changes and auto-update display (implies --pretty)
      --wisp-type string             Filter by wisp type: heartbeat, ping, patrol, gc_report, recovery, error, escalation
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc mail`

## bd mail

Delegates mail operations to an external mail provider.

Agents often type 'bd mail' when working with beads, but mail functionality
is typically provided by the orchestrator. This command bridges that gap
by delegating to the configured mail provider.

Configuration (checked in order):
  1. BEADS_MAIL_DELEGATE or BD_MAIL_DELEGATE environment variable
  2. 'mail.delegate' config setting (bd config set mail.delegate "gt mail")

Examples:
  # Configure delegation (one-time setup)
  export BEADS_MAIL_DELEGATE="gt mail"
  # or
  bd config set mail.delegate "gt mail"

  # Then use bd mail as if it were gt mail
  bd mail inbox                    # Lists inbox
  bd mail send mayor/ -s "Hi"      # Sends mail
  bd mail read msg-123             # Reads a message

```
bd mail [subcommand] [args...] [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc memories`

## bd memories

List all memories, or search by keyword.

Examples:
  bd memories              # list all memories
  bd memories dolt         # search for memories about dolt
  bd memories "race flag"  # search for a phrase

```
bd memories [search] [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc merge-slot`

## bd merge-slot

Merge-slot gates serialize conflict resolution in the merge queue.

A merge slot is an exclusive access primitive: only one agent can hold it at a time.
This prevents "monkey knife fights" where multiple polecats race to resolve conflicts
and create cascading conflicts.

Each rig has one merge slot bead: &lt;prefix&gt;-merge-slot (labeled gt:slot).
The slot uses:
  - status=open: slot is available
  - status=in_progress: slot is held
  - metadata.holder: who currently holds the slot
  - metadata.waiters: priority-ordered queue of waiters

Examples:
  bd merge-slot create              # Create merge slot for current rig
  bd merge-slot check               # Check if slot is available
  bd merge-slot acquire             # Try to acquire the slot
  bd merge-slot release             # Release the slot

```
bd merge-slot [flags]
```

### bd merge-slot acquire

Attempt to acquire the merge slot for exclusive access.

If the slot is available (status=open), it will be acquired:
  - status set to in_progress
  - holder set to the requester

If the slot is held (status=in_progress), the command fails unless
--wait is passed, which adds the requester to the waiters queue.

Use --holder to specify who is acquiring (default: BEADS_ACTOR env var).

```
bd merge-slot acquire [flags]
```

**Flags:**

```
      --holder string   Who is acquiring the slot (default: BEADS_ACTOR)
      --wait            Add to waiters list if slot is held
```

### bd merge-slot check

Check if the merge slot is available or held.

Returns:
  - available: slot can be acquired
  - held by &lt;holder&gt;: slot is currently held
  - not found: no merge slot exists for this rig

```
bd merge-slot check [flags]
```

### bd merge-slot create

Create a merge slot bead for serialized conflict resolution.

The slot ID is automatically generated based on the beads prefix (e.g., gt-merge-slot).
The slot is created with status=open (available).

```
bd merge-slot create [flags]
```

### bd merge-slot release

Release the merge slot after conflict resolution is complete.

Sets status back to open and clears the holder field.
If there are waiters, the highest-priority waiter should then acquire.

```
bd merge-slot release [flags]
```

**Flags:**

```
      --holder string   Who is releasing the slot (for verification)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc metrics`

## bd metrics

Show whether anonymous usage metrics are on, see exactly what is sent, and
turn them on or off.

bd shares anonymous usage metrics to learn how people actually use it — just
which commands get run, plus the bd version and OS platform. That's how we decide
what to polish next. We never collect your issues, paths, remotes, identity, or
any user-supplied text.

  bd metrics            show the current status and what is collected
  bd metrics on         turn metrics on
  bd metrics off        turn metrics off
  bd metrics example    show real examples of the events bd sends

```
bd metrics [flags]
```

### bd metrics example

Show real examples of the anonymous metrics bd sends

```
bd metrics example [flags]
```

### bd metrics off

Turn anonymous usage metrics off

```
bd metrics off [flags]
```

### bd metrics on

Turn anonymous usage metrics on

```
bd metrics on [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc migrate`

## bd migrate

Database migration and data transformation commands.

Without subcommand, checks and updates database metadata to current version.

Subcommands:
  hooks       Plan git hook migration to marker-managed format
  issues      Move issues between repositories
  schema      Apply pending schema migrations (idempotent)
  sync        Set up sync.branch workflow for multi-clone setups


```
bd migrate [flags]
```

**Flags:**

```
      --dry-run          Show what would be done without making changes
      --inspect          Show migration plan and database state for AI agent analysis
      --json             Output migration statistics in JSON format
      --update-repo-id   Update repository ID (use after changing git remote)
      --yes              Auto-confirm prompts
```

### bd migrate hooks

Analyze git hook files and sidecar artifacts for migration to marker-managed format.

Modes:
  --dry-run  Preview migration operations without changing files
  --apply    Apply migration operations

Examples:
  bd migrate hooks --dry-run
  bd migrate hooks --apply
  bd migrate hooks --apply --yes
  bd migrate hooks --dry-run --json

```
bd migrate hooks [path] [flags]
```

**Flags:**

```
      --apply     Apply planned hook migration changes
      --dry-run   Show what would be done without making changes
      --json      Output in JSON format
      --yes       Skip confirmation prompt for --apply
```

### bd migrate issues

Move issues from one source repository to another with filtering and dependency preservation.

This command updates the source_repo field for selected issues, allowing you to:
- Move contributor planning issues to upstream repository
- Reorganize issues across multi-phase repositories
- Consolidate issues from multiple repos

Examples:
  # Preview migration from planning repo to current repo
  bd migrate-issues --from ~/.beads-planning --to . --dry-run

  # Move all open P1 bugs
  bd migrate-issues --from ~/repo1 --to ~/repo2 --priority 1 --type bug --status open

  # Move specific issues with their dependencies
  bd migrate-issues --from . --to ~/archive --id bd-abc --id bd-xyz --include closure

  # Move issues with label filter
  bd migrate-issues --from . --to ~/feature-work --label frontend --label urgent

```
bd migrate issues [flags]
```

**Flags:**

```
      --dry-run            Show plan without making changes
      --from string        Source repository (required)
      --id strings         Specific issue IDs to migrate (can specify multiple)
      --ids-file string    File containing issue IDs (one per line)
      --include string     Include dependencies: none/upstream/downstream/closure (default "none")
      --label strings      Filter by labels (can specify multiple)
      --priority int       Filter by priority (0-4) (default -1)
      --status string      Filter by status (open/closed/all)
      --strict             Fail on orphaned dependencies or missing repos
      --to string          Destination repository (required)
      --type string        Filter by issue type (bug/feature/task/epic/chore/decision)
      --within-from-only   Only include dependencies from source repo (default true)
      --yes                Skip confirmation prompt
```

### bd migrate schema

Apply pending schema migrations idempotently.

Schema migrations also run automatically on store open, so this subcommand
is typically a no-op. It exists to make migration explicit and observable
in CI, release gates, and recovery scenarios.

Example:
  bd migrate schema
  bd migrate schema --json

```
bd migrate schema [flags]
```

**Flags:**

```
      --json   Output in JSON format
```

### bd migrate sync

Configure separate branch workflow for multi-clone setups.

This sets the sync.branch config value so that issue data is committed
to a dedicated branch, keeping your main branch clean.

Example:
  bd migrate sync beads-sync

```
bd migrate sync <branch> [flags]
```

**Flags:**

```
      --dry-run   Show what would be done without making changes
      --json      Output in JSON format
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc mol`

## bd mol

Manage molecules - work templates for agent workflows.

Protos are template epics with the "template" label. They define a DAG of work
that can be spawned to create real issues (molecules).

The molecule metaphor:
  - A proto is an uninstantiated template (reusable work pattern)
  - Spawning creates a molecule (real issues) from the proto
  - Variables (&#123;&#123;key&#125;&#125;) are substituted during spawning
  - Bonding combines protos or molecules into compounds
  - Distilling extracts a proto from an ad-hoc epic

Commands:
  show       Show proto/molecule structure and variables
  pour       Instantiate proto as persistent mol (liquid phase)
  wisp       Instantiate proto as ephemeral wisp (vapor phase)
  bond       Polymorphic combine: proto+proto, proto+mol, mol+mol
  squash     Condense molecule to digest
  burn       Discard wisp
  distill    Extract proto from ad-hoc epic

Use "bd formula list" to list available formulas.

```
bd mol [flags]
```

**Aliases:** protomolecule

### bd mol bond

Bond two protos or molecules to create a compound.

The bond command is polymorphic - it handles different operand types:

  formula + formula → cook both, compound proto
  formula + proto   → cook formula, compound proto
  formula + mol     → cook formula, spawn and attach
  proto + proto     → compound proto (reusable template)
  proto + mol       → spawn proto, attach to molecule
  mol + proto       → spawn proto, attach to molecule
  mol + mol         → join into compound molecule

Formula names (e.g., mol-polecat-arm) are cooked inline as ephemeral protos.
This avoids needing pre-cooked proto beads in the database.

Bond types:
  sequential (default) - B runs after A completes
  parallel            - B runs alongside A
  conditional         - B runs only if A fails

Phase control:
  By default, spawned protos follow the target's phase:
  - Attaching to mol (Ephemeral=false) → spawns as persistent (Ephemeral=false)
  - Attaching to ephemeral issue (Ephemeral=true) → spawns as ephemeral (Ephemeral=true)

  Override with:
  --pour  Force spawn as liquid (persistent, Ephemeral=false)
  --ephemeral  Force spawn as vapor (ephemeral, Ephemeral=true, excluded from Dolt sync via dolt_ignore)

Dynamic bonding (Christmas Ornament pattern):
  Use --ref to specify a custom child reference with variable substitution.
  This creates IDs like "parent.child-ref" instead of random hashes.

  Example:
    bd mol bond mol-worker-arm bd-patrol --ref arm-&#123;&#123;worker_name&#125;&#125; --var worker_name=ace
    # Creates: bd-patrol.arm-ace (and children like bd-patrol.arm-ace.capture)

Use cases:
  - Found important bug during patrol? Use --pour to persist it
  - Need ephemeral diagnostic on persistent feature? Use --ephemeral
  - Spawning per-worker arms on a patrol? Use --ref for readable IDs

Examples:
  bd mol bond mol-feature mol-deploy                    # Compound proto
  bd mol bond mol-feature mol-deploy --type parallel    # Run in parallel
  bd mol bond mol-feature bd-abc123                     # Attach proto to molecule
  bd mol bond bd-abc123 bd-def456                       # Join two molecules
  bd mol bond mol-critical-bug wisp-patrol --pour       # Persist found bug
  bd mol bond mol-temp-check bd-feature --ephemeral          # Ephemeral diagnostic
  bd mol bond mol-arm bd-patrol --ref arm-&#123;&#123;name&#125;&#125; --var name=ace  # Dynamic child ID

```
bd mol bond <A> <B> [flags]
```

**Aliases:** fart

**Flags:**

```
      --as string         Custom title for compound proto (proto+proto only)
      --dry-run           Preview what would be created
      --ephemeral         Force spawn as vapor (ephemeral, Ephemeral=true)
      --pour              Force spawn as liquid (persistent, Ephemeral=false)
      --ref string        Custom child reference with {{var}} substitution (e.g., arm-{{polecat_name}})
      --type string       Bond type: sequential, parallel, or conditional (default "sequential")
      --var stringArray   Variable substitution for spawned protos (key=value)
```

### bd mol burn

Burn a molecule, deleting it without creating a digest.

Unlike squash (which creates a permanent digest before deletion), burn
completely removes the molecule with no trace. Use this for:
  - Abandoned patrol cycles
  - Crashed or failed workflows
  - Test/debug molecules you don't want to preserve

The burn operation differs based on molecule phase:
  - Wisp (ephemeral): Direct delete
  - Mol (persistent): Cascade delete (syncs to remotes)

CAUTION: This is a destructive operation. The molecule's data will be
permanently lost. If you want to preserve a summary, use 'bd mol squash'.

Example:
  bd mol burn bd-abc123              # Delete molecule with no trace
  bd mol burn bd-abc123 --dry-run    # Preview what would be deleted
  bd mol burn bd-abc123 --force      # Skip confirmation
  bd mol burn bd-a1 bd-b2 bd-c3      # Batch delete multiple wisps

```
bd mol burn <molecule-id> [molecule-id...] [flags]
```

**Flags:**

```
      --dry-run   Preview what would be deleted
      --force     Skip confirmation prompt
```

### bd mol current

Show where you are in a molecule workflow.

If molecule-id is given, show status for that molecule.
If not given, infer from in_progress issues assigned to current agent.

The output shows all steps with status indicators:
  [done]     - Step is complete (closed)
  [current]  - Step is in_progress (you are here)
  [ready]    - Step is ready to start (unblocked)
  [blocked]  - Step is blocked by dependencies
  [pending]  - Step is waiting

For large molecules (&gt;100 steps), a summary is shown instead.
Use --limit or --range to view specific steps:
  bd mol current &lt;id&gt; --limit 50       # Show first 50 steps
  bd mol current &lt;id&gt; --range 100-150  # Show steps 100-150

```
bd mol current [molecule-id] [flags]
```

**Flags:**

```
      --for string     Show molecules for a specific agent/assignee
      --limit int      Maximum number of steps to display (0 = auto, use 'all' threshold)
      --range string   Display specific step range (e.g., '1-50', '100-150')
```

### bd mol distill

Distill a molecule by extracting a reusable formula from an existing epic.

This is the reverse of pour: instead of formula → molecule, it's molecule → formula.

The distill command:
  1. Loads the existing epic and all its children
  2. Converts the structure to a .formula.json file
  3. Replaces concrete values with &#123;&#123;variable&#125;&#125; placeholders (via --var flags)

Use cases:
  - Team develops good workflow organically, wants to reuse it
  - Capture tribal knowledge as executable templates
  - Create starting point for similar future work

Variable syntax (both work - we detect which side is the concrete value):
  --var branch=feature-auth    Spawn-style: variable=value (recommended)
  --var feature-auth=branch    Substitution-style: value=variable

Output locations (first writable wins):
  1. &lt;resolved-beads-dir&gt;/formulas/ (project-level, default)
  2. &lt;checkout-root&gt;/.beads/formulas/ (repo-local formulas)
  3. ~/.beads/formulas/     (user-level, if project not writable)

Examples:
  bd mol distill bd-o5xe my-workflow
  bd mol distill bd-abc release-workflow --var feature_name=auth-refactor

```
bd mol distill <epic-id> [formula-name] [flags]
```

**Flags:**

```
      --dry-run           Preview what would be created
      --output string     Output directory for formula file
      --var stringArray   Replace value with {{variable}} placeholder (variable=value)
```

### bd mol last-activity

Show the most recent activity timestamp for a molecule.

Returns the timestamp of the most recent change to any step in the molecule,
making it easy to detect stale or stuck molecules.

Activity sources:
  step_closed      - A step was closed
  step_updated     - A step was updated (claimed, edited, etc.)
  molecule_updated - The molecule root itself was updated

Examples:
  bd mol last-activity hq-wisp-0laki
  bd mol last-activity hq-wisp-0laki --json

```
bd mol last-activity <molecule-id> [flags]
```

### bd mol pour

Pour a proto into a persistent mol - like pouring molten metal into a mold.

This is the chemistry-inspired command for creating PERSISTENT work from templates.
The resulting mol lives in .beads/ (permanent storage) and is synced with git.

Phase transition: Proto (solid) -&gt; pour -&gt; Mol (liquid)

WHEN TO USE POUR vs WISP:
  pour (liquid): Persistent work that needs audit trail
    - Feature implementations spanning multiple sessions
    - Work you may need to reference later
    - Anything worth preserving in git history

  wisp (vapor): Ephemeral work that auto-cleans up
    - Release workflows (one-time execution)
    - Operational loops and recurring cycles
    - Health checks and diagnostics
    - Any operational workflow without audit value

TIP: Formulas can specify phase:"vapor" to recommend wisp usage.
     If you pour a vapor-phase formula, you'll get a warning.

Examples:
  bd mol pour mol-feature --var name=auth    # Persistent feature work
  bd mol pour mol-review --var pr=123        # Persistent code review

```
bd mol pour <proto-id> [flags]
```

**Flags:**

```
      --assignee string      Assign the root issue to this agent/user
      --attach strings       Proto to attach after spawning (repeatable)
      --attach-type string   Bond type for attachments: sequential, parallel, or conditional (default "sequential")
      --dry-run              Preview what would be created
      --var stringArray      Variable substitution (key=value)
```

### bd mol progress

Show efficient progress summary for a molecule.

This command uses indexed queries to count progress without loading all steps,
making it suitable for very large molecules (millions of steps).

If no molecule-id is given, shows progress for any molecule you're working on.

Output includes:
  - Progress: completed / total (percentage)
  - Current step: the in-progress step (if any)
  - Rate: steps/hour based on closure times
  - ETA: estimated time to completion

Example:
  bd mol progress bd-hanoi-xyz

```
bd mol progress [molecule-id] [flags]
```

### bd mol ready

Find molecules where a gate has closed and the workflow is ready to resume.

This command discovers molecules waiting at a gate step where:
1. The molecule has a gate bead that blocks a step
2. The gate bead is now closed (condition satisfied)
3. The blocked step is now ready to proceed
4. No agent currently has this molecule hooked

This enables discovery-based resume without explicit waiter tracking.
The patrol system uses this to find and dispatch gate-ready molecules.

Examples:
  bd mol ready --gated           # Find all gate-ready molecules
  bd mol ready --gated --json    # JSON output for automation

```
bd mol ready --gated [flags]
```

### bd mol seed

Verify that a formula is accessible and can be cooked.

The seed command checks formula search paths to ensure a formula exists
and can be loaded. This is useful for verifying system health before
attempting to spawn work from a formula.

Formula search paths (checked in order):
  1. &lt;resolved-beads-dir&gt;/formulas/ (active project)
  2. &lt;checkout-root&gt;/.beads/formulas/ (repo-local formulas)
  3. ~/.beads/formulas/ (user level)
  4. $GT_ROOT/.beads/formulas/ (shared workspace root, if GT_ROOT set)

Examples:
  bd mol seed mol-feature                 # Verify specific formula
  bd mol seed mol-review --var name=test  # Verify with variable substitution

```
bd mol seed <formula-name> [flags]
```

**Flags:**

```
      --var stringArray   Variable substitution for condition filtering (key=value)
```

### bd mol show

Show molecule structure and details.

The --parallel flag highlights parallelizable steps:
  - Steps with no blocking dependencies can run in parallel
  - Shows which steps are ready to start now
  - Identifies parallel groups (steps that can run concurrently)

Example:
  bd mol show bd-patrol --parallel

```
bd mol show <molecule-id> [flags]
```

**Flags:**

```
  -p, --parallel   Show parallel step analysis
```

### bd mol squash

Squash a molecule's ephemeral children into a single digest issue.

This command collects all ephemeral child issues of a molecule (Ephemeral=true),
generates a summary digest, and promotes the wisps to persistent by
clearing their Wisp flag (or optionally deletes them).

The squash operation:
  1. Loads the molecule and all its children
  2. Filters to only wisps (ephemeral issues with Ephemeral=true)
  3. Generates a digest (summary of work done)
  4. Creates a permanent digest issue (Ephemeral=false)
  5. Clears Wisp flag on children (promotes to persistent)
     OR keeps them with --keep-children (default: delete)

AGENT INTEGRATION:
Use --summary to provide an AI-generated summary. This keeps bd as a pure
tool - the calling agent (orchestrator worker, Claude Code, etc.) is responsible
for generating intelligent summaries. Without --summary, a basic concatenation
of child issue content is used.

This is part of the wisp workflow: spawn creates wisps,
execution happens, squash compresses the trace into an outcome (digest).

Example:
  bd mol squash bd-abc123                    # Squash and promote children
  bd mol squash bd-abc123 --dry-run          # Preview what would be squashed
  bd mol squash bd-abc123 --keep-children    # Keep wisps after digest
  bd mol squash bd-abc123 --summary "Agent-generated summary of work done"

```
bd mol squash <molecule-id> [flags]
```

**Flags:**

```
      --dry-run          Preview what would be squashed
      --keep-children    Don't delete ephemeral children after squash
      --summary string   Agent-provided summary (bypasses auto-generation)
```

### bd mol stale

Detect molecules (epics with children) that are complete but still open.

A molecule is considered stale if:
  1. All children are closed (Completed == Total)
  2. Root issue is still open
  3. Not assigned to anyone (optional, use --unassigned)
  4. Is blocking other work (optional, use --blocking)

By default, shows all complete-but-unclosed molecules.

Examples:
  bd mol stale              # List all stale molecules
  bd mol stale --json       # Machine-readable output
  bd mol stale --blocking   # Only show those blocking other work
  bd mol stale --unassigned # Only show unassigned molecules
  bd mol stale --all        # Include molecules with 0 children

```
bd mol stale [flags]
```

**Flags:**

```
      --all          Include molecules with 0 children
      --blocking     Only show molecules blocking other work
      --unassigned   Only show unassigned molecules
```

### bd mol wisp

Create or manage wisps - EPHEMERAL molecules for operational workflows.

When called with a proto-id argument, creates a wisp from that proto.
When called with a subcommand (list, gc), manages existing wisps.

Wisps are issues with Ephemeral=true in the main database. They're stored
locally but NOT synced via git.

WHEN TO USE WISP vs POUR:
  wisp (vapor): Ephemeral work that auto-cleans up
    - Release workflows (one-time execution)
    - Operational loops and recurring cycles
    - Health checks and diagnostics
    - Any operational workflow without audit value

  pour (liquid): Persistent work that needs audit trail
    - Feature implementations spanning multiple sessions
    - Work you may need to reference later
    - Anything worth preserving in git history

TIP: Formulas can specify phase:"vapor" to recommend wisp usage.
     If you use pour on a vapor-phase formula, you'll get a warning.

The wisp lifecycle:
  1. Create: bd mol wisp &lt;proto&gt; or bd create --ephemeral
  2. Execute: Normal bd operations work on wisp issues
  3. Squash: bd mol squash &lt;id&gt; (clears Ephemeral flag, promotes to persistent)
  4. Or burn: bd mol burn &lt;id&gt; (deletes without creating digest)

Examples:
  bd mol wisp beads-release --var version=1.0  # Release workflow
  bd mol wisp mol-my-workflow                  # Ephemeral operational cycle
  bd mol wisp list                             # List all wisps
  bd mol wisp gc                               # Garbage collect old wisps

Subcommands:
  list  List all wisps in current context
  gc    Garbage collect orphaned wisps

```
bd mol wisp [proto-id] [flags]
```

**Flags:**

```
      --dry-run           Preview what would be created
      --root-only         Create only the root issue (no child step issues)
      --var stringArray   Variable substitution (key=value)
```

#### bd mol wisp create

Create a wisp from a proto - sublimation from solid to vapor.

This is the chemistry-inspired command for creating ephemeral work from templates.
The resulting wisp is stored in the main database with Ephemeral=true and NOT synced via git.

Phase transition: Proto (solid) -&gt; Wisp (vapor)

Use wisp for:
  - Operational loops and recurring cycles
  - Health checks and monitoring
  - One-shot orchestration runs
  - Routine operations with no audit value

The wisp will:
  - Be stored in main database with Ephemeral=true flag
  - NOT be synced via git
  - Either evaporate (burn) or condense to digest (squash)

Examples:
  bd mol wisp create mol-patrol                    # Ephemeral patrol cycle
  bd mol wisp create mol-health-check              # One-time health check
  bd mol wisp create mol-diagnostics --var target=db  # Diagnostic run

```
bd mol wisp create <proto-id> [flags]
```

**Flags:**

```
      --dry-run           Preview what would be created
      --root-only         Create only the root issue (no child step issues)
      --var stringArray   Variable substitution (key=value)
```

#### bd mol wisp gc

Garbage collect old or abandoned wisps from the database.

A wisp is considered abandoned if:
  - It hasn't been updated in --age duration and is not closed

Abandoned wisps are deleted without creating a digest. Use 'bd mol squash'
if you want to preserve a summary before garbage collection.

Use --closed to purge ALL closed wisps (regardless of age). This is the
fastest way to reclaim space from accumulated wisp bloat. Safe by default:
requires --force to actually delete.

Note: This uses time-based cleanup, appropriate for ephemeral wisps.
For graph-pressure staleness detection (blocking other work), see 'bd mol stale'.

Examples:
  bd mol wisp gc                                    # Clean abandoned wisps (default: 1h threshold)
  bd mol wisp gc --dry-run                          # Preview what would be cleaned
  bd mol wisp gc --age 24h                          # Custom age threshold
  bd mol wisp gc --all                              # Also clean closed wisps older than threshold
  bd mol wisp gc --closed                           # Preview closed wisp deletion
  bd mol wisp gc --closed --force                   # Delete all closed wisps
  bd mol wisp gc --closed --dry-run                 # Explicit dry-run (same as no --force)
  bd mol wisp gc --exclude-type agent,rig           # Protect agent and rig wisps from GC
  bd mol wisp gc --closed --force --exclude-type mol # Delete closed wisps except mol type

```
bd mol wisp gc [flags]
```

**Flags:**

```
      --age string             Age threshold for abandoned wisp detection (default "1h")
      --all                    Also clean closed wisps older than threshold
      --closed                 Delete all closed wisps (ignores --age threshold)
      --dry-run                Preview what would be cleaned
      --exclude-type strings   Exclude wisps of these types from GC (comma-separated, e.g., agent,rig)
  -f, --force                  Actually delete (default: preview only)
```

#### bd mol wisp list

List all wisps (ephemeral molecules) in the current context.

Wisps are issues with Ephemeral=true in the main database. They are stored
locally but not synced via git.

The list shows:
  - ID: Issue ID of the wisp
  - Title: Wisp title
  - Status: Current status (open, in_progress, closed)
  - Started: When the wisp was created
  - Updated: Last modification time

Old wisp detection:
  - Old wisps haven't been updated in 24+ hours
  - Use 'bd mol wisp gc' to clean up old/abandoned wisps

Examples:
  bd mol wisp list              # List all wisps
  bd mol wisp list --json       # JSON output for programmatic use
  bd mol wisp list --all        # Include closed wisps

```
bd mol wisp list [flags]
```

**Flags:**

```
      --all           Include closed wisps
      --type string   Filter by issue type (e.g., agent, task, patrol)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc note`

## bd note

Append a note to an issue's notes field.

Shorthand for 'bd update &lt;id&gt; --append-notes "text"'.

Examples:
  bd note gt-abc "Fixed the flaky test"
  bd note gt-abc Fixed the flaky test
  echo "note from pipe" | bd note gt-abc --stdin
  bd note gt-abc --file notes.txt

```
bd note <id> [text...] [flags]
```

**Flags:**

```
      --file string   Read note text from file
      --stdin         Read note text from stdin
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc notion`

## bd notion

Commands for syncing issues between beads and Notion.

```
bd notion [flags]
```

### bd notion connect

Connect bd to an existing Notion database or data source

```
bd notion connect [flags]
```

**Flags:**

```
      --url string   Existing Notion database or data source URL
```

### bd notion init

Create a dedicated Beads database in Notion

```
bd notion init [flags]
```

**Flags:**

```
      --parent string   Parent page ID
      --title string    Database title (default "Beads Issues")
```

### bd notion pull

Pull one or more items from Notion.

Accepts bead IDs or external references as positional arguments.
Equivalent to: bd notion sync --pull --issues &lt;refs&gt;

```
bd notion pull [refs...] [flags]
```

**Flags:**

```
      --dry-run   Preview pull without making changes
```

### bd notion push

Push one or more beads issues to Notion.

Accepts bead IDs as positional arguments.
Equivalent to: bd notion sync --push --issues &lt;ids&gt;

```
bd notion push [bead-ids...] [flags]
```

**Flags:**

```
      --dry-run   Preview push without making changes
```

### bd notion status

Show Notion sync status

```
bd notion status [flags]
```

### bd notion sync

Synchronize issues between beads and Notion.

By default this performs bidirectional sync. Use --pull or --push to limit direction.

```
bd notion sync [flags]
```

**Flags:**

```
      --create-only     Only create missing remote pages, do not update existing ones
      --dry-run         Preview changes without making mutations
      --issues string   Comma-separated bead IDs to sync selectively (e.g., bd-abc,bd-def). Mutually exclusive with --parent.
      --parent string   Limit push to this bead and its descendants (push only). Mutually exclusive with --issues.
      --prefer-local    On conflict, keep the local beads version
      --prefer-notion   On conflict, use the Notion version
      --pull            Only pull issues from Notion
      --push            Only push issues to Notion
      --state string    Issue state to sync: open, closed, or all (default "all")
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc onboard`

## bd onboard

Display a minimal snippet to add to your agent instructions file for bd integration.

By default, the agent instructions file is AGENTS.md. Use 'bd init --agents-file'
to configure a different filename (e.g. BEADS.md).

This outputs a small (~10 line) snippet that points to 'bd prime' for full
workflow context. This is the same minimal profile that 'bd init' generates
by default. This approach:

  • Keeps your agent file lean (doesn't bloat with instructions)
  • bd prime provides dynamic, always-current workflow details
  • Hooks auto-inject bd prime at session start

For agents or environments that do not auto-inject hook output, use
'bd init --agents-profile=full' to embed the complete command reference.

```
bd onboard [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc orphans`

## bd orphans

Identify orphaned issues - issues that are referenced in commit messages but remain open or in_progress in the database.

This helps identify work that has been implemented but not formally closed.

Examples:
  bd orphans              # Show orphaned issues
  bd orphans --json       # Machine-readable output
  bd orphans --details    # Show full commit information
  bd orphans --fix        # Close orphaned issues with confirmation
  bd orphans --label theme:personal             # Only orphans with this label
  bd orphans --label-any theme:personal,theme:ventures  # Orphans with either label

```
bd orphans [flags]
```

**Flags:**

```
      --details             Show full commit information
  -f, --fix                 Close orphaned issues with confirmation
  -l, --label strings       Filter by labels (AND: must have ALL). Can combine with --label-any
      --label-any strings   Filter by labels (OR: must have AT LEAST ONE). Can combine with --label
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc ping`

## bd ping

Lightweight health check that confirms bd can reach its database.

Steps:
  1. Resolve the .beads workspace
  2. Open the store (embedded or server)
  3. Run a trivial query (issue count)
  4. Report timing

Exit 0 on success, exit 1 on failure.

Examples:
  bd ping              # Quick connectivity check
  bd ping --json       # Structured output for automation

```
bd ping [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc preflight`

## bd preflight

Display a checklist of common pre-PR checks for contributors.

This command helps catch common issues before pushing to CI:
- Tests not run locally
- Lint errors
- Unformatted Go files
- .beads/issues.jsonl pollution
- Stale nix vendorHash
- Version mismatches

Examples:
  bd preflight              # Show checklist
  bd preflight --check      # Run checks automatically
  bd preflight --check --json  # JSON output for programmatic use
  bd preflight --check --skip-lint  # Explicitly skip lint check


```
bd preflight [flags]
```

**Flags:**

```
      --check       Run checks automatically
      --fix         Auto-fix issues where possible (not yet implemented)
      --json        Output results as JSON
      --skip-lint   Skip lint check explicitly
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc prime`

## bd prime

Output essential Beads workflow context in AI-optimized markdown format.

Automatically detects if MCP server is active and adapts output:
- MCP mode: Brief workflow reminders (~50 tokens)
- CLI mode: Full command reference (~1-2k tokens)

Designed for Claude Code, Gemini CLI, and Codex SessionStart hooks to prevent
agents from forgetting bd workflow after context compaction.

Config options:
- no-git-ops: When true, outputs stealth mode (no git commands in session close protocol).
  Set via: bd config set no-git-ops true
  Useful when you want to control when commits happen manually.

	Workflow customization:
	- Place a .beads/PRIME.md file in the local clone or resolved workspace to override the default output entirely.
	- Use --export to dump the default content for customization.
	- Use --memories-only for hook contexts that should inject only persistent memories.

```
bd prime [flags]
```

**Flags:**

```
      --export          Output default content (ignores PRIME.md override)
      --full            Force full CLI output (ignore MCP detection)
      --hook-json       Wrap output in the SessionStart hook JSON envelope (Claude Code, Gemini CLI, Codex)
      --mcp             Force MCP mode (minimal output)
      --memories-only   Output only persistent memories for compact hook contexts
      --stealth         Stealth mode (no git operations, flush only)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc priority`

## bd priority

Set the priority of an issue.

Shorthand for 'bd update &lt;id&gt; --priority &lt;n&gt;'.

Priority levels:
  0 - Critical (security, data loss, broken builds)
  1 - High (major features, important bugs)
  2 - Medium (default)
  3 - Low (polish, optimization)
  4 - Backlog (future ideas)

Examples:
  bd priority bd-123 0    # Critical
  bd priority bd-123 2    # Medium

```
bd priority <id> <n> [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc promote`

## bd promote

Promote a wisp (ephemeral issue) to a permanent bead.

This copies the issue from the wisps table (dolt_ignored) to the permanent
issues table (Dolt-versioned), preserving labels, dependencies, events, and
comments. The original ID is preserved so all links keep working.

A comment is added recording the promotion and optional reason.

Examples:
  bd promote bd-wisp-abc123
  bd promote bd-wisp-abc123 --reason "Worth tracking long-term"

```
bd promote <wisp-id> [flags]
```

**Flags:**

```
  -r, --reason string   Reason for promotion
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc prune`

## bd prune

Permanently delete closed non-ephemeral beads and their associated data.

Use this to trim closed regular beads (tasks, features, bugs, chores, etc.)
that are no longer useful. The common case is a long-lived repo where
closed work has piled up and is bloating auto-export or slowing queries.

Requires --older-than or --pattern. The flag is a safety gate — without
it, a muscle-memory `--force` could wipe every closed bead in the repo.
Use `--pattern '*'` if you really do want to sweep everything closed.

Deletes: issues, dependencies, labels, events, and comments for matching beads.
Skips: pinned beads (protected), open/in-progress beads, and ephemeral beads.

To delete closed ephemeral beads (wisps, transient molecules) use
`bd purge` instead.

For full Dolt storage reclaim after deleting many rows, follow with `bd flatten`
so history can be collapsed and old chunks can be garbage-collected.

EXAMPLES:
  bd prune --older-than 30d              # Preview closed beads &gt;30d old
  bd prune --older-than 30d --force      # Delete them
  bd prune --older-than 90d --dry-run    # Detailed preview with stats
  bd prune --pattern "*" --force         # Delete all closed regular beads
  bd prune --pattern "gm-temp-*" --force # Scope to a pattern

```
bd prune [flags]
```

**Flags:**

```
      --dry-run             Preview what would be pruned with stats
  -f, --force               Actually prune (without this, shows preview)
      --older-than string   Only prune beads closed more than N ago (e.g., 30d, 2w, 60)
      --pattern string      Only prune beads matching ID glob pattern (e.g., 'gm-old-*')
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc purge`

## bd purge

Permanently delete closed ephemeral beads and their associated data.

Closed ephemeral beads (wisps, transient molecules) accumulate rapidly and
have no value once closed. This command removes them to reclaim storage.

Deletes: issues, dependencies, labels, events, and comments for matching beads.
Skips: pinned beads (protected).

To delete closed non-ephemeral beads (regular tasks, features, bugs, etc.)
use `bd prune` instead.

For full Dolt storage reclaim after deleting many rows, follow with `bd flatten`
so history can be collapsed and old chunks can be garbage-collected.

EXAMPLES:
  bd purge                           # Preview what would be purged
  bd purge --force                   # Delete all closed ephemeral beads
  bd purge --older-than 7d --force   # Only purge items closed 7+ days ago
  bd purge --pattern "*-wisp-*"      # Only purge matching ID pattern
  bd purge --dry-run                 # Detailed preview with stats

```
bd purge [flags]
```

**Flags:**

```
      --dry-run             Preview what would be purged with stats
  -f, --force               Actually purge (without this, shows preview)
      --older-than string   Only purge beads closed more than N ago (e.g., 7d, 2w, 30)
      --pattern string      Only purge beads matching ID glob pattern (e.g., *-wisp-*)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc q`

## bd q

Quick capture creates an issue and outputs only the issue ID.
Designed for scripting and AI agent integration.

Example:
  bd q "Fix login bug"           # Outputs: bd-a1b2
  ISSUE=$(bd q "New feature")    # Capture ID in variable
  bd q "Task" | xargs bd show    # Pipe to other commands

```
bd q [title] [flags]
```

**Flags:**

```
  -l, --labels strings    Labels
  -p, --priority string   Priority (0-4 or P0-P4) (default "2")
  -t, --type string       Issue type (default "task")
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc query`

## bd query

Query issues using a simple query language that supports compound filters,
boolean operators, and date-relative expressions.

The query language enables complex filtering that would otherwise require
multiple flags or piping through jq.

Syntax:
  field=value       Equality comparison
  field!=value      Inequality comparison
  field&gt;value       Greater than
  field&gt;=value      Greater than or equal
  field&lt;value       Less than
  field&lt;=value      Less than or equal

Boolean operators (case-insensitive):
  expr AND expr     Both conditions must match
  expr OR expr      Either condition can match
  NOT expr          Negates the condition
  (expr)            Grouping with parentheses

Supported fields:
  status            Stored status (open, in_progress, blocked, deferred, closed). Note: dependency-blocked issues stay "open"; use 'bd blocked' to find them
  priority          Priority level (0-4)
  type              Issue type (bug, feature, task, epic, chore, decision)
  assignee          Assigned user (use "none" for unassigned)
  owner             Issue owner
  label             Issue label (use "none" for unlabeled)
  title             Search in title (contains)
  description       Search in description (contains, "none" for empty)
  notes             Search in notes (contains)
  created           Creation date/time
  updated           Last update date/time
  started           Date/time issue first transitioned to in_progress
  closed            Close date/time
  id                Issue ID (supports wildcards: bd-*)
  spec              Spec ID (supports wildcards)
  pinned            Boolean (true/false)
  ephemeral         Boolean (true/false)
  template          Boolean (true/false)
  parent            Parent issue ID
  mol_type          Molecule type (swarm, patrol, work)

Date values:
  Relative durations: 7d (7 days ago), 24h (24 hours ago), 2w (2 weeks ago)
  Absolute dates: 2025-01-15, 2025-01-15T10:00:00Z
  Natural language: tomorrow, "next monday", "in 3 days"

Examples:
  bd query "status=open AND priority&gt;1"
  bd query "status=open AND priority&lt;=2 AND updated&gt;7d"
  bd query "(status=open OR status=blocked) AND priority&lt;2"
  bd query "type=bug AND label=urgent"
  bd query "NOT status=closed"
  bd query "assignee=none AND type=task"
  bd query "created&gt;30d AND status!=closed"
  bd query "label=frontend OR label=backend"
  bd query "title=authentication AND priority=0"

```
bd query [expression] [flags]
```

**Flags:**

```
  -a, --all           Include closed issues (default: exclude closed)
  -n, --limit int     Limit results (default: 50, 0 = unlimited) (default 50)
      --long          Show detailed multi-line output for each issue
      --offset int    Skip the first N matching results (0-based). Only supported under --proxied-server.
      --parse-only    Only parse the query and show the AST (for debugging)
  -r, --reverse       Reverse sort order
      --sort string   Sort by field: priority, created, updated, closed, status, id, title, type, assignee
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc quickstart`

## bd quickstart

Display a quick start guide showing common bd workflows and patterns.

```
bd quickstart [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc ready`

## bd ready

Show ready work (open issues with no active blockers).

Excludes in_progress, blocked, deferred, and hooked issues. This uses the
GetReadyWork API which applies blocker-aware semantics to find truly claimable work.

Note: 'bd list --ready' uses the same blocker-aware ready-work semantics.

Use --mol to filter to a specific molecule's steps:
  bd ready --mol bd-patrol   # Show ready steps within molecule

Use --gated to find molecules ready for gate-resume dispatch:
  bd ready --gated           # Find molecules where a gate closed

Use --claim to atomically claim the first ready issue matching the filters:
  bd ready --claim --json

This is useful for agents executing molecules to see which steps can run next.

```
bd ready [flags]
```

**Flags:**

```
  -a, --assignee string              Filter by assignee
      --claim                        Atomically claim the first ready issue matching the filters
      --exclude-label strings        Exclude issues that have ANY of these labels
      --exclude-type strings         Exclude issue types from results (comma-separated or repeatable, e.g., --exclude-type=convoy,epic)
      --explain                      Show dependency-aware reasoning for why issues are ready or blocked
      --gated                        Find molecules ready for gate-resume dispatch
      --has-metadata-key string      Filter issues that have this metadata key set
      --include-deferred             Include issues with future defer_until timestamps
      --include-ephemeral            Include ephemeral issues (wisps) in results
  -l, --label strings                Filter by labels (AND: must have ALL). Can combine with --label-any
      --label-any strings            Filter by labels (OR: must have AT LEAST ONE). Can combine with --label
  -n, --limit int                    Maximum issues to show (use 0 for unlimited) (default 100)
      --metadata-field stringArray   Filter by metadata field (key=value, repeatable)
      --mol string                   Filter to steps within a specific molecule
      --mol-type string              Filter by molecule type: swarm, patrol, or work
      --offset int                   Skip the first N matching results (0-based). Only supported under --proxied-server.
      --parent string                Filter to descendants of this bead/epic
      --plain                        Display issues as a plain numbered list
      --pretty                       Display issues in a tree format with status/priority symbols (default true)
  -p, --priority int                 Filter by priority
  -s, --sort string                  Sort policy: priority (default), hybrid, oldest (default "priority")
  -t, --type string                  Filter by issue type (task, bug, feature, epic, decision, merge-request). Aliases: mr→merge-request, feat→feature, mol→molecule, dec/adr→decision
  -u, --unassigned                   Show only unassigned issues
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc recall`

## bd recall

Retrieve the full content of a memory by its key.

Examples:
  bd recall dolt-phantoms
  bd recall auth-jwt

```
bd recall <key> [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc recompute-blocked`

## bd recompute-blocked

Recompute the denormalized is_blocked flag for every issue and wisp.

is_blocked is derived from the dependency graph and maintained automatically by
local writes and by a post-pull recompute scoped to what the merge changed. If
that scoped recompute is skipped — a recompute that failed after its merge
committed, or a conflicted pull resolved by hand — the flag can go stale, and a
later pull that merges nothing will not refresh it (bd-6dnrw.37). 'bd ready'
trusts the flag, so stale values silently hide ready work or surface blocked
work.

This command runs the full recompute unconditionally and commits the result.
It is idempotent: on a consistent database it changes nothing. Works in both
embedded and server mode (unlike 'bd doctor', which is server-mode only).

Examples:
  bd recompute-blocked          # Repair stale is_blocked flags
  bd recompute-blocked --json   # Machine-parseable &#123;"rows_corrected": N&#125;

```
bd recompute-blocked [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc remember`

## bd remember

Store a memory that persists across sessions and account rotations.

Memories are injected at prime time (bd prime) so you have them
in every session without manual loading.

The positional arg is the memory CONTENT (the key is auto-generated from it
unless --key is given). As a convenience, if the arg is a bare key naming an
existing memory, it is RECALLED instead of stored (same as 'bd recall');
a bare key naming nothing is refused. Use --key to store slug-like content.

Examples:
  bd remember "always run tests with -race flag"
  bd remember "Dolt phantom DBs hide in three places" --key dolt-phantoms
  bd remember "auth module uses JWT not sessions" --key auth-jwt
  bd remember dolt-phantoms        # bare existing key: reads it (= bd recall)

```
bd remember "<insight>" [flags]
```

**Flags:**

```
      --key string   Explicit key for the memory (auto-generated from content if not set). If a memory with this key already exists, it will be updated in place
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc rename-prefix`

## bd rename-prefix

Rename the issue prefix for all issues in the database.
This will update all issue IDs and all text references across all fields.

USE CASES:
- Shortening long prefixes (e.g., 'knowledge-work-' → 'kw-')
- Rebranding project naming conventions
- Consolidating multiple prefixes after database corruption
- Migrating to team naming standards

Prefix validation rules:
- Max length: 8 characters
- Allowed characters: lowercase letters, numbers, hyphens
- Must start with a letter
- Must end with a hyphen (e.g., 'kw-', 'work-')
- Cannot be empty or just a hyphen

Multiple prefix detection and repair:
If issues have multiple prefixes (corrupted database), use --repair to consolidate them.
The --repair flag will rename all issues with incorrect prefixes to the new prefix,
preserving issues that already have the correct prefix.

EXAMPLES:
  bd rename-prefix kw-                # Rename from 'knowledge-work-' to 'kw-'
  bd rename-prefix mtg- --repair      # Consolidate multiple prefixes into 'mtg-'
  bd rename-prefix team- --dry-run    # Preview changes without applying

NOTE: This is a rare operation. Most users never need this command.

```
bd rename-prefix <new-prefix> [flags]
```

**Flags:**

```
      --dry-run   Preview changes without applying them
      --repair    Repair database with multiple prefixes by consolidating them
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc rename`

## bd rename

Rename an issue from one ID to another.

This updates:
- The issue's primary ID
- All references in other issues (descriptions, titles, notes, etc.)
- Dependencies pointing to/from this issue
- Labels, comments, and events

Examples:
  bd rename bd-w382l bd-dolt     # Rename to memorable ID
  bd rename gt-abc123 gt-auth    # Use descriptive ID

Note: The new ID must use a valid prefix for this database.

```
bd rename <old-id> <new-id> [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc reopen`

## bd reopen

Reopen closed issues by setting status to 'open' and clearing the closed_at timestamp.
This is more explicit than 'bd update --status open' and emits a Reopened event.

```
bd reopen [id...] [flags]
```

**Flags:**

```
  -r, --reason string   Reason for reopening
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc repo`

## bd repo

Configure and manage multiple repository support for multi-repo hydration.

Multi-repo support allows hydrating issues from multiple beads repositories
into a single database for unified cross-repo issue tracking.

Configuration is stored in .beads/config.yaml under the 'repos' section:

  repos:
    primary: "."
    additional:
      - ~/beads-planning
      - ~/work-repo

Examples:
  bd repo add ~/beads-planning       # Add planning repo
  bd repo add ../other-repo          # Add relative path repo
  bd repo list                       # Show all configured repos
  bd repo remove ~/beads-planning    # Remove by path
  bd repo sync                       # Sync from all configured repos

```
bd repo [flags]
```

### bd repo add

Add a repository path to the repos.additional list in config.yaml.

The path should point to a directory containing a .beads folder.
Paths can be absolute or relative (they are stored as-is).

This modifies .beads/config.yaml, which is version-controlled and
shared across all clones of this repository.

```
bd repo add <path> [flags]
```

**Flags:**

```
      --json   Output JSON
```

### bd repo list

List all repositories configured in .beads/config.yaml.

Shows the primary repository (always ".") and any additional
repositories configured for hydration.

```
bd repo list [flags]
```

**Flags:**

```
      --json   Output JSON
```

### bd repo remove

Remove a repository path from the repos.additional list in config.yaml.

The path must exactly match what was added (e.g., if you added "~/foo",
you must remove "~/foo", not "/home/user/foo").

This command also removes any previously-hydrated issues from the database
that came from the removed repository.

```
bd repo remove <path> [flags]
```

**Flags:**

```
      --json   Output JSON
```

### bd repo sync

Synchronize issues from all configured additional repositories.

Reads issues.jsonl from each additional repository and imports them into
the primary database with their original prefixes and source_repo set.
Uses mtime caching to skip repos whose JSONL hasn't changed.

Also triggers Dolt push/pull if a remote is configured.

```
bd repo sync [flags]
```

**Flags:**

```
      --json      Output JSON
      --verbose   Show detailed sync progress
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc restore`

## bd restore

Restore the pre-compaction content of a compacted issue.

When an issue is compacted, its description/design/notes/acceptance criteria
are summarized and the originals are archived to a compaction snapshot. This
command recovers that original content.

By default it is read-only: it displays the archived content without modifying
the database. Pass --apply to write the original content back into the issue
and step its compaction level back down.

If no archived snapshot exists (e.g. the issue was compacted by an older bd
before snapshot archiving), restore falls back to a best-effort reconstruction
from Dolt version history, which can only be displayed, not applied.

```
bd restore <issue-id> [flags]
```

**Flags:**

```
      --apply   Write the restored content back into the issue (default: display only)
      --json    Output restore results in JSON format
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc rules`

## bd rules

Audit and compact Claude rules

```
bd rules [flags]
```

### bd rules audit

Scan rules for contradictions and merge opportunities

```
bd rules audit [flags]
```

**Flags:**

```
      --path string       Path to rules directory (default ".claude/rules/")
      --threshold float   Jaccard similarity threshold (default 0.6)
```

### bd rules compact

Merge related rules into composites

```
bd rules compact [flags]
```

**Flags:**

```
      --auto            Apply audit suggestions
      --dry-run         Preview without applying
      --group strings   Rule names to merge
      --path string     Path to rules directory (default ".claude/rules/")
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc search`

## bd search

Search issues across title and ID (excludes closed issues by default).

ID-like queries (e.g., "bd-123", "hq-319") use fast exact/prefix matching.
Text queries search titles. Use --desc-contains for description search.
Use --status all to include closed issues.

Examples:
  bd search "authentication bug"
  bd search "login" --status open
  bd search "database" --label backend --limit 10
  bd search --query "performance" --assignee alice
  bd search "bd-5q" # Search by partial ID (fast prefix match)
  bd search "security" --priority-min 0 --priority-max 2
  bd search "bug" --created-after 2025-01-01
  bd search "refactor" --status all  # Include closed issues
  bd search "bug" --sort priority
  bd search "task" --sort created --reverse
  bd search "api" --desc-contains "endpoint"
  bd search "cleanup" --no-assignee --no-labels

```
bd search [query] [flags]
```

**Flags:**

```
  -a, --assignee string              Filter by assignee
      --closed-after string          Filter issues closed after date (YYYY-MM-DD or RFC3339)
      --closed-before string         Filter issues closed before date (YYYY-MM-DD or RFC3339)
      --created-after string         Filter issues created after date (YYYY-MM-DD or RFC3339)
      --created-before string        Filter issues created before date (YYYY-MM-DD or RFC3339)
      --desc-contains string         Filter by description substring (case-insensitive)
      --empty-description            Filter issues with empty or missing description
      --external-contains string     Filter by external ref substring (case-insensitive)
      --has-metadata-key string      Filter issues that have this metadata key set
  -l, --label strings                Filter by labels (AND: must have ALL)
      --label-any strings            Filter by labels (OR: must have AT LEAST ONE)
  -n, --limit int                    Limit results (default: 50) (default 50)
      --long                         Show detailed multi-line output for each issue
      --metadata-field stringArray   Filter by metadata field (key=value, repeatable)
      --no-assignee                  Filter issues with no assignee
      --no-labels                    Filter issues with no labels
      --notes-contains string        Filter by notes substring (case-insensitive)
      --priority-max string          Filter by maximum priority (inclusive, 0-4 or P0-P4)
      --priority-min string          Filter by minimum priority (inclusive, 0-4 or P0-P4)
      --query string                 Search query (alternative to positional argument)
  -r, --reverse                      Reverse sort order
      --sort string                  Sort by field: priority, created, updated, closed, status, id, title, type, assignee
  -s, --status string                Filter by stored status (open, in_progress, blocked, deferred, closed, all). Default excludes closed; use 'all' to include closed. Note: dependency-blocked issues use 'bd blocked'
  -t, --type string                  Filter by type (bug, feature, task, epic, chore, decision, merge-request, molecule, gate)
      --updated-after string         Filter issues updated after date (YYYY-MM-DD or RFC3339)
      --updated-before string        Filter issues updated before date (YYYY-MM-DD or RFC3339)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc set-state`

## bd set-state

Atomically set operational state on an issue.

This command:
1. Creates an event bead recording the state change (source of truth)
2. Removes any existing label for the dimension
3. Adds the new dimension:value label (fast lookup cache)

State labels follow the convention &lt;dimension&gt;:&lt;value&gt;, for example:
  patrol:active, patrol:muted
  mode:normal, mode:degraded
  health:healthy, health:failing

Examples:
  bd set-state agent-abc patrol=muted --reason "Investigating stuck worker"
  bd set-state agent-abc mode=degraded --reason "High error rate detected"
  bd set-state agent-abc health=healthy

The --reason flag provides context for the event bead (recommended).

```
bd set-state <issue-id> <dimension>=<value> [flags]
```

**Flags:**

```
      --reason string   Reason for the state change (recorded in event)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc setup`

## bd setup

Setup integration files for AI editors and coding assistants.

Recipes define where beads workflow instructions are written. Built-in recipes
include cursor, claude, copilot, gemini, aider, factory, codex, mux, opencode, junie, windsurf, cody, and kilocode.

Examples:
  bd setup cursor          # Install Cursor IDE integration
  bd setup codex           # Install Codex skill + AGENTS.md guidance + native hooks
  bd setup codex --global  # Install global Codex skill + guidance + native hooks
  bd setup copilot         # Install Copilot CLI plugin + repository instructions
  bd setup mux --project   # Install Mux workspace layer (.mux/AGENTS.md)
  bd setup mux --global    # Install Mux global layer (~/.mux/AGENTS.md)
  bd setup mux --project --global  # Install both Mux layers
  bd setup --list          # Show all available recipes
  bd setup --print         # Print the template to stdout
  bd setup -o rules.md     # Write template to custom path
  bd setup --add myeditor .myeditor/rules.md  # Add custom recipe

Use 'bd setup &lt;recipe&gt; --check' to verify installation status.
Use 'bd setup &lt;recipe&gt; --remove' to uninstall.

```
bd setup [recipe] [flags]
```

**Flags:**

```
      --add string      Add a custom recipe with given name
      --check           Check if integration is installed
      --global          Install globally (claude/codex/mux; writes to ~/.claude/settings.json, $CODEX_HOME/AGENTS.md or ~/.codex/AGENTS.md, or ~/.mux/AGENTS.md)
      --list            List all available recipes
  -o, --output string   Write template to custom path
      --print           Print the template to stdout
      --project         Install for this project only (gemini/mux)
      --remove          Remove the integration
      --stealth         Use stealth mode (claude/gemini)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc ship`

## bd ship

Ship a capability to satisfy cross-project dependencies.

This command:
  1. Finds issue with export:&lt;capability&gt; label
  2. Validates issue is closed (or --force to override)
  3. Adds provides:&lt;capability&gt; label

External projects can depend on this capability using:
  bd dep add &lt;issue&gt; external:&lt;project&gt;:&lt;capability&gt;

The capability is resolved when the external project has a closed issue
with the provides:&lt;capability&gt; label.

Examples:
  bd ship mol-run-assignee              # Ship the mol-run-assignee capability
  bd ship mol-run-assignee --force      # Ship even if issue is not closed
  bd ship mol-run-assignee --dry-run    # Preview without making changes

```
bd ship <capability> [flags]
```

**Flags:**

```
      --dry-run   Preview without making changes
      --force     Ship even if issue is not closed
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc show`

## bd show

Show issue details

```
bd show [id...] [--id=<id>...] [--current] [flags]
```

**Aliases:** view

**Flags:**

```
      --as-of string         Show issue as it existed at a specific commit hash or branch (requires Dolt)
      --children             Show only the children of this issue
      --current              Show the currently active issue (in-progress, hooked, or last touched)
      --id stringArray       Issue ID (use for IDs that look like flags, e.g., --id=gt--xyz)
      --include-comments     Stream full comment bodies in JSON output (--json only; may be slow on issues with many comments)
      --include-dependents   Stream full dependent issues in JSON output (--json only; may be slow on hub beads)
      --local-time           Show timestamps in local time instead of UTC
      --long                 Show all available fields (extended metadata, agent identity, gate fields, etc.)
      --refs                 Show issues that reference this issue (reverse lookup)
      --short                Show compact one-line output per issue
      --thread               Show full conversation thread (for messages)
  -w, --watch                Watch for changes and auto-refresh display
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc sql`

## bd sql

Execute a raw SQL query against the underlying database (SQLite or Dolt).

Useful for debugging, maintenance, and working around bugs in higher-level commands.

Examples:
  bd sql 'SELECT COUNT(*) FROM issues'
  bd sql 'SELECT id, title FROM issues WHERE status = "open" LIMIT 5'
  bd sql 'DELETE FROM dirty_issues WHERE issue_id = "bd-abc123"'
  bd sql --csv 'SELECT id, title, status FROM issues'

The query is passed directly to the database. SELECT queries return results as a
table (or JSON/CSV with --json/--csv). Non-SELECT queries (INSERT, UPDATE, DELETE)
report the number of rows affected.

WARNING: Direct database access bypasses the storage layer. Use with caution.

```
bd sql <query> [flags]
```

**Flags:**

```
      --csv   Output results in CSV format
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc stale`

## bd stale

Show issues that haven't been updated recently and may need attention.
This helps identify:
- In-progress issues with no recent activity (may be abandoned)
- Open issues that have been forgotten
- Issues that might be outdated or no longer relevant

```
bd stale [flags]
```

**Flags:**

```
  -d, --days int        Issues not updated in this many days (default 30)
  -n, --limit int       Maximum issues to show (default 50)
  -s, --status string   Filter by status (open|in_progress|blocked|deferred)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc state`

## bd state

Query the current value of a state dimension from an issue's labels.

State labels follow the convention &lt;dimension&gt;:&lt;value&gt;, for example:
  patrol:active
  mode:degraded
  health:healthy

This command extracts the value for a given dimension.

Examples:
  bd state witness-abc patrol     # Output: active
  bd state witness-abc mode       # Output: normal
  bd state witness-abc health     # Output: healthy

```
bd state <issue-id> <dimension> [flags]
```

### bd state list

List all state labels (dimension:value format) on an issue.

This filters labels to only show those following the state convention.

Example:
  bd state list witness-abc
  # Output:
  #   patrol: active
  #   mode: normal
  #   health: healthy

```
bd state list <issue-id> [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc status`

## bd status

Show a quick snapshot of the issue database state and statistics.

This command provides a summary of issue counts by state (open, in_progress,
blocked, closed), ready work, extended statistics (pinned issues,
average lead time), and recent activity over the last 24 hours from git history.

Similar to how 'git status' shows working tree state, 'bd status' gives you
a quick overview of your issue database without needing multiple queries.

Use cases:
  - Quick project health check
  - Onboarding for new contributors
  - Integration with shell prompts or CI/CD
  - Daily standup reference

Examples:
  bd status                    # Show summary with activity
  bd status --no-activity      # Skip git activity (faster)
  bd status --json             # JSON format output
  bd status --assigned         # Show issues assigned to current user
  bd stats                     # Alias for bd status

```
bd status [flags]
```

**Aliases:** stats

**Flags:**

```
      --all           Show all issues (default behavior)
      --assigned      Show issues assigned to current user
      --no-activity   Skip git activity tracking (faster)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc statuses`

## bd statuses

List all valid issue statuses and their categories.

Built-in statuses (open, in_progress, blocked, etc.) are always valid.
Additional statuses can be configured via status.custom:

  bd config set status.custom "in_review:active,qa_testing:wip,on_hold:frozen"

Categories control behavior:
  active  — appears in 'bd ready' and default 'bd list'
  wip     — excluded from 'bd ready', visible in default 'bd list'
  done    — excluded from 'bd ready' and default 'bd list'
  frozen  — excluded from 'bd ready' and default 'bd list'

Statuses without a category (legacy format) are valid but excluded from 'bd ready'.

Examples:
  bd statuses            # List all statuses with icons and categories
  bd statuses --json     # Output as JSON


```
bd statuses [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc supersede`

## bd supersede

Mark an issue as superseded by a newer version.

The superseded issue is automatically closed with a reference to the replacement.
Useful for design docs, specs, and evolving artifacts.

Examples:
  bd supersede bd-old --with bd-new    # Mark bd-old as superseded by bd-new

```
bd supersede <id> --with <new> [flags]
```

**Flags:**

```
      --with string   Replacement issue ID (required)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc swarm`

## bd swarm

Swarm management commands for coordinating parallel work on epics.

A swarm is a structured body of work defined by an epic and its children,
with dependencies forming a DAG (directed acyclic graph) of work.

```
bd swarm [flags]
```

### bd swarm create

Create a swarm molecule to orchestrate parallel work on an epic.

The swarm molecule:
- Links to the epic it orchestrates
- Has mol_type=swarm for discovery
- Specifies a coordinator (optional)
- Can be picked up by any coordinator agent

If given a single issue (not an epic), it will be auto-wrapped:
- Creates an epic with that issue as its only child
- Then creates the swarm molecule for that epic

Examples:
  bd swarm create bd-epic-123                          # Create swarm for epic
  bd swarm create bd-epic-123 --coordinator=observer/   # With specific coordinator
  bd swarm create bd-task-456                          # Auto-wrap single issue

```
bd swarm create [epic-id] [flags]
```

**Flags:**

```
      --coordinator string   Coordinator address (e.g., my-project/witness)
      --force                Create new swarm even if one already exists
```

### bd swarm list

List all swarm molecules with their status.

Shows each swarm molecule with:
- Progress (completed/total issues)
- Active workers
- Epic ID and title

Examples:
  bd swarm list         # List all swarms
  bd swarm list --json  # Machine-readable output

```
bd swarm list [flags]
```

### bd swarm status

Show the current status of a swarm, computed from beads.

Accepts either:
- An epic ID (shows status for that epic's children)
- A swarm molecule ID (follows the link to find the epic)

Displays issues grouped by state:
- Completed: Closed issues
- Active: Issues currently in_progress (with assignee)
- Ready: Open issues with all dependencies satisfied
- Blocked: Open issues waiting on dependencies

The status is COMPUTED from beads, not stored separately.
If beads changes, status changes.

Examples:
  bd swarm status gt-epic-123       # Show swarm status by epic
  bd swarm status gt-swarm-456      # Show status via swarm molecule
  bd swarm status gt-epic-123 --json  # Machine-readable output

```
bd swarm status [epic-or-swarm-id] [flags]
```

### bd swarm validate

Validate an epic's structure to ensure it's ready for swarm execution.

Checks for:
- Correct dependency direction (requirement-based, not temporal)
- Orphaned issues (roots with no dependents)
- Missing dependencies (leaves that should depend on something)
- Cycles (impossible to resolve)
- Disconnected subgraphs

Reports:
- Ready fronts (waves of parallel work)
- Estimated worker-sessions
- Maximum parallelism
- Warnings for potential issues

Examples:
  bd swarm validate gt-epic-123           # Validate epic structure
  bd swarm validate gt-epic-123 --verbose # Include detailed issue graph

```
bd swarm validate [epic-id] [flags]
```

**Flags:**

```
      --verbose   Include detailed issue graph in output
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc tag`

## bd tag

Add a label to an issue.

Shorthand for 'bd update &lt;id&gt; --add-label &lt;label&gt;'.

Examples:
  bd tag bd-123 bug
  bd tag bd-123 needs-review

```
bd tag <id> <label> [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc todo`

## bd todo

Manage TODO items as lightweight task issues.

TODOs are regular task-type issues with convenient shortcuts:
  bd todo add "Title"    -&gt; bd create "Title" -t task -p 2
  bd todo                -&gt; bd list --type task --status open
  bd todo done &lt;id&gt;      -&gt; bd close &lt;id&gt;

TODOs can be promoted to full issues by changing type or priority:
  bd update todo-123 --type bug --priority 0

```
bd todo [flags]
```

### bd todo add

Add a new TODO item

```
bd todo add <title> [flags]
```

**Flags:**

```
  -d, --description string   Description
  -p, --priority int         Priority (0-4, default 2) (default 2)
```

### bd todo done

Mark TODO(s) as done

```
bd todo done <id> [<id>...] [flags]
```

**Flags:**

```
      --reason string   Reason for closing (default: Completed)
```

### bd todo list

List TODO items

```
bd todo list [flags]
```

**Flags:**

```
      --all   Show all TODOs including completed
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc types`

## bd types

List all valid issue types that can be used with bd create --type.

Core work types (bug, task, feature, chore, epic, decision) are always valid.
Additional types require configuration via types.custom in .beads/config.yaml.

Examples:
  bd types              # List all types with descriptions
  bd types --json       # Output as JSON


```
bd types [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc undefer`

## bd undefer

Undefer issues to restore them to open status.

This brings issues back from the icebox so they can be worked on again.
Issues will appear in 'bd ready' if they have no blockers.

Examples:
  bd undefer bd-abc        # Undefer a single issue
  bd undefer bd-abc bd-def # Undefer multiple issues

```
bd undefer [id...] [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc update`

## bd update

Update one or more issues.

If no issue ID is provided, updates the last touched issue (from most recent
create, update, show, or close operation).

```
bd update [id...] [flags]
```

**Flags:**

```
      --acceptance string            Acceptance criteria
      --add-label strings            Add labels (repeatable)
      --allow-empty-description      Allow empty description replacement when reading from stdin or file
      --append-notes string          Append to existing notes (with newline separator)
  -a, --assignee string              Assignee
      --await-id string              Set gate await_id (e.g., GitHub run ID for gh:run gates)
      --body-file string             Read description from file (use - for stdin)
      --claim                        Atomically claim the issue (sets assignee to you, status to in_progress; idempotent if already claimed by you)
      --defer string                 Defer until date (empty to clear). Issue hidden from bd ready until then
  -d, --description string           Issue description
      --design string                Design notes
      --design-file string           Read design from file (use - for stdin)
      --due string                   Due date/time (empty to clear). Formats: +6h, +1d, +2w, tomorrow, next monday, 2025-01-15
      --ephemeral                    Mark issue as ephemeral (wisp) - not exported to JSONL
  -e, --estimate int                 Time estimate in minutes (e.g., 60 for 1 hour)
      --external-ref string          External reference (e.g., 'gh-9', 'jira-ABC', Linear URL)
      --history                      Clear no-history flag (re-enable Dolt commit history)
      --metadata string              Set custom metadata (JSON string or @file.json to read from file)
      --no-history                   Mark issue as no-history (skip Dolt commits, not GC-eligible)
      --notes string                 Additional notes
      --parent string                New parent issue ID (reparents the issue, use empty string to remove parent)
      --persistent                   Mark issue as persistent (promote wisp to regular issue)
  -p, --priority string              Priority (0-4 or P0-P4, 0=highest)
      --remove-label strings         Remove labels (repeatable)
      --session string               Claude Code session ID for status=closed (or set CLAUDE_SESSION_ID env var)
      --set-labels strings           Set labels, replacing all existing (repeatable)
      --set-metadata stringArray     Set metadata key=value (repeatable, e.g., --set-metadata team=platform)
      --spec-id string               Link to specification document
  -s, --status string                New status
      --stdin                        Read description from stdin (alias for --body-file -)
      --title string                 New title
  -t, --type string                  New type (bug|feature|task|epic|chore|decision); custom types require types.custom config
      --unset-metadata stringArray   Remove metadata key (repeatable, e.g., --unset-metadata team)
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc upgrade`

## bd upgrade

Commands for checking bd version upgrades and reviewing changes.

The upgrade command helps you stay aware of bd version changes:
  - bd upgrade status: Check if bd version changed since last use
  - bd upgrade review: Show what's new since your last version
  - bd upgrade ack: Acknowledge the current version

Version tracking is automatic - bd updates metadata.json on every run.

```
bd upgrade [flags]
```

### bd upgrade ack

Mark the current bd version as acknowledged.

This updates metadata.json to record that you've seen the current
version. Mainly useful after reviewing upgrade changes to suppress
future upgrade notifications.

Note: Version tracking happens automatically, so you don't need to
run this command unless you want to explicitly mark acknowledgement.

Examples:
  bd upgrade ack
  bd upgrade ack --json

```
bd upgrade ack [flags]
```

### bd upgrade review

Show what's new in bd since the last version you used.

Unlike 'bd info --whats-new' which shows the last 3 versions,
this command shows ALL changes since your specific last version.

If you're upgrading from an old version, you'll see the complete
changelog of everything that changed since then.

Examples:
  bd upgrade review
  bd upgrade review --json

```
bd upgrade review [flags]
```

### bd upgrade status

Check if bd has been upgraded since you last used it.

This command uses the version tracking that happens automatically
at startup to detect if bd was upgraded.

Examples:
  bd upgrade status
  bd upgrade status --json

```
bd upgrade status [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc vc`

## bd vc

Version control operations for the beads database.

These commands provide git-like version control for your issue data, including branching, merging, and
viewing history.

Note: 'bd history', 'bd diff', and 'bd branch' also work for quick access.
This subcommand provides additional operations like merge and commit.

```
bd vc [flags]
```

### bd vc commit

Create a new Dolt commit with all current changes.

Examples:
  bd vc commit -m "Added new feature issues"
  bd vc commit --message "Fixed priority on several issues"
  echo "Multi-line message" | bd vc commit --stdin

```
bd vc commit [flags]
```

**Flags:**

```
  -m, --message string   Commit message
      --stdin            Read commit message from stdin
```

### bd vc merge

Merge the specified branch into the current branch.

If there are merge conflicts, they will be reported. You can resolve
conflicts with --strategy.

Examples:
  bd vc merge feature-xyz                    # Merge feature-xyz into current branch
  bd vc merge feature-xyz --strategy ours    # Merge, preferring our changes on conflict
  bd vc merge feature-xyz --strategy theirs  # Merge, preferring their changes on conflict

```
bd vc merge <branch> [flags]
```

**Flags:**

```
      --strategy string   Conflict resolution strategy: 'ours' or 'theirs'
```

### bd vc status

Show the current branch, commit hash, and any uncommitted changes.

Examples:
  bd vc status

```
bd vc status [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc version`

## bd version

Print version information

```
bd version [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc where`

## bd where

Show the active beads database location, including redirect information.

	This command is useful for debugging when using redirects, to understand
	which beads workspace is actually being used.

Examples:
  bd where           # Show active beads location
  bd where --json    # Output in JSON format


```
bd where [flags]
```

</document>

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


<!-- AUTO-GENERATED: do not edit manually -->
Generated from `bd help --doc worktree`

## bd worktree

Manage git worktrees with proper beads configuration.

Worktrees allow multiple working directories sharing the same git repository,
enabling parallel development (e.g., multiple agents or features).

Worktrees automatically share the same beads database as the main repository
via git common directory discovery — no manual redirect configuration needed.

Examples:
  bd worktree create feature-auth           # Create worktree
  bd worktree create bugfix --branch fix-1  # Create with specific branch name
  bd worktree list                          # List all worktrees
  bd worktree remove feature-auth           # Remove worktree (with safety checks)
  bd worktree info                          # Show info about current worktree

```
bd worktree [flags]
```

### bd worktree create

Create a git worktree for parallel development.

This command:
1. Creates a git worktree at ./&lt;name&gt; (or specified path)
2. Adds the worktree path to .gitignore (if inside repo root)

The worktree automatically shares the same beads database as the main
repository via git common directory discovery — no redirect file needed.

Examples:
  bd worktree create feature-auth           # Create at ./feature-auth
  bd worktree create bugfix --branch fix-1  # Create with branch name
  bd worktree create ../agents/worker-1     # Create at relative path

```
bd worktree create <name> [--branch=<branch>] [flags]
```

**Flags:**

```
      --branch string   Branch name for the worktree (default: same as name)
```

### bd worktree info

Show information about the current worktree.

If the current directory is in a git worktree, shows:
- Worktree path and name
- Branch
- Beads configuration (redirect or main)
- Main repository location

Examples:
  bd worktree info          # Show current worktree info
  bd worktree info --json   # JSON output

```
bd worktree info [flags]
```

### bd worktree list

List all git worktrees and their beads configuration state.

Shows each worktree with:
- Name (directory name)
- Path (full path)
- Branch
- Beads state: "redirect" (uses shared db), "shared" (is main), "none" (no beads)

Examples:
  bd worktree list          # List all worktrees
  bd worktree list --json   # JSON output

```
bd worktree list [flags]
```

### bd worktree remove

Remove a git worktree with safety checks.

Before removing, this command checks for:
- Uncommitted changes
- Unpushed commits
- Stashes

Use --force to skip safety checks (not recommended).

Examples:
  bd worktree remove feature-auth         # Remove with safety checks
  bd worktree remove feature-auth --force # Skip safety checks

```
bd worktree remove <name> [flags]
```

**Flags:**

```
      --force   Skip safety checks
```

</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 --claim
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 --claim

# 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 --claim

# 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 --claim
```

### 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/index.md">


# Integrations

Beads integration pages are based on two sources of support in the repository:

- Built-in `bd setup` recipes from `internal/recipes/recipes.go`
- First-party MCP integrations and editor guides already shipped in the repo

Run this command to see the built-in setup recipes supported by your installed `bd` binary:

```bash
bd setup --list
```

## Built-in Setup Recipes

| Recipe | Integration | Primary setup surface |
|--------|-------------|-----------------------|
| `aider` | [Aider](/integrations/aider) | `.aider.conf.yml` and `.aider/` instructions |
| `claude` | [Claude Code](/integrations/claude-code) | Claude hooks and `CLAUDE.md` |
| `codex` | [Codex](/integrations/codex) | Beads skill, `AGENTS.md`, and Codex hooks |
| `cody` | [Sourcegraph Cody](/integrations/cody) | `.cody/rules/beads.md` |
| `cursor` | [Cursor](/integrations/cursor) | `.cursor/rules/beads.mdc` |
| `factory` | [Factory.ai Droid](/integrations/factory) | `AGENTS.md` |
| `gemini` | [Gemini CLI](/integrations/gemini) | Gemini hooks and `GEMINI.md` |
| `junie` | [Junie](/integrations/junie) | `.junie/guidelines.md` and MCP config |
| `kilocode` | [Kilo Code](/integrations/kilocode) | `.kilocode/rules/beads.md` |
| `mux` | [Mux](/integrations/mux) | `AGENTS.md`, optional `.mux/AGENTS.md`, and Mux hooks |
| `opencode` | [OpenCode](/integrations/opencode) | `AGENTS.md` |
| `windsurf` | [Windsurf](/integrations/windsurf) | `.windsurf/rules/beads.md` |

## MCP-Based Integrations

These integrations use the Beads MCP server rather than a dedicated `bd setup` recipe:

- [MCP Server](/integrations/mcp-server)
- [GitHub Copilot](/integrations/github-copilot)

</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 — bd prime provides issue context
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 --claim
bd ready
```

### End Session

```bash
bd dolt push
```

## Best Practices

1. **Keep issues visible** - Use `bd prime` to inject issue context
2. **Push regularly** - Run `bd dolt push` 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 push
bd close bd-42 --reason "Fixed"
bd dolt push
```

## Troubleshooting

### Config not loading

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

# Regenerate
bd setup aider
```

### Issues not visible

```bash
# Use bd prime to inject issue context
bd prime | aider --message-file -

# Or check database health
bd doctor
```

## 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
- **SessionStart compact refresh** - Runs `bd prime` after context compaction

### Manual Setup

Add to your Claude Code hooks configuration:

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

### 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 prime` refreshes workflow context before compaction
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 --claim --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 dolt push
```

## 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
```

### Push Before Session End

```bash
# ALWAYS run before ending
bd dolt push
```

## Plugin (Optional)

For enhanced UX with slash commands:

```bash
# In Claude Code
/plugin marketplace add gastownhall/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 push
bd dolt push

# Check system health
bd doctor
```

### 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/codex.md">


# Codex Integration

Use Beads with Codex through the `beads` skill, managed `AGENTS.md` guidance, and native Codex hooks.

```bash
bd setup codex
bd setup codex --check
```

Codex 0.129.0+ supports `/hooks`, compact lifecycle hooks, and hook-provided developer context. Beads uses that lifecycle to inject `bd prime` on session start and recover context after compaction.

## Hook Lifecycle

- `SessionStart` (`startup|resume|clear`) injects full `bd prime` output.
- `PreCompact` (`manual|auto`) checks `bd prime --memories-only` and warns if Beads context is unavailable.
- `PostCompact` (`manual|auto`) records that the session needs a Beads refresh.
- `UserPromptSubmit` injects full `bd prime` once after compaction, then clears the refresh marker.

`PreCompact` alone does not inject context because Codex ignores plain stdout from compact hooks. The post-compact marker plus first-prompt refresh is the reliable recovery path.

The Beads Codex plugin stores hooks at `plugins/beads/.codex-plugin/hooks/hooks.json` and declares them as `"hooks": "./hooks/hooks.json"`. Without the plugin, `bd setup codex` installs the same hook config in `.codex/hooks.json` and enables `[features].hooks = true`.

</document>

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


# Sourcegraph Cody Integration

Use Beads with Sourcegraph Cody through a project rules file.

```bash
bd setup cody
bd setup cody --check
```

The setup command creates `.cody/rules/beads.md` with Beads workflow guidance.

## Remove

```bash
bd setup cody --remove
```

</document>

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


# Cursor Integration

Use Beads with Cursor through a project rules file.

```bash
bd setup cursor
bd setup cursor --check
```

The setup command creates `.cursor/rules/beads.mdc` with Beads workflow guidance and quick `bd` command references. Restart Cursor after setup so the rules file is loaded into new agent sessions.

## Remove

```bash
bd setup cursor --remove
```

</document>

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


# Factory.ai Droid Integration

Use Beads with Factory.ai Droid through managed `AGENTS.md` guidance.

```bash
bd setup factory
bd setup factory --check
```

The setup command creates or updates `AGENTS.md` with a managed Beads section. Factory Droid reads `AGENTS.md` automatically when it starts a session.

## Remove

```bash
bd setup factory --remove
```

</document>

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


# Gemini CLI Integration

Use Beads with Gemini CLI through SessionStart hooks and `GEMINI.md` guidance.

```bash
bd setup gemini
bd setup gemini --check
```

By default, setup installs global hooks in `~/.gemini/settings.json`. For project-local hooks, use:

```bash
bd setup gemini --project
```

The hook runs `bd prime --hook-json` so Gemini receives compact Beads workflow context at session start. The setup also writes Beads guidance to `GEMINI.md`.

## Stealth Mode

For CI or other environments where setup should avoid git operations:

```bash
bd setup gemini --stealth
bd setup gemini --project --stealth
```

## Remove

```bash
bd setup gemini --remove
bd setup gemini --project --remove
```

</document>

<document path="docs/integrations/github-copilot.md">


# GitHub Copilot Integration

How to use beads with GitHub Copilot in VS Code.

## Setup

### Quick Setup

1. Install beads-mcp:
   ```bash
   uv tool install beads-mcp
   ```

2. Create `.vscode/mcp.json` in your project:
   ```json
   {
     "servers": {
       "beads": {
         "command": "beads-mcp"
       }
     }
   }
   ```

   **For all projects:** Add to VS Code user-level MCP config:

   | Platform | Path |
   |----------|------|
   | macOS | `~/Library/Application Support/Code/User/mcp.json` |
   | Linux | `~/.config/Code/User/mcp.json` |
   | Windows | `%APPDATA%\Code\User\mcp.json` |

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

3. Initialize beads:
   ```bash
   bd init --quiet
   ```

4. Reload VS Code

### Verify Setup

Ask Copilot Chat: "What beads issues are ready to work on?"

## Using Natural Language

With MCP configured, interact naturally:

```
You: Create a bug for the login timeout
Copilot: Created bd-42: Login timeout bug

You: What issues are ready?
Copilot: 3 issues ready: bd-42, bd-99, bd-17

You: Close bd-42, it's fixed
Copilot: Closed bd-42
```

## MCP Tools

| Tool | Description |
|------|-------------|
| `beads_ready` | List unblocked issues |
| `beads_create` | Create new issue |
| `beads_show` | Show issue details |
| `beads_update` | Update issue |
| `beads_close` | Close issue |
| `beads_dolt_push` | Push to Dolt remote |
| `beads_dep_add` | Add dependency |
| `beads_dep_tree` | Show dependency tree |

## Copilot Instructions

Optionally add `.github/copilot-instructions.md`:

```markdown
## Issue Tracking

This project uses **bd (beads)** for issue tracking.
Run `bd prime` for workflow context.

Quick reference:
- `bd ready` - Find unblocked work
- `bd create "Title" --type task --priority 2` - Create issue
- `bd close <id>` - Complete work
- `bd dolt push` - Push changes to Dolt remote
```

## Troubleshooting

### Tools not appearing

1. Check VS Code 1.96+
2. Verify mcp.json syntax is valid JSON
3. Reload VS Code window
4. Check Output panel for MCP errors

### "beads-mcp not found"

```bash
# Check installation
which beads-mcp

# Reinstall if needed
uv tool install beads-mcp --force
```

### No database found

```bash
bd init --quiet
```

## FAQ

### Do I need to clone beads?

**No.** Beads is a system-wide CLI tool. Install once, use everywhere. The `.beads/` directory in your project only contains the issue database.

### What about git hooks?

Git hooks are optional. They refresh exports and legacy fallback checks, while issue sync uses `bd dolt push` / `bd dolt pull`.

## See Also

- [MCP Server](/integrations/mcp-server) - Detailed MCP configuration
- [Installation](/getting-started/installation) - Full install guide
- [Detailed Copilot Guide](https://github.com/gastownhall/beads/blob/main/docs/COPILOT_INTEGRATION.md) - Comprehensive documentation

</document>

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


# Junie Integration

How to use beads with Junie (JetBrains AI Agent).

## Setup

### Quick Setup

```bash
bd setup junie
```

This creates:
- **`.junie/guidelines.md`** - Agent instructions for beads workflow
- **`.junie/mcp/mcp.json`** - MCP server configuration

### Verify Setup

```bash
bd setup junie --check
```

## How It Works

1. **Session starts** → Junie reads `.junie/guidelines.md` for workflow context
2. **MCP tools available** → Junie can use beads MCP tools directly
3. **You work** → Use `bd` CLI commands or MCP tools
4. **Session ends** → Run `bd dolt push` to push changes to Dolt remote

## Configuration Files

### Guidelines (`.junie/guidelines.md`)

Contains workflow instructions that Junie reads automatically:
- Core workflow rules
- Command reference
- Issue types and priorities
- MCP tool documentation

### MCP Config (`.junie/mcp/mcp.json`)

Configures the beads MCP server:

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

## MCP Tools

With MCP configured, Junie can use these tools directly:

| Tool | Description |
| --- | --- |
| `mcp_beads_ready` | Find tasks ready for work |
| `mcp_beads_list` | List issues with filters |
| `mcp_beads_show` | Show issue details |
| `mcp_beads_create` | Create new issues |
| `mcp_beads_update` | Update issue status/priority |
| `mcp_beads_close` | Close completed issues |
| `mcp_beads_dep` | Manage dependencies |
| `mcp_beads_blocked` | Show blocked issues |
| `mcp_beads_stats` | Get issue statistics |

## CLI Commands

You can also use the `bd` CLI directly:

### 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 --claim --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 dolt push
```

## 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
```

### Push Before Session End

```bash
# ALWAYS run before ending
bd dolt push
```

## Troubleshooting

### Guidelines not loaded

```bash
# Check setup
bd setup junie --check

# Reinstall if needed
bd setup junie
```

### MCP tools not available

```bash
# Verify MCP config exists
cat .junie/mcp/mcp.json

# Test MCP server
bd mcp --help
```

### Changes not syncing

```bash
# Force push
bd dolt push

# Check system health
bd doctor
```

### Database not found

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

## Removing Integration

```bash
bd setup junie --remove
```

This removes:
- `.junie/guidelines.md`
- `.junie/mcp/mcp.json`
- Empty `.junie/mcp/` and `.junie/` directories

## See Also

- [MCP Server](/integrations/mcp-server) - MCP server details
- [Claude Code](/integrations/claude-code) - Similar hook-based integration
- [IDE Setup](/getting-started/ide-setup) - Other editors

</document>

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


# Kilo Code Integration

Use Beads with Kilo Code through a project rules file.

```bash
bd setup kilocode
bd setup kilocode --check
```

The setup command creates `.kilocode/rules/beads.md` with Beads workflow guidance.

## Remove

```bash
bd setup kilocode --remove
```

</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": []
  }
}
```

### VS Code / GitHub Copilot

Create `.vscode/mcp.json` in your project:

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

**For all projects:** Add to VS Code user-level MCP config:

| Platform | Path |
|----------|------|
| macOS | `~/Library/Application Support/Code/User/mcp.json` |
| Linux | `~/.config/Code/User/mcp.json` |
| Windows | `%APPDATA%\Code\User\mcp.json` |

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

**Note:** Requires VS Code 1.96+ with MCP support enabled.

See [GitHub Copilot Integration](/integrations/github-copilot) for complete setup guide.

## 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/integrations/mux.md">


# Mux Integration

Use Beads with Mux through `AGENTS.md`, optional layered Mux instruction files, and Mux hooks.

```bash
bd setup mux
bd setup mux --check
```

The default setup writes a managed Beads section to root `AGENTS.md`.

## Workspace and Global Layers

Mux also supports workspace and global instruction layers:

```bash
bd setup mux --project
bd setup mux --global
bd setup mux --project --global
```

Project setup writes `.mux/AGENTS.md` and installs Mux hook files under `.mux/`:

- `.mux/init`
- `.mux/tool_post`
- `.mux/tool_env`

Global setup writes `~/.mux/AGENTS.md`.

## Remove

```bash
bd setup mux --remove
bd setup mux --project --remove
bd setup mux --global --remove
```

</document>

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


# OpenCode Integration

Use Beads with OpenCode through managed `AGENTS.md` guidance.

```bash
bd setup opencode
bd setup opencode --check
```

The setup command creates or updates `AGENTS.md` with a managed Beads section. Restart OpenCode after setup if it is already running.

## Remove

```bash
bd setup opencode --remove
```

</document>

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


# Windsurf Integration

Use Beads with Windsurf through a project rules file.

```bash
bd setup windsurf
bd setup windsurf --check
```

The setup command creates `.windsurf/rules/beads.md` with Beads workflow guidance.

## Remove

```bash
bd setup windsurf --remove
```

</document>

<document path="docs/community-tools.md">


# Beads Community Tools

A curated list of community-built UIs, extensions, and integrations for Beads. Ranked by activity and maturity.

> **Note:** Beads uses a Dolt SQL database for storage. Tools should use
> the `bd` CLI (`bd list --json`, etc.) to access data. Tools that read
> the old `.beads/issues.jsonl` format directly are not compatible with
> current versions.

## Terminal UIs

- **[Mardi Gras](https://github.com/quietpublish/mardi-gras)** - Parade-themed terminal UI with real-time updates, multi-agent orchestration, tmux integration, and Claude Code dispatch. Uses `bd list --json`. Built by [@matt-wright86](https://github.com/matt-wright86). (Go)

- **[perles](https://github.com/zjrosen/perles)** - Terminal UI search, dependency and kanban viewer powered by a custom BQL (Beads Query Language). Built by [@zjrosen](https://github.com/zjrosen). (Go)

## Web UIs

- **[beads-ui](https://github.com/mantoni/beads-ui)** - Local web interface with live updates and kanban board. Uses the `bd` CLI for Dolt compatibility. Run with `npx beads-ui start`. Built by [@mantoni](https://github.com/mantoni). (Node.js)

- **[BeadBoard](https://github.com/zenchantlive/beadboard)** - Multi-agent orchestration and communication system with a live dashboard. Agent-to-agent messaging (HANDOFF/BLOCKED/DECISION/INFO), DAG dependency graph, swarm coordination with archetypes and templates, scope-based work reservations, and an embedded execution runtime (bb-pi) built on [Pi](https://github.com/badlogic/pi-mono) that spawns typed worker agents. Cross-platform (macOS, Linux, Windows). Includes the `beadboard-driver` skill for agent integration (`npx skills add zenchantlive/beadboard --skill beadboard-driver`). Built by [@zenchantlive](https://github.com/zenchantlive). (Next.js/TypeScript)

- **[beads-web](https://github.com/weselow/beads-web)** - Actively maintained fork of beads-kanban-ui. Cross-platform single-binary distribution (macOS, Linux, Windows), 7 visual themes, Dolt direct SQL integration, Windows multi-drive path support, drag-and-drop status updates. Download from [GitHub Releases](https://github.com/weselow/beads-web/releases). Built by [@weselow](https://github.com/weselow). (TypeScript/Rust)

## Editor Extensions

- **[vscode-beads](https://marketplace.visualstudio.com/items?itemName=planet57.vscode-beads)** - VS Code extension with issues panel and server management. Built by [@jdillon](https://github.com/jdillon). (TypeScript)

- **[opencode-beads](https://github.com/joshuadavidthomas/opencode-beads)** - OpenCode plugin with automatic context injection, `/bd-*` slash commands, and autonomous task agent. Built by [@joshuadavidthomas](https://github.com/joshuadavidthomas). (Node.js)

- **[Lista Beads](https://marketplace.visualstudio.com/items?itemName=ListaDev.lista-beads)** - Full-featured VS Code extension: filterable tree view, issue detail panel, dashboard with metrics, dependency graph, Dolt push/pull, CodeLens for bead references, wisps & formula support, stale issue management, and multi-tracker sync (Azure DevOps, GitHub, Jira, Linear, GitLab). Built by [@harry-miller-trimble](https://github.com/harry-miller-trimble). (TypeScript)

- **[nvim-beads (fancypantalons)](https://github.com/fancypantalons/nvim-beads)** - Neovim plugin for managing Beads issues. By [@fancypantalons](https://github.com/fancypantalons). (Lua)

- **[beads-manager](https://plugins.jetbrains.com/plugin/30089-beads-manager)** - Jetbrains IDE plugin to manage and view bead details. Maintained by [@developmeh](https://github.com/developmeh). (Kotlin)

## Native Apps

- **[Beads Task-Issue Tracker](https://github.com/w3dev33/beads-task-issue-tracker)** - Cross-platform desktop application (macOS, Windows, Linux) for browsing, creating, and managing Beads issues with a visual interface. Features multi-project support with favorites, image attachments, dashboard with statistics, advanced filtering, and dark/light theme. Built by [@w3dev33](https://github.com/w3dev33). (Tauri/Vue)

- **[Beadbox](https://github.com/beadbox/beadbox)** - Native macOS dashboard with real-time sync, epic tree progress bars, multi-workspace support, and inline editing. Install with `brew tap beadbox/cask && brew install --cask beadbox`. Built by [@nmelo](https://github.com/nmelo). (Tauri/Next.js)

## Data Source Middleware

- **[stringer](https://github.com/davetashner/stringer)** - Codebase archaeology CLI that mines git repos for TODOs, churn hotspots, lottery-risk files, dependency health, and more. Outputs JSONL compatible with `bd init --from-jsonl`. Install with `brew install davetashner/tap/stringer`. Built by [@davetashner](https://github.com/davetashner). (Go)

## Analytics & Observability

* **[Thread](https://github.com/jklenk/thread)** - Read-only forensics and analytics layer for Beads. Reads local Dolt history and produces fidelity scores, rework cost metrics, session compliance scoring, and a self-contained HTML report. Add `Run 'thread prime --json' at session start` to your `AGENTS.md` to give agents project health context before they claim their first bead.

Install with `uv tool install git+https://github.com/jklenk/thread`. Built by [@jklenk](https://github.com/jklenk). (Python/DuckDB)

## SDKs & Libraries

- **[beads-sdk](https://github.com/HerbCaudill/beads-sdk)** - Typed TypeScript SDK with zero runtime dependencies. High-level `BeadsClient` for CRUD, filtering, search, labels, dependencies, comments, epics, and sync. Install with `pnpm add @herbcaudill/beads-sdk`. Built by [@HerbCaudill](https://github.com/HerbCaudill). (TypeScript)

## Claude Code Orchestration

- **[Foolery](https://github.com/acartine/foolery)** - Local web UI that sits on top of Beads, giving you a visual control surface for organizing, orchestrating, and reviewing AI agent work. Features dependency-aware wave planning, a built-in terminal for live agent monitoring, a verification queue for reviewing completed beats, and keyboard-first navigation. Install with `curl -fsSL https://raw.githubusercontent.com/acartine/foolery/main/scripts/install.sh | bash`. Built by [@acartine](https://github.com/acartine). (Next.js/TypeScript)

- **[beads-compound](https://github.com/roberto-mello/beads-compound-plugin)** - Claude Code plugin marketplace with persistent memory and compound-engineering workflows. Hooks auto-capture knowledge from `bd comments add` at session end and inject relevant entries at session start based on open beads. Includes 28 specialized agents, 26 commands, and 15 skills for planning, review, research, and parallel work. Also supports OpenCode and Gemini CLI. Built by [@roberto-mello](https://github.com/roberto-mello). (Bash/TypeScript)

- **[claude-handoff](https://github.com/REMvisual/claude-handoff)** - Session handoff skills for Claude Code. Captures decisions, failed approaches, measurements, and next steps into structured files so the next session picks up where you left off. Uses bead IDs as chain tags for multi-session continuity, auto-detects active beads, and updates bead notes on close. Includes `/handoff`, `/handoffplan`, and a PreCompact safety-net hook. Built by [@REMvisual](https://github.com/REMvisual). (Markdown/Bash)
- **[claude-workspace-snapshot](https://github.com/REMvisual/claude-workspace-snapshot)** - Snapshot and restore live Claude Code sessions as named, color-coded Windows Terminal tabs. Detects running sessions via process inspection and .jsonl file activity. Restores tab layout after any restart. Pairs with claude-handoff for full session continuity. Built by [@REMvisual](https://github.com/REMvisual). (PowerShell/Batch)
- **[claude-protocol](https://github.com/weselow/claude-protocol)** - Actively maintained fork of beads-orchestration. Ground-up rewrite optimized for Claude 4.6 family models: trigger-based dev rules (TDD, logging, resilience), cross-platform Node.js hooks (replaced 19 bash scripts with 8 .cjs hooks), mandatory checklist verification, session-start dashboard, knowledge base with auto-capture. Install via `npx claude-protocol init`. Built by [@weselow](https://github.com/weselow). (Node.js/Python)

## Coordination Servers

- **[BeadHub](https://github.com/beadhub/beadhub)** - Open-source coordination server for AI agent teams running beads. The `bdh` CLI is a transparent wrapper over `bd` that adds work claiming, file reservation, presence awareness, and inter-agent messaging (async mail and sync chat). Includes a web dashboard. Free hosted at beadhub.ai for open-source projects. Built by [@juanre](https://github.com/juanre). (Python/TypeScript)

## Historical / Stale

- **[bdui](https://github.com/assimelha/bdui)** - Real-time terminal UI with tree view, dependency graph, and vim-style navigation. Built by [@assimelha](https://github.com/assimelha). (Node.js)

- **[beads.el](https://codeberg.org/ctietze/beads.el)** - Emacs UI to browse, edit, and manage beads. Built by [@ctietze](https://codeberg.org/ctietze). (Elisp)

- **[lazybeads](https://github.com/codegangsta/lazybeads)** - Lightweight terminal UI built with Bubble Tea for browsing and managing beads issues. Built by [@codegangsta](https://github.com/codegangsta). (Go)

- **[bsv](https://github.com/bglenden/bsv)** - Simple two-panel terminal (TUI) viewer with tree navigation organized by epic/task/sub-task, markdown rendering, and mouse support. Built by [@bglenden](https://github.com/bglenden). (Rust)

- **[abacus](https://github.com/ChrisEdwards/abacus)** - A powerful terminal UI for visualizing and navigating Beads issue tracking databases.

- **[beads-viz-prototype](https://github.com/mattbeane/beads-viz-prototype)** - Web-based visualization generating interactive HTML from `bd export`. Built by [@mattbeane](https://github.com/mattbeane). (Python)

- **[beads-dashboard](https://github.com/rhydlewis/beads-dashboard)** - A local, lean metrics dashboard for your beads data. Provides insights into lead time, throughput and other continuous improvement metrics. Includes a filterable table view of "all issues". Built by [@rhydlewis](https://github.com/rhydlewis). (Node.js/React)

- **[beads-kanban-ui](https://github.com/AvivK5498/Beads-Kanban-UI)** - Visual Kanban board with git branch status tracking, epic/subtask management, design doc viewer, and activity timeline. Install via npm: `npm install -g beads-kanban-ui`. Built by [@AvivK5498](https://github.com/AvivK5498). (TypeScript/Rust)

- **[beads-pm-ui](https://github.com/qosha1/beads-pm-ui)** - Gantt chart timeline view, project / team based filtering (via folder structure), quarterly goal setting and dependency chain visualization. Inline editable. Built by [@qosha1](https://github.com/qosha1). (Nextjs/Typscript)

- **[Beadspace](https://github.com/cameronsjo/beadspace)** - Drop-in GitHub Pages dashboard with triage suggestions, priority/status breakdowns, and searchable issue table. Single HTML file, zero build dependencies, auto-deploys via GitHub Action. Built by [@cameronsjo](https://github.com/cameronsjo). (HTML/CSS/JS)

- **[beadsmap](https://github.com/dariye/beadsmap)** - Interactive roadmap visualization with timeline (Gantt), list, and table views. Multi-source support, dependency arrows, milestone grouping, GitHub integration via OAuth device flow, and light/dark/system themes. Ships as a single `index.html`. Built by [@dariye](https://github.com/dariye). (Svelte/TypeScript)

- **[Agent Native Abstraction Layer for Beads](https://marketplace.visualstudio.com/items?itemName=AgentNativeAbstractionLayer.agent-native-kanban)** (ANAL Beads) - VS Code Kanban board. Maintained by [@sebcook-ctrl](https://github.com/sebcook-ctrl). (Node.js)

- **[Beads-Kanban](https://github.com/davidcforbes/Beads-Kanban)** - VS Code Kanban board for Beads issue tracking. Maintained by [@davidcforbes](https://github.com/davidcforbes). (TypeScript)

- **[nvim-beads](https://github.com/joeblubaugh/nvim-beads)** - Neovim plugin for managing beads. Built by [@joeblubaugh](https://github.com/joeblubaugh). (Lua)

- **[Beadster](https://github.com/beadster/beadster)** - macOS app for browsing and managing issues from `.beads/` directories in git repositories. Built by [@podviaznikov](https://github.com/podviaznikov). (Swift)

-  **[Parade](https://github.com/JeremyKalmus/parade)** - Electron app for workflow orchestration with visual Kanban board, discovery wizard, and task visualization. Run with `npx parade-init`. Built by [@JeremyKalmus](https://github.com/JeremyKalmus). (Electron/React)

- **[jira-beads-sync](https://github.com/conallob/jira-beads-sync)** - CLI tool & Claude Code plugin to sync tasks from Jira into beads and publish beads task states back to Jira. Built by [@conallob](https://github.com/conallob). (Go)

- **[beads-orchestration](https://github.com/AvivK5498/Claude-Code-Beads-Orchestration)** - Multi-agent orchestration skill for Claude Code. Orchestrator investigates issues, manages beads tasks automatically, and delegates to tech-specific supervisors on isolated branches. Includes hooks for workflow enforcement, epic/subtask support, and optional external provider delegation (Codex/Gemini). Install via npm: `npm install -g @avivkaplan/beads-orchestration`. Built by [@AvivK5498](https://github.com/AvivK5498). (Node.js/Python)

- **[beads_viewer](https://github.com/Dicklesworthstone/beads_viewer)** - Terminal interface with tree navigation and vim-style commands. Not compatible with Dolt-based beads (v0.50+); see [issue #121](https://github.com/Dicklesworthstone/beads_viewer/issues/121). Built by [@Dicklesworthstone](https://github.com/Dicklesworthstone). (Go)

- **[beady](https://github.com/maphew/beady)** - Early prototype effort, now stale. Built by [@maphew](https://github.com/maphew). (Go)

## Discussion

See [GitHub Discussions #276](https://github.com/gastownhall/beads/discussions/276) for ongoing UI development conversations, design decisions, and community contributions.

## Contributing

Found or built a tool? Open a PR to add it to this list or comment on discussion #276.

</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 | Dolt conflicts during sync | [Merge Conflicts](/recovery/merge-conflicts) |
| Circular Dependencies | Cycle detection errors | [Circular Dependencies](/recovery/circular-dependencies) |
| Sync Failures | `bd dolt push`/`bd dolt pull` errors | [Sync Failures](/recovery/sync-failures) |

## Quick Diagnostic

Before diving into specific runbooks, try these quick checks:

```bash
# Check Beads status
bd status

# Verify Dolt server is running
bd doctor

# 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/gastownhall/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 database corruption in Beads.

## Symptoms

- Error messages during `bd` commands
- "database is locked" errors that persist
- Missing issues that should exist
- Inconsistent database state

## Diagnosis

```bash
# Check database integrity
bd doctor

# Check Dolt server health
bd dolt show
```

## Solution

**Step 1:** Stop the Dolt server
```bash
bd dolt stop
```

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

**Step 3:** Preview what doctor would fix
```bash
bd doctor --dry-run
```

**Step 4:** Rebuild database
```bash
bd doctor --fix
```

**Step 5:** Verify recovery
```bash
bd doctor
bd list
```

**Step 6:** Restart the Dolt server
```bash
dolt sql-server
```

## Prevention

- Let the Dolt server handle synchronization
- Use `bd dolt stop` before system shutdown
- Run `bd doctor` periodically to catch issues early

</document>

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


# Merge Conflicts Recovery

This runbook helps you resolve merge conflicts that occur during Dolt sync operations.

## Symptoms

- `bd dolt pull` fails with conflict errors
- Different issue states between clones

## Diagnosis

```bash
# Check database health
bd doctor

# Preview what fixes would be applied
bd doctor --dry-run
```

## Solution

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

**Step 2:** Check for conflicts
```bash
bd doctor
```

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

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

**Step 5:** Push resolved state
```bash
bd dolt push
```

## Prevention

- Sync before and after work sessions using `bd dolt pull` / `bd dolt push`
- Avoid concurrent modifications from multiple clones without the Dolt server running

</document>

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


# Sync Failures Recovery

This runbook helps you recover from Dolt sync failures.

## Symptoms

- `bd dolt push` or `bd dolt pull` hangs or times out
- Network-related error messages
- "failed to push" or "failed to pull" errors
- Dolt server not responding

## Diagnosis

```bash
# Check Dolt server health
bd doctor
bd dolt show

# View Dolt server logs
tail -50 .beads/dolt/sql-server.log
```

## Solution

**Step 1:** Stop the Dolt server
```bash
bd dolt stop
```

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

**Step 3:** Back up and preview fixes
```bash
cp -r .beads .beads.backup
bd doctor --dry-run
```

**Step 4:** Apply fixes if needed
```bash
bd doctor --fix
```

**Step 5:** Restart the Dolt server
```bash
dolt sql-server
```

**Step 6:** Verify sync works
```bash
bd dolt push
bd doctor
```

## Common Causes

| Cause | Solution |
|-------|----------|
| Network timeout | Retry with better connection |
| Stale lock file | Remove lock after stopping Dolt server |
| Corrupted state | Back up, then `bd doctor --fix` |
| Merge conflicts | See [Merge Conflicts](/recovery/merge-conflicts) |

## Prevention

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

</document>

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


# Uninstalling Beads

This guide explains how to remove beads from a repository or remove the `bd`
binary from a machine.

## Before You Remove Data

Removing `.beads/` permanently deletes the local Dolt database. If the issue
history matters, make a Dolt-native backup first:

```bash
bd backup init /path/to/beads-backup
bd backup sync
```

For review, migration, or interoperability, you can also write an issue-table
export:

```bash
bd export -o ~/beads-issues-$(date +%Y%m%d).jsonl
```

`bd export` is not a complete restorable database backup. It does not preserve
Dolt branches, commit history, working-set state, or non-issue tables.

## Repository Reset

Use `bd reset` from the repository root. It previews what will be removed by
default:

```bash
bd reset
```

If the preview is correct, run:

```bash
bd reset --force
```

This removes beads-managed repository data such as:

- the `.beads/` directory
- beads-managed git hook sections
- legacy beads sync worktrees under `.git/beads-worktrees/`

## Remove Hooks Only

To keep issue data but remove git hooks:

```bash
bd hooks uninstall
```

This is preferable to manually deleting hook files because beads preserves
unrelated user hook content outside its managed hook markers.

## Manual Cleanup

Use manual cleanup only if `bd reset` is unavailable or cannot run in the
repository.

```bash
# Stop a local Dolt server if one is running.
bd dolt stop 2>/dev/null || true

# Remove beads-managed hooks when bd hooks uninstall is unavailable.
rm -f .git/hooks/pre-commit
rm -f .git/hooks/prepare-commit-msg
rm -f .git/hooks/post-merge
rm -f .git/hooks/pre-push
rm -f .git/hooks/post-checkout

# Remove the local beads database and config.
rm -rf .beads

# Remove legacy sync-branch worktrees from older beads versions.
rm -rf .git/beads-worktrees
git worktree prune
```

If `.gitattributes` contains only beads merge-driver configuration, remove it.
If it contains other project entries, edit out only the beads line.

If beads-specific git config remains, remove it:

```bash
git config --unset beads.role 2>/dev/null || true
git config --unset merge.beads.driver 2>/dev/null || true
git config --unset merge.beads.name 2>/dev/null || true
```

## Remove the `bd` Binary

The CLI is a standalone binary. Remove it according to how it was installed:

```bash
# Homebrew
brew uninstall beads

# Go install
rm -f "$(which bd)"

# Manual install location
rm -f /usr/local/bin/bd
```

If you installed the MCP package separately, remove that package with the tool
you used to install it.

## Verify Removal

```bash
which bd
test ! -e .beads
bd hooks status 2>/dev/null || true
git config --get merge.beads.driver
```

## Reinstall Later

To initialize beads again:

```bash
bd init
```

</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 — requires dolt sql-server running)
bd dolt sql "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 the [bd-example-extension-go example](https://github.com/gastownhall/beads/blob/main/examples/bd-example-extension-go/README.md) for a working extension.

## 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
# Bootstrap a new database from JSONL
bd init --from-jsonl issues.jsonl
```

### 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/embeddeddolt"

store, _ := embeddeddolt.New(ctx, ".beads", "beads", "main")
defer store.Close()
issue, _ := store.GetIssue(ctx, "bd-a1b2")
```

## 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

Beads uses Dolt server mode to handle concurrent access from multiple agents.
The server manages transaction isolation automatically.

```bash
# Start the Dolt server
bd dolt start

# Check server health
bd doctor
```

### CI/CD Optimization

In CI/CD environments, beads uses embedded mode by default (no server required):

```bash
# Just run commands directly — no special flags needed
bd list
```

</document>

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


# Antivirus False Positives

## Overview

Some antivirus software may flag beads (`bd` or `bd.exe`) as malicious. This is a **false positive** - beads is a legitimate, open-source command-line tool for issue tracking.

Beads release installers now verify downloaded archives against release `checksums.txt` before installation. For users who manually install binaries, checksum verification should be the first trust step before running `bd` or creating antivirus exclusions.

## Why This Happens

Go binaries (including beads) are sometimes flagged by antivirus software due to:

1. **Heuristic detection**: Some malware is written in Go, causing antivirus ML models to flag Go-specific binary patterns as suspicious
2. **Behavioral analysis**: CLI tools that modify files and interact with git may trigger behavioral detection
3. **Unsigned binaries**: Without code signing, new executables may be treated with suspicion

This is a **known industry-wide problem** affecting many legitimate Go projects. See the [Go project issues](https://github.com/golang/go/issues/16292) for examples.

## Known Issues

### Kaspersky Antivirus

**Detection**: `PDM:Trojan.Win32.Generic`
**Affected versions**: bd.exe v0.23.1 and potentially others
**Component**: System Watcher (Proactive Defense Module)

Kaspersky's PDM (Proactive Defense Module) uses behavioral analysis that commonly triggers false positives on Go executables.

## Solutions for Users

### Option 1: Verify File Integrity (Recommended First)

Before running a downloaded binary or adding antivirus exclusions, verify the file is legitimate:

1. Download beads from the [official GitHub releases](https://github.com/gastownhall/beads/releases)
2. Verify the SHA256 checksum matches the `checksums.txt` file in the release
3. If a release includes code signing, verify that signature too

**Verify checksum (Windows PowerShell):**
```powershell
Get-FileHash bd.exe -Algorithm SHA256
```

**Verify checksum (macOS/Linux):**
```bash
shasum -a 256 bd
```

Compare the output with the checksum in `checksums.txt` from the release page.

### Option 2: Add Exclusion (After Verification)

Add beads to your antivirus exclusion list:

**Kaspersky:**
1. Open Kaspersky and go to Settings
2. Navigate to Threats and Exclusions → Manage Exclusions
3. Click Add → Add path to exclusion
4. Add the directory containing `bd.exe` (e.g., `C:\Users\YourName\AppData\Local\bd\`)
5. Select which components the exclusion applies to (scan, monitoring, etc.)

**Windows Defender:**
1. Open Windows Security
2. Go to Virus & threat protection → Manage settings
3. Scroll to Exclusions → Add or remove exclusions
4. Add the beads installation directory or the specific `bd.exe` file

**Other antivirus software:**
- Look for "Exclusions", "Whitelist", or "Trusted Applications" settings
- Add the beads installation directory or executable

### Option 3: Report False Positive

Help improve detection accuracy by reporting the false positive:

**Kaspersky:**
1. Visit [Kaspersky Threat Intelligence Portal](https://opentip.kaspersky.com/)
2. Upload the `bd.exe` file for analysis
3. Mark it as a false positive
4. Reference: beads is open-source CLI tool (https://github.com/gastownhall/beads)

**Windows Defender:**
1. Go to [Microsoft Security Intelligence](https://www.microsoft.com/en-us/wdsi/filesubmission)
2. Submit the file as a false positive
3. Provide details about the legitimate software

**Other vendors:**
- Check their website for false positive submission forms
- Most major vendors have a process for reviewing flagged files

## For Developers/Distributors

If you're building beads from source or distributing it:

### Current Build Configuration

Beads releases are built with multiple optimizations to reduce false positives:

```yaml
ldflags:
  - -s -w  # Strip debug symbols and DWARF info
```

**Windows PE version info**: Release builds embed legitimate PE resource metadata
(company name, product name, file description, version, copyright, and an
application manifest) into the Windows binary using `go-winres`. This is one of the
most effective measures against AV false positives — legitimate software almost
always has PE metadata, and AV heuristics use its absence as a suspicion signal.

These optimizations are applied automatically in official release builds.

### Code Signing

Windows releases are signed with an Authenticode certificate when available. Code signing:
- Reduces false positive rates over time
- Builds reputation with SmartScreen/antivirus vendors
- Provides tamper verification

**Verify a signed binary (Windows PowerShell):**
```powershell
# Check if the binary is signed
Get-AuthenticodeSignature .\bd.exe

# Expected output for signed binary:
# SignerCertificate: [Certificate details]
# Status: Valid
```

**Verify a signed binary (Linux/macOS with osslsigncode):**
```bash
# Install osslsigncode if not available
# Ubuntu/Debian: apt-get install osslsigncode
# macOS: brew install osslsigncode

osslsigncode verify -in bd.exe
```

**Note:** Code signing requires an EV (Extended Validation) certificate, which involves a verification process. If a release is not signed, it means the certificate was not available at build time. Follow the checksum verification steps above to verify authenticity.

### Alternative Build Methods

Some users report success with:
```bash
go build -ldflags "-s -w" -o bd ./cmd/bd
```

However, results vary by antivirus vendor and version.

## Frequently Asked Questions

### Is beads safe to use?

Yes. Beads is:
- Open source (all code is auditable on [GitHub](https://github.com/gastownhall/beads))
- Releases include checksums for verification
- Used by developers worldwide
- A simple CLI tool for issue tracking

### Why don't you just fix the code to avoid detection?

The issue isn't specific to beads' code - it's a characteristic of Go binaries in general. Changing code won't reliably prevent heuristic/behavioral detection. The proper solutions are:
1. Code signing (builds trust over time)
2. Whitelist applications with antivirus vendors
3. User reports of false positives

### Will this be fixed in future releases?

We've implemented:
- **Windows PE version info** embedded in binaries (company name, product name, version, manifest)
- **Code signing infrastructure** for Windows releases (requires EV certificate)
- **Build optimizations** to reduce heuristic triggers (`-s -w` ldflags)
- **Documentation** for users to add exclusions and report false positives

Still in progress:
- Acquiring an EV code signing certificate
- Submitting beads to antivirus vendor whitelists

False positives may still occur with new releases until the certificate builds reputation with antivirus vendors. This typically takes several months of consistent signed releases.

### Should I disable my antivirus?

**No.** Instead:
1. Verify release checksums before first run
2. Keep your antivirus enabled for other threats
3. Add beads to your antivirus exclusions only after verification if detections persist

## Reporting Issues

If you encounter a new antivirus false positive:

1. Open an issue on [GitHub](https://github.com/gastownhall/beads/issues)
2. Include:
   - Antivirus software name and version
   - Detection/threat name
   - Beads version (`bd version`)
   - Operating system

This helps us track and address false positives across different antivirus vendors.

## References

- [Kaspersky False Positive Guide](https://support.kaspersky.com/1870)
- [Go Binary False Positives Discussion](https://www.linkedin.com/pulse/go-false-positives-melle-boudewijns)
- [Go Project Issue Tracker](https://github.com/golang/go/issues/16292)
- [Kaspersky Community Forum](https://forum.kaspersky.com/topic/pdmtrojanwin32generic-54425/)

</document>

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


# Configuration

Complete configuration reference for beads.

beads has two complementary configuration systems:

1. **Tool-level configuration** (YAML, managed by [Viper](https://github.com/spf13/viper)) — startup flags and tool behavior, stored in `config.yaml` files.
2. **Project-level configuration** (managed by `bd config`) — integration credentials, status maps, and project-specific settings, stored in the Dolt database. Some keys are routed to `config.yaml` instead (see [YAML-only keys](#yaml-only-keys-startup-settings) below).

For a deeper treatment of every namespace and its semantics, see [docs/CONFIG.md](https://github.com/gastownhall/beads/blob/main/docs/CONFIG.md).

## Configuration Locations

`config.yaml` is searched in this order, with later files overriding earlier ones:

1. `~/.beads/config.yaml` (legacy user-level, lowest priority)
2. `~/.config/bd/config.yaml` (XDG user-level)
3. `<repo>/.beads/config.yaml` (project-level, walked up from the current directory)
4. `$BEADS_DIR/config.yaml` (highest priority, when `BEADS_DIR` is set)

A `config.local.yaml` next to the project `config.yaml` is also merged in last for machine-specific overrides that should not be committed.

## Precedence

For Viper-managed (YAML) keys, highest to lowest:

1. **Command-line flags** (e.g. `--json`, `--db`, `--actor`)
2. **Environment variables** (`BD_*`, plus a small set of legacy `BEADS_*` names — see below)
3. **`config.yaml`** files (in the order listed above)
4. **Built-in defaults**

Project-level keys written via `bd config set` (Jira, Linear, GitHub, status maps, etc.) live in the Dolt database. They are read at command time and have no env var override.

## Managing Configuration

```bash
# Set a value (auto-routes to config.yaml or the database)
bd config set jira.url "https://company.atlassian.net"
bd config set validation.on-create warn   # YAML-only key

# Set many values in one go
bd config set-many jira.url=https://example.atlassian.net jira.project=PROJ

# Get a value
bd config get jira.url

# List all database-stored config (with override warnings)
bd config list

# Show all effective config with provenance (env / config.yaml / default / database)
bd config show
bd config show --source config.yaml
bd config show --json

# Validate sync-related configuration
bd config validate

# Remove a value
bd config unset jira.url
```

`bd config set` automatically routes the write to the right location: keys in the YAML namespace (see below) are written to the project `config.yaml`; everything else is written to the Dolt database. `beads.role` is stored in git config.

## YAML-only Keys (Startup Settings)

These keys must live in `config.yaml`, not the database, because they are read before the database is opened. Writing them with `bd config set` automatically updates `config.yaml`.

The full namespaces routed to YAML are:

`routing.*`, `sync.*`, `git.*`, `directory.*`, `repos.*`, `external_projects.*`, `validation.*`, `hierarchy.*`, `ai.*`, `backup.*`, `export.*`, `dolt.*`, `federation.*`

Plus these individual keys:

`no-db`, `json`, `db`, `actor`, `identity`, `no-push`, `no-git-ops`, `create.require-description`, `github.token`, `linear.api_key`, `linear.oauth_client_id`, `linear.oauth_client_secret`.

Secrets in this list are refused on git-tracked `config.yaml` files unless you pass `--force-git-tracked`; export the value as an environment variable instead (e.g. `LINEAR_API_KEY`).

## Tool-Level Settings (config.yaml)

| Setting | Flag | Env Var | Default | Description |
|---|---|---|---|---|
| `json` | `--json` | `BD_JSON` | `false` | JSON output for scripting |
| `db` | `--db` | `BD_DB` | (auto-discover) | Database path |
| `actor` | `--actor` | `BEADS_ACTOR` | `git config user.name` | Actor name for audit trail |
| `identity` | `--identity` | `BEADS_IDENTITY` | (git user / hostname) | Sender identity for `bd mail` |
| `no-db` | `--no-db` | `BD_NO_DAEMON` (related) | `false` | Run without opening the database |
| `no-push` | `--no-push` | — | `false` | Skip pushing to Dolt remote |
| `no-git-ops` | — | — | `false` | Disable git ops in `bd prime` close protocol |
| `dolt.auto-commit` | `--dolt-auto-commit` | `BD_DOLT_AUTO_COMMIT` | `on` | Create a Dolt history commit after each successful write |
| `dolt.auto-push` | — | `BD_DOLT_AUTO_PUSH` | `false` | Auto-push to Dolt remote after writes (opt-in) |
| `dolt.shared-server` | `--shared-server` | `BEADS_DOLT_SHARED_SERVER` | `false` | Share one Dolt server at `~/.beads/shared-server/` |
| `dolt.max-conns` | — | `BEADS_DOLT_MAX_CONNS` | `10` | Connection pool size |
| `git.author` | — | — | (none) | Override commit author for beads commits |
| `git.no-gpg-sign` | — | — | `false` | Disable GPG signing for beads commits |
| `create.require-description` | — | `BD_CREATE_REQUIRE_DESCRIPTION` | `false` | Require description on `bd create` |
| `validation.on-create` | — | `BD_VALIDATION_ON_CREATE` | `none` | Template validation: `none`, `warn`, `error` |
| `validation.on-close` | — | `BD_VALIDATION_ON_CLOSE` | `none` | Template validation on close |
| `validation.on-sync` | — | `BD_VALIDATION_ON_SYNC` | `none` | Template validation before sync |
| `validation.metadata.mode` | — | — | `none` | Metadata schema validation |
| `hierarchy.max-depth` | — | — | `3` | Max hierarchical ID nesting depth |
| `backup.enabled` | — | `BD_BACKUP_ENABLED` | `false` | Enable periodic Dolt-native backup |
| `backup.interval` | — | `BD_BACKUP_INTERVAL` | `15m` | Minimum time between auto-backups |
| `backup.git-push` | — | — | `false` | Auto-push backup repo |
| `backup.git-repo` | — | `BD_BACKUP_GIT_REPO` | (none) | Backup git repo URL |
| `export.auto` | — | — | `false` | Refresh `.beads/issues.jsonl` export after every write; not cross-machine sync |
| `export.path` | — | — | `issues.jsonl` | Output filename relative to `.beads/` |
| `import.path` | — | — | `issues.jsonl` | Input filename relative to `.beads/` for implied JSONL imports; use relative paths for portability |
| `export.interval` | — | — | `60s` | Minimum time between auto-exports |
| `export.git-add` | — | — | `false` | Run `git add` on the export file |
| `routing.mode` | — | — | (none) | Multi-repo routing: `auto`, `maintainer`, `contributor`, `explicit` |
| `routing.default` | — | — | `.` | Default routing target |
| `routing.maintainer` | — | — | `.` | Maintainer-routed path |
| `routing.contributor` | — | — | `~/.beads-planning` | Contributor-routed path |
| `federation.remote` | — | `BD_FEDERATION_REMOTE` | (none) | Dolt remote URL (`dolthub://`, `gs://`, `s3://`, `az://`, `file://`) |
| `federation.sovereignty` | — | `BD_FEDERATION_SOVEREIGNTY` | (none) | Sovereignty tier: `T1`, `T2`, `T3`, `T4` |
| `federation.allowed-remote-patterns` | — | — | `[]` | Glob patterns restricting allowed remote URLs |
| `federation.exclude_types` | — | — | `[wisp]` | Issue types excluded from federation push |
| `sync.require_confirmation_on_mass_delete` | — | — | `false` | Prompt before pushing >50% issue deletions |
| `directory.labels` | — | — | `{}` | Map directory patterns → labels for monorepos |
| `external_projects` | — | — | `{}` | Map project names → paths for cross-project deps |
| `output.title-length` | — | — | `255` | Title display in feedback (`0` hides); see routing note below |
| `ai.model` | — | `BD_AI_MODEL` | `claude-haiku-4-5-20251001` | Default AI model |
| `agents.file` | — | — | `AGENTS.md` | Agents instruction filename; see routing note below |

:::important JSONL export is opt-in

`export.auto` and `export.git-add` are disabled unless configured explicitly.
`.beads/issues.jsonl` is an optional export for viewers, interchange, and
issue-level migration. It is not the canonical source of truth, not
cross-machine sync, and not a full database backup.

Workflows that depend on a fresh, git-staged JSONL file should opt in:

```bash
bd config set export.auto true
bd config set export.git-add true
```

Use `bd dolt push` / `bd dolt pull` for sync and `bd backup` for restorable
database backups.

:::

Routing note: `output.title-length` and `agents.file` are functionally tool-level settings, but `bd config set` writes them to the Dolt database. They are typically read from `config.yaml` when set there directly.

`bd config show` is the source of truth for what's currently effective on your machine, including provenance.

## Project-Level Settings (Database)

These are written to the Dolt database by `bd config set` and have no env var override. Common namespaces:

| Namespace | Purpose |
|---|---|
| `jira.*` | Jira integration (URL, project, status_map, type_map) |
| `linear.*` | Linear integration (team_id, state_map, label_type_map, relation_map) |
| `github.*` | GitHub integration (org, repo, label_map) |
| `ado.*` | Azure DevOps integration (org, project, state_map, type_map) |
| `custom.*` | User-defined / custom integrations |
| `status.custom` | Comma-separated list of custom statuses |
| `types.custom` | Comma-separated list of custom issue types |
| `types.infra` | Infra types routed to wisps table |
| `import.orphan_handling` | `allow` (default) \| `resurrect` \| `skip` \| `strict` |
| `compact_*` | Compaction tuning (see [docs/CONFIG.md](https://github.com/gastownhall/beads/blob/main/docs/CONFIG.md)) |
| `issue_id_mode` | `hash` (default) \| `counter` (sequential) |
| `min_hash_length`, `max_hash_length` | Adaptive ID bounds (defaults `4` and `8`) |
| `max_collision_prob` | Hash ID collision tolerance (default `0.25`) |
| `doctor.suppress.*` | Suppress specific `bd doctor` warnings by check slug |

Issue prefix (`issue_prefix`) is **not** settable via `bd config set` — use `bd init --prefix`, `bd bootstrap`, or `bd rename-prefix`.

## Environment Variables

The Viper env prefix is `BD_`. Config keys map to env vars by upper-casing and replacing `.` and `-` with `_` (e.g. `dolt.auto-commit` → `BD_DOLT_AUTO_COMMIT`, `validation.on-create` → `BD_VALIDATION_ON_CREATE`).

Selected commonly-used variables:

| Variable | Description |
|---|---|
| `BD_DB`, `BEADS_DB` | Database path (legacy `BEADS_DB` still honored) |
| `BD_JSON` | Force JSON output |
| `BD_DOLT_AUTO_COMMIT` | Override `dolt.auto-commit` (`on`/`off`) |
| `BD_DOLT_AUTO_PUSH` | Override `dolt.auto-push` |
| `BD_BACKUP_ENABLED`, `BD_BACKUP_INTERVAL`, `BD_BACKUP_GIT_REPO` | Override backup settings |
| `BD_AI_MODEL` | Override AI model |
| `BD_FEDERATION_REMOTE`, `BD_FEDERATION_SOVEREIGNTY` | Override federation settings |
| `BD_VALIDATION_ON_CREATE` / `_ON_CLOSE` / `_ON_SYNC` | Override validation modes |
| `BD_NO_PAGER`, `BD_PAGER` | Pager behavior |
| `BD_NON_INTERACTIVE` | Disable prompts |
| `BD_DEBUG` | Enable debug logging |
| `BEADS_DIR` | Force the active beads workspace directory |
| `BEADS_ACTOR` | Actor identity (preferred over `BD_ACTOR`, which is a deprecated alias) |
| `BEADS_IDENTITY` | Sender identity for `bd mail` |
| `BEADS_DOLT_SERVER_MODE`, `BEADS_DOLT_SHARED_SERVER`, `BEADS_DOLT_DATA_DIR`, `BEADS_DOLT_PORT`, ... | Embedded/server Dolt overrides |

Secrets like API tokens follow integration-specific conventions: `LINEAR_API_KEY`, `GITHUB_TOKEN`, `ANTHROPIC_API_KEY`, `AZURE_DEVOPS_PAT`. These are preferred over storing the value in `config.yaml` for git-tracked projects.

`bd config show` will display the source of every effective key, making overrides explicit.

## Example `.beads/config.yaml`

```yaml
# Default JSON output for scripting
json: true

# Dolt history & sync
dolt:
  auto-commit: on    # Create a Dolt commit after each successful write
  auto-push: false   # Opt-in for single-writer setups

# Issue creation policies
create:
  require-description: true

validation:
  on-create: warn    # Warn when creating issues missing required sections
  on-close: none
  on-sync: none

# Git commit signing for beads commits (GH#600)
git:
  author: "beads-bot <beads@example.com>"
  no-gpg-sign: true

# Periodic Dolt-native backup to .beads/backup/
backup:
  enabled: true
  interval: 15m

# Optional auto-export of issues.jsonl after writes for viewers/interchange
export:
  auto: false
  path: issues.jsonl
  interval: 60s
  git-add: false

# Optional Dolt federation
federation:
  remote: dolthub://myorg/beads
  sovereignty: T2

# Directory-aware label scoping for monorepos (GH#541)
directory:
  labels:
    packages/maverick: maverick
    packages/agency: agency

# Cross-project dependency resolution (bd-h807)
external_projects:
  beads: ../beads
  other-project: /absolute/path/to/other-project

output:
  title-length: 255
```

For machine-specific overrides that should not be committed, drop them in `.beads/config.local.yaml`; it is merged in last.

## Per-Command Override

```bash
bd --db /tmp/test.db list           # Override database for one command
bd --json --actor "ci-bot" create "Fix things"  # Multiple flags
```

## Viewing Active Configuration

```bash
bd config show                # Effective config with provenance
bd config show --json         # Machine-readable
bd config list                # Database-stored config
bd info --json | jq '.config' # Quick snapshot
```

</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
- **Dolt-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 Dolt instead of plain SQLite?

- **Dolt** provides a version-controlled SQL database with built-in replication
- Git-like branching, diffing, and merging at the database level
- No need for a separate sync format -- Dolt handles it natively

### 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.

### How does the Dolt server work?

Beads uses Dolt server mode for concurrent access:
- Transaction isolation for multiple agents
- SQL-based queries for performance
- Automatic retry on conflicts

In CI/CD or single-agent environments, beads uses embedded mode automatically (no server required).

## Usage

### How do I sync issues?

```bash
# Push changes to Dolt remote:
bd dolt push

# Pull changes from Dolt remote:
bd dolt pull
```

### How do I handle merge conflicts?

Dolt handles merge conflicts at the database level. If conflicts arise during pull:
```bash
bd doctor --fix
bd dolt push
```

### 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
# Just run commands directly — beads uses embedded mode in CI
bd 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 — see the [GitHub integration documentation](https://github.com/gastownhall/beads/blob/main/docs/GITHUB_IMPORT.md) for details.

## Troubleshooting

### Why is the Dolt server not starting?

```bash
# Check server status
bd doctor

# Check server logs
cat .beads/dolt/sql-server.log

# Restart the server
bd dolt stop
bd dolt start
```

### Why aren't my changes syncing?

```bash
# Force push to Dolt remote
bd dolt push

# Check hooks
bd hooks status
```

### How do I report a bug?

1. Check existing issues: https://github.com/gastownhall/beads/issues
2. Include: `bd version`, `bd info --json`, reproduction steps
3. File at: https://github.com/gastownhall/beads/issues/new

</document>

<document path="docs/reference/git-integration.md">


# Git Integration

How beads integrates with git.

## Overview

Beads uses git for:
- **Project hosting** - Your code repository also hosts beads configuration
- **Hooks** - Auto-sync on git operations

Data storage and sync are handled by Dolt (a version-controlled SQL database).

## File Structure

```
.beads/
├── config.yaml        # Project config (git-tracked)
├── metadata.json      # Backend metadata (git-tracked)
└── dolt/              # Dolt database and server data (gitignored)
```

## Git Hooks

### Installation

```bash
bd hooks install
```

Installs:
- **pre-commit** - Triggers Dolt commit
- **post-merge** - Triggers Dolt sync after pull
- **pre-push** - Ensures Dolt sync before push

### Status

```bash
bd hooks status
```

### Uninstall

```bash
bd hooks uninstall
```

## Conflict Resolution

Dolt handles merge conflicts at the database level using its built-in
merge capabilities. When conflicts arise during sync, Dolt identifies
conflicting rows and allows resolution through SQL.

```bash
# Check for and fix conflicts
bd doctor --fix
```

## Protected Branches

Dolt stores data under `refs/dolt/data`, separate from Git refs. This means beads data doesn't conflict with protected Git branches — no special branch flag is needed. On new projects with a git `origin`, `bd init` configures that origin as the Dolt remote automatically.

## Git Worktrees

Beads works in git worktrees using embedded mode:

```bash
# In worktree — just run commands directly
bd create "Task"
bd list
```

## Branch Workflows

### Feature Branch

```bash
git checkout -b feature-x
bd create "Feature X" -t feature
# Work...
bd dolt push
git push
```

### Fork Workflow

```bash
# In fork
bd init --contributor
# Work in separate planning repo...
bd dolt push
```

### Team Workflow

```bash
bd init --team
# All team members share the Dolt database
bd dolt pull   # Pull latest changes from Dolt remote
bd dolt push   # Push your changes to Dolt remote
```

### Duplicate Detection

After merging branches:

```bash
bd duplicates --auto-merge
```

## Best Practices

1. **Install hooks** - `bd hooks install`
2. **Push regularly** - `bd dolt push` at session end
3. **Pull before work** - `bd dolt pull` to get latest issues
4. **Worktrees use embedded mode automatically**

</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 with the recommended installer
curl -fsSL https://raw.githubusercontent.com/gastownhall/beads/main/scripts/install.sh | bash
```

### `zsh: killed bd` on macOS

CGO/SQLite compatibility issue:

```bash
CGO_ENABLED=1 GOFLAGS=-tags=gms_pure_go 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 the Dolt server if running
bd dolt stop

# Try again
bd list
```

### Corrupted database

```bash
# Check and fix database
bd doctor --fix

# Or pull from Dolt remote
bd dolt pull

# Or restore from a backup
bd backup restore [path] --force
```

## Dolt Server Issues

### Server not starting

```bash
# Check server health
bd doctor

# Check server logs
cat .beads/dolt/sql-server.log

# Restart the server
bd dolt stop
bd dolt start
```

### Version mismatch

After upgrading bd:

```bash
bd dolt stop
bd dolt start
```

## Sync Issues

### Changes not syncing

```bash
# Force push to Dolt remote
bd dolt push

# Check hooks
bd hooks status
```

### Recovery from backup

```bash
# Restore from a Dolt backup
bd backup restore [path] --force

# Or pull from Dolt remote
bd dolt pull
```

### Merge conflicts

```bash
# Check for and fix Dolt conflicts
bd doctor --fix

# Re-push
bd dolt push
```

## 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
cat .beads/dolt/sql-server.log
```

### 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/gastownhall/beads/issues

</document>

---

# End of Documentation

For updates and contributions, visit: https://github.com/gastownhall/beads
