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


Add config/metadata and comment operations to Transaction

Extend Transaction interface with config, metadata, and comment operations.

## Tasks
1. Add to Transaction interface:
   - SetConfig(ctx, key, value) error
   - GetConfig(ctx, key) (string, error)
   - SetMetadata(ctx, key, value) error
   - GetMetadata(ctx, key) (string, error)
   - AddComment(ctx, issueID, actor, comment) error

2. Implement on sqliteTxStorage:
   - Simple SQL operations using conn
   - Read-your-writes consistency within transaction

## Acceptance Criteria
- [ ] Config operations work within transaction
- [ ] Metadata operations work within transaction
- [ ] AddComment works within transaction
- [ ] Test: atomic config update with issue creation


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


SECURITY: No authorization check - any agent can deregister others

In deregister_agent (app.py:2882), there is no authorization check to verify the calling agent has permission to deregister another agent. Any agent or external caller can deregister any other agent in a project, allowing malicious or buggy agents to disrupt legitimate agents. Recommendation: Restrict to self-deregistration, add caller_agent verification, or require admin approval.


Test issue 2


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

## Implementation Complete

**Phase 1: Created staleness check (cmd/bd/staleness.go)**
- ensureDatabaseFresh() function checks JSONL mtime vs last_import_time
- Returns error with helpful message when database is stale
- Auto-skips in daemon mode (daemon has auto-import)

**Phase 2: Added to all read commands**
- list, show, ready, status, stale, info, duplicates, validate
- Check runs before database queries in direct mode
- Daemon mode already protected via checkAndAutoImportIfStale()

**Phase 3: Code Review Findings**
See follow-up issues:
- bd-XXXX: Add warning when staleness check errors
- bd-YYYY: Improve CheckStaleness error handling
- bd-ZZZZ: Refactor redundant daemon checks (low priority)

**Testing:**
- Build successful: go build ./cmd/bd
- Binary works: ./bd --version
- Ready for manual testing

**Next Steps:**
1. Test with stale database scenario
2. Implement review improvements
3. Close issue when tests pass

# Updated Analysis

## Root Cause

The bug has multiple contributing factors:

1. **Daemon mode bypasses auto-import**: When running in daemon mode (most common), the `PersistentPreRun` returns early (main.go:332) before reaching auto-import logic (main.go:451-467)

2. **No staleness validation on reads**: Read operations (list, show, search) don't verify database is fresh before returning results

3. **Auto-import can be disabled**: Users with `--no-auto-import` can unknowingly operate on stale data

## Current Auto-Import Behavior

Auto-import DOES exist and uses SHA256 hash comparison:
- Location: `autoflush.go:autoImportIfNewer()`
- Stores last import hash in DB metadata: `last_import_hash`
- Runs in `PersistentPreRun` for direct mode only
- Skipped for: import, delete, sync --dry-run commands

## Proposed Solution

Add lightweight hash-based staleness check to all read operations:

### Implementation Points:
1. **Before ANY database read** (list, show, search, ready, etc.):
   ```go
   func ensureDatabaseFresh(ctx context.Context) error {
       // Get stored import hash from DB
       storedHash, _ := store.GetMetadata(ctx, "last_import_hash")

       // Compute current JSONL hash
       currentHash := computeJSONLHash(findJSONLPath())

       if currentHash != storedHash {
           if autoImportEnabled {
               // Try auto-import
               autoImportIfNewer()
               // Re-check - fail if still stale
           } else {
               return fmt.Errorf("database out of sync with JSONL. Run 'bd import' or enable auto-import")
           }
       }
       return nil
   }
   ```

2. **Add to daemon RPC handlers** - daemon mode currently has NO staleness checking

3. **Make check fast** - hash comparison is O(1) if JSONL hash is cached

### Benefits:
- Works in both daemon and direct mode
- Minimal performance overhead (just hash comparison)
- Catches all staleness cases
- Clear error messages guide users to fix
- Defense in depth - doesn't rely solely on auto-import

### Alternatives Considered:
- **mtime comparison**: Unreliable after git operations
- **Block all reads when stale**: Too aggressive, breaks workflows
- **Only check on mutations**: Current bug - reads return stale data
- **Only rely on auto-import**: Fails in daemon mode and when disabled

## Files to Modify:
- `cmd/bd/list.go` - add check before SearchIssues
- `cmd/bd/show.go` - add check before GetIssue
- `cmd/bd/ready.go` - add check before GetReadyWork
- `internal/rpc/server.go` - add check in daemon RPC handlers
- Create `cmd/bd/staleness.go` - shared staleness check function

## Implementation Tasks

### Phase 1: Core Infrastructure
- [ ] Create `cmd/bd/staleness.go` with `ensureDatabaseFresh()` function
- [ ] Add unit tests for staleness detection
- [ ] Handle edge cases (missing JSONL, missing hash, etc.)

### Phase 2: Direct Mode Read Commands
- [ ] Add check to `cmd/bd/list.go`
- [ ] Add check to `cmd/bd/show.go`
- [ ] Add check to `cmd/bd/ready.go`
- [ ] Add check to `cmd/bd/blocked.go`
- [ ] Add check to `cmd/bd/stale.go`
- [ ] Integration tests for direct mode

### Phase 3: Daemon Mode
- [ ] Add staleness check to daemon RPC handlers in `internal/rpc/server.go`
- [ ] Ensure daemon can access JSONL path
- [ ] Integration tests for daemon mode

### Phase 4: Polish
- [ ] Performance testing (check should be <10ms)
- [ ] Error message clarity
- [ ] Documentation updates


Rename last_import_hash metadata key to jsonl_content_hash

The metadata key 'last_import_hash' is misleading because it's updated on both import AND export (sync.go:614, import.go:320).

Better names:
- jsonl_content_hash (more accurate)
- last_sync_hash (clearer intent)

This is a breaking change requiring migration of existing metadata values.


Audit remaining cmd/bd files for error handling consistency

Extend ERROR_HANDLING_AUDIT.md to cover: daemon_sync.go, update.go, list.go, show.go, close.go, reopen.go, dep.go, label.go, comments.go, delete.go, compact.go, config.go, validate.go and other high-usage command files


Auto-repair stale merge driver configs with invalid placeholders

Old bd versions (<0.24.0) installed merge driver with invalid placeholders %L %R instead of %A %B. Add detection to bd doctor --fix: check if git config merge.beads.driver contains %L or %R, auto-repair to 'bd merge %A %O %A %B'. One-time migration for users who initialized with old versions.


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.


Add test coverage for internal/git package

Git package has 1 test file. Critical package needs comprehensive testing. Target: 70% coverage

- At least 4 test files
- Package coverage >= 70%
- Tests cover git commands, error handling


Fix TestFallbackToDirectModeEnablesFlush deadlock causing 10min test timeout

## Problem

TestFallbackToDirectModeEnablesFlush in direct_mode_test.go deadlocks for 9m59s before timing out, causing the entire test suite to take 10+ minutes instead of <10 seconds.

## Root Cause

Database lock contention between test cleanup and flushToJSONL():
- Test cleanup (line 36) tries to close DB via defer
- flushToJSONL() (line 132) is still accessing DB
- Results in deadlock: database/sql.(*DB).Close() waits for mutex while GetJSONLFileHash() holds it

## Stack Trace Evidence

```
goroutine 512 [sync.Mutex.Lock, 9 minutes]:
database/sql.(*DB).Close(0x14000643790)
  .../database/sql/sql.go:927 +0x84
github.com/steveyegge/beads/cmd/bd.TestFallbackToDirectModeEnablesFlush.func1()
  .../direct_mode_test.go:36 +0xf4

While goroutine running flushToJSONL() holds DB connection via GetJSONLFileHash()
```

## Impact

- Test suite: 10+ minutes → should be <10 seconds
- ALL other tests pass in ~4 seconds
- This ONE test accounts for 99.9% of test runtime

## Related

This is the EXACT same issue documented in MAIN_TEST_REFACTOR_NOTES.md for why main_test.go refactoring was deferred - global state manipulation + DB cleanup = deadlock.

## Fix Approaches

1. **Add proper cleanup sequencing** - stop flush goroutines BEFORE closing DB
2. **Use test-specific DB lifecycle** - ensure flush completes before cleanup
3. **Mock the flush mechanism** - avoid real DB for testing this code path
4. **Add explicit timeout handling** - fail fast with clear error instead of hanging

## Files

- cmd/bd/direct_mode_test.go:36-132
- cmd/bd/autoflush.go:353 (validateJSONLIntegrity)
- cmd/bd/autoflush.go:508 (flushToJSONLWithState)

## Acceptance

- Test passes without timeout
- Test suite completes in <10 seconds
- No deadlock between cleanup and flush operations


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


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


Add test for cross-project contact with deregistered agent

Test coverage for agent deregistration is missing cross-project scenarios. Add tests for: 1) Agent A in Project X tries to contact deregistered Agent B in Project Y, 2) Agent in Project X is deregistered - verify cleanup of cross-project links.


Epic: Transaction Support for Atomic Operations

Add RunInTransaction API to enable atomic multi-operation workflows.

This epic implements transaction support in the Beads storage layer, allowing clients (like VC) to execute multiple storage operations atomically. Without this, operations like plan approval that create issues, dependencies, and labels cannot guarantee all-or-nothing semantics.

## Problem
- Each storage method manages its own transaction
- External callers cannot coordinate multiple operations atomically
- Attempting to use BeginTx externally causes deadlocks (methods try to acquire separate connections)

## Solution
Add `RunInTransaction(func(tx Transaction) error)` API where Transaction interface exposes key storage methods that execute within a single database transaction.

## Success Criteria
- WHEN multiple issues created in transaction THEN all succeed or all rollback
- WHEN transaction commits THEN all changes are durable
- WHEN transaction rolls back THEN no partial state remains
- WHEN concurrent transactions compete THEN proper serialization via IMMEDIATE mode

See bd-9dbq for detailed design notes.

Architecture:
1. Add Transaction interface to storage/storage.go
2. Add RunInTransaction to Storage interface
3. Implement sqliteTxStorage in sqlite package
4. Refactor internal helpers to accept *sql.Conn

Key design decisions:
- Use BEGIN IMMEDIATE for write lock acquisition
- Dedicated connection per transaction (prevents pool contention)
- Transaction interface mirrors Storage methods (subset)
- Panic-safe with deferred rollback


_get_agent_by_id does not check deregistration status

In app.py:2270-2281, _get_agent_by_id does not filter deregistered agents. Used in reply_to_message (line 3958) and message resource (line 7083). May leak deregistered agent info or allow operations on their behalf. Recommendation: Add include_deregistered=False parameter and audit call sites.


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.


Silent exception swallowing in deregister_agent cleanup

In app.py:3019-3020 and 3027-3028, exceptions are silently swallowed with 'pass' and no logging. This makes debugging difficult when build slot or archive operations fail. Recommendation: Add logger.warning() calls to log the errors.


Git merge driver uses invalid placeholders (%L, %R instead of %A, %B)

## Problem

The beads git merge driver is configured with invalid Git placeholders:

```
git config merge.beads.driver "bd merge %A %O %L %R"
```

Git doesn't recognize `%L` or `%R` as valid merge driver placeholders. The valid placeholders are:
- `%O` = base (common ancestor)
- `%A` = current version (ours)
- `%B` = other version (theirs)

## Impact

- Affects ALL users when they have `.beads/beads.jsonl` merge conflicts
- Automatic JSONL merge fails with error: "error reading left file: failed to open file: open 7: no such file or directory"
- Users must manually resolve conflicts instead of getting automatic merge

## Root Cause

The `bd init` command (or wherever the merge driver is configured) is using non-standard placeholders. When Git encounters `%L` and `%R`, it either passes them literally or interprets them incorrectly.

## Fix

Update the merge driver configuration to:
```
git config merge.beads.driver "bd merge %A %O %A %B"
```

Where:
- 1st `%A` = output file (current file, will be overwritten)
- `%O` = base (common ancestor)
- 2nd `%A` = left/current version
- `%B` = right/other version

## Action Items

1. Fix `bd init` (or equivalent setup command) to use correct placeholders
2. Add migration/warning for existing users with misconfigured merge driver
3. Update documentation with correct merge driver setup
4. Consider adding validation when `bd init` is run


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)


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


Add transaction support for atomic issue creation

Use Beads transaction API to create all issues atomically

Design:
Add a transaction-aware API to Beads Storage interface.

Approach 1 (Recommended): RunInTransaction wrapper
```go
// In beads/storage.go
type Storage interface {
    // ... existing methods ...

    // RunInTransaction executes fn in a transaction
    // If fn returns error, transaction is rolled back
    // If fn returns nil, transaction is committed
    RunInTransaction(ctx context.Context, fn func(tx Transaction) error) error
}

type Transaction interface {
    // Same methods as Storage, but use underlying *sql.Tx
    CreateIssue(ctx context.Context, issue *Issue, actor string) error
    AddLabel(ctx context.Context, issueID, label, actor string) error
    AddDependency(ctx context.Context, dep *Dependency, actor string) error
    UpdateIssue(ctx context.Context, id string, updates map[string]interface{}, actor string) error
    // ... etc
}
```

Implementation in sqlite/sqlite.go:
```go
func (s *SQLiteStorage) RunInTransaction(ctx context.Context, fn func(tx Transaction) error) error {
    tx, err := s.db.BeginTx(ctx, nil)
    if err != nil {
        return err
    }
    defer tx.Rollback() // Safe to call even after commit

    txStorage := &transactionStorage{tx: tx, storage: s}
    if err := fn(txStorage); err != nil {
        return err
    }

    return tx.Commit()
}

type transactionStorage struct {
    tx *sql.Tx
    storage *SQLiteStorage
}

func (t *transactionStorage) CreateIssue(ctx context.Context, issue *Issue, actor string) error {
    // Same logic as storage.CreateIssue but use t.tx instead of s.db
    // ...
}
```

Approach 2 (Alternative): Optional tx parameter
```go
// More invasive - requires changing all method signatures
CreateIssue(ctx context.Context, issue *Issue, actor string, tx ...*sql.Tx) error
```

Prefer Approach 1 - cleaner API and explicit transaction scope.

Notes:
Context from VC implementation (vc-apx8):

The VC plan approval code (internal/planning/approval.go) needs to create multiple issues atomically:
1. Phase issues (chores)
2. Task issues
3. Dependencies between them
4. Labels
5. Mission metadata updates
6. Plan deletion

Current problem:
- Each operation uses storage methods that get their own DB connections
- Starting a transaction (db.BeginTx) and then calling storage methods causes deadlock
- Storage methods try to acquire connections while transaction holds a lock

What Beads needs:
1. A transaction-aware API, either:
   - RunInTransaction(func(tx) error) pattern (preferred)
   - OR: All storage methods accept optional *sql.Tx parameter

2. Example usage:
   err := store.RunInTransaction(ctx, func(tx Transaction) error {
       // All operations use tx instead of separate connections
       issue := &Issue{...}
       if err := tx.CreateIssue(ctx, issue, actor); err != nil {
           return err // Triggers rollback
       }
       if err := tx.AddLabel(ctx, issue.ID, "label", actor); err != nil {
           return err // Triggers rollback
       }
       return nil // Triggers commit
   })

3. The Transaction interface should expose same methods as Storage:
   - CreateIssue
   - AddLabel
   - AddDependency
   - UpdateMission
   - DeletePlan
   - etc.

Reference implementation:
- See internal/storage/beads/wrapper.go for existing transaction examples
- Lines 146, 236, 305 show BeginTx usage for migrations
- But these are DDL operations, not issue CRUD

Acceptance Criteria:
- WHEN creating issues in transaction THEN all succeed or all rollback
- WHEN transaction commits THEN all issues exist in Beads
- WHEN transaction rolls back THEN no issues exist


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


Command Set Standardization & Flag Consistency

Comprehensive improvements to bd command set based on 2025 audit findings.

## Background
See docs/command-audit-2025.md for detailed analysis.

## Goals
1. Standardize flag naming and behavior across all commands
2. Add missing flags for feature parity
3. Fix naming confusion
4. Improve consistency in JSON output

## Success Criteria
- All mutating commands support --dry-run (no --preview variants)
- bd update supports label operations
- bd search has filter parity with bd list
- Priority flags accept both int and P0-P4 format everywhere
- JSON output is consistent across all commands


Add global verbosity flags (--verbose, --quiet)

Add consistent verbosity controls across all commands.

**Current state:**
- bd init has --quiet flag
- No other commands have verbosity controls
- Debug output controlled by BD_VERBOSE env var

**Proposal:**
Add persistent flags:
- --verbose / -v: Enable debug output
- --quiet / -q: Suppress non-essential output

**Implementation:**
- Add to rootCmd.PersistentFlags()
- Replace BD_VERBOSE checks with flag checks
- Standardize output levels:
  * Quiet: Errors only
  * Normal: Errors + success messages
  * Verbose: Errors + success + debug info

**Files to modify:**
- cmd/bd/main.go (add flags)
- internal/debug/debug.go (respect flags)
- Update all commands to respect quiet mode

**Testing:**
- Verify --verbose shows debug output
- Verify --quiet suppresses normal output
- Ensure errors always show regardless of mode


Add date and priority filters to bd search

Add filter parity with bd list for consistent querying.

**Missing filters to add:**
- --priority, --priority-min, --priority-max
- --created-after, --created-before
- --updated-after, --updated-before
- --closed-after, --closed-before
- --empty-description, --no-assignee, --no-labels
- --desc-contains, --notes-contains

**Files to modify:**
- cmd/bd/search.go
- internal/rpc/protocol.go (SearchArgs)
- internal/storage/storage.go (Search method)

**Testing:**
- All filter combinations
- Date format parsing
- Daemon and direct mode


Add comprehensive filters to bd export

Enhance bd export with filtering options for selective exports.

**Currently only has:**
- --status

**Add filters:**
- --label, --label-any
- --assignee
- --type
- --priority, --priority-min, --priority-max
- --created-after, --created-before
- --updated-after, --updated-before

**Use case:**
- Export only open issues: bd export --status open
- Export high-priority bugs: bd export --type bug --priority-max 1
- Export recent issues: bd export --created-after 2025-01-01

**Files to modify:**
- cmd/bd/export.go
- Reuse filter logic from list.go


Audit and standardize JSON output across all commands

Ensure consistent JSON format and error handling when --json flag is used.

**Scope:**
1. Verify all commands respect --json flag
2. Standardize success response format
3. Standardize error response format
4. Document JSON schemas

**Commands to audit:**
- Core CRUD: create, update, delete, show, list, search ✓
- Queries: ready, blocked, stale, count, stats, status
- Deps: dep add/remove/tree/cycles
- Labels: label commands
- Comments: comments add/list/delete
- Epics: epic status/close-eligible
- Export/import: already support --json ✓

**Testing:**
- Success cases return valid JSON
- Error cases return valid JSON (not plain text)
- Consistent field naming (snake_case vs camelCase)
- Array vs object wrapping consistency


Improve clean vs cleanup command naming/documentation

Clarify the difference between bd clean and bd cleanup to reduce user confusion.

**Current state:**
- bd clean: Remove temporary artifacts (.beads/bd.sock, logs, etc.)
- bd cleanup: Delete old closed issues from database

**Options:**
1. Rename for clarity:
   - bd clean → bd clean-temp
   - bd cleanup → bd cleanup-issues

2. Keep names but improve help text and documentation

3. Add prominent warnings in help output

**Preferred approach:** Option 2 (improve documentation)
- Update short/long descriptions in commands
- Add examples to help text
- Update README.md
- Add cross-references in help output

**Files to modify:**
- cmd/bd/clean.go
- cmd/bd/cleanup.go
- README.md or ADVANCED.md


Review and document rarely-used commands

Document use cases or consider deprecation for infrequently-used commands.

**Commands to review:**
1. bd rename-prefix - How often is this used? Document use cases
2. bd detect-pollution - Consider integrating into bd validate
3. bd migrate-hash-ids - One-time migration, keep but document as legacy

**For each command:**
- Document typical use cases
- Add examples to help text
- Consider if it should be a subcommand instead
- Add deprecation warning if appropriate

**Not changing:**
- duplicates ✓ (useful for data quality)
- repair-deps ✓ (useful for fixing broken refs)
- restore ✓ (critical for compacted issues)
- compact ✓ (performance feature)

**Deliverable:**
- Updated help text
- Documentation in ADVANCED.md
- Deprecation plan if needed


Race condition: double commit in deregister_agent

In app.py:2958-2994, deregister_agent commits twice within the same session: line 2962 after setting deregistered_ts, and line 2994 after cleanup operations. If second operation fails, agent is marked deregistered but cleanup is incomplete. Fix: Use single transaction or handle partial failure explicitly.


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.


Default to YES for git hooks and merge driver installation

Currently bd init prompts user to install git hooks and merge driver, but setup is incomplete if user declines. Change to install by default unless --skip-hooks or --skip-merge-driver flags are passed. Better safe defaults. If installation fails, warn user and suggest bd doctor --fix.


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:[deleted:[deleted:[deleted:[deleted:[deleted:[deleted:[deleted:[deleted:bd-e16b]]]]]]]]]]] implementation.


Refactor: Move staleness check inside daemon branch

## Problem

Currently ensureDatabaseFresh() is called before the daemon mode check, but it checks daemonClient != nil internally and returns early. This is redundant.

**Location:** All read commands (list.go:196, show.go:27, ready.go:102, status.go:80, etc.)

## Current Pattern

Call happens before daemon check, function checks daemonClient internally.

## Better Pattern

Move staleness check to direct mode branch only, after daemon check.

## Impact
Low - minor performance improvement (avoids one function call per command in daemon mode)

## Effort
Medium - requires refactoring 8 command files

## Priority
Low - can defer to future cleanup PR


Week 1 task


Improve CheckStaleness error handling

## Problem

CheckStaleness returns 'false' (not stale) for multiple error conditions instead of returning errors. This masks problems.

**Location:** internal/autoimport/autoimport.go:253-285

## Edge Cases That Return False

1. **Invalid last_import_time format** (line 259-262)
   - Corrupted metadata returns 'not stale'
   - Could show stale data

2. **No JSONL file found** (line 267-277)
   - If glob fails, falls back to 'issues.jsonl'
   - If that's empty, returns 'not stale'

3. **JSONL stat fails** (line 279-282)
   - Permission denied, file missing
   - Returns 'not stale' even though can't verify

## Current Code

```go
lastImportTime, err := time.Parse(time.RFC3339, lastImportStr)
if err \!= nil {
    return false, nil  // ← Should return error
}

// ...

if jsonlPath == "" {
    return false, nil  // ← Should return error
}

stat, err := os.Stat(jsonlPath)
if err \!= nil {
    return false, nil  // ← Should return error
}
```

## Fix

```go
lastImportTime, err := time.Parse(time.RFC3339, lastImportStr)
if err \!= nil {
    return false, fmt.Errorf("corrupted last_import_time: %w", err)
}

// ...

if jsonlPath == "" {
    return false, fmt.Errorf("no JSONL file found")
}

stat, err := os.Stat(jsonlPath)
if err \!= nil {
    return false, fmt.Errorf("cannot stat JSONL: %w", err)
}
```

## Impact
Medium - edge cases are rare but should be handled

## Effort
30 minutes - requires updating callers in RPC server

## Dependencies
Requires: bd-n4td (warning on errors)


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)


Add test coverage for internal/autoimport package

The autoimport package has only 1 test file. Need comprehensive tests. Target: 70% coverage

- At least 3 test files
- Package coverage >= 70%
- Tests cover main functionality, error paths, edge cases


Add security tests for WriteFile permissions in doctor command

Test coverage gap identified by automated analysis (vc-217).

**Original Issue:** [deleted:[deleted:[deleted:[deleted:bd-da96-baseline-lint]]]]

In cmd/bd/doctor/gitignore.go:98, os.WriteFile uses 0644 permissions, flagged by gosec G306 as potentially too permissive.

Add tests to verify:
- File is created with appropriate permissions (0600 or less)
- Existing file permissions are not loosened
- File ownership is correct
- Sensitive data handling if .gitignore contains secrets

This ensures .gitignore files are created with secure permissions to prevent unauthorized access.

_This issue was automatically created by AI test coverage analysis._


No database index on Agent.deregistered_ts field

In models.py:58, deregistered_ts field has no index. Every agent query now filters on this field, which will slow down as the agents table grows. Fix: Add index=True to the field definition.


Improve Beads test coverage from 46% to 80%

Currently at 46% test coverage. Need to systematically improve coverage across all subsystems, focusing first on packages with minimal or no tests.

Target: 80% overall coverage

Approach:
- Break down by subsystem (internal/* packages)
- Prioritize packages with 0-1 test files
- Each child issue targets specific coverage goals
- Focus on unit tests for core logic, error paths, and edge cases

This epic will be executed by the VC executor to test its ability to handle sustained multi-issue work.

- Overall test coverage reaches 80% or higher
- All internal/* packages have at least 60% coverage
- All packages with only 1 test file now have at least 3 test files
- Quality gates (go test, golangci-lint) pass
- Tests are maintainable and test actual behavior, not implementation details


Implement health checks in daemon event loop

Add health checks to checkDaemonHealth() function in daemon_event_loop.go:170:
- Database integrity check
- Disk space check
- Memory usage check

Currently it's just a no-op placeholder.


Implement auto-merge functionality in duplicates command

The duplicates.go file has a TODO at line 95 to implement the performMerge function for automatic duplicate merging. Currently it just prints a warning message. This would automate the merge process instead of just suggesting commands.


Add --body-file flag to bd create for reading descriptions from files

## Problem

Creating issues with long/complex descriptions via CLI requires shell escaping gymnastics:

```bash
# Current workaround - awkward heredoc quoting
bd create --title="..." --description="$(cat <<'EOF'
...markdown...
EOF
)"

# Often fails with quote escaping errors in eval context
# Agents resort to writing temp files then reading them
```

## Proposed Solution

Add `--body-file` and `--description-file` flags to read description from a file, matching `gh` CLI pattern.

```bash
# Natural pattern that aligns with training data
cat > /tmp/desc.md << 'EOF'
...markdown content...
EOF

bd create --title="..." --body-file=/tmp/desc.md
```

## Implementation

### 1. Add new flags to `bd create`

```go
createCmd.Flags().String("body-file", "", "Read description from file (use - for stdin)")
createCmd.Flags().String("description-file", "", "Alias for --body-file")
```

### 2. Flag precedence

- If `--body-file` or `--description-file` is provided, read from file
- If value is `-`, read from stdin
- Otherwise fall back to `--body` or `--description` flag
- If neither provided, description is empty (current behavior)

### 3. Error handling

- File doesn't exist → clear error message
- File not readable → clear error message
- stdin specified but not available → clear error message

## Benefits

✅ **Matches training data**: `gh issue create --body-file file.txt` is a common pattern
✅ **No shell escaping issues**: File content is read directly
✅ **Works with any content**: Markdown, special characters, quotes, etc.
✅ **Agent-friendly**: Agents already write complex content to temp files
✅ **User-friendly**: Easier for humans too when pasting long descriptions

## Related Commands

Consider adding similar support to:
- `bd update --body-file` (for updating descriptions)
- `bd comment --body-file` (if/when we add comments)

## Examples

```bash
# From file
bd create --title="Add new feature" --body-file=feature.md

# From stdin
echo "Quick description" | bd create --title="Bug fix" --body-file=-

# With other flags
bd create \
  --title="Security issue" \
  --type=bug \
  --priority=0 \
  --body-file=security-report.md \
  --label=security
```

## Testing

- Test with normal files
- Test with stdin (`-`)
- Test with non-existent files (error handling)
- Test with binary files (should handle gracefully)
- Test with empty files (valid - empty description)
- Test that `--description-file` and `--body-file` are equivalent aliases


Audit and fix JSONL filename mismatches across all repo clones

## Problem

Multiple clones of repos are configured with different JSONL filenames (issues.jsonl vs beads.jsonl), causing:
1. JSONL files to be resurrected after deletion (one clone pushes issues.jsonl, another pushes beads.jsonl)
2. Agents unable to see issues filed by other agents after sync
3. Merge conflicts and data inconsistencies

## Root Cause

When repos were "bd doctored" or initialized at different times, some got issues.jsonl (old default) and others got beads.jsonl (Beads repo specific). These clones push their respective files, creating duplicates.

## Task

Scan all repo clones under ~/src/ (1-2 levels deep) and standardize their JSONL configuration.

### Step 1: Find all beads-enabled repos

```bash
# Find all directories named 'beads' at levels 1-2 under ~/src/
find ~/src -maxdepth 2 -type d -name beads
```

### Step 2: For each repo found, check configuration

For each directory from Step 1, check:
- Does `.beads/metadata.json` exist?
- What is the `jsonl_export` value?
- What JSONL files actually exist in `.beads/`?
- Are there multiple JSONL files (problem!)?

### Step 3: Create audit report

Generate a report showing:
```
Repo Path                           | Config        | Actual Files           | Status
----------------------------------- | ------------- | ---------------------- | --------
~/src/beads                         | beads.jsonl   | beads.jsonl            | OK
~/src/dave/beads                    | issues.jsonl  | issues.jsonl           | MISMATCH
~/src/emma/beads                    | issues.jsonl  | issues.jsonl, beads.jsonl | DUPLICATE!
```

### Step 4: Determine canonical name for each repo

For repos that are the SAME git repository (check `git remote -v`):
- Group them together
- Determine which JSONL filename should be canonical (majority wins, or beads.jsonl for the beads repo itself)
- List which clones need to be updated

### Step 5: Generate fix script

Create a script that for each mismatched clone:
1. Updates `.beads/metadata.json` to use the canonical name
2. If JSONL file needs renaming: `git mv .beads/old.jsonl .beads/new.jsonl`
3. Removes any duplicate JSONL files: `git rm .beads/duplicate.jsonl`
4. Commits the change
5. Syncs: `bd sync`

### Expected Output

1. Audit report showing all repos and their config status
2. List of repos grouped by git remote (same repository)
3. Fix script or manual instructions for standardizing each repo
4. Verification that after fixes, all clones of the same repo use the same JSONL filename

### Edge Cases

- Handle repos without metadata.json (use default discovery)
- Handle repos with no git remote (standalone/local)
- Handle repos that are not git repositories
- Don't modify repos with uncommitted changes (warn instead)

### Success Criteria

- All clones of the same git repository use the same JSONL filename
- No duplicate JSONL files in any repo
- All configurations documented in metadata.json
- bd doctor passes on all repos


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.


Auto-migrate database on CLI version bump

When CLI is upgraded (e.g., 0.24.0 → 0.24.1), database version becomes stale. Add auto-migration in PersistentPreRun or daemon startup. Check dbVersion != CLIVersion and run bd migrate automatically. Fixes recurring UX issue where bd doctor shows version mismatch after every CLI upgrade.


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


Add test coverage for internal/validation package

Validation package has 1 test file. Critical for data integrity. Target: 80% coverage

- At least 4 test files
- Package coverage >= 80%
- Tests cover all validation rules


Add transaction support for atomic multi-operation workflows

Add a transaction-aware API to the Beads Storage interface to support atomic multi-operation workflows. Context from VC project: The VC plan approval code needs to create multiple issues atomically (phases, tasks, dependencies, labels, metadata updates). Currently each storage operation gets its own DB connection making transactions impossible. When approving a mission plan we need to atomically: create 5-10 phase issues, create 20-30 task issues, add dependencies between them, apply labels to all issues, update mission metadata, delete ephemeral plan. If ANY step fails ALL changes should rollback.

Add RunInTransaction wrapper to Storage interface. Create Transaction interface with same methods as Storage but using underlying sql.Tx. Implementation creates transactionStorage struct that wraps tx and uses tx.ExecContext instead of db.ExecContext for all operations.

WHEN calling RunInTransaction THEN all operations use same transaction. WHEN transaction function returns nil THEN transaction is committed. WHEN transaction function returns error THEN transaction is rolled back. WHEN transaction commits THEN all changes are visible. WHEN transaction rolls back THEN no changes are visible.


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.


Add test for concurrent deregistration race condition

No test verifies behavior when two concurrent deregistration calls race. Add a test that calls deregister_agent twice concurrently to verify idempotency holds under race conditions.


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.


Add SearchIssues to Transaction for read-your-writes

Add search capability within transaction for read-your-writes consistency.

## Tasks
1. Add to Transaction interface:
   - SearchIssues(ctx, query, filter) ([]*types.Issue, error)

2. Implement on sqliteTxStorage:
   - Reuse existing search logic with conn
   - Ensure reads see uncommitted writes within same transaction

## Acceptance Criteria
- [ ] SearchIssues returns issues created in same transaction
- [ ] Filter logic works correctly within transaction
- [ ] Test: create issue then search for it in same transaction


Build slot cleanup uses synchronous file I/O in async function

In app.py:2996-3020, deregister_agent uses synchronous file I/O (iterdir, glob, read_text, write_text) in an async function. This can cause latency spikes with many build slot files. Recommendation: Use anyio or aiofiles for async file operations, or run in thread pool.


Add warning when staleness check errors

## Problem

When ensureDatabaseFresh() calls CheckStaleness() and it errors (corrupted metadata, permission issues, etc.), we silently proceed with potentially stale data.

**Location:** cmd/bd/staleness.go:27-32

**Scenarios:**
- Corrupted metadata table
- Database locked by another process
- Permission issues reading JSONL file
- Invalid last_import_time format in DB

## Current Code

```go
isStale, err := autoimport.CheckStaleness(ctx, store, dbPath)
if err \!= nil {
    // If we can't determine staleness, allow operation to proceed
    // (better to show potentially stale data than block user)
    return nil
}
```

## Fix

```go
isStale, err := autoimport.CheckStaleness(ctx, store, dbPath)
if err \!= nil {
    fmt.Fprintf(os.Stderr, "Warning: Could not verify database freshness: %v\n", err)
    fmt.Fprintf(os.Stderr, "Proceeding anyway. Data may be stale.\n\n")
    return nil
}
```

## Impact
Medium - users should know when staleness check fails

## Effort
Easy - 5 minutes


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.


Improve CheckStaleness error handling

## Problem

CheckStaleness returns 'false' (not stale) for multiple error conditions instead of returning errors. This masks problems.

**Location:** internal/autoimport/autoimport.go:253-285

## Edge Cases That Return False

1. **Invalid last_import_time format** (line 259-262)
2. **No JSONL file found** (line 267-277)
3. **JSONL stat fails** (line 279-282)

## Fix

Return errors for abnormal conditions:

```go
lastImportTime, err := time.Parse(time.RFC3339, lastImportStr)
if err != nil {
    return false, fmt.Errorf("corrupted last_import_time: %w", err)
}

if jsonlPath == "" {
    return false, fmt.Errorf("no JSONL file found")
}

stat, err := os.Stat(jsonlPath)
if err != nil {
    return false, fmt.Errorf("cannot stat JSONL: %w", err)
}
```

## Impact
Medium - edge cases are rare but should be handled

## Effort
30 minutes - requires updating callers in RPC server


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


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.


resource://project/{slug} does not filter deregistered agents

In app.py:6859, the project_resource retrieves ALL agents without filtering deregistered ones, while resource://agents/{project_key} correctly filters at line 6921-6923. This causes inconsistent behavior between discovery endpoints. Fix: Add Agent.deregistered_ts.is_(None) filter to line 6859.


Manual task


Consider extracting error handling helpers

Evaluate creating FatalError() and WarnError() helpers as suggested in ERROR_HANDLING.md to reduce boilerplate and enforce consistency. Prototype in a few files first to validate the approach.


Block version bumps/releases when CI is failing

The bump-version.sh script and release process should verify that CI is passing before creating version tags and releases.

## Problem
Currently we can cut releases even when CI tests are failing, which could ship broken code to users.

## Proposed Solution
Add a CI status check to:
1. scripts/bump-version.sh - Check CI status before tagging
2. Potentially add a GitHub branch protection rule requiring CI to pass before tags can be pushed

## Implementation Ideas
- Use `gh run list --branch main --limit 1` to check latest CI status
- Add `--force` flag to override the check if needed
- Consider GitHub Actions workflow that validates CI before release

## Benefits
- Prevents shipping broken releases
- Catches test failures before they reach users
- Maintains quality standards in distribution channels


Add test coverage for internal/config package

Config package has 1 test file. Need comprehensive tests. Target: 70% coverage

- At least 3 test files
- Package coverage >= 70%


bd init UX Improvements

bd init leaves users with incomplete setup, requiring manual bd doctor --fix. Issues found: (1) git hooks not installed if user declines prompt, (2) no auto-migration when CLI is upgraded, (3) stale merge driver configs from old versions. Fix by making bd init more robust with better defaults and auto-migration.


Consider adding preserve_metadata option on agent reactivation

Currently reactivation always overwrites agent metadata (program, model, task_description). Some use cases might prefer preserving original inception_ts or other historical data. Suggestion: Add preserve_metadata: bool = False parameter for flexibility.


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


Test label update feature


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


String-based error detection for deregistered agents is fragile

In app.py:4192-4194, the code checks 'if "deregistered" in str(exc).lower()' to detect deregistered agent errors. This relies on error message text which is fragile. Recommendation: Create custom AgentDeregisteredException that inherits from NoResultFound, or add structured attribute to exception.


Code Review Sweep: thorough

Perform thorough code review sweep based on accumulated activity.

**AI Reasoning:**
Significant code activity with 7608 lines added and 120 files changed indicates substantial modifications. Multiple high-churn areas (cmd/bd, internal/rpc) suggest potential for subtle issues and emerging patterns that warrant review.

**Scope:** thorough
**Target Areas:** cmd/bd, internal/rpc, .beads
**Estimated Files:** 12
**Estimated Cost:** $5

**Task:**
Review files for non-obvious issues that agents miss during focused work:
- Inefficiencies (algorithmic, resource usage)
- Subtle bugs (race conditions, off-by-one, copy-paste)
- Poor patterns (coupling, complexity, duplication)
- Missing best practices (error handling, docs, tests)
- Unnamed anti-patterns

File discovered issues with detailed reasoning and suggestions.

- Reviewed target files for code quality issues
- Filed discovered issues with detailed reasoning
- Completed sweep according to scope criteria

code-review-sweep review-area:.beads review-area:cmd/bd review-area:internal/rpc


Consider adding purge_data option for GDPR-style deletion

delete_inbox=False is a safe default, but leaves orphaned data. Consider adding purge_data: bool = False parameter that deletes all associated data (inbox, sent messages, etc.) for GDPR-style 'right to be forgotten' scenarios.


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.


troubleshoot GH#278 daemon exits every few secs


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

Resetting stale in_progress status from old executor run (13 days old)


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


Run bd doctor at end of bd init to verify setup

Run bd doctor diagnostics at end of bd init (after line 398 in init.go). If issues found, warn user immediately: '⚠ Setup incomplete. Run bd doctor --fix to complete setup.' Catches configuration problems before user encounters them in normal workflow.