Write tests for merge functionality

Unit tests: validation, merge logic, data integrity. Integration tests: end-to-end workflow, export/import. Edge case tests: chains, circular refs, epics.


Consider implementing pre-commit hooks for Storage interface changes

The documentation (INTERFACE_CHANGES.md) suggests adding pre-commit hooks that automatically check for Storage interface changes and verify all mocks are updated. This would prevent similar issues in the future where interface changes break mock implementations.

Discovered during execution of vc-228 (dogfooding run #14/15).

Implement a pre-commit hook that:
1. Detects changes to internal/storage/storage.go
2. Runs scripts/find-storage-mocks.sh to find all mock implementations
3. Attempts to compile all test files with mocks
4. Blocks commit if compilation fails

Tools: husky, pre-commit framework, or simple .git/hooks/pre-commit script

- Pre-commit hook installed and documented
- Hook detects Storage interface changes
- Hook validates all mocks compile
- Hook can be bypassed with --no-verify if needed
- Documentation updated with installation instructions


Phase 2: Implement VCStorage Wrapper

Create VCStorage wrapper that embeds beads.Storage and adds VC-specific operations.

**Goal:** Build clean abstraction layer where VC extends Beads without modifying Beads library.

**Architecture:**
- VCStorage embeds beads.Storage (delegates core operations)
- VCStorage adds VC-specific methods (executor instances, events)
- Same database, separate table namespaces (Beads tables + VC tables)
- Zero changes to Beads library code

**Key Tasks:**
1. Create VCStorage struct that embeds beads.Storage
2. Implement VC-specific methods: CreateExecutorInstance(), GetStaleExecutors(), LogEvent(), UpdateExecutionState()
3. Create VC table schemas (executor_instances, issue_execution_state, agent_events)
4. Verify type compatibility between VC types.Issue and Beads Issue
5. Create MockVCStorage for testing
6. Write unit tests for VC-specific methods
7. Write integration tests (end-to-end with Beads)
8. Benchmark performance vs current SQLite
9. Verify NO changes needed to Beads library

**Acceptance Criteria:**
- VCStorage successfully wraps Beads storage (embedding works)
- VC-specific tables created and accessible via foreign keys to Beads tables
- VC-specific methods work (executor instances, events)
- Core operations delegate to Beads correctly
- Tests pass with >90% coverage
- Performance benchmark shows no regression
- Beads library remains unmodified and standalone

**Technical Details:**
- Use beadsStore.DB() to get underlying database connection
- Create VC tables with FOREIGN KEY references to Beads issues table
- Schema separation: Beads owns (issues, dependencies, labels), VC owns (executor_instances, agent_events)
- Testing: Embed MockBeadsStorage in MockVCStorage

**Dependencies:**
- Blocked by Phase 1 (need Beads library imported)

**Estimated Effort:** 1.5 sprints


Make maxDepth configurable in bd dep tree command

Currently maxDepth is hardcoded to 50 in GetDependencyTree. Add --max-depth flag to bd dep tree command to allow users to control recursion depth. Default should remain 50 for safety, but users with very deep trees or wanting shallow views should be able to configure it.


Add transaction support to storage layer for atomic multi-operation workflows

Currently each storage method (CreateIssue, UpdateIssue, etc.) starts its own transaction. This makes it impossible to perform atomic multi-step operations like collision resolution. Add support for passing *sql.Tx through the storage interface, or create transaction-aware versions of methods. This would make remapCollisions and other batch operations truly atomic.


Test real auto-export


Daemon storage cache doesn't detect external database modifications

When bd commands bypass the daemon and directly modify the database (e.g., `bd import` with direct file access, or deleting/recreating bd.db), the daemon's cached storage connection becomes stale and serves outdated data.

**Reproduction**:
1. Start daemon: `bd daemon`
2. Run bd stats → shows N issues
3. Delete database: `rm .beads/bd.db`
4. Reinit and import: `bd init && bd import -i .beads/issues.jsonl`
5. Run bd stats → shows 0 issues (wrong!)
6. Direct query: `sqlite3 .beads/bd.db 'SELECT COUNT(*) FROM issues'` → shows correct count
7. Restart daemon: `bd daemon --stop` then retry stats → now shows correct count

**Root cause**:
- server.go:1410-1414 retrieves cached storage without checking if DB file changed
- Cache only evicts based on TTL (30min) or LRU, never on external modifications
- Direct file operations bypass daemon, leaving cache stale

**Impact**:
- Users see incorrect/stale data after external DB operations
- Confusing behavior with no clear indication cache is stale
- Requires daemon restart to fix

**Proposed fixes**:
1. Check mtime on cache hit, invalidate if file changed
2. Add cache eviction API (bd cache --clear)
3. Use file locking to prevent external modifications while daemon running
4. SQLite WAL mode change notifications

**Better approach: Check DB file mtime on cache lookup**

Too many commands bypass the daemon (import, init, renumber, compact, delete, dep tree, export, stale). Notifying from each would be error-prone and easy to forget when adding new commands.

**Implementation:**

1. Add `dbMtime time.Time` field to `StorageCacheEntry`
2. In `getStorageForRequest()` on cache hit:
   - Stat the DB file to get current mtime
   - If mtime changed since cached, evict entry and reopen
   - Otherwise return cached connection
3. Store mtime when initially caching

**Code location:**
- `internal/rpc/server.go:1410-1414` (cache hit path)
- `internal/rpc/server.go:49-52` (StorageCacheEntry struct)

**Benefits:**
- Simple, centralized check
- Works for all commands that bypass daemon
- Works for external tools modifying DB
- No need to update every command
- Minimal performance overhead (one stat() call on cache hit)

**Trade-offs:**
- Small overhead on every cache hit (negligible - stat is fast)
- mtime granularity may miss rapid changes (unlikely in practice)


Auto-flush writes test pollution and session work to git-tracked issues.jsonl

Auto-flush exports ALL issues from DB to issues.jsonl every 5 seconds, including:
- Test issues (bd-4053 through bd-4059 were version test junk)
- Issues created during debugging sessions
- Test pollution from stress tests
- Temporary diagnostic issues

This pollutes the git-tracked issues.jsonl with garbage that shouldn't be committed.

Example from today:
- Git had 49 clean issues
- Our DB grew to 100+ with test junk and session work
- Auto-flush wrote all 100+ to issues.jsonl
- Git status showed modified issues.jsonl with 50+ unwanted issues

Impact:
- Pollutes git history with test/debug garbage
- Makes code review difficult (noise in diffs)
- Can't distinguish real work from session artifacts
- Other team members pull polluted issues

Solutions to consider:
1. Disable auto-flush by default (require explicit --enable-auto-flush)
2. Add .beadsignore to exclude issue ID patterns
3. Make auto-flush only export 'real' issues (exclude test-*)
4. Require manual 'bd sync' for git commit
5. Auto-flush to separate file (.beads/session.jsonl vs issues.jsonl)

Related: bd-122 (test pollution), isolation_test.go (test DB separation)

## Analysis

Confirmed the issue exists - bd-52 through bd-58 are test pollution in the git-tracked issues.jsonl.

### Solution Evaluation:

**Option 1: Disable auto-flush by default** ❌
- Breaks the auto-sync workflow that users rely on
- Requires manual intervention which defeats the purpose
- Not recommended

**Option 2: Add .beadsignore** ⚠
- Complex to implement (pattern matching, configuration)
- Doesn't solve root cause: test issues in production DB
- Better to prevent pollution at source

**Option 3: Filter on export** ❌
- Doesn't solve root cause
- Test issues still pollute production DB
- Complicates export logic

**Option 4: Manual 'bd sync'** ❌
- Same issues as Option 1
- Breaks automated workflow

**Option 5: Separate session file** ❌
- Splits issue tracking across files
- Confusing for users
- Import/export complexity

### RECOMMENDED SOLUTION:

**Fix the root cause: Tests should NEVER touch the production database**

The real problem is that Go tests ARE properly isolated (they use temp DBs), but someone must be manually creating test issues in the production DB during development/debugging.

**Best fix:**
1. Document that production DB is for real work only
2. Add a convenience command: `bd test-create` that uses a separate test database
3. Clean up the existing test pollution: bd-52 through bd-58
4. Consider adding a git pre-commit hook to warn about suspicious issues

This preserves auto-flush (which is valuable) while preventing pollution at the source.

## Resolution

**Root Cause Identified:**
The issue was NOT a bug in auto-flush, but rather test pollution in the production database from manual testing/debugging. Go tests are properly isolated using temp directories.

**Actions Taken:**
1. Cleaned up test pollution: deleted bd-52 through bd-58 (all "Version test issue" entries)
2. Verified auto-flush is working correctly - it exports the database as designed
3. Confirmed Go test isolation works properly (uses temp dirs, not production DB)

**Prevention Strategy:**
- Production database (.beads/) should only contain real work issues
- Manual testing should use throwaway databases or test scripts
- Go tests already use isolated temp databases
- Auto-flush is working as intended and should remain enabled

**Conclusion:**
This was user error, not a system bug. The auto-flush mechanism is correct - it should export ALL database contents. The problem was polluting the production database with test issues in the first place.


Phase 1: Add Beads Dependency (Non-Breaking)

Introduce Beads library alongside existing SQLite code without breaking production.

**Goal:** Add Beads as optional dependency with feature flag, establish compatibility baseline.

**Key Tasks:**
1. Add github.com/steveyegge/beads to go.mod
2. Create compatibility test suite comparing VC SQLite vs Beads schema
3. Identify schema differences and document migration requirements
4. Create internal/storage/beads/adapter.go implementing Storage interface
5. Add feature flag: VC_USE_BEADS_LIBRARY=true (disabled by default)

**Acceptance Criteria:**
- Beads library imported successfully
- Compatibility tests pass identifying all schema differences
- Both implementations coexist without conflicts
- No production impact (feature flag disabled by default)
- Documentation of schema differences and migration needs

**Technical Details:**
- Use feature flag to allow A/B testing
- Compatibility tests must cover: issues, dependencies, labels, status transitions, ID generation
- Adapter must implement full Storage interface
- Zero changes to existing production code paths

**Blockers:** None - can start immediately

**Estimated Effort:** 1 sprint


Global daemon should warn/reject --auto-commit and --auto-push

When user runs 'bd daemon --global --auto-commit', it's unclear which repo the daemon will commit to (especially after fixing bd-101 where global daemon won't open a DB).

Options:
1. Warn and ignore the flags in global mode
2. Error out with clear message

Line 87-91 already checks autoPush, but should skip check entirely for global mode. Add user-friendly messaging about flag incompatibility.


Add cross-repo issue references (future enhancement)

Support referencing issues across different beads repositories. Useful for tracking dependencies between separate projects.

Proposed syntax:
- Local reference: bd-102 (current behavior)
- Cross-repo by path: ~/src/other-project#bd-456
- Cross-repo by workspace name: @project2:bd-789

Use cases:
1. Frontend project depends on backend API issue
2. Shared library changes blocking multiple projects
3. System administrator tracking work across machines
4. Monorepo with separate beads databases per component

Implementation challenges:
- Storage layer needs to query external databases
- Dependency resolution across repos
- What if external repo not available?
- How to handle in JSONL export/import?
- Security: should repos be able to read others?

Design questions to resolve first:
1. Read-only references vs full cross-repo dependencies?
2. How to handle repo renames/moves?
3. Absolute paths vs workspace names vs git remotes?
4. Should bd-77 auto-discover related repos?

Recommendation:
- Gather user feedback first
- Start with read-only references
- Implement as plugin/extension?

Context: This is mentioned in bd-77 as approach #2. Much more complex than daemon multi-repo approach. Only implement if there's strong user demand.

Priority: Backlog (4) - wait for user feedback before designing


Add transaction support for atomic merges

Wrap all merge operations in SQLite transaction for atomicity. Implement rollback on failure.


Make beads reusable as a Go library for external projects like vc

Currently beads is only usable as a CLI tool. We want to use beads as a library in other Go projects like ~/src/vc so they can programmatically manage issues without shelling out to the bd CLI.

Goals:
- Export public API from internal packages
- Document Go package usage
- Provide examples of programmatic usage
- Ensure vc can import and use beads storage layer directly

Use case: The vc project needs issue tracking and wants to use beads as an embedded library rather than as a separate CLI tool.

UnderlyingDB() method implemented and tested. Core functionality complete. Still needs documentation updates (bd-65) and lifecycle safety enhancements (bd-64).


Beads Library Integration

Migrate from custom SQLite implementation to using Beads as a library dependency. This eliminates ~3000 lines of duplicated code, reduces schema drift risk, and automatically inherits new Beads features.

**Key Benefits:**
- Remove 3000+ lines of duplicated SQLite code
- Eliminate schema drift between bd and vc CLIs
- Inherit Beads improvements automatically
- Stronger type safety with Beads error types
- Faster development velocity for new features
- Clean separation: Beads stays general-purpose, VC extends via wrapper

**Architecture Principle:**
Beads remains 100% standalone with NO VC dependencies. VC imports Beads (VC → Beads dependency) and wraps it with VC-specific storage methods. Both share the same database but maintain separate table namespaces.

**Current Pain Points:**
1. Code Duplication: Issue CRUD, dependency graphs, labels, status transitions all reimplemented
2. Schema Drift Risk: VC schema manually defined, could diverge from Beads
3. Lost Features: Can't leverage Beads query optimizer or advanced features without process spawning
4. Atomic Operations: Hand-rolled 100+ line transaction management
5. Maintenance Burden: Every Beads feature must be manually replicated

**Concrete Example:**
When Beads adds a new field (e.g., estimated_hours):
- Current: 4-6 hours of manual work (update types, 6+ SQL queries, migration, testing)
- With Library: 5 minutes (go get -u github.com/steveyegge/beads)

**Phased Approach:**
1. Phase 1: Add Beads dependency (non-breaking, feature flag)
2. Phase 2: Implement VCStorage wrapper (embeds beads.Storage)
3. Phase 3: Migration script for existing databases
4. Phase 4: Gradual cutover, deprecate SQLite code

**Related Analysis:**
See BEADS_INTEGRATION_ANALYSIS.md for detailed current state analysis and BEADS_LIBRARY_INTEGRATION_EPIC.md for full design document (both to be archived after issue creation).

**Estimated Effort:** 3-4 sprints
**Priority:** P2 (Medium-High - architectural improvement, high ROI)

Phase 1 (bd-59) complete! Beads can now be used as a Go library. VC can import github.com/steveyegge/beads and use beads.Storage directly instead of spawning CLI processes. No custom tables needed - VC uses pure Beads primitives.


Make merge command idempotent for safe retry after partial failures

The merge command currently performs 3 operations without an outer transaction:
1. Migrate dependencies from source → target
2. Update text references across all issues
3. Close source issues

If merge fails mid-operation (network issue, daemon crash, etc.), a retry will fail or produce incorrect results because some operations already succeeded.

**Goal:** Make merge idempotent so retrying after partial failure is safe and completes the remaining work.

**Idempotency checks needed:**
- Skip dependency migration if target already has the dependency
- Skip text reference updates if already updated
- Skip closing source issues if already closed
- Report which operations were skipped vs performed

**Example output:**
```
✓ Merged 2 issue(s) into bd-102
  - Dependencies: 3 migrated, 2 already existed
  - Text references: 5 updated, 0 already correct
  - Source issues: 1 closed, 1 already closed
```

**Related:** bd-23 originally requested transaction support, but idempotency is a better solution for this use case since individual operations are already atomic.

Current merge code already has some idempotency:
- Dependency migration checks `alreadyExists` before adding (line ~145-151 in merge.go)
- Text reference updates are naturally idempotent (replacing bd-X with bd-Y twice has same result)

Missing idempotency:
- CloseIssue fails if source already closed
- Error messages don't distinguish "already done" from "real failure"

Implementation:
1. Check source issue status before closing - skip if already closed
2. Track which operations succeeded/skipped
3. Return detailed results for user visibility
4. Consider adding --dry-run output showing what would be done vs skipped


Counter not synced after import on existing DB with populated issue_counters table

The counter sync fix in counter_sync_test.go only syncs during initial migration when issue_counters table is empty (migrateIssueCountersTable checks count==0). For existing databases with stale counters:

- Import doesn't resync the counter
- Delete doesn't update counter
- Renumber doesn't fix counter
- Counter remains stuck at old high value

Example from today:
- Had 49 issues after clean import
- Counter stuck at 4106 from previous test pollution
- Next issue would be bd-4107 instead of bd-50
- Even after renumber, counter stayed at 4106

Root cause: Migration only syncs if table is empty (line 182 in sqlite.go). Once populated, never resyncs.

Fix needed:
1. Sync counter after import operations (not just empty table)
2. Add counter resync after renumber
3. Daemon caches counter value - needs to reload after external changes

Related: bd-122 (original counter sync fix), bd-6 (daemon cache staleness)

## Investigation Results

After thorough code review, all the fixes mentioned in the issue description have ALREADY been implemented:

### ✅ Fixes Already in Place:

1. **Import DOES resync counters**
   - `cmd/bd/import_shared.go:253` calls `SyncAllCounters()` after batch import
   - Verified with new test `TestCounterSyncAfterImport`

2. **Delete DOES update counters**
   - `internal/storage/sqlite/sqlite.go:1424` calls `SyncAllCounters()` after deletion
   - Both single delete and batch delete sync properly
   - Verified with existing tests: `TestCounterSyncAfterDelete`, `TestCounterSyncAfterBatchDelete`

3. **Renumber DOES fix counters**
   - `cmd/bd/renumber.go:298-304` calls `ResetCounter()` then `SyncAllCounters()`
   - Forces counter to actual max ID (not just MAX with stale value)

4. **Daemon cache DOES detect external changes**
   - `internal/rpc/server.go:1466-1487` checks file mtime and evicts stale cache
   - When DB file changes externally, cached storage is evicted and reopened

### Tests Added:

- `TestCounterSyncAfterImport`: Confirms import syncs counters from stale value (4106) to actual max (49)
- `TestCounterNotSyncedWithoutExplicitSync`: Documents what would happen without the fix (bd-4107 instead of bd-50)

### Conclusion:

The issue described in bd-50 has been **fully resolved**. All operations (import, delete, renumber) now properly sync counters. The daemon correctly detects external DB changes via file modification time.

The root cause (migration only syncing empty tables) was fixed by adding explicit `SyncAllCounters()` calls after import, delete, and renumber operations.


Stress tests pollute production database with test issues

TestStressNoUniqueConstraintViolations and other stress tests in internal/rpc/stress_test.go create issues in production database instead of test database. Confirmed: 1,000 test issues (Agent X Issue Y) created at 20:46:01 during test run. Root cause: test goroutines connect to production daemon at .beads/bd.sock instead of isolated test daemon in temp directory.


Compact command fails with daemon - requires --no-daemon workaround

The 'bd compact' command fails with 'Error: compact requires SQLite storage' when used with the daemon (default mode), but works correctly with the '--no-daemon' flag.

The daemon RPC interface doesn't properly expose the compact command, even though the daemon itself uses SQLite storage.

Reproduction:
1. Ensure daemon is running (bd daemon status)
2. Run: bd compact --stats
   Result: Error: compact requires SQLite storage
3. Run: bd compact --stats --no-daemon
   Result: Works correctly, shows statistics

Expected behavior:
The compact command should work through the daemon RPC interface just like other commands (list, create, update, delete, renumber, etc.)

Impact:
Users cannot use compact operations in the normal workflow. They must use --no-daemon which bypasses the daemon entirely.

Suggested fix:
Add compact operation support to the daemon RPC interface, similar to how renumber and other operations are exposed.


Implement bd quickstart command

Add bd quickstart command to show context-aware repo information: recent issues, database location, configured prefix, example queries. Helps AI agents understand current project state. Companion to bd onboard.

After review, we already have good context tools: bd stats, bd list, bd ready, and the AGENTS.md onboarding section. Adding bd quickstart would be redundant and doesn't add enough value to justify maintenance cost. Closing as won't implement.


Issue counter gets out of sync with actual issues

The issue counter in issue_counters table frequently desyncs from actual max issue ID, causing:
- Import from JSONL leaves counter at old high value
- Test pollution increments counter but cleanup doesn't decrement it
- Delete issues doesn't update counter
- Only fix is 'rm -rf .beads' which is destructive

Examples from today's session:
- Had 48 issues but counter at 7714 after test pollution
- Import from git didn't reset counter
- Next new issue would be bd-7715 instead of bd-122

Proposed fixes:
1. Auto-recalculate counter from max(issue_id) on import
2. Add 'bd fix-counter' command
3. Make counter lazy (always compute from DB, don't store)
4. Import should reset counter to match imported data

Related: bd-47 (test isolation), bd-50 (init timestamp bug)


The issue counter in issue_counters table frequently desyncs from actual max issue ID, causing:
- Import from JSONL leaves counter at old high value
- Test pollution increments counter but cleanup doesn't decrement it
- Delete issues doesn't update counter
- Only fix is 'rm -rf .beads' which is destructive

Examples from today's session:
- Had 48 issues but counter at 7714 after test pollution
- Import from git didn't reset counter
- Next new issue would be bd-7715 instead of bd-15

Proposed fixes:
1. Auto-recalculate counter from max(issue_id) on import
2. Add 'bd fix-counter' command
3. Make counter lazy (always compute from DB, don't store)
4. Import should reset counter to match imported data

Related: bd-47 (test isolation), bd-50 (init timestamp bug)


Update export/import for merge fields

Include merged_into in JSONL export format. Handle merge relationships on import.


The merge command currently performs 3 operations without an outer transaction:
1. Migrate dependencies from source → target
2. Update text references across all issues
3. Close source issues

If merge fails mid-operation (network issue, daemon crash, etc.), a retry will fail or produce incorrect results because some operations already succeeded.

**Goal:** Make merge idempotent so retrying after partial failure is safe and completes the remaining work.

**Idempotency checks needed:**
- Skip dependency migration if target already has the dependency
- Skip text reference updates if already updated
- Skip closing source issues if already closed
- Report which operations were skipped vs performed

**Example output:**
```
✓ Merged 2 issue(s) into bd-78
  - Dependencies: 3 migrated, 2 already existed
  - Text references: 5 updated, 0 already correct
  - Source issues: 1 closed, 1 already closed
```

**Related:** bd-23 originally requested transaction support, but idempotency is a better solution for this use case since individual operations are already atomic.


Enforce one daemon per repository

Multiple daemons can run for the same repository, causing race conditions, data corruption, and unpredictable behavior. Need to implement lock file or PID check to ensure only one daemon runs per .beads directory. This has caused production issues including test database pollution (bd-19) and potential concurrent write conflicts.


The merge command currently performs 3 operations without an outer transaction:
1. Migrate dependencies from source → target
2. Update text references across all issues
3. Close source issues

If merge fails mid-operation (network issue, daemon crash, etc.), a retry will fail or produce incorrect results because some operations already succeeded.

**Goal:** Make merge idempotent so retrying after partial failure is safe and completes the remaining work.

**Idempotency checks needed:**
- Skip dependency migration if target already has the dependency
- Skip text reference updates if already updated
- Skip closing source issues if already closed
- Report which operations were skipped vs performed

**Example output:**
```
✓ Merged 2 issue(s) into bd-128
  - Dependencies: 3 migrated, 2 already existed
  - Text references: 5 updated, 0 already correct
  - Source issues: 1 closed, 1 already closed
```

**Related:** bd-53 originally requested transaction support, but idempotency is a better solution for this use case since individual operations are already atomic.


Add compact --dry-run that shows size savings estimates

When running 'bd compact --dry-run', show estimated database size reduction in KB/MB and percentage, similar to what 'du -h' would show.

Example output:
  Tier 1 candidates: 15 issues
  Current size: 2.4 MB
  After compaction: ~1.7 MB (70% reduction, 0.7 MB saved)

This helps users understand impact before compacting.


Add rule-based compaction (e.g., compact children of closed epics)

Support semantic compaction rules beyond just time-based, such as:
- Compact all children of closed epics
- Compact by priority level (e.g., all P3/P4 closed issues)
- Compact by label (e.g., all issues labeled 'archive')
- Compact by type (e.g., all closed chores)

This would allow smarter database size management based on semantic meaning rather than just age.


The merge command currently performs 3 operations without an outer transaction:
1. Migrate dependencies from source → target
2. Update text references across all issues
3. Close source issues

If merge fails mid-operation (network issue, daemon crash, etc.), a retry will fail or produce incorrect results because some operations already succeeded.

**Goal:** Make merge idempotent so retrying after partial failure is safe and completes the remaining work.

**Idempotency checks needed:**
- Skip dependency migration if target already has the dependency
- Skip text reference updates if already updated
- Skip closing source issues if already closed
- Report which operations were skipped vs performed

**Example output:**
```
✓ Merged 2 issue(s) into bd-128
  - Dependencies: 3 migrated, 2 already existed
  - Text references: 5 updated, 0 already correct
  - Source issues: 1 closed, 1 already closed
```

**Related:** bd-113 originally requested transaction support, but idempotency is a better solution for this use case since individual operations are already atomic.


Add --id flag to bd list for filtering by specific issue IDs

Add --id flag accepting comma-separated IDs. Usage: bd list --id wy-11,wy-12. Combines with other filters. From filter-flag-design.md.


Add customizable time threshold for compact command

Currently compact uses fixed 30-day and 90-day tiers. Add support for custom time thresholds like '--older-than 60h' or '--older-than 2.5d' to allow more flexible compaction policies.

Examples:
  bd compact --all --older-than 60h
  bd compact --all --older-than 2.5d
  bd compact --all --tier 1 --age 48h

This would allow users to set their own compaction schedules based on their workflow needs.


Implement bd quickstart command


Add merged_into field to database schema

Add merged_into field to Issue struct and update database schema to support merge tracking

Simplified: no schema field needed. Close merged issues with reason 'Merged into bd-X'. See bd-79 design.


Comment test

first comment


Version test issue


Support referencing issues across different beads repositories. Useful for tracking dependencies between separate projects.

Proposed syntax:
- Local reference: bd-78 (current behavior)
- Cross-repo by path: ~/src/other-project#bd-456
- Cross-repo by workspace name: @project2:bd-789

Use cases:
1. Frontend project depends on backend API issue
2. Shared library changes blocking multiple projects
3. System administrator tracking work across machines
4. Monorepo with separate beads databases per component

Implementation challenges:
- Storage layer needs to query external databases
- Dependency resolution across repos
- What if external repo not available?
- How to handle in JSONL export/import?
- Security: should repos be able to read others?

Design questions to resolve first:
1. Read-only references vs full cross-repo dependencies?
2. How to handle repo renames/moves?
3. Absolute paths vs workspace names vs git remotes?
4. Should bd-77 auto-discover related repos?

Recommendation:
- Gather user feedback first
- Start with read-only references
- Implement as plugin/extension?

Context: This is mentioned in bd-77 as approach #2. Much more complex than daemon multi-repo approach. Only implement if there's strong user demand.

Priority: Backlog (4) - wait for user feedback before designing


Daemon storage cache doesn't detect external database modifications

When bd commands bypass the daemon and directly modify the database (e.g., `bd import` with direct file access, or deleting/recreating bd.db), the daemon's cached storage connection becomes stale and serves outdated data.

**Reproduction**:
1. Start daemon: `bd daemon`
2. Run bd stats → shows N issues
3. Delete database: `rm .beads/bd.db`
4. Reinit and import: `bd init && bd import -i .beads/issues.jsonl`
5. Run bd stats → shows 0 issues (wrong!)
6. Direct query: `sqlite3 .beads/bd.db 'SELECT COUNT(*) FROM issues'` → shows correct count
7. Restart daemon: `bd daemon --stop` then retry stats → now shows correct count

**Root cause**:
- server.go:1410-1414 retrieves cached storage without checking if DB file changed
- Cache only evicts based on TTL (30min) or LRU, never on external modifications
- Direct file operations bypass daemon, leaving cache stale

**Impact**:
- Users see incorrect/stale data after external DB operations
- Confusing behavior with no clear indication cache is stale
- Requires daemon restart to fix

**Proposed fixes**:
1. Check mtime on cache hit, invalidate if file changed
2. Add cache eviction API (bd cache --clear)
3. Use file locking to prevent external modifications while daemon running
4. SQLite WAL mode change notifications


Add CLI merge command and flags

Implement bd merge command with: multiple sources, --into target, --dry-run, --json flags. Add interactive confirmation.


Implement text reference scanning and replacement

Scan all issues for text references to merged IDs (bd-X patterns) and update to target ID. Reuse logic from import collision resolution.


Add CLI merge command and flags


The issue counter in issue_counters table frequently desyncs from actual max issue ID, causing:
- Import from JSONL leaves counter at old high value
- Test pollution increments counter but cleanup doesn't decrement it
- Delete issues doesn't update counter
- Only fix is 'rm -rf .beads' which is destructive

Examples from today's session:
- Had 48 issues but counter at 7714 after test pollution
- Import from git didn't reset counter
- Next new issue would be bd-7715 instead of bd-118

Proposed fixes:
1. Auto-recalculate counter from max(issue_id) on import
2. Add 'bd fix-counter' command
3. Make counter lazy (always compute from DB, don't store)
4. Import should reset counter to match imported data

Related: bd-115 (test isolation), bd-114 (init timestamp bug)


Wrap all merge operations in SQLite transaction for atomicity. Implement rollback on failure.


Implement dependency migration for merge

Migrate all dependencies from source issue(s) to target issue during merge, removing duplicates and preserving graph integrity


Test issue 2


The 'bd compact' command fails with 'Error: compact requires SQLite storage' when used with the daemon (default mode), but works correctly with the '--no-daemon' flag.

The daemon RPC interface doesn't properly expose the compact command, even though the daemon itself uses SQLite storage.

Reproduction:
1. Ensure daemon is running (bd daemon status)
2. Run: bd compact --stats
   Result: Error: compact requires SQLite storage
3. Run: bd compact --stats --no-daemon
   Result: Works correctly, shows statistics

Expected behavior:
The compact command should work through the daemon RPC interface just like other commands (list, create, update, delete, renumber, etc.)

Impact:
Users cannot use compact operations in the normal workflow. They must use --no-daemon which bypasses the daemon entirely.

Suggested fix:
Add compact operation support to the daemon RPC interface, similar to how renumber and other operations are exposed.


Add validation/warning for malformed issue IDs

getNextID silently ignores non-numeric ID suffixes (e.g., bd-foo). CAST returns NULL for invalid strings. Consider detecting and warning about malformed IDs in database. Location: internal/storage/sqlite/sqlite.go:79-82


Investigate stress test database pollution (vc-248)

Investigation of stress tests polluting production database with 1,600+ test issues on Oct 21 at 20:24-20:25. Root cause analysis completed. Tests now verified to work correctly with proper isolation.

Bug confirmed! Tests DO pollute production DB. 1,000 test issues created at 20:46:01-20:46:02 during TestStressNoUniqueConstraintViolations. Root cause: test goroutines connect to production daemon at .beads/bd.sock instead of test daemon.


Document merge command and AI integration

Update README, AGENTS.md with merge command examples. Document AI agent duplicate detection workflow.


Test issue 1


Global daemon should warn/reject --auto-commit and --auto-push

When user runs 'bd daemon --global --auto-commit', it's unclear which repo the daemon will commit to (especially after fixing bd-77 where global daemon won't open a DB).

Options:
1. Warn and ignore the flags in global mode
2. Error out with clear message

Line 87-91 already checks autoPush, but should skip check entirely for global mode. Add user-friendly messaging about flag incompatibility.


bd sync crashes with nil pointer when daemon is running

The 'bd sync' command crashes with a nil pointer dereference when the daemon is running.

**Reproduction:**
```bash
# With daemon running
./bd sync
```

**Error:**
```
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x2 addr=0x120 pc=0x1012314ac]

goroutine 1 [running]:
main.exportToJSONL({0x1014ec2e0, 0x101a49900}, {0x14000028db0, 0x30})
        /Users/stevey/src/fred/beads/cmd/bd/sync.go:245 +0x4c
```

**Root cause:**
The sync command's `exportToJSONL` function directly accesses `store.SearchIssues()` at line 245, but when daemon mode is active, the global `store` variable is nil. The sync command should either:
1. Use daemon RPC when daemon is running, or
2. Force direct mode for sync operations

**Workaround:**
Use `--no-daemon` flag: `bd sync --no-daemon`


Make merge command idempotent for safe retry after partial failures

The merge command currently performs 3 operations without an outer transaction:
1. Migrate dependencies from source → target
2. Update text references across all issues
3. Close source issues

If merge fails mid-operation (network issue, daemon crash, etc.), a retry will fail or produce incorrect results because some operations already succeeded.

**Goal:** Make merge idempotent so retrying after partial failure is safe and completes the remaining work.

**Idempotency checks needed:**
- Skip dependency migration if target already has the dependency
- Skip text reference updates if already updated
- Skip closing source issues if already closed
- Report which operations were skipped vs performed

**Example output:**
```
✓ Merged 2 issue(s) into bd-78
  - Dependencies: 3 migrated, 2 already existed
  - Text references: 5 updated, 0 already correct
  - Source issues: 1 closed, 1 already closed
```

**Related:** bd-117 originally requested transaction support, but idempotency is a better solution for this use case since individual operations are already atomic.


Implement bd quickstart command

Add bd quickstart command to show context-aware repo information: recent issues, database location, configured prefix, example queries. Helps AI agents understand current project state. Companion to bd onboard.


Add godoc comments for auto-flush functions

Add comprehensive godoc comments for findJSONLPath(), markDirtyAndScheduleFlush(), and flushToJSONL() explaining behavior, concurrency considerations, and error handling. Include notes about debouncing behavior (timer resets on each write, flush occurs 5s after LAST operation) and flush-on-exit guarantees. Located in cmd/bd/main.go:188-307.


Remove unused issueMap in scoreCollisions

scoreCollisions() creates issueMap and populates it (lines 135-138) but never uses it. Either remove it or add a TODO comment explaining future use. Located in collision.go:135-138. Cosmetic cleanup.


Test real auto-export


Consider implementing pre-commit hooks for Storage interface changes

The documentation (INTERFACE_CHANGES.md) suggests adding pre-commit hooks that automatically check for Storage interface changes and verify all mocks are updated. This would prevent similar issues in the future where interface changes break mock implementations.

Discovered during execution of vc-228 (dogfooding run #14/15).


Write tests for merge functionality

Unit tests: validation, merge logic, data integrity. Integration tests: end-to-end workflow, export/import. Edge case tests: chains, circular refs, epics.


Improve error handling in dependency removal during remapping

In updateDependencyReferences(), RemoveDependency errors are caught and ignored with continue (line 392). Comment says 'if dependency doesn't exist' but this catches ALL errors including real failures. Should check error type with errors.Is(err, ErrDependencyNotFound) and only ignore not-found errors, returning other errors properly.


Fix flaky CI tests in compactor and daemon modules

Multiple test failures observed in CI:
- TestCompactTier1_DryRun
- TestCompactTier1Batch_DryRun
- TestCompactTier1Batch_WithIneligible
- TestMockAPI_CompactTier1
- TestBatchOperations_ErrorHandling
- TestCommentOperationsViaRPC
- TestMemoryPressureDetection
- TestPing

All failures related to 'issue has open dependents or not closed long enough' eligibility checks.

See CI run: https://github.com/steveyegge/beads/actions/runs/18688772658


Enforce one daemon per repository

Multiple daemons can run for the same repository, causing race conditions, data corruption, and unpredictable behavior. Need to implement lock file or PID check to ensure only one daemon runs per .beads directory. This has caused production issues including test database pollution (bd-116) and potential concurrent write conflicts.


Fix: Import should preserve original timestamps instead of overwriting with current time

Issue GH-121: Import unconditionally overwrites created_at/updated_at in validateBatchIssues(), losing historical dates from external systems (Jira, GitHub). Causes dirty git repo on every import. Fix: Only set timestamps if IsZero().

Change validateBatchIssues() in internal/storage/sqlite/sqlite.go lines 668-669 to check IsZero() before setting timestamps. Preserves existing behavior for new issues while allowing imports to keep original dates.

Import with historical timestamps preserves them. Import without timestamps still gets current time. No git diff after importing unchanged JSONL.


Fix: RemapCollisions deletes existing issue dependencies during import collision resolution

Bug in updateDependencyReferences() was deleting ALL existing issue dependencies during import with --resolve-collisions, not just dependencies from imported issues.

Root cause: Function was checking if dep.IssueID was in idMapping keys (old imported IDs), but those are also IDs of existing DB issues. Fixed to only update dependencies where IssueID is in idMapping values (new remapped IDs).

During normal import, this is now effectively a no-op since imported dependencies haven't been added to DB yet when RemapCollisions runs.

Fixes GH issue #120


init command ignores --db flag and BEADS_DB env var

The bd init command hardcodes the database path to .beads/{prefix}.db and ignores both the --db flag and BEADS_DB environment variable. This prevents users from initializing databases outside the project directory.

Root cause: cmd/bd/init.go line 71 creates a local dbPath variable instead of using the global dbPath from the flag.

Related to GitHub issue #118.

Fix completed and reviewed by oracle.

Changes made:
1. Check BEADS_DB environment variable at start of init command
2. Use global dbPath if set via --db flag or BEADS_DB, otherwise default to .beads/{prefix}.db
3. Use proper path comparison (filepath.Abs + filepath.Clean) instead of strings.Contains to determine if database is local
4. Only create .beads/ directory when database will actually be stored there
5. Ensure parent directory exists for custom database paths
6. Added comprehensive tests including edge cases:
   - Custom path with --db flag
   - Custom path with BEADS_DB env var
   - Custom path containing ".beads" substring (to prevent false positive)
   - Flag precedence over env var

Oracle review feedback implemented:
- Replaced strings.Contains heuristic with canonical path comparison
- Added tests for edge cases
- All init tests passing

This properly fixes GitHub issue #118.


MCP dep tool uses confusing parameter names (from_id/to_id instead of issue_id/depends_on_id)

GitHub issue #113 reports that Claude Code is creating dependencies backwards because the MCP tool parameters are confusing.

Current: from_id, to_id (ambiguous - does from_id block to_id or vice versa?)
Should be: issue_id, depends_on_id (clear - issue_id depends on depends_on_id)

The CLI uses the clear naming: `bd dep add [issue-id] [depends-on-id]`
The MCP tool should match this for consistency and clarity.

Files to update:
- integrations/beads-mcp/src/beads_mcp/tools.py (parameter names and docs)
- integrations/beads-mcp/src/beads_mcp/bd_client.py (if needed)
- integrations/beads-mcp/src/beads_mcp/bd_daemon_client.py (if needed)
- All tests that use add_dependency


Document Claude Code MCP auto-approval options for beads tools

Users report needing to manually approve every beads MCP command, disrupting workflow. Investigation reveals Claude Code supports MCP server-level auto-approval but NOT per-tool granularity.

**Key Findings:**
- Claude Code settings.json supports `enabledMcpjsonServers` for server-level auto-approval
- No mechanism exists to selectively approve specific tools within an MCP server
- Cannot auto-approve read-only tools (bd ready, bd show) while requiring confirmation for mutations (bd create, bd update)

**Current Solutions:**
1. Add `"enabledMcpjsonServers": ["beads"]` to auto-approve ALL beads tools
2. Use `"enableAllProjectMcpServers": true` for project-defined servers
3. Live with manual approvals for safety

**Documentation Needed:**
- Update PLUGIN.md with auto-approval configuration examples
- Document trade-offs between convenience vs safety
- Provide recommended settings for different use cases

Add new section to PLUGIN.md titled "Auto-Approval Configuration" covering:

1. Why manual approval happens (security model)
2. Server-level auto-approval with enabledMcpjsonServers
3. Project-level auto-approval with enableAllProjectMcpServers
4. Trade-offs and recommendations
5. Future: potential feature request for per-tool approval to Anthropic

Example configurations for different risk profiles:
- Conservative: Manual approval (default)
- Balanced: Auto-approve for trusted projects only
- Aggressive: Auto-approve all beads commands

- PLUGIN.md has "Auto-Approval Configuration" section
- Documents enabledMcpjsonServers usage
- Documents enableAllProjectMcpServers usage
- Explains security trade-offs clearly
- Provides recommended configurations
- Links to Claude Code docs for reference


Add generic `bd config` command for external integration configuration

External integrations (Jira, Linear, GitHub) need project-specific configuration that's:
- Per-project (isolated to each .beads/*.db)
- Version-control-friendly
- Easy to discover and edit
- Machine-readable for scripts

**Implementation:**
Infrastructure already exists - config table and SetConfig()/GetConfig() methods in sqlite.go. Just needs CLI wrapper.

**Commands:**
- `bd config set <key> <value>` - Set config value
- `bd config get <key>` - Get config value
- `bd config list` - List all config
- `bd config unset <key>` - Delete config value
- All with `--json` flag for scripting

**Use case:**
Configure Jira integration without hardcoded scripts:
```
bd config set jira.url "https://company.atlassian.net"
bd config set jira.project "PROJ"
bd config set jira.status_map.todo "open"
```

**Benefits:**
- Standard pattern (like git config, npm config)
- Enables clean integration scripts
- Foundation for agent preferences
- Namespace convention (jira.*, linear.*, custom.*)

Implementation checklist:
1. Add cmd/bd/config.go with cobra subcommands
2. Implement config set/get/list/unset
3. Add --json flag to all commands
4. Use existing storage.SetConfig()/GetConfig() methods
5. Add tests in cmd/bd/config_test.go
6. Document namespace convention (core, integration, custom)
7. Update README.md and create CONFIG.md
8. Add examples in integration docs

Optional: config export/import for file-based sharing (defer to later)

- bd config set/get/list/unset commands work
- --json flag outputs valid JSON
- Per-project config isolated in .beads/*.db
- Documentation covers namespace convention
- Examples show Jira/Linear integration use
- Tests cover all subcommands and error cases


Phase 3: Migration Path & Database Schema Alignment

Enable existing .beads/vc.db files to work with Beads library through automated migration.

**Goal:** Provide safe, tested migration path from SQLite implementation to Beads library.

**Key Tasks:**
1. Run compatibility tests against production databases
2. Identify schema differences (columns, indexes, constraints)
3. Document required migrations
4. Create migration CLI command: 'vc migrate --from sqlite --to beads'
5. Add dry-run mode for preview
6. Add backup/restore capability
7. Implement rollback mechanism
8. Add auto-detection of schema version on startup
9. Add auto-migrate with user prompt

**Acceptance Criteria:**
- Existing databases migrate successfully
- Data integrity preserved (zero data loss verified via checksums)
- Rollback works if migration fails
- Migration tested on real production VC databases
- Dry-run mode shows exactly what will change
- Backup created before migration
- Feature flag: VC_FORCE_SQLITE=true provides escape hatch

**Technical Details:**
- Compare current SQLite schema with Beads schema
- Handle version detection (read schema_version or detect from structure)
- Migration should be idempotent (safe to run multiple times)
- Backup strategy: Copy .beads/vc.db to .beads/vc.db.backup-<timestamp>
- Verify foreign key integrity after migration

**Safety Measures:**
- Require executor shutdown before migration (check for running executors)
- Atomic migration (BEGIN IMMEDIATE transaction)
- Comprehensive pre/post migration validation
- Clear error messages with recovery instructions

**Dependencies:**
- Blocked by Phase 2 (need VCStorage implementation)

**Estimated Effort:** 0.5 sprint


Phase 4: Gradual Cutover & Production Rollout

Replace SQLite implementation with Beads library in production and remove legacy code.

**Goal:** Complete transition to Beads library, deprecate and remove custom SQLite implementation.

**Key Tasks:**
1. Run VC executor with Beads library in CI
2. Dogfood: Use Beads library for VC's own development
3. Monitor for regressions and performance issues
4. Flip feature flag: VC_USE_BEADS_LIBRARY=true by default
5. Monitor production logs for errors
6. Collect user feedback
7. Add deprecation notice to CLAUDE.md
8. Provide migration guide for users
9. Remove legacy code: internal/storage/sqlite/sqlite.go (~1500 lines)
10. Remove migration framework: internal/storage/migrations/
11. Remove manual transaction management code
12. Update all documentation

**Acceptance Criteria:**
- Beads library enabled by default in production
- Zero production incidents related to migration
- Performance meets or exceeds SQLite implementation
- All tests passing with Beads library
- Legacy SQLite code removed
- Documentation updated
- Celebration documented 🎉

**Rollout Strategy:**
1. Week 1: Enable for CI/testing environments
2. Week 2: Dogfood on VC development
3. Week 3: Enable for 50% of production (canary)
4. Week 4: Enable for 100% of production
5. Week 5: Remove legacy code

**Monitoring:**
- Track error rates before/after cutover
- Monitor database query performance
- Track issue creation/update latency
- Monitor executor claim performance

**Rollback Plan:**
- Keep VC_FORCE_SQLITE=true escape hatch for 2 weeks post-cutover
- Keep legacy code for 1 sprint after cutover
- Document rollback procedure

**Success Metrics:**
- Zero data loss
- No performance regression (< 5% latency increase acceptable)
- Reduced maintenance burden (code LOC reduction)
- Positive developer feedback

**Dependencies:**
- Blocked by Phase 3 (need migration tooling)

**Estimated Effort:** 1 sprint


Example library-created issue

This issue was created programmatically using Beads as a library


Add lifecycle safety docs and tests for UnderlyingDB() method

The new UnderlyingDB() method exposes the raw *sql.DB connection for extensions like VC to create their own tables. While database/sql is concurrency-safe, there are lifecycle and misuse risks that need documentation and testing.

**What needs to be done:**

1. **Enhanced documentation** - Expand UnderlyingDB() comments to warn:
   - Callers MUST NOT call Close() on returned DB
   - Do NOT change pool/driver settings (SetMaxOpenConns, SetConnMaxIdleTime)
   - Do NOT modify SQLite PRAGMAs (WAL mode, journal, etc.)
   - Expect errors after Storage.Close() - use contexts
   - Keep write transactions short to avoid blocking core storage

2. **Add lifecycle tracking** - Implement closed flag:
   - Add atomic.Bool closed field to SQLiteStorage
   - Set flag in Close(), clear in New()
   - Optional: Add IsClosed() bool method

3. **Add safety tests** (run with -race):
   - TestUnderlyingDB_ConcurrentAccess - N goroutines using UnderlyingDB() during normal storage ops
   - TestUnderlyingDB_AfterClose - Verify operations fail cleanly after storage closed
   - TestUnderlyingDB_CreateExtensionTables - Create VC table with FK to issues, verify FK enforcement
   - TestUnderlyingDB_LongTxDoesNotCorrupt - Ensure long read tx doesn't block writes indefinitely

**Why this matters:**
VC will use this to create tables in the same database. Need to ensure production-ready safety without over-engineering.

**Estimated effort:** S+S+S = M total (1-3h)

Oracle recommends "simple path": enhanced docs + minimal guardrails + focused tests. See oracle output for detailed rationale on concurrency safety, lifecycle risks, and when to consider advanced path (wrapping interface).


Update EXTENDING.md with UnderlyingDB() usage and best practices

EXTENDING.md currently shows how to use direct sql.Open() to access the database, but doesn't mention the new UnderlyingDB() method that's the recommended way for extensions.

**Update needed:**
1. Add section showing UnderlyingDB() usage:
   ```go
   store, err := beads.NewSQLiteStorage(dbPath)
   db := store.UnderlyingDB()
   // Create extension tables using db
   ```

2. Document when to use UnderlyingDB() vs direct sql.Open():
   - Use UnderlyingDB() when you want to share the storage connection
   - Use sql.Open() when you need independent connection management

3. Add safety warnings (cross-reference from UnderlyingDB() docs):
   - Don't close the DB
   - Don't modify pool settings
   - Keep transactions short

4. Update the VC example to show UnderlyingDB() pattern

5. Explain beads.Storage.UnderlyingDB() in the API section


Consider adding UnderlyingConn(ctx) for safer scoped DB access

Currently UnderlyingDB() returns *sql.DB which is correct for most uses, but for extension migrations/DDL, a scoped connection might be safer.

**Proposal:** Add optional UnderlyingConn(ctx) (*sql.Conn, error) method that:
- Returns a scoped connection via s.db.Conn(ctx)
- Encourages lifetime-bounded usage
- Reduces temptation to tune global pool settings
- Better for one-time DDL operations like CREATE TABLE

**Implementation:**
```go
// UnderlyingConn returns a single connection from the pool for scoped use
// Useful for migrations and DDL. Close the connection when done.
func (s *SQLiteStorage) UnderlyingConn(ctx context.Context) (*sql.Conn, error) {
    return s.db.Conn(ctx)
}
```

**Benefits:**
- Safer for migrations (explicit scope)
- Complements UnderlyingDB() for different use cases
- Low implementation cost

**Trade-off:** Adds another method to maintain, but Oracle considers this balanced compromise between safety and flexibility.

**Decision:** This is optional - evaluate based on VC's actual usage patterns.


MCP close tool method signature error - takes 1 positional argument but 2 were given

The close approval routing fix in beads-mcp v0.11.0 works correctly and successfully routes update(status="closed") calls to close() tool. However, the close() tool has a Python method signature bug that prevents execution.

Impact: All MCP-based close operations are broken. Workaround: Use bd CLI directly.

Error: BdDaemonClient.close() takes 1 positional argument but 2 were given

Root cause: BdDaemonClient.close() only accepts self, but MCP tool passes issue_id and reason.

Additional issue: CLI close has FOREIGN KEY constraint error when recording reason parameter.

See GitHub issue #107 for full details.


Test close issue


Fix pre-existing MCP test failures - show/update return arrays not dicts

9 tests fail in beads-mcp because bd CLI commands return arrays but MCP client expects dicts:

Failing tests:
- test_create_and_show_issue: show returns array, expects dict
- test_update_issue: update returns array, expects dict
- test_add_dependency: show returns array, expects dict
- test_invalid_issue_id: show returns empty dict instead of error
- test_dependency_types: show returns array, expects dict
- test_show_issue_tool: show returns array, expects dict
- test_update_issue_tool: update returns array, expects dict
- test_update_partial_fields: update returns array, expects dict
- test_client_lazy_initialization: BdClient import issue

Root cause: bd CLI commands like 'bd show' and 'bd update' output JSON arrays, but BdCliClient.show() and BdCliClient.update() expect single dict objects.

Example:
```bash
bd show test-1 --json
[{"id":"test-1",...}]  # Array, not dict
```

Fix needed: Update bd_client.py to handle array responses and extract first element, or change CLI to return single object for single-ID operations.


Compact command fails with daemon - requires --no-daemon workaround

The 'bd compact' command fails with 'Error: compact requires SQLite storage' when used with the daemon (default mode), but works correctly with the '--no-daemon' flag.

The daemon RPC interface doesn't properly expose the compact command, even though the daemon itself uses SQLite storage.

Reproduction:
1. Ensure daemon is running (bd daemon status)
2. Run: bd compact --stats
   Result: Error: compact requires SQLite storage
3. Run: bd compact --stats --no-daemon
   Result: Works correctly, shows statistics

Expected behavior:
The compact command should work through the daemon RPC interface just like other commands (list, create, update, delete, renumber, etc.)

Impact:
Users cannot use compact operations in the normal workflow. They must use --no-daemon which bypasses the daemon entirely.

Suggested fix:
Add compact operation support to the daemon RPC interface, similar to how renumber and other operations are exposed.


Fix bd sync prefix mismatch error message suggesting non-existent flag

GH #103: bd sync suggests using --rename-on-import flag that doesn't exist. Need to either implement the flag or fix the error message to suggest the correct workflow.


Fix MCP close tool method signature error

GH #107: MCP close() tool fails with "BdDaemonClient.close() takes 1 positional argument but 2 were given". Need to fix method signature in beads-mcp server.


Test auto-export timing


Consider implementing pre-commit hooks for Storage interface changes

The documentation (INTERFACE_CHANGES.md) suggests adding pre-commit hooks that automatically check for Storage interface changes and verify all mocks are updated. This would prevent similar issues in the future where interface changes break mock implementations.

Discovered during execution of vc-228 (dogfooding run #14/15).


Add customizable time threshold for compact command

Currently compact uses fixed 30-day and 90-day tiers. Add support for custom time thresholds like '--older-than 60h' or '--older-than 2.5d' to allow more flexible compaction policies.

Examples:
  bd compact --all --older-than 60h
  bd compact --all --older-than 2.5d
  bd compact --all --tier 1 --age 48h

This would allow users to set their own compaction schedules based on their workflow needs.


Add --id flag to bd list for filtering by specific issue IDs


Test issue 2


Make merge command idempotent for safe retry after partial failures

The merge command currently performs 3 operations without an outer transaction:
1. Migrate dependencies from source → target
2. Update text references across all issues
3. Close source issues

If merge fails mid-operation (network issue, daemon crash, etc.), a retry will fail or produce incorrect results because some operations already succeeded.

**Goal:** Make merge idempotent so retrying after partial failure is safe and completes the remaining work.

**Idempotency checks needed:**
- Skip dependency migration if target already has the dependency
- Skip text reference updates if already updated
- Skip closing source issues if already closed
- Report which operations were skipped vs performed

**Example output:**
```
✓ Merged 2 issue(s) into bd-78
  - Dependencies: 3 migrated, 2 already existed
  - Text references: 5 updated, 0 already correct
  - Source issues: 1 closed, 1 already closed
```

**Related:** bd-23 originally requested transaction support, but idempotency is a better solution for this use case since individual operations are already atomic.


Document merge command and AI integration

Update README, AGENTS.md with merge command examples. Document AI agent duplicate detection workflow.


Add EXPLAIN QUERY PLAN tests for ready work query

Verify that the hierarchical blocking query uses proper indexes and doesn't do full table scans.

**Queries to analyze:**
1. The recursive CTE (both base case and recursive case)
2. The final SELECT with NOT EXISTS
3. Impact of various filters (status, priority, assignee)

**Implementation:**
Add test function that:
- Runs EXPLAIN QUERY PLAN on GetReadyWork query
- Parses output to verify no SCAN TABLE operations
- Documents expected query plan in comments
- Fails if query plan degrades

**Benefits:**
- Catch performance regressions in tests
- Document expected query behavior
- Ensure indexes are being used

Related to: bd-87 (composite index on depends_on_id, type)


Investigate stress test database pollution (vc-248)

Investigation of stress tests polluting production database with 1,600+ test issues on Oct 21 at 20:24-20:25. Root cause analysis completed. Tests now verified to work correctly with proper isolation.


Optimize export dependency queries (N+1 problem)

Export triggers separate GetDependencyRecords() per issue. For large DBs (1000+ issues), this is N+1 queries. Add GetAllDependencyRecords() to fetch all dependencies in one query. Location: cmd/bd/export.go:52-59, import.go:138-142


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.


Use safer placeholder pattern in replaceIDReferences

Currently uses bd-313 which could theoretically collide with user text. Use a truly unique placeholder like null bytes: \x00REMAP\x00_0_\x00 which are unlikely to appear in normal text. Located in collision.go:324. Very low probability issue but worth fixing for completeness.


Implement full cross-type cycle prevention in AddDependency

Expand cycle prevention in AddDependency to check for cycles across ALL dependency types, not just 'blocks'. Currently only 'blocks' type dependencies are checked for cycles, allowing cross-type circular dependencies to form (e.g., A blocks B, B parent-child A). This can cause semantic confusion and is a maintenance hazard for future operations that traverse dependencies.

Implementation approach:
1. Modify the cycle check in AddDependency (postgres.go:559-599)
2. Remove the 'type = blocks' filter from the recursive CTE
3. Check for cycles regardless of dependency type being added
4. Return a clear error message indicating which types form the cycle

Trade-offs to consider:
- This is more mathematically correct (no cycles in dependency DAG)
- May break legitimate use cases where cross-type cycles are intentional
- Need to evaluate whether ANY cross-type cycles are valid in practice
- Alternative: make this configurable with a --allow-cycle flag

Before implementing, should investigate:
- Are there legitimate reasons for cross-type cycles?
- What's the performance impact on large graphs (1000+ issues)?
- Should certain type combinations be allowed to cycle?

- AddDependency prevents cycles across all dependency types, not just 'blocks'
- Clear error message when cycle would be created, including dependency types
- All existing tests pass
- Performance benchmarked on large dependency graphs (100+ issues)
- Decision documented on whether to add --allow-cycle flag or exception rules


Refactor duplicate flush logic in PersistentPostRun

PersistentPostRun contains a complete copy of the flush logic instead of calling flushToJSONL(). This violates DRY principle and makes maintenance harder. Refactor to use flushToJSONL() with a force parameter to bypass isDirty check, or extract shared logic into a helper function. Located in cmd/bd/main.go:104-138.


Optimize auto-flush to use incremental updates

Every flush exports ALL issues and ALL dependencies, even if only one issue changed. For large projects (1000+ issues), this could be expensive. Current approach guarantees consistency, which is fine for MVP, but future optimization could track which issues changed and use incremental updates. Located in cmd/bd/main.go:255-276.


Make auto-flush debounce duration configurable

flushDebounce is hardcoded to 5 seconds. Make it configurable via environment variable BEADS_FLUSH_DEBOUNCE (e.g., '500ms', '10s'). Current 5-second value is reasonable for interactive use, but CI/automated scenarios might want faster flush. Add getDebounceDuration() helper function. Located in cmd/bd/main.go:31.


Document label best practices and use cases

Create documentation covering:
- When to use labels vs structured fields
- Common label sets (coding agents, open source, product dev, SRE)
- Naming conventions (kebab-case, specificity, present tense)
- Anti-patterns (too many labels, overlapping, personal labels)
- Label lifecycle management

Content from LABELS.md analysis document.


Add rule-based compaction (e.g., compact children of closed epics)

Support semantic compaction rules beyond just time-based, such as:
- Compact all children of closed epics
- Compact by priority level (e.g., all P3/P4 closed issues)
- Compact by label (e.g., all issues labeled 'archive')
- Compact by type (e.g., all closed chores)

This would allow smarter database size management based on semantic meaning rather than just age.


Test issue 1


Implement text reference scanning and replacement

Scan all issues for text references to merged IDs (bd-X patterns) and update to target ID. Reuse logic from import collision resolution.


Improve error handling in dependency removal during remapping

In updateDependencyReferences(), RemoveDependency errors are caught and ignored with continue (line 392). Comment says 'if dependency doesn't exist' but this catches ALL errors including real failures. Should check error type with errors.Is(err, ErrDependencyNotFound) and only ignore not-found errors, returning other errors properly.


Global daemon should warn/reject --auto-commit and --auto-push

When user runs 'bd daemon --global --auto-commit', it's unclear which repo the daemon will commit to (especially after fixing bd-77 where global daemon won't open a DB).

Options:
1. Warn and ignore the flags in global mode
2. Error out with clear message

Line 87-91 already checks autoPush, but should skip check entirely for global mode. Add user-friendly messaging about flag incompatibility.


Add performance benchmarks document

Document actual performance metrics with hyperfine tests


Investigate vector/semantic search for issue discovery

From GH issue #2 RFC discussion: Evaluate if vector/semantic search over issues would provide value for beads.

**Use case:** Find semantically related issues (e.g., 'login broken' finds 'authentication failure', 'session expired').

**Questions to answer:**
1. What workflows would this enable that we can't do now?
2. Is dataset size (typically 50-200 issues) large enough to benefit?
3. Do structured features (deps, tags, types) already provide better relationships?
4. What's the maintenance cost (embeddings, storage, recomputation)?

**Alternatives to consider:**
- Improve 'bd list' filtering with regex/boolean queries
- Add 'bd related <id>' showing deps + mentions + same tags
- Export to JSON and pipe to external AI tools

**Decision:** Only implement if clear use case emerges. Don't add complexity for theoretical benefits.

**Context:** Part of evaluating Turso RFC ideas (GH #2). Vector search was proposed but unclear if needed for typical beads usage.


Add visual indicators for nodes with multiple parents in dep tree

When a node appears in the dependency tree via multiple paths (diamond dependencies), add a visual indicator like (*) or (multiple parents) to help users understand the graph structure. This would make it clear when deduplication has occurred. Example: 'bd-503: Shared dependency (*) [P1] (open)'


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.


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.

Split the function into smaller, focused units:

1. parseMarkdownFile(filepath) - Main entry point, handles file I/O
2. parseMarkdownContent(scanner) - Core parsing logic
3. processIssueSection(issue, section, content) - Handle section finalization (current switch statement)
4. parseLabels(content) []string - Extract labels from content
5. parseDependencies(content) []string - Extract dependencies from content
6. parsePriority(content) int - Parse and validate priority

Benefits:
- Each function has a single responsibility
- Easier to test individual components
- Lower cognitive load when reading code
- Better encapsulation of parsing logic

- parseMarkdownFile complexity < 15
- New helper functions each have complexity < 10
- All existing tests still pass
- No change in functionality or behavior
- Code coverage maintained or improved


Simplify getNextID SQL query parameters

Query passes prefix four times to same SQL query. Works but fragile if query changes. Consider simplifying SQL to require fewer parameters. Location: internal/storage/sqlite/sqlite.go:73-78


Write tests for merge functionality

Unit tests: validation, merge logic, data integrity. Integration tests: end-to-end workflow, export/import. Edge case tests: chains, circular refs, epics.


Remove unused issueMap in scoreCollisions

scoreCollisions() creates issueMap and populates it (lines 135-138) but never uses it. Either remove it or add a TODO comment explaining future use. Located in collision.go:135-138. Cosmetic cleanup.