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

author: tester

text: first comment


title: Version test issue


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.


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`


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: Scan all issues for text references to merged IDs (bd-X patterns) and update to target ID. Reuse logic from import collision resolution.