Agent 3 Issue 10


Agent 1 Batch 47 Issue 1


Agent 0 Batch 26 Issue 1


Agent 1 Issue 89


Socket permissions should be 0600 for security

Unix sockets should use 0600 permissions to prevent other users from connecting.

Currently:
- Global .beads dir uses 0700 (good)
- Local .beads dir uses 0700 (good)
- But socket itself may inherit default perms

Verify rpc.NewServer creates socket with 0600, or set umask/explicit perms.


Agent 9 Issue 14


Agent 2 Batch 4 Issue 1


Agent 6 Issue 95


Agent 0 Issue 82


Agent 8 Issue 92


Feature P1


Agent 3 Issue 56


Validate issue prefix matches database prefix on create

Users can accidentally create issues with the wrong prefix (e.g., creating 'bd-95' in the vc tracker instead of the beads tracker).

This causes problems:
- Issues appear in wrong project
- Renumbering silently removes them (correct behavior, but surprising)
- Confusion about which tracker owns the issue

Evidence from vc project:
- bd-95 and bd-96 were created in ~/src/vc/vc/.beads/vc.db (should use vc- prefix)
- These were silently removed during renumbering (working as intended)
- But user didn't realize they were in wrong database until too late

Root cause: User was in vc directory but created issues with bd- prefix, probably because they were beads-related fixes.


Document or automate JSONL sync workflow for git collaboration

When using beads across multiple machines/environments via git, there's a workflow gap:

1. Machine A: Create issues → stored in .beads/project.db
2. Machine A: bd export -o .beads/issues.jsonl
3. Machine A: git add .beads/issues.jsonl && git commit && git push
4. Machine B: git pull
5. Machine B: ??? issues.jsonl exists but project.db is empty/stale

The missing step is: bd import --db .beads/project.db -i .beads/issues.jsonl

This needs to be either:
a) Documented clearly in workflow docs
b) Automated (e.g., git hook, or bd auto-imports if jsonl is newer than db)
c) Both

Real-world impact: User had Claude Code on GCP VM create vc issues from BOOTSTRAP.md. They were exported to issues.jsonl and committed. But on local machine, vc.db was empty until manual import was run.


Add tests for extracted modules

Create tests for migrations.go, hash_ids.go, batch_ops.go, and validators.go


YABB: Spurious issue updates during normal operations

Issue bd-627d was updated during config refactoring session without any actual changes to it. Only timestamps and content_hash changed.

Observed: Running various bd commands (list, create, etc.) caused bd-627d updated_at to change from 14:14 to 14:31.

Expected: Issues should only be updated when explicitly modified.

This causes:
- Dirty JSONL after every session
- False conflicts in git
- Confusing git history

Likely culprit: Daemon auto-import/export cycle or database migration touching all issues.

Investigated thoroughly - unable to reproduce. The import logic has IssueDataChanged() checks before calling UpdateIssue (importer/importer.go:458). All tests pass. May have been fixed by recent refactorings. Closing as cannot reproduce - please reopen with specific repro steps if it occurs again.


Extract SQLite migrations into separate files

The file `internal/storage/sqlite/sqlite.go` is 2,136 lines and contains 11 sequential migrations alongside core storage logic. Extract migrations into a versioned system.

Current issues:
- 11 migration functions mixed with core logic
- Hard to see migration history
- Sequential migrations slow database open
- No clear migration versioning

Migration functions to extract:
- `migrateDirtyIssuesTable()`
- `migrateIssueCountersTable()`
- `migrateExternalRefColumn()`
- `migrateCompositeIndexes()`
- `migrateClosedAtConstraint()`
- `migrateCompactionColumns()`
- `migrateSnapshotsTable()`
- `migrateCompactionConfig()`
- `migrateCompactedAtCommitColumn()`
- `migrateExportHashesTable()`
- Plus 1 more (11 total)

Target structure:
```
internal/storage/sqlite/
├── sqlite.go          # Core storage (~800 lines)
├── schema.go          # Table definitions (~200 lines)
├── migrations.go      # Migration orchestration (~200 lines)
└── migrations/        # Individual migrations
    ├── 001_initial_schema.go
    ├── 002_dirty_issues.go
    ├── 003_issue_counters.go
    [... through 011_export_hashes.go]
```

Benefits:
- Clear migration history
- Each migration self-contained
- Easier to review migration changes in PRs
- Future migrations easier to add


Add TestNWayCollision for 5+ clones

## Overview
Add comprehensive tests for N-way (5+) collision resolution to verify the solution scales beyond 3 clones.

## Purpose
While TestThreeCloneCollision validates the basic N-way case, we need to verify:
1. Solution scales to arbitrary N
2. Performance is acceptable with more clones
3. Convergence time is bounded
4. No edge cases in larger collision groups

## Implementation Tasks

### 1. Create TestFiveCloneCollision
File: beads_twoclone_test.go (or new beads_nway_test.go)

```go
func TestFiveCloneCollision(t *testing.T) {
    // Test with 5 clones creating same ID with different content
    // Verify all 5 clones converge after sync rounds

    t.Run("SequentialSync", func(t *testing.T) {
        testNCloneCollision(t, 5, "A", "B", "C", "D", "E")
    })

    t.Run("ReverseSync", func(t *testing.T) {
        testNCloneCollision(t, 5, "E", "D", "C", "B", "A")
    })

    t.Run("RandomSync", func(t *testing.T) {
        testNCloneCollision(t, 5, "C", "A", "E", "B", "D")
    })
}
```

### 2. Implement generalized testNCloneCollision
Generalize the 3-clone test to handle arbitrary N:

```go
func testNCloneCollision(t *testing.T, numClones int, syncOrder ...string) {
    t.Helper()

    if len(syncOrder) != numClones {
        t.Fatalf("syncOrder length (%d) must match numClones (%d)",
            len(syncOrder), numClones)
    }

    tmpDir := t.TempDir()

    // Setup remote and N clones
    remoteDir := setupBareRepo(t, tmpDir)
    cloneDirs := make(map[string]string)

    for i := 0; i < numClones; i++ {
        name := string(rune('A' + i))
        cloneDirs[name] = setupClone(t, tmpDir, remoteDir, name)
    }

    // Each clone creates issue with same ID but different content
    for name, dir := range cloneDirs {
        createIssue(t, dir, fmt.Sprintf("Issue from clone %s", name))
    }

    // Sync in specified order
    for _, name := range syncOrder {
        syncClone(t, cloneDirs[name], name)
    }

    // Final pull for convergence
    for name, dir := range cloneDirs {
        finalPull(t, dir, name)
    }

    // Verify all clones have all N issues
    expectedTitles := make(map[string]bool)
    for i := 0; i < numClones; i++ {
        name := string(rune('A' + i))
        expectedTitles[fmt.Sprintf("Issue from clone %s", name)] = true
    }

    for name, dir := range cloneDirs {
        titles := getTitles(t, dir)
        if !compareTitleSets(titles, expectedTitles) {
            t.Errorf("Clone %s missing issues: expected %v, got %v",
                name, expectedTitles, titles)
        }
    }

    t.Log("✓ All", numClones, "clones converged successfully")
}
```

### 3. Add performance benchmarks
Test convergence time and memory usage:

```go
func BenchmarkNWayCollision(b *testing.B) {
    for _, n := range []int{3, 5, 10, 20} {
        b.Run(fmt.Sprintf("N=%d", n), func(b *testing.B) {
            for i := 0; i < b.N; i++ {
                // Run N-way collision and measure time
                testNCloneCollisionBench(b, n)
            }
        })
    }
}
```

### 4. Add convergence time tests
Verify bounded convergence:

```go
func TestConvergenceTime(t *testing.T) {
    // Test that convergence happens within expected rounds
    // For N clones, should converge in at most N-1 sync rounds

    for n := 3; n <= 10; n++ {
        t.Run(fmt.Sprintf("N=%d", n), func(t *testing.T) {
            rounds := measureConvergenceRounds(t, n)
            maxExpected := n - 1
            if rounds > maxExpected {
                t.Errorf("Convergence took %d rounds, expected ≤ %d",
                    rounds, maxExpected)
            }
        })
    }
}
```

### 5. Add edge case tests
Test boundary conditions:
- All N clones have identical content (dedup works)
- N-1 clones have same content, 1 differs
- All N clones have unique content
- Mix of collisions and non-collisions

## Acceptance Criteria
- TestFiveCloneCollision passes with all sync orders
- All 5 clones converge to identical content
- Performance is acceptable (< 5 seconds for 5 clones)
- Convergence time is bounded (≤ N-1 rounds)
- Edge cases handled correctly
- Benchmarks show scalability to 10+ clones

## Files to Create/Modify
- beads_twoclone_test.go or beads_nway_test.go
- Add helper functions for N-clone setup

## Testing Strategy

### Test Matrix
| N Clones | Sync Orders | Expected Result |
|----------|-------------|-----------------|
| 3        | A→B→C       | Pass            |
| 3        | C→B→A       | Pass            |
| 5        | A→B→C→D→E   | Pass            |
| 5        | E→D→C→B→A   | Pass            |
| 5        | Random      | Pass            |
| 10       | Sequential  | Pass            |

### Performance Targets
- 3 clones: < 2 seconds
- 5 clones: < 5 seconds
- 10 clones: < 15 seconds

## Dependencies
- Requires bd-cbed9619.5, bd-cbed9619.4, bd-cbed9619.3, bd-dcd6f14b to be completed
- TestThreeCloneCollision must pass first

## Success Metrics
- All tests pass for N ∈ {3, 5, 10}
- Convergence time scales linearly (O(N))
- Memory usage reasonable (< 100MB for 10 clones)
- No data corruption or loss in any scenario


CRDT-based architecture for guaranteed convergence (v2.0)

## Vision
Redesign beads around Conflict-Free Replicated Data Types (CRDTs) to provide mathematical guarantees for N-way collision resolution at arbitrary scale.

## Current Limitations
- Content-hash based collision resolution fails at 5+ clones
- Non-deterministic convergence in multi-round scenarios
- UNIQUE constraint violations during rename operations
- No formal proof of convergence properties

## CRDT Benefits
- Provably convergent (Strong Eventual Consistency)
- Commutative/Associative/Idempotent operations
- No coordination required between clones
- Scales to 100+ concurrent workers
- Well-understood mathematical foundations

## Proposed Architecture

### 1. UUID-Based IDs
Replace sequential IDs with UUIDs:
- Current: bd-1c63eb84, bd-9063acda, bd-4d80b7b1
- CRDT: bd-a1b2c3d4-e5f6-7890-abcd-ef1234567890
- Human aliases maintained separately: #42 maps to UUID

### 2. Last-Write-Wins (LWW) Elements
Each field becomes an LWW register:
- title: (timestamp, clone_id, value)
- status: (timestamp, clone_id, value)
- Deterministic conflict resolution via Lamport timestamp + clone_id tiebreaker

### 3. Operation Log
Track all operations as CRDT ops:
- CREATE(uuid, timestamp, clone_id, fields)
- UPDATE(uuid, field, timestamp, clone_id, value)
- DELETE(uuid, timestamp, clone_id) - tombstone, not hard delete

### 4. Sync as Merge
Syncing becomes merging two CRDT states:
- No merge conflicts possible
- Deterministic merge function
- Guaranteed convergence

## Implementation Phases

### Phase 1: Research & Design (4 weeks)
- Study existing CRDT implementations (Automerge, Yjs, Loro)
- Design schema for CRDT-based issue tracking
- Prototype LWW-based Issue CRDT
- Benchmark performance vs current system

### Phase 2: Parallel Implementation (6 weeks)
- Implement CRDT storage layer alongside SQLite
- Build conversion tools: SQLite ↔ CRDT
- Maintain backward compatibility with v1.x format
- Migration path for existing databases

### Phase 3: Testing & Validation (4 weeks)
- Formal verification of convergence properties
- Stress testing with 100+ clone scenario
- Performance profiling and optimization
- Documentation and examples

### Phase 4: Migration & Rollout (4 weeks)
- Release v2.0-beta with CRDT backend
- Gradual migration from v1.x
- Monitoring and bug fixes
- Final v2.0 release

## Risks & Mitigations

**Risk 1: Performance overhead**
- Mitigation: Benchmark early, optimize hot paths
- CRDTs can be slower than append-only logs
- May need compaction strategy

**Risk 2: Storage bloat**
- Mitigation: Implement operation log compaction
- Tombstone garbage collection for deleted issues
- Periodic snapshots to reduce log size

**Risk 3: Breaking changes**
- Mitigation: Maintain v1.x compatibility layer
- Gradual migration tools
- Dual-mode operation during transition

**Risk 4: Complexity**
- Mitigation: Use battle-tested CRDT libraries
- Comprehensive documentation
- Clear migration guide

## Success Criteria
- 100-clone collision test passes without failures
- Formal proof of convergence properties
- Performance within 2x of current system
- Zero manual conflict resolution required
- Backward compatible with v1.x databases

## Timeline
18-20 weeks total (4-5 months)

## References
- Automerge: https://automerge.org
- Yjs: https://docs.yjs.dev
- Loro: https://loro.dev
- CRDT theory: Shapiro et al, A comprehensive study of CRDTs
- Related issues: bd-e6d71828, bd-7a2b58fc,-1


Add sync.branch configuration

Add configuration layer to support sync.branch setting via config file, environment variable, or CLI flag.

Tasks:
- Add sync.branch field to config schema
- Add BEADS_SYNC_BRANCH environment variable
- Add --branch flag to bd init
- Add bd config get/set sync.branch commands
- Validation (branch name format, conflicts)
- Config migration for existing users

Estimated effort: 1-2 days


Document -short flag in testing guide

Add documentation about the -short flag and how it's used to skip slow tests. Should explain that developers can run 'go test -short ./...' for fast iteration and 'go test ./...' for full coverage.


Add tests for internal/utils package

Currently 0.0% coverage. Need tests for utility functions including issue ID parsing and validation.


Improve daemon visibility and status reporting

Add clear daemon status output, uptime reporting, and user-friendly error messages.


Agent 3 Issue 46


Base Issue 4


Agent 1 Batch 9 Issue 2


Agent 3 Batch 17 Issue 2


Agent 5 Issue 19


Agent 3 Issue 86


Batch test 2


Agent 0 Issue 89


Agent 2 Issue 76

Created by agent 2


Agent 8 Issue 70


Agent 6 Issue 74


Agent 3 Batch 14 Issue 2


Agent 2 Batch 39 Issue 2


Agent 7 Issue 72


Agent 0 Issue 48


Agent 4 Issue 60


bd validate - Comprehensive health check

Run all validation checks in one command.

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

Supports --fix-all for auto-repair.

Depends on bd-cbed9619.1, bd-0dcea000, bd-2752a7a2, bd-9826b69a.

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


Base Issue 9


RPC diagnostics: BD_RPC_DEBUG timing logs

Add lightweight diagnostic logging for RPC connection attempts:
- BD_RPC_DEBUG=1 prints to stderr:
  - Socket path being dialed
  - Socket exists check result
  - Dial start/stop time
  - Connection outcome
- Improve bd daemon --status messaging when lock not held

This helps field triage of connection issues without verbose daemon logs.


Agent 4 Issue 32

Created by agent 4


Agent 8 Issue 47


Daemons don't exit when parent process dies, causing accumulation and race conditions

Multiple daemon processes accumulate over time because daemons don't automatically stop when their parent process (e.g., coding agent) is killed. This causes:

1. Race conditions: 8+ daemons watching same .beads/beads.db, each with own 30s debounce timer
2. Git conflicts: Multiple daemons racing to commit/push .beads/issues.jsonl
3. Resource waste: Orphaned daemons from sessions days/hours old still running

Example: User had 8 daemons from multiple sessions (12:37AM, 7:20PM, 7:22PM, 7:47PM, 9:19PM yesterday + 9:54AM, 10:55AM today).

Solutions to consider:
1. Track parent PID and exit when parent dies
2. Use single global daemon instead of per-session
3. Document manual cleanup: pkill -f "bd daemon"
4. Add daemon lifecycle management (auto-cleanup of stale daemons)

Implementation complete:

1. Added ParentPID field to DaemonLockInfo struct (stored in daemon.lock JSON)
2. Daemon now tracks parent PID via os.Getppid() at startup
3. Both event loops (polling and event-driven) check parent process every 10 seconds
4. Daemon gracefully exits if parent process dies (detected via isProcessRunning check)
5. Handles edge cases:
   - ParentPID=0: Older daemons without tracking (ignored)
   - ParentPID=1: Adopted by init means parent died (exits)
   - Otherwise checks if parent process is still running

The fix prevents daemon accumulation by ensuring orphaned daemons automatically exit within 10 seconds of parent death.


Agent 6 Issue 48


Agent 7 Issue 60

Created by agent 7


Agent 4 Issue 91


Agent 6 Issue 43

Created by agent 6


Investigate database pollution - issue count anomalies

Multiple repos showing inflated issue counts suggesting cross-repo pollution:
- ~/src/dave/beads: 895 issues (675 open) - clearly polluted
- ~/src/stevey/src/beads: 280 issues (expected ~209-220) - possibly polluted

Need to investigate:
1. Source of pollution (multi-repo sync issues?)
2. How many duplicate/foreign issues exist
3. Whether recent sync operations caused cross-contamination
4. How to clean up and prevent future pollution

Investigation findings:

**Root cause identified:**
- NOT cross-repo contamination
- NOT automated test leakage (tests properly use t.TempDir())
- Manual testing during template feature development (Nov 2-4)
- Commit ba325a2: "test issues were accidentally committed during template feature development"

**Database growth timeline:**
- Nov 3: 19 issues (baseline)
- Nov 2-5: +244 issues (massive development spike)
- Nov 6-7: +40 issues (continued growth)
- Current: 291 issues → 270 after cleanup

**Test pollution breakdown:**
- 21 issues matching "Test " prefix pattern
- Most created Nov 2-5 during feature development
- Pollution from manual `./bd create "Test issue"` commands in production workspace
- All automated tests properly isolated with t.TempDir()

**Cleanup completed:**
- Ran scripts/cleanup-test-pollution.sh successfully
- Removed 21 test issues
- Database reduced from 291 → 270 issues (7.2% cleanup)
- JSONL synced to git

**Prevention strategy:**
- Filed follow-up issue for prevention mechanisms
- Script can be deleted once prevention is in place
- Tests are already properly isolated - no code changes needed there


Agent 0 New Issue 25


Agent 1 Issue 32


Daemon crashes silently when multiple .db files exist in .beads/

When daemon detects multiple .db files (after filtering out .backup and vc.db files), it writes error details to .beads/daemon-error file before exiting.

The error file is checked when:
1. Daemon discovery fails to connect (internal/daemon/discovery.go)
2. Auto-start fails to yield a running daemon (cmd/bd/main.go)
3. Daemon list shows 'daemon not responding' error

This makes the error immediately visible to users without requiring them to check daemon logs.

File created:  cmd/bd/daemon.go (writes daemon-error on multiple .db detection)
Files modified:
- internal/daemon/discovery.go (reads daemon-error and surfaces in DaemonInfo.Error)
- cmd/bd/main.go (displays daemon-error when auto-start fails)

Testing: Create multiple .db files in .beads/, start daemon, verify error file created and shown in bd daemons list

Root cause: Daemon exits with os.Exit(1) when multiple .db files detected (daemon.go:1381), but error only goes to daemon log file. User sees 'daemon not responding' without knowing why.

Current detection:
- daemon.go filters out .backup and vc.db files
- bd doctor detects multiple databases
- Error message tells user to run 'bd init' or manually remove

Problem: Error is not user-visible unless they check daemon logs.

Proposed fix options:
1. Surface the error in 'bd info' and 'bd daemons list' output
2. Add a hint in error messages to run 'bd doctor' when daemon fails
3. Make daemon write error to a .beads/daemon-error file that gets checked
4. Improve 'bd doctor' to run automatically when daemon is unhealthy


Agent 9 Issue 46


Agent 5 Issue 28

Created by agent 5


Agent 4 Issue 33


Agent 2 Batch 24 Issue 2


Assigned issue


Wrap git operations in GitClient interface

Create internal/daemonrunner/git.go with GitClient interface (HasUpstream, HasChanges, Commit, Push, Pull). Default implementation using os/exec. Use in Syncer and Run loop for testability.


Agent 3 Batch 15 Issue 2


Agent 4 Issue 39

Created by agent 4


Agent 2 Issue 53


Agent 2 Issue 93

Created by agent 2


Agent 1 New Issue 35


Agent 2 Issue 91

Created by agent 2


Agent 5 Issue 62

Created by agent 5


Implement filesystem shims for WASM

WASM needs JS shims for filesystem access. Child of epic bd-44d0.

## Tasks
- [ ] Implement file read/write shims
- [ ] Map WASM syscalls to Node.js fs API
- [ ] Handle .beads/ directory discovery
- [ ] Test with real JSONL files
- [ ] Support both absolute and relative paths

## Technical Notes
- Use Node.js fs module via syscall/js
- Consider MEMFS for in-memory option


Agent 0 Issue 54


Agent 0 Issue 40


Agent 8 Issue 54


Agent 0 Issue 56

Created by agent 0


Agent 6 Issue 85


Agent 2 Batch 39 Issue 1


Agent 6 Issue 31

Created by agent 6


Implement storage driver interface for pluggable backends

Create abstraction layer for storage to support multiple backends (SQLite, Postgres, Turso, in-memory testing, etc.).

**Current state:** All storage logic hardcoded to SQLite in internal/storage/sqlite/sqlite.go

**Proposed design:**

```go
// internal/storage/storage.go
type Store interface {
    // Issue CRUD
    CreateIssue(issue *Issue) error
    GetIssue(id string) (*Issue, error)
    UpdateIssue(id string, updates *Issue) error
    DeleteIssue(id string) error
    ListIssues(filter *Filter) ([]*Issue, error)

    // Dependencies
    AddDependency(from, to string, depType DependencyType) error
    RemoveDependency(from, to string, depType DependencyType) error
    GetDependencies(id string) ([]*Dependency, error)

    // Counters, stats
    GetNextID(prefix string) (string, error)
    GetStats() (*Stats, error)

    Close() error
}
```

**Benefits:**
- Better testing (mock/in-memory stores)
- Future flexibility (Postgres, cloud APIs, etc.)
- Clean architecture (business logic decoupled from storage)
- Enable Turso or other backends without refactoring everything

**Implementation steps:**
1. Define Store interface in internal/storage/storage.go
2. Refactor SQLiteStore to implement interface
3. Update all commands to use interface, not concrete type
4. Add MemoryStore for testing
5. Add driver selection via config (storage.driver = sqlite|turso|postgres)
6. Update tests to use interface

**Note:** This is valuable even without adopting Turso. Good architecture practice.

**Context:** From GH issue #2 RFC evaluation. Driver interface is low-cost, high-value regardless of whether we add alternative backends.


Agent 4 Issue 44

Created by agent 4


Agent 5 Issue 83


Agent 9 Issue 8


Agent 3 Issue 78

Created by agent 3


Agent 7 Issue 0


Agent 0 Issue 98

Created by agent 0


Agent 7 Issue 9

Created by agent 7


Agent 1 Issue 33

Created by agent 1


Agent 9 Issue 48


Agent 3 Issue 53


bd init creates nested .beads directories

bd init sometimes creates .beads/.beads/ nested directories, which should never happen. This occurs fairly often and can cause confusion about which .beads directory is active. Need to add validation to detect if already inside a .beads directory and either error or use the parent .beads location.


Agent 4 Issue 29


Implement ID remapping with reference updates

Allocate new IDs for colliding issues. Update all text field references using word-boundary regex (\bbd-10\b). Update dependency records. Build id_mapping for reporting. Handle chain dependencies properly.


Issue with desc

This is a description


Agent 2 Issue 75


Agent 4 Issue 18


Agent 3 Issue 72

Created by agent 3


Agent 0 Issue 16

Created by agent 0


Agent 0 Issue 66

Created by agent 0


Agent 1 Batch 28 Issue 2


cmd/bd tests fail without -short flag (parallel test deadlock)


Agent 6 Issue 61

Created by agent 6


Event-driven daemon architecture

Replace 5-second polling sync loop with event-driven architecture that reacts instantly to changes. Eliminates stale data issues while reducing CPU ~60%. Key components: FileWatcher (fsnotify), Debouncer (500ms), RPC mutation events, optional git hooks. Target latency: <500ms (vs 5000ms). See event_driven_daemon.md for full design.

## Implementation Progress

**Completed:**
1. ✅ Mutation events infrastructure (bd-143 equivalent)
   - MutationEvent channel in RPC server
   - Events emitted for all write operations: create, update, close, label add/remove, dep add/remove, comment add
   - Non-blocking emission with dropped event counter

2. ✅ FileWatcher with fsnotify (bd-b0c7f7ef related)
   - Watches .beads/issues.jsonl and .git/refs/heads
   - 500ms debounce
   - Polling fallback if fsnotify unavailable

3. ✅ Debouncer (bd-144 equivalent)
   - 500ms debounce for both export and import triggers
   - Thread-safe trigger/cancel

4. ✅ Separate export-only and import-only functions
   - createExportFunc(): exports + optional commit/push (no pull/import)
   - createAutoImportFunc(): pull + import (no export)
   - Target latency <500ms achieved by avoiding full sync

5. ✅ Dropped events safety net (bd-eef03e0a related)
   - Atomic counter tracks dropped mutation events
   - 60-second health check triggers export if events were dropped
   - Prevents silent data loss from event storms

**Still Needed:**
- Platform-specific tests (bd-69bce74a)
- Integration test for mutation→export latency (bd-140)
- Unit tests for FileWatcher (bd-b0c7f7ef)
- Unit tests for Debouncer (bd-144)
- Event storm stress test (bd-eef03e0a)
- Documentation update (bd-142)

**Next Steps:**
Add comprehensive test coverage before enabling events mode by default.


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


Agent 2 Batch 3 Issue 1


Agent 3 Issue 81


Agent 8 Issue 39


Agent 2 Issue 93


Agent 9 Issue 81


Agent 0 Issue 30


Agent 2 Issue 0

Created by agent 2


Agent 0 Batch 10 Issue 2


Agent 9 Issue 90


Agent 2 Issue 58


Agent 5 Issue 42


Agent 1 Issue 28

Created by agent 1


Agent 0 Issue 91

Created by agent 0


Agent 2 Issue 70

Created by agent 2


Agent 3 Issue 34

Created by agent 3


Implement `bd prime` command for AI context loading

Create a `bd prime` command that outputs AI-optimized markdown containing essential Beads workflow context. This provides an alternative to the MCP server for token-conscious users and enables context recovery after compaction/clearing.


Agent 3 Issue 13

Created by agent 3


Agent 1 Issue 26

Created by agent 1


Agent 3 Issue 90

Created by agent 3


Agent 6 Issue 58


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


Agent 4 Issue 35

Created by agent 4


Agent 4 Issue 80

Created by agent 4


Agent 1 Issue 77

Created by agent 1


Agent 3 Issue 59


Agent 0 Issue 40

Created by agent 0


Agent 1 Batch 46 Issue 2


Agent 7 Issue 44

Created by agent 7


Issue 1


Agent 4 Issue 41


Agent 3 Batch 1 Issue 2


Agent 2 Batch 44 Issue 2


Agent 4 Issue 62


Add stale socket and crash recovery for daemon

When daemon crashes (panic, OOM, signal), socket file remains and blocks new daemon start. Users must manually remove .beads/bd.sock.

Problems:
- Socket file remains after crash
- PID file remains (isDaemonRunning false positive)
- No automatic recovery
- Users get 'daemon already running' error

Location: cmd/bd/daemon.go, cmd/bd/main.go:221-311

Oracle code review identified race conditions. Improvements made:
- Moved cleanup AFTER lock acquisition (prevents unlinking live sockets)
- Added PID liveness check before removing socket
- Added stale lock detection with retry
- Tightened directory permissions to 0700
- Improved socket readiness probing with short timeouts
- Made removeOldSocket() ignore ENOENT errors

Changes eliminate race where socket could be removed during daemon startup window.


Agent 4 Issue 30

Created by agent 4


Agent 5 Issue 99

Created by agent 5


Agent 0 Batch 33 Issue 1


Agent 3 Issue 93

Created by agent 3


Agent 2 Issue 99

Created by agent 2


Agents confused by multiple MCP beads servers - use wrong database

When multiple beads MCP servers are configured (e.g., beads-wyvern, beads-adar), agents may use the wrong server and create issues in wrong database. In this session, created wy-22 (wyvern) when working in beads repo. Root cause: All MCP servers available simultaneously with different BEADS_WORKING_DIR/BEADS_DB env vars. Agent must manually choose correct server or use direct bd commands.

This issue is a SYMPTOM of bd-86 (missing CWD propagation). The multi-server workaround (beads-wyvern, beads-adar, etc.) doesn't solve the root cause and creates new problems (agent confusion about which server to use). See bd-86 for comprehensive analysis and architectural solutions. Should be resolved when bd-86 is fixed with Path 1 (SetContext/WhereAmI approach).


Agent 4 Issue 94

Created by agent 4


Agent 8 Issue 12


UX nightmare: multiple ways daemon can fail with misleading messages


Agent 7 Issue 69

Created by agent 7


Agent 2 Issue 30


Agent 3 Batch 32 Issue 2


Fix Homebrew warning about Ruby file location

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


Agent 0 Batch 33 Issue 2


Agent 0 Issue 72

Created by agent 0


Agent 0 Issue 72


Add --resolve-collisions flag and user reporting

Add import flags: --resolve-collisions (auto-fix) and --dry-run (preview). Display clear report: collisions detected, remappings applied (old→new with scores), reference counts updated. Default behavior: fail on collision (safe).


Agent 0 Issue 93

Created by agent 0


Agent 6 Issue 73

Created by agent 6


Audit Current Cache Usage

Understand exactly what code depends on the storage cache

Audit complete. See CACHE_AUDIT.md for full findings.

Summary:
- Cache was already removed in commit 322ab63 (2025-10-28)
- server_cache_storage.go deleted (~286 lines)
- All getStorageForRequest calls replaced with s.storage
- All environment variables removed
- MCP multi-repo works via per-project daemon architecture
- All tests updated and passing
- Only stale comment in server.go needed fixing


Agent 0 Issue 97


Agent 5 Issue 60

Created by agent 5


Agent 4 Issue 95


Agent 1 Issue 36


Agent 6 Issue 22


Agent 7 Issue 71

Created by agent 7


Agent 5 Issue 35


Design hash ID generation algorithm

Design and specify the hash-based ID generation algorithm.

## Requirements
- Deterministic: same inputs → same ID
- Collision-resistant: ~2^32 space for 8-char hex
- Fast: <1μs per generation
- Includes timestamp for uniqueness
- Includes creator/workspace for distributed uniqueness

## Proposed Algorithm
```go
func GenerateIssueID(title, desc string, created time.Time, workspaceID string) string {
    h := sha256.New()
    h.Write([]byte(title))
    h.Write([]byte(desc))
    h.Write([]byte(created.Format(time.RFC3339Nano)))
    h.Write([]byte(workspaceID))
    hash := hex.EncodeToString(h.Sum(nil))
    return "bd-" + hash[:8]  // 8-char prefix = 2^32 space
}
```

## Open Questions
1. 8 chars (2^32) or 16 chars (2^64) for collision resistance?
2. Include priority/type in hash? (Pro: more entropy. Con: immutable)
3. How to handle workspace ID generation? (hostname? UUID?)
4. What if title+desc change? (Answer: ID stays same - hash only used at creation)

## Deliverables
- Design doc: docs/HASH_ID_DESIGN.md
- Collision probability analysis
- Performance benchmarks
- Prototype implementation in internal/types/id_generator.go


Daemon stop has race condition with SIGKILL

When stopping daemon, sometimes see 'Warning: daemon did not stop after 5 seconds, sending SIGKILL' followed by 'Error killing process: os: process already finished'. Indicates timing issue where process exits between check and kill.


Agent 6 Issue 23


Agent 4 Issue 72


Agent 4 Issue 92

Created by agent 4


Agent 2 Issue 29


Agent 3 Issue 75

Created by agent 3


Sync versions to 0.9.2 across all components

Version mismatch discovered: bd CLI is 0.9.2 but other components still at 0.9.0 or 1.0.0.

Current state:
- bd CLI (cmd/bd/version.go): 0.9.2 ✓
- Plugin (.claude-plugin/plugin.json): 0.9.0 ✗
- MCP Server (integrations/beads-mcp): 1.0.0 ✗
- README.md: 0.9.0 ✗

Files to update:
1. .claude-plugin/plugin.json
2. integrations/beads-mcp/pyproject.toml
3. README.md (all mentions)
4. PLUGIN.md (if any mentions)
5. CHANGELOG.md (add 0.9.1 and 0.9.2 entries)

Root cause: Version bumps only updated version.go, not other components.
Solution needed: Script or process to sync versions across all files.


Refactor parseMarkdownFile to reduce cyclomatic complexity

The parseMarkdownFile function in cmd/bd/markdown.go has a cyclomatic complexity of 38, which exceeds the recommended threshold of 30. This makes the function harder to understand, test, and maintain.


Agent 0 Batch 20 Issue 2


Agent 3 Batch 36 Issue 2


Agent 8 Issue 0


Add design/notes/acceptance_criteria fields to update command

Currently bd update only supports status, priority, title, assignee. Add support for --design, --notes, --acceptance-criteria flags. This makes it easier to add detailed designs to issues after creation.


Agent 1 Batch 31 Issue 2


Agent 3 Issue 14


Agent 0 New Issue 5


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

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

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

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


Add template support for issue creation

Support creating issues from predefined templates to streamline common workflows like epics, bug reports, or feature proposals.

Example usage:
  bd create --from-template epic "Phase 3 Features"
  bd create --from-template bug "Login failure"
  bd template list
  bd template create epic

Templates should include:
- Pre-filled description structure
- Suggested priority and type
- Common labels
- Design/acceptance criteria sections

Implementation notes:
- Store templates in .beads/templates/ directory
- Support YAML or JSON format
- Ship with built-in templates (epic, bug, feature)
- Allow custom project-specific templates


Agent 0 Batch 8 Issue 2


Agent 2 Batch 45 Issue 2


Agent 7 Issue 80

Created by agent 7


Agent 5 Issue 37

Created by agent 5


Create Claude Code plugin for beads

Package beads as a Claude Code plugin for easy installation via /plugin command.

Context: GitHub issue #28 - https://github.com/steveyegge/beads/issues/28

Current state:
- MCP server exists in integrations/beads-mcp/
- No plugin packaging yet

Deliverables:
1. .claude-plugin/plugin.json with metadata
2. .claude-plugin/marketplace.json for distribution
3. Custom slash commands (/bd-ready, /bd-create, /bd-show, etc.)
4. Bundle MCP server configuration
5. Optional: Pre-configured hooks for auto-sync
6. Documentation for installation and usage

Benefits:
- Makes beads instantly discoverable in Claude Code ecosystem
- Single-command installation vs. manual setup
- Bundled cohesive experience
- Lowers adoption barrier significantly

References:
- https://www.anthropic.com/news/claude-code-plugins
- https://docs.claude.com/en/docs/claude-code/plugins


Vendor and integrate beads-merge tool

Incorporate @neongreen's beads-merge 3-way merge tool into bd to solve:
- Multi-workspace deletion sync (bd-hv01)
- Git merge conflicts in JSONL
- Field-level intelligent merging

**Repository**: https://github.com/neongreen/mono/tree/main/beads-merge

**Integration approach**: Vendor the Go code with attribution, pending @neongreen's approval (GitHub issue #240)

**Benefits**:
- Prevents deletion resurrection bug
- Smart dependency merging (union + dedup)
- Timestamp handling (max wins)
- Detects deleted-vs-modified conflicts
- Works as git merge driver

**Acceptance criteria**:
- beads-merge code vendored into bd codebase
- Available as `bd merge` command
- Git merge driver setup during `bd init`
- Tests verify 3-way merge logic
- Documentation updated
- @neongreen credited


Agent 6 Issue 83


Agent 3 Issue 16

Created by agent 3


show commit hash in 'bd version' when built from source'


Agent 6 Issue 20


Update AGENTS.md with Agent Mail workflow

Update agent workflow section to include Agent Mail coordination as optional step.

Acceptance Criteria:
- Add Agent Mail to recommended workflow
- Show both with/without examples
- Update "Multi-Agent Patterns" section
- Cross-reference to AGENT_MAIL.md

File: AGENTS.md (lines 468-475)


Fix transaction conflict in TryResurrectParent

Integration test TestImportWithDeletedParent fails with 'database is locked' error when resurrection happens inside CreateIssue.

Root cause: TryResurrectParent calls conn.Get() and insertIssue() which conflicts with existing transaction in CreateIssue.

Error: failed to create tombstone for parent bd-parent: failed to insert issue: sqlite3: database is locked

Solution: Refactor resurrection to accept optional transaction parameter, use existing transaction when available instead of creating new connection.

Impact: Blocks resurrection from working in CreateIssue flow, only works in EnsureIDs (which may not have active transaction).


Agent 5 Issue 73


Agent 3 Batch 43 Issue 2


Agent 8 Issue 5


Agent 9 Issue 72


Add test for deep hierarchy blocking (50+ levels)

Current tests verify 2-level depth (grandparent → parent → child). The depth limit is hardcoded to 50 in the recursive CTE, but we don't test edge cases near that limit.

**Test cases needed:**
1. Verify 50-level deep hierarchy works correctly
2. Verify depth limit prevents runaway recursion
3. Measure performance impact of deep hierarchies
4. Consider if 50 is the right limit (why not 100? why not 20?)

**Rationale:**
- Most hierarchies are 2-5 levels deep
- But pathological cases (malicious or accidental) could create 50+ level nesting
- Need to ensure graceful degradation, not catastrophic failure

**Implementation:**
Add TestDeepHierarchyBlocking to ready_test.go


Agent 3 Batch 34 Issue 2


Agent 2 Issue 14


Agent 3 Batch 42 Issue 2


Update documentation for hash IDs and aliases

Update all documentation to explain hash-based IDs and aliasing system.

## Files to Update

### 1. README.md
Add section explaining hash IDs:
```markdown
## Issue IDs

Beads uses **hash-based IDs** for collision-free distributed issue tracking:

- **Hash ID**: `bd-af78e9a2` (8-char SHA256 prefix, immutable, globally unique)
- **Alias**: `#42` (sequential number, mutable, human-friendly)

### Using IDs
```bash
bd show bd-af78e9a2   # Use hash ID
bd show #42           # Use alias
bd show 42            # Use alias (shorthand)
```

### Why Hash IDs?
- **Collision-free**: Work offline without ID conflicts
- **Distributed**: No coordination needed between clones
- **Git-friendly**: Different IDs = different JSONL lines, fewer merge conflicts

### Aliases
Aliases are workspace-local shortcuts for hash IDs. They're:
- Automatically assigned on issue creation
- Reassigned deterministically on sync (if conflicts)
- Can be manually controlled with `bd alias` commands
```

### 2. AGENTS.md
Update agent workflow:
```markdown
## Hash-Based IDs (v2.0+)

Beads v2.0 uses hash-based IDs to eliminate collision problems:

**When creating issues**:
```bash
bd create "Fix bug" -p 1
# → Creates bd-af78e9a2 with alias #1
```

**When referencing issues**:
- In text: Use hash IDs (stable): "See bd-af78e9a2 for details"
- In CLI: Use aliases (readable): `bd update #42 --status done`

**After sync**:
- Alias conflicts resolved automatically (content-hash ordering)
- No ID collisions possible
- No remapping needed

**Migration from v1.x**:
```bash
bd migrate --hash-ids  # One-time migration
```
```

### 3. QUICKSTART.md (if exists)
Show alias usage in examples:
```bash
# Create issue (gets hash ID + alias)
bd create "Fix authentication bug" -p 1
# → Created bd-af78e9a2 (alias: #1)

# Reference by alias
bd show #1
bd update #1 --status in_progress
bd close #1 --reason "Fixed"
```

### 4. ADVANCED.md
Add section on hash ID internals:
```markdown
## Hash ID Generation

Hash IDs are generated deterministically:

```go
SHA256(title || description || timestamp || workspace_id)[:8]
```

**Collision probability**:
- 8 hex chars = 2^32 space = ~4 billion IDs
- Birthday paradox: 50% collision probability at ~65,000 issues
- For typical projects (<10,000 issues), collision risk is negligible

**Collision detection**:
If a hash collision occurs (extremely rare), beads:
1. Detects on insert (UNIQUE constraint)
2. Appends random suffix: `bd-af78e9a2-a1b2`
3. Retries insert

## Alias Conflict Resolution

When multiple clones assign same alias to different issues:

**Strategy**: Content-hash ordering (deterministic)
- Sort conflicting issue IDs lexicographically
- Lowest hash ID keeps the alias
- Others reassigned to next available aliases

**Example**:
```
Clone A: Assigns #42 to bd-a1b2c3d4
Clone B: Assigns #42 to bd-e5f6a7b8
After sync: bd-a1b2c3d4 keeps #42 (lower hash)
            bd-e5f6a7b8 gets #100 (next available)
```
```

### 5. MIGRATION.md (new file)
```markdown
# Migrating to Hash-Based IDs (v2.0)

## Overview
Beads v2.0 introduces hash-based IDs to eliminate collision problems. This is a **breaking change** requiring migration.

## Migration Steps

### 1. Backup
```bash
cp -r .beads .beads.backup
git commit -am "Pre-migration backup"
```

### 2. Run Migration
```bash
# Dry run first
bd migrate --hash-ids --dry-run

# Apply migration
bd migrate --hash-ids
```

### 3. Commit Changes
```bash
git add .beads/issues.jsonl
git commit -m "Migrate to hash-based IDs (v2.0)"
git push origin main
```

### 4. Coordinate with Collaborators
All clones must migrate before syncing:
1. Notify team: "Migrating to v2.0 on [date]"
2. All collaborators pull latest
3. All run `bd migrate --hash-ids`
4. All push changes
5. Resume normal work

## Rollback
```bash
# Restore backup
mv .beads.backup .beads
bd export  # Regenerate JSONL
git checkout .beads/issues.jsonl
```

## FAQ

**Q: Can I mix v1.x and v2.0 clones?**
A: No. All clones must be on same version.

**Q: Will my old issue IDs work?**
A: No, but aliases preserve the numbers: bd-1c63eb84 → #1

**Q: What happens to links like "see bd-cb64c226.3"?**
A: Migration updates all text references automatically.
```

### 6. CHANGELOG.md
```markdown
## v2.0.0 (YYYY-MM-DD)

### Breaking Changes
- **Hash-based IDs**: Issues now use collision-free hash IDs (bd-af78e9a2)
  instead of sequential IDs (bd-1c63eb84, bd-9063acda)
- **Aliasing system**: Human-friendly aliases (#42) for hash IDs
- **Migration required**: Run `bd migrate --hash-ids` to convert v1.x databases

### Added
- `bd alias` command for manual alias control
- `bd migrate --hash-ids` migration tool
- Alias conflict resolution (deterministic, content-hash ordering)

### Removed
- ID collision detection and resolution (~2,100 LOC)
- `bd import --resolve-collisions` flag (no longer needed)

### Benefits
- ✅ Zero ID collisions in distributed workflows
- ✅ Simpler codebase (-1,350 net LOC)
- ✅ Better git merge behavior
- ✅ True offline-first operation
```

## Testing
- Build docs locally (if using doc generator)
- Check all links work
- Verify examples are correct
- Spellcheck

## Files to Create/Modify
- README.md (hash ID section)
- AGENTS.md (workflow updates)
- ADVANCED.md (internals)
- MIGRATION.md (new)
- CHANGELOG.md (v2.0 entry)
- docs/ (any other docs)


Agent 5 Issue 51


Agent 0 Batch 37 Issue 1


Agent 9 Issue 76


Agent 5 Issue 6

Created by agent 5


Agent 9 Issue 70


Agent 1 Issue 19


Remove unreachable RPC methods

Several RPC server and client methods are unreachable and should be removed:

Server methods (internal/rpc/server.go):
- `Server.GetLastImportTime` (line 2116)
- `Server.SetLastImportTime` (line 2123)
- `Server.findJSONLPath` (line 2255)

Client methods (internal/rpc/client.go):
- `Client.Import` (line 311) - RPC import not used (daemon uses autoimport)

Evidence:
```bash
go run golang.org/x/tools/cmd/deadcode@latest -test ./...
```

Impact: Removes ~80 LOC of unused RPC code


Agent 0 Issue 26


Refactor path canonicalization into helper function

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

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

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

Related to bd-e16b implementation.


Agent 4 New Issue 20


Agent 3 Issue 25


Agent 2 Issue 82


Performance Validation

Confirm no performance regression from cache removal


Agent 9 Issue 86


Agent 3 Batch 27 Issue 1


Agent 1 Issue 42


Agent 1 Issue 74

Created by agent 1


Agent 3 Batch 32 Issue 1


~/src/beads daemon has 'sql: database is closed' errors - zombie daemon


Extract validation functions to validators.go

Move validatePriority, validateStatus, validateIssueType, validateTitle, validateEstimatedMinutes, validateFieldUpdate to validators.go


Agent 6 Issue 13


Agent 0 Batch 8 Issue 1


Agent 8 Issue 71


Agent 8 Issue 11


Agent 2 Issue 21

Created by agent 2


Agent 1 Issue 66

Created by agent 1


Agent 3 Batch 37 Issue 2


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


bd list shows 0 issues despite database containing 115 issues

When running 'bd list --status all' it shows 'Found 0 issues' even though 'bd stats' shows 115 total issues and 'sqlite3 .beads/vc.db "SELECT COUNT(*) FROM issues"' returns 115.

Reproduction:
1. cd ~/src/vc/vc
2. bd stats  # Shows 115 issues
3. bd list --status all  # Shows 0 issues
4. sqlite3 .beads/vc.db 'SELECT COUNT(*) FROM issues;'  # Shows 115

Expected: bd list should show all 115 issues
Actual: Shows 'Found 0 issues:'

This occurs with both /opt/homebrew/bin/bd (v0.9.9) and ~/src/vc/adar/beads/bd (v0.9.10)


Agent 4 Issue 17

Created by agent 4


Agent 1 Batch 41 Issue 1


Agent 3 Batch 30 Issue 1


Agent 3 Issue 25

Created by agent 3


Add UNIQUE constraint on external_ref column

The external_ref column should have a UNIQUE constraint to prevent multiple issues from having the same external reference. This ensures data integrity when syncing from external systems (Jira, GitHub, Linear).

Current behavior:
- Multiple issues can have the same external_ref
- GetIssueByExternalRef returns first match (non-deterministic with duplicates)

Proposed solution:
- Add UNIQUE constraint to external_ref column
- Add migration to check for and resolve existing duplicates
- Update tests to verify constraint enforcement

Related: bd-1022


Agent 1 Batch 2 Issue 2


Agent 2 Issue 57


Add import.orphan_handling config option

Add configuration option to control orphan handling behavior: 'strict' (fail on missing parent, current behavior), 'resurrect' (auto-resurrect from JSONL, recommended default), 'skip' (skip orphaned issues with warning), 'allow' (import orphans without validation). Update CONFIG.md documentation.


Agent 0 Issue 20


Agent 6 Issue 49


Agent 3 Batch 41 Issue 2


Agent 0 Batch 29 Issue 1


Agent 3 Issue 33


Migration tool: sequential → hash IDs

Create migration tool to convert existing sequential-ID databases to hash-ID format.

## Command: bd migrate --hash-ids

```bash
bd migrate --hash-ids [--dry-run]
```

## Migration Process

### 1. Backup Database
```bash
cp .beads/beads.db .beads/beads.db.backup-1761798384
echo "✓ Backup created: .beads/beads.db.backup-1234567890"
```

### 2. Generate Hash IDs for Existing Issues
```go
func migrateToHashIDs(db *SQLiteStorage) error {
    // Read all issues
    issues, err := db.ListIssues(ctx, ListOptions{Status: "all"})

    // Generate mapping: old ID → new hash ID
    mapping := make(map[string]string)
    for _, issue := range issues {
        hashID := GenerateHashID(
            issue.Title,
            issue.Description,
            issue.CreatedAt,
            db.workspaceID,
        )
        mapping[issue.ID] = hashID
    }

    // Detect hash collisions (extremely rare)
    if hasCollisions(mapping) {
        return fmt.Errorf("hash collision detected, aborting")
    }

    return nil
}
```

### 3. Update Database Schema
```sql
-- Add alias column
ALTER TABLE issues ADD COLUMN alias INTEGER UNIQUE;

-- Populate aliases from old IDs
UPDATE issues SET alias = CAST(SUBSTR(id, 4) AS INTEGER)
  WHERE id LIKE 'bd-%' AND SUBSTR(id, 4) GLOB '[0-9]*';

-- Create new issues_new table with hash IDs
CREATE TABLE issues_new (
    id TEXT PRIMARY KEY,  -- Hash IDs now
    alias INTEGER UNIQUE,
    title TEXT NOT NULL,
    -- ... rest of schema
);

-- Copy data with ID mapping
INSERT INTO issues_new SELECT
    <new_hash_id>,  -- From mapping
    alias,
    title,
    -- ...
FROM issues;

-- Drop old table, rename new
DROP TABLE issues;
ALTER TABLE issues_new RENAME TO issues;
```

### 4. Update Dependencies
```sql
-- Update depends_on_id using mapping
UPDATE dependencies
SET issue_id = <new_hash_id>,
    depends_on_id = <new_depends_on_hash_id>
FROM mapping;
```

### 5. Update Text References
```go
// Update all text fields that mention old IDs
func updateTextReferences(db *SQLiteStorage, mapping map[string]string) error {
    for oldID, newID := range mapping {
        // Update description, notes, design, acceptance_criteria
        db.Exec(`UPDATE issues SET
            description = REPLACE(description, ?, ?),
            notes = REPLACE(notes, ?, ?),
            design = REPLACE(design, ?, ?),
            acceptance_criteria = REPLACE(acceptance_criteria, ?, ?)
        `, oldID, newID, oldID, newID, oldID, newID, oldID, newID)
    }
}
```

### 6. Export to JSONL
```bash
bd export  # Writes hash IDs to .beads/issues.jsonl
git add .beads/issues.jsonl
git commit -m "Migrate to hash-based IDs"
```

## Output
```bash
$ bd migrate --hash-ids
Migrating to hash-based IDs...
✓ Backup created: .beads/beads.db.backup-1730246400
✓ 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/issues.jsonl
✓ Migration complete!

Next steps:
  1. Test: bd list, bd show #1, etc.
  2. Commit: git commit -m "Migrate to hash-based IDs"
  3. Push: git push origin main
  4. Notify collaborators to pull and re-init
```

## Dry Run Mode
```bash
$ bd migrate --hash-ids --dry-run
[DRY RUN] Would migrate 150 issues:
  bd-1c63eb84   → bd-af78e9a2  (alias: #1)
  bd-9063acda   → bd-e5f6a7b8  (alias: #2)
  ...
  bd-150 → bd-9a8b7c6d  (alias: #150)

[DRY RUN] Would update:
  - 150 issue IDs
  - 87 dependencies
  - 234 text references in descriptions/notes

No changes made. Run without --dry-run to apply.
```

## Files to Create
- cmd/bd/migrate.go (new command)
- internal/storage/sqlite/migrations/hash_ids.go

## Testing
- Test migration on small database (10 issues)
- Test migration on large database (1000 issues)
- Test hash collision detection (inject collision artificially)
- Test text reference updates
- Test rollback (restore from backup)
- Test migrated database works correctly

## Rollback Procedure
```bash
# If migration fails or has issues
mv .beads/beads.db.backup-1234567890 .beads/beads.db
bd export  # Restore JSONL from backup DB
```

## Multi-Clone Coordination
**Important**: All clones must migrate before syncing:

1. Coordinator sends message: "Migrating to hash IDs on 2025-10-30 at 10:00 UTC"
2. All collaborators pull latest changes
3. All run: `bd migrate --hash-ids`
4. All push changes
5. New work can continue with hash IDs

**Do NOT**:
- Mix sequential and hash IDs in same database
- Sync before all clones migrate


Agent 4 Issue 15

Created by agent 4


Agent 0 Issue 89

Created by agent 0


Agent 2 Issue 65

Created by agent 2


Fix TestTwoCloneCollision timeout


Agent 0 Issue 18

Created by agent 0


Agent 5 Issue 92

Created by agent 5


Agent 0 Issue 91


Agent 0 Issue 74

Created by agent 0


Agent 1 Batch 3 Issue 2


Agent 2 Batch 9 Issue 1


Agent 4 Issue 77


Agent 5 Issue 61


Integrate beads-merge tool by @neongreen

**Context**: @neongreen built a production-ready 3-way merge tool for JSONL files that works with both Git and Jujutsu. This is superior to our planned bd resolve-conflicts because it prevents conflicts proactively instead of resolving them after the fact.

**Tool**: https://github.com/neongreen/mono/tree/main/beads-merge

**What it does**:
- 3-way merge of JSONL files (base, left, right)
- Field-level merging (titles, status, priority, etc.)
- Smart dependency merging (union + dedup)
- Conflict markers for unresolvable conflicts
- Exit code 1 for conflicts (standard)

**Integration options**:

1. **Recommend (minimal effort)** - Document in AGENTS.md + TROUBLESHOOTING.md
2. **Bundle binary** - Include in releases (cross-platform builds)
3. **Port to Go** - Reimplement in bd codebase
4. **Auto-install hook** - During bd init, offer to install merge driver

**Recommendation**: Start with option 1 (document), then option 2 (bundle) once proven.

**Related**: bd-5f483051 (bd resolve-conflicts - can close as superseded)

Created GitHub issue to discuss integration approach with @neongreen: https://github.com/neongreen/mono/issues/240

Awaiting their preference on:
1. Vendor with attribution (fastest)
2. Extract as importable module (best long-term)
3. Keep as separate tool (current state)

Next: Wait for response before proceeding with integration.

UPDATE 2025-11-06: @neongreen gave permission to vendor! Quote: "I switched from beads to my own thing (tk) so I'm very happy to give beads-merge away — feel free to move it into the beads repo and I will point mono's readme to beads"

Next: Vendor beads-merge with full attribution


Agent 1 Batch 17 Issue 2


Agent 2 Issue 38


Agent 0 Issue 71


Add --show-all-paths flag to bd dep tree

Currently bd dep tree deduplicates nodes when multiple paths exist (diamond dependencies). Add optional --show-all-paths flag to display the full graph with all paths, showing duplicates. Useful for debugging complex dependency structures and understanding all relationships.


Agent 3 Issue 28

Created by agent 3


Agent 0 Issue 45


Agent 3 Issue 29


Agent 2 Issue 23

Created by agent 2


Agent 1 Batch 36 Issue 2


Agent 5 New Issue 45


Agent 4 Issue 69


Batch test 3


Agent 1 Issue 98

Created by agent 1


Agent 1 Issue 99

Created by agent 1


Another explicit ID


Agent 2 Issue 74

Created by agent 2


Agent 4 Issue 33

Created by agent 4


Agent 6 Issue 42


Agent 2 Issue 9


Need comprehensive daemon health check command (bd daemon doctor?)


Agent 6 Issue 45

Created by agent 6


Agent 2 Issue 86


Agent 1 Issue 43

Created by agent 1


Add MCP server functions for repair commands

Expose new repair commands via MCP server for agent access:

Functions to add:
- beads_repair_deps()
- beads_detect_pollution()
- beads_validate()
- beads_resolve_conflicts() (when implemented)

Update integrations/beads-mcp/src/beads_mcp/server.py

See repair_commands.md lines 803-884 for design.

Implemented all three MCP server functions:

1. **repair_deps(fix=False)** - Find/fix orphaned dependencies
2. **detect_pollution(clean=False)** - Detect/clean test issues
3. **validate(checks=None, fix_all=False)** - Run comprehensive health checks

Changes:
- Added abstract methods to BdClientBase
- Implemented in BdCliClient (CLI execution)
- Added NotImplementedError stubs in BdDaemonClient (falls back to CLI)
- Created wrapper functions in tools.py
- Registered @mcp.tool decorators in server.py

All commands tested and working with --no-daemon flag.


Agent 1 Issue 32

Created by agent 1


bd-hv01: Missing cleanup of .merged temp file on failure

Problem: deletion_tracking.go:49 creates tmpMerged file but does not clean up on failure, causing disk space leak and potential interference with subsequent syncs.

Fix: Add defer os.Remove(tmpMerged) after creating temp file path.

Files: cmd/bd/deletion_tracking.go:38-89


Cache getMultiRepoJSONLPaths() result during sync to avoid redundant calls

From bd-xo6b code review: getMultiRepoJSONLPaths() is called 3x per sync cycle.

**Current behavior:**
daemon_sync.go calls getMultiRepoJSONLPaths() three times per sync:
- Line 505: Snapshot capture before pull
- Line 575: Merge/prune after pull
- Line 613: Base snapshot update after import

**Cost per call:**
- Config lookup (likely cached, but still overhead)
- Path construction: O(N) where N = number of repos
- String allocations: (N + 1) × filepath.Join() calls

**Total per sync:** 3N path constructions + 3 config lookups + 3 slice allocations

**Impact:**
- For N=3 repos: Negligible (< 1ms)
- For N=10 repos: Still minimal
- For N=100+ repos: Wasteful

**Solution:**
Call once at sync start, reuse result:

```go
func createSyncFunc(...) func() {
    return func() {
        // ... existing setup ...

        // Call once at start
        multiRepoPaths := getMultiRepoJSONLPaths()

        // Snapshot capture
        if multiRepoPaths != nil {
            for _, path := range multiRepoPaths {
                if err := captureLeftSnapshot(path); err != nil { ... }
            }
        }

        // ... later ...

        // Merge/prune - reuse same paths
        if multiRepoPaths != nil {
            for _, path := range multiRepoPaths { ... }
        }

        // ... later ...

        // Base snapshot update - reuse same paths
        if multiRepoPaths != nil {
            for _, path := range multiRepoPaths { ... }
        }
    }
}
```

**Files:**
- cmd/bd/daemon_sync.go:449-636 (createSyncFunc)

**Note:** This is a performance optimization, not a correctness fix. Low priority unless multi-repo usage scales significantly.


Agent 5 New Issue 20


Agent 6 Issue 72


Agent 3 New Issue 25


Agent 1 Batch 26 Issue 2


Agent 6 Issue 78


Agent 1 Batch 5 Issue 2


Agent 3 Issue 20

Created by agent 3


Agent 3 Issue 6

Created by agent 3


Agent 5 Issue 99


Add `bd merge` command wrapping 3-way merge logic

Implement CLI command to invoke beads-merge functionality.

**Interface**:
```bash
bd merge <output> <base> <left> <right>
bd merge --debug <output> <base> <left> <right>
```

**Behavior**:
- Exit code 0 on clean merge
- Exit code 1 if conflicts (write conflict markers)
- Support --debug flag for verbose output
- Match beads-merge's existing behavior

**File**: `cmd/bd/merge.go`


Agent 1 Issue 25


File change test issue


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.


Agent 7 Issue 65

Created by agent 7


Agent 3 Issue 74


Agent 5 Issue 6


Agent 1 Batch 0 Issue 1


Agent 6 Issue 75


Agent 9 Issue 79


Agent 7 Issue 28

Created by agent 7


Agent 5 Issue 22


Agent 3 Issue 3


Agent 8 Issue 88


Add integration tests for multi-repo sync

Test: Clone A deletes issue, Clone B imports Clone A's JSONL. Verify Clone B handles deletion gracefully with resurrection. Test concurrent imports with same orphans (should be idempotent). Test round-trip fidelity (export→delete parent→import→verify structure).


Agent 2 Batch 47 Issue 1


Agent 4 Issue 80


Agent 2 Issue 40


Agent 0 Issue 85


Replace getStorageForRequest with Direct Access

Replace all getStorageForRequest(req) calls with s.storage


Agent 5 Issue 52


Agent 2 Issue 61

Created by agent 2


Agent 4 Issue 11


Agent 1 Batch 24 Issue 1


Agent 3 Batch 8 Issue 1


Agent 1 Issue 54


Agent 3 Issue 77

Created by agent 3


Agent 2 Issue 54


Agent 9 Issue 36


Agent 0 Batch 37 Issue 2


Test issue 1


Agent 4 Issue 10

Created by agent 4


Agent 3 Issue 1


Agent 3 Batch 14 Issue 1


Agent 6 Issue 9

Created by agent 6


Agent 3 Batch 47 Issue 1


Agent 1 Issue 97


Detect and warn about outdated git hooks

Users may have outdated git hooks installed that reference removed flags (e.g., --resolve-collisions). bd should detect this and warn users to reinstall.


Task A under epic


Agent 5 Issue 71


Agent 1 Batch 29 Issue 2


Agent 7 Issue 20

Created by agent 7


Agent 3 Batch 28 Issue 1


Agent 0 Issue 48

Created by agent 0


Agent 2 Batch 47 Issue 2


Agent 0 Batch 24 Issue 1


Agent 3 Issue 50

Created by agent 3


Agent 7 Issue 90


Agent 2 Issue 16


Agent 2 Issue 88

Created by agent 2


CI failing on all 3/4 test jobs despite individual tests passing

CI has been broken for a day+ with mysterious test failures. Issue #173 on GitHub tracks this.

## Current Status
- **Lint job**: ✅ PASSING
- **Test (Linux)**: ❌ FAILING (exit code 1)
- **Test (Windows)**: ❌ FAILING (exit code 1)
- **Test Nix Flake**: ❌ FAILING (exit code 1)

## Key Observations
All three failing jobs show identical pattern:
- Individual test output shows PASS for every test
- Final result: `FAIL github.com/steveyegge/beads/cmd/bd`
- Exit code 1 despite no visible test failures
- Last visible test output before failure: "No Reason Issue" test (TestCloseCommand/close_without_reason)

## Investigation So Far
1. All tests appear to pass when examined individually
2. Likely causes:
   - Race detector finding data races during test cleanup (`-race` flag)
   - Panic/error occurring after main tests complete
   - Test harness issue not reporting actual failure
   - Possible regression from PR #203 (dependency_type changes)

## Recent CI Runs
- Run 19015040655 (latest): 3/4 failing
- Multiple recent commits tried to fix Windows/lint issues
- Agent on rrnewton/beads fork attempting fixes (2/4 passing there)

## Next Steps
1. Run tests locally with `-race -v` to see full output
2. Check for unreported test failures or panics
3. Examine test cleanup/teardown code
4. Review recent changes around close command tests
5. Consider if race detector is too sensitive or catching real issues

## Progress Update

### ✅ Fixed (commits 09bd4d3, 21a29bc)
1. **Daemon auto-import** - Always recompute content_hash in importer to avoid stale hashes
2. **TestScripts failures** - Added bd binary to PATH for shell subprocess tests
3. **Test infrastructure** - Added .gitignore to test repos, fixed last_import_time metadata

### ✅ CI Status (Run 19015638968)
- **Test (Linux)**: ✅ SUCCESS - All tests passing
- **Test (Windows)**: ❌ FAILURE - Pre-existing Windows test failures
- **Test Nix Flake**: ❌ FAILURE - Build fails with same test errors
- **Lint**: ❌ FAILURE - Pre-existing issue in migrate.go:647

### ❌ Remaining Issues (not related to original bd-1231)

**Windows failures:**
- TestFindDatabasePathEnvVar
- TestHashIDs_MultiCloneConverge
- TestHashIDs_IdenticalContentDedup
- TestDatabaseReinitialization (5 subtests)
- TestFindBeadsDir_NotFound
- TestMetricsSnapshot/uptime

**Lint failure:**
- cmd/bd/migrate.go:647:37: cleanupWALFiles - result 0 (error) is always nil (unparam)

**Nix failure:**
- Build fails during test phase with same test errors

### Next Steps
1. Investigate Windows-specific test failures
2. Fix linting issue in migrate.go
3. Debug Nix build test failures


Agent 9 Issue 54


Agent 1 New Issue 40


Remove unreachable RPC methods

Several RPC server and client methods are unreachable and should be removed:

Server methods (internal/rpc/server.go):
- `Server.GetLastImportTime` (line 2116)
- `Server.SetLastImportTime` (line 2123)
- `Server.findJSONLPath` (line 2255)

Client methods (internal/rpc/client.go):
- `Client.Import` (line 311) - RPC import not used (daemon uses autoimport)

Evidence:
```bash
go run golang.org/x/tools/cmd/deadcode@latest -test ./...
```

Impact: Removes ~80 LOC of unused RPC code


Agent 3 Batch 21 Issue 2


bd-hv01: Storage backend extensibility broken by type assertion

Problem: deletion_tracking.go:69-82 uses type assertion for DeleteIssue which breaks if someone adds a new storage backend.

Fix: Check capability before starting merge or add DeleteIssue to Storage interface.

Files: cmd/bd/deletion_tracking.go:69-82, internal/storage/storage.go


Agent 5 Issue 82


Agent 6 Issue 71


Agent 4 Issue 85


Agent 2 Batch 12 Issue 1


Agent 9 Issue 51


Agent 1 Issue 27


Agent 4 Issue 79


Test database naming


Agent 7 Issue 79


Agent 1 Batch 34 Issue 1


bd-hv01: Refactor snapshot management into dedicated module

Problem: Snapshot logic is scattered across deletion_tracking.go. Would benefit from abstraction with SnapshotManager type.

Benefits: cleaner separation of concerns, easier to test in isolation, better encapsulation, could add observability/metrics.

Suggested improvements: add magic constants, track merge statistics, better error messages.

Files: cmd/bd/deletion_tracking.go (refactor into new snapshot_manager.go)


Refactor sqlite.go into focused modules

Split sqlite.go (2,298 lines) into focused modules: migrations.go, ids.go, issues.go, events.go, dirty.go, db.go. This will improve maintainability and reduce cognitive load.


Sub-task under A


Add comprehensive daemon tests for RPC integration

Add tests for:
- RPC server integration (daemon accepts connections)
- Concurrent client operations
- Socket cleanup on shutdown
- Server start failures (socket already exists)
- Graceful shutdown verification

These tests were identified in bd-83 code review but not implemented yet.


Agent 0 Issue 46

Created by agent 0


Fix autoimport tests for content-hash collision scoring

## Overview
Three autoimport tests are failing after [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`


Agent 4 Issue 54


bd-hv01: Race condition with concurrent snapshot operations

## Problem
Snapshot files have no locking. Multiple processes can call captureLeftSnapshot simultaneously:

1. Process A: export → begins snapshot
2. Process B: export → begins snapshot
3. Process A: writes partial left.jsonl
4. Process B: overwrites with its left.jsonl
5. Process A: completes merge with wrong snapshot

## Impact
- Data corruption in multi-process scenarios
- Daemon + manual sync race
- Multiple git clones on same filesystem

## Fix
Use atomic file operations with process-specific temp files:
```go
func captureLeftSnapshot(jsonlPath string) error {
    _, leftPath := getSnapshotPaths(jsonlPath)
    tempPath := fmt.Sprintf("%s.%d.tmp", leftPath, os.Getpid())
    if err := copyFileSnapshot(jsonlPath, tempPath); err != nil {
        return err
    }
    return os.Rename(tempPath, leftPath) // Atomic on POSIX
}
```

## Files Affected
- cmd/bd/deletion_tracking.go:24-29 (captureLeftSnapshot)
- cmd/bd/deletion_tracking.go:31-36 (updateBaseSnapshot)


Agent 0 Issue 87

Created by agent 0


Fix N-way collision convergence

Epic to fix the N-way collision convergence problem documented in n-way-collision-convergence.md.

## Problem Summary
The current collision resolution implementation works correctly for 2-way collisions but does not converge for 3-way (and by extension N-way) collisions. TestThreeCloneCollision demonstrates this with reproducible failures.

## Root Causes Identified
1. Pairwise resolution doesn't scale - each clone makes local decisions without global context
2. DetectCollisions modifies state during detection (line 83-86 in collision.go)
3. No remapping history - can't track transitive remap chains (test-1 → test-2 → test-3)
4. Import-time resolution is too late - happens after git merge

## Solution Architecture
Replace pairwise resolution with deterministic global N-way resolution using:
- Content-addressable identity (content hashing)
- Global collision resolution (sort all versions by hash)
- Read-only detection phase (separate from modification)
- Idempotent imports (content-first matching)

## Success Criteria
- TestThreeCloneCollision passes without skipping
- All clones converge to identical content after final pull
- No data loss (all issues present in all clones)
- Works for N workers (test with 5+ clones)
- Idempotent imports (importing same JSONL multiple times is safe)

## Implementation Phases
See child issues for detailed breakdown of each phase.


Agent 6 Issue 94

Created by agent 6


Agent 3 Issue 4

Created by agent 3


Agent 0 Batch 40 Issue 1


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.


Agent 2 Issue 71


Agent 7 Issue 85

Created by agent 7


Agent 4 Issue 9


Agent 9 Issue 67


Agent 6 Issue 33


Agent 5 Issue 95

Created by agent 5


Agent 4 New Issue 40


Agent 3 Batch 29 Issue 1


Agent 2 Issue 42


Agent 1 Batch 44 Issue 1


URGENT: main branch has failing tests (syncbranch migration error)

The main branch has failing tests that are blocking CI for all PRs.

## Problem
All syncbranch_test.go tests failing with:
"migration external_ref_column failed: failed to create index on external_ref: sqlite3: SQL logic error: no such table: main.issues"

## Evidence
- Last 5 CI runs on main: ALL FAILED
- Tests fail locally on current main (bd6dca5)
- Affects: TestGet, TestSet, TestUnset in internal/syncbranch

## Impact
- Blocking all PR merges
- CI shows red for all branches
- Can't trust test results

## Root Cause
Migration order issue - trying to create index on external_ref column before the issues table exists, or before the external_ref column is added to the issues table.

## Quick Fix Needed
Need to investigate migration order in internal/storage/sqlite/migrations.go and ensure:
1. issues table is created first
2. external_ref column is added to issues table
3. THEN index on external_ref is created

This is CRITICAL - main should never have breaking tests.


Agent 9 Issue 42


Agent 0 Issue 57


Agent 6 Issue 98


Agent 7 Issue 24


Make DetectCollisions read-only (separate detection from modification)

## Overview
Phase 2: Separate collision detection from state modification to enable safe, composable collision resolution.

## Current Problem
DetectCollisions (collision.go:38-111) modifies database state during detection:
- Line 83-86: Deletes issues when content matches but ID differs
- This violates separation of concerns
- Causes race conditions when processing multiple issues
- Makes contentToDBIssue map stale after first deletion
- Partial failures leave DB in inconsistent state

## Solution
Make DetectCollisions purely read-only. Move all modifications to a separate ApplyCollisionResolution function.

## Implementation Tasks

### 1. Add RenameDetail to CollisionResult
File: internal/storage/sqlite/collision.go
```go
type CollisionResult struct {
    ExactMatches []string
    Collisions   []*CollisionDetail
    NewIssues    []string
    Renames      []*RenameDetail  // NEW
}

type RenameDetail struct {
    OldID string        // ID in database
    NewID string        // ID in incoming
    Issue *types.Issue  // The issue with new ID
}
```

### 2. Remove deletion from DetectCollisions
Replace lines 83-86:
```go
// OLD (DELETE THIS):
if err := s.DeleteIssue(ctx, dbMatch.ID); err != nil {
    return nil, fmt.Errorf("failed to delete renamed issue...")
}

// NEW (ADD THIS):
result.Renames = append(result.Renames, &RenameDetail{
    OldID: dbMatch.ID,
    NewID: incoming.ID,
    Issue: incoming,
})
continue  // Don't mark as NewIssue yet
```

### 3. Create ApplyCollisionResolution function
New function to apply all modifications atomically:
```go
func ApplyCollisionResolution(ctx context.Context, s *SQLiteStorage,
    result *CollisionResult, mapping map[string]string) error {

    // Phase 1: Handle renames (delete old IDs)
    for _, rename := range result.Renames {
        if err := s.DeleteIssue(ctx, rename.OldID); err != nil {
            return fmt.Errorf("failed to delete renamed issue %s: %w",
                rename.OldID, err)
        }
    }

    // Phase 2: Create new IDs (from mapping)
    // Phase 3: Update references
    return nil
}
```

### 4. Update callers to use two-phase approach
File: internal/importer/importer.go (handleCollisions)
```go
// Phase 1: Detect (read-only)
collisionResult, err := sqlite.DetectCollisions(ctx, sqliteStore, issues)

// Phase 2: Resolve (compute mapping)
mapping, err := sqlite.ResolveNWayCollisions(ctx, sqliteStore, collisionResult)

// Phase 3: Apply (modify DB)
err = sqlite.ApplyCollisionResolution(ctx, sqliteStore, collisionResult, mapping)
```

### 5. Update tests
- Verify DetectCollisions doesn't modify DB
- Test ApplyCollisionResolution separately
- Add test for rename detection without modification

## Acceptance Criteria
- DetectCollisions performs zero writes to database
- DetectCollisions returns RenameDetail entries for content matches
- ApplyCollisionResolution handles all modifications
- All existing tests still pass
- New test verifies read-only detection
- contentToDBIssue map stays consistent throughout detection

## Files to Modify
- internal/storage/sqlite/collision.go (DetectCollisions, new function)
- internal/importer/importer.go (handleCollisions caller)
- internal/storage/sqlite/collision_test.go (add tests)

## Testing
- Unit test: DetectCollisions with content match doesn't delete DB issue
- Unit test: RenameDetail correctly populated
- Unit test: ApplyCollisionResolution applies renames
- Integration test: Full flow still works end-to-end

## Risk Mitigation
This is a significant refactor of core collision logic. Recommend:
1. Add comprehensive tests before modifying
2. Use feature flag to enable/disable new behavior
3. Test thoroughly with TestTwoCloneCollision first


Agent 5 Issue 83

Created by agent 5


Agent 8 Issue 51


Agent 8 Issue 69


Agent 9 Issue 43


Agent 3 Issue 90


Agent 5 Issue 54


Add docs/architecture/event_driven.md

Copy event_driven_daemon.md into docs/ folder. Add to documentation index.


Agent 2 Issue 16

Created by agent 2


Show dependency status in bd show output

When bd show displays dependencies and dependents, include their status (open/closed/in_progress/blocked) for quick progress tracking. Improves context rebuilding and planning.


Test RPC mutation event


Agent 8 Issue 59


Agent 6 Issue 50

Created by agent 6


Agent 1 Issue 4


Agent 3 Batch 25 Issue 1


Agent 3 Issue 12


Add WaitGroup tracking to FileWatcher goroutines

FileWatcher spawns goroutines without WaitGroup tracking, causing race condition on shutdown.

Location: cmd/bd/daemon_watcher.go:123-182, 215-291

Problem:
- Goroutines spawned without sync.WaitGroup
- Close() cancels context but doesn't wait for goroutines to exit
- Race condition: goroutine may access fw.debouncer during Close() cleanup
- No guarantee goroutine stopped before fw.watcher.Close() is called

Solution:
- Add sync.WaitGroup field to FileWatcher
- Track goroutines with wg.Add(1) and defer wg.Done()
- Call wg.Wait() in Close() before cleanup

Impact: Race condition on daemon shutdown; potential panic

Effort: 2 hours


Agent 1 Issue 59


Implement content-first idempotent import

## Overview
Phase 4: Refactor import to be content-first and idempotent, ensuring importing same JSONL multiple times always converges correctly.

## Current Problem
Current import is ID-first:
1. Look up by ID
2. If exists, update
3. If not exists, create

This causes issues when:
- Same content arrives with different IDs (renames not detected)
- Multiple rounds of import needed for convergence
- Import order affects final state

## Solution
Make import content-first and idempotent:
1. Hash all incoming and existing issues
2. Match by content hash first (detect renames)
3. Handle ID conflicts second (using global resolution)
4. Ensure importing same data multiple times = no-op

## Implementation Tasks

### 1. Refactor ImportIssues to be content-first
File: internal/importer/importer.go

```go
func ImportIssues(ctx context.Context, dbPath string, store storage.Storage,
    issues []*types.Issue, opts Options) (*Result, error) {

    result := &Result{...}

    sqliteStore, needCloseStore, err := getOrCreateStore(ctx, dbPath, store)
    if err != nil {
        return nil, err
    }
    if needCloseStore {
        defer func() { _ = sqliteStore.Close() }()
    }

    // Phase 1: Compute content hashes for all incoming issues
    for _, issue := range issues {
        issue.ContentHash = issue.ComputeContentHash()
    }

    // Phase 2: Build content hash maps
    incomingByHash := buildHashMap(issues)
    dbIssues, _ := sqliteStore.SearchIssues(ctx, "", types.IssueFilter{})
    dbByHash := buildHashMap(dbIssues)
    dbByID := buildIDMap(dbIssues)

    // Phase 3: Content-first matching
    var newIssues []*types.Issue
    var idConflicts []*CollisionDetail

    for hash, incoming := range incomingByHash {
        if existing, found := dbByHash[hash]; found {
            // Same content exists
            if existing.ID == incoming.ID {
                // Exact match - idempotent case
                result.Unchanged++
            } else {
                // Same content, different ID - rename detected
                // Delete old ID, keep new ID (incoming is canonical)
                if err := handleRename(ctx, sqliteStore, existing, incoming); err != nil {
                    return nil, err
                }
                result.Updated++
            }
        } else {
            // New content - check for ID collision
            if existingWithID, found := dbByID[incoming.ID]; found {
                // ID exists but different content - collision
                idConflicts = append(idConflicts, &CollisionDetail{
                    ID:            incoming.ID,
                    IncomingIssue: incoming,
                    ExistingIssue: existingWithID,
                })
            } else {
                // Truly new issue
                newIssues = append(newIssues, incoming)
            }
        }
    }

    // Phase 4: Resolve ID conflicts using global algorithm
    if len(idConflicts) > 0 {
        if !opts.ResolveCollisions {
            return nil, fmt.Errorf("collision detected")
        }

        idMapping, err := sqlite.ResolveNWayCollisions(ctx, sqliteStore,
            idConflicts, issues)
        if err != nil {
            return nil, err
        }

        if err := applyIDMapping(ctx, sqliteStore, idMapping); err != nil {
            return nil, err
        }

        result.IDMapping = idMapping
        result.Collisions = len(idConflicts)
    }

    // Phase 5: Create new issues
    if len(newIssues) > 0 {
        if err := sqliteStore.CreateIssues(ctx, newIssues, "import"); err != nil {
            return nil, err
        }
        result.Created = len(newIssues)
    }

    // Phase 6: Import dependencies, labels, comments (existing logic)
    // ...

    return result, nil
}
```

### 2. Implement helper functions

```go
// buildHashMap creates a map of content hash → issue
func buildHashMap(issues []*types.Issue) map[string]*types.Issue {
    result := make(map[string]*types.Issue)
    for _, issue := range issues {
        result[issue.ContentHash] = issue
    }
    return result
}

// buildIDMap creates a map of ID → issue
func buildIDMap(issues []*types.Issue) map[string]*types.Issue {
    result := make(map[string]*types.Issue)
    for _, issue := range issues {
        result[issue.ID] = issue
    }
    return result
}

// handleRename handles content match with different IDs
func handleRename(ctx context.Context, s *SQLiteStorage,
    existing *types.Issue, incoming *types.Issue) error {

    // Delete old ID
    if err := s.DeleteIssue(ctx, existing.ID); err != nil {
        return fmt.Errorf("failed to delete old ID %s: %w", existing.ID, err)
    }

    // Create with new ID
    if err := s.CreateIssue(ctx, incoming, "import-rename"); err != nil {
        return fmt.Errorf("failed to create renamed issue %s: %w",
            incoming.ID, err)
    }

    // Update references from old ID to new ID
    idMapping := map[string]string{existing.ID: incoming.ID}
    return updateReferences(ctx, s, idMapping)
}
```

### 3. Add idempotency tests

Test cases:
1. Import same JSONL twice → second import reports all Unchanged
2. Import, modify DB, import again → reports Updated
3. Import with rename, import again → idempotent
4. Import with collision resolution, import again → idempotent

### 4. Update handleCollisions to use new flow
Current handleCollisions in importer.go needs to be updated to:
- Use content-first matching
- Call new ResolveNWayCollisions
- Apply results using ApplyCollisionResolution

## Acceptance Criteria
- Import matches by content hash before checking IDs
- Importing same JSONL multiple times is idempotent (reports Unchanged)
- Rename detection works (same content, different ID)
- ID conflicts resolved using global algorithm
- Result.Unchanged correctly tracks idempotent imports
- TestThreeCloneCollision passes
- All existing import tests still pass

## Testing Strategy

### Unit Tests
- buildHashMap correctly indexes by content hash
- buildIDMap correctly indexes by ID
- handleRename deletes old, creates new, updates references

### Integration Tests
- Import same data twice → idempotent
- Import renamed issue → handled correctly
- Import with collision → resolved globally
- Final pull after 3-way collision → all clones converge

### Property Tests
- Idempotency: Import(x); Import(x) ≡ Import(x)
- Commutativity: Import(a); Import(b) ≡ Import(b); Import(a) (for non-colliding issues)
- Convergence: After N rounds of sync, all clones identical

## Files to Modify
- internal/importer/importer.go (major refactor of ImportIssues)
- internal/importer/importer_test.go (new tests)
- cmd/bd/import_bug_test.go (update for new behavior)

## Dependencies
- Requires bd-cbed9619.5 (ContentHash field)
- Requires bd-cbed9619.4 (read-only detection)
- Requires bd-cbed9619.3 (global resolution)

## Risk Mitigation
Major refactor of import logic. Recommend:
1. Comprehensive tests before modifying
2. Feature flag to enable/disable
3. Keep old import code path for rollback
4. Test with all existing import tests
5. Manual testing with real repositories

## Success Metrics
After this phase:
- TestThreeCloneCollision should PASS
- All clones converge after final pull
- Import is demonstrably idempotent
- No data loss in N-way scenarios


bd-hv01: Brittle string comparison breaks with JSON field reordering

## Problem
deletion_tracking.go:125 uses string comparison to detect unchanged issues:

```go
if leftLine, existsInLeft := leftIndex[id]; existsInLeft && leftLine == baseLine {
    deletions = append(deletions, id)
}
```

This breaks if:
- JSON field order changes (legal in JSON)
- Timestamps updated by import/export
- Whitespace/formatting changes
- Floating point precision varies

## Example Failure
```json
// baseLine
{"id":"bd-1","priority":1,"status":"open"}
// leftLine (same data, different order)
{"id":"bd-1","status":"open","priority":1}
```
These are semantically identical but string comparison fails.

## Fix
Parse and compare JSON semantically:
```go
func jsonEquals(a, b string) bool {
    var objA, objB map[string]interface{}
    json.Unmarshal([]byte(a), &objA)
    json.Unmarshal([]byte(b), &objB)
    return reflect.DeepEqual(objA, objB)
}
```

## Files Affected
- cmd/bd/deletion_tracking.go:125
- cmd/bd/deletion_tracking.go:134-170 (buildIDToLineMap)


Agent 9 Issue 33


Agent 2 Issue 18


Agent 8 Issue 30


Another test with multiple deps


Agent 3 Batch 41 Issue 1


Agent 3 Issue 74

Created by agent 3


Update docs with multi-repo patterns

Update AGENTS.md, README.md, QUICKSTART.md with multi-repo patterns. Document: config options, routing behavior, backward compatibility, troubleshooting, best practices.


Agent 1 Issue 92

Created by agent 1


Agent 4 Issue 40

Created by agent 4


Agent 2 Batch 19 Issue 2


Agent 7 Issue 78

Created by agent 7


Agent 3 Batch 35 Issue 1


Agent 2 Issue 97


Agent 1 Issue 90


Agent 7 Issue 86

Created by agent 7


Agent 4 Issue 57


Agent 2 Issue 58

Created by agent 2


Integration test: mutation to export latency

Measure time from bd create to JSONL update. Verify <500ms latency. Test with multiple rapid mutations to verify batching.


Improve compact/daemon/merge documentation and UX

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

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


Agent 3 Issue 26


Agent 8 Issue 65


Agent 7 Issue 20


Agent 5 Issue 50

Created by agent 5


Agent 0 Issue 65


Agent 3 Issue 94


Latency test manual


Agent 2 Batch 2 Issue 2


Agent 3 Issue 92


Update LINTING.md with current baseline

After cleanup, document the remaining acceptable baseline in LINTING.md so we can track regression.


Agent 1 Batch 18 Issue 1


Agent 0 Batch 47 Issue 1


Agent 7 Issue 17


Agent 1 Issue 21


Agent 6 Issue 89


Agent 1 Batch 33 Issue 2


Agent 7 Issue 14


bd message: Refactor duplicated error messages


Agent 5 Issue 40


Import overwrites newer local issues with older remote versions

## Problem

During git pull + import, local issues with newer updated_at timestamps get overwritten by older versions from remote JSONL.

## What Happened

Timeline:
1. 17:52 - Closed bd-df190564 and bd-b501fcc1 locally (updated_at: 2025-10-31)
2. 17:51 - Remote pushed same issues with status=open (updated_at: 2025-10-30)
3. 17:52 - Local sync pulled remote commit and imported JSONL
4. Result: Issues reverted to open despite local version being newer

## Root Cause

DetectCollisions (internal/storage/sqlite/collision.go:67-79) compares fields but doesn't check timestamps:

```go
conflictingFields := compareIssues(existing, incoming)
if len(conflictingFields) == 0 {
    result.ExactMatches = append(result.ExactMatches, incoming.ID)
} else {
    // Same ID, different content - treats as UPDATE
    result.Collisions = append(result.Collisions, &CollisionDetail{...})
}
```

Import applies incoming version regardless of which is newer.

## Expected Behavior

Import should:
1. Compare updated_at timestamps when collision detected
2. Skip update if local version is newer
3. Apply update only if remote version is newer
4. Warn on timestamp conflicts

## Solution

Add timestamp checking to DetectCollisions or importIssues:

```go
if len(conflictingFields) > 0 {
    // Check timestamps
    if !incoming.UpdatedAt.After(existing.UpdatedAt) {
        // Local is newer or same - skip update
        result.ExactMatches = append(result.ExactMatches, incoming.ID)
        continue
    }
    // Remote is newer - apply update
    result.Collisions = append(result.Collisions, &CollisionDetail{...})
}
```

## Files
- internal/storage/sqlite/collision.go
- internal/importer/importer.go

## References
- Discovered during bd-df190564, bd-b501fcc1 re-opening


Agent 7 Issue 86


Agent 4 Issue 82


bd-hv01: Multi-repo mode not tested with deletion tracking

Problem: Test suite has no coverage for multi-repo mode. ExportToMultiRepo creates multiple JSONL files but snapshot files are hardcoded to single JSONL location.

Impact: Deletion tracking likely silently broken for multi-repo users, could cause data loss.

Fix: Add test and update snapshot logic to handle multiple JSONL files.

Files: cmd/bd/deletion_tracking_test.go, cmd/bd/deletion_tracking.go, cmd/bd/daemon_sync.go:24-34


Agent 8 Issue 95


Test dependency parent


Agent 3 Issue 2


Extract batch operations to batch_ops.go

Move validateBatchIssues, generateBatchIDs, bulkInsertIssues, bulkRecordEvents, bulkMarkDirty, CreateIssues to batch_ops.go


Agent 1 Issue 16

Created by agent 1


Fix renumbering temp ID collision bug

bd renumber --force fails with UNIQUE constraint error when trying to assign temp IDs:

Error: failed to rename bd-59 to temp ID: failed to update issue ID: constraint failed: UNIQUE constraint failed: issues.id (1555)

The temp ID generation logic in renumber.go doesn't guarantee unique IDs. Need to:
1. Use a temp ID strategy that can't collide (e.g., prefix with 'temp-', use UUIDs, or use high numbers like 999999+)
2. Verify temp IDs don't exist before using them
3. Add test case for renumbering with various ID gaps

Reproduced when renumbering 107 issues with gaps (IDs 1-344 compacting to 1-107).


Agent 3 Batch 3 Issue 2


Agent 0 Batch 48 Issue 2


Agent 1 Issue 45

Created by agent 1


Agent 7 Issue 87


Agent 4 Issue 45


Agent 0 Issue 52


Single-user issue


Add MCP functions for repair commands

Add repair commands to beads-mcp for agent access:
- beads_resolve_conflicts()
- beads_find_duplicates()
- beads_detect_pollution()
- beads_validate()

Files: integrations/beads-mcp/src/beads_mcp/server.py


Agent 6 Issue 86


Latency test 1


Agent 5 Issue 81


Clean up merge conflict artifacts in .beads directory

After resolving merge conflicts in .beads/beads.jsonl, leftover artifacts remain as untracked files:
- .beads/beads.base.jsonl
- .beads/beads.left.jsonl

These appear to be temporary files created during merge conflict resolution.

Options to fix:
1. Add these patterns to .beads/.gitignore automatically
2. Clean up these files after successful merge resolution
3. Document that users should delete them manually
4. Add a check in 'bd sync' or 'bd doctor' to detect and remove stale merge artifacts

Preferred solution: Add *.base.jsonl and *.left.jsonl patterns to .beads/.gitignore during 'bd init', and optionally clean them up automatically after successful import.


Agent 1 Issue 24

Created by agent 1


Agent 2 Issue 39

Created by agent 2


Agent 6 Issue 15


Add workspace config file for multi-repo management (optional enhancement)

For users who want explicit control over multi-repo setup without daemon, add optional workspace config file.

Config file: ~/.beads/workspaces.toml

Example:
[workspaces]
current = "global"

[workspace.global]
db = "~/.beads/global.db"
description = "System-wide tasks"

[workspace.project1]
db = "~/src/project1/.beads/db.sqlite"
description = "Main product"

[workspace.project2]
db = "~/src/project2/.beads/db.sqlite"
description = "Internal tools"

Commands:
bd workspace list                    # Show all workspaces
bd workspace add NAME PATH           # Add workspace
bd workspace remove NAME             # Remove workspace
bd workspace use NAME                # Switch active workspace
bd workspace current                 # Show current workspace
bd --workspace NAME <command>        # Override for single command

Implementation:
- Load config in PersistentPreRun
- Override dbPath based on current workspace
- Store workspace state in config file
- Support both workspace config AND auto-discovery
- Workspace config takes precedence over auto-discovery

Priority rationale:
- Priority 3 (low) because daemon approach already solves this
- Only implement if users request explicit workspace management
- Adds complexity vs daemon's automatic discovery

Alternative: Users can use BEADS_DB env var for manual workspace switching today.


Agent 4 Issue 55


Enhance `bd doctor` to verify Claude Code integration

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


bd delete panics with nil pointer when daemon is running

When the daemon is running (daemonClient != nil), the delete command panics with nil pointer dereference because it tries to use the global store variable which is nil.

The PersistentPreRun in main.go returns early when daemon is connected (line 104), skipping store initialization. But delete.go:92 calls store.GetIssue() without checking if store is nil or if it should use daemonClient instead.

Reproduction:
1. Start daemon: bd daemon start
2. Try to delete: bd delete bd-130 --force
3. Panic: runtime error: invalid memory address or nil pointer dereference

Root cause: Missing daemon fallback pattern that other commands use (see ready.go:135-143)


Agent 5 Issue 86

Created by agent 5


Agent 0 Issue 86

Created by agent 0


Implement fs bridge layer for WASM (Go syscall/js to Node.js fs)

Go's os package in WASM returns 'not implemented on js' for mkdir and other file operations. Need to create a bridge layer that:

1. Detects WASM environment (GOOS=js)
2. Uses syscall/js to call Node.js fs module functions
3. Implements wrappers for:
   - os.MkdirAll
   - os.ReadFile / os.WriteFile
   - os.Open / os.Create
   - os.Stat / os.Lstat
   - filepath operations

Approach:
- Create internal/wasm/fs_bridge.go with //go:build js && wasm
- Export Node.js fs functions to Go using global.readFileSync, global.writeFileSync, etc.
- Wrap in Go API that matches os package signatures
- Update beads.go and storage layer to use bridge when in WASM

This unblocks bd-4462 (basic WASM testing) and [deleted:bd-5bbf] (feature parity testing).


Agent 1 Batch 33 Issue 1


Implement daemon RPC with per-request context routing (PATH 1.5)

Enable MCP server to use daemon with per-request context instead of shelling out to bd CLI. This solves multi-repo routing properly.

## Progress: Session 2 (2025-10-17 continued)

### Completed
1. ✅ Updated MCP server to use daemon client
   - Modified `tools.py` to use `create_bd_client()` factory
   - Passes `BEADS_WORKING_DIR` from environment
   - Uses daemon by default, falls back to CLI
2. ✅ Added `BEADS_USE_DAEMON` environment variable
   - Default: `1` (enabled)
   - Set to `0` to force CLI mode
3. ✅ Created multi-repo integration test (`test_multi_repo.py`)
   - Tests concurrent operations across two repos
   - Verifies proper database routing based on cwd
   - Validates issue prefix isolation (r1- vs r2-)
   - All tests pass! ✅
4. ✅ Updated MCP README with daemon usage docs
   - Added BEADS_USE_DAEMON to environment variables
   - Added multi-repo test documentation

### Test Results
```
=== All Tests Passed! ===
Summary:
  ✅ Per-request context routing works
  ✅ Multiple repos are properly isolated
  ✅ Concurrent operations succeed
  ✅ Daemon handles rapid context switching
```

### Files Modified/Added (Session 2)
- `integrations/beads-mcp/src/beads_mcp/tools.py` - uses daemon client ✅
- `integrations/beads-mcp/test_multi_repo.py` - NEW integration test ✅
- `integrations/beads-mcp/README.md` - daemon documentation ✅

### Architecture Validated

```
AI Client (Claude/Amp)
  ↓
MCP Server (workspace_root from set_context)
  ↓ create_bd_client(prefer_daemon=True, workspace_root)
Daemon Client Library
  ↓ RPC with cwd field
beadsd Daemon
  ↓ per-request tree-walking
Correct .beads/*.db
```

### Ready to Close
All acceptance criteria met:
- ✅ MCP server can use daemon RPC instead of CLI
- ✅ Each operation includes cwd context
- ✅ Daemon routes to correct database per request
- ✅ Works with multiple repos simultaneously
- ✅ Falls back to CLI gracefully if daemon unavailable
- ✅ All existing MCP tests pass
- ✅ New multi-repo integration tests pass