Split monolithic sqlite.go into focused files

internal/storage/sqlite/sqlite.go is 1050 lines containing initialization, 20+ CRUD methods, query building, and schema management.

Split into:
- store.go: Store struct & initialization (150 lines)
- bead_queries.go: Bead CRUD (300 lines)
- work_queries.go: Work queries (200 lines)
- stats_queries.go: Statistics (150 lines)
- schema.go: Schema & migrations (150 lines)
- helpers.go: Common utilities (100 lines)

Impact: Impossible to understand at a glance; hard to find specific functionality; high cognitive load

Effort: 6-8 hours


bd doctor should recommend bd prime migration for existing repos

bd doctor should detect old beads integration patterns and recommend migrating to bd prime approach.

## Current behavior
- bd doctor checks if Claude hooks are installed globally
- Doesn't check project-level integration (AGENTS.md, CLAUDE.md)
- Doesn't recommend migration for repos using old patterns

## Desired behavior
bd doctor should detect and suggest:

1. **Old slash command pattern detected**
   - Check for /beads:* references in AGENTS.md, CLAUDE.md
   - Suggest: These slash commands are deprecated, use bd prime hooks instead

2. **No agent documentation**
   - Check if AGENTS.md or CLAUDE.md exists
   - Suggest: Run 'bd onboard' or 'bd setup claude' to document workflow

3. **Old MCP-only pattern**
   - Check for instructions to use MCP tools but no bd prime hooks
   - Suggest: Add bd prime hooks for better token efficiency

4. **Migration path**
   - Show: 'Run bd setup claude to add SessionStart/PreCompact hooks'
   - Show: 'Update AGENTS.md to reference bd prime instead of slash commands'

## Example output

⚠ Warning: Old beads integration detected in CLAUDE.md
  Found: /beads:* slash command references (deprecated)
  Recommend: Migrate to bd prime hooks for better token efficiency
  Fix: Run 'bd setup claude' and update CLAUDE.md

💡 Tip: bd prime + hooks reduces token usage by 80-99% vs slash commands
  MCP mode: ~50 tokens vs ~10.5k for full MCP scan
  CLI mode: ~1-2k tokens with automatic context recovery

## Benefits
- Helps existing repos adopt new best practices
- Clear migration path for users
- Better token efficiency messaging


Create backup and restore procedures

Disaster recovery procedures for Agent Mail data.

Acceptance Criteria:
- Automated daily snapshots (GCP persistent disk)
- SQLite backup script
- Git repository backup
- Restore procedure documentation
- Test restore from backup

File: deployment/agent-mail/backup.sh


Test issue 2


Fix compact --analyze/--apply error messages to clarify direct mode requirement

**Problem:**
When users run `bd compact --analyze` with daemon running, they get:
```
Error: compact requires SQLite storage
```

This is misleading because they ARE using SQLite (via daemon), but the command needs DIRECT SQLite access.

**Current behavior:**
- Error message suggests they don't have SQLite
- No hint about using --no-daemon flag
- Related to issue #349 item #1

**Proposed fix:**
1. Update error messages in cmd/bd/compact.go lines 106-114 (analyze) and 121-137 (apply)
2. Add explicit hint: "Use --no-daemon flag to bypass daemon"
3. Change SQLite check error from "requires SQLite storage" to "failed to open database in direct mode"

**Files to modify:**
- cmd/bd/compact.go (lines ~106-137)

**Testing:**
- Run with daemon: `bd compact --analyze` should show clear error + hint
- Run with --no-daemon: `bd compact --analyze --no-daemon` should work
- Verify error message is actionable

Change error messages to be explicit about direct mode requirement:

```go
if err := ensureDirectMode("compact --analyze requires direct database access"); err != nil {
    fmt.Fprintf(os.Stderr, "Error: %v\n", err)
    fmt.Fprintf(os.Stderr, "Hint: Use --no-daemon flag to bypass daemon and access database directly\n")
    os.Exit(1)
}
```

For SQLite check failure:
```go
if !ok {
    fmt.Fprintf(os.Stderr, "Error: failed to open database in direct mode\n")
    fmt.Fprintf(os.Stderr, "Hint: Ensure .beads/beads.db exists and is readable\n")
    os.Exit(1)
}
```

Addresses GitHub issue #349 item 1: https://github.com/steveyegge/beads/issues/349

User reported misleading error when running 'bd compact --analyze' with daemon active. Error says 'requires SQLite storage' but user IS using SQLite via daemon - the real issue is that --analyze mode needs DIRECT database access.


Proposal: Custom status states via config

Proposal to add 'custom status states' via `bd config`.
Users could define an optional issue status enum (e.g., awaiting_review, review_in_progress) in the config.
This would enable multi-step pipelines to process issues where each step correlates to a specific status.

Examples:
- awaiting_verification
- awaiting_docs
- awaiting_testing


Add WebSocket support

## Feature Request

[Describe the desired feature]

## Motivation

[Why is this feature needed? What problem does it solve?]

## Use Cases

1. **Use Case 1**: [description]
2. **Use Case 2**: [description]

## Proposed Solution

[High-level approach to implementing this feature]

## Alternatives Considered

- **Alternative 1**: [description and why not chosen]
- **Alternative 2**: [description and why not chosen]

## Technical Design

[Detailed technical approach]

## API Changes

[New commands, flags, or APIs]

## Data Model Changes

[Database schema changes if any]

## Implementation Notes

- Note 1
- Note 2

## Testing Strategy

- Unit tests: [scope]
- Integration tests: [scope]
- Manual testing: [steps]

- [ ] Feature implements all described use cases
- [ ] All tests pass
- [ ] Documentation updated (README, commands)
- [ ] Examples added if applicable
- [ ] No performance regressions


Add 'bd status' command for issue database overview

Implement a bd status command that provides a quick snapshot of the issue database state, similar to how git status shows working tree state.

Expected output: Show summary including counts by state (open, in-progress, blocked, closed), recent activity (last 7 days), and quick overview without needing multiple queries.

Example output showing issue counts, recent activity stats, and pointer to bd list for details.

Proposed options: --all (show all issues), --assigned (show issues assigned to current user), --json (JSON format output)

Use cases: Quick project health check, onboarding for new contributors, integration with shell prompts or CI/CD, daily standup reference


Beads commands operate on stale database without warning

All beads read operations should validate database is in sync with JSONL before proceeding.

**Current Behavior:**
- Commands can query/read from stale database
- Only mutation operations (like 'bd sync') check if JSONL is newer
- User gets incorrect results without realizing database is out of sync

**Expected Behavior:**
- All beads commands should have pre-flight check for database freshness
- If JSONL is newer than database, refuse to operate with error: "Database out of sync. Run 'bd import' first."
- Same safety check that exists for 'bd sync' should apply to ALL operations

**Impact:**
- Users make decisions based on incomplete/outdated data
- Silent failures lead to confusion (e.g., thinking issues don't exist when they do)
- Similar to running git commands on stale repo without being warned to pull

**Example:**
- Searched for bd-g9eu issue file: not found
- Issue exists in .beads/issues.jsonl (in git)
- Database was stale, but no warning was given
- Led to incorrect conclusion that issue was already closed/deleted


Implement `bd setup cursor` for Cursor IDE integration

Create a `bd setup cursor` command that integrates Beads workflow into Cursor IDE via .cursorrules file. Unlike Claude Code (which has hooks), Cursor uses a static rules file to provide context to its AI.

## Implementation

Create `cursor` subcommand in `cmd/bd/setup.go` that manages `.cursorrules` integration:

### Command Interface
```bash
bd setup cursor           # Install/update Cursor integration
bd setup cursor --check   # Verify .cursorrules has bd section
bd setup cursor --remove  # Remove bd section from .cursorrules
```

### Behavior

**If `.cursorrules` doesn't exist:**
- Create new file with complete bd rules template
- Mark sections for easy identification

**If `.cursorrules` exists:**
- Check if bd section already exists (look for marker comments)
- If not exists: append bd section
- If exists: update in place (preserve user customizations outside bd section)
- Backup original with `.cursorrules.backup` suffix

### .cursorrules Template

```markdown
# Beads Issue Tracking
# Auto-generated by 'bd setup cursor' - do not remove these markers
# BEGIN BEADS INTEGRATION

This project uses [Beads (bd)](https://github.com/steveyegge/beads) for issue tracking.

## Core Rules
- Track ALL work in bd (never use markdown TODOs or comment-based task lists)
- Use `bd ready` to find available work
- Use `bd create` to track new issues/tasks/bugs
- Use `bd sync` at end of session to sync with git remote
- Git hooks auto-sync on commit/merge

## Quick Reference
```bash
bd prime                              # Load complete workflow context
bd ready                              # Show issues ready to work (no blockers)
bd list --status=open                 # List all open issues
bd create --title="..." --type=task  # Create new issue
bd update <id> --status=in_progress  # Claim work
bd close <id>                         # Mark complete
bd dep <from> <to>                    # Add dependency (from blocks to)
bd sync                               # Sync with git remote
```

## Workflow
1. Check for ready work: `bd ready`
2. Claim an issue: `bd update <id> --status=in_progress`
3. Do the work
4. Mark complete: `bd close <id>`
5. Sync: `bd sync` (or let git hooks handle it)

## Context Loading
Run `bd prime` to get complete workflow documentation in AI-optimized format (~1-2k tokens).

For detailed docs: see AGENTS.md, QUICKSTART.md, or run `bd --help`

# END BEADS INTEGRATION
```

### Detection Logic

```go
func setupCursor() error {
    cursorRulesPath := ".cursorrules"

    // Check if file exists
    content, err := os.ReadFile(cursorRulesPath)
    if err != nil {
        if os.IsNotExist(err) {
            // Create new file
            return createCursorRules(cursorRulesPath)
        }
        return err
    }

    // Check if bd section exists
    if hasBeadsSection(string(content)) {
        // Update existing section
        return updateBeadsSection(cursorRulesPath, string(content))
    } else {
        // Append new section
        return appendBeadsSection(cursorRulesPath, string(content))
    }
}

func hasBeadsSection(content string) bool {
    return strings.Contains(content, "BEGIN BEADS INTEGRATION")
}
```

## Files
- `cmd/bd/setup.go` - Add cursor subcommand
- `cmd/bd/setup_cursor.go` - Cursor-specific logic
- `cmd/bd/setup_cursor_test.go` - Tests
- Template stored as Go string constant

## Differences from Claude Setup

| Aspect | Claude | Cursor |
|--------|--------|--------|
| **Integration file** | `.claude/commands/`, `.claude/hooks/` | `.cursorrules` |
| **Auto-refresh** | Hooks call `bd prime` | Static rules (manual refresh) |
| **Setup complexity** | Multiple files | Single file |
| **Update frequency** | Dynamic (hooks) | Static (updated via `bd setup cursor`) |

- `bd setup cursor` creates/updates .cursorrules
- Idempotent (safe to run multiple times)
- Preserves non-bd content in .cursorrules
- Backs up existing .cursorrules before modifying
- `bd setup cursor --check` verifies integration
- Markers allow updating bd section without affecting user content
- Unit tests for template insertion/update logic
- Documentation in AGENTS.md mentions Cursor setup


Add orphan detection migration

Create migration to detect orphaned children in existing databases. Query: SELECT id FROM issues WHERE id LIKE '%.%' AND substr(id, 1, instr(id || '.', '.') - 1) NOT IN (SELECT id FROM issues). Log results, let user decide action (delete orphans or convert to top-level).


Workaround for FastMCP outputSchema bug in Claude Code

The beads MCP server (v0.23.1) successfully connects to Claude Code, but all tools fail to load with a schema validation error due to a bug in FastMCP 2.13.1.

Error: "Invalid literal value, expected \"object\"" in outputSchema.

Root Cause: FastMCP generates outputSchema with $ref at root level without "type": "object" for self-referential models (Issue).

Workaround: Use slash commands (/beads:ready) or wait for FastMCP fix.


Fix failing integration tests in beads-mcp

The `beads-mcp` test suite has failures in `tests/test_bd_client_integration.py` (assertion error in `test_init_creates_beads_directory`) and errors in `tests/test_worktree_separate_dbs.py` (setup failures finding database). These need to be investigated and fixed to ensure a reliable CI baseline.


Widespread double JSON encoding bug in daemon mode RPC calls

Multiple CLI commands had the same double JSON encoding bug found in bd-1048. All commands that called ResolveID via RPC used string(resp.Data) instead of properly unmarshaling the JSON response. This caused IDs to retain JSON quotes ("bd-1048" instead of bd-1048), which then got double-encoded when passed to subsequent RPC calls.

Affected commands:
- bd show (3 instances)
- bd dep add/remove/tree (5 instances)
- bd label add/remove/list (3 instances)
- bd reopen (1 instance)

Root cause: resp.Data is json.RawMessage (already JSON-encoded), so string() conversion preserves quotes.

Fix: Replace all string(resp.Data) with json.Unmarshal(resp.Data, &id) for proper deserialization.

All commands now tested and working correctly with daemon mode.


bd find-duplicates - AI-powered duplicate detection

Find semantically duplicate issues.

Approaches:
1. Mechanical: Exact title/description matching
2. Embeddings: Cosine similarity (cheap, scalable)
3. AI: LLM-based semantic comparison (expensive, accurate)

Uses embeddings by default for >100 issues.

Files: cmd/bd/find_duplicates.go (new)


Test parent issue


Add tests for helper functions (GetDirtyIssueHash, GetAllDependencyRecords, export hashes)

Several utility functions have 0% coverage:
- GetDirtyIssueHash (dirty.go)
- GetAllDependencyRecords (dependencies.go)
- GetExportHash, SetExportHash, ClearAllExportHashes (hash.go)

These are lower priority but should have basic coverage.


Latency test 1


Optimize GetReadyWork performance - 752ms on 10K database (target: <50ms)

# Performance Analysis (10K Issue Database)

Analyzed using CPU profiles from benchmark suite on Apple M2 Pro.

## Operation Performance

| Operation                        | Time    | Allocations | Memory |
|----------------------------------|---------|-------------|--------|
| bd ready (GetReadyWork)          | ~752ms  | 167,466     | 16MB   |
| bd list (SearchIssues no filter) | ~11.6ms | 89,214      | 5.8MB  |
| bd list (SearchIssues filtered)  | ~9.2ms  | 62,365      | 3.5MB  |
| bd create (CreateIssue)          | ~2.6ms  | 146         | 8.6KB  |
| bd update (UpdateIssue)          | ~0.32ms | 364         | 15KB   |
| bd close (UpdateIssue)           | ~0.32ms | 364         | 15KB   |

**Target: <50ms for all operations on 10K database**

**Current issue: GetReadyWork is 15x over target (752ms vs 50ms)**

## Root Cause

GetReadyWork (internal/storage/sqlite/ready.go:90-128) uses recursive CTE to propagate blocking:
- 65x slower than SearchIssues
- Recalculates entire blocked issue tree on every call
- Algorithm:
  1. Find directly blocked issues via 'blocks' dependencies
  2. Recursively propagate blockage to descendants (max depth: 50)
  3. Exclude all blocked issues from results

## CPU Profile Analysis

- Database syscalls (pthread_cond_signal, syscall6): ~75%
- SQLite engine overhead: inherent to recursive CTE
- Application code (query construction): <1%

**Bottleneck is the recursive CTE query execution, not application code.**

## Optimization Recommendations

### High Impact (Likely to achieve <50ms target)

1. **Cache blocked issue calculation**
   - Add `blocked_issues` table updated on dependency changes
   - Trade write complexity for read speed (ready called >> dependency changes)
   - Eliminates recursive CTE on every read

2. **Add/verify database indexes**
   ```sql
   CREATE INDEX IF NOT EXISTS idx_dependencies_blocked
     ON dependencies(issue_id, type, depends_on_id);
   CREATE INDEX IF NOT EXISTS idx_issues_status
     ON issues(status);
   ```

### Medium Impact

3. **Reduce allocations** (167K allocations for GetReadyWork)
   - Profile `scanIssues()` for object pooling opportunities
   - Reuse slice capacity for repeated calls

### Low Impact (Not recommended)
- Query optimization for CRUD operations (already <3ms)
- Connection pooling tuning (not showing in profiles)

## Verification

Run benchmarks to validate optimization:
```bash
make bench-quick
go tool pprof -http=:8080 internal/storage/sqlite/bench-cpu-*.prof
```

Profile files automatically generated in `internal/storage/sqlite/`.


Log errors from timer-triggered flushes instead of discarding

In FlushManager.run() at flush_manager.go:197-200, timer-triggered flushes silently discard errors:

```go
case <-fm.timerFiredCh:
    if isDirty {
        _ = fm.performFlush(needsFullExport)  // ← Error discarded!
```

Users won't know if auto-flush is failing. Should at minimum log errors.

Consider:
- Log error with debug.Logf() or fmt.Fprintf(os.Stderr)
- Optionally expose flush status via a Status() method
- Track last flush error for diagnostics

Related: Code review finding #4 from bd-52 race condition fix review.


Refactor path canonicalization into helper function

The path canonicalization logic (filepath.Abs + EvalSymlinks) is duplicated in 3 places:
- beads.go:131-137 (BEADS_DIR handling)
- cmd/bd/main.go:446-451 (--no-db cleanup)
- cmd/bd/nodb.go:26-31 (--no-db initialization)

Refactoring suggestion:
Extract to a helper function like:
  func canonicalizePath(path string) string

This would:
- Reduce code duplication
- Make the logic easier to maintain
- Ensure consistent behavior across all path handling

Related to bd-e16b implementation.


Import reports misleading '0 created, 0 updated' when actually importing all issues

When running 'bd import' on a fresh database (no existing issues), the command reports 'Import complete: 0 created, 0 updated' even though it successfully imported all issues from the JSONL file.

**Steps to reproduce:**
1. Delete .beads/beads.db
2. Run: bd import .beads/issues.jsonl
3. Observe output: 'Import complete: 0 created, 0 updated'
4. Run: bd list
5. Confirm: All issues are actually present in the database

**Expected behavior:**
Report the actual number of issues imported, e.g., 'Import complete: 523 created, 0 updated'

**Actual behavior:**
'Import complete: 0 created, 0 updated' (misleading - makes user think import failed)

**Impact:**
- Users think import failed when it succeeded
- Confusing during database sync operations (e.g., after git pull)
- Makes debugging harder (can't tell if import actually worked)

**Context:**
Discovered during VC session when syncing database after git pull. The misleading message caused confusion about whether the database was properly synced with the canonical JSONL file.

- Import command reports accurate count of created/updated issues
- Fresh database import shows 'N created' where N is the actual number
- Update operations show 'N updated' where N is the actual number changed
- Message clearly indicates success vs failure


Document which files to commit after bd init --branch

GH #312 reported confusion about which files should be committed after running 'bd init --branch beads-metadata'. Updated PROTECTED_BRANCHES.md to clearly document:

1. Files that should be committed to protected branch (main):
   - .beads/.gitignore
   - .gitattributes

2. Files that are automatically gitignored
3. Files that live in the sync branch (beads-metadata)

Changes:
- Added step-by-step instructions in Quick Start section
- Added 'What lives in each branch' section to How It Works
- Clarified the directory structure diagram

Fixes: https://github.com/steveyegge/beads/issues/312


bd resolve-conflicts - Git merge conflict resolver

Automatically resolve JSONL merge conflicts.

Modes:
- Mechanical: ID remapping (no AI)
- AI-assisted: Smart merge/keep decisions
- Interactive: Review each conflict

Handles <<<<<<< conflict markers in .beads/beads.jsonl

Files: cmd/bd/resolve_conflicts.go (new)


Add programmatic tip injection API

Allow tips to be programmatically injected at runtime based on detected conditions. This enables dynamic tips (not just pre-defined ones) to be shown with custom priority and frequency.

## API Design

Add to `cmd/bd/tips.go`:

```go
// InjectTip adds a dynamic tip to the registry at runtime
func InjectTip(id, message string, priority int, frequency time.Duration, probability float64, condition func() bool) {
    tipsMutex.Lock()
    defer tipsMutex.Unlock()

    tips = append(tips, Tip{
        ID:          id,
        Condition:   condition,
        Message:     message,
        Frequency:   frequency,
        Priority:    priority,
        Probability: probability,
    })
}

// RemoveTip removes a tip from the registry
func RemoveTip(id string) {
    tipsMutex.Lock()
    defer tipsMutex.Unlock()

    for i, tip := range tips {
        if tip.ID == id {
            tips = append(tips[:i], tips[i+1:]...)
            return
        }
    }
}
```

## Use Cases

### Example 1: Critical Security Update
```go
// In bd version check code
if criticalSecurityUpdate {
    InjectTip(
        "security_update",
        fmt.Sprintf("CRITICAL: Security update available (bd %s). Update immediately!", remoteVersion),
        100,         // Highest priority
        0,           // No frequency limit
        1.0,         // Always show (100% probability)
        func() bool { return true },
    )
}
```

### Example 2: New Version Available
```go
// In bd version check code
if remoteVersion > currentVersion {
    InjectTip(
        "upgrade_available",
        fmt.Sprintf("New bd version %s available (you have %s). Run: go install github.com/steveyegge/beads/cmd/bd@latest", remoteVersion, currentVersion),
        90,          // High priority
        7 * 24 * time.Hour,  // Weekly
        0.8,         // 80% probability (frequent but not always)
        func() bool { return true },
    )
}
```

### Example 3: Large Issue Count Suggestion
```go
// In bd list code
if issueCount > 100 {
    InjectTip(
        "use_filters",
        "You have many issues. Use filters: 'bd list --status=open --priority=1'",
        50,          // Medium priority
        14 * 24 * time.Hour,  // Bi-weekly
        0.4,         // 40% probability (occasional suggestion)
        func() bool { return true },
    )
}
```

### Example 4: No Dependencies Used
```go
// After analyzing project
if hasIssues && noDependenciesCreated {
    InjectTip(
        "try_dependencies",
        "Try using dependencies: 'bd dep <issue> <blocks-issue>' to track blockers",
        30,          // Low priority
        30 * 24 * time.Hour,  // Monthly
        0.3,         // 30% probability (low-key suggestion)
        func() bool { return true },
    )
}
```

## Probability Guidelines

- **1.0 (100%)**: Critical security, breaking changes, data loss prevention
- **0.7-0.9 (70-90%)**: Important updates, major new features
- **0.4-0.6 (40-60%)**: General tips, workflow improvements, feature discovery
- **0.1-0.3 (10-30%)**: Nice-to-know features, advanced tips, optional optimizations

## Thread Safety
- Use mutex to protect tip registry
- Safe for concurrent command execution
- Deterministic testing via BEADS_TIP_SEED env var

- InjectTip() API exists and is documented
- RemoveTip() API exists
- Thread-safe with mutex protection
- Can inject tips from any command
- Injected tips participate in priority/frequency rotation
- Unit tests for injection API
- Example usage in code comments


Remove misleading placeholder 'bd merge' command from duplicates output

**Problem:**
The `bd duplicates` command suggests running a command that doesn't exist:
```
bd merge <source-ids> --into <target-id>
```

This is confusing because:
1. `bd merge` is actually a git 3-way JSONL merge driver (takes 4 file paths)
2. The suggested syntax for merging duplicate issues is not implemented
3. Line 75 in duplicates.go even has: `// TODO: performMerge implementation pending`

**Current behavior:**
- Users see suggested command that doesn't work
- No indication that feature is unimplemented
- Related to issue #349 item #2

**Proposed fix:**
Replace line 77 in cmd/bd/duplicates.go with either:

Option A (conservative):
```go
cmd := fmt.Sprintf("# TODO: Merge %s into %s (merge command not yet implemented)",
    strings.Join(sources, " "), target.ID)
```

Option B (actionable):
```go
cmd := fmt.Sprintf("# Duplicate found: %s\n# Manual merge: Close duplicates with 'bd close %s' and link to %s as 'related'",
    strings.Join(sources, " "), strings.Join(sources, " "), target.ID)
```

**Files to modify:**
- cmd/bd/duplicates.go (line ~77)

Remove the non-existent command suggestion and replace with actionable guidance.

Since there are two unrelated `bd merge` concepts:
1. Git JSONL merge driver (exists, works)
2. Duplicate issue merger (doesn't exist, TODO)

We should not conflate them in user-facing output.

Addresses GitHub issue #349 item 2: https://github.com/steveyegge/beads/issues/349

User confused by 'bd merge' help text. The help text is actually correct (it's a git merge driver), but the duplicates command suggests a non-existent 'bd merge <ids> --into <target>' syntax for merging duplicate issues.


bd prime: AI context loading and Claude Code integration

Implement `bd prime` command and Claude Code hooks for context recovery. Hooks work with BOTH MCP server and CLI approaches - they solve the context memory problem (keeping bd workflow fresh after compaction) not the tool access problem (MCP vs CLI).

## Epic Scope

This epic covers:
1. Core `bd prime` command implementation with MCP-aware output
2. Claude Code hooks via `bd setup claude` (works with MCP OR CLI)
3. Automatic context recovery via SessionStart/PreCompact hooks
4. `bd doctor` verification for Claude setup
5. Documentation updates

## Goals
- Keep bd workflow fresh in agent context (prevent markdown TODO reversion)
- Enable automatic context recovery after compaction/clear
- Adapt to user's workflow preference (MCP vs CLI) automatically
- Support multi-user projects (mixed Claude/non-Claude teams)
- Verify setup with `bd doctor`

## Architecture Understanding

**MCP vs CLI is a user preference (not project-level):**
- User installs MCP server globally → gets native bd tools
- User doesn't install MCP → uses CLI via Bash tool
- `bd prime` auto-detects which mode and adapts output
- Same hooks work for all users regardless of preference

**Hooks complement both approaches:**
- **With MCP**: Hooks output workflow reminders (~500 tokens) - prevents forgetting to use MCP tools
- **Without MCP**: Hooks output full CLI reference (~1-2k tokens) - provides command syntax
- **Both cases**: Prevents markdown TODO reversion after compaction

**Why hooks matter even with MCP:**
- MCP tools can be forgotten after compaction
- Hooks refresh "use bd, not markdown" reminder
- PreCompact keeps bd workflow fresh in memory
- Works in both MCP and CLI scenarios

## Token Optimization

**MCP mode** (~500 tokens):
- Workflow reminders only
- No CLI syntax (user has native tools)
- References to MCP tool names

**Non-MCP mode** (~1-2k tokens):
- Full workflow rules
- Complete CLI command reference
- Examples and common patterns

**Why adaptive output matters:**
- MCP users waste tokens on CLI docs they don't need
- Non-MCP users need full command reference
- Same hook works for everyone, adapts automatically
- Multi-user projects: each dev gets appropriate output for their setup

## Out of Scope
- Tip system infrastructure (separate epic)
- Cursor/Windsurf integration (separate issues)
- MCP server modifications

- `bd prime` command exists and outputs AI-optimized markdown
- `bd setup claude` installs hooks and slash commands
- Hooks auto-call `bd prime` when .beads/ detected
- `bd doctor` verifies Claude integration
- Documentation complete in AGENTS.md, README.md, QUICKSTART.md
- All child issues closed


Update AGENTS.md with event-driven mode

Document BEADS_DAEMON_MODE env var. Explain opt-in during Phase 1. Add troubleshooting for watcher failures.


Update docs for import bug fix

Update AGENTS.md, README.md, TROUBLESHOOTING.md with import.orphan_handling config documentation. Document resurrection behavior, tombstones, config modes. Add troubleshooting section for import failures with deleted parents.


Optimize Memory backend GetIssueByExternalRef with index

Currently GetIssueByExternalRef in Memory storage uses O(n) linear search through all issues.

Current code (memory.go:282-308):
for _, issue := range m.issues {
    if issue.ExternalRef != nil && *issue.ExternalRef == externalRef {
        return &issueCopy, nil
    }
}

Proposed optimization:
- Add externalRefToID map[string]string to MemoryStorage
- Maintain it in CreateIssue, UpdateIssue, DeleteIssue
- Achieve O(1) lookup like SQLite's index

Impact: Low (--no-db mode typically has smaller datasets)
Related: bd-1022


Create Docker image for Agent Mail

Containerize Agent Mail server for easy deployment.

Acceptance Criteria:
- Dockerfile with Python 3.14
- Health check endpoint
- Volume mount for storage
- Environment variable configuration
- Multi-arch builds (amd64, arm64)

File: deployment/agent-mail/Dockerfile


Add monitoring and alerting

Observability for production Agent Mail server.

Acceptance Criteria:
- Health check endpoint (/health)
- Prometheus metrics export
- Grafana dashboard
- Alerts for server downtime
- Alerts for high error rate
- Log aggregation config

File: deployment/agent-mail/monitoring/


Add 'When to use daemon mode' decision tree to daemon.md

**Problem:**
Users (especially local-only developers) see daemon-related messages but don't understand:
- What daemon mode does (git sync automation)
- Whether they need it
- Why they see "daemon_unsupported" messages

Related to issue #349 item #3.

**Current state:**
commands/daemon.md explains WHAT daemon does but not WHEN to use it.

**Proposed addition:**
Add a "When to Use Daemon Mode" section after line 20 in commands/daemon.md with clear decision criteria:

**✅ You SHOULD use daemon mode if:**
- Working in a team with git remote sync
- Want automatic commit/push of issue changes
- Need background auto-sync (5-second debounce)
- Making frequent bd commands (performance benefit)

**❌ You DON'T need daemon mode if:**
- Solo developer with local-only tracking
- Working in git worktrees (use --no-daemon)
- Running one-off commands/scripts
- Debugging database issues

**Local-only users:** Direct mode is perfectly fine. Daemon mainly helps with git sync automation. You can use `bd sync` manually when needed.

**Files to modify:**
- commands/daemon.md (add section after line 20)

Clear decision tree that helps users understand:
1. Daemon = git sync automation + performance
2. Local-only users don't need it
3. Direct mode is simpler for debugging
4. Both modes are valid depending on workflow

Addresses GitHub issue #349 item 3: https://github.com/steveyegge/beads/issues/349

Local-only users see daemon-related messages without understanding when they need daemon mode vs when direct mode is sufficient. Need clear decision tree in daemon.md.


Fix autoimport tests for content-hash collision scoring

## Overview
Three autoimport tests are failing after bd-cbed9619.4 because they expect behavior based on the old reference-counting collision resolution, but the system now uses deterministic content-hash scoring.

## Failing Tests
1. `TestAutoImportMultipleCollisionsRemapped` - expects local versions preserved
2. `TestAutoImportAllCollisionsRemapped` - expects local versions preserved
3. `TestAutoImportCollisionRemapMultipleFields` - expects specific collision resolution behavior

## Root Cause
These tests were written when ScoreCollisions used reference counting to determine which version to keep. Now it uses content-hash comparison (introduced in commit 2e87329), which produces different but deterministic results.

## Example
Old behavior: Issue with more references would be kept
New behavior: Issue with lexicographically lower content hash is kept

## Solution
Update each test to:
1. Verify the new content-hash based behavior is correct
2. Check that the remapped issue (not necessarily local/remote) has the expected content
3. Ensure dependencies are preserved on the correct remapped issue

## Acceptance Criteria
- All three autoimport tests pass
- Tests verify content-hash determinism (same collision always resolves the same way)
- Tests check dependency preservation on remapped issues
- Test documentation explains content-hash scoring expectations

## Files to Modify
- `cmd/bd/autoimport_collision_test.go`

## Testing
Run: `go test ./cmd/bd -run "TestAutoImport.*Collision" -v`


Improve compact/daemon/merge documentation and UX

Multiple documentation and UX issues encountered:
1. "bd compact --analyze" fails with misleading "requires SQLite storage" error when daemon is running. Needs --no-daemon or better error.
2. "bd merge" help text is outdated (refers to 3-way merge instead of issue merging).
3. Daemon mode purpose isn't clear to local-only users.
4. Compact/cleanup commands are hard to discover.

Proposed fixes:
- Fix compact+daemon interaction or error message.
- Update "bd merge" help text.
- Add "when to use daemon" section to docs.
- Add maintenance section to quickstart.


Centralize error handling patterns in storage layer

80+ instances of inconsistent error handling across sqlite.go with mix of %w, %v, and no wrapping.

Location: internal/storage/sqlite/sqlite.go (throughout)

Problem:
- Some use fmt.Errorf("op failed: %w", err) - correct wrapping
- Some use fmt.Errorf("op failed: %v", err) - loses error chain
- Some return err directly - no context
- Hard to debug production issues
- Can't distinguish error types

Solution: Create internal/storage/sqlite/errors.go:
- Define sentinel errors (ErrNotFound, ErrInvalidID, etc.)
- Create wrapDBError(op string, err error) helper
- Convert sql.ErrNoRows to ErrNotFound
- Always wrap with operation context

Impact: Lost error context; inconsistent messages; hard to debug

Effort: 5-7 hours


Extract database search logic into helper function

The logic for finding a database in a beads directory is duplicated:
- FindDatabasePath() BEADS_DIR section (beads.go:141-169)
- findDatabaseInTree() (beads.go:248-280)

Both implement the same search order:
1. Check config.json first (single source of truth)
2. Fall back to canonical beads.db
3. Search for *.db files, filtering backups and vc.db

Refactoring suggestion:
Extract to a helper function like:
  func findDatabaseInBeadsDir(beadsDir string) string

Benefits:
- Single source of truth for database search logic
- Easier to maintain and update search order
- Reduces code duplication

Related to [deleted:[deleted:[deleted:bd-e16b]]] implementation.


Week 1 task


Create tip system infrastructure for contextual hints

Implement a tip/hint system that shows helpful contextual messages after successful commands. This is different from the existing error-path "Hint:" messages - tips appear on success paths to educate users about features they might not know about.

## Implementation

Create `cmd/bd/tips.go` with:

### Core Infrastructure
```go
type Tip struct {
    ID          string
    Condition   func() bool      // Should this tip be eligible?
    Message     string
    Frequency   time.Duration    // Minimum gap between showings
    Priority    int              // Higher = shown first when eligible
    Probability float64          // 0.0 to 1.0 - chance of showing
}

func maybeShowTip(store storage.Storage) {
    if jsonOutput || quietMode {
        return // Respect output flags
    }

    tip := selectNextTip(store)
    if tip != nil {
        fmt.Fprintf(os.Stdout, "\n💡 Tip: %s\n", tip.Message)
        recordTipShown(store, tip.ID)
    }
}

func selectNextTip(store storage.Storage) *Tip {
    now := time.Now()
    var eligibleTips []Tip

    // Filter to eligible tips (condition + frequency check)
    for _, tip := range tips {
        if !tip.Condition() {
            continue
        }

        lastShown := getLastShown(store, tip.ID)
        if !lastShown.IsZero() && now.Sub(lastShown) < tip.Frequency {
            continue
        }

        eligibleTips = append(eligibleTips, tip)
    }

    if len(eligibleTips) == 0 {
        return nil
    }

    // Sort by priority (highest first)
    sort.Slice(eligibleTips, func(i, j int) bool {
        return eligibleTips[i].Priority > eligibleTips[j].Priority
    })

    // Apply probability roll (in priority order)
    for _, tip := range eligibleTips {
        if rand.Float64() < tip.Probability {
            return &tip
        }
    }

    return nil  // No tips won probability roll
}
```

### Probability Examples

```go
// High priority, high probability = shows often
{Priority: 90, Probability: 0.8}  // 80% chance when eligible

// High priority, medium probability = important but not spammy
{Priority: 100, Probability: 0.6}  // 60% chance

// Low priority, low probability = rare suggestion
{Priority: 30, Probability: 0.3}  // 30% chance
```

### Metadata Storage
Use existing metadata table to track:
- `tip_{id}_last_shown` - Timestamp of last display (RFC3339 format)
- `tip_{id}_dismissed` - User permanently dismissed (future feature)

### Integration Points
Call `maybeShowTip()` at end of:
- `bd list` - After showing issues
- `bd ready` - After showing ready work
- `bd create` - After creating issue
- `bd show` - After showing issue details

## Design Decisions
- Tips shown on stdout (informational, not errors)
- Respects `--json` and `--quiet` flags
- Frequency enforces minimum gap between showings
- Priority determines evaluation order
- Probability reduces spam (not every eligible tip shows)
- Store state in metadata table (no new files)
- Deterministic seed for testing (optional BEADS_TIP_SEED env var)

- Tip infrastructure exists in cmd/bd/tips.go
- Tips respect --json and --quiet flags
- Frequency tracking works (no spam)
- Metadata table stores tip state
- Unit tests for tip selection logic
- Documentation in code comments


bd validate - Comprehensive health check

Run all validation checks in one command.

Checks:
- Duplicates
- Orphaned dependencies
- Test pollution
- Git conflicts

Supports --fix-all for auto-repair.

Depends on bd-cbed9619.1, bd-0dcea000, bd-31aab707, bd-9826b69a.

Files: cmd/bd/validate.go (new)


Improve timestamp comparison readability in import

The timestamp comparison logic uses double-negative which can be confusing:

Current code:
if !incoming.UpdatedAt.After(existing.UpdatedAt) {
    // skip update
}

More readable:
if incoming.UpdatedAt.After(existing.UpdatedAt) {
    // perform update
} else {
    // skip (local is newer)
}

This is a minor refactor for code clarity.

Related: bd-1022
Files: internal/importer/importer.go:411, 488


Extract duplicated validation logic from CLI commands

~150 lines of identical validation logic duplicated between cmd_create.go and cmd_update.go

Duplication found:
- validateBeadFields(): 2 identical copies (50+ lines each)
- parseTimeWithDefault(): 2 identical copies (30 lines each)
- Flag definitions: 15+ duplicate registrations

Solution: Extract to shared packages:
- internal/validation/bead.go - Centralized validation
- internal/utils/time.go - Consolidate time parsing (already exists)
- cmd/bd/flags.go - Shared flag registration

Impact: Changes require touching 2+ files; high risk of inconsistency; steep learning curve

Effort: 4-6 hours


Investigate TestRoutingIntegration failure

TestRoutingIntegration/maintainer_with_SSH_remote failed during pre-commit check with "expected role maintainer, got contributor".
This occurred while running `go test -short ./...` on darwin/arm64.
The failure appears unrelated to storage/sqlite changes.
Need to investigate if this is a flaky test or environmental issue.


Add functional tests for FlushManager correctness verification

Current race detector tests only verify "no race detected" but don't verify data correctness.

Need functional tests that:
- Create real SQLite store with test data
- Mark issues dirty and trigger flush
- Verify JSONL file was updated correctly
- Test debouncing actually reduces flush count
- Verify shutdown performs final flush
- Test recovery after flush failures

Example test structure:
```go
func TestFlushManagerActuallyFlushes(t *testing.T) {
    // Setup real SQLite store in temp dir
    // Create test issue
    // Mark dirty via FlushManager
    // Wait for debounce + flush
    // Read JSONL file
    // Verify issue appears in JSONL with correct data
}
```

Related: Code review finding #3 from bd-52 race condition fix review.


Convert magic numbers to named constants in FlushManager

Several magic numbers should be named constants for clarity and maintainability:

flush_manager.go:
- Line 64: `10` (markDirtyCh buffer size)
- Line 65: `1` (timerFiredCh buffer size)
- Line 139: `30 * time.Second` (shutdown timeout)

autoflush.go:
- Line 562: `3` (flush failure threshold before warning)

Suggested constants:
```go
const (
    markDirtyBufferSize = 10  // Buffer rapid mark requests
    timerFiredBufferSize = 1  // Timer notifications coalesce
    shutdownTimeout = 30 * time.Second  // Generous for large DBs
    flushFailureThreshold = 3  // Show warning after N failures
)
```

Related: Code review finding #6 from bd-52 race condition fix review.


Fix mypy errors in beads-mcp

Running `mypy .` in `integrations/beads-mcp` reports 287 errors. These should be addressed to improve type safety and code quality.


Add database maintenance commands section to QUICKSTART.md

**Problem:**
Users don't discover `bd compact` or `bd cleanup` commands until their database grows large. These maintenance commands aren't mentioned in quickstart documentation.

Related to issue #349 item #4.

**Current state:**
docs/QUICKSTART.md ends at line 217 with "See README.md for full documentation" but has no mention of maintenance operations.

**Proposed addition:**
Add a "Database Maintenance" section after line 140 (before "Advanced: Agent Mail" section) covering:
- When database grows (many closed issues)
- How to view compaction statistics
- How to compact old issues
- How to delete closed issues
- Warning about permanence

**Example content:**
```markdown
## Database Maintenance

As your project accumulates closed issues, the database grows. Use these commands to manage size:

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

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

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

# Immediately delete closed issues (use with caution!)
bd cleanup --force
```

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

**Files to modify:**
- docs/QUICKSTART.md (add section after line 140)

Brief, actionable guidance on database maintenance.

Focus on:
1. When to do maintenance (size/age triggers)
2. Non-destructive options first (stats, analyze)
3. Clear warnings about permanence
4. Reference to bd restore for git history recovery

Addresses GitHub issue #349 item 4: https://github.com/steveyegge/beads/issues/349

Users don't discover compact/cleanup commands until database grows large. Quickstart should mention maintenance operations.


Optimize CLI test suite - eliminate redundant git init calls

Current: Each of 13 CLI tests calls git init (31s total). Solution: Use single test binary built once in init(), skip git operations where possible, or use mock filesystem.


Performance Testing Framework

Add comprehensive performance testing for beads focusing on optimization guidance and validating 10K+ database scale. Uses standard Go tooling, follows existing patterns, minimal complexity.

Components:
- Benchmark suite for critical operations at 10K-20K scale
- Fixture generator for realistic test data (epic hierarchies, cross-links)
- User diagnostics via bd doctor --perf
- Always-on profiling integration

Goals:
- Identify bottlenecks for optimization work
- Validate performance at 10K+ issue scale
- Enable users to collect diagnostics for bug reports
- Support both SQLite and JSONL import paths


Fix `bd sync` failure due to daemon auto-export timestamp skew

`bd sync` fails with false-positive "JSONL is newer than database" after daemon auto-export.
Root Cause: Daemon exports local changes to JSONL, updating its timestamp. `bd sync` sees JSONL.mtime > DB.mtime and assumes external changes, blocking export.
Proposed Fixes:
1. `bd sync` auto-imports if timestamp matches but content differs (or just auto-imports).
2. Content-based comparison instead of timestamp only.


Add .beads/README.md during 'bd init' for project documentation and promotion

When 'bd init' is run, automatically generate a .beads/README.md file that:

1. Briefly explains what Beads is (AI-native issue tracking that lives in your repo)
2. Links to the main repository: https://github.com/steveyegge/beads
3. Provides a quick reference of essential commands:
   - bd create: Create new issues
   - bd list: View all issues
   - bd update: Modify issue status/details
   - bd show: View issue details
   - bd sync: Sync with git remote
4. Highlights key benefits for AI coding agents and developers
5. Encourages developers to try it out

The README should be enthusiastic and compelling to get open source contributors excited about using Beads for their AI-assisted development workflows.


Investigate performance issues in VS Code Copilot (Windows)

Beads unusable in Windows 11 VS Code Copilot chat with Sonnet 4.5.
Summary event happens every 3-4 turns, taking 3 minutes.
Copilot summarizes after ~125k tokens despite model supporting 1M.
Large context size of beads might be triggering aggressive summarization.
Need workaround or optimization for context size.


Fix Homebrew warning about Ruby file location

Homebrew warning: Found Ruby file outside steveyegge/beads tap formula directory.
Warning points to: /opt/homebrew/Library/Taps/steveyegge/homebrew-beads/bd.rb
It should likely be inside a Formula/ directory or similar structure expected by Homebrew taps.


Enhance `bd doctor` to verify Claude Code integration

Add checks to `bd doctor` that verify Claude Code integration is properly set up when .claude/ directory or Claude environment is detected.

## Checks to Add

### 1. Claude Environment Detection
```go
if isClaudeDetected() {
    fmt.Println("✓ Claude Code environment detected")

    // Check what's installed
    hasMCP := isMCPServerInstalled()
    hasHooks := isClaudeSetupComplete()

    if hasMCP && hasHooks {
        fmt.Println("✓ MCP server installed")
        fmt.Println("✓ Claude hooks installed (provides workflow reminders)")
    } else if !hasMCP && hasHooks {
        fmt.Println("✓ Claude hooks installed (provides CLI reference)")
        fmt.Println("  Note: MCP server not detected (using CLI mode)")
    } else if hasMCP && !hasHooks {
        fmt.Println("✓ MCP server installed")
        fmt.Println("⚠ Claude hooks not installed")
        fmt.Println("  Hooks prevent agent from forgetting bd workflow after compaction")
        fmt.Println("  Run: bd setup claude")
    } else {
        fmt.Println("⚠ Claude integration not set up")
        fmt.Println("  Run: bd setup claude")
        // TODO (future): Recommend CLI approach once proven in production
        // fmt.Println("  Tip: CLI mode (without MCP) uses fewer tokens")
    }
}

func isMCPServerInstalled() bool {
    // Check ~/.claude/settings.json for beads MCP server
    home, _ := os.UserHomeDir()
    settingsPath := filepath.Join(home, ".claude/settings.json")

    data, err := os.ReadFile(settingsPath)
    if err != nil {
        return false
    }

    var settings map[string]interface{}
    if err := json.Unmarshal(data, &settings); err != nil {
        return false
    }

    // Check mcpServers section for beads
    mcpServers, ok := settings["mcpServers"].(map[string]interface{})
    if !ok {
        return false
    }

    // Look for beads server (any key containing "beads")
    for key := range mcpServers {
        if strings.Contains(strings.ToLower(key), "beads") {
            return true
        }
    }

    return false
}
```

### 2. Hook Installation Verification (MCP-Aware)

```go
func checkClaudeHooks() {
    home, _ := os.UserHomeDir()
    globalSettings := filepath.Join(home, ".claude/settings.json")
    projectSettings := ".claude/settings.local.json"

    globalHooks := hasBeadsHooks(globalSettings)
    projectHooks := hasBeadsHooks(projectSettings)

    if globalHooks {
        fmt.Println("✓ Global hooks installed")
    } else if projectHooks {
        fmt.Println("✓ Project hooks installed")
    } else {
        fmt.Println("⚠ No hooks installed")
        fmt.Println("  Run: bd setup claude")
        return
    }

    // Check if hooks will work
    if !commandExists("bd") {
        fmt.Println("⚠ 'bd' command not in PATH")
        fmt.Println("  Hooks won't work - ensure bd is installed globally")
    }
}

func hasBeadsHooks(settingsPath string) bool {
    data, err := os.ReadFile(settingsPath)
    if err != nil {
        return false
    }

    var settings map[string]interface{}
    if err := json.Unmarshal(data, &settings); err != nil {
        return false
    }

    hooks, ok := settings["hooks"].(map[string]interface{})
    if !ok {
        return false
    }

    // Check SessionStart and PreCompact for "bd prime"
    for _, event := range []string{"SessionStart", "PreCompact"} {
        eventHooks, ok := hooks[event].([]interface{})
        if !ok {
            continue
        }

        for _, hook := range eventHooks {
            hookMap, _ := hook.(map[string]interface{})
            commands, _ := hookMap["hooks"].([]interface{})
            for _, cmd := range commands {
                cmdMap, _ := cmd.(map[string]interface{})
                if cmdMap["command"] == "bd prime" {
                    return true
                }
            }
        }
    }

    return false
}
```

### 3. AGENTS.md/CLAUDE.md Reference Check
```go
// Check if documentation references bd prime
agentsContent := readFileIfExists("AGENTS.md")
claudeContent := readFileIfExists("CLAUDE.md")

if strings.Contains(agentsContent, "bd prime") || strings.Contains(claudeContent, "bd prime") {
    // Verify bd prime command exists in current version
    if !commandExists("prime") {
        fmt.Println("⚠ Documentation references 'bd prime' but command not found")
        fmt.Println("  Upgrade bd or remove references")
    } else {
        fmt.Println("✓ Documentation references match installed features")
    }
}
```

### 4. Context Priming Test
```go
// Verify bd prime actually works
cmd := exec.Command("bd", "prime")
output, err := cmd.CombinedOutput()

if err != nil {
    fmt.Println("⚠ 'bd prime' failed to execute")
    fmt.Println("  Error:", err)
} else if len(output) == 0 {
    fmt.Println("⚠ 'bd prime' produced no output")
    fmt.Println("  Expected workflow context markdown")
} else {
    // Check if output adapts to MCP mode
    hasMCP := isMCPServerInstalled()
    outputStr := string(output)

    if hasMCP && strings.Contains(outputStr, "mcp__plugin_beads_beads__") {
        fmt.Println("✓ bd prime detected MCP mode (workflow reminders)")
    } else if !hasMCP && strings.Contains(outputStr, "bd ready") {
        fmt.Println("✓ bd prime using CLI mode (full command reference)")
    } else {
        fmt.Println("⚠ bd prime output may not be adapting to environment")
    }
}
```

## Output Format Examples

### With MCP and Hooks
```
bd doctor

Database:
✓ Database found at .beads/beads.db
✓ Git hooks installed

Claude Code Integration:
✓ Claude Code environment detected
✓ MCP server installed
✓ Claude hooks installed (provides workflow reminders)
✓ bd prime detected MCP mode (workflow reminders)
✓ Documentation references match installed features

Sync Status:
✓ No sync issues detected
```

### Without MCP, With Hooks
```
bd doctor

Database:
✓ Database found at .beads/beads.db
✓ Git hooks installed

Claude Code Integration:
✓ Claude Code environment detected
✓ Claude hooks installed (provides CLI reference)
  Note: MCP server not detected (using CLI mode)
✓ bd prime using CLI mode (full command reference)

Sync Status:
✓ No sync issues detected
```

### No Integration
```
bd doctor

Database:
✓ Database found at .beads/beads.db
✓ Git hooks installed

Claude Code Integration:
✓ Claude Code environment detected
⚠ Claude integration not set up
  Run: bd setup claude

Sync Status:
✓ No sync issues detected
```

## Future Enhancement (Post-Production Validation)

Once CLI mode is proven in production, add recommendation:

```go
if isClaudeDetected() && !hasMCP && !hasHooks {
    fmt.Println("⚠ Claude integration not set up")
    fmt.Println("  Run: bd setup claude")
    fmt.Println("  Tip: CLI mode (without MCP) uses fewer tokens than MCP server")
    fmt.Println("       Both approaches work equally well - choose based on preference")
}
```

This recommendation should only be added after CLI mode with `bd prime` is validated in real-world usage.

- bd doctor checks for Claude environment
- Verifies hook installation if .claude/ exists
- Checks AGENTS.md/CLAUDE.md for bd prime references
- Detects version mismatches between docs and installed bd
- Provides actionable suggestions (bd setup claude, upgrade)
- Tests cover detection logic


Implement transaction retry logic for SQLITE_BUSY

BEGIN IMMEDIATE fails immediately on SQLITE_BUSY instead of retrying with exponential backoff.

Location: internal/storage/sqlite/sqlite.go:223-225

Problem:
- Under concurrent write load, BEGIN IMMEDIATE can fail with SQLITE_BUSY
- Current implementation fails immediately instead of retrying
- Results in spurious failures under normal concurrent usage

Solution: Implement exponential backoff retry:
- Retry up to N times (e.g., 5)
- Backoff: 10ms, 20ms, 40ms, 80ms, 160ms
- Check for context cancellation between retries
- Only retry on SQLITE_BUSY/database locked errors

Impact: Spurious failures under concurrent write load

Effort: 3 hours


Clarify .beads/.gitattributes handling in Protected Branches docs

Protected Branches docs quick start leaves untracked `.beads` directory and `.gitattributes`.
Question: Are these changes meant to be checked into the protected branch?
Need to clarify if these should be ignored or committed, or if the instructions are missing a step.


Manual task


False positive detection by Kaspersky Antivirus (Trojan)

Kaspersky Antivirus falsely detects beads (bd.exe v0.23.1) as a Trojan (PDM:Trojan.Win32.Generic) and removes it.
Event: Malicious object detected
Component: System Watcher
Object name: bd.exe


Add Claude setup tip with dynamic priority

Add a predefined tip that suggests running `bd setup claude` when Claude Code is detected but not configured. This tip should have higher priority (shown more frequently) until the setup is complete.

## Implementation

Add to tip registry in `cmd/bd/tips.go`:

```go
{
    ID: "claude_setup",
    Condition: func() bool {
        return isClaudeDetected() && !isClaudeSetupComplete()
    },
    Message: "Run 'bd setup claude' to enable automatic context recovery in Claude Code",
    Frequency: 24 * time.Hour,  // Daily minimum gap
    Priority: 100,              // Highest priority
    Probability: 0.6,           // 60% chance when eligible
}
```

## Detection Logic

```go
func isClaudeDetected() bool {
    // Check environment variables
    if os.Getenv("CLAUDE_CODE") != "" || os.Getenv("ANTHROPIC_CLI") != "" {
        return true
    }
    // Check if .claude/ directory exists
    if _, err := os.Stat(filepath.Join(os.Getenv("HOME"), ".claude")); err == nil {
        return true
    }
    return false
}

func isClaudeSetupComplete() bool {
    // Check for global installation
    home, err := os.UserHomeDir()
    if err == nil {
        _, err1 := os.Stat(filepath.Join(home, ".claude/commands/prime_beads.md"))
        _, err2 := os.Stat(filepath.Join(home, ".claude/hooks/sessionstart"))
        if err1 == nil && err2 == nil {
            return true  // Global hooks installed
        }
    }

    // Check for project installation
    _, err1 := os.Stat(".claude/commands/prime_beads.md")
    _, err2 := os.Stat(".claude/hooks/sessionstart")
    return err1 == nil && err2 == nil
}
```

## Priority and Probability Behavior

**Why 60% probability?**
- Important message (priority 100) but not critical
- Daily frequency + 60% = shows ~4 times per week
- Avoids spam while staying visible
- Balances persistence with user experience

**Comparison with other probabilities:**
- 100% probability: Shows EVERY day (annoying)
- 80% probability: Shows ~6 days per week (too frequent)
- 60% probability: Shows ~4 days per week (balanced)
- 40% probability: Shows ~3 days per week (might be missed)

**Auto-stops when setup complete:**
- Condition becomes false after `bd setup claude`
- No manual dismissal needed
- Tip naturally disappears from rotation

- Claude setup tip added to registry
- isClaudeDetected() checks environment and filesystem
- isClaudeSetupComplete() verifies hook installation
- Tip shows daily until setup complete
- Tip stops showing after setup
- Unit tests for detection functions


Update documentation for bd prime and Claude integration

Update AGENTS.md, README.md, and QUICKSTART.md to document the new `bd prime` command, `bd setup claude` command, and tip system.

## Documentation Updates

### AGENTS.md
Add new section "Context Recovery":
```markdown
## Context Recovery

### The Problem
After context compaction or clearing conversation, AI agents may forget to use Beads and revert to markdown TODOs. Claude Code hooks solve this.

### bd prime Command
The `bd prime` command outputs essential Beads workflow context in AI-optimized markdown format (~1-2k tokens).

**When to use:**
- After context compaction
- After clearing conversation
- Starting new session
- When agent seems to forget bd workflow
- Manual context refresh

**Usage:**
```bash
bd prime              # Output workflow context
```

### Automatic Integration (Recommended)

Run `bd setup claude` to install hooks that auto-refresh bd context:
- **SessionStart hook**: Loads context in new sessions
- **PreCompact hook**: Refreshes context before compaction (survives better)
- **Works with MCP**: Hooks complement MCP server (not replace)
- **Works without MCP**: bd prime provides workflow via CLI

**Why hooks matter even with MCP:**
- MCP provides native tools, but agent may forget to use them
- Hooks keep "use bd, not markdown" fresh in context
- PreCompact refreshes workflow before compaction

### MCP Server vs bd prime

**Not an either/or choice** - they solve different problems:

| Aspect | MCP Server | bd prime | Both |
|--------|-----------|----------|------|
| **Purpose** | Native bd tools | Workflow context | Best of both |
| **Tokens** | 10.5k always loaded | ~1-2k when called | 10.5k + ~2k |
| **Tool access** | Function calls | CLI via Bash | Function calls |
| **Context memory** | Can fade after compaction | Hooks keep fresh | Hooks + tools |
| **Recommended** | Heavy usage | Token optimization | Best experience |

**Setup options:**
```bash
bd setup claude           # Install hooks (works with or without MCP)
bd setup claude --local   # Per-project only
bd setup claude --remove  # Remove hooks
```
```

### README.md
Add to "Getting Started" section:
```markdown
### AI Agent Integration

**Claude Code users:** Run `bd setup claude` to install automatic context recovery hooks.

Hooks work with both MCP server and CLI approaches, preventing agents from forgetting bd workflow after compaction.

**MCP vs bd prime:**
- **With MCP server**: Hooks keep agent using bd tools (prevents markdown TODO reversion)
- **Without MCP server**: Hooks provide workflow context via `bd prime` (~1-2k tokens)
```

### QUICKSTART.md
Add section on agent integration:
```markdown
## For AI Agents

**Context loading:**
```bash
bd prime    # Load workflow context (~1-2k tokens)
```

**Automatic setup (Claude Code):**
```bash
bd setup claude    # Install hooks for automatic context recovery
```

Hooks prevent agents from forgetting bd workflow after compaction.
```

- AGENTS.md has Context Recovery section
- README.md mentions bd setup claude
- QUICKSTART.md mentions bd prime
- Examples show when to use bd prime vs MCP
- Clear comparison of trade-offs


Document CLI + hooks as recommended approach over MCP

Update documentation to position CLI + bd prime hooks as the primary recommended approach over MCP server, explaining why minimizing context matters even with large context windows (compute cost, energy, environment, latency).

## Goals

Position CLI + `bd prime` hooks as the **primary recommended approach** for AI agent integration, with MCP server as a legacy/fallback option.

Explore **hybrid mode** - if certain commands benefit from MCP (UX/DX advantages like no approval prompts), minimize MCP surface area to only those commands.

This requires production validation first - only update docs after CLI mode is proven reliable.

## Why Minimize Context (Even With Large Windows)

**Context window size ≠ free resource**

Large context windows (100k+, 200k+) don't mean we should fill them wastefully. Every token in context has real costs:

### Compute Cost
- **Processing overhead**: Larger context = more GPU/CPU cycles per request
- **Memory usage**: 10.5k tokens consume significant RAM/VRAM
- **Scaling impact**: Multiplied across all users, all sessions, all requests

### Energy & Environment
- **Electricity**: More compute = more power consumption
- **Carbon footprint**: Data centers running on grid power (not all renewable)
- **Sustainability**: Unnecessary token usage contributes to AI's environmental impact
- **Responsibility**: Efficient tools are better for the planet

### User Experience
- **Latency**: Larger context = slower processing (noticeable at 10k+ tokens)
- **Cost**: Many AI services charge per token (input + output)
- **Rate limits**: Context counts against API quotas

### Engineering Excellence
- **Efficiency**: Good engineering minimizes resource usage
- **Scalability**: Efficient tools scale better
- **Best practices**: Optimize for the common case

**The comparison:**

| Approach | Standing Context | Efficiency | User Cost | Environmental Impact |
|----------|-----------------|------------|-----------|---------------------|
| **CLI + hooks** | ~1-2k tokens | 80-90% reduction | Lower | Sustainable ✓ |
| **MCP minimal** | ~2-4k tokens | 60-80% reduction | Medium | Better ✓ |
| **MCP full** | ~10.5k tokens | Baseline | Higher | Wasteful ✗ |

**Functional equivalence:**
- CLI via Bash tool works just as well as MCP native calls
- Same features, same reliability
- No downside except initial learning curve

## Hybrid Mode: Minimal MCP Surface Area

**Philosophy:** MCP server doesn't have to expose everything.

If certain commands have legitimate UX/DX benefits from MCP (e.g., no approval prompts, cleaner syntax), we can expose ONLY those commands via MCP while using CLI for everything else.

### Potential MCP-Only Candidates (TBD)

Commands that might benefit from MCP native calls:
- `ready` - frequently checked, no side effects, approval prompt annoying
- `show` - read-only, frequently used, approval slows workflow
- `list` - read-only, no risk, approval adds friction

Commands that work fine via CLI:
- `create` - complex parameters, benefits from explicit confirmation
- `update` - state changes, good to see command explicitly
- `close` - state changes, explicit is better
- `dep` - relationships, good to see what's being linked
- `sync` - git operations, definitely want visibility

### Token Budget

**Full MCP** (current): ~10.5k tokens
- All ~20+ bd commands exposed
- All parameter schemas
- All descriptions and examples

**Minimal MCP** (proposed): ~2-4k tokens
- 3-5 high-frequency read commands only
- Simplified schemas
- Minimal descriptions
- Everything else via CLI

**Pure CLI**: ~1-2k tokens (only on SessionStart/PreCompact)
- No MCP tools loaded
- All commands via Bash

### Investigation Required

Before implementing hybrid mode, validate:

1. **Do MCP calls actually skip approval prompts?**
   - Test with Claude Code approval settings
   - Compare MCP tool calls vs Bash tool calls
   - Measure UX difference in real usage

2. **What's the actual token breakdown per command?**
   - Measure individual command schemas
   - Calculate token savings for minimal vs full

3. **Is approval prompt the only benefit?**
   - Are there other UX advantages to MCP?
   - Does native syntax actually improve experience?
   - User testing with both approaches

4. **Can we dynamically load MCP tools?**
   - Only load MCP when certain commands needed?
   - Hot-swap between CLI and MCP?
   - Probably not - MCP loads at startup

### Hybrid Mode Documentation (If Validated)

```markdown
## Choosing Your Integration Approach

Beads supports three AI agent integration approaches:

### CLI + Hooks (Recommended - Most Efficient)

**Setup:** `bd setup claude`

Uses Claude Code hooks to inject workflow context via `bd prime` command. Agent uses bd via Bash tool.

**Tokens:** ~1-2k (on SessionStart/PreCompact only)

**Pros:**
- Maximum efficiency (80-90% reduction vs full MCP)
- Lowest compute/energy usage
- Same functionality as MCP

**Cons:**
- Bash tool calls may require approval prompts
- Slightly more verbose in conversation

### Minimal MCP + Hooks (Balanced)

**Setup:** Install minimal MCP server (read-only commands) + `bd setup claude`

Exposes only high-frequency read commands via MCP (ready, show, list). Everything else via CLI.

**Tokens:** ~2-4k MCP + ~1-2k hooks

**Pros:**
- 60-80% reduction vs full MCP
- No approval prompts for common queries
- Cleaner syntax for frequent operations
- Still efficient

**Cons:**
- Requires MCP server (additional setup)
- Mixed interface (some MCP, some CLI)

### Full MCP + Hooks (Legacy)

**Setup:** Install full MCP server + `bd setup claude`

**Tokens:** ~10.5k MCP + hooks

**Pros:**
- All commands as native function calls
- Consistent interface

**Cons:**
- Highest token usage (worst for compute/energy/cost)
- Slowest processing
- Less sustainable

### Recommendation

1. **Start with CLI + hooks** - most efficient, works great
2. **Try minimal MCP** if approval prompts become annoying
3. **Avoid full MCP** - wasteful with no significant benefit
```

## Production Validation Checklist

Before making these documentation changes, validate CLI approach works reliably:

### Phase 1: Pure CLI Validation
- [ ] `bd prime` implemented and tested
- [ ] Hooks installed and working in Claude Code
- [ ] Real-world usage by at least 2-3 developers for 1+ weeks
- [ ] No significant usability issues reported
- [ ] Agent successfully uses bd via Bash tool
- [ ] Document which commands (if any) have approval prompt issues

### Phase 2: Hybrid Mode Investigation (Optional)
- [ ] Test if MCP calls skip approval prompts vs Bash calls
- [ ] Measure token cost per MCP command
- [ ] Identify minimal set of commands worth exposing via MCP
- [ ] Build minimal MCP server variant
- [ ] Validate token savings (should be 60-80% vs full MCP)
- [ ] User testing shows actual UX improvement

### Phase 3: Documentation Update
- [ ] Update based on validation results
- [ ] Include measured token counts (not estimates)
- [ ] Provide clear migration paths
- [ ] Update `bd doctor` recommendations

## Migration Guide (Optional)

For users currently using MCP:

```markdown
### Migrating from Full MCP to CLI + Hooks

Already using full MCP server? You can switch to the more efficient CLI approach:

1. Install hooks: `bd setup claude`
2. Test it works (hooks inject context, agent uses Bash tool)
3. Remove MCP server from `~/.claude/settings.json`
4. Restart Claude Code

You'll get the same functionality with 80-90% less token usage.

### Migrating to Minimal MCP (If Available)

If you find approval prompts annoying for certain commands:

1. Replace full MCP with minimal MCP in `~/.claude/settings.json`
2. Restart Claude Code
3. Verify high-frequency commands (ready, show, list) work via MCP
4. Everything else automatically uses CLI

You'll get 60-80% token reduction vs full MCP while keeping the UX benefits.
```

## Files to Update

- `README.md` - Add recommendation in AI Integration section
- `AGENTS.md` - Add "Choosing Your Integration Approach" section early
- `QUICKSTART.md` - Update AI integration section
- `docs/` - Any other AI integration docs if they exist
- `mcp-server/` - Create minimal variant if hybrid validated

## Future: Update `bd init`

Once validated, update `bd init` to:
- Default to recommending `bd setup claude` (hooks only)
- Mention minimal MCP as option for UX improvement
- Detect existing full MCP and suggest migration
- Provide token usage estimates for each approach

## MCP Server Architecture Note

**Key insight:** MCP server doesn't have to expose all bd functionality.

Current design exposes ~20+ commands (all bd subcommands). This is over-engineered.

**Better design:**
- **Minimal MCP**: 3-5 read-only commands (~2-4k tokens)
- **CLI**: Everything else via Bash tool
- **Hooks**: Context injection via `bd prime`

This achieves best of both worlds:
- Low token usage (efficient)
- No approval prompts for common queries (UX)
- Explicit visibility for state changes (safety)

If validation shows NO meaningful benefit to MCP (even minimal), skip hybrid mode entirely and recommend pure CLI.

- Documentation explains CLI + hooks as recommended approach
- Explains why context size matters (compute/energy/cost/latency)
- Token comparison table shows 80-90% reduction
- Migration guide for existing MCP users
- Only deployed AFTER production validation
- Clear that both approaches are supported


Refactor AGENTS.md to use external references

Suggestion to use external references (e.g., "ALWAYS REFER TO ./beads/prompt.md") instead of including all instructions directly within AGENTS.md.
Reasons:
1. Agents can follow external references.
2. Prevents context pollution/stuffing in AGENTS.md as more tools append instructions.


Add bd doctor --fix flag to automatically repair issues

Implement a --fix flag for bd doctor that can automatically repair detected issues.

Requirements:
- Add --fix flag to bd doctor command
- Show all fixable issues and prompt for confirmation before applying fixes
- Organize fix implementations under doctor/fix/<type_of_fix>.go
- Each fix type should have its own file (e.g., doctor/fix/hooks.go, doctor/fix/sync.go)
- Display what will be fixed and ask user to confirm (Y/n) before proceeding
- Support fixing issues like:
  - Missing or broken git hooks
  - Sync problems with remote
  - File permission issues
  - Any other auto-repairable issues doctor detects

Implementation notes:
- Maintain separation between detection (existing doctor code) and repair (new fix code)
- Each fix should be idempotent and safe to run multiple times
- Provide clear output about what was fixed
- Log any fixes that fail with actionable error messages


Channel isolation test - beads


Create deployment scripts for GCP

Automated provisioning scripts for GCP Compute Engine deployment.

Acceptance Criteria:
- Terraform/gcloud scripts
- Static IP allocation
- Firewall rules
- NGINX reverse proxy config
- TLS setup (Let's Encrypt)
- Systemd service file

File: deployment/agent-mail/gcp/


Performance Testing Documentation

Create docs/performance-testing.md documenting the performance testing framework.

Sections:
1. Overview - What the framework does, goals
2. Running Benchmarks
   - make bench command
   - Running specific benchmarks
   - Interpreting output (ns/op, allocs/op)
3. Profiling and Analysis
   - Viewing CPU profiles with pprof
   - Reading flamegraphs
   - Memory profiling
   - Finding hotspots
4. User Diagnostics
   - bd doctor --perf usage
   - Sharing profiles with bug reports
   - Understanding the report output
5. Comparing Performance
   - Using benchstat for before/after comparisons
   - Detecting regressions
6. Tips for Optimization
   - Common patterns
   - When to profile vs benchmark

Style:
- Concise, practical examples
- Screenshots/examples of pprof output
- Clear command-line examples
- Focus on workflow, not theory