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


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


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.


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


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


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


Fix Nix flake: stale vendorHash and version

The Nix flake in default.nix has:
1. version = "0.9.9" (should track current release version)
2. vendorHash needs regeneration after dependency updates

This causes 'Test Nix Flake' CI to fail consistently.

To fix:
1. Update version to 0.24.4
2. Run 'nix build' and copy the correct vendorHash from the error message
3. Update vendorHash in default.nix


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


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


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


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


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.


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


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.


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)


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


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.


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


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


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.


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%


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.


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.


troubleshoot GH#278 daemon exits every few secs


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