Add --lock-timeout global flag

Add new global flag to control SQLite busy_timeout.

## Implementation
1. Add to cmd/bd/main.go:
   - `lockTimeout time.Duration` global variable
   - Register flag: `--lock-timeout=<duration>` (default 30s)

2. Add config support in internal/config/config.go:
   - `v.SetDefault("lock-timeout", "30s")`
   - Read from config.yaml if not set via flag

3. Pass timeout to sqlite.New() - see next task

## Acceptance Criteria
- `bd --lock-timeout=0 list` fails immediately if DB is locked
- `bd --lock-timeout=100ms list` waits max 100ms
- Config file setting works: `lock-timeout: 100ms`
- Default remains 30s for backward compatibility

Part of bd-olc1


Use external_ref as primary matching key for import updates

Enable re-syncing from external systems (Jira, GitHub, Linear) by using external_ref as the primary matching key during imports. Currently imports treat any content change as a collision, making it impossible to sync updates from external systems without creating duplicates.

See GH #142 for detailed proposal and implementation plan.

Key changes needed:
1. Add findByExternalRef() query function
2. Update DetectCollisions() to match by external_ref first
3. Update import_shared.go to update existing issues when external_ref matches
4. Add index on external_ref for performance
5. Preserve local issues (no external_ref) from being overwritten

This enables hybrid workflows: import external backlog, break down with local tasks, re-sync anytime.

## Code Review Complete ✅

**Overall Assessment**: EXCELLENT - Production ready

### Implementation Quality
- ✓ Clean architecture with proper interface extension
- ✓ Dual backend support (SQLite + Memory)
- ✓ Smart matching priority: external_ref → ID → content hash
- ✓ O(1) lookups with database index
- ✓ Timestamp-based conflict resolution
- ✓ Comprehensive test coverage (11 test cases)

### Follow-up Issues Filed
High Priority (P2):
- bd-897a: Add UNIQUE constraint on external_ref column
- bd-7315: Add validation for duplicate external_ref in batch imports

Medium Priority (P3):
- bd-f9a1: Add index usage verification test
- bd-3f6a: Add concurrent import race condition tests

Low Priority (P4):
- bd-e166: Improve timestamp comparison readability
- bd-9e23: Optimize Memory backend with index
- bd-537e: Add external_ref change tracking
- bd-df11: Add import metrics
- bd-9f4a: Document external_ref in content hash

### Key Features
✅ External systems (Jira, GitHub, Linear) can re-sync without duplicates
✅ Hybrid workflows: import external backlog, add local tasks, re-sync anytime
✅ Local issues protected from being overwritten
✅ Timestamp checking ensures only newer updates applied
✅ Performance optimized with database index

**Confidence Level**: 95% - Ship it! 🚀


Test all core bd commands in WASM for feature parity

Comprehensive testing of bd-wasm against native bd:
- Test all CRUD operations (create, update, show, close)
- Test dependency management (dep add, dep tree)
- Test sync operations (sync, import, export)
- Verify JSONL output matches native bd
- Run existing Go test suite in WASM if possible
- Benchmark performance (should be within 2x of native)


Feature with design

This is a description


Issue with labels

This is a description


GH#497: bd onboard copilot-instructions.md is beads-specific, not generic

bd onboard outputs beads repo specific content (Go/SQLite/Cobra) for copilot-instructions.md instead of a generic template. AGENTS.md output is correct. See: https://github.com/steveyegge/beads/issues/497


Respond to GitHub issue #479 with solution

Once bd reset is implemented and released, respond to GitHub issue #479.

## Response should include
- Announce the new bd reset command
- Show basic usage examples
- Link to any documentation
- Thank the user for the feedback

## Example response
```
Thanks for raising this! We've added a `bd reset` command to handle this case.

Usage:
- `bd reset` - Reset to clean state (prompts for confirmation)
- `bd reset --backup` - Create backup first
- `bd reset --hard` - Also clean up git history

This is available in version X.Y.Z.
```

## Notes
- Wait until feature is merged and released
- Consider if issue should be closed or left for user confirmation


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


Document sandbox workarounds for GH #353

Add documentation for sandbox troubleshooting and new flags.

**Tasks:**
1. Create or update TROUBLESHOOTING.md with sandbox section
2. Document new flags in CLI reference
3. Add comment to GH #353 with immediate workarounds

**Content needed:**
- Symptoms of daemon lock issues in sandboxed environments
- Usage guide for --sandbox, --force, and --allow-stale flags
- Step-by-step troubleshooting for Codex users
- Examples of each escape hatch

**Files to update:**
- docs/TROUBLESHOOTING.md (create if needed)
- docs/CLI_REFERENCE.md or README.md
- GitHub issue #353

**References:**
- docs/GH353_INVESTIGATION.md (lines 240-276)


Update bash-agent example with Agent Mail integration

Add Agent Mail integration to examples/bash-agent/agent.sh using curl for HTTP calls.

Acceptance Criteria:
- Health check function using curl
- Reserve issue before claiming
- Send notifications on status change
- Release on completion
- Graceful degradation if curl fails
- No bash errors when Agent Mail unavailable

File: examples/bash-agent/agent.sh


Fix TestTwoCloneCollision timeout


Repair Commands & AI-Assisted Tooling

Add specialized repair tools to reduce agent repair burden:
1. Git merge conflicts in JSONL
2. Duplicate issues from parallel work
3. Semantic inconsistencies
4. Orphaned references

See ~/src/fred/beads/repair_commands.md for full design doc.

Reduces agent repair time from 5-10 minutes to <30 seconds per repair.


Add test files for internal/storage

The internal/storage package has no test files at all. This package provides the storage interface abstraction.

Current coverage: N/A (no test files)
Target: Add basic interface tests


Graph Link: replies_to for conversation threading

Implement replies_to link type for message threading.

New command:
- bd mail reply <id> -m 'Response' creates a message with replies_to set

Query support:
- bd show <id> --thread shows full conversation thread
- Thread traversal in storage layer

Storage:
- replies_to column in issues table
- Index for efficient thread queries

This enables Reddit-style nested threads where messages reply to other messages.


Investigate and upgrade to modernc.org/sqlite 1.39.1+

We had to pin modernc.org/sqlite to v1.38.2 due to a FOREIGN KEY constraint regression in v1.39.1 (SQLite 3.50.4).

**Issue:** [deleted:bd-cb64c226.2], GH #144

**Symptom:** CloseIssue fails with "FOREIGN KEY constraint failed (787)" when called via MCP/daemon, but works fine via CLI.

**Root Cause:** Unknown - likely stricter FK enforcement in SQLite 3.50.4 or modernc.org wrapper changes.

**Workaround:** Pinned to v1.38.2 (SQLite 3.49.x)

**TODO:**
1. Monitor modernc.org/sqlite releases for fixes
2. Check SQLite 3.50.5+ changelogs for FK-related fixes
3. Investigate why daemon mode fails but CLI succeeds (connection reuse? transaction isolation?)
4. Consider filing upstream issue with reproducible test case
5. Upgrade when safe


Add edge case tests for export metadata updates

## Current Coverage
TestExportUpdatesMetadata tests basic happy path only.

## Missing Test Cases

### 1. Multi-Repo Mode
- Export with multi-repo configuration
- Verify metadata updated for ALL JSONL files
- Critical gap (related to bd-ar2.2)

### 2. computeJSONLHash Failure
- JSONL file deleted/inaccessible after export
- Should log warning, not crash
- Verify behavior on next export

### 3. SetMetadata Failures
- Database write-protected
- Disk full
- Should log warnings, continue

### 4. os.Stat Failure
- JSONL file deleted after export, before stat
- Should handle gracefully (mtime just not updated)

### 5. Concurrent Exports
- Two daemon instances export simultaneously
- Verify metadata doesn't get corrupted
- Race condition test

### 6. Clock Skew
- System time goes backward between exports
- Verify mtime handling still works

### 7. Partial Export Failure
- Multi-repo mode: some exports succeed, some fail
- What metadata should be updated?

### 8. Large JSONL Files
- Performance test with large files (10k+ issues)
- Verify hash computation doesn't timeout

## Files
- cmd/bd/daemon_sync_test.go

## Implementation Priority
1. Multi-repo test (P1 - related to critical issue)
2. Failure handling tests (P2)
3. Performance/edge cases (P3)


Audit all cmd/bd tests and group into suites

Analyze all 279 tests in cmd/bd and identify:
1. Which tests can share DB setup (most of them\!)
2. Which tests actually need isolation (export/import, git ops)
3. Optimal grouping into test suites

Create a mapping document showing:
- Current: 279 individual test functions
- Proposed: ~10-15 test suites with subtests
- Expected speedup per suite

Blocks all refactoring work.


Sync sanitize incorrectly removes newly created issues

## Problem

The sync sanitize process incorrectly identifies newly created issues as 'deleted issues resurrected by git merge' and removes them from the local JSONL file.

## Reproduction

1. Create a new issue: bd create --title='Test issue'
2. Run bd sync
3. Observe: New issue appears in sanitize removal list
4. Issue is removed from local JSONL but preserved on beads-sync branch

## Observed Behavior

During sync, the sanitize step outputs:
```
→ Sanitized JSONL: removed 738 deleted issue(s) that were resurrected by git merge
  - bd-08ea  (newly created issue!)
  - bd-tnsq  (newly created issue!)
  ...
```

The newly created issues get removed locally but remain on beads-sync branch.

## Expected Behavior

Newly created issues should NOT be removed by sanitize. The sanitize should only remove issues that:
1. Were previously deleted (have tombstones or are in deletions manifest)
2. Are being resurrected from old git history

## Root Cause Investigation

The sanitize logic likely compares the local DB snapshot against some reference and incorrectly classifies new issues as 'resurrected deleted issues'. Possible causes:
- Snapshot protection logic not accounting for new issues
- Deletion manifest containing stale entries
- Race condition between export and sanitize

## Impact

- New issues disappear from local JSONL after sync
- Issues remain on beads-sync but cause confusion
- Multi-agent workflows affected when agents can't see new issues locally
- Requires manual intervention to recover

## Files to Investigate

- cmd/bd/sync.go - sanitize logic
- cmd/bd/snapshot_manager.go - snapshot comparison
- Deletion manifest handling

## Acceptance Criteria

- [ ] Newly created issues survive sync without being sanitized
- [ ] Only truly deleted/resurrected issues are removed
- [ ] Add test case for this scenario


Test basic bd commands in WASM (init, create, list)

Compile and verify basic bd functionality works in WASM:
- Test bd init --quiet
- Test bd create with simple issue
- Test bd list --json output
- Verify SQLite database creation and queries work
- Document any runtime issues or workarounds needed


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.


bd cleanup should also prune expired tombstones

## Problem

`bd cleanup` deletes closed issues (converting them to tombstones) but does NOT prune expired tombstones. Users expect 'cleanup' to do comprehensive cleanup.

## Current Behavior

1. `bd cleanup --force` → converts closed issues to tombstones
2. Expired tombstones (>30 days) remain in issues.jsonl
3. User must separately run `bd compact` to prune tombstones
4. `bd doctor` warns about expired tombstones: 'Run bd compact to prune'

## Expected Behavior

`bd cleanup` should also prune expired tombstones from issues.jsonl.

## Impact

With v0.30.0 making tombstones the default migration path, this UX gap becomes more visible. Users cleaning up their database shouldn't need to know about a separate `bd compact` command.

## Proposed Solution

Call `pruneExpiredTombstones()` at the end of the cleanup command (same function used by compact). Report results:

```
✓ Deleted 15 closed issue(s)
✓ Pruned 3 expired tombstone(s) (older than 30 days)
```

## Files to Modify

- `cmd/bd/cleanup.go` - Add call to pruneExpiredTombstones after deleteBatch
- May need to move pruneExpiredTombstones to shared location if not already accessible

## Acceptance Criteria

- [ ] `bd cleanup --force` prunes expired tombstones after deleting closed issues
- [ ] `bd cleanup --dry-run` shows what tombstones would be pruned
- [ ] JSON output includes tombstone prune results


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

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

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

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

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

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

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


Add orphan detection migration

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


Fix autoimport tests for content-hash collision scoring

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

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

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

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

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

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

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

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


Implement content-hash based collision resolution for deterministic convergence

The current collision resolution uses creation timestamps to decide which issue to keep vs. remap. This is non-deterministic when two clones create issues at nearly the same time.

Root cause of bd-71107098:
- Clone A creates test-1="Issue from clone A" at T0
- Clone B creates test-1="Issue from clone B" at T0+30ms
- Clone B syncs first, remaps Clone A's to test-2
- Clone A syncs second, sees collision, remaps Clone B's to test-2
- Result: titles are swapped between clones

Solution:
- Use content-based hashing (title + description + priority + type)
- Deterministic winner: always keep issue with lower hash
- Same collision on different clones produces same result (idempotent)

Implementation:
- Modify ScoreCollisions in internal/storage/sqlite/collision.go
- Replace timestamp-based scoring with content hash comparison
- Ensure hash function is stable across platforms

Rename detection successfully implemented and tested!

**What was implemented:**
1. Content-hash based rename detection in DetectCollisions
2. When importing JSONL, if an issue has different ID but same content as DB issue, treat as rename
3. Delete old ID and accept new ID from JSONL
4. Added post-import re-export in sync command to flush rename changes
5. Added post-import commit to capture rename changes

**Test results:**
TestTwoCloneCollision now shows full convergence:
- Clone A: test-2="Issue from clone A", test-1="Issue from clone B"
- Clone B: test-1="Issue from clone B", test-2="Issue from clone A"

Both clones have **identical content** (titles match IDs correctly). Only timestamps differ (expected).

**What remains:**
- Test still expects exact JSON match including timestamps
- Could normalize timestamp comparison, but content convergence is the critical success metric
- The two-clone collision workflow now works without data corruption!


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.


Refactor create_test.go to use shared DB setup

Convert TestCreate_* functions to use test suites with shared database setup.

Example transformation:
- Before: 10 separate tests, each with newTestStore()
- After: 1 TestCreate() with 10 t.Run() subtests sharing one DB

Estimated speedup: 10x faster (1 DB setup instead of 10)


Update documentation for beads-merge integration

Document the integrated merge functionality.

**Updates needed**:
- AGENTS.md: Replace "use external beads-merge" with "bd merge"
- README.md: Add git merge driver section
- TROUBLESHOOTING.md: Update merge conflict resolution
- ADVANCED.md: Document 3-way merge algorithm
- Create CREDITS.md or ATTRIBUTION.md for @neongreen

**Highlight**: Deletion sync fix (bd-hv01)


Refactor duplicate JSONL-from-git parsing code

Both readFirstIssueFromGit() in init.go and importFromGit() in autoimport.go have similar code patterns for:
1. Running git show <ref>:<path>
2. Scanning the output with bufio.Scanner
3. Parsing JSON lines

Could be refactored to share a helper like:
- readJSONLFromGit(gitRef, path string) ([]byte, error)
- Or a streaming version: streamJSONLFromGit(gitRef, path string) (io.Reader, error)

Files:
- cmd/bd/autoimport.go:225-256 (importFromGit)
- cmd/bd/init.go:1212-1243 (readFirstIssueFromGit)

Priority is low since code duplication is minimal and both functions work correctly.


Add tests for bd init --team wizard

Write integration tests for the team wizard:
- Test branch detection
- Test sync branch creation
- Test protected branch workflow
- Test auto-sync configuration


Sync should cleanup snapshot files after completion

After sync completion, orphan .base.jsonl and .left.jsonl snapshot files remain in .beads/ directory. These should be cleaned up on successful sync.


Make MCP compaction settings configurable (COMPACTION_THRESHOLD, PREVIEW_COUNT)

Currently COMPACTION_THRESHOLD (20) and PREVIEW_COUNT (5) are hardcoded constants at the module level. This prevents users from tuning context engineering behavior.

## Current State
```python
COMPACTION_THRESHOLD = 20  # Compact results with more than 20 issues
PREVIEW_COUNT = 5          # Show first 5 issues in preview
```

## Problems
1. No way for MCP clients to request different preview sizes
2. No way to disable compaction for debugging
3. No way to adapt to different context window sizes
4. Values are not documented in tool schema

## Recommended Solution
Add environment variables or MCP tool parameters:
- `BEADS_MCP_COMPACTION_THRESHOLD` env var (default: 20)
- `BEADS_MCP_PREVIEW_COUNT` env var (default: 5)
- Optional `compact_threshold` and `preview_size` parameters to list/ready tools

## Implementation Notes
- Keep current defaults for backward compatibility
- Read from environment at server initialization
- Document in CONTEXT_ENGINEERING.md
- Add tests verifying env var behavior


Migration and onboarding for multi-repo

Create migration tools, wizards, and documentation to help users adopt multi-repo workflow, with special focus on OSS contributor onboarding and team adoption scenarios.


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


Auth tokens expire too quickly

## Summary

[Brief description of the bug]

## Steps to Reproduce

1. Step 1
2. Step 2
3. Step 3

## Expected Behavior

[What should happen]

## Actual Behavior

[What actually happens]

## Environment

- OS: [e.g., macOS 15.7.1]
- Version: [e.g., bd 0.20.1]
- Additional context: [any relevant details]

## Additional Context

[Screenshots, logs, or other relevant information]


Refactor: extract common helpers in sync-branch hook checks

Code review of #532 fix identified duplication between checkSyncBranchHookCompatibility and checkSyncBranchHookQuick.

Suggested refactoring:
1. Extract getPrePushHookPath(path string) helper for git dir + hook path resolution
2. Extract extractHookVersion(hookContent string) helper for version parsing
3. Consider whether Warning for custom hooks is appropriate (vs OK with info message)
4. Document the intentional behavior difference between full check (Warning for custom) and quick check (OK for custom)


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

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

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

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

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

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

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

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


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)


bd blocked shows empty (GH#545)

bd blocked only shows dependency-blocked issues, not status=blocked issues.

Either:
- Include status=blocked issues, OR
- Document/rename to clarify behavior

Fix in: cmd/bd/blocked.go


Fix TestListCommand duplicate dependency constraint violation


Implement TryResurrectParent function

Create internal/storage/sqlite/resurrection.go with TryResurrectParent(ctx, parentID) function. Parse JSONL history to find deleted parent, create tombstone with status=deleted and is_tombstone=true flag. Handle recursive resurrection for multi-level missing parents (bd-abc.1.2 with missing bd-abc and bd-abc.1).


Fix CI failures before 0.21.3 release

CI is failing on multiple jobs:
1. Nix flake: Tests fail due to missing git in build environment
2. Windows tests: Need to check what's failing
3. Linux tests: Need to check what's failing
4. Linter errors: Many unchecked errors need fixing

Need to fix before tagging v0.21.3 release.

Fixed linter errors (errcheck, misspell), Nix flake git dependency, and import database discovery bug. Tests still failing - need to investigate further.


Add error handling test for cmd.Help() in search command

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

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

In cmd/bd/search.go:39, the return value of cmd.Help() is not checked, flagged by errcheck linter.

Add test to verify:
- Error handling when cmd.Help() fails (e.g., output redirection fails)
- Proper error propagation to caller
- Command still exits gracefully on help error

This ensures the search command handles help errors properly and doesn't silently ignore failures.

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


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


Extract daemon logger functions to daemon_logger.go


Parameterize SQLite busy_timeout in store.go

Modify sqlite.New() to accept configurable busy_timeout.

## Current State
`internal/storage/sqlite/store.go` hardcodes:
```go
connStr = "file:" + path + "?_pragma=foreign_keys(ON)&_pragma=busy_timeout(30000)&..."
```

## Implementation Options

### Option A: Add timeout parameter to New()
```go
func New(ctx context.Context, path string, busyTimeout time.Duration) (*SQLiteStorage, error)
```
Pro: Simple, explicit
Con: Changes function signature (breaking change for callers)

### Option B: Options struct pattern
```go
type Options struct {
    BusyTimeout time.Duration // default 30s
}
func New(ctx context.Context, path string, opts *Options) (*SQLiteStorage, error)
```
Pro: Extensible, nil means defaults
Con: More boilerplate

### Recommendation: Option A with default
```go
func New(ctx context.Context, path string) (*SQLiteStorage, error) {
    return NewWithOptions(ctx, path, 30*time.Second)
}

func NewWithOptions(ctx context.Context, path string, busyTimeout time.Duration) (*SQLiteStorage, error)
```

## Acceptance Criteria
- busy_timeout is parameterized in connection string
- 0 timeout means no waiting (immediate SQLITE_BUSY)
- All existing callers continue to work (via default wrapper)

Part of bd-olc1


Sync validation false positive: legitimate deletions trigger 'data loss detected'

## Problem
`bd sync` fails with false positive data loss detection when legitimate deletions occur:
```
Post-import validation failed: import reduced issue count: 26 → 25 (data loss detected!)
```

## Root Cause
The validation in `sync.go:329-340` counts DB issues BEFORE import, but `purgeDeletedIssues()` in `importer.go:159` legitimately removes issues DURING import. The validation doesn't account for expected deletions.

**The Flow:**
```
sync.go:293     → beforeCount = countDBIssues() = 26
sync.go:310-319 → sanitizeJSONL removes deleted issues from JSONL (RemovedCount=N)
sync.go:323     → importFromJSONL() runs subprocess
                  └→ importer.go:159 purgeDeletedIssues() removes issues from DB
sync.go:331     → afterCount = countDBIssues() = 25
sync.go:335     → validatePostImport(26, 25) → ERROR
```

## Fix
Pass `sanitizeResult.RemovedCount` to validation and account for expected deletions:

```go
// sync.go around line 335
expectedDecrease := 0
if sanitizeResult != nil {
    expectedDecrease = sanitizeResult.RemovedCount
}
if err := validatePostImportWithDeletions(beforeCount, afterCount, expectedDecrease); err != nil {
    // ...
}
```

```go
// integrity.go - new or modified function
func validatePostImportWithDeletions(before, after, expectedDeletions int) error {
    if after < before - expectedDeletions {
        return fmt.Errorf("unexpected data loss: %d → %d (expected max decrease: %d)",
            before, after, expectedDeletions)
    }
    // ...
}
```

## Files
- cmd/bd/sync.go:329-340
- cmd/bd/integrity.go:289-301


worktree: any bd command is slow

in a git worktree any bd command is slow, with a 2-3s pause before any results are shown. The identical command with `--no-daemon` is near instant.


Implement core reset package (internal/reset)

Create the core reset logic in internal/reset/ package.

## Responsibilities
- ResetOptions struct with all flag options
- CountImpact() - count issues/tombstones that will be deleted
- ValidateState() - check .beads/ exists, check git dirty state
- ExecuteReset() - main reset logic (without CLI concerns)
- Integrate with daemon killall

## Interface Design
```go
type ResetOptions struct {
    Hard      bool   // Include git operations (git rm, commit)
    Backup    bool   // Create backup before reset
    DryRun    bool   // Preview only, don't execute
    SkipInit  bool   // Don't re-initialize after reset
}

type ResetResult struct {
    IssuesDeleted     int
    TombstonesDeleted int
    BackupPath        string  // if backup was created
    DaemonsKilled     int
}

type ImpactSummary struct {
    IssueCount      int
    OpenCount       int
    ClosedCount     int
    TombstoneCount  int
    HasUncommitted  bool  // git dirty state
}

func Reset(opts ResetOptions) (*ResetResult, error)
func CountImpact() (*ImpactSummary, error)
func ValidateState() error
```

## IMPORTANT: CLI vs Core Separation
- `Force` (skip confirmation) is NOT in ResetOptions - that's a CLI concern
- Core always executes when called; CLI decides whether to prompt first
- Keep CLI-agnostic: no prompts, no colored output, no user interaction
- Return errors for CLI to handle with user-friendly messages
- Unit testable in isolation

## Dependencies
- Uses daemon.KillAllDaemons() from internal/daemon/
- Calls bd init logic after reset (unless SkipInit)


Measure git operation reduction

Quantify the reduction in git operations (pulls, commits, pushes) when using Agent Mail for coordination.

Acceptance Criteria:
- Baseline: count git ops for 10 issues without Agent Mail
- With Agent Mail: count git ops for 10 issues
- Document reduction percentage
- Verify 70-80% reduction claim
- Measure impact on .git directory size growth

Success Metric: ≥70% reduction in git operations


Add 'new' as alias for 'create' command


Fix gosec lint warnings in doctor.go, main.go, and fix subdirectory

CI lint job failing with 4 gosec warnings:
- cmd/bd/doctor.go:664 (G304: file inclusion via variable)
- cmd/bd/doctor/fix/database_config.go:166 (G304: file inclusion via variable)
- cmd/bd/doctor/fix/untracked.go:61 (G204: subprocess launched with variable)
- cmd/bd/main.go:645 (G304: file inclusion via variable)

Either suppress with `// #nosec` if false positives, or refactor to validate paths properly.


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.


Test Epic

## Overview

[Describe the high-level goal and scope of this epic]

## Success Criteria

- [ ] Criteria 1
- [ ] Criteria 2
- [ ] Criteria 3

## Background

[Provide context and motivation]

## Scope

**In Scope:**
- Item 1
- Item 2

**Out of Scope:**
- Item 1
- Item 2


Refactor daemon.go into internal/daemonrunner

Extract daemon runtime from daemon.go (1,565 lines) into internal/daemonrunner with focused modules: config.go, daemon.go, process.go, rpc_server.go, sync.go, git.go. Keep cobra command thin.


wish: a 'continue' or similar cmd/flag which means alter last issue

so many time I create an issue and then have another thought: 'oh, before I did X and it crashed there was ZZZ happening' or 'actually that is P4 not P2'. It would be nice if when `bd {cmd}` is used without a {title} or {id} it just adds or updates the most recently touched issue.


Fix TestExportUpdatesMetadata to test actual daemon functions

## Problem
TestExportUpdatesMetadata (daemon_sync_test.go:296) manually replicates the metadata update logic rather than calling the fixed functions (createExportFunc/createSyncFunc).

This means:
- Test verifies the CONCEPT works
- But doesn't verify the IMPLEMENTATION in the actual daemon functions
- If daemon code is wrong, test still passes

## Current Test Flow
```go
// Test does:
exportToJSONLWithStore()  // ← Direct call
// ... manual metadata update ...
exportToJSONLWithStore()  // ← Direct call again
```

## Should Be
```go
// Test should:
createExportFunc(...)()  // ← Call actual daemon function
// ... verify metadata was updated by the function ...
createExportFunc(...)()  // ← Call again, should not fail
```

## Challenge
createExportFunc returns a closure that's run by the daemon. Testing this requires:
- Mock logger
- Proper context setup
- Git operations might need mocking

## Files
- cmd/bd/daemon_sync_test.go

## Acceptance Criteria
- Test calls actual createExportFunc and createSyncFunc
- Test verifies metadata updated by daemon code, not test code
- Both functions tested (export and sync)


bd doctor --fix needs non-interactive mode (-y/--yes flag)

When running `bd doctor --fix` in non-interactive mode (scripts, CI, Claude Code), it prompts 'Continue? (Y/n):' and fails with EOF.

**Expected**: A `-y` or `--yes` flag to auto-confirm fixes.

**Workaround**: Currently have to run `bd init` instead, but that's not discoverable from the doctor output.


Update documentation for merge driver auto-config

Update documentation to reflect the new merge driver auto-configuration during `bd init`.

**Files to update:**
- README.md - Mention merge driver setup in initialization section
- AGENTS.md - Update onboarding section about merge driver
- Possibly QUICKSTART.md

**Content:**
- Explain what the merge driver does
- Show --skip-merge-driver flag usage
- Manual installation steps for post-init setup


Add bd alias command for manual alias control

Add command for users to manually view and reassign aliases.

## Command: bd alias

### Subcommands

#### 1. bd alias list
Show all alias mappings:
```bash
$ bd alias list
#1    → bd-af78e9a2  Fix authentication bug
#2    → bd-e5f6a7b8  Add logging to daemon
#42   → bd-1a2b3c4d  Investigate jujutsu integration
#100  → bd-9a8b7c6d  (reassigned after conflict)
```

#### 2. bd alias set <alias> <hash-id>
Manually assign alias to specific issue:
```bash
$ bd alias set 42 bd-1a2b3c4d
✓ Assigned alias #42 to bd-1a2b3c4d

$ bd alias set 1 bd-af78e9a2
✗ Error: Alias #1 already assigned to bd-e5f6a7b8
Use --force to override
```

#### 3. bd alias compact
Renumber all aliases to fill gaps:
```bash
$ bd alias compact [--dry-run]

Current aliases: #1, #2, #5, #7, #100, #101
After compacting: #1, #2, #3, #4, #5, #6

Renumbering:
  #5   → #3
  #7   → #4
  #100 → #5
  #101 → #6

Apply changes? [y/N]
```

#### 4. bd alias reset
Regenerate all aliases (sequential from 1):
```bash
$ bd alias reset [--sort-by=priority|created|id]

WARNING: This will reassign ALL aliases. Continue? [y/N]

Reassigning 150 issues by priority:
  bd-a1b2c3d4 → #1   (P0: Critical security bug)
  bd-e5f6a7b8 → #2   (P0: Data loss fix)
  bd-1a2b3c4d → #3   (P1: Jujutsu integration)
  ...
```

#### 5. bd alias find <hash-id>
Look up alias for hash ID:
```bash
$ bd alias find bd-af78e9a2
#1

$ bd alias find bd-nonexistent
✗ Error: Issue not found
```

## Use Cases

### 1. Keep Important Issues Low-Numbered
```bash
# After closing many P0 issues, compact to free low numbers
bd alias compact

# Or manually set
bd alias set 1 bd-<critical-bug-hash>
```

### 2. Consistent Aliases Across Clones
```bash
# After migration, coordinator assigns canonical aliases
bd alias reset --sort-by=id
git add .beads/aliases.jsonl
git commit -m "Canonical alias assignments"
git push

# Other clones pull and adopt
git pull
bd import  # Alias conflicts resolved automatically
```

### 3. Debug Alias Conflicts
```bash
# See which aliases were reassigned
bd alias list | grep "#100"
```

## Flags

### Global
- `--dry-run`: Preview changes without applying
- `--force`: Override existing alias assignments

### bd alias reset
- `--sort-by=priority`: Assign by priority (P0 first)
- `--sort-by=created`: Assign by creation time (oldest first)
- `--sort-by=id`: Assign by hash ID (lexicographic)

## Implementation

File: cmd/bd/alias.go
```go
func aliasListCmd() *cobra.Command {
    return &cobra.Command{
        Use:   "list",
        Short: "List all alias mappings",
        Run: func(cmd *cobra.Command, args []string) {
            aliases := storage.GetAllAliases()
            for _, a := range aliases {
                fmt.Printf("#%-4d → %s  %s\n",
                    a.Alias, a.IssueID, a.Title)
            }
        },
    }
}

func aliasSetCmd() *cobra.Command {
    return &cobra.Command{
        Use:   "set <alias> <hash-id>",
        Short: "Manually assign alias to issue",
        Args:  cobra.ExactArgs(2),
        Run: func(cmd *cobra.Command, args []string) {
            alias, _ := strconv.Atoi(args[0])
            hashID := args[1]

            force, _ := cmd.Flags().GetBool("force")
            if err := storage.SetAlias(alias, hashID, force); err != nil {
                fmt.Fprintf(os.Stderr, "Error: %v\n", err)
                os.Exit(1)
            }
            fmt.Printf("✓ Assigned alias #%d to %s\n", alias, hashID)
        },
    }
}
```

## Files to Create
- cmd/bd/alias.go

## Testing
- Test alias list output
- Test alias set with/without force
- Test alias compact removes gaps
- Test alias reset with different sort orders
- Test alias find lookup


Add test coverage for internal/autoimport package


Add functional tests for FlushManager correctness verification


Short tests taking 13+ minutes (performance regression)


Prevent multiple daemons from running on the same repo

Multiple bd daemons running on the same repo clone causes race conditions and data corruption risks.

**Problem:**
- Nothing prevents spawning multiple daemons for the same repository
- Multiple daemons watching the same files can conflict during sync operations
- Observed: 4 daemons running simultaneously caused sync race condition

**Solution:**
Implement daemon singleton enforcement per repo:
1. Use a lock file (e.g., .beads/.daemon.lock) with PID
2. On daemon start, check if lock exists and process is alive
3. If stale lock (dead PID), clean up and acquire lock
4. If active daemon exists, either:
   - Exit with message 'daemon already running (PID xxx)'
   - Or offer --replace flag to kill existing and take over
5. Release lock on graceful shutdown

**Edge cases to handle:**
- Daemon crashes without releasing lock (stale PID detection)
- Multiple repos in same directory tree (each repo gets own lock)
- Race between two daemons starting simultaneously (atomic lock acquisition)


Integration Layer Implementation

Build the adapter layer that makes Agent Mail optional and non-intrusive.

Progress: bd-m9th (Python adapter library) completed with full test coverage. Next: bd-fzbg (update python-agent example with Agent Mail integration).


GH#523: Fix closed issues missing closed_at timestamp during db upgrade

Old beads databases may have closed issues without closed_at timestamps, causing 'closed issues must have closed_at timestamp' validation errors on upgrade to 0.29.0. Need defensive handling during import. See: https://github.com/steveyegge/beads/issues/523


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


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


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.


Parent: bd-imj

Ensure deletions.jsonl is tracked in git (not ignored).

Update bd init and gitignore upgrade logic to:
1. NOT add deletions.jsonl to .gitignore
2. Ensure it is committed alongside beads.jsonl

The file must be in git for cross-clone propagation to work.

Acceptance criteria:
- bd init does not ignore deletions.jsonl
- Existing .gitignore files are not broken
- File appears in git status when modified


Update python-agent example with Agent Mail integration

Modify examples/python-agent/agent.py to use Agent Mail adapter at 4 integration points.

Acceptance Criteria:
- Import and initialize adapter
- Check inbox before find_ready_work()
- Reserve issue before claim_task()
- Notify on status changes
- Release reservation on complete_task()
- Works identically when Agent Mail disabled
- No changes required to core Beads CLI

File: examples/python-agent/agent.py


Stealth mode global gitignore should use absolute project path

**GitHub Issue:** #538

**Problem:**
`bd init --stealth` adds `.beads/` to the global gitignore, which ignores ALL `.beads/` folders across all repositories. Users who want stealth mode in one project but open beads usage in others are blocked.

**Solution:**
Change stealth mode to use absolute paths instead of generic patterns:

**Before (current):**
```
# Beads stealth mode configuration (added by bd init --stealth)
.beads/
.claude/settings.local.json
```

**After (proposed):**
```
# Beads stealth mode: /Users/foo/work-project (added by bd init --stealth)
/Users/foo/work-project/.beads/
/Users/foo/work-project/.claude/settings.local.json
```

**Implementation:**
1. Modify `setupGlobalGitIgnore()` in `cmd/bd/init.go`
2. Get current working directory (absolute path)
3. Use absolute path patterns instead of generic ones
4. Update comment to show which project the entry is for

**Tradeoffs:**
- If project directory moves, gitignore entry becomes stale (acceptable - user can re-run `bd init --stealth`)
- Multiple stealth projects = multiple entries (works correctly)

**Testing:**
- Verify absolute path is added to global gitignore
- Verify other projects' .beads/ folders are NOT ignored
- Test with existing global gitignore file
- Test creating new global gitignore file


Manual task


Hooks System

Implement hook system for extensibility.

Hook directory: .beads/hooks/
Hook files (executable scripts):
- on_create - runs after bd create
- on_update - runs after bd update
- on_close - runs after bd close
- on_message - runs after bd mail send

Hook invocation:
- Pass issue ID as first argument
- Pass event type as second argument
- Pass JSON issue data on stdin
- Run asynchronously (dont block command)

Example hook (GGT notification):
  #!/bin/bash
  gt notify --event=$2 --issue=$1

This allows GGT to register notification handlers without Beads knowing about GGT.


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.


Improve test coverage for cmd/bd/setup (28.4% → 50%)

The setup package has only 28.4% test coverage. Setup commands are critical for first-time user experience.

Current coverage: 28.4%
Target coverage: 50%


Test Agent Mail server failure scenarios

Verify graceful degradation across various failure modes.

Test Cases:
- Server never started
- Server crashes during operation
- Network partition (timeout)
- Server returns 500 error
- Invalid bearer token
- SQLite corruption

Acceptance Criteria:
- Agents continue working in all scenarios
- Clear log messages about degradation
- No crashes or data loss
- Beads JSONL remains consistent

File: tests/integration/test_mail_failures.py


Investigate jujutsu VCS as potential solution for conflict-free merging

## Context
Current N-way collision resolution struggles with Git line-based merge model. When 5+ clones create issues with same ID, Git merge conflicts require manual resolution, and our collision resolver can fail during convergence rounds.

## Research Question
Could jujutsu (jj) provide better conflict handling for JSONL files?

## Jujutsu Overview
- Next-gen VCS built on libgit2
- Designed to handle conflicts as first-class citizens
- Supports conflict-free replicated data types (CRDTs) in some scenarios
- Better handling of concurrent edits
- Can work with Git repos (compatible with existing infrastructure)

## Investigation Tasks
1. JSONL Merge Behavior - How does jj handle line-by-line JSONL conflicts?
2. Integration Feasibility - Can beads use jj as backend while maintaining Git compatibility?
3. Conflict Resolution Model - Does jj conflict model map to our collision resolution?
4. Operational Transform Support - Does jj implement operational transforms?

## Deliverables
1. Technical report on jj merge algorithm for JSONL
2. Proof-of-concept: 5-clone collision test using jj instead of Git
3. Performance comparison: Git vs jj for beads workload
4. Recommendation: Adopt, experiment further, or abandon

## References
- https://github.com/martinvonz/jj
- Related to bd-e6d71828, bd-7a2b58fc


bd export should detect and prevent stale database exports

## Problem

When `bd export` is run with a stale database (older than issues.jsonl), it silently overwrites the JSONL file with stale data, causing data loss.

## What Happened (vc project)

1. Agent A created 4 new issues and exported to issues.jsonl (commit 99a9d58)
2. Agent A closed an issue and exported again (commit 58b4613) - JSONL now has 4 epics
3. Agent B had stale database (from before step 1)
4. Agent B worked on unrelated issue and exported (commit 0609233)
5. Agent B's export **overwrote issues.jsonl**, removing the 4 epics created by Agent A
6. Required manual recovery by re-exporting from Agent A's correct database

## Expected Behavior

`bd export` should detect that the database is stale and either:
- **Refuse to export** with error message explaining the issue
- **Warn prominently** and require explicit --force flag to override
- **Auto-import first** to sync database before exporting

## How to Detect Staleness

Compare modification times (similar to VC's ValidateDatabaseFreshness):
1. Check .db, .db-wal, .db-shm timestamps (use newest for WAL mode)
2. Check issues.jsonl timestamp
3. If JSONL is newer by >1 second: database is stale

## Suggested Fix

Add staleness check in `bd export`:

```go
func Export(dbPath, jsonlPath string, force bool) error {
    // Check if database is stale
    if !force {
        if err := checkDatabaseFreshness(dbPath, jsonlPath); err != nil {
            return fmt.Errorf("database is stale: %w\n" +
                "Run 'bd import %s' first to sync, or use --force to override",
                err, jsonlPath)
        }
    }

    // Proceed with export...
}
```

## Impact

- **Severity**: High (silent data loss)
- **Frequency**: Happens in multi-agent workflows when agents don't sync
- **Workaround**: Manual recovery (re-export from correct database)

## References

- VC issue tracker: commits 58b4613 -> 0609233 -> c41c638
- VC has similar check: `storage.ValidateDatabaseFreshness()`
- Tolerance: 1 second (handles filesystem timestamp precision)

Fixed with ID-based comparison instead of just count. Now detects:
1. DB has fewer issues than JSONL (count check)
2. DB has different issues than JSONL (ID comparison)

Both scenarios now properly refuse export unless --force is used.

Implementation uses getIssueIDsFromJSONL() to build a set of IDs from JSONL, then checks if any JSONL IDs are missing from DB. Shows specific missing issue IDs in error message.


Update AGENTS.md with event-driven mode

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


Dogfood: Migrate beads repo to hash IDs

Final validation: migrate the beads project itself to hash-based IDs.

## Purpose
Dogfooding the migration on beads' own issue database to:
1. Validate migration tool works on real data
2. Discover edge cases
3. Verify all workflows still work
4. Build confidence for users

## Pre-Migration Checklist
- [ ] All bd-f8b764c9 child tasks completed
- [ ] All tests pass: `go test ./...`
- [ ] Migration tool tested on test databases
- [ ] Documentation updated
- [ ] MCP server updated and published
- [ ] Clean git status

## Migration Steps

### 1. Create Backup
```bash
# Backup database
cp -r .beads .beads.backup-1761798568

# Backup JSONL
cp .beads/beads.jsonl .beads/beads.jsonl.backup

# Create git branch for migration
git checkout -b hash-id-migration
git add .beads.backup-*
git commit -m "Pre-migration backup"
```

### 2. Run Migration (Dry Run)
```bash
bd migrate --hash-ids --dry-run > migration-plan.txt
cat migration-plan.txt

# Review:
# - Number of issues to migrate
# - Hash collision check (should be zero)
# - Text reference updates
# - Dependency updates
```

### 3. Run Migration (Real)
```bash
bd migrate --hash-ids 2>&1 | tee migration-log.txt

# Expected output:
# ✓ Backup created: .beads/beads.db.backup-1234567890
# ✓ Generated 150 hash IDs
# ✓ No hash collisions detected
# ✓ Updated issues table schema
# ✓ Updated 150 issue IDs
# ✓ Updated 87 dependencies
# ✓ Updated 234 text references
# ✓ Exported to .beads/beads.jsonl
# ✓ Migration complete!
```

### 4. Validation

#### Database Integrity
```bash
# Check all issues have hash IDs
bd list | grep -v "bd-[a-f0-9]\{8\}" && echo "FAIL: Non-hash IDs found"

# Check all issues have aliases
sqlite3 .beads/beads.db "SELECT COUNT(*) FROM issues WHERE alias IS NULL"
# Should be 0

# Check no alias duplicates
sqlite3 .beads/beads.db "SELECT alias, COUNT(*) FROM issues GROUP BY alias HAVING COUNT(*) > 1"
# Should be empty
```

#### Functionality Tests
```bash
# Test show by hash ID
bd show bd-

# Test show by alias
bd show #1

# Test create new issue
bd create "Test issue after migration" -p 2
# Should get hash ID + alias

# Test update
bd update #1 --priority 1

# Test dependencies
bd dep tree #1

# Test export
bd export
git diff .beads/beads.jsonl
# Should show hash IDs
```

#### Text Reference Validation
```bash
# Check that old IDs were updated in descriptions
grep -r "bd-[0-9]\{1,3\}[^a-f0-9]" .beads/beads.jsonl && echo "FAIL: Old ID format found"

# Verify hash ID references exist
grep -o "bd-[a-f0-9]\{8\}" .beads/beads.jsonl | sort -u | wc -l
# Should match number of hash IDs
```

### 5. Commit Migration
```bash
git add .beads/beads.jsonl .beads/beads.db
git commit -m "Migrate to hash-based IDs (v2.0)

- Migrated 150 issues to hash IDs
- Preserved aliases (#1-#150)
- Updated 87 dependencies
- Updated 234 text references
- Zero hash collisions

Migration log: migration-log.txt"

git push origin hash-id-migration
```

### 6. Create PR
```bash
gh pr create --title "Migrate to hash-based IDs (v2.0)" --body "## Summary
Migrates beads project to hash-based IDs as part of v2.0 release.

## Migration Stats
- Issues migrated: 150
- Dependencies updated: 87
- Text references updated: 234
- Hash collisions: 0
- Aliases assigned: 150

## Validation
- ✅ All tests pass
- ✅ Database integrity verified
- ✅ All workflows tested (show, update, create, deps)
- ✅ Text references updated correctly
- ✅ Export produces valid JSONL

## Files Changed
- `.beads/beads.jsonl` - Hash IDs in all entries
- `.beads/beads.db` - Schema updated with aliases

## Rollback
If issues arise:
\`\`\`bash
mv .beads.backup-1234567890 .beads
bd export
\`\`\`

See migration-log.txt for full details."
```

### 7. Merge and Cleanup
```bash
# After PR approval
git checkout main
git merge hash-id-migration
git push origin main

# Tag release
git tag v2.0.0
git push origin v2.0.0

# Cleanup
rm migration-log.txt migration-plan.txt
git checkout .beads.backup-*  # Keep in git history
```

## Rollback Procedure
If migration fails or has issues:

```bash
# Restore backup
mv .beads .beads.failed-migration
mv .beads.backup-1234567890 .beads

# Regenerate JSONL
bd export

# Verify restoration
bd list
git diff .beads/beads.jsonl

# Cleanup
git checkout hash-id-migration
git reset --hard main
```

## Post-Migration Communication

### GitHub Issue/Discussion
```markdown
## Beads v2.0 Released: Hash-Based IDs

We've migrated beads to hash-based IDs! 🎉

**What changed:**
- Issues now use hash IDs (bd-af78e9a2) instead of sequential (bd-cb64c226.3)
- Human-friendly aliases (#42) for easy reference
- Zero collision risk in distributed workflows

**Action required:**
If you have a local clone, you need to migrate:

\`\`\`bash
git pull origin main
bd migrate --hash-ids
git push origin main
\`\`\`

See MIGRATION.md for details.

**Benefits:**
- ✅ No more ID collisions
- ✅ Work offline without coordination
- ✅ Simpler codebase (-2,100 LOC)

Questions? Reply here or see docs/HASH_IDS.md
```

## Success Criteria
- [ ] Migration completes without errors
- [ ] All validation checks pass
- [ ] PR merged to main
- [ ] v2.0.0 tagged and released
- [ ] Documentation updated
- [ ] Community notified
- [ ] No rollback needed within 1 week

## Files to Create
- migration-log.txt (transient)
- migration-plan.txt (transient)

## Timeline
Execute after all other bd-f8b764c9 tasks complete (estimated: ~8 weeks from start)


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

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

These are lower priority but should have basic coverage.


Improve bd doctor output formatting for better readability

The current bd doctor output is a wall of text that's hard to process. Consider improvements like:
- Grouping related checks into collapsible sections
- Using color/bold for section headers
- Showing only failures/warnings by default with --verbose for full output
- Better visual hierarchy between major sections
- Summary line at top (e.g., '24 checks passed, 0 warnings, 0 errors')


Remove Daemon Storage Cache

The daemon's multi-repo storage cache is the root cause of stale data bugs. Since global daemon is deprecated, we only ever serve one repository, making the cache unnecessary complexity. This epic removes the cache entirely for simpler, more reliable direct storage access.


Tests take too long - unacceptable for project size

## Problem

Running `go test ./internal/importer/... -v` takes an unacceptably long time (minutes). For a project this size, tests should complete in seconds.

## Impact

- Slows down development iteration
- AI agents waste time waiting for tests
- Blocks rapid bug fixes and validation
- Poor developer experience

## Investigation Needed

- Profile which tests are slow
- Check for unnecessary sleeps, timeouts, or integration tests
- Look for tests that could be parallelized
- Consider splitting unit vs integration tests

## Goal

Test suite for a single package should complete in <5 seconds, ideally <2 seconds.

## Optimizations Applied

1. **Added t.Parallel() to CLI tests** (13 tests) - allows concurrent execution
2. **Removed unnecessary 200ms sleep** in daemon_autoimport_test.go - Execute() forces auto-import synchronously
3. **Reduced filesystem settle wait** from 100ms → 50ms on non-Windows platforms
4. **Optimized debouncer test sleeps** (9 reductions):
   - Before debounce waits: 30ms → 20ms, 20ms → 10ms
   - After debounce waits: 40ms → 35ms, 30ms → 35ms, etc.
   - Thread safety test: 100ms → 70ms
   - Sequential cycles: 50ms → 40ms (3x)
   - Cancel tests: 70-80ms → 60ms

## Results

### cmd/bd package (main improvement target):
- **Before**: 5+ minutes (timeout)
- **After**: ~18-20 seconds
- **Speedup**: ~15-18x faster

### internal/importer package:
- **After**: <1 second (0.9s)

### Full test suite (with `-short` flag):
- Most packages complete in <2s
- Total runtime constrained by sequential integration tests

## Known Issues

- TestConcurrentExternalRefImports hangs due to :memory: connection pool issue (bd-b121)
- Some sync_branch tests may need sequential execution (git worktree conflicts)


Git history fallback doesn't escape regex special chars in IDs

## Problem

In `batchCheckGitHistory`, IDs are directly interpolated into a regex pattern:

```go
patterns = append(patterns, fmt.Sprintf(\`"id":"%s"\`, id))
searchPattern := strings.Join(patterns, "|")
cmd := exec.Command("git", "log", "--all", "-G", searchPattern, ...)
```

If an ID contains regex special characters (e.g., `bd-foo.bar` or `bd-test+1`), the pattern will be malformed or match unintended strings.

## Location
`internal/importer/importer.go:923-926`

## Impact
- False positives: IDs with `.` could match any character
- Regex errors: IDs with `[` or `(` could cause git to fail
- Security: potential for regex injection (low risk since IDs are validated)

## Fix
Escape regex special characters:

```go
import "regexp"

escapedID := regexp.QuoteMeta(id)
patterns = append(patterns, fmt.Sprintf(\`"id":"%s"\`, escapedID))
```


Add migration guide for library consumers

The contributor-workflow-analysis.md has excellent migration examples for CLI users (lines 508-549) but lacks examples for library consumers like VC that use beadsLib in Go/TypeScript code.

Library consumers need to know:
- Whether their existing code continues to work unchanged (backward compatibility)
- How config.toml is automatically read (transparent hydration)
- When and how to use explicit multi-repo configuration
- What happens if config.toml doesn't exist (defaults)

Example needed:
```go
// Before (v0.17.3)
store, err := beadsLib.NewSQLiteStorage(".beads/vc.db")

// After (v0.18.0 with multi-repo) - still works!
store, err := beadsLib.NewSQLiteStorage(".beads/vc.db")
// Automatically reads .beads/config.toml if present

// Explicit multi-repo (if needed)
cfg := beadsLib.Config{
    Primary: ".beads/vc.db",
    Additional: []string{"~/.beads-planning"},
}
store, err := beadsLib.NewStorageWithConfig(cfg)
```


Database import silently fails when daemon version != CLI version


Write Agent Mail integration guide

Comprehensive guide for setting up and using Agent Mail with Beads.

Acceptance Criteria:
- Installation instructions
- Configuration (environment variables)
- Architecture diagram
- Benefits and tradeoffs
- When to use vs not use
- Troubleshooting section
- Migration from git-only mode

File: docs/AGENT_MAIL.md

Sections:
- Quick start
- How it works
- Integration points
- Graceful degradation
- Multi-machine deployment
- FAQ


Verify MCP Server Compatibility

Ensure MCP server works with cache-free daemon


Implement global N-way collision resolution algorithm

**Summary:** Replaced pairwise collision resolution with a global N-way algorithm that deterministically resolves issue ID conflicts across multiple clones. The new approach groups collisions, deduplicates by content hash, and assigns sequential IDs to ensure consistent synchronization.

**Key Decisions:**
- Use content hash for global, stable sorting
- Group collisions by base ID
- Assign sequential IDs based on sorted unique versions
- Eliminate order-dependent remapping logic

**Resolution:** Implemented ResolveNWayCollisions function that guarantees deterministic issue ID assignment across multiple synchronization scenarios, solving the core challenge of maintaining consistency in distributed systems with potential conflicts.


Fix checkExistingBeadsData to be worktree-aware

The checkExistingBeadsData function in cmd/bd/init.go checks for .beads in the current working directory, but for worktrees it should check the main repository root instead. This prevents proper worktree compatibility.


Wire config to import pipeline

Connect import.orphan_handling config to importer.go and sqlite validation functions. Pass mode flag through call chain. Implement all four modes (strict/resurrect/skip/allow) with proper error messages and logging.


Create backup and restore procedures

Disaster recovery procedures for Agent Mail data.

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

File: deployment/agent-mail/backup.sh


Remove misleading placeholder 'bd merge' command from duplicates output

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

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

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

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

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

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

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


Latency test manual


Document bd-wasm installation and usage

Create documentation for bd-wasm:
- Update README with npm installation instructions
- Add troubleshooting section for WASM-specific issues
- Document known limitations vs native bd
- Add examples for Claude Code Web sandbox usage
- Update INSTALLING.md with bd-wasm option


bd cleanup --hard should skip tombstone creation for true permanent deletion

## Problem

When using bd cleanup --hard --older-than N --force, the command:
1. Deletes closed issues older than N days (converting them to tombstones with NOW timestamp)
2. Then tries to prune tombstones older than N days (finds none because they were just created)

This leaves the database bloated with fresh tombstones that will not be pruned.

## Expected Behavior

In --hard mode, the deletion should be permanent without creating tombstones, since the user explicitly requested bypassing sync safety.

## Workaround

Manually delete from database: sqlite3 .beads/beads.db 'DELETE FROM issues WHERE status=tombstone'

## Fix Options

1. In --hard mode, use a different delete path that does not create tombstones
2. After deleting, immediately prune the just-created tombstones regardless of age
3. Pass a skip_tombstone flag to the delete operation

Option 1 is cleanest - --hard should mean permanent delete without tombstone.


Implement transaction retry logic for SQLITE_BUSY

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

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

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

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

Impact: Spurious failures under concurrent write load

Effort: 3 hours


bd sync --squash: batch multiple syncs into single commit

For solo developers who don't need real-time multi-agent coordination, add a --squash option to bd sync that accumulates changes and commits them in a single commit rather than one commit per sync.

This addresses the git history pollution concern (many 'bd sync: timestamp' commits) while preserving the default behavior needed for orchestration.

**Proposed behavior:**
- `bd sync --squash` accumulates pending exports
- Only commits when explicitly requested or on session end
- Default behavior unchanged (immediate commits for orchestration)

**Use case:** Solo developers who want cleaner git history but don't need real-time coordination between agents.

**Related:** PR #411 (docs: reduce bd sync commit pollution)
**See also:** Multi-repo support as alternative solution (docs/MULTI_REPO_AGENTS.md)


Doctor should exclude merge artifacts from 'multiple JSONL' warning

Doctor command warns about 'multiple JSONL files' when .base.jsonl and .left.jsonl merge artifacts exist. These are expected during/after merge operations and should be excluded from the warning.


Improve internal/daemon test coverage (currently 22.5%)

Daemon functionality needs better coverage:
- Auto-start behavior
- Lock file management
- Discovery mechanisms
- Connection handling
- Error recovery

Current coverage: 58.3% (improved from 22.5% as of Nov 2025)


Fix silent error handling in RPC response writing

Marshal and write errors silently ignored in writeResponse, can send partial JSON and hang clients.

Location: internal/rpc/server_lifecycle_conn.go:228-232

Problem:
- json.Marshal error ignored - cyclic reference sends corrupt JSON
- Write error ignored - connection closed, no indication to caller
- WriteByte error ignored - client hangs waiting for newline
- Flush error ignored - partial data buffered

Current code:
func (s *Server) writeResponse(writer *bufio.Writer, resp Response) {
    data, _ := json.Marshal(resp)  // Ignored!
    _, _ = writer.Write(data)      // Ignored!
    _ = writer.WriteByte('\n')     // Ignored!
    _ = writer.Flush()             // Ignored!
}

Solution: Return errors, handle in caller, close connection on error

Impact: Client hangs waiting for response; corrupt JSON sent

Effort: 1 hour


Add richer query capabilities to bd list

Current bd list filters are limited to basic field matching (status, priority, type, assignee, label). This forces users to resort to piping through jq for common queries.

Missing query capabilities:
- Pattern matching: --title-contains, --desc-contains
- Date ranges: --created-after, --updated-before, --closed-after
- Empty/null checks: --empty-description, --no-assignee, --no-labels
- Numeric ranges: --priority-min, --priority-max
- Complex boolean logic: --and, --or operators
- Full-text search: --search across all text fields
- Negation: --not-status, --exclude-label

Example use cases:
- Find issues with empty descriptions
- Find stale issues not updated in 30 days
- Find high-priority bugs with no assignee
- Search for keyword across title/description/notes

Implementation approach:
- Add query builder pattern to storage layer
- Support --query DSL for complex queries
- Keep simple flags for common cases
- Add --json output for programmatic use

## Progress Update

**Completed:**
- ✅ Extended IssueFilter struct with new fields (pattern matching, date ranges, empty/null checks, priority ranges)
- ✅ Updated SQLite SearchIssues implementation
- ✅ Added CLI flags to list.go
- ✅ Added parseTimeFlag helper
- ✅ Comprehensive tests added - all passing

**Remaining:**
- ⚠ RPC layer needs updating (internal/rpc/protocol.go ListArgs)
- ⚠ Daemon handler needs to forward new filters
- ⚠ End-to-end testing with daemon mode
- 📝 Documentation updates

**Files Modified:**
- internal/types/types.go
- internal/storage/sqlite/sqlite.go
- cmd/bd/list.go
- cmd/bd/list_test.go

**Next Steps:**
1. Update RPC protocol
2. Update daemon handler
3. Test with daemon mode
4. Update docs


Add tests for internal/importer package

Currently 0.0% coverage. Need tests for JSONL import logic including collision detection and resolution.


Implement backup functionality for reset

Add backup capability that can be used by reset command.

## Functionality
- Copy .beads/ to .beads-backup-{timestamp}/
- Timestamp format: YYYYMMDD-HHMMSS
- Preserve file permissions
- Return backup path for user feedback

## Location
`internal/reset/backup.go` - keep with reset package for now (YAGNI)

## Interface
```go
func CreateBackup(beadsDir string) (backupPath string, err error)
```

## Notes
- Simple recursive file copy, no compression needed
- Error if backup dir already exists (unlikely with timestamp)
- Backup directories SHOULD be gitignored
- Add `.beads-backup-*/` pattern to .beads/.gitignore template in doctor package
- Consider: ListBackups() for future `bd backup list` command (not for this PR)


Polecats get stuck on interactive shell prompts (cp/mv/rm -i)

During swarm operations, polecats frequently get stuck waiting for interactive prompts from shell commands like:
- cp prompting 'overwrite file? (y/n)'
- mv prompting 'overwrite file? (y/n)'
- rm prompting 'remove file?'

This happens because macOS aliases or shell configs may have -i flags set by default.

Root cause: Claude Code runs commands that trigger interactive confirmation prompts, but cannot respond to them, causing the agent to hang indefinitely.

Observed in: Multiple polecats during GH issues swarm (Dec 2024)
- Derrick, Roustabout, Prospector, Warboy all got stuck on y/n prompts

Suggested fixes:
1. AGENTS.md should instruct agents to always use -f flag with cp/mv/rm
2. Polecat startup could set shell aliases to use non-interactive versions
3. bd prime hook could include guidance about non-interactive commands
4. Consider detecting stuck prompts and auto-recovering


Add tests for daemon lifecycle module


Document Claude Code for Web SessionStart hook

Create documentation for using bd in Claude Code for Web:

## Documentation locations
- README.md - Add Claude Code for Web section
- Create docs/CLAUDE_CODE_WEB.md with detailed instructions

## SessionStart hook example
```json
{
  "sessionStart": {
    "script": "npm install -g @beads/bd && bd init --quiet --prefix bd || true"
  }
}
```

## Documentation should cover
- How to configure SessionStart hook in .claude/settings.json
- Verification: Check bd is installed (bd --version)
- Basic workflow in Claude Code for Web
- Troubleshooting common issues
- Note about network restrictions and why npm approach works

## Examples
- Creating issues in web sandbox
- Syncing with git in web environment
- Using MCP server (if applicable)


VCS-agnostic sync support

Make bd sync work with multiple VCS types (git, jujutsu, mercurial, sapling) by detecting VCS per repo and using appropriate sync commands, supporting mixed-VCS multi-repo configs.


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 alias field to database schema

Extend database schema to support human-friendly aliases alongside hash IDs.

## Database Changes

### 1. Add alias column to issues table
```sql
ALTER TABLE issues ADD COLUMN alias INTEGER UNIQUE;
CREATE INDEX idx_issues_alias ON issues(alias);
```

### 2. Add alias counter table
```sql
CREATE TABLE alias_counter (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    next_alias INTEGER NOT NULL DEFAULT 1
);
INSERT INTO alias_counter (id, next_alias) VALUES (1, 1);
```

### 3. Add alias conflict tracking (for multi-clone scenarios)
```sql
CREATE TABLE alias_history (
    issue_id TEXT NOT NULL,
    alias INTEGER NOT NULL,
    assigned_at TIMESTAMP NOT NULL,
    workspace_id TEXT NOT NULL,
    PRIMARY KEY (issue_id, alias)
);
```

## API Changes

### CreateIssue
- Generate hash ID
- Assign next available alias
- Store both in database

### ResolveAliasConflicts (new function)
- Detect conflicting alias assignments after import
- Apply resolution strategy (content-hash ordering)
- Reassign losers to next available aliases

## Migration Path
```bash
bd migrate --add-aliases  # Adds columns, assigns aliases to existing issues
```

## Files to Modify
- internal/storage/sqlite/schema.go
- internal/storage/sqlite/sqlite.go (CreateIssue, GetIssue)
- internal/storage/sqlite/aliases.go (new file for alias logic)
- internal/storage/sqlite/migrations.go

## Testing
- Test alias auto-assignment on create
- Test alias uniqueness constraint
- Test alias lookup performance
- Test alias conflict resolution


File change test issue


Add --hard flag to bd cleanup to permanently cull tombstones before cutoff date

Currently tombstones persist for 30 days before cleanup prunes them. Need an official way to force-cull tombstones earlier than the default TTL, for scenarios like cleaning house after extended absence where resurrection from old clones is not a concern. Proposed: bd cleanup --hard --older-than N to bypass the 30-day tombstone TTL.


Add multi-repo support to export metadata updates

## Problem
The bd-ymj fix only updates metadata for the main jsonlPath, but the codebase supports multi-repo mode where exports write to multiple JSONL files.

Other daemon_sync operations handle multi-repo correctly:
- Lines 509-518: Snapshots captured for all multi-repo paths
- Lines 578-587: Deletions applied for all multi-repo paths

But metadata updates are missing!

## Investigation Needed
Metadata is stored globally in database (`last_import_hash`, `last_import_mtime`), but multi-repo has per-repo JSONL files. Current schema may not support tracking multiple JSONL files.

Options:
1. Store metadata per-repo (new schema)
2. Store combined hash of all repos
3. Document that multi-repo doesn't need this metadata (why?)

## Solution (if needed)
```go
// After export
if multiRepoPaths := getMultiRepoJSONLPaths(); multiRepoPaths != nil {
    // Multi-repo mode: update metadata for each JSONL
    for _, path := range multiRepoPaths {
        updateExportMetadata(exportCtx, store, path, log)
    }
} else {
    // Single-repo mode: update metadata for main JSONL
    updateExportMetadata(exportCtx, store, jsonlPath, log)
}
```

## Files
- cmd/bd/daemon_sync.go (createExportFunc, createSyncFunc)
- Possibly: internal/storage/sqlite/metadata.go (schema changes)

## Related
Depends on bd-ar2.1 (extract helper function first)


bd doctor --json flag not working

The --json flag on bd doctor command doesn't produce JSON output. It continues to show human-readable output instead. The flag is registered locally on doctorCmd but the code uses the global jsonOutput variable set by PersistentPreRun. Need to investigate why the flag isn't being honored.


Add bd hooks install command to embed git hooks in binary

Currently git hooks are installed via `examples/git-hooks/install.sh`, which only exists in the beads source repo. Users who install bd via installer/homebrew/npm can't easily install hooks.

**Proposal:**
Add `bd hooks install` command that:
- Embeds hook scripts in the bd binary (using go:embed)
- Installs them to .git/hooks/ in current repo
- Backs up existing hooks
- Makes them executable

**Commands:**
- `bd hooks install` - Install all hooks
- `bd hooks uninstall` - Remove hooks
- `bd hooks list` - Show installed hooks status

**Benefits:**
- Works for all bd users, not just source repo users
- More discoverable (shows in bd --help)
- Consistent with bd workflow
- Can version hooks with bd releases


Document external_ref in content hash behavior

The content hash includes external_ref, which has implications that should be documented.

Current behavior:
- external_ref is included in content hash calculation (collision.go:158-160)
- Changing external_ref changes content hash
- This means: local issue → add external_ref → different hash

Implications:
- Local issue + external_ref addition = looks like 'new content'
- May not match by content hash in some scenarios
- Generally correct behavior, but subtle

Action items:
- Document in code comments
- Add to ARCHITECTURE.md or similar
- Add test demonstrating this behavior
- Consider if this is desired long-term

Related: bd-1022
Files: internal/storage/sqlite/collision.go:158-160


Consider consolidating config.yaml parsing into shared utility

Multiple places parse config.yaml with custom structs:

1. **autoimport.go:148** - `localConfig{SyncBranch}`
2. **main.go:310** - strings.Contains for no-db (fragile, see bd-r6k2)
3. **doctor.go:863** - strings.Contains for no-db (fragile, see bd-r6k2)
4. **internal/config/config.go** - Uses viper (but caches at startup, problematic for tests)

Consider creating a shared utility in `internal/configfile/` or extending the viper config:

```go
// internal/configfile/yaml.go
type YAMLConfig struct {
    SyncBranch string `yaml:"sync-branch"`
    NoDb       bool   `yaml:"no-db"`
    IssuePrefix string `yaml:"issue-prefix"`
    Author     string `yaml:"author"`
}

func LoadYAML(beadsDir string) (*YAMLConfig, error) {
    // Parse config.yaml with proper YAML library
}
```

Benefits:
- Single source of truth for config.yaml structure
- Proper YAML parsing everywhere
- Easier to add new config fields

Trade-off: May add complexity for simple one-off reads.


## Problem

bd cleanup deletes closed issues (converting them to tombstones) but does NOT prune expired tombstones. Users expect 'cleanup' to do comprehensive cleanup.

## Current Behavior

1. bd cleanup --force converts closed issues to tombstones
2. Expired tombstones (>30 days) remain in issues.jsonl
3. User must separately run bd compact to prune tombstones
4. bd doctor warns about expired tombstones: Run bd compact to prune

## Expected Behavior

bd cleanup should also prune expired tombstones from issues.jsonl.

## Impact

With v0.30.0 making tombstones the default migration path, this UX gap becomes more visible. Users cleaning up their database should not need to know about a separate bd compact command.

## Proposed Solution

Call pruneExpiredTombstones() at the end of the cleanup command (same function used by compact).

## Files to Modify

- cmd/bd/cleanup.go - Add call to pruneExpiredTombstones after deleteBatch

## Acceptance Criteria

- bd cleanup --force prunes expired tombstones after deleting closed issues
- bd cleanup --dry-run shows what tombstones would be pruned
- JSON output includes tombstone prune results


Add cancellation and timeout tests

Add comprehensive tests for context cancellation and timeout behavior.

## Context
Part of context propagation work. Validates that bd-rtp and bd-yb8 work correctly.

## Test Coverage Needed

### 1. Cancellation Tests
- [ ] Import operation cancelled mid-stream
- [ ] Export operation cancelled mid-stream
- [ ] Database query cancelled during long operation
- [ ] No corruption after cancellation
- [ ] Proper cleanup (defers execute, connections closed)

### 2. Timeout Tests
- [ ] Operations respect context deadlines
- [ ] Appropriate error messages on timeout
- [ ] State remains consistent after timeout

### 3. Signal Handling Tests
- [ ] SIGINT (Ctrl+C) triggers cancellation
- [ ] SIGTERM triggers graceful shutdown
- [ ] Multiple signals handled correctly

## Implementation Approach
```go
func TestImportCancellation(t *testing.T) {
    ctx, cancel := context.WithCancel(context.Background())

    // Start import in goroutine
    go func() {
        err := runImport(ctx, largeFile)
        assert.Error(err, context.Canceled)
    }()

    // Cancel after short delay
    time.Sleep(100 * time.Millisecond)
    cancel()

    // Verify database integrity
    assertDatabaseConsistent(t, store)
}
```

## Files to Create/Update
- cmd/bd/import_test.go - cancellation tests
- cmd/bd/export_test.go - cancellation tests
- internal/storage/sqlite/*_test.go - context timeout tests

## Acceptance Criteria
- [ ] All critical operations have cancellation tests
- [ ] Tests verify database integrity after cancellation
- [ ] Signal handling tested (if feasible)
- [ ] Test coverage >80% for context paths


Add tests for daemon vs non-daemon parity in list filters

After bd-o43 RPC integration, we need tests to verify daemon mode behaves identically to direct mode for all new filter flags.

Test coverage needed:
- Pattern matching: --title-contains, --desc-contains, --notes-contains
- Date ranges: all 6 date filter flags (created/updated/closed after/before)
- Empty/null checks: --empty-description, --no-assignee, --no-labels
- Priority ranges: --priority-min, --priority-max
- Status normalization: --status all vs no status flag
- Date parsing: YYYY-MM-DD, RFC3339, and error cases
- Backward compat: deprecated --label flag still works

Oracle review findings (bd-o43):
- Date parsing should support multiple formats
- Status 'all' should be treated as unset
- NoLabels field was missing from RPC protocol
- Error messages should be clear and actionable

Test approach:
- Create RPC integration tests in internal/rpc/server_issues_epics_test.go
- Compare daemon client.List() vs direct store.SearchIssues() for same filters
- Verify error messages match between modes
- Test with real daemon instance, not just unit tests


Configure database connection pool limits for daemon mode

Database connection pool not configured for file-based databases when running in daemon mode.

Location: internal/storage/sqlite/sqlite.go:108-116

Problem:
- Daemon is a long-running server handling concurrent RPC requests
- Multiple CLI commands hit same daemon simultaneously
- Go default: unlimited connections (MaxOpenConns=0)
- SQLite IMMEDIATE transactions serialize on write lock
- Can have 100+ goroutines blocked waiting, each holding connection
- Results in connection exhaustion and 'database is locked' errors

Current code only limits in-memory DBs:
if isInMemory {
    db.SetMaxOpenConns(1)
    db.SetMaxIdleConns(1)
}
// File DBs: UNLIMITED connections!

Fix:
if !isInMemory {
    maxConns := runtime.NumCPU() + 1  // 1 writer + N readers
    db.SetMaxOpenConns(maxConns)
    db.SetMaxIdleConns(2)
    db.SetConnMaxLifetime(0)
}

Impact: 'database is locked' errors under concurrent load in daemon mode

Note: NOT an issue for direct CLI usage (each process isolated). Only affects daemon mode where multiple CLI commands share one database pool.

Effort: 1 hour


Document 3-clone ID non-determinism in collision resolution

Document the known behavior of 3+ way collision resolution where ID assignments may vary based on sync order, even though content always converges correctly.

Updates needed:
- Update bd-71107098 notes to mark 2-clone case as solved
- Document 3-clone ID non-determinism as known limitation
- Add explanation to ADVANCED.md or collision resolution docs
- Explain why this happens (pairwise hash comparison is deterministic, but multi-way ID allocation uses sync-order dependent counters)
- Clarify trade-offs: content convergence ✅ vs ID stability ❌

Key points to document:
- Hash-based resolution is pairwise deterministic
- Content always converges correctly (all issues present with correct data)
- Numeric ID assignments in 3+ way collisions depend on sync order
- This is acceptable for most use cases (content convergence is primary goal)
- Full determinism would require complex multi-way comparison


Isolate RPC server startup into rpc_server.go

Create internal/daemonrunner/rpc_server.go with StartRPC function. Move startRPCServer logic here and return typed handle.


Remove dead test code in info_test.go

Code health review found cmd/bd/info_test.go has two tests permanently skipped:

- TestInfoCommand
- TestInfoCommandNoDaemon

Both skip with: 'Manual test - bd info command is working, see manual testing'

These are essentially dead code. Either automate them or remove them entirely.


Add internal/ai package for AI-assisted repairs

Add AI integration package to support AI-powered repair commands.

Providers:
- Anthropic (Claude)
- OpenAI
- Ollama (local)

Features:
- Conflict resolution analysis
- Duplicate detection via embeddings
- Configuration via env vars (BEADS_AI_PROVIDER, BEADS_AI_API_KEY, etc.)

See repair_commands.md lines 357-425 for design.


bd init overwrites existing git hooks without detection or chaining

GH #254: bd init silently overwrites existing git hooks (like pre-commit framework) without detecting them, backing them up, or offering to chain. This breaks workflows and can result in committed code with failing tests.

Fix: Detect existing hooks, prompt user with options to chain/overwrite/skip.


Optimize cmd/bd test suite performance (currently 30+ minutes)

CLI test suite is extremely slow (~30+ minutes for full run). Tests are poorly designed and need performance optimization before expanding coverage.

Current coverage: 24.8% (improved from 20.2%)

**Problem**: Tests take far too long to run, making development iteration painful.

**Priority**: Fix test performance FIRST, then consider increasing coverage.

**Investigation needed**:
- Profile test execution to identify bottlenecks
- Look for redundant git operations, database initialization, or daemon operations
- Identify opportunities for test parallelization
- Consider mocking or using in-memory databases where appropriate
- Review test design patterns

**Related**: bd-ktng mentions 13 CLI tests with redundant git init calls (31s total)

**Goal**: Get full test suite under 1-2 minutes before adding more tests.


Test parent issue


Add comprehensive tests for show.go commands (show, update, edit, close)

Need to add tests for cmd/bd/show.go which contains show, update, edit, and close commands.

**Challenge**: The existing test patterns use rootCmd.SetArgs() and rootCmd.Execute(), but the global `store` variable needs to match what the commands use. Initial attempt created tests that failed with "no issue found" because the test's store instance wasn't the same as the command's store.

**Files to test**:
- show.go (contains showCmd, updateCmd, editCmd, closeCmd)

**Coverage needed**:
- show command (single issue, multiple issues, JSON output, with dependencies, with labels, with compaction)
- update command (status, priority, title, assignee, description, multiple fields, multiple issues)
- edit command (requires $EDITOR, may need mocking)
- close command (single issue, multiple issues, with reason, JSON output)

**Test approach**:
1. Study working test patterns in init_test.go, list_test.go, etc.
2. Ensure BEADS_NO_DAEMON=1 is set
3. Properly initialize database with bd init
4. Use the command's global store, not a separate instance
5. May need to reset global state between tests

**Success criteria**:
- All test functions pass
- Coverage for show.go increases significantly
- Tests follow existing patterns in cmd/bd/*_test.go


bd init should refuse when JSONL already has issues (safety guard)

When running `bd init` in a directory with an existing JSONL containing issues, bd should refuse and suggest the correct action instead of proceeding.

## The Problem

Current behavior when database is missing but JSONL exists:
```
$ bd create "test"
Error: no beads database found
Hint: run 'bd init' to create a database...
```

This leads users (and AI agents) to reflexively run `bd init`, which can cause:
- Prefix mismatch if wrong prefix specified
- Data corruption if JSONL is damaged
- Confusion about what actually happened

## Proposed Behavior

```
$ bd init --prefix bd

⚠ Found existing .beads/issues.jsonl with 76 issues.

This appears to be a fresh clone, not a new project.

To hydrate the database from existing JSONL:
  bd doctor --fix

To force re-initialization (may cause data loss):
  bd init --prefix bd --force

Aborting.
```

## Trigger Conditions

- `.beads/issues.jsonl` or `.beads/beads.jsonl` exists
- File contains > 0 valid issue lines
- No `--force` flag provided

## Edge Cases

- Empty JSONL (0 issues) → allow init (new project)
- Corrupted JSONL → warn but allow with confirmation
- Existing `.db` file → definitely refuse (weird state)

## Related

- bd-dmb: Fresh clone should suggest hydration (better error messages)
- bd-4ew: bd doctor should detect fresh clone

This issue is about the safety guard on `bd init` itself, not the error messages from other commands.


Extract daemon server functions to daemon_server.go


GH#519: bd sync fails when sync.branch is currently checked-out branch


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


Hash-based IDs with aliasing system

Replace sequential auto-increment IDs (bd-1c63eb84, bd-9063acda) with content-hash based IDs (bd-af78e9a2) plus human-friendly aliases (#1, #2).

## Motivation
Current sequential IDs cause collision problems when multiple clones work offline:
- Non-deterministic convergence in N-way scenarios (bd-cbed9619.1, bd-e6d71828)
- Complex collision resolution logic (~2,100 LOC)
- UNIQUE constraint violations during import
- Requires coordination between workers

Hash-based IDs eliminate collisions entirely while aliases preserve human readability.

## Benefits
- ✅ Collision-free distributed ID generation
- ✅ Eliminates ~2,100 LOC of collision handling code
- ✅ Better git merge behavior (different IDs = different JSONL lines)
- ✅ True offline-first workflows
- ✅ Simpler auto-import (no remapping needed)
- ✅ Enables parallel CI/CD workers without coordination

## Design
- Canonical ID: bd-af78e9a2 (8-char SHA256 prefix of title+desc+timestamp+creator)
- Alias: #42 (auto-increment per workspace, mutable, display-only)
- CLI accepts both: bd show bd-af78e9a2 OR bd show #42
- JSONL stores hash IDs only (aliases reconstructed on import)
- Alias conflicts resolved via content-hash ordering (deterministic)

## Breaking Change
This is a v2.0 feature requiring migration. Provide bd migrate --hash-ids tool.

## Timeline
~9 weeks (Phase 1: Hash IDs 4w, Phase 2: Aliases 3w, Phase 3: Testing 2w)

## Dependencies
Should complete after bd-7c5915ae (cleanup validation) and before bd-710a4916 (CRDT).


Document protected branch workflow

Create comprehensive documentation for protected branch workflow.

Tasks:
- Add "Protected Branch Workflow" section to AGENTS.md
- Create docs/PROTECTED_BRANCHES.md guide
- Update README.md quick start
- Add examples to examples/protected-branch/
- Update bd init --help documentation
- Add troubleshooting guide
- Add migration guide for existing users
- Record demo video (optional)

Estimated effort: 2-3 days

Completed protected branch workflow documentation. Created comprehensive guide (docs/PROTECTED_BRANCHES.md), updated AGENTS.md with workflow section, added feature to README.md, and created working example (examples/protected-branch/). All commands verified working (bd init --branch, bd sync --status, bd sync --merge, bd config get/set sync.branch).


Issue 1 to reopen


Split test suites: fast vs. integration

Reorganize tests into separate packages/files for fast unit tests vs slow integration tests.

Benefits:
- Clear separation of concerns
- Easier to run just fast tests during development
- Can parallelize CI jobs better

Files to organize:
- beads_hash_multiclone_test.go (slow integration tests)
- beads_integration_test.go (medium-speed integration tests)
- Other test files (fast unit tests)


Duplicate DefaultRetentionDays constants

## Problem

There are now two constants for the same value:

1. `deletions.DefaultRetentionDays = 7` in `internal/deletions/deletions.go:184`
2. `configfile.DefaultDeletionsRetentionDays = 7` in `internal/configfile/configfile.go:102`

## Impact
- DRY violation
- Risk of values getting out of sync
- Confusing which one to use

## Fix
Remove the constant from `deletions` package and have it import from `configfile`, or create a shared constants package.


Add bd daemon --stop-all command to kill all daemon processes

Currently there's no easy way to stop all running bd daemon processes. Users must resort to pkill -f 'bd daemon' or similar shell commands.

Add a --stop-all flag to bd daemon that:
1. Finds all running bd daemon processes (not just the current repo's daemon)
2. Gracefully stops them all
3. Reports how many were stopped

This is useful when:
- Multiple daemons are running and causing race conditions
- User wants a clean slate before running bd sync
- Debugging daemon-related issues


Fix GH #227: bd edit broken pipe errors

bd edit command gets "broken pipe" errors when using daemon mode because editing can take minutes and the daemon connection times out.

Solution: Force bd edit to always use direct mode (--no-daemon) since it's human-only and interactive.

Fixed by checking cmd.Name() == "edit" in main.go PersistentPreRun and setting noDaemon = true.


Add tests for Comments API (AddIssueComment, GetIssueComments)

Comments API currently has 0% coverage. Need tests for:
- AddIssueComment - adding comments to issues
- GetIssueComments - retrieving comments
- Comment ordering and pagination
- Edge cases (non-existent issues, empty comments)


Override test

## Overview

[Describe the high-level goal and scope of this epic]

## Success Criteria

- [ ] Criteria 1
- [ ] Criteria 2
- [ ] Criteria 3

## Background

[Provide context and motivation]

## Scope

**In Scope:**
- Item 1
- Item 2

**Out of Scope:**
- Item 1
- Item 2


Fix bd --version and bd completion to work without database