title: Write tests for merge functionality

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

status: open

issue_type: task


title: Consider implementing pre-commit hooks for Storage interface changes

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

design:
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

acceptance_criteria:
- 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

issue_type: feature


title: Add transaction support for atomic merges

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


title: Update export/import for merge fields

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


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

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


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

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


title: Make merge command idempotent for safe retry after partial failures

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

design:
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


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

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


title: Add customizable time threshold for compact command

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


title: Implement bd quickstart command

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


title: Stress tests pollute production database with test issues

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

acceptance_criteria: Test with new flag

status: closed

issue_type: bug


title: Add merged_into field to database schema

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

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


title: Comment test


title: Version test issue


title: bd sync crashes with nil pointer when daemon is running

description:
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`


title: Add cross-repo issue references (future enhancement)

description:
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


title: Daemon storage cache doesn't detect external database modifications

description:
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

design:
**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)


title: Add CLI merge command and flags

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


title: Implement text reference scanning and replacement

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


title: Issue counter gets out of sync with actual issues

description:
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)


title: Implement dependency migration for merge

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


title: Test issue 2


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

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


title: Add validation/warning for malformed issue IDs

description: 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


title: Investigate stress test database pollution (vc-248)

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

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


title: Document merge command and AI integration

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


title: Test issue 1


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

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


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


title: Implement bd quickstart command


title: Add godoc comments for auto-flush functions

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

issue_type: chore


title: Remove unused issueMap in scoreCollisions

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


title: Test real auto-export


title: Consider implementing pre-commit hooks for Storage interface changes

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


title: Write tests for merge functionality

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


title: Improve error handling in dependency removal during remapping

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


title: Fix flaky CI tests in compactor and daemon modules

description:
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


title: Enforce one daemon per repository

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


description:
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


title: Add transaction support for atomic merges

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


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

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

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


title: Beads Library Integration

description:
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)

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

issue_type: epic


title: Phase 1: Add Beads Dependency (Non-Breaking)

description:
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

type: parent-child

created_by: daemon


title: Phase 2: Implement VCStorage Wrapper

description:
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

type: blocks


title: Phase 3: Migration Path & Database Schema Alignment

description:
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


title: Phase 4: Gradual Cutover & Production Rollout

description:
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


title: Example library-created issue

description: This issue was created programmatically using Beads as a library

type: discovered-from

created_by: library-example

author: library-example

text: This is a programmatic comment


title: Add lifecycle safety docs and tests for UnderlyingDB() method

description:
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)

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


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

description:
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


title: Consider adding UnderlyingConn(ctx) for safer scoped DB access

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

type: related


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

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


title: Test close issue


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

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


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

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


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

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


title: Fix MCP close tool method signature error

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


title: Update Claude Code marketplace plugin

description:
Update the beads plugin in the Claude Code marketplace to the latest version. This may help resolve some of the open GitHub issues related to marketplace installation and compatibility (#54, #112).

Should include:
- Latest beads version
- Updated documentation
- Any new features or bug fixes


title: Git worktree support - ensure --no-daemon works correctly

description:
Users working with git worktrees report that beads MCP commits to the wrong branch (main instead of worktree branch).

**Root cause:** Git worktrees share the same .beads directory, so the daemon/MCP server doesn't know which branch the worktree has checked out.

**Current state:**
- Daemon mode: Cannot work properly with worktrees (fundamental limitation - shared .beads, unknown branch)
- CLI with --no-daemon: Should work but needs verification

**Action items:**
1. Test and verify --no-daemon works correctly in worktrees
2. Document the limitation in README/AGENTS.md
3. Add clear error/warning when using daemon with worktrees
4. Consider if MCP server can detect worktree usage and auto-disable daemon

**Workaround for users:**
Use --no-daemon flag when working in worktrees, or set BEADS_AUTO_DAEMON=false

**Related:** GH issue #55

notes:
**Implementation completed with oracle review improvements:**

1. **Robust detection** - Changed from substring check to canonical git-dir vs git-common-dir comparison
2. **Correct warning gate** - Now only checks isGitWorktree() and only called when daemon is actually connected
3. **Complete coverage** - Added warning to `bd daemon` command start path
4. **Better UX** - Shows shared database path and clarifies BEADS_AUTO_START_DAEMON behavior
5. **Improved tests** - Validates canonical detection method and path truncation

**Files changed:**
- cmd/bd/worktree.go - Improved detection and warning
- cmd/bd/worktree_test.go - Better test coverage
- cmd/bd/main.go - Warning after daemon connection (2 places)
- cmd/bd/daemon.go - Warning when starting daemon
- README.md & AGENTS.md - Documented limitations and solutions


title: Investigate stress test database pollution (vc-248)

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


title: Implement text reference scanning and replacement

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