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-166 (test pollution), isolation_test.go (test DB separation)

## Analysis

Confirmed the issue exists - bd-167 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-167 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-167 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.


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


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.


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


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.


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


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

This is a programmatic comment


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.


Test real auto-export


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.


Update Claude Code marketplace plugin

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


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

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

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


Investigate jujutsu integration for beads

Research and document how beads could integrate with jujutsu (jj), the next-generation VCS. Key areas to explore:
- How jj's operation model differs from git (immutable operations, working-copy-as-commit)
- JSONL sync strategy with jj's conflict resolution model
- Daemon compatibility with jj's more frequent rewrites
- Whether auto-import/export needs changes for jj workflows
- Example configurations and documentation updates needed


Add description parameter to bd update command and MCP server

Issue #114 and #122 show that agents expect to update issue descriptions. Currently only create supports description. Need to add --description flag to CLI update command and description parameter to MCP update_issue tool.


Test description update

Updated with daemon running


Add integration tests for worktree workflow with separate databases

Created test_worktree_separate_dbs.py that verifies the recommended workflow: one beads database per worktree with daemon-less MCP mode (BEADS_USE_DAEMON=0). Tests confirm isolation, git syncing, MCP operations, and --no-daemon flag.


Migrate to Viper for unified configuration management

Consolidate all config, flags, and environment variables into a singleton using spf13/viper. Benefits: unified config precedence, auto-env binding, live reloading, better integration with Cobra. Current state: manual env var handling, global flags, and new bd config command (GH #124).

Hybrid architecture:
- Viper: Tool-level user preferences (global defaults for --json, --no-daemon, etc) from ~/.config/bd/config.yaml, env vars, flags
- bd config: Project-level integration data (jira.url, linear.token) in database - version-controlled, team-shared

This separation is correct: tool settings are user-specific, project config is team-shared. Agents benefit from bd config's structured interface vs manual YAML editing.


Add viper dependency and initialize singleton

go get github.com/spf13/viper, create viper instance in main, set up config file paths (.beads/config.yaml, ~/.config/bd/config.yaml)


Test auto-export timing


Bind all global flags to viper

Migrate --db, --actor, --json, --no-daemon, --no-auto-flush, --no-auto-import to viper with automatic env binding (BD_DB, BD_ACTOR, etc)


Replace manual env var handling with viper

Remove os.Getenv() calls for BD_* variables, use viper.GetString() etc. Update CONFIG.md with viper precedence order


Keep bd config independent from Viper

Update config.go to use viper for get/set/list operations. Consider whether to keep db-stored config or migrate fully to file-based

Keep bd config independent from Viper. Two separate systems:
- Viper: tool-level preferences (global flags, env vars, ~/.config/bd/config.yaml) - user settings like default --json, --no-daemon
- bd config: project-level integration config (jira.url, linear.token) - stored in database, version-controlled, team-shared

Rationale: Agents need structured commands with validation/discoverability. Direct YAML editing is error-prone for agents. This separation is architecturally correct: tool settings vs project data.


Add tests for viper configuration

Test config precedence (defaults < config file < env vars < flags), test config file discovery, test env binding


Auto-import updates all issue timestamps causing perpetually dirty JSONL

**Problem:**
Every bd command ends sessions with dirty .beads/beads.jsonl because auto-import unnecessarily updates `updated_at` timestamps on ALL issues, even when issue data is unchanged.

**Root Cause:**
Auto-import (autoImportIfNewer) imports issues and the import process updates `updated_at` timestamps on every issue, even when the issue data is identical. This causes:
1. Import updates all 83 issues' timestamps (e.g., 2025-10-23T11:01:13.xxx)
2. Export writes JSONL with new timestamps
3. Git shows JSONL as modified with 200+ line changes
4. User commits changes
5. Next command triggers auto-import again
6. Cycle repeats

**Evidence:**
```bash
git diff .beads/beads.jsonl | grep 'updated_at' | wc -l
# Shows 200+ lines changed (every issue touched)

git diff .beads/beads.jsonl | grep 'updated_at' | sed 's/.*updated_at[^:]*:\s*"\([^"]*\)".*/\1/' | sort -u
# All timestamps identical, proving bulk update
```

**Expected Behavior:**
Import should only update `updated_at` when issue data actually changes. Idempotent imports should not modify timestamps.

**Impact:**
- Frustrating UX: "always conclude sessions with dirty beads.jsonl"
- Pollutes git history with timestamp-only changes
- Makes actual changes hard to detect in git diff
- Wastes CI/CD time on false changes

**Related:**
- bd-55 fixed import to preserve timestamps, but doesn't address this issue
- May be related to how UpdateIssue works vs just inserting/replacing


Add GoReleaser workflow for cross-platform binary releases

GitHub issue #89 requests pre-compiled binaries for vendoring.

Currently users must have Go installed to use beads via 'go install'. Publishing release binaries would:
- Enable vendoring (user's use case)
- Support users without Go
- Enable version pinning
- Simplify CI/CD integration

Implementation:
1. Add .goreleaser.yml config
2. Add .github/workflows/release.yml for tag pushes
3. Build matrix: darwin (amd64/arm64), linux (amd64/arm64), windows (amd64)
4. Generate checksums
5. Create GitHub releases automatically
6. Update install.sh to download from releases

Reference: https://github.com/steveyegge/beads/issues/89


Add transaction support for atomicity in merge operations

The merge operation in cmd/bd/merge.go should use transactions to ensure atomicity. Currently marked as TODO at line 143.

This would prevent partial merges if an error occurs partway through the operation.


Add RPC support for epic commands in daemon mode

Epic status and close-eligible commands currently error out in daemon mode with a message to use --no-daemon. These commands should work with daemon RPC like other commands.

Locations:
- cmd/bd/epic.go:26 (epic status command)
- cmd/bd/epic.go:106 (epic close-eligible command)


bd import reports "0 created, 0 updated" when successfully importing issues

The `bd import` command successfully imported 125 issues but reported "0 created, 0 updated" in the output. The import actually worked, but the success message is incorrect/misleading.

This appears to be a bug in the reporting logic that counts and displays the number of issues created/updated during import.


Auto-detect and kill old daemon versions

When the client version doesn't match the daemon version, we get confusing behavior (auto-flush race conditions, stale data, etc.). The client should automatically detect version mismatches and handle them gracefully.

**Current behavior:**
- `bd version --daemon` shows mismatch but requires manual intervention
- Old daemons keep running after binary upgrades
- MCP server may connect to old daemon
- Results in dirty working tree after commits, stale data

**Proposed solution:**

Key lifecycle points to check/restart daemon:
1. **On first command after version mismatch**: Check daemon version, auto-restart if incompatible
2. **On daemon start**: Check for existing daemons, kill old ones before starting
3. **After brew upgrade/install**: Add post-install hook to kill old daemons
4. **On `bd init`**: Ensure fresh daemon

**Detection logic:**
```go
// PersistentPreRun: check daemon version
if daemonVersion != clientVersion {
    log.Warn("Daemon version mismatch, restarting...")
    killDaemon()
    startDaemon()
}
```

**Considerations:**
- Should we be aggressive (always kill mismatched) or conservative (warn first)?
- What about multiple workspaces with different bd versions?
- Should this be opt-in via config flag?
- How to handle graceful shutdown vs force kill?

**Related issues:**
- Race condition with auto-flush (see bd-89)
- Version mismatch confusion for users
- Stale daemon after upgrades

## Implementation Summary

Implemented automatic daemon version detection and restart in v0.16.0.

### Changes Made

**1. Auto-restart on version mismatch (main.go PersistentPreRun)**
- Check daemon version during health check
- If incompatible, automatically stop old daemon and start new one
- Falls back to direct mode if restart fails
- Transparent to users - no manual intervention needed

**2. Auto-stop old daemon on startup (daemon.go)**
- When starting daemon, check if existing daemon has compatible version
- If versions are incompatible, auto-stop old daemon before starting new one
- Prevents "daemon already running" errors after upgrades

**3. Robust restart implementation**
- Sets correct working directory so daemon finds right database
- Cleans up stale socket files after force kill
- Properly reaps child process to avoid zombies
- Uses waitForSocketReadiness helper for reliable startup detection
- 5-second readiness timeout

### Key Features

- **Automatic**: No user action required after upgrading bd
- **Transparent**: Works with both MCP server and CLI
- **Safe**: Falls back to direct mode if restart fails
- **Tested**: All existing tests pass

### Related
- Addresses race conditions mentioned in bd-90
- Uses semver compatibility checking from internal/rpc/server.go


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


Race condition between git commit and auto-flush debounce

When using MCP/daemon mode, operations trigger a 5-second debounced auto-flush to JSONL. This creates a race condition with git commits, leaving the working tree dirty.

**Example scenario:**
1. User closes issue via MCP → daemon schedules flush (5 sec delay)
2. User commits code changes → JSONL appears clean
3. Daemon flush fires → JSONL modified after commit
4. Result: dirty working tree showing JSONL changes

**Root cause:**
- Auto-flush uses 5-second debounce to batch changes
- Git commits happen immediately
- No coordination between flush schedule and git operations

**Possible solutions:**

1. **Immediate flush before git operations**
   - Detect git commands (commit, status, push)
   - Force immediate flush if pending
   - Pros: Clean working tree guaranteed
   - Cons: Requires hooking git, may be slow

2. **Commit includes pending flushes**
   - Add `bd sync` to commit workflow
   - Wait for flush to complete before committing
   - Pros: Simple, explicit
   - Cons: Requires user discipline

3. **Git hooks integration**
   - pre-commit hook: `bd sync --wait`
   - Ensures JSONL is up-to-date before commit
   - Pros: Automatic, reliable
   - Cons: Requires hook installation

4. **Reduce debounce delay**
   - Lower from 5s to 1s or 500ms
   - Pros: Faster sync, less likely to race
   - Cons: More frequent I/O, doesn't eliminate race

5. **Lock-based coordination**
   - Daemon holds lock while flush pending
   - Git operations wait for lock
   - Pros: Guarantees ordering
   - Cons: Complex, may block operations

**Recommended approach:**
Combine #2 and #3:
- Add `bd sync` command to explicitly flush
- Provide git hooks in `examples/git-hooks/`
- Document workflow in AGENTS.md
- Keep 5s debounce for normal operations

**Related:**
- bd-89 (daemon version detection)


Clean up linter errors (914 total issues)

The codebase has 914 linter issues reported by golangci-lint. While many are documented as baseline in LINTING.md, we should clean these up systematically to improve code quality and maintainability.

Break down by linter category, prioritizing high-impact issues:
1. dupl (7) - Code duplication
2. goconst (12) - Repeated strings
3. gocyclo (11) - High complexity functions
4. revive (78) - Style issues
5. gosec (102) - Security warnings
6. errcheck (683) - Unchecked errors (many in tests)

All linter categories reduced to acceptable levels, with remaining baseline documented in LINTING.md

Reduced from 56 to 41 issues locally, then to 0 issues.

**Fixed in commits:**
- c2c7eda: Fixed 15 actual errors (dupl, gosec, revive, staticcheck, unparam)
- 963181d: Configured exclusions to get to 0 issues locally

**Current status:**
- ✅ Local: golangci-lint reports 0 issues
- ❌ CI: Still failing (see bd-104)

**Problem:**
Config v2 format or golangci-lint-action@v8 compatibility issue causing CI to fail despite local success.

**Next:** Debug bd-104 to fix CI/local discrepancy


Fix code duplication in label.go (dupl)

Lines 72-120 duplicate lines 122-170 in cmd/bd/label.go. The add and remove commands have nearly identical structure.

Extract common batch operation logic into a shared helper function that takes the operation type as a parameter.


Convert repeated strings to constants (goconst)

12 instances of repeated strings that should be constants: "alice", "windows", "bd-163", "daemon", "import", "healthy", "unhealthy", "1.0.0", "custom-1", "custom-2"

Create package-level or test-level constants for frequently used test strings and command names.


Refactor high complexity functions (gocyclo)

11 functions exceed cyclomatic complexity threshold (>30): runDaemonLoop (42), importIssuesCore (71), TestLabelCommands (67), issueDataChanged (39), etc.

Break down complex functions into smaller, testable units. Extract validation, error handling, and business logic into separate functions.


Fix revive style issues (78 issues)

Style violations: unused parameters (many cmd/args in cobra commands), missing exported comments, stuttering names (SQLiteStorage), indent-error-flow issues.

Rename unused params to _, add godoc comments to exported types, fix stuttering names, simplify control flow.


Address gosec security warnings (102 issues)

Security linter warnings: file permissions (0755 should be 0750), G304 file inclusion via variable, G204 subprocess launches. Many are false positives but should be reviewed.

Review each gosec warning. Add exclusions for legitimate cases to .golangci.yml. Fix real security issues (overly permissive file modes).


Handle unchecked errors (errcheck - 683 issues)

683 unchecked error returns, mostly in tests (Close, Rollback, RemoveAll). Many already excluded in config but still showing up.

Review .golangci.yml exclude-rules. Most defer Close/Rollback errors in tests can be ignored. Add systematic exclusions or explicit _ = assignments where appropriate.


Update LINTING.md with current baseline

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


Fix Windows CI test failures (5 failing tests)

Windows CI has 5 flaky/failing tests: TestTryDaemonLockDetectsRunning, TestIsDaemonRunning_CurrentProcess (PID detection issues), TestScripts/import, TestMetricsSnapshot/uptime, TestSocketCleanup (socket in use).

Investigate Windows-specific PID/process detection and socket cleanup. These may be race conditions or platform differences in how Windows handles process IDs and file locks.