Files
beads/.beads/bd.jsonl
Steve Yegge b893be7d0e Fix bd-161: Implement daemon JSONL import (fix NO-OP stub)
Replace the NO-OP importToJSONLWithStore() stub with full implementation:
- Reads and parses JSONL file line by line using bufio.Scanner
- Uses importIssuesCore() with auto-collision resolution enabled
- Integrates with existing import infrastructure
- Fixes PRIMARY root cause of bd-160 multi-clone sync failure

The daemon now properly imports remote changes pulled from git instead
of ignoring them, allowing databases to converge across clones.

Amp-Thread-ID: https://ampcode.com/threads/T-9b92c2dc-e0e2-4d77-b562-136da8c3f64e
Co-authored-by: Amp <amp@ampcode.com>
2025-10-26 20:05:31 -07:00

170 lines
243 KiB
JSON
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{"id":"bd-1","title":"Make auto-flush debounce duration configurable","description":"flushDebounce is hardcoded to 5 seconds. Make it configurable via environment variable BEADS_FLUSH_DEBOUNCE (e.g., '500ms', '10s'). Current 5-second value is reasonable for interactive use, but CI/automated scenarios might want faster flush. Add getDebounceDuration() helper function. Located in cmd/bd/main.go:31.","status":"closed","priority":3,"issue_type":"feature","created_at":"2025-10-21T23:53:44.31362-07:00","updated_at":"2025-10-25T23:15:33.461232-07:00","closed_at":"2025-10-18T09:47:43.22126-07:00"}
{"id":"bd-10","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.\n\nGoals:\n- Export public API from internal packages\n- Document Go package usage\n- Provide examples of programmatic usage\n- Ensure vc can import and use beads storage layer directly\n\nUse 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-17) and lifecycle safety enhancements (bd-16).","status":"closed","priority":2,"issue_type":"feature","created_at":"2025-10-22T12:27:30.35968-07:00","updated_at":"2025-10-25T23:15:33.517762-07:00","closed_at":"2025-10-22T19:46:09.362533-07:00"}
{"id":"bd-100","title":"GH#146: No color showing in terminal for some users","description":"User reports color not working in macOS (Taho 26.0.1) with iTerm 3.6.4 and Terminal.app, despite color working elsewhere in terminal. Python rich and printf escape codes work.\n\nNeed to investigate:\n- Is NO_COLOR env var set?\n- Terminal type detection?\n- fatih/color library configuration\n- Does bd list show colors? bd ready? bd init?\n- What's the output of: echo $TERM, echo $NO_COLOR","status":"open","priority":2,"issue_type":"bug","created_at":"2025-10-24T22:26:36.22163-07:00","updated_at":"2025-10-25T23:15:33.508654-07:00","external_ref":"github:146"}
{"id":"bd-101","title":"Fix nil pointer crash in bd reopen command","description":"bd reopen crashes with SIGSEGV at reopen.go:30. Nil pointer dereference when trying to reopen an issue.","notes":"Fixed by adding daemon RPC support to reopen command. Pattern: check daemonClient != nil first, use RPC UpdateArgs with Status=open, fall back to direct store if daemon unavailable.","status":"closed","priority":0,"issue_type":"bug","created_at":"2025-10-25T10:30:31.602438-07:00","updated_at":"2025-10-25T23:15:33.50884-07:00","closed_at":"2025-10-25T10:33:39.016623-07:00"}
{"id":"bd-102","title":"Address gosec security warnings (102 issues)","description":"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.","design":"Review each gosec warning. Add exclusions for legitimate cases to .golangci.yml. Fix real security issues (overly permissive file modes).","status":"open","priority":2,"issue_type":"task","created_at":"2025-10-25T13:47:10.719134-07:00","updated_at":"2025-10-25T23:15:33.50904-07:00"}
{"id":"bd-103","title":"Multi-project MCP context switching (GH#145)","description":"Enable MCP server to manage multiple beads projects in a single session with per-request workspace_root parameter.\n\nCurrent bug: set_context(workspace_root) doesn't actually switch sockets - all operations hit first initialized socket.\n\nUse case: Managing tasks across multiple organizations with different permission models (internal, partners, open source).\n\nArchitecture: Connection pool keyed by workspace_root, each maintaining its own daemon socket connection. Request-scoped routing using ContextVar to avoid global state races.\n\nSee GH#145 for full requirements and user context.","design":"✅ APPROVED WITH MODIFICATIONS by architectural review (2025-10-25)\n\nLSP-style model is correct: Single MCP server → per-project daemons → isolated databases.\n\nCRITICAL CHANGES from review:\n1. **Simplify connection pool**: No LRU eviction initially (typical user: 2-5 projects)\n2. **Add asyncio.Lock**: Prevent race conditions in pool access\n3. **Defer health checks**: Only retry on failure, not preemptive pings\n4. **Handle submodules**: Check local .beads BEFORE git toplevel\n5. **Path canonicalization**: realpath + git toplevel with caching\n\nRISKS MITIGATED:\n- Global _client bug: Replace with connection pool keyed by canonical path\n- Race conditions: Add asyncio.Lock for pool mutations\n- Submodule edge case: Check .beads directory first\n- Stale sockets: Retry once on connection failure\n\nEstimated effort: 2.5-3.5 days (simplified from 2.5-4.5 days)\nConfidence: 8/10","acceptance_criteria":"- Multiple projects can be accessed in single MCP session\n- Per-request workspace_root parameter works on all tools\n- No cross-project data leakage\n- Concurrent calls to different projects work correctly\n- Stale sockets auto-reconnect with retry/backoff\n- Integration tests verify isolation across 2+ temp repos\n- set_context() still works as default fallback","notes":"Review doc: docs/bd-103-architectural-review.md\n\nImplementation order:\n1. bd-108 (connection manager) - Foundation with pool + lock\n2. bd-104 (ContextVar routing) - Per-request workspace\n3. bd-106 (require_context) - Validation\n4. bd-105 (tests) - Concurrency + edge cases\n5. bd-109 (docs) - Usage guide\n6. [deleted:bd-142] (health checks) - DEFERRED to Phase 2","status":"closed","priority":1,"issue_type":"epic","assignee":"amp","created_at":"2025-10-25T13:59:57.231937-07:00","updated_at":"2025-10-25T23:15:33.522558-07:00","closed_at":"2025-10-25T14:36:02.046142-07:00"}
{"id":"bd-104","title":"Implement request-scoped routing with ContextVar","description":"Add ContextVar-based routing to avoid global state races during concurrent multi-project calls.\n\nApproach:\n- Define current_workspace: ContextVar[str|None] in server.py\n- Add @with_workspace decorator that resolves workspace_root (via _resolve_workspace_root + realpath)\n- Set ContextVar for duration of tool call, reset after\n- Falls back to set_context default (BEADS_WORKING_DIR) if workspace_root not provided\n- beads_mcp.tools.get_client() reads current_workspace from ContextVar\n\nBlocks: bd-103 (connection manager must exist first)","design":"Decorator pattern with ContextVar for request-scoped workspace routing.\n\n@with_workspace decorator:\n- Extract workspace_root parameter from tool call\n- Resolve via _resolve_workspace_root + realpath\n- Set current_workspace ContextVar for request duration\n- Falls back to BEADS_WORKING_DIR if workspace_root not provided\n- Reset ContextVar after tool completes\n\nApplied to all tools in server.py. _get_client() reads current_workspace.\n\n⚠ CONCURRENCY GOTCHA (from architectural review):\n- ContextVar doesn't propagate to asyncio.create_task() spawned tasks\n- SOLUTION: Keep tool calls synchronous, no background task spawning\n- If background tasks needed: use contextvars.copy_context()\n\nDocument this limitation in bd-109.","notes":"Blocks on bd-108 (connection pool must exist first).\n\nCRITICAL: Do NOT spawn background tasks within tool implementations.\nContextVar propagation to spawned tasks is unreliable.","status":"closed","priority":1,"issue_type":"task","assignee":"amp","created_at":"2025-10-25T14:00:27.895512-07:00","updated_at":"2025-10-25T23:15:33.522814-07:00","closed_at":"2025-10-25T14:32:36.531658-07:00","dependencies":[{"issue_id":"bd-104","depends_on_id":"bd-103","type":"parent-child","created_at":"2025-10-25T14:00:27.896366-07:00","created_by":"daemon"}]}
{"id":"bd-105","title":"Add integration tests for multi-project MCP switching","description":"Comprehensive tests to verify multi-project isolation, concurrency, and edge cases.\n\nEXPANDED TEST COVERAGE (per architectural review):\n\n**Concurrency tests (CRITICAL):**\n- asyncio.gather() with calls to different workspace_root values\n- Verify no cross-project data leakage\n- Verify pool lock prevents race conditions\n\n**Edge case tests:**\n- Submodule handling: Parent repo vs submodule with own .beads\n- Symlink deduplication: Same physical path via different symlinks\n- Stale socket recovery: Kill daemon, verify retry on failure\n- Missing .beads directory handling\n\n**Isolation tests:**\n- Create 2+ temp repos with bd init\n- Verify operations in project A don't affect project B\n- Stress test: many parallel calls across 3-5 repos\n\nEstimated effort: M (1-2 days) including fixtures for temp repos and daemon process management","design":"Test structure:\n\n1. test_concurrent_multi_project.py:\n - asyncio.gather with 2+ projects\n - Verify pool lock prevents corruption\n \n2. test_path_canonicalization.py:\n - Submodule edge case (check .beads first)\n - Symlink deduplication (realpath normalization)\n \n3. test_stale_socket_recovery.py:\n - Kill daemon mid-session\n - Verify retry-on-failure works\n \n4. test_cross_project_isolation.py:\n - Create issues in project A\n - List from project B, verify empty\n - No data leakage\n\nUse pytest fixtures for temp repos and daemon lifecycle.","acceptance_criteria":"- All concurrency tests pass with asyncio.gather\n- Submodule edge case handled correctly\n- Symlinks deduplicated to same connection\n- Stale socket retry works\n- No cross-project data leakage in stress tests","status":"closed","priority":1,"issue_type":"task","assignee":"amp","created_at":"2025-10-25T14:00:27.896623-07:00","updated_at":"2025-10-25T23:15:33.509737-07:00","closed_at":"2025-10-25T14:35:13.09686-07:00","dependencies":[{"issue_id":"bd-105","depends_on_id":"bd-103","type":"parent-child","created_at":"2025-10-25T14:00:27.90028-07:00","created_by":"daemon"}]}
{"id":"bd-106","title":"Fix require_context to support per-request workspace_root","description":"Update require_context decorator to pass if either:\n- workspace_root was provided on the tool call (via ContextVar), OR\n- BEADS_WORKING_DIR is set (from set_context)\n\nStop using BEADS_DB as router - treat it only as CLI fallback.\n\nEnsures backward compatibility with set_context() while supporting new per-request routing.","status":"closed","priority":2,"issue_type":"task","created_at":"2025-10-25T14:00:27.896646-07:00","updated_at":"2025-10-25T23:15:33.509989-07:00","closed_at":"2025-10-25T14:32:36.533618-07:00","dependencies":[{"issue_id":"bd-106","depends_on_id":"bd-103","type":"parent-child","created_at":"2025-10-25T14:00:27.89804-07:00","created_by":"daemon"}]}
{"id":"bd-107","title":"Add health checks and reconnection logic for stale sockets","description":"Handle stale/broken socket connections after daemon restarts or upgrades.\n\nFeatures:\n- ping/health_check method on client\n- Check before use or periodic health check\n- On failure: drop from pool, attempt reconnect with exponential backoff\n- Clear error propagation if reconnect fails after retries\n- Handle version mismatch after daemon upgrade\n- Handle long-idle connections closed by daemon","design":"Add async ping() to DaemonClient. ConnectionManager.get_client() pings before returning cached client. On failure, del from pool and retry connect. Bounded retry (3-5 attempts) with backoff.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-25T14:00:27.8967-07:00","updated_at":"2025-10-25T23:15:33.510234-07:00","closed_at":"2025-10-25T17:35:42.762836-07:00"}
{"id":"bd-108","title":"Add connection manager for per-project daemon sockets","description":"Create connection pool for managing multiple daemon socket connections in beads_mcp.tools.\n\nSIMPLIFIED APPROACH (per architectural review):\n- Connection pool dict[str, BdClientBase] keyed by canonical path\n- Add asyncio.Lock for thread-safe pool access (CRITICAL)\n- Path canonicalization with @lru_cache for performance\n- NO LRU eviction (start simple, add if monitoring shows memory issues)\n- NO preemptive health checks (only retry on failure)\n\nFeatures:\n- get_client(workspace_root) → returns client for that project\n- Canonicalization: realpath + git toplevel (handles symlinks)\n- Submodule-aware: Check local .beads BEFORE git toplevel\n- Auto-start daemon if socket missing (existing behavior)\n- Validate version on connect (existing behavior)\n\nCRITICAL: Replace global _client singleton with pool to fix set_context() bug.","design":"Implementation in tools.py:\n\n```python\nfrom contextvars import ContextVar\nimport asyncio\nfrom functools import lru_cache\n\ncurrent_workspace: ContextVar[str | None] = ContextVar('workspace', default=None)\n_connection_pool: Dict[str, BdClientBase] = {}\n_pool_lock = asyncio.Lock() # Prevent race conditions\n\n@lru_cache(maxsize=128)\ndef _canonicalize_path(path: str) -\u003e str:\n # 1. realpath to resolve symlinks\n real = os.path.realpath(path)\n \n # 2. Check local .beads (submodule edge case)\n if os.path.exists(os.path.join(real, \".beads\")):\n return real\n \n # 3. Try git toplevel\n return _resolve_workspace_root(real)\n\nasync def _get_client() -\u003e BdClientBase:\n workspace = current_workspace.get() or os.environ.get(\"BEADS_WORKING_DIR\")\n if not workspace:\n raise BdError(\"No workspace set\")\n \n canonical = _canonicalize_path(workspace)\n \n async with _pool_lock: # CRITICAL: prevent concurrent mutations\n if canonical not in _connection_pool:\n _connection_pool[canonical] = create_bd_client(\n prefer_daemon=True,\n working_dir=canonical\n )\n return _connection_pool[canonical]\n```\n\n~200 LOC total (simplified from ~400-500)","status":"closed","priority":1,"issue_type":"task","assignee":"amp","created_at":"2025-10-25T14:00:27.896896-07:00","updated_at":"2025-10-25T23:15:33.511078-07:00","closed_at":"2025-10-25T14:31:08.910695-07:00","dependencies":[{"issue_id":"bd-108","depends_on_id":"bd-103","type":"parent-child","created_at":"2025-10-25T14:00:27.89917-07:00","created_by":"daemon"}]}
{"id":"bd-109","title":"Update MCP multi-project documentation","description":"Update documentation for multi-project workflow in README.md, AGENTS.md, and MCP integration docs.\n\nEXPANDED SECTIONS (per architectural review):\n\n**Usage examples:**\n- Per-request workspace_root parameter usage\n- Concurrent multi-project queries with asyncio.gather\n- Migration from set_context() to workspace_root parameter\n\n**Architecture notes:**\n- Connection pooling behavior (no limits initially)\n- set_context() as default fallback (still supported)\n- Library users NOT affected (all changes in MCP layer)\n\n**Concurrency gotchas (CRITICAL):**\n- ContextVar doesn't propagate to asyncio.create_task()\n- Do NOT spawn background tasks in tool implementations\n- All tool calls should be synchronous/sequential\n\n**Troubleshooting:**\n- Stale sockets (retry once on failure)\n- Version mismatches (auto-detected since v0.16.0)\n- Path aliasing via symlinks (deduplicated by realpath)\n- Submodules with own .beads (handled correctly)\n\n**Use cases:**\n- Multi-organization collaboration (GH#145)\n- Parallel project management scripts\n- Cross-project queries","design":"Documentation structure:\n\n1. integrations/beads-mcp/README.md:\n - Add \"Multi-Project Support\" section\n - workspace_root parameter examples\n - Connection pool behavior\n \n2. AGENTS.md:\n - Update MCP section with workspace_root usage\n - Add concurrency warning (no spawned tasks)\n - Document library non-impact\n \n3. New: docs/MCP_MULTI_PROJECT.md:\n - Detailed architecture explanation\n - Migration guide from set_context()\n - Troubleshooting guide\n - Edge cases (submodules, symlinks)","status":"closed","priority":2,"issue_type":"task","assignee":"amp","created_at":"2025-10-25T14:00:27.897025-07:00","updated_at":"2025-10-25T23:15:33.511411-07:00","closed_at":"2025-10-25T14:35:55.392654-07:00","dependencies":[{"issue_id":"bd-109","depends_on_id":"bd-103","type":"parent-child","created_at":"2025-10-25T14:00:27.901495-07:00","created_by":"daemon"}]}
{"id":"bd-11","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.\n\n**Key Benefits:**\n- Remove 3000+ lines of duplicated SQLite code\n- Eliminate schema drift between bd and vc CLIs\n- Inherit Beads improvements automatically\n- Stronger type safety with Beads error types\n- Faster development velocity for new features\n- Clean separation: Beads stays general-purpose, VC extends via wrapper\n\n**Architecture Principle:**\nBeads 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.\n\n**Current Pain Points:**\n1. Code Duplication: Issue CRUD, dependency graphs, labels, status transitions all reimplemented\n2. Schema Drift Risk: VC schema manually defined, could diverge from Beads\n3. Lost Features: Can't leverage Beads query optimizer or advanced features without process spawning\n4. Atomic Operations: Hand-rolled 100+ line transaction management\n5. Maintenance Burden: Every Beads feature must be manually replicated\n\n**Concrete Example:**\nWhen Beads adds a new field (e.g., estimated_hours):\n- Current: 4-6 hours of manual work (update types, 6+ SQL queries, migration, testing)\n- With Library: 5 minutes (go get -u github.com/steveyegge/beads)\n\n**Phased Approach:**\n1. Phase 1: Add Beads dependency (non-breaking, feature flag)\n2. Phase 2: Implement VCStorage wrapper (embeds beads.Storage)\n3. Phase 3: Migration script for existing databases\n4. Phase 4: Gradual cutover, deprecate SQLite code\n\n**Related Analysis:**\nSee 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).\n\n**Estimated Effort:** 3-4 sprints\n**Priority:** P2 (Medium-High - architectural improvement, high ROI)","notes":"Phase 1 (bd-12) 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.","status":"closed","priority":2,"issue_type":"epic","created_at":"2025-10-22T14:04:08.692803-07:00","updated_at":"2025-10-25T23:15:33.518516-07:00","closed_at":"2025-10-22T14:40:10.225406-07:00"}
{"id":"bd-110","title":"bd daemon auto-sync can wipe out issues.jsonl when database is empty","description":"During dogfooding session, bd daemon auto-sync exported empty database to JSONL, losing all 177 issues. Had to git restore to recover.\n\nRoot cause: bd export doesn't check if database is empty before exporting. When daemon has empty/wrong database, it wipes out valid JSONL file.\n\nImpact: DATA LOSS","design":"Add safeguard in bd export:\n1. Count total issues in database before export\n2. If count is 0, refuse to export and show error\n3. Provide --force flag to override if truly want empty export\n\nAlternative: Check if target JSONL exists and has issues, warn if about to replace with empty export","acceptance_criteria":"- bd export refuses to export when database has 0 issues\n- Clear error message: \"Refusing to export empty database (0 issues). Use --force to override.\"\n- --force flag allows override for intentional empty exports\n- Test: export with empty db fails, export with --force succeeds","status":"closed","priority":0,"issue_type":"bug","created_at":"2025-10-25T16:29:16.045548-07:00","updated_at":"2025-10-25T23:15:33.511656-07:00","closed_at":"2025-10-25T16:35:38.233384-07:00"}
{"id":"bd-111","title":"bd import doesn't update database modification time (WAL mode)","description":"When running bd import in WAL mode, the -wal file is updated but main .db file timestamp stays old. This breaks staleness detection which only checks main .db file.\n\nDiscovered during dogfooding when import didn't trigger staleness refresh.\n\nImpact: Staleness checks fail to detect that database is newer than expected","design":"Two options:\n1. Checkpoint WAL after import to flush changes to main .db file\n2. Update staleness detection to check both .db and -wal file timestamps\n\nOption 1 is simpler and safer - just add PRAGMA wal_checkpoint(FULL) after import completes","acceptance_criteria":"- After bd import, main .db file modification time is updated\n- Staleness detection correctly sees database as fresh\n- Test: import, check .db mtime, verify it's recent","status":"closed","priority":1,"issue_type":"bug","created_at":"2025-10-25T16:29:16.048176-07:00","updated_at":"2025-10-25T23:15:33.511871-07:00","closed_at":"2025-10-25T16:37:49.940187-07:00"}
{"id":"bd-112","title":"bd should show which database file it's using","description":"During dogfooding, bd showed \"0 issues\" when correct database had 177 issues. Confusion arose from which database path was being used (daemon default vs explicit --db flag).\n\nUsers need clear feedback about which database file bd is actually using, especially when daemon is involved.\n\nImpact: User confusion, working with wrong database unknowingly","design":"Add database path to verbose output or as a bd info command:\n1. bd info shows current database path, daemon status\n2. OR: bd ready/list/etc --verbose shows \"Using database: /path/to/.beads/beads.db\"\n3. Consider adding to bd status output\n\nWhen database path differs from expected, show warning","acceptance_criteria":"- User can easily determine which database file bd is using\n- bd info or similar command shows full database path\n- When using unexpected database (e.g., daemon vs explicit --db), show clear indication\n- Documentation updated with how to check database path","status":"closed","priority":1,"issue_type":"feature","assignee":"amp","created_at":"2025-10-25T16:29:16.059118-07:00","updated_at":"2025-10-25T23:15:33.512099-07:00","closed_at":"2025-10-25T16:42:45.768187-07:00"}
{"id":"bd-113","title":"Implement configurable sort policy for GetReadyWork","description":"Add SortPolicy field to WorkFilter to support different sorting strategies:\n- hybrid (default): Recent issues by priority, old by age\n- priority: Strict priority ordering for autonomous execution\n- oldest: Backlog clearing mode\n\nSolves issue where VC executor selects low-priority work instead of critical P0 work.","design":"See SORT_POLICY_DESIGN.md for complete design spec including:\n- Type definitions and constants\n- SQL ORDER BY clause generation\n- Testing strategy with test cases\n- CLI integration with --sort flag\n- Migration plan and backwards compatibility","acceptance_criteria":"- SortPolicy type added to types.go\n- buildOrderByClause() implemented in ready.go\n- Unit tests for all 3 policies pass\n- Integration tests verify priority selection order\n- bd ready --sort priority|oldest|hybrid works\n- Empty SortPolicy defaults to hybrid (backwards compatible)\n- Documentation updated in README.md and WORKFLOW.md","status":"closed","priority":1,"issue_type":"feature","created_at":"2025-10-25T18:46:44.35198-07:00","updated_at":"2025-10-25T23:15:33.51234-07:00","closed_at":"2025-10-25T18:53:02.258745-07:00"}
{"id":"bd-114","title":"Add configurable SortPolicy to GetReadyWork","description":"Add SortPolicy field to WorkFilter to support different ordering strategies: hybrid (default), priority-first, oldest-first. See SORT_POLICY_DESIGN.md for full specification.","design":"See SORT_POLICY_DESIGN.md for complete design.\n\nImplementation summary:\n1. Add SortPolicy type and constants (hybrid, priority, oldest)\n2. Add SortPolicy field to WorkFilter \n3. Implement buildOrderByClause() to generate SQL based on policy\n4. Default to hybrid for backwards compatibility\n5. Add --sort flag to bd ready command\n\nThis enables autonomous execution systems (like VC) to use strict priority ordering while preserving the current hybrid behavior for interactive use.","acceptance_criteria":"Unit tests verify each policy generates correct ORDER BY. Integration tests verify priority, hybrid, and oldest policies select issues in expected order. CLI bd ready --sort priority works. Empty SortPolicy defaults to hybrid (backwards compatible).","status":"closed","priority":1,"issue_type":"feature","created_at":"2025-10-25T18:51:11.560979-07:00","updated_at":"2025-10-26T12:25:44.40049-07:00","closed_at":"2025-10-26T12:25:44.40049-07:00"}
{"id":"bd-115","title":"Implement exclusive lock protocol for daemon/external tool coexistence","description":"VC (VibeCoder) cannot coexist with bd daemon managing the same database. VC needs deterministic execution and directly manages JSONL sync, but daemon's auto-flush creates timing conflicts and nondeterministic behavior.\n\nCurrent workaround (vc-195): VC kills ALL bd daemon processes with pkill, which is too aggressive and prevents developers from using daemon for their own workflow.\n\nSolution: Implement lock file protocol (.beads/.exclusive-lock) that allows applications to claim exclusive management of a database. bd daemon respects these locks and skips locked databases.\n\nSee VC_DAEMON_EXCLUSION_PROTOCOL.md for full specification.","design":"Lock File Protocol:\n- File: .beads/.exclusive-lock (JSON format)\n- Contains: holder name, PID, hostname, timestamp, version\n- Created when external tool (VC) starts\n- Removed on clean shutdown\n- Stale lock detection: if PID doesn't exist, lock is removed\n\nbd daemon behavior:\n1. Before touching any database, check for .exclusive-lock\n2. If lock exists and valid (PID alive): skip database in sync cycle\n3. If lock is stale (PID dead): remove lock and proceed\n4. If lock is malformed: log warning and skip (fail-safe)\n\nExternal tool behavior:\n1. On startup: create .exclusive-lock with process info\n2. If lock exists, check if stale; fail if another process is running\n3. On shutdown: remove .exclusive-lock\n\nBenefits:\n- Clean separation, no process killing\n- Developer-friendly (can run daemon for other projects)\n- Fail-safe with stale lock detection\n- Extensible for other tools beyond VC","acceptance_criteria":"1. bd daemon skips databases with valid exclusive locks\n2. bd daemon cleans up stale locks automatically\n3. Lock file format documented and implemented\n4. Integration tests show daemon + external tool coexistence\n5. Documentation updated with protocol specification","status":"closed","priority":1,"issue_type":"epic","created_at":"2025-10-25T22:43:08.994891-07:00","updated_at":"2025-10-25T23:24:55.928527-07:00","closed_at":"2025-10-25T23:24:55.928527-07:00"}
{"id":"bd-116","title":"Add ExclusiveLock struct and JSON marshaling","description":"Create Go struct to represent exclusive lock file format with JSON marshaling support.\n\nFields needed:\n- Holder (string): name of lock holder (e.g., \"vc-executor\")\n- PID (int): process ID\n- Hostname (string): hostname where process is running\n- StartedAt (time.Time): when lock was acquired\n- Version (string): version of lock holder\n\nShould support both Marshal and Unmarshal for reading/writing lock files.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-25T22:43:18.536901-07:00","updated_at":"2025-10-25T23:19:48.792787-07:00","closed_at":"2025-10-25T23:19:48.792787-07:00","dependencies":[{"issue_id":"bd-116","depends_on_id":"bd-115","type":"parent-child","created_at":"2025-10-25T22:43:18.538184-07:00","created_by":"daemon"}]}
{"id":"bd-117","title":"Implement isProcessAlive() helper for PID validation","description":"Implement helper function to check if a process is alive given PID and hostname.\n\nLogic:\n- If hostname != current host: return true (can't verify remote, assume alive)\n- If hostname == current host: check if PID exists using os.FindProcess + Signal(0)\n- Return true if process exists, false otherwise\n\nNeeded for stale lock detection.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-25T22:43:26.074997-07:00","updated_at":"2025-10-25T23:20:24.641036-07:00","closed_at":"2025-10-25T23:20:24.641036-07:00","dependencies":[{"issue_id":"bd-117","depends_on_id":"bd-115","type":"parent-child","created_at":"2025-10-25T22:43:28.313879-07:00","created_by":"daemon"}]}
{"id":"bd-118","title":"Implement shouldSkipDatabase() to check for exclusive locks","description":"Add shouldSkipDatabase() function to daemon that checks for .beads/.exclusive-lock before processing a database.\n\nLogic:\n1. Check if .beads/.exclusive-lock exists\n2. If not: return false (proceed with database)\n3. If yes: read and parse JSON\n4. If malformed: log warning and skip (fail-safe)\n5. If valid: check if PID is alive\n6. If stale (PID dead): remove lock file and proceed\n7. If active (PID alive): log skip message and return true\n\nDepends on ExclusiveLock struct and isProcessAlive() helper.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-25T22:43:34.561247-07:00","updated_at":"2025-10-25T23:21:33.58887-07:00","closed_at":"2025-10-25T23:21:33.58887-07:00","dependencies":[{"issue_id":"bd-118","depends_on_id":"bd-116","type":"blocks","created_at":"2025-10-25T22:43:36.6504-07:00","created_by":"daemon"},{"issue_id":"bd-118","depends_on_id":"bd-117","type":"blocks","created_at":"2025-10-25T22:43:38.730862-07:00","created_by":"daemon"},{"issue_id":"bd-118","depends_on_id":"bd-115","type":"parent-child","created_at":"2025-10-25T22:43:40.602161-07:00","created_by":"daemon"}]}
{"id":"bd-119","title":"Integrate exclusive lock check into daemon sync cycle","description":"Integrate shouldSkipDatabase() into daemon's sync cycle to respect exclusive locks.\n\nBefore processing each database:\n1. Call shouldSkipDatabase(beadsDir)\n2. If true: skip all operations (export, import, commit, push)\n3. If false: proceed with normal sync\n\nAdd appropriate logging:\n- \"Skipping .beads/foo.db (locked by vc-executor, PID 12345)\" when skipping\n- \"Removed stale lock at .beads/foo.db (PID 12345 not found)\" when cleaning up\n\nDepends on shouldSkipDatabase() implementation.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-25T22:43:46.221736-07:00","updated_at":"2025-10-25T23:21:58.454603-07:00","closed_at":"2025-10-25T23:21:58.454603-07:00","dependencies":[{"issue_id":"bd-119","depends_on_id":"bd-118","type":"blocks","created_at":"2025-10-25T22:43:48.204682-07:00","created_by":"daemon"},{"issue_id":"bd-119","depends_on_id":"bd-115","type":"parent-child","created_at":"2025-10-25T22:43:50.283951-07:00","created_by":"daemon"}]}
{"id":"bd-12","title":"Phase 1: Add Beads Dependency (Non-Breaking)","description":"Introduce Beads library alongside existing SQLite code without breaking production.\n\n**Goal:** Add Beads as optional dependency with feature flag, establish compatibility baseline.\n\n**Key Tasks:**\n1. Add github.com/steveyegge/beads to go.mod\n2. Create compatibility test suite comparing VC SQLite vs Beads schema\n3. Identify schema differences and document migration requirements\n4. Create internal/storage/beads/adapter.go implementing Storage interface\n5. Add feature flag: VC_USE_BEADS_LIBRARY=true (disabled by default)\n\n**Acceptance Criteria:**\n- Beads library imported successfully\n- Compatibility tests pass identifying all schema differences\n- Both implementations coexist without conflicts\n- No production impact (feature flag disabled by default)\n- Documentation of schema differences and migration needs\n\n**Technical Details:**\n- Use feature flag to allow A/B testing\n- Compatibility tests must cover: issues, dependencies, labels, status transitions, ID generation\n- Adapter must implement full Storage interface\n- Zero changes to existing production code paths\n\n**Blockers:** None - can start immediately\n\n**Estimated Effort:** 1 sprint","status":"closed","priority":2,"issue_type":"task","created_at":"2025-10-22T14:04:20.24179-07:00","updated_at":"2025-10-25T23:15:33.471639-07:00","closed_at":"2025-10-22T14:36:08.066041-07:00","dependencies":[{"issue_id":"bd-12","depends_on_id":"bd-11","type":"parent-child","created_at":"2025-10-24T13:17:40.322877-07:00","created_by":"renumber"}]}
{"id":"bd-120","title":"Add unit tests for exclusive lock detection","description":"Add unit tests for exclusive lock functionality:\n\nTest cases:\n1. No lock file exists -\u003e shouldSkipDatabase returns false\n2. Valid lock with alive PID -\u003e shouldSkipDatabase returns true\n3. Stale lock with dead PID -\u003e removes lock, returns false\n4. Malformed lock JSON -\u003e logs warning, returns true (fail-safe)\n5. Lock with different hostname -\u003e assumes alive, returns true\n6. isProcessAlive() correctly detects running/dead processes\n\nUse test helpers to create lock files with specific PIDs.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-25T22:43:57.616-07:00","updated_at":"2025-10-25T23:22:12.680681-07:00","closed_at":"2025-10-25T23:22:12.680681-07:00","dependencies":[{"issue_id":"bd-120","depends_on_id":"bd-118","type":"blocks","created_at":"2025-10-25T22:44:00.494553-07:00","created_by":"daemon"},{"issue_id":"bd-120","depends_on_id":"bd-115","type":"parent-child","created_at":"2025-10-25T22:44:02.7215-07:00","created_by":"daemon"}]}
{"id":"bd-121","title":"Add integration tests for daemon + external tool coexistence","description":"Add integration tests simulating real-world daemon + external tool usage:\n\nTest scenarios:\n1. Start daemon, create lock file, verify daemon skips database\n2. Create stale lock (with dead PID), start daemon, verify lock cleanup\n3. Multiple lock/unlock cycles\n4. Daemon resumes managing database after lock is removed\n5. Lock file created/removed during daemon operation\n\nShould verify:\n- Daemon log messages correct\n- No JSONL auto-flush when database is locked\n- Daemon resumes normal operation after lock removed","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-25T22:44:08.686473-07:00","updated_at":"2025-10-25T23:23:31.488427-07:00","closed_at":"2025-10-25T23:23:31.488427-07:00","dependencies":[{"issue_id":"bd-121","depends_on_id":"bd-119","type":"blocks","created_at":"2025-10-25T22:44:10.75056-07:00","created_by":"daemon"},{"issue_id":"bd-121","depends_on_id":"bd-115","type":"parent-child","created_at":"2025-10-25T22:44:12.984228-07:00","created_by":"daemon"}]}
{"id":"bd-122","title":"Document exclusive lock protocol in README and new doc file","description":"Update documentation to explain exclusive lock protocol:\n\n1. Create EXCLUSIVE_LOCK.md with:\n - Protocol specification\n - Lock file format (JSON schema)\n - Usage examples for external tools\n - Stale lock behavior\n - Edge cases and limitations\n\n2. Update README.md:\n - Mention exclusive lock support in daemon section\n - Link to EXCLUSIVE_LOCK.md for details\n\n3. Update AGENTS.md:\n - Note that external tools can use exclusive locks\n - Explain daemon skips locked databases\n\nTarget audience: developers integrating bd with external tools (like VC).","status":"closed","priority":2,"issue_type":"task","created_at":"2025-10-25T22:44:18.676992-07:00","updated_at":"2025-10-25T23:23:31.489472-07:00","closed_at":"2025-10-25T23:23:31.489472-07:00","dependencies":[{"issue_id":"bd-122","depends_on_id":"bd-119","type":"blocks","created_at":"2025-10-25T22:44:22.31844-07:00","created_by":"daemon"},{"issue_id":"bd-122","depends_on_id":"bd-115","type":"parent-child","created_at":"2025-10-25T22:44:24.324785-07:00","created_by":"daemon"}]}
{"id":"bd-123","title":"Add staleness check to non-daemon mode","description":"Extend staleness detection to non-daemon mode (--no-daemon).\n\nImplementation:\n- On database open, check if .beads/issues.jsonl exists\n- If JSONL exists and is newer than .db file: auto-import\n- Compare JSONL mtime vs .db mtime (both os.Stat)\n- Log: \"Auto-importing from .beads/issues.jsonl (newer than database)\"\n\nThis ensures both daemon and non-daemon modes handle git pull correctly.","notes":"INVESTIGATION COMPLETE:\n\nThe requested feature is already implemented in ensureStoreActive() (cmd/bd/direct_mode.go:79-81) which calls autoImportIfNewer() on every database open in non-daemon mode.\n\nThe implementation uses hash-based staleness detection via autoimport.AutoImportIfNewer() instead of mtime-based, which is BETTER because:\n1. Avoids unnecessary imports when file is merely touched\n2. Detects actual content changes reliably \n3. Works correctly after git pull\n\nVerified working with BD_DEBUG=1:\n```\nBD_DEBUG=1 ./bd --no-daemon stats\nDebug: auto-import skipped, JSONL unchanged (hash match)\n```\n\nThe issue description requested mtime-based approach like daemon mode, but hash-based is superior for non-daemon usage. Both modes now have auto-import after git pull.","status":"closed","priority":0,"issue_type":"task","created_at":"2025-10-25T22:46:44.664917-07:00","updated_at":"2025-10-26T12:23:13.349472-07:00","closed_at":"2025-10-26T12:23:13.349472-07:00"}
{"id":"bd-124","title":"Add 'bd sync' command for explicit synchronization","description":"Add explicit `bd sync` command as fallback for manual synchronization after git pull.\n\nBehavior:\n- Import from .beads/issues.jsonl\n- If daemon mode: send RPC command to daemon to re-import\n- If non-daemon: directly import to local db\n- Show summary: \"Imported N issues, updated M issues\"\n\nUsage:\n```bash\ngit pull\nbd sync # Force immediate sync\n```\n\nThis complements auto-detection but gives users manual control.","notes":"IMPLEMENTED:\n\nAdded `bd sync --import-only` flag that:\n- Imports from .beads/issues.jsonl automatically (no need to specify path)\n- Works in both daemon and non-daemon modes\n- Shows summary: \"Import complete: X created, Y updated, Z unchanged, N remapped\"\n- Handles collisions automatically with --resolve-collisions\n\nUsage:\n```bash\ngit pull\nbd sync --import-only # Force immediate sync\n```\n\nThe existing `bd sync` command does full git workflow (export, commit, pull, import, push). The new --import-only flag complements --flush-only for granular control.\n\nImplementation in cmd/bd/sync.go","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-25T22:46:52.139434-07:00","updated_at":"2025-10-26T12:27:40.539108-07:00","closed_at":"2025-10-26T12:27:40.539108-07:00"}
{"id":"bd-125","title":"Add integration test for git pull sync scenario","description":"Add integration test simulating the git pull sync issue.\n\nTest scenario:\n1. Create temp git repo with beads initialized\n2. Clone 1: Create and close issue, export, commit, push\n3. Clone 2: Start daemon, git pull\n4. Clone 2: Verify bd show \u003cissue\u003e reflects closed status immediately\n5. Verify no manual import or daemon restart needed\n\nAlso test:\n- Non-daemon mode (--no-daemon) handles git pull correctly\n- bd sync command works in both modes\n- Performance: staleness check adds \u003c10ms overhead\n\nDepends on staleness detection implementation.","status":"closed","priority":0,"issue_type":"task","created_at":"2025-10-25T22:47:01.101808-07:00","updated_at":"2025-10-26T12:32:34.054034-07:00","closed_at":"2025-10-26T12:32:34.054034-07:00","dependencies":[{"issue_id":"bd-125","depends_on_id":"bd-123","type":"blocks","created_at":"2025-10-25T22:47:05.615638-07:00","created_by":"daemon"}]}
{"id":"bd-126","title":"Add optional post-merge git hook example for bd sync","description":"Create example git hook that auto-runs bd sync after git pull/merge.\n\nAdd to examples/git-hooks/:\n- post-merge hook that checks if .beads/issues.jsonl changed\n- If changed: run `bd sync` automatically\n- Make it optional/documented (not auto-installed)\n\nBenefits:\n- Zero-friction sync after git pull\n- Complements auto-detection as belt-and-suspenders\n\nNote: post-merge hook already exists for pre-commit/post-merge. Extend it to support sync.","status":"open","priority":2,"issue_type":"task","created_at":"2025-10-25T22:47:14.668842-07:00","updated_at":"2025-10-25T23:15:33.515404-07:00","dependencies":[{"issue_id":"bd-126","depends_on_id":"bd-124","type":"blocks","created_at":"2025-10-25T22:47:16.949519-07:00","created_by":"daemon"}]}
{"id":"bd-127","title":"Update documentation for auto-sync behavior","description":"Update documentation to explain auto-sync after git pull.\n\nFiles to update:\n1. README.md - Add section on git workflow and auto-sync\n2. AGENTS.md - Note that bd auto-detects JSONL changes after git pull\n3. WORKFLOW.md - Update git pull workflow to remove manual import step\n4. FAQ.md - Add Q\u0026A about sync behavior and staleness\n\nKey points:\n- bd automatically detects when JSONL is newer than database\n- No manual import needed after git pull\n- bd sync command available for manual control\n- Optional git hook for guaranteed sync","status":"closed","priority":2,"issue_type":"task","created_at":"2025-10-25T22:47:24.618649-07:00","updated_at":"2025-10-26T12:44:33.996187-07:00","closed_at":"2025-10-26T12:44:33.996187-07:00"}
{"id":"bd-128","title":"Refactor autoImportIfNewer to be callable from daemon","description":"The staleness check in [deleted:bd-160] detects when JSONL is newer than last import, but can't trigger the actual import because autoImportIfNewer() is in cmd/bd and uses global variables.\n\nNeed to:\n1. Extract core import logic from autoImportIfNewer() into importable function\n2. Move to internal/autoimport or similar package\n3. Make it callable from daemon (no global state dependency)\n4. Update staleness check in server.go to call actual import instead of just logging\n\nThis completes the auto-sync feature - daemon will truly auto-import after git pull.","status":"closed","priority":0,"issue_type":"task","created_at":"2025-10-25T23:10:41.392416-07:00","updated_at":"2025-10-25T23:51:09.811006-07:00","closed_at":"2025-10-25T23:51:09.811006-07:00"}
{"id":"bd-129","title":"Enforce daemon singleton per workspace with file locking","description":"Agent in ~/src/wyvern discovered 4 simultaneous daemon processes running, causing infinite directory recursion (.beads/.beads/.beads/...). Each daemon used relative paths and created nested .beads/ directories.\n\nRoot cause: No singleton enforcement. Multiple `bd daemon` processes can start in same workspace.\n\nExpected: One daemon per workspace (each workspace = separate .beads/ dir with bd.sock)\nActual: Multiple daemons can run simultaneously in same workspace\n\nNote: Separate git clones = separate workspaces = separate daemons (correct). Git worktrees share .beads/ and have known limitations (documented, use --no-daemon).","design":"Use flock (file locking) on daemon socket or database file to enforce singleton:\n\n1. On daemon start, attempt exclusive lock on .beads/bd.sock or .beads/daemon.lock\n2. If lock held by another process, refuse to start (exit with clear error)\n3. Hold lock for lifetime of daemon process\n4. Release lock on daemon shutdown\n\nAlternative: Use PID file with stale detection (check if PID is still running)\n\nImplementation location: Daemon startup code in cmd/bd/ or internal/daemon/","acceptance_criteria":"1. Starting second daemon process in same workspace fails with clear error\n2. Test: Start daemon, attempt second start, verify failure\n3. Killing daemon releases lock, allowing new daemon to start\n4. No infinite .beads/ directory recursion possible\n5. Works correctly with auto-start mechanism","status":"in_progress","priority":0,"issue_type":"bug","created_at":"2025-10-25T23:13:12.269549-07:00","updated_at":"2025-10-25T23:15:33.516072-07:00"}
{"id":"bd-13","title":"Phase 2: Implement VCStorage Wrapper","description":"Create VCStorage wrapper that embeds beads.Storage and adds VC-specific operations.\n\n**Goal:** Build clean abstraction layer where VC extends Beads without modifying Beads library.\n\n**Architecture:**\n- VCStorage embeds beads.Storage (delegates core operations)\n- VCStorage adds VC-specific methods (executor instances, events)\n- Same database, separate table namespaces (Beads tables + VC tables)\n- Zero changes to Beads library code\n\n**Key Tasks:**\n1. Create VCStorage struct that embeds beads.Storage\n2. Implement VC-specific methods: CreateExecutorInstance(), GetStaleExecutors(), LogEvent(), UpdateExecutionState()\n3. Create VC table schemas (executor_instances, issue_execution_state, agent_events)\n4. Verify type compatibility between VC types.Issue and Beads Issue\n5. Create MockVCStorage for testing\n6. Write unit tests for VC-specific methods\n7. Write integration tests (end-to-end with Beads)\n8. Benchmark performance vs current SQLite\n9. Verify NO changes needed to Beads library\n\n**Acceptance Criteria:**\n- VCStorage successfully wraps Beads storage (embedding works)\n- VC-specific tables created and accessible via foreign keys to Beads tables\n- VC-specific methods work (executor instances, events)\n- Core operations delegate to Beads correctly\n- Tests pass with \u003e90% coverage\n- Performance benchmark shows no regression\n- Beads library remains unmodified and standalone\n\n**Technical Details:**\n- Use beadsStore.DB() to get underlying database connection\n- Create VC tables with FOREIGN KEY references to Beads issues table\n- Schema separation: Beads owns (issues, dependencies, labels), VC owns (executor_instances, agent_events)\n- Testing: Embed MockBeadsStorage in MockVCStorage\n\n**Dependencies:**\n- Blocked by Phase 1 (need Beads library imported)\n\n**Estimated Effort:** 1.5 sprints","status":"closed","priority":2,"issue_type":"task","created_at":"2025-10-22T14:04:36.674165-07:00","updated_at":"2025-10-25T23:15:33.472658-07:00","closed_at":"2025-10-22T21:37:48.747033-07:00","dependencies":[{"issue_id":"bd-13","depends_on_id":"bd-11","type":"parent-child","created_at":"2025-10-24T13:17:40.321936-07:00","created_by":"renumber"},{"issue_id":"bd-13","depends_on_id":"bd-12","type":"blocks","created_at":"2025-10-24T13:17:40.322171-07:00","created_by":"renumber"}]}
{"id":"bd-130","title":"Track last JSONL import timestamp in daemon state","description":"Add state tracking to daemon to record when .beads/issues.jsonl was last imported.\n\nImplementation:\n- Add lastImportTime field to daemon state (time.Time)\n- Update timestamp after successful import\n- Persist across RPC requests (in-memory state)\n- Initialize on daemon startup\n\nNeeded for staleness detection to compare against JSONL mtime.","status":"closed","priority":0,"issue_type":"task","created_at":"2025-10-25T23:13:12.270048-07:00","updated_at":"2025-10-25T23:15:33.516267-07:00","closed_at":"2025-10-25T23:04:33.056154-07:00"}
{"id":"bd-131","title":"Implement staleness check before serving daemon requests","description":"Add staleness detection to daemon RPC handler that checks if JSONL is newer than last import.\n\nLogic:\n1. Before processing any RPC request (show, list, ready, etc.)\n2. Get .beads/issues.jsonl mtime (os.Stat)\n3. Compare with lastImportTime\n4. If JSONL mtime \u003e lastImportTime: auto-import before processing request\n5. If import fails: log error but continue with existing data\n\nPerformance: mtime check is fast (\u003c1ms). Only imports if needed.\n\nDepends on lastImportTime tracking.","status":"closed","priority":0,"issue_type":"task","created_at":"2025-10-25T23:13:12.270392-07:00","updated_at":"2025-10-25T23:15:33.516457-07:00","closed_at":"2025-10-25T23:04:33.056796-07:00"}
{"id":"bd-132","title":"Daemon fails to auto-import after git pull updates JSONL","description":"After git pull updates .beads/issues.jsonl, daemon doesn't automatically re-import changes, causing stale data to be shown until next sync cycle (up to 5 minutes).\n\nReproduction:\n1. Repo A: Close issues, export, commit, push\n2. Repo B: git pull (successfully updates .beads/issues.jsonl)\n3. bd show \u003cissue\u003e shows OLD status from daemon's SQLite db\n4. JSONL on disk has correct new status\n\nRoot cause: Daemon sync cycle runs on timer (5min). When user manually runs git pull, daemon doesn't detect JSONL was updated externally and continues serving stale data from SQLite.\n\nImpact:\n- High for AI agents using beads in git workflows\n- Breaks fundamental git-as-source-of-truth model\n- Confusing UX: git log shows commit, bd shows old state\n- Data consistency issues between JSONL and daemon\n\nSee WYVERN_SYNC_ISSUE.md for full analysis.","design":"Three possible solutions:\n\nOption 1: Auto-detect and re-import (recommended)\n- Before serving any bd command, check if .beads/issues.jsonl mtime \u003e last import time\n- If newer, auto-import before processing request\n- Fast check, minimal overhead\n\nOption 2: File watcher in daemon\n- Daemon watches .beads/issues.jsonl for mtime changes\n- Auto-imports when file changes\n- More complex, requires file watching infrastructure\n\nOption 3: Explicit sync command\n- User runs `bd sync` after git pull\n- Manual, error-prone, defeats automation\n\nRecommended: Option 1 (auto-detect) + Option 3 (explicit sync) as fallback.","acceptance_criteria":"1. After git pull updates .beads/issues.jsonl, next bd command sees fresh data\n2. No manual import or daemon restart required\n3. Performance impact \u003c 10ms per command (mtime check is fast)\n4. Works in both daemon and non-daemon modes\n5. Test: Two repo clones, update in one, pull in other, verify immediate sync","notes":"**Current Status (2025-10-26):**\n\n✅ **Completed (bd-128):**\n- Created internal/autoimport package with staleness detection\n- Daemon can detect when JSONL is newer than last import\n- Infrastructure exists to call import logic\n\n❌ **Remaining Work:**\nThe daemon's importFunc in server.go (line 2096-2102) is a stub that just logs a notice. It needs to actually import the issues.\n\n**Problem:** \n- importIssuesCore is in cmd/bd package, not accessible from internal/rpc\n- daemon's handleImport() returns 'not yet implemented' error\n\n**Two approaches:**\n1. Move importIssuesCore to internal/import package (shares with daemon)\n2. Use storage layer directly in daemon (create/update issues via Storage interface)\n\n**Blocker:** \nThis is the critical bug causing data corruption:\n- Agent A pushes changes\n- Agent B does git pull\n- Agent B's daemon serves stale SQLite data\n- Agent B exports stale data back to JSONL, overwriting Agent A's changes\n- Agent B pushes, losing Agent A's work\n\n**Next Steps:**\n1. Choose approach (probably #1 - move importIssuesCore to internal/import)\n2. Implement real importFunc in daemon's checkAndAutoImportIfStale()\n3. Test with two-repo scenario (push from A, pull in B, verify B sees changes)\n4. Ensure no data corruption in multi-agent workflows","status":"in_progress","priority":0,"issue_type":"epic","created_at":"2025-10-25T23:13:12.270766-07:00","updated_at":"2025-10-26T12:11:20.217716-07:00"}
{"id":"bd-133","title":"Enforce daemon singleton per workspace with file locking","description":"Agent in ~/src/wyvern discovered 4 simultaneous daemon processes running, causing infinite directory recursion (.beads/.beads/.beads/...). Each daemon used relative paths and created nested .beads/ directories.\n\nRoot cause: No singleton enforcement. Multiple `bd daemon` processes can start in same workspace.\n\nExpected: One daemon per workspace (each workspace = separate .beads/ dir with bd.sock)\nActual: Multiple daemons can run simultaneously in same workspace\n\nNote: Separate git clones = separate workspaces = separate daemons (correct). Git worktrees share .beads/ and have known limitations (documented, use --no-daemon).","design":"Use flock (file locking) on daemon socket or database file to enforce singleton:\n\n1. On daemon start, attempt exclusive lock on .beads/bd.sock or .beads/daemon.lock\n2. If lock held by another process, refuse to start (exit with clear error)\n3. Hold lock for lifetime of daemon process\n4. Release lock on daemon shutdown\n\nAlternative: Use PID file with stale detection (check if PID is still running)\n\nImplementation location: Daemon startup code in cmd/bd/ or internal/daemon/","acceptance_criteria":"1. Starting second daemon process in same workspace fails with clear error\n2. Test: Start daemon, attempt second start, verify failure\n3. Killing daemon releases lock, allowing new daemon to start\n4. No infinite .beads/ directory recursion possible\n5. Works correctly with auto-start mechanism","status":"closed","priority":0,"issue_type":"bug","created_at":"2025-10-25T23:15:14.418051-07:00","updated_at":"2025-10-26T12:28:21.145649-07:00","closed_at":"2025-10-26T12:28:21.145649-07:00"}
{"id":"bd-134","title":"Track last JSONL import timestamp in daemon state","description":"Add state tracking to daemon to record when .beads/issues.jsonl was last imported.\n\nImplementation:\n- Add lastImportTime field to daemon state (time.Time)\n- Update timestamp after successful import\n- Persist across RPC requests (in-memory state)\n- Initialize on daemon startup\n\nNeeded for staleness detection to compare against JSONL mtime.","status":"closed","priority":0,"issue_type":"task","created_at":"2025-10-25T23:15:14.4184-07:00","updated_at":"2025-10-25T23:15:33.517097-07:00","closed_at":"2025-10-25T23:04:33.056154-07:00"}
{"id":"bd-135","title":"Daemon fails to auto-import after git pull updates JSONL","description":"After git pull updates .beads/issues.jsonl, daemon doesn't automatically re-import changes, causing stale data to be shown until next sync cycle (up to 5 minutes).\n\nReproduction:\n1. Repo A: Close issues, export, commit, push\n2. Repo B: git pull (successfully updates .beads/issues.jsonl)\n3. bd show \u003cissue\u003e shows OLD status from daemon's SQLite db\n4. JSONL on disk has correct new status\n\nRoot cause: Daemon sync cycle runs on timer (5min). When user manually runs git pull, daemon doesn't detect JSONL was updated externally and continues serving stale data from SQLite.\n\nImpact:\n- High for AI agents using beads in git workflows\n- Breaks fundamental git-as-source-of-truth model\n- Confusing UX: git log shows commit, bd shows old state\n- Data consistency issues between JSONL and daemon\n\nSee WYVERN_SYNC_ISSUE.md for full analysis.","design":"Three possible solutions:\n\nOption 1: Auto-detect and re-import (recommended)\n- Before serving any bd command, check if .beads/issues.jsonl mtime \u003e last import time\n- If newer, auto-import before processing request\n- Fast check, minimal overhead\n\nOption 2: File watcher in daemon\n- Daemon watches .beads/issues.jsonl for mtime changes\n- Auto-imports when file changes\n- More complex, requires file watching infrastructure\n\nOption 3: Explicit sync command\n- User runs `bd sync` after git pull\n- Manual, error-prone, defeats automation\n\nRecommended: Option 1 (auto-detect) + Option 3 (explicit sync) as fallback.","acceptance_criteria":"1. After git pull updates .beads/issues.jsonl, next bd command sees fresh data\n2. No manual import or daemon restart required\n3. Performance impact \u003c 10ms per command (mtime check is fast)\n4. Works in both daemon and non-daemon modes\n5. Test: Two repo clones, update in one, pull in other, verify immediate sync","status":"closed","priority":0,"issue_type":"epic","created_at":"2025-10-25T23:15:14.418651-07:00","updated_at":"2025-10-26T11:59:31.178532-07:00","closed_at":"2025-10-26T11:59:31.178532-07:00"}
{"id":"bd-136","title":"Add configurable SortPolicy to GetReadyWork","description":"Add SortPolicy field to WorkFilter to support different ordering strategies: hybrid (default), priority-first, oldest-first. See SORT_POLICY_DESIGN.md for full specification.","design":"See SORT_POLICY_DESIGN.md for complete design.\n\nImplementation summary:\n1. Add SortPolicy type and constants (hybrid, priority, oldest)\n2. Add SortPolicy field to WorkFilter \n3. Implement buildOrderByClause() to generate SQL based on policy\n4. Default to hybrid for backwards compatibility\n5. Add --sort flag to bd ready command\n\nThis enables autonomous execution systems (like VC) to use strict priority ordering while preserving the current hybrid behavior for interactive use.","acceptance_criteria":"Unit tests verify each policy generates correct ORDER BY. Integration tests verify priority, hybrid, and oldest policies select issues in expected order. CLI bd ready --sort priority works. Empty SortPolicy defaults to hybrid (backwards compatible).","status":"closed","priority":1,"issue_type":"feature","created_at":"2025-10-26T12:27:22.805413-07:00","updated_at":"2025-10-26T12:28:52.524291-07:00","closed_at":"2025-10-26T12:28:52.524291-07:00"}
{"id":"bd-137","title":"Add 'bd sync' command for explicit synchronization","description":"Add explicit `bd sync` command as fallback for manual synchronization after git pull.\n\nBehavior:\n- Import from .beads/issues.jsonl\n- If daemon mode: send RPC command to daemon to re-import\n- If non-daemon: directly import to local db\n- Show summary: \"Imported N issues, updated M issues\"\n\nUsage:\n```bash\ngit pull\nbd sync # Force immediate sync\n```\n\nThis complements auto-detection but gives users manual control.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-26T12:27:22.805868-07:00","updated_at":"2025-10-26T12:28:52.533454-07:00","closed_at":"2025-10-26T12:28:52.533454-07:00"}
{"id":"bd-138","title":"Add configurable SortPolicy to GetReadyWork","description":"Add SortPolicy field to WorkFilter to support different ordering strategies: hybrid (default), priority-first, oldest-first. See SORT_POLICY_DESIGN.md for full specification.","design":"See SORT_POLICY_DESIGN.md for complete design.\n\nImplementation summary:\n1. Add SortPolicy type and constants (hybrid, priority, oldest)\n2. Add SortPolicy field to WorkFilter \n3. Implement buildOrderByClause() to generate SQL based on policy\n4. Default to hybrid for backwards compatibility\n5. Add --sort flag to bd ready command\n\nThis enables autonomous execution systems (like VC) to use strict priority ordering while preserving the current hybrid behavior for interactive use.","acceptance_criteria":"Unit tests verify each policy generates correct ORDER BY. Integration tests verify priority, hybrid, and oldest policies select issues in expected order. CLI bd ready --sort priority works. Empty SortPolicy defaults to hybrid (backwards compatible).","status":"closed","priority":1,"issue_type":"feature","created_at":"2025-10-26T12:27:22.889669-07:00","updated_at":"2025-10-26T12:28:21.152107-07:00","closed_at":"2025-10-26T12:28:21.152107-07:00"}
{"id":"bd-139","title":"Add 'bd sync' command for explicit synchronization","description":"Add explicit `bd sync` command as fallback for manual synchronization after git pull.\n\nBehavior:\n- Import from .beads/issues.jsonl\n- If daemon mode: send RPC command to daemon to re-import\n- If non-daemon: directly import to local db\n- Show summary: \"Imported N issues, updated M issues\"\n\nUsage:\n```bash\ngit pull\nbd sync # Force immediate sync\n```\n\nThis complements auto-detection but gives users manual control.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-26T12:27:22.890111-07:00","updated_at":"2025-10-26T12:28:21.133303-07:00","closed_at":"2025-10-26T12:28:21.133303-07:00"}
{"id":"bd-14","title":"Phase 3: Migration Path \u0026 Database Schema Alignment","description":"Enable existing .beads/vc.db files to work with Beads library through automated migration.\n\n**Goal:** Provide safe, tested migration path from SQLite implementation to Beads library.\n\n**Key Tasks:**\n1. Run compatibility tests against production databases\n2. Identify schema differences (columns, indexes, constraints)\n3. Document required migrations\n4. Create migration CLI command: 'vc migrate --from sqlite --to beads'\n5. Add dry-run mode for preview\n6. Add backup/restore capability\n7. Implement rollback mechanism\n8. Add auto-detection of schema version on startup\n9. Add auto-migrate with user prompt\n\n**Acceptance Criteria:**\n- Existing databases migrate successfully\n- Data integrity preserved (zero data loss verified via checksums)\n- Rollback works if migration fails\n- Migration tested on real production VC databases\n- Dry-run mode shows exactly what will change\n- Backup created before migration\n- Feature flag: VC_FORCE_SQLITE=true provides escape hatch\n\n**Technical Details:**\n- Compare current SQLite schema with Beads schema\n- Handle version detection (read schema_version or detect from structure)\n- Migration should be idempotent (safe to run multiple times)\n- Backup strategy: Copy .beads/vc.db to .beads/vc.db.backup-\u003ctimestamp\u003e\n- Verify foreign key integrity after migration\n\n**Safety Measures:**\n- Require executor shutdown before migration (check for running executors)\n- Atomic migration (BEGIN IMMEDIATE transaction)\n- Comprehensive pre/post migration validation\n- Clear error messages with recovery instructions\n\n**Dependencies:**\n- Blocked by Phase 2 (need VCStorage implementation)\n\n**Estimated Effort:** 0.5 sprint","status":"closed","priority":2,"issue_type":"task","created_at":"2025-10-22T14:04:51.320435-07:00","updated_at":"2025-10-25T23:15:33.473975-07:00","closed_at":"2025-10-22T21:37:48.748273-07:00","dependencies":[{"issue_id":"bd-14","depends_on_id":"bd-11","type":"parent-child","created_at":"2025-10-24T13:17:40.323317-07:00","created_by":"renumber"},{"issue_id":"bd-14","depends_on_id":"bd-13","type":"blocks","created_at":"2025-10-24T13:17:40.323527-07:00","created_by":"renumber"}]}
{"id":"bd-140","title":"Clarify that humans should run bd init, not agents","description":"Current docs are ambiguous about who runs `bd init`. This leads to agents running it incorrectly, causing daemon issues, sync problems, and confusion.\n\n**Problem:** Agents struggle with:\n- Interactive prompts (git hooks)\n- Directory detection\n- Understanding when to import existing JSONL\n- Daemon startup timing\n\n**Solution:** Make it crystal clear that `bd init` is a human setup task, like `npm install` or `git init`.","design":"Update docs to emphasize:\n1. README.md - Rewrite Quick Start to show human does `bd init` first\n2. AGENTS.md - Add clear \"Human does init, agent uses bd\" section\n3. QUICKSTART.md - Update tutorial flow\n4. FAQ.md - Add Q\u0026A about who runs init","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-26T12:50:14.555803-07:00","updated_at":"2025-10-26T12:53:10.836604-07:00","closed_at":"2025-10-26T12:53:10.836604-07:00","dependencies":[{"issue_id":"bd-140","depends_on_id":"bd-141","type":"blocks","created_at":"2025-10-26T12:52:23.433758-07:00","created_by":"daemon"}]}
{"id":"bd-141","title":"Make bd init --quiet skip interactive prompts","description":"Currently `bd init --quiet` flag exists but doesn't actually skip the git hooks prompt. This makes it impossible for agents to run init non-interactively.\n\n**Problem:** Agents setting up repos can't use `bd init` because it prompts for user input.\n\n**Solution:** Make `--quiet` flag actually work:\n- Skip git hooks prompt\n- Auto-install hooks by default in quiet mode (safest)\n- No output except errors","design":"In cmd/bd/init.go, check the quiet flag before prompting:\n\n```go\nif isGitRepo() \u0026\u0026 !hooksInstalled() {\n if quiet {\n // Auto-install hooks silently in quiet mode\n _ = installGitHooks() // Ignore errors\n } else {\n // Show prompt for interactive mode\n fmt.Printf(\"Install git hooks now? [Y/n] \")\n // ... existing prompt logic\n }\n}\n```","status":"closed","priority":1,"issue_type":"bug","created_at":"2025-10-26T12:52:19.482162-07:00","updated_at":"2025-10-26T12:52:39.295979-07:00","closed_at":"2025-10-26T12:52:39.295979-07:00"}
{"id":"bd-142","title":"Local testing of bd init --quiet and auto-sync improvements","description":"Before doing official version bump, test the new changes locally across multiple agent projects:\n\n**Changes to test:**\n- bd init --quiet (non-interactive for agents)\n- Auto-sync documentation updates\n- Git hooks auto-install in quiet mode\n\n**Test scenarios:**\n1. Fresh repo clone with existing .beads/issues.jsonl (bd init --quiet)\n2. Agent setting up new project (bd init --quiet)\n3. Verify git hooks install automatically in quiet mode\n4. Test auto-import after git pull\n5. Verify no daemon conflicts across projects\n\n**Projects/agents to test:**\n- ~/src/vc (waiting on exclusive lock protocol)\n- Other agent projects with fresh clones\n- Multiple agents on same machine","design":"From RELEASING.md, for local testing:\n\n1. Build local binary: `go build -o bd ./cmd/bd`\n2. Use `./bd` directly (don't install via brew yet)\n3. Optional: `alias bd=\"$PWD/bd\"` to test across projects\n4. Kill all daemons first: `pkill -f \"bd.*daemon\"`\n\n**Testing workflow:**\n- Build latest bd binary in ~/src/beads\n- Create alias: `alias bd=\"$HOME/src/beads/bd\"`\n- Test with multiple agents in different repos\n- Verify version: `bd version` shows latest\n- Check daemon compatibility after restart","notes":"Found and fixed bug: bd init --quiet was returning before hooks installation.\n\nFixed by:\n1. Moving hooks check/install before quiet mode return\n2. Embedding hooks inline instead of using external install.sh\n3. This makes bd init --quiet fully self-contained\n\nTested successfully in /tmp/bd-test-quiet - hooks installed correctly.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-26T12:56:04.960569-07:00","updated_at":"2025-10-26T13:19:22.400117-07:00","closed_at":"2025-10-26T13:19:22.400117-07:00"}
{"id":"bd-143","title":"Review and respond to new GitHub PRs","description":"Check for new pull requests on GitHub and review/respond to them.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-26T13:19:22.407693-07:00","updated_at":"2025-10-26T13:22:33.395599-07:00","closed_at":"2025-10-26T13:22:33.395599-07:00"}
{"id":"bd-144","title":"Document bd edit command and verify MCP exclusion","description":"Follow-up from PR #152:\n1. Add \"bd edit\" to AGENTS.md with \"Humans only\" note\n2. Verify MCP server doesn't expose bd edit command\n3. Consider adding test for command registration","status":"open","priority":2,"issue_type":"task","created_at":"2025-10-26T13:23:47.982295-07:00","updated_at":"2025-10-26T13:23:47.982295-07:00","dependencies":[{"issue_id":"bd-144","depends_on_id":"bd-143","type":"discovered-from","created_at":"2025-10-26T13:23:47.983557-07:00","created_by":"daemon"}]}
{"id":"bd-145","title":"Add \"bd daemons\" command for multi-daemon management","description":"Add a new \"bd daemons\" command with subcommands to manage daemon processes across all beads repositories/worktrees. Should show all running daemons with metadata (version, workspace, uptime, last sync), allow stopping/restarting individual daemons, auto-clean stale processes, view logs, and show exclusive lock status.","design":"Subcommands:\n- list: Show all running daemons with metadata (workspace, PID, version, socket path, uptime, last activity, exclusive lock status)\n- stop \u003cpath|pid\u003e: Gracefully stop a specific daemon\n- restart \u003cpath|pid\u003e: Stop and restart daemon\n- killall: Emergency stop all daemons\n- health: Verify each daemon responds to ping\n- logs \u003cpath\u003e: View daemon logs\n\nFeatures:\n- Auto-clean stale sockets/dead processes\n- Discovery: Scan for .beads/bd.sock files + running processes\n- Communication: Use existing socket protocol, add GET /status endpoint for metadata","status":"in_progress","priority":1,"issue_type":"epic","created_at":"2025-10-26T16:53:40.970042-07:00","updated_at":"2025-10-26T18:11:11.077613-07:00"}
{"id":"bd-146","title":"Implement daemon discovery mechanism","description":"Build the core discovery logic to find all running bd daemons. Scan filesystem for .beads/bd.sock files, check if processes are alive, and collect metadata.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-26T16:54:00.22163-07:00","updated_at":"2025-10-26T18:05:22.257361-07:00","closed_at":"2025-10-26T18:05:22.257361-07:00","dependencies":[{"issue_id":"bd-146","depends_on_id":"bd-145","type":"parent-child","created_at":"2025-10-26T16:54:00.222398-07:00","created_by":"daemon"}]}
{"id":"bd-147","title":"Implement \"bd daemons list\" subcommand","description":"Create the \"bd daemons list\" command that displays all running daemons in a table with: workspace path, PID, version, socket path, uptime, last activity, exclusive lock status. Include --json flag.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-26T16:54:00.232956-07:00","updated_at":"2025-10-26T18:10:24.905516-07:00","closed_at":"2025-10-26T18:10:24.905516-07:00","dependencies":[{"issue_id":"bd-147","depends_on_id":"bd-145","type":"parent-child","created_at":"2025-10-26T17:47:47.922208-07:00","created_by":"stevey"}]}
{"id":"bd-148","title":"Add GET /status endpoint to daemon HTTP server","description":"Add a new HTTP endpoint that returns daemon metadata: version, workspace path, PID, uptime, last activity timestamp, exclusive lock status.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-26T16:54:00.233084-07:00","updated_at":"2025-10-26T17:55:32.40399-07:00","closed_at":"2025-10-26T17:55:32.40399-07:00","dependencies":[{"issue_id":"bd-148","depends_on_id":"bd-145","type":"parent-child","created_at":"2025-10-26T16:54:00.238293-07:00","created_by":"daemon"}]}
{"id":"bd-149","title":"Add auto-cleanup of stale sockets and dead processes","description":"When discovering daemons, automatically detect and clean up stale socket files (where process is dead) and orphaned PID files. Should be safe and only remove confirmed-dead processes.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-26T16:54:00.246629-07:00","updated_at":"2025-10-26T18:17:18.560526-07:00","closed_at":"2025-10-26T18:17:18.560526-07:00","dependencies":[{"issue_id":"bd-149","depends_on_id":"bd-145","type":"parent-child","created_at":"2025-10-26T16:54:00.247788-07:00","created_by":"daemon"}]}
{"id":"bd-15","title":"Phase 4: Gradual Cutover \u0026 Production Rollout","description":"Replace SQLite implementation with Beads library in production and remove legacy code.\n\n**Goal:** Complete transition to Beads library, deprecate and remove custom SQLite implementation.\n\n**Key Tasks:**\n1. Run VC executor with Beads library in CI\n2. Dogfood: Use Beads library for VC's own development\n3. Monitor for regressions and performance issues\n4. Flip feature flag: VC_USE_BEADS_LIBRARY=true by default\n5. Monitor production logs for errors\n6. Collect user feedback\n7. Add deprecation notice to CLAUDE.md\n8. Provide migration guide for users\n9. Remove legacy code: internal/storage/sqlite/sqlite.go (~1500 lines)\n10. Remove migration framework: internal/storage/migrations/\n11. Remove manual transaction management code\n12. Update all documentation\n\n**Acceptance Criteria:**\n- Beads library enabled by default in production\n- Zero production incidents related to migration\n- Performance meets or exceeds SQLite implementation\n- All tests passing with Beads library\n- Legacy SQLite code removed\n- Documentation updated\n- Celebration documented 🎉\n\n**Rollout Strategy:**\n1. Week 1: Enable for CI/testing environments\n2. Week 2: Dogfood on VC development\n3. Week 3: Enable for 50% of production (canary)\n4. Week 4: Enable for 100% of production\n5. Week 5: Remove legacy code\n\n**Monitoring:**\n- Track error rates before/after cutover\n- Monitor database query performance\n- Track issue creation/update latency\n- Monitor executor claim performance\n\n**Rollback Plan:**\n- Keep VC_FORCE_SQLITE=true escape hatch for 2 weeks post-cutover\n- Keep legacy code for 1 sprint after cutover\n- Document rollback procedure\n\n**Success Metrics:**\n- Zero data loss\n- No performance regression (\u003c 5% latency increase acceptable)\n- Reduced maintenance burden (code LOC reduction)\n- Positive developer feedback\n\n**Dependencies:**\n- Blocked by Phase 3 (need migration tooling)\n\n**Estimated Effort:** 1 sprint","status":"closed","priority":2,"issue_type":"task","created_at":"2025-10-22T14:05:07.755107-07:00","updated_at":"2025-10-25T23:15:33.474948-07:00","closed_at":"2025-10-22T21:37:48.748919-07:00","dependencies":[{"issue_id":"bd-15","depends_on_id":"bd-11","type":"parent-child","created_at":"2025-10-24T13:17:40.324637-07:00","created_by":"renumber"},{"issue_id":"bd-15","depends_on_id":"bd-14","type":"blocks","created_at":"2025-10-24T13:17:40.324851-07:00","created_by":"renumber"}]}
{"id":"bd-150","title":"Update AGENTS.md and README.md with \"bd daemons\" documentation","description":"Document the new \"bd daemons\" command and all subcommands in AGENTS.md and README.md. Include examples and troubleshooting guidance.","status":"closed","priority":2,"issue_type":"task","created_at":"2025-10-26T16:54:00.254006-07:00","updated_at":"2025-10-26T19:03:21.93015-07:00","closed_at":"2025-10-26T19:03:21.93015-07:00","dependencies":[{"issue_id":"bd-150","depends_on_id":"bd-145","type":"parent-child","created_at":"2025-10-26T16:54:00.254862-07:00","created_by":"daemon"}]}
{"id":"bd-151","title":"Implement \"bd daemons health\" subcommand","description":"Add health check command that pings each daemon and reports responsiveness. Should detect and report stale sockets, version mismatches, unresponsive daemons.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-26T16:54:00.255444-07:00","updated_at":"2025-10-26T18:21:59.75853-07:00","closed_at":"2025-10-26T18:21:59.75853-07:00","dependencies":[{"issue_id":"bd-151","depends_on_id":"bd-145","type":"parent-child","created_at":"2025-10-26T17:47:47.949848-07:00","created_by":"stevey"}]}
{"id":"bd-152","title":"Implement \"bd daemons logs\" subcommand","description":"Add command to view daemon logs for a specific workspace. Requires daemon logging to file (may need separate issue for log infrastructure).","status":"closed","priority":2,"issue_type":"task","created_at":"2025-10-26T16:54:00.256037-07:00","updated_at":"2025-10-26T19:03:21.929414-07:00","closed_at":"2025-10-26T19:03:21.929414-07:00","dependencies":[{"issue_id":"bd-152","depends_on_id":"bd-145","type":"parent-child","created_at":"2025-10-26T16:54:00.256797-07:00","created_by":"daemon"}]}
{"id":"bd-153","title":"Implement \"bd daemons killall\" subcommand","description":"Add emergency command to stop all running bd daemons. Should discover all daemons and stop them gracefully (with timeout fallback to SIGKILL).","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-26T16:54:00.258822-07:00","updated_at":"2025-10-26T19:03:21.928597-07:00","closed_at":"2025-10-26T19:03:21.928597-07:00","dependencies":[{"issue_id":"bd-153","depends_on_id":"bd-145","type":"parent-child","created_at":"2025-10-26T16:54:00.259421-07:00","created_by":"daemon"}]}
{"id":"bd-154","title":"Implement \"bd daemons stop\" and \"bd daemons restart\" subcommands","description":"Add commands to stop and restart individual daemons by path or PID. Should send graceful shutdown signal via socket, with fallback to SIGTERM.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-26T16:54:00.259875-07:00","updated_at":"2025-10-26T18:35:28.407904-07:00","closed_at":"2025-10-26T18:35:28.407904-07:00","dependencies":[{"issue_id":"bd-154","depends_on_id":"bd-145","type":"parent-child","created_at":"2025-10-26T16:54:00.260433-07:00","created_by":"daemon"}]}
{"id":"bd-155","title":"Daemon auto-import creates race condition with deletions","description":"When a user deletes an issue while the daemon is running, the daemon's periodic import from JSONL can immediately re-add the deleted issue before the deletion is flushed to the JSONL file.\n\n## Steps to reproduce:\n1. Start daemon: bd daemon --interval 30s --auto-commit --auto-push\n2. Delete an issue: bd delete wy-XX --force\n3. Wait for daemon sync cycle (observe daemon log showing \"Imported from JSONL\")\n4. Run bd show wy-XX - issue still exists despite successful deletion\n\n## Expected behavior:\nThe deletion should be immediately flushed to JSONL before the next import cycle, or imports should respect deletions in the database.\n\n## Actual behavior:\nThe daemon imports from JSONL and re-adds the deleted issue, overwriting the deletion. The user sees \"✓ Deleted wy-XX\" but the issue persists.\n\n## Workaround:\n1. Stop daemon: bd daemon --stop\n2. Delete issue: bd delete wy-XX --force\n3. Export to JSONL: bd export -o .beads/issues.jsonl\n4. Commit and push manually\n5. Restart daemon\n\n## Suggested fixes:\n1. Flush pending changes to JSONL before each import cycle\n2. Track deletions separately and don't re-import deleted issues\n3. Make delete operation immediately flush to JSONL when daemon is running\n4. Add a \"dirty\" flag that prevents import if there are pending exports","status":"closed","priority":1,"issue_type":"bug","created_at":"2025-10-26T17:02:30.576489-07:00","updated_at":"2025-10-26T17:07:10.34777-07:00","closed_at":"2025-10-26T17:07:10.34777-07:00","labels":["daemon","data-integrity","race-condition"]}
{"id":"bd-156","title":"bd create files issues in wrong project when multiple beads databases exist","description":"When working in a directory with a beads database (e.g., /Users/stevey/src/wyvern/.beads/wy.db), bd create can file issues in a different project's database instead of the current directory's database.\n\n## Steps to reproduce:\n1. Have multiple beads projects (e.g., ~/src/wyvern with wy.db, ~/vibecoder with vc.db)\n2. cd ~/src/wyvern\n3. Run bd create --title \"Test\" --type bug\n4. Observe issue created with wrong prefix (e.g., vc-1 instead of wy-1)\n\n## Expected behavior:\nbd create should respect the current working directory and use the beads database in that directory (.beads/ folder).\n\n## Actual behavior:\nbd create appears to use a different project's database, possibly the last accessed or a global default.\n\n## Impact:\nThis can cause issues to be filed in completely wrong projects, polluting unrelated issue trackers.\n\n## Suggested fix:\n- Always check for .beads/ directory in current working directory first\n- Add --project flag to explicitly specify which database to use\n- Show which project/database is being used in command output\n- Add validation/confirmation when creating issues if current directory doesn't match database project","status":"closed","priority":2,"issue_type":"bug","created_at":"2025-10-26T17:02:30.578817-07:00","updated_at":"2025-10-26T17:08:43.009159-07:00","closed_at":"2025-10-26T17:08:43.009159-07:00","labels":["cli","project-context"]}
{"id":"bd-157","title":"Implement \"bd daemons health\" subcommand","description":"Add health check command that pings each daemon and reports responsiveness. Should detect and report stale sockets, version mismatches, unresponsive daemons.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-26T17:09:51.138682-07:00","updated_at":"2025-10-26T17:47:47.958834-07:00","closed_at":"2025-10-26T17:47:47.958834-07:00","dependencies":[{"issue_id":"bd-157","depends_on_id":"bd-145","type":"parent-child","created_at":"2025-10-26T17:09:51.140111-07:00","created_by":"daemon"}]}
{"id":"bd-158","title":"Implement \"bd daemons list\" subcommand","description":"Create the \"bd daemons list\" command that displays all running daemons in a table with: workspace path, PID, version, socket path, uptime, last activity, exclusive lock status. Include --json flag.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-26T17:09:51.140442-07:00","updated_at":"2025-10-26T17:47:47.929666-07:00","closed_at":"2025-10-26T17:47:47.929666-07:00","dependencies":[{"issue_id":"bd-158","depends_on_id":"bd-145","type":"parent-child","created_at":"2025-10-26T17:09:51.150077-07:00","created_by":"daemon"}]}
{"id":"bd-159","title":"Timestamp-only changes still being exported despite dedup logic","description":"User observed timestamp-only changes in .beads/beads.jsonl causing dirty working tree. Example: bd-128's updated_at changed from 2025-10-25T23:51:09.811006-07:00 to 2025-10-26T14:12:45.207573-07:00 with no other field changes.\n\nThis should have been prevented by the export deduplication logic that's supposed to skip timestamp-only updates.\n\nNeed to investigate why timestamp-only changes are still being exported and fix the dedup logic.","status":"open","priority":1,"issue_type":"bug","created_at":"2025-10-26T17:58:15.41007-07:00","updated_at":"2025-10-26T17:58:15.41007-07:00"}
{"id":"bd-16","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.\n\n**What needs to be done:**\n\n1. **Enhanced documentation** - Expand UnderlyingDB() comments to warn:\n - Callers MUST NOT call Close() on returned DB\n - Do NOT change pool/driver settings (SetMaxOpenConns, SetConnMaxIdleTime)\n - Do NOT modify SQLite PRAGMAs (WAL mode, journal, etc.)\n - Expect errors after Storage.Close() - use contexts\n - Keep write transactions short to avoid blocking core storage\n\n2. **Add lifecycle tracking** - Implement closed flag:\n - Add atomic.Bool closed field to SQLiteStorage\n - Set flag in Close(), clear in New()\n - Optional: Add IsClosed() bool method\n\n3. **Add safety tests** (run with -race):\n - TestUnderlyingDB_ConcurrentAccess - N goroutines using UnderlyingDB() during normal storage ops\n - TestUnderlyingDB_AfterClose - Verify operations fail cleanly after storage closed\n - TestUnderlyingDB_CreateExtensionTables - Create VC table with FK to issues, verify FK enforcement\n - TestUnderlyingDB_LongTxDoesNotCorrupt - Ensure long read tx doesn't block writes indefinitely\n\n**Why this matters:**\nVC will use this to create tables in the same database. Need to ensure production-ready safety without over-engineering.\n\n**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).","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-22T17:07:56.812983-07:00","updated_at":"2025-10-25T23:15:33.476053-07:00","closed_at":"2025-10-22T20:10:52.636372-07:00"}
{"id":"bd-160","title":"Critical: Multi-clone sync is fundamentally broken","description":"## Problem\n\nTwo clones of the same beads repo working on non-overlapping issues cannot stay in sync. The JSONL export/import mechanism creates catastrophic divergence instead of keeping databases synchronized.\n\n## What Happened (2025-10-26)\n\nTwo repos working simultaneously:\n- ~/src/beads (bd.db, 159 issues) - worked on bd-153, bd-152, bd-150, closed them\n- ~/src/fred/beads (beads.db, 165 issues) - worked on bd-159, bd-160-164\n\nResult after attempting sync:\n- Databases completely diverged (159 vs 165 issues)\n- JSONL files contain conflicting state\n- Database corruption in fred/beads\n- bd-150/152/153 show as closed in one repo, open in the other\n- No clear recovery path without manual database copying\n- git pull + bd sync does NOT synchronize state\n\n## Root Cause Analysis\n\n### SMOKING GUN: Daemon Import is a NO-OP\n**Location**: cmd/bd/daemon.go:791-797\n\nThe daemon's importToJSONLWithStore() function returns nil without actually importing.\nThis means the daemon exports DB to JSONL, commits, pulls from remote, but NEVER imports remote changes back into the database.\n\nResult: Remote changes are pulled but never imported, daemon keeps exporting stale state.\n\n### Other Root Causes\n\n1. **Database naming inconsistency**: One repo uses bd.db, other uses beads.db - no enforcement\n2. **Daemon state divergence**: Each repo's daemon maintains separate state, never converges\n3. **JSONL import/export race conditions**: Auto-import can overwrite local changes before export\n4. **No conflict resolution**: When databases diverge, there's no merge strategy\n5. **Timestamp-only changes**: bd-159 - exports trigger even with no real changes\n6. **Multiple daemons**: No coordination between daemon instances\n\n## Impact\n\n**Beads is unusable for multi-developer or multi-agent workflows**. The core promise - git-based sync via JSONL - is broken.\n\n## Fix Strategy (Epic)\n\nThis issue is tracked as an EPIC with child issues:\n\n### Phase 1: Stop the Bleeding (P0)\n- Implement daemon JSONL import (fixes the NO-OP)\n- Add database integrity checks\n- Fix timestamp-only exports (bd-159)\n\n### Phase 2: Database Consistency (P0)\n- Enforce canonical database naming\n- Add database fingerprinting\n- Migration tooling\n\n### Phase 3: Conflict Resolution (P1)\n- Implement version tracking\n- Three-way merge detection\n- Interactive conflict resolution\n\n### Phase 4: Testing \u0026 Validation (P1)\n- Multi-clone integration tests\n- Stress tests\n- Documentation\n\n## Severity\n\nP0 - This breaks the fundamental use case of beads. Without reliable sync, the tool is unusable for any multi-agent or team scenario.","status":"open","priority":0,"issue_type":"bug","created_at":"2025-10-26T19:42:43.355244-07:00","updated_at":"2025-10-26T19:53:08.681645-07:00"}
{"id":"bd-161","title":"Implement daemon JSONL import (fix NO-OP stub)","description":"## Critical Bug\n\nThe daemon's sync loop calls importToJSONLWithStore() but this function is a NO-OP stub that returns nil without importing any changes.\n\n## Location\n\n**File**: cmd/bd/daemon.go:791-797\n\nCurrent implementation:\n```go\nfunc importToJSONLWithStore(ctx context.Context, store storage.Storage, jsonlPath string) error {\n // TODO Phase 4: Implement direct import for daemon\n // Currently a no-op - daemon doesn't import git changes into DB\n return nil\n}\n```\n\n## Impact\n\nThis is the PRIMARY cause of bd-160. When the daemon:\n1. Exports DB → JSONL\n2. Commits changes\n3. Pulls from remote (gets other clone's changes)\n4. Calls importToJSONLWithStore() ← **Does nothing!**\n5. Pushes commits (overwrites remote with stale state)\n\nResult: Perpetual divergence between clones.\n\n## Implementation Approach\n\nReplace the NO-OP with actual import logic:\n\n```go\nfunc importToJSONLWithStore(ctx context.Context, store storage.Storage, jsonlPath string) error {\n // Read JSONL file\n file, err := os.Open(jsonlPath)\n if err != nil {\n return fmt.Errorf(\"failed to open JSONL: %w\", err)\n }\n defer file.Close()\n \n // Parse all issues\n var issues []*types.Issue\n scanner := bufio.NewScanner(file)\n for scanner.Scan() {\n var issue types.Issue\n if err := json.Unmarshal(scanner.Bytes(), \u0026issue); err != nil {\n return fmt.Errorf(\"failed to parse issue: %w\", err)\n }\n issues = append(issues, \u0026issue)\n }\n \n if err := scanner.Err(); err != nil {\n return fmt.Errorf(\"failed to read JSONL: %w\", err)\n }\n \n // Use existing import logic with auto-conflict resolution\n opts := ImportOptions{\n ResolveCollisions: true, // Auto-resolve ID conflicts\n DryRun: false,\n SkipUpdate: false,\n Strict: false,\n }\n \n _, err = importIssuesCore(ctx, \"\", store, issues, opts)\n return err\n}\n```\n\n## Testing\n\nAfter implementation, test with:\n```bash\n# Create two clones\ngit init repo1 \u0026\u0026 cd repo1 \u0026\u0026 bd init \u0026\u0026 bd daemon\nbd new \"Issue A\"\ngit add . \u0026\u0026 git commit -m \"init\"\n\ncd .. \u0026\u0026 git clone repo1 repo2 \u0026\u0026 cd repo2 \u0026\u0026 bd init \u0026\u0026 bd daemon\n\n# Make changes in repo1\ncd ../repo1 \u0026\u0026 bd new \"Issue B\"\n\n# Wait for daemon sync, then check repo2\nsleep 10\ncd ../repo2 \u0026\u0026 bd list # Should show both Issue A and B\n```\n\n## Success Criteria\n\n- Daemon imports remote changes after git pull\n- Issue count converges across clones within one sync cycle\n- No manual intervention needed\n- Existing collision resolution logic handles conflicts\n\n## Estimated Effort\n\n30-60 minutes\n\n## Priority\n\nP0 - This is the critical path fix for bd-160","status":"closed","priority":0,"issue_type":"task","created_at":"2025-10-26T19:53:55.313039-07:00","updated_at":"2025-10-26T20:04:41.902916-07:00","closed_at":"2025-10-26T20:04:41.902916-07:00","dependencies":[{"issue_id":"bd-161","depends_on_id":"bd-160","type":"blocks","created_at":"2025-10-26T19:53:55.3136-07:00","created_by":"daemon"}]}
{"id":"bd-162","title":"Add database integrity checks to sync operations","description":"## Problem\n\nWhen databases diverge (due to the import NO-OP bug or race conditions), there are no safety checks to detect or prevent catastrophic data loss.\n\nNeed integrity checks before/after sync operations to catch divergence early.\n\n## Implementation Locations\n\n**Pre-export checks** (cmd/bd/daemon.go:948, sync.go:108):\n- Before exportToJSONLWithStore()\n- Before exportToJSONL()\n\n**Post-import checks** (cmd/bd/daemon.go:985):\n- After importToJSONLWithStore()\n\n## Checks to Implement\n\n### 1. Database vs JSONL Count Divergence\n\nBefore export:\n```go\nfunc validatePreExport(store storage.Storage, jsonlPath string) error {\n dbIssues, _ := store.SearchIssues(ctx, \"\", types.IssueFilter{})\n dbCount := len(dbIssues)\n \n jsonlCount, _ := countIssuesInJSONL(jsonlPath)\n \n if dbCount == 0 \u0026\u0026 jsonlCount \u003e 0 {\n return fmt.Errorf(\"refusing to export empty DB over %d issues in JSONL\", jsonlCount)\n }\n \n divergencePercent := math.Abs(float64(dbCount-jsonlCount)) / float64(jsonlCount) * 100\n if divergencePercent \u003e 50 {\n log.Printf(\"WARNING: DB has %d issues, JSONL has %d (%.1f%% divergence)\", \n dbCount, jsonlCount, divergencePercent)\n log.Printf(\"This suggests sync failure - investigate before proceeding\")\n }\n \n return nil\n}\n```\n\n### 2. Duplicate ID Detection\n\n```go\nfunc checkDuplicateIDs(store storage.Storage) error {\n // Query for duplicate IDs\n rows, _ := db.Query(`\n SELECT id, COUNT(*) as cnt \n FROM issues \n GROUP BY id \n HAVING cnt \u003e 1\n `)\n \n var duplicates []string\n for rows.Next() {\n var id string\n var count int\n rows.Scan(\u0026id, \u0026count)\n duplicates = append(duplicates, fmt.Sprintf(\"%s (x%d)\", id, count))\n }\n \n if len(duplicates) \u003e 0 {\n return fmt.Errorf(\"database corruption: duplicate IDs: %v\", duplicates)\n }\n return nil\n}\n```\n\n### 3. Orphaned Dependencies\n\n```go\nfunc checkOrphanedDeps(store storage.Storage) ([]string, error) {\n // Find dependencies pointing to non-existent issues\n rows, _ := db.Query(`\n SELECT DISTINCT d.depends_on_id \n FROM dependencies d \n LEFT JOIN issues i ON d.depends_on_id = i.id \n WHERE i.id IS NULL\n `)\n \n var orphaned []string\n for rows.Next() {\n var id string\n rows.Scan(\u0026id)\n orphaned = append(orphaned, id)\n }\n \n if len(orphaned) \u003e 0 {\n log.Printf(\"WARNING: Found %d orphaned dependencies: %v\", len(orphaned), orphaned)\n }\n \n return orphaned, nil\n}\n```\n\n### 4. Post-Import Validation\n\nAfter import, verify:\n```go\nfunc validatePostImport(before, after int) error {\n if after \u003c before {\n return fmt.Errorf(\"import reduced issue count: %d → %d (data loss!)\", before, after)\n }\n if after == before {\n log.Printf(\"Import complete: no changes\")\n } else {\n log.Printf(\"Import complete: %d → %d issues (+%d)\", before, after, after-before)\n }\n return nil\n}\n```\n\n## Integration Points\n\nAdd to daemon sync loop (daemon.go:920-999):\n```go\n// Before export\nif err := validatePreExport(store, jsonlPath); err != nil {\n log.log(\"Pre-export validation failed: %v\", err)\n return\n}\n\n// Export...\n\n// Before import\nbeforeCount := countDBIssues(store)\n\n// Import...\n\n// After import\nafterCount := countDBIssues(store)\nif err := validatePostImport(beforeCount, afterCount); err != nil {\n log.log(\"Post-import validation failed: %v\", err)\n}\n```\n\n## Testing\n\nCreate test scenarios:\n1. Empty DB, non-empty JSONL → should error\n2. Duplicate IDs in DB → should error\n3. Orphaned dependencies → should warn\n4. Import reduces count → should error\n\n## Success Criteria\n\n- Catches divergence \u003e50% before export\n- Detects duplicate IDs\n- Reports orphaned dependencies\n- Validates import doesn't lose data\n- All checks logged clearly\n\n## Estimated Effort\n\n2-3 hours\n\n## Priority\n\nP0 - Safety checks prevent data loss during sync","status":"open","priority":0,"issue_type":"task","created_at":"2025-10-26T19:54:22.558861-07:00","updated_at":"2025-10-26T19:54:22.558861-07:00","dependencies":[{"issue_id":"bd-162","depends_on_id":"bd-160","type":"blocks","created_at":"2025-10-26T19:54:22.55941-07:00","created_by":"daemon"}]}
{"id":"bd-164","title":"Fix timestamp-only export deduplication (bd-159)","description":"## Problem\n\nExport deduplication logic is supposed to skip timestamp-only changes, but it's not working. This causes:\n- Spurious git commits every sync cycle\n- Increased race condition window\n- Harder to detect real changes\n- Amplifies bd-160 sync issues\n\nRelated to bd-159.\n\n## Location\n\n**File**: cmd/bd/export.go:236-246\n\nCurrent code clears dirty flags for all exported issues:\n```go\nif output == \"\" || output == findJSONLPath() {\n if err := store.ClearDirtyIssuesByID(ctx, exportedIDs); err != nil {\n fmt.Fprintf(os.Stderr, \"Warning: failed to clear dirty issues: %v\\n\", err)\n }\n clearAutoFlushState()\n}\n```\n\nProblem: No check whether issue actually changed (beyond timestamps).\n\n## Root Cause\n\nIssues are marked dirty on ANY update, including:\n- Timestamp updates (UpdatedAt field)\n- No-op updates (same values written)\n- Database reopens (sqlite WAL journal replays)\n\n## Implementation Approach\n\n### 1. Add Content Hash to dirty_issues Table\n\n```sql\nALTER TABLE dirty_issues ADD COLUMN content_hash TEXT;\n```\n\nThe hash should exclude timestamp fields:\n```go\nfunc computeIssueContentHash(issue *types.Issue) string {\n // Clone issue and zero out timestamps\n normalized := *issue\n normalized.CreatedAt = time.Time{}\n normalized.UpdatedAt = time.Time{}\n \n // Serialize to JSON\n data, _ := json.Marshal(normalized)\n \n // SHA256 hash\n hash := sha256.Sum256(data)\n return hex.EncodeToString(hash[:])\n}\n```\n\n### 2. Track Previous Export State\n\nStore issue snapshots in issue_snapshots table (already exists):\n```go\nfunc saveExportSnapshot(ctx context.Context, store storage.Storage, issue *types.Issue) error {\n snapshot := \u0026types.IssueSnapshot{\n IssueID: issue.ID,\n SnapshotAt: time.Now(),\n Title: issue.Title,\n Description: issue.Description,\n Status: issue.Status,\n // ... all fields except timestamps\n }\n return store.SaveSnapshot(ctx, snapshot)\n}\n```\n\n### 3. Deduplicate During Export\n\nIn export.go:\n```go\n// Before encoding each issue\nif shouldSkipExport(ctx, store, issue) {\n skippedCount++\n continue\n}\n\nfunc shouldSkipExport(ctx context.Context, store storage.Storage, issue *types.Issue) bool {\n // Get last exported snapshot\n snapshot, err := store.GetLatestSnapshot(ctx, issue.ID)\n if err != nil || snapshot == nil {\n return false // No snapshot, must export\n }\n \n // Compare content hash\n currentHash := computeIssueContentHash(issue)\n snapshotHash := computeSnapshotHash(snapshot)\n \n if currentHash == snapshotHash {\n // Timestamp-only change, skip\n log.Printf(\"Skipping %s (timestamp-only change)\", issue.ID)\n return true\n }\n \n return false\n}\n```\n\n### 4. Update on Real Export\n\nOnly save snapshot when actually exporting:\n```go\nfor _, issue := range issues {\n if shouldSkipExport(ctx, store, issue) {\n continue\n }\n \n if err := encoder.Encode(issue); err != nil {\n return err\n }\n \n // Save snapshot of exported state\n saveExportSnapshot(ctx, store, issue)\n exportedIDs = append(exportedIDs, issue.ID)\n}\n```\n\n## Alternative: Simpler Approach\n\nIf snapshot complexity is too much, use a simpler hash:\n\n```go\n// In dirty_issues table, store hash when marking dirty\nfunc markIssueDirty(ctx context.Context, issueID string, issue *types.Issue) error {\n hash := computeIssueContentHash(issue)\n \n _, err := db.Exec(`\n INSERT INTO dirty_issues (issue_id, content_hash) \n VALUES (?, ?)\n ON CONFLICT(issue_id) DO UPDATE SET content_hash = ?\n `, issueID, hash, hash)\n \n return err\n}\n\n// During export, check if hash changed\nfunc hasRealChanges(ctx context.Context, store storage.Storage, issue *types.Issue) bool {\n var storedHash string\n err := db.QueryRow(\"SELECT content_hash FROM dirty_issues WHERE issue_id = ?\", issue.ID).Scan(\u0026storedHash)\n if err != nil {\n return true // No stored hash, export it\n }\n \n currentHash := computeIssueContentHash(issue)\n return currentHash != storedHash\n}\n```\n\n## Testing\n\nTest cases:\n1. Update issue timestamp only → no export\n2. Update issue title → export\n3. Multiple timestamp updates → single export\n4. Database reopen → no spurious exports\n\nValidation:\n```bash\n# Start daemon, wait 1 hour\nbd daemon --interval 5s\nsleep 3600\n\n# Check git log - should be 0 commits\ngit log --since=\"1 hour ago\" --oneline | wc -l # expect: 0\n```\n\n## Success Criteria\n\n- Zero spurious exports for timestamp-only changes\n- Real changes still exported immediately\n- No performance regression\n- bd-159 resolved\n\n## Estimated Effort\n\n2-3 hours\n\n## Priority\n\nP0 - Prevents noise that amplifies bd-160 sync issues","status":"open","priority":0,"issue_type":"task","created_at":"2025-10-26T19:54:58.248715-07:00","updated_at":"2025-10-26T19:54:58.248715-07:00","dependencies":[{"issue_id":"bd-164","depends_on_id":"bd-160","type":"blocks","created_at":"2025-10-26T19:54:58.24935-07:00","created_by":"daemon"},{"issue_id":"bd-164","depends_on_id":"bd-159","type":"related","created_at":"2025-10-26T19:54:58.249718-07:00","created_by":"daemon"}]}
{"id":"bd-165","title":"Enforce canonical database naming (beads.db)","description":"## Problem\n\nCurrently, different clones can use different database filenames (bd.db, beads.db, issues.db), causing incompatibility when attempting to sync.\n\nExample from bd-160:\n- ~/src/beads uses bd.db\n- ~/src/fred/beads uses beads.db\n- Sync fails because they're fundamentally different databases\n\n## Solution\n\nEnforce a single canonical database name: **beads.db**\n\n## Implementation\n\n### 1. Define Canonical Name\n\n**File**: beads.go or constants.go (create if needed)\n\n```go\npackage beads\n\n// CanonicalDatabaseName is the required database filename for all beads repositories\nconst CanonicalDatabaseName = \"beads.db\"\n\n// LegacyDatabaseNames are old names that should be migrated\nvar LegacyDatabaseNames = []string{\"bd.db\", \"issues.db\", \"bugs.db\"}\n```\n\n### 2. Update bd init Command\n\n**File**: cmd/bd/init.go\n\n```go\nfunc runInit(cmd *cobra.Command, args []string) error {\n beadsDir := \".beads\"\n os.MkdirAll(beadsDir, 0755)\n \n dbPath := filepath.Join(beadsDir, beads.CanonicalDatabaseName)\n \n // Check for legacy databases\n for _, legacy := range beads.LegacyDatabaseNames {\n legacyPath := filepath.Join(beadsDir, legacy)\n if exists(legacyPath) {\n fmt.Printf(\"Found legacy database: %s\\n\", legacy)\n fmt.Printf(\"Migrating to canonical name: %s\\n\", beads.CanonicalDatabaseName)\n \n // Rename to canonical\n if err := os.Rename(legacyPath, dbPath); err != nil {\n return fmt.Errorf(\"migration failed: %w\", err)\n }\n fmt.Printf(\"✓ Migrated %s → %s\\n\", legacy, beads.CanonicalDatabaseName)\n }\n }\n \n // Create new database if doesn't exist\n if !exists(dbPath) {\n store, err := sqlite.New(dbPath)\n if err != nil {\n return err\n }\n defer store.Close()\n \n // Initialize with version metadata\n store.SetMetadata(context.Background(), \"bd_version\", Version)\n store.SetMetadata(context.Background(), \"db_name\", beads.CanonicalDatabaseName)\n }\n \n // ... rest of init\n}\n```\n\n### 3. Validate on Daemon Start\n\n**File**: cmd/bd/daemon.go:1076-1095\n\nUpdate the existing multiple-DB check:\n```go\n// Check for multiple .db files\nbeadsDir := filepath.Dir(daemonDBPath)\nmatches, err := filepath.Glob(filepath.Join(beadsDir, \"*.db\"))\nif err == nil \u0026\u0026 len(matches) \u003e 1 {\n log.log(\"Error: Multiple database files found:\")\n for _, match := range matches {\n log.log(\" - %s\", filepath.Base(match))\n }\n log.log(\"\")\n log.log(\"Beads requires a single canonical database: %s\", beads.CanonicalDatabaseName)\n log.log(\"Run 'bd init' to migrate legacy databases\")\n os.Exit(1)\n}\n\n// Validate using canonical name\nif filepath.Base(daemonDBPath) != beads.CanonicalDatabaseName {\n log.log(\"Error: Non-canonical database name: %s\", filepath.Base(daemonDBPath))\n log.log(\"Expected: %s\", beads.CanonicalDatabaseName)\n log.log(\"Run 'bd init' to migrate to canonical name\")\n os.Exit(1)\n}\n```\n\n### 4. Add Migration Command\n\n**File**: cmd/bd/migrate.go (create new)\n\n```go\nvar migrateCmd = \u0026cobra.Command{\n Use: \"migrate\",\n Short: \"Migrate database to canonical naming and schema\",\n Run: func(cmd *cobra.Command, args []string) {\n beadsDir := \".beads\"\n \n // Find current database\n var currentDB string\n for _, name := range append(beads.LegacyDatabaseNames, beads.CanonicalDatabaseName) {\n path := filepath.Join(beadsDir, name)\n if exists(path) {\n currentDB = path\n break\n }\n }\n \n if currentDB == \"\" {\n fmt.Println(\"No database found\")\n return\n }\n \n targetPath := filepath.Join(beadsDir, beads.CanonicalDatabaseName)\n \n if currentDB == targetPath {\n fmt.Println(\"Database already using canonical name\")\n return\n }\n \n // Backup first\n backupPath := currentDB + \".backup\"\n copyFile(currentDB, backupPath)\n fmt.Printf(\"Created backup: %s\\n\", backupPath)\n \n // Rename\n if err := os.Rename(currentDB, targetPath); err != nil {\n fmt.Fprintf(os.Stderr, \"Migration failed: %v\\n\", err)\n os.Exit(1)\n }\n \n fmt.Printf(\"✓ Migrated: %s → %s\\n\", filepath.Base(currentDB), beads.CanonicalDatabaseName)\n \n // Update metadata\n store, _ := sqlite.New(targetPath)\n defer store.Close()\n store.SetMetadata(context.Background(), \"db_name\", beads.CanonicalDatabaseName)\n },\n}\n```\n\n### 5. Update FindDatabasePath\n\n**File**: beads.go (or wherever FindDatabasePath is defined)\n\n```go\nfunc FindDatabasePath() string {\n beadsDir := findBeadsDir()\n if beadsDir == \"\" {\n return \"\"\n }\n \n // First try canonical name\n canonical := filepath.Join(beadsDir, CanonicalDatabaseName)\n if exists(canonical) {\n return canonical\n }\n \n // Check for legacy names (warn user)\n for _, legacy := range LegacyDatabaseNames {\n path := filepath.Join(beadsDir, legacy)\n if exists(path) {\n fmt.Fprintf(os.Stderr, \"WARNING: Using legacy database name: %s\\n\", legacy)\n fmt.Fprintf(os.Stderr, \"Run 'bd migrate' to upgrade to canonical name: %s\\n\", CanonicalDatabaseName)\n return path\n }\n }\n \n return \"\"\n}\n```\n\n## Testing\n\n```bash\n# Test migration\nmkdir test-repo \u0026\u0026 cd test-repo \u0026\u0026 git init\nmkdir .beads\nsqlite3 .beads/bd.db \"CREATE TABLE test (id int);\"\n\nbd init # Should detect and migrate bd.db → beads.db\n\n# Verify\nls .beads/*.db # Should only show beads.db\n\n# Test daemon rejection\nsqlite3 .beads/old.db \"CREATE TABLE test (id int);\"\nbd daemon # Should error: multiple databases found\n\n# Test clean init\nrm -rf test-repo2 \u0026\u0026 mkdir test-repo2 \u0026\u0026 cd test-repo2\nbd init # Should create .beads/beads.db directly\n```\n\n## Rollout Strategy\n\n1. Add migration logic to bd init\n2. Update FindDatabasePath to warn on legacy names\n3. Add 'bd migrate' command for manual migration\n4. Update docs to specify canonical name\n5. Add daemon validation after 2 releases\n\n## Success Criteria\n\n- All new repositories use beads.db\n- bd init auto-migrates legacy names\n- bd daemon rejects non-canonical names\n- Clear migration path for existing users\n- No data loss during migration\n\n## Estimated Effort\n\n3-4 hours\n\n## Priority\n\nP0 - Critical for multi-clone compatibility","status":"open","priority":0,"issue_type":"task","created_at":"2025-10-26T19:55:39.056716-07:00","updated_at":"2025-10-26T19:55:39.056716-07:00","dependencies":[{"issue_id":"bd-165","depends_on_id":"bd-160","type":"blocks","created_at":"2025-10-26T19:55:39.057336-07:00","created_by":"daemon"}]}
{"id":"bd-166","title":"Add database fingerprinting and validation","description":"## Problem\n\nWhen multiple clones exist, there's no validation that they're actually clones of the same repository. Different repos can accidentally share databases, causing data corruption.\n\nNeed database fingerprinting to ensure clones belong to the same logical repository.\n\n## Solution\n\nAdd repository fingerprint to database metadata and validate on daemon start.\n\n## Implementation\n\n### 1. Compute Repository ID\n\n**File**: pkg/fingerprint.go (create new)\n\n```go\npackage beads\n\nimport (\n \"crypto/sha256\"\n \"encoding/hex\"\n \"fmt\"\n \"os/exec\"\n)\n\n// ComputeRepoID generates a unique identifier for this git repository\nfunc ComputeRepoID() (string, error) {\n // Get git remote URL (canonical repo identifier)\n cmd := exec.Command(\"git\", \"config\", \"--get\", \"remote.origin.url\")\n output, err := cmd.Output()\n if err != nil {\n // No remote configured, use local path\n cmd = exec.Command(\"git\", \"rev-parse\", \"--show-toplevel\")\n output, err = cmd.Output()\n if err != nil {\n return \"\", fmt.Errorf(\"not a git repository\")\n }\n }\n \n repoURL := strings.TrimSpace(string(output))\n \n // Normalize URL (remove .git suffix, https vs git@, etc.)\n repoURL = normalizeGitURL(repoURL)\n \n // SHA256 hash for privacy (don't expose repo URL in database)\n hash := sha256.Sum256([]byte(repoURL))\n return hex.EncodeToString(hash[:16]), nil // Use first 16 bytes\n}\n\nfunc normalizeGitURL(url string) string {\n // Convert git@github.com:user/repo.git → github.com/user/repo\n // Convert https://github.com/user/repo.git → github.com/user/repo\n url = strings.TrimSuffix(url, \".git\")\n url = strings.ReplaceAll(url, \"git@\", \"\")\n url = strings.ReplaceAll(url, \"https://\", \"\")\n url = strings.ReplaceAll(url, \"http://\", \"\")\n url = strings.ReplaceAll(url, \":\", \"/\")\n return url\n}\n\n// GetCloneID generates a unique ID for this specific clone (not shared with other clones)\nfunc GetCloneID() string {\n // Use hostname + path for uniqueness\n hostname, _ := os.Hostname()\n path, _ := os.Getwd()\n hash := sha256.Sum256([]byte(hostname + \":\" + path))\n return hex.EncodeToString(hash[:8])\n}\n```\n\n### 2. Store Fingerprint on Init\n\n**File**: cmd/bd/init.go\n\n```go\nfunc runInit(cmd *cobra.Command, args []string) error {\n // ... create database ...\n \n // Compute and store repo ID\n repoID, err := beads.ComputeRepoID()\n if err != nil {\n fmt.Fprintf(os.Stderr, \"Warning: could not compute repo ID: %v\\n\", err)\n } else {\n if err := store.SetMetadata(ctx, \"repo_id\", repoID); err != nil {\n return fmt.Errorf(\"failed to set repo_id: %w\", err)\n }\n fmt.Printf(\"Repository ID: %s\\n\", repoID[:8])\n }\n \n // Store clone ID\n cloneID := beads.GetCloneID()\n if err := store.SetMetadata(ctx, \"clone_id\", cloneID); err != nil {\n return fmt.Errorf(\"failed to set clone_id: %w\", err)\n }\n fmt.Printf(\"Clone ID: %s\\n\", cloneID)\n \n // Store creation timestamp\n if err := store.SetMetadata(ctx, \"created_at\", time.Now().Format(time.RFC3339)); err != nil {\n return fmt.Errorf(\"failed to set created_at: %w\", err)\n }\n \n return nil\n}\n```\n\n### 3. Validate on Database Open\n\n**File**: cmd/bd/daemon.go (in runDaemonLoop)\n\n```go\nfunc validateDatabaseFingerprint(store storage.Storage) error {\n ctx := context.Background()\n \n // Get stored repo ID\n storedRepoID, err := store.GetMetadata(ctx, \"repo_id\")\n if err != nil \u0026\u0026 err.Error() != \"metadata key not found: repo_id\" {\n return fmt.Errorf(\"failed to read repo_id: %w\", err)\n }\n \n // If no repo_id, this is a legacy database - set it now\n if storedRepoID == \"\" {\n repoID, err := beads.ComputeRepoID()\n if err != nil {\n log.log(\"Warning: could not compute repo ID: %v\", err)\n return nil // Non-fatal for backward compat\n }\n \n log.log(\"Legacy database detected, setting repo_id: %s\", repoID[:8])\n if err := store.SetMetadata(ctx, \"repo_id\", repoID); err != nil {\n return fmt.Errorf(\"failed to set repo_id: %w\", err)\n }\n return nil\n }\n \n // Validate repo ID matches\n currentRepoID, err := beads.ComputeRepoID()\n if err != nil {\n log.log(\"Warning: could not compute current repo ID: %v\", err)\n return nil // Non-fatal\n }\n \n if storedRepoID != currentRepoID {\n return fmt.Errorf(`\nDATABASE MISMATCH DETECTED!\n\nThis database belongs to a different repository:\n Database repo ID: %s\n Current repo ID: %s\n\nThis usually means:\n 1. You copied a .beads directory from another repo (don't do this!)\n 2. Git remote URL changed (run 'bd migrate' to update)\n 3. Database corruption\n\nSolutions:\n - If remote URL changed: bd migrate --update-repo-id\n - If wrong database: rm -rf .beads \u0026\u0026 bd init\n - If correct database: BEADS_IGNORE_REPO_MISMATCH=1 bd daemon\n`, storedRepoID[:8], currentRepoID[:8])\n }\n \n return nil\n}\n\n// In runDaemonLoop, after opening database:\nif err := validateDatabaseFingerprint(store); err != nil {\n if os.Getenv(\"BEADS_IGNORE_REPO_MISMATCH\") != \"1\" {\n log.log(\"Error: %v\", err)\n os.Exit(1)\n }\n log.log(\"Warning: repo mismatch ignored (BEADS_IGNORE_REPO_MISMATCH=1)\")\n}\n```\n\n### 4. Add Update Command for Remote Changes\n\n**File**: cmd/bd/migrate.go\n\n```go\nvar updateRepoID bool\n\nfunc init() {\n migrateCmd.Flags().BoolVar(\u0026updateRepoID, \"update-repo-id\", false, \n \"Update repository ID (use after changing git remote)\")\n}\n\n// In migrate command:\nif updateRepoID {\n newRepoID, err := beads.ComputeRepoID()\n if err != nil {\n fmt.Fprintf(os.Stderr, \"Error: %v\\n\", err)\n os.Exit(1)\n }\n \n oldRepoID, _ := store.GetMetadata(ctx, \"repo_id\")\n \n fmt.Printf(\"Updating repository ID:\\n\")\n fmt.Printf(\" Old: %s\\n\", oldRepoID[:8])\n fmt.Printf(\" New: %s\\n\", newRepoID[:8])\n \n if err := store.SetMetadata(ctx, \"repo_id\", newRepoID); err != nil {\n fmt.Fprintf(os.Stderr, \"Error: %v\\n\", err)\n os.Exit(1)\n }\n \n fmt.Println(\"✓ Repository ID updated\")\n}\n```\n\n## Metadata Schema\n\nAdd to `metadata` table:\n\n| Key | Value | Description |\n|-----|-------|-------------|\n| repo_id | sha256(git_remote)[..16] | Repository fingerprint |\n| clone_id | sha256(hostname:path)[..8] | Clone-specific ID |\n| created_at | RFC3339 timestamp | Database creation time |\n| db_name | \"beads.db\" | Canonical database name |\n| bd_version | \"v0.x.x\" | Schema version |\n\n## Testing\n\n```bash\n# Test repo ID generation\ncd /tmp/test-repo \u0026\u0026 git init\ngit remote add origin https://github.com/user/repo.git\nbd init\nbd show-meta repo_id # Should show consistent hash\n\n# Test mismatch detection\ncd /tmp/other-repo \u0026\u0026 git init\ngit remote add origin https://github.com/other/repo.git\ncp -r /tmp/test-repo/.beads /tmp/other-repo/\nbd daemon # Should error: repo mismatch\n\n# Test migration\ngit remote set-url origin https://github.com/user/new-repo.git\nbd migrate --update-repo-id # Should update successfully\n```\n\n## Success Criteria\n\n- New databases automatically get repo_id\n- Daemon validates repo_id on start\n- Clear error messages on mismatch\n- Migration path for remote URL changes\n- Legacy databases automatically fingerprinted\n\n## Estimated Effort\n\n3-4 hours\n\n## Priority\n\nP0 - Prevents accidental database mixing across repos","status":"open","priority":0,"issue_type":"task","created_at":"2025-10-26T19:56:18.53693-07:00","updated_at":"2025-10-26T19:56:18.53693-07:00","dependencies":[{"issue_id":"bd-166","depends_on_id":"bd-160","type":"blocks","created_at":"2025-10-26T19:56:18.537546-07:00","created_by":"daemon"}]}
{"id":"bd-167","title":"Implement version tracking for issues","description":"## Problem\n\nWhen two clones modify the same issue concurrently, there's no way to detect or handle the conflict properly. Last writer wins arbitrarily, losing data.\n\nNeed version tracking to implement proper conflict detection and resolution.\n\n## Solution\n\nAdd version counter and last-modified metadata to issues for Last-Writer-Wins (LWW) conflict resolution.\n\n## Database Schema Changes\n\n**File**: internal/storage/sqlite/schema.go\n\n```sql\n-- Add version tracking columns to issues table\nALTER TABLE issues ADD COLUMN version INTEGER DEFAULT 1 NOT NULL;\nALTER TABLE issues ADD COLUMN modified_by TEXT DEFAULT '' NOT NULL;\nALTER TABLE issues ADD COLUMN modified_at DATETIME;\n\n-- Create index for version-based queries\nCREATE INDEX IF NOT EXISTS idx_issues_version ON issues(id, version);\n\n-- Store modification history\nCREATE TABLE IF NOT EXISTS issue_versions (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n issue_id TEXT NOT NULL,\n version INTEGER NOT NULL,\n modified_by TEXT NOT NULL,\n modified_at DATETIME NOT NULL,\n snapshot BLOB NOT NULL, -- JSON snapshot of issue at this version\n FOREIGN KEY (issue_id) REFERENCES issues(id) ON DELETE CASCADE,\n UNIQUE(issue_id, version)\n);\n\nCREATE INDEX IF NOT EXISTS idx_issue_versions_lookup \n ON issue_versions(issue_id, version);\n```\n\n## Implementation\n\n### 1. Update Issue Type\n\n**File**: internal/types/issue.go\n\n```go\ntype Issue struct {\n ID string `json:\"id\"`\n Title string `json:\"title\"`\n Description string `json:\"description\"`\n Status Status `json:\"status\"`\n Priority int `json:\"priority\"`\n CreatedAt time.Time `json:\"created_at\"`\n UpdatedAt time.Time `json:\"updated_at\"`\n \n // Version tracking (new fields)\n Version int `json:\"version\"` // Incremented on each update\n ModifiedBy string `json:\"modified_by\"` // Clone ID that made the change\n ModifiedAt time.Time `json:\"modified_at\"` // When the change was made\n \n // ... rest of fields\n}\n```\n\n### 2. Increment Version on Update\n\n**File**: internal/storage/sqlite/sqlite.go\n\n```go\nfunc (s *SQLiteStorage) UpdateIssue(ctx context.Context, issue *types.Issue) error {\n // Get current version from database\n var currentVersion int\n var currentModifiedAt time.Time\n err := s.db.QueryRowContext(ctx, `\n SELECT version, modified_at \n FROM issues \n WHERE id = ?\n `, issue.ID).Scan(\u0026currentVersion, \u0026currentModifiedAt)\n \n if err != nil \u0026\u0026 err != sql.ErrNoRows {\n return fmt.Errorf(\"failed to get current version: %w\", err)\n }\n \n // Detect conflict: incoming version is stale\n if issue.Version \u003e 0 \u0026\u0026 issue.Version \u003c currentVersion {\n return \u0026ConflictError{\n IssueID: issue.ID,\n LocalVersion: currentVersion,\n RemoteVersion: issue.Version,\n LocalModified: currentModifiedAt,\n RemoteModified: issue.ModifiedAt,\n }\n }\n \n // No conflict or local is newer: increment version\n issue.Version = currentVersion + 1\n issue.ModifiedBy = getCloneID() // From fingerprinting\n issue.ModifiedAt = time.Now()\n \n // Save version snapshot before updating\n if err := s.saveVersionSnapshot(ctx, issue); err != nil {\n // Non-fatal warning\n log.Printf(\"Warning: failed to save version snapshot: %v\", err)\n }\n \n // Perform update\n _, err = s.db.ExecContext(ctx, `\n UPDATE issues SET\n title = ?,\n description = ?,\n status = ?,\n priority = ?,\n updated_at = ?,\n version = ?,\n modified_by = ?,\n modified_at = ?\n WHERE id = ?\n `, issue.Title, issue.Description, issue.Status, issue.Priority,\n issue.UpdatedAt, issue.Version, issue.ModifiedBy, issue.ModifiedAt,\n issue.ID)\n \n return err\n}\n\nfunc (s *SQLiteStorage) saveVersionSnapshot(ctx context.Context, issue *types.Issue) error {\n snapshot, _ := json.Marshal(issue)\n \n _, err := s.db.ExecContext(ctx, `\n INSERT INTO issue_versions (issue_id, version, modified_by, modified_at, snapshot)\n VALUES (?, ?, ?, ?, ?)\n `, issue.ID, issue.Version, issue.ModifiedBy, issue.ModifiedAt, snapshot)\n \n return err\n}\n```\n\n### 3. Conflict Detection on Import\n\n**File**: cmd/bd/import_core.go\n\n```go\ntype ConflictError struct {\n IssueID string\n LocalVersion int\n RemoteVersion int\n LocalModified time.Time\n RemoteModified time.Time\n LocalIssue *types.Issue\n RemoteIssue *types.Issue\n}\n\nfunc (e *ConflictError) Error() string {\n return fmt.Sprintf(\"conflict on %s: local v%d (modified %s) vs remote v%d (modified %s)\",\n e.IssueID, e.LocalVersion, e.LocalModified, e.RemoteVersion, e.RemoteModified)\n}\n\nfunc detectVersionConflict(local, remote *types.Issue) *ConflictError {\n // No conflict if same version\n if local.Version == remote.Version {\n return nil\n }\n \n // Remote is newer - no conflict\n if remote.Version \u003e local.Version {\n return nil\n }\n \n // Local is newer - remote is stale\n if remote.Version \u003c local.Version {\n // Check if concurrent modification (both diverged from same base)\n if local.ModifiedAt.Sub(remote.ModifiedAt).Abs() \u003c 1*time.Minute {\n return \u0026ConflictError{\n IssueID: local.ID,\n LocalVersion: local.Version,\n RemoteVersion: remote.Version,\n LocalModified: local.ModifiedAt,\n RemoteModified: remote.ModifiedAt,\n LocalIssue: local,\n RemoteIssue: remote,\n }\n }\n }\n \n return nil\n}\n```\n\n### 4. Conflict Resolution Strategies\n\n```go\ntype ConflictStrategy int\n\nconst (\n StrategyLWW ConflictStrategy = iota // Last Writer Wins (use newest modified_at)\n StrategyHighestVersion // Use highest version number\n StrategyInteractive // Prompt user\n StrategyMerge // Three-way merge (future)\n)\n\nfunc resolveConflict(conflict *ConflictError, strategy ConflictStrategy) (*types.Issue, error) {\n switch strategy {\n case StrategyLWW:\n if conflict.RemoteModified.After(conflict.LocalModified) {\n return conflict.RemoteIssue, nil\n }\n return conflict.LocalIssue, nil\n \n case StrategyHighestVersion:\n if conflict.RemoteVersion \u003e conflict.LocalVersion {\n return conflict.RemoteIssue, nil\n }\n return conflict.LocalIssue, nil\n \n case StrategyInteractive:\n return promptUserForResolution(conflict)\n \n default:\n return nil, fmt.Errorf(\"unknown conflict strategy: %v\", strategy)\n }\n}\n```\n\n## Migration for Existing Databases\n\n**File**: cmd/bd/migrate.go\n\n```go\nfunc migrateToVersionTracking(store storage.Storage) error {\n ctx := context.Background()\n \n // Add columns if not exist\n _, err := db.Exec(`\n ALTER TABLE issues ADD COLUMN IF NOT EXISTS version INTEGER DEFAULT 1 NOT NULL\n `)\n if err != nil {\n return err\n }\n \n _, err = db.Exec(`\n ALTER TABLE issues ADD COLUMN IF NOT EXISTS modified_by TEXT DEFAULT ''\n `)\n if err != nil {\n return err\n }\n \n _, err = db.Exec(`\n ALTER TABLE issues ADD COLUMN IF NOT EXISTS modified_at DATETIME\n `)\n if err != nil {\n return err\n }\n \n // Backfill modified_at from updated_at\n _, err = db.Exec(`\n UPDATE issues SET modified_at = updated_at WHERE modified_at IS NULL\n `)\n \n return err\n}\n```\n\n## Testing\n\n```bash\n# Test version increment\nbd create \"Test issue\"\nbd show bd-1 --json | jq .version # Should be 1\nbd update bd-1 --title \"Updated\"\nbd show bd-1 --json | jq .version # Should be 2\n\n# Test conflict detection\n# Clone A: modify bd-1\ncd repo-a \u0026\u0026 bd update bd-1 --title \"A's version\"\n# Clone B: modify bd-1\ncd repo-b \u0026\u0026 bd update bd-1 --title \"B's version\"\n\n# Sync\ncd repo-a \u0026\u0026 bd sync # Should detect conflict\n```\n\n## Success Criteria\n\n- All issues have version numbers\n- Version increments on each update\n- Conflicts detected when importing stale versions\n- Version history preserved in issue_versions table\n- Migration works for existing databases\n\n## Estimated Effort\n\n4-5 hours\n\n## Priority\n\nP1 - Enables proper conflict detection (required before three-way merge)","status":"open","priority":1,"issue_type":"task","created_at":"2025-10-26T19:57:01.745351-07:00","updated_at":"2025-10-26T19:57:01.745351-07:00","dependencies":[{"issue_id":"bd-167","depends_on_id":"bd-160","type":"blocks","created_at":"2025-10-26T19:57:01.746071-07:00","created_by":"daemon"}]}
{"id":"bd-168","title":"Add three-way merge conflict detection and resolution","description":"## Problem\n\nWhen version tracking detects a conflict (two clones modified same issue), we need intelligent merge logic instead of just picking a winner.\n\nDepends on: bd-167 (version tracking)\n\n## Solution\n\nImplement three-way merge algorithm using git merge-base concept:\n- Base: Last common version\n- Local: Current database state\n- Remote: Incoming JSONL state\n\n## Three-Way Merge Algorithm\n\n### 1. Find Merge Base\n\n**File**: internal/merge/merge.go (create new)\n\n```go\npackage merge\n\nimport (\n \"github.com/steveyegge/beads/internal/types\"\n)\n\n// FindMergeBase finds the last common version between local and remote\nfunc FindMergeBase(store storage.Storage, issueID string, localVersion, remoteVersion int) (*types.Issue, error) {\n // Get version history from issue_versions table\n baseVersion := min(localVersion, remoteVersion)\n \n var snapshot []byte\n err := db.QueryRow(`\n SELECT snapshot FROM issue_versions \n WHERE issue_id = ? AND version = ?\n ORDER BY version DESC LIMIT 1\n `, issueID, baseVersion).Scan(\u0026snapshot)\n \n if err != nil {\n return nil, fmt.Errorf(\"merge base not found: %w\", err)\n }\n \n var base types.Issue\n json.Unmarshal(snapshot, \u0026base)\n return \u0026base, nil\n}\n```\n\n### 2. Detect Conflict Type\n\n```go\ntype ConflictType int\n\nconst (\n NoConflict ConflictType = iota\n ModifyModify // Both modified same field\n ModifyDelete // One modified, one deleted\n CreateCreate // Both created same ID (ID collision)\n AutoMergeable // Different fields modified\n)\n\ntype FieldConflict struct {\n Field string\n BaseValue interface{}\n LocalValue interface{}\n RemoteValue interface{}\n}\n\ntype MergeResult struct {\n Type ConflictType\n Merged *types.Issue\n Conflicts []FieldConflict\n}\n\nfunc ThreeWayMerge(base, local, remote *types.Issue) (*MergeResult, error) {\n result := \u0026MergeResult{\n Type: NoConflict,\n Merged: \u0026types.Issue{},\n }\n \n // Copy base as starting point\n *result.Merged = *base\n \n // Check each field\n conflicts := []FieldConflict{}\n \n // Title\n if local.Title != base.Title \u0026\u0026 remote.Title != base.Title {\n if local.Title != remote.Title {\n conflicts = append(conflicts, FieldConflict{\n Field: \"title\",\n BaseValue: base.Title,\n LocalValue: local.Title,\n RemoteValue: remote.Title,\n })\n } else {\n result.Merged.Title = local.Title // Same change\n }\n } else if local.Title != base.Title {\n result.Merged.Title = local.Title // Only local changed\n } else if remote.Title != base.Title {\n result.Merged.Title = remote.Title // Only remote changed\n }\n \n // Description\n if local.Description != base.Description \u0026\u0026 remote.Description != base.Description {\n if local.Description != remote.Description {\n // Try smart merge for text fields\n merged, conflict := mergeText(base.Description, local.Description, remote.Description)\n if conflict {\n conflicts = append(conflicts, FieldConflict{\n Field: \"description\",\n BaseValue: base.Description,\n LocalValue: local.Description,\n RemoteValue: remote.Description,\n })\n } else {\n result.Merged.Description = merged\n }\n }\n } else if local.Description != base.Description {\n result.Merged.Description = local.Description\n } else if remote.Description != base.Description {\n result.Merged.Description = remote.Description\n }\n \n // Status\n if local.Status != base.Status \u0026\u0026 remote.Status != base.Status {\n if local.Status != remote.Status {\n conflicts = append(conflicts, FieldConflict{\n Field: \"status\",\n BaseValue: base.Status,\n LocalValue: local.Status,\n RemoteValue: remote.Status,\n })\n }\n } else if local.Status != base.Status {\n result.Merged.Status = local.Status\n } else if remote.Status != base.Status {\n result.Merged.Status = remote.Status\n }\n \n // Priority (numeric: take higher)\n if local.Priority != base.Priority \u0026\u0026 remote.Priority != base.Priority {\n result.Merged.Priority = min(local.Priority, remote.Priority) // Lower number = higher priority\n } else if local.Priority != base.Priority {\n result.Merged.Priority = local.Priority\n } else if remote.Priority != base.Priority {\n result.Merged.Priority = remote.Priority\n }\n \n // Set conflict type\n if len(conflicts) \u003e 0 {\n result.Type = ModifyModify\n result.Conflicts = conflicts\n } else if hasChanges(base, result.Merged) {\n result.Type = AutoMergeable\n }\n \n return result, nil\n}\n```\n\n### 3. Smart Text Merging\n\n```go\n// mergeText attempts to merge text changes using line-based diff\nfunc mergeText(base, local, remote string) (string, bool) {\n // If one side didn't change, use the other\n if local == base {\n return remote, false\n }\n if remote == base {\n return local, false\n }\n \n // Both changed - try line-based merge\n baseLines := strings.Split(base, \"\\n\")\n localLines := strings.Split(local, \"\\n\")\n remoteLines := strings.Split(remote, \"\\n\")\n \n // Simple merge: if changes are in different lines, combine them\n merged, conflict := mergeLines(baseLines, localLines, remoteLines)\n return strings.Join(merged, \"\\n\"), conflict\n}\n\nfunc mergeLines(base, local, remote []string) ([]string, bool) {\n // Use Myers diff algorithm or simple LCS\n // For MVP, use simple strategy:\n // - If local added lines, keep them\n // - If remote added lines, keep them\n // - If both modified same line, conflict\n \n // This is a simplified implementation\n // Production would use a proper diff library\n \n if reflect.DeepEqual(local, remote) {\n return local, false // Same changes\n }\n \n // Different changes - conflict\n return local, true\n}\n```\n\n### 4. Conflict Resolution UI\n\n**File**: cmd/bd/import_core.go\n\n```go\nfunc handleMergeConflict(result *merge.MergeResult) (*types.Issue, error) {\n fmt.Fprintf(os.Stderr, \"\\n=== MERGE CONFLICT ===\\n\")\n fmt.Fprintf(os.Stderr, \"Issue: %s\\n\", result.Merged.ID)\n fmt.Fprintf(os.Stderr, \"Conflicts in %d field(s):\\n\\n\", len(result.Conflicts))\n \n for _, conflict := range result.Conflicts {\n fmt.Fprintf(os.Stderr, \"Field: %s\\n\", conflict.Field)\n fmt.Fprintf(os.Stderr, \" Base: %v\\n\", conflict.BaseValue)\n fmt.Fprintf(os.Stderr, \" Local: %v\\n\", conflict.LocalValue)\n fmt.Fprintf(os.Stderr, \" Remote: %v\\n\", conflict.RemoteValue)\n \n fmt.Fprintf(os.Stderr, \"\\nChoose resolution:\\n\")\n fmt.Fprintf(os.Stderr, \" 1) Use local\\n\")\n fmt.Fprintf(os.Stderr, \" 2) Use remote\\n\")\n fmt.Fprintf(os.Stderr, \" 3) Edit manually\\n\")\n fmt.Fprintf(os.Stderr, \"Choice: \")\n \n var choice int\n fmt.Scanln(\u0026choice)\n \n switch choice {\n case 1:\n setField(result.Merged, conflict.Field, conflict.LocalValue)\n case 2:\n setField(result.Merged, conflict.Field, conflict.RemoteValue)\n case 3:\n // Open editor with conflict markers\n edited := editWithConflictMarkers(conflict)\n setField(result.Merged, conflict.Field, edited)\n }\n }\n \n return result.Merged, nil\n}\n```\n\n### 5. Auto-Merge Strategy\n\nFor non-interactive mode (daemon):\n\n```go\nfunc autoResolveConflict(result *merge.MergeResult, strategy string) *types.Issue {\n switch strategy {\n case \"local-wins\":\n for _, c := range result.Conflicts {\n setField(result.Merged, c.Field, c.LocalValue)\n }\n \n case \"remote-wins\":\n for _, c := range result.Conflicts {\n setField(result.Merged, c.Field, c.RemoteValue)\n }\n \n case \"newest-wins\":\n // Use ModifiedAt timestamp\n for _, c := range result.Conflicts {\n if result.Merged.ModifiedAt.After(remoteModifiedAt) {\n setField(result.Merged, c.Field, c.LocalValue)\n } else {\n setField(result.Merged, c.Field, c.RemoteValue)\n }\n }\n }\n \n return result.Merged\n}\n```\n\n## Integration with Import\n\n**File**: cmd/bd/import_core.go\n\n```go\nfunc importIssuesCore(ctx context.Context, dbPath string, store storage.Storage, issues []*types.Issue, opts ImportOptions) (*ImportResult, error) {\n // ...\n \n for _, remoteIssue := range issues {\n localIssue, err := store.GetIssue(ctx, remoteIssue.ID)\n \n if err == nil {\n // Issue exists - check for conflict\n if localIssue.Version != remoteIssue.Version {\n // Get merge base\n base, err := merge.FindMergeBase(store, remoteIssue.ID, \n localIssue.Version, remoteIssue.Version)\n \n if err != nil {\n // No merge base - use LWW\n if localIssue.ModifiedAt.After(remoteIssue.ModifiedAt) {\n continue // Keep local\n } else {\n store.UpdateIssue(ctx, remoteIssue) // Use remote\n }\n } else {\n // Three-way merge\n result, err := merge.ThreeWayMerge(base, localIssue, remoteIssue)\n if err != nil {\n return nil, err\n }\n \n if result.Type == merge.AutoMergeable {\n // Clean merge\n store.UpdateIssue(ctx, result.Merged)\n result.Updated++\n } else if result.Type == merge.ModifyModify {\n // Conflict - need resolution\n if opts.Interactive {\n merged, _ := handleMergeConflict(result)\n store.UpdateIssue(ctx, merged)\n } else {\n // Auto-resolve\n merged := autoResolveConflict(result, \"newest-wins\")\n store.UpdateIssue(ctx, merged)\n result.Conflicts++\n }\n }\n }\n }\n }\n }\n \n return result, nil\n}\n```\n\n## Testing\n\n```bash\n# Test auto-merge (different fields)\ncd repo-a \u0026\u0026 bd update bd-1 --title \"New title\"\ncd repo-b \u0026\u0026 bd update bd-1 --description \"New desc\"\ncd repo-a \u0026\u0026 bd sync \u0026\u0026 cd ../repo-b \u0026\u0026 bd sync\n# Expected: Both changes merged\n\n# Test conflict (same field)\ncd repo-a \u0026\u0026 bd update bd-2 --title \"A's title\"\ncd repo-b \u0026\u0026 bd update bd-2 --title \"B's title\"\ncd repo-a \u0026\u0026 bd sync \u0026\u0026 cd ../repo-b \u0026\u0026 bd sync\n# Expected: Conflict detected, newest wins\n```\n\n## Success Criteria\n\n- Different field changes auto-merge successfully\n- Same field conflicts detected\n- Interactive resolution for manual sync\n- Auto-resolution for daemon (newest-wins)\n- All merges preserve version history\n\n## Estimated Effort\n\n6-8 hours\n\n## Priority\n\nP1 - Enables intelligent conflict resolution","status":"open","priority":1,"issue_type":"task","created_at":"2025-10-26T19:57:51.037146-07:00","updated_at":"2025-10-26T19:57:51.037146-07:00","dependencies":[{"issue_id":"bd-168","depends_on_id":"bd-160","type":"blocks","created_at":"2025-10-26T19:57:51.0378-07:00","created_by":"daemon"},{"issue_id":"bd-168","depends_on_id":"bd-167","type":"blocks","created_at":"2025-10-26T19:57:51.03819-07:00","created_by":"daemon"}]}
{"id":"bd-169","title":"Multi-clone integration tests and stress testing","description":"## Problem\n\nMulti-clone sync is complex with many race conditions and edge cases. Need comprehensive integration tests to validate all scenarios.\n\n## Test Scenarios\n\n### 1. Basic Two-Clone Sync\n\n**File**: test/integration/multi_clone_test.go\n\n```go\nfunc TestBasicTwoCloneSync(t *testing.T) {\n // Setup\n repo1 := setupTestRepo(t, \"repo1\")\n defer cleanup(repo1)\n \n // Create initial issue\n bd(repo1, \"create\", \"Issue A\")\n bd(repo1, \"sync\")\n \n // Clone to repo2\n repo2 := cloneRepo(t, repo1, \"repo2\")\n defer cleanup(repo2)\n \n // Verify issue synced\n issues := listIssues(repo2)\n assert.Len(t, issues, 1)\n assert.Equal(t, \"Issue A\", issues[0].Title)\n \n // Make change in repo1\n bd(repo1, \"create\", \"Issue B\")\n bd(repo1, \"sync\")\n \n // Pull in repo2\n bd(repo2, \"sync\")\n \n // Verify both issues present\n issues = listIssues(repo2)\n assert.Len(t, issues, 2)\n}\n```\n\n### 2. Concurrent Non-Overlapping Changes\n\n```go\nfunc TestConcurrentNonOverlappingChanges(t *testing.T) {\n repo1, repo2 := setupTwoClones(t)\n \n // Repo1: Create bd-1\n bd(repo1, \"create\", \"Issue 1\")\n \n // Repo2: Create bd-2\n bd(repo2, \"create\", \"Issue 2\")\n \n // Both sync\n bd(repo1, \"sync\")\n bd(repo2, \"sync\")\n bd(repo1, \"sync\") // Pull repo2's changes\n \n // Verify both repos have both issues\n assert.Len(t, listIssues(repo1), 2)\n assert.Len(t, listIssues(repo2), 2)\n}\n```\n\n### 3. Concurrent Modification Same Issue (Different Fields)\n\n```go\nfunc TestConcurrentModificationDifferentFields(t *testing.T) {\n repo1, repo2 := setupTwoClones(t)\n \n // Create initial issue\n bd(repo1, \"create\", \"Issue 1\", \"--description\", \"Base description\")\n bd(repo1, \"sync\")\n bd(repo2, \"sync\")\n \n // Repo1: Update title\n bd(repo1, \"update\", \"bd-1\", \"--title\", \"New title\")\n \n // Repo2: Update description\n bd(repo2, \"update\", \"bd-1\", \"--description\", \"New description\")\n \n // Both sync\n bd(repo1, \"sync\")\n bd(repo2, \"sync\")\n bd(repo1, \"sync\")\n \n // Verify auto-merge happened\n issue1 := getIssue(repo1, \"bd-1\")\n issue2 := getIssue(repo2, \"bd-1\")\n \n assert.Equal(t, \"New title\", issue1.Title)\n assert.Equal(t, \"New description\", issue1.Description)\n assert.Equal(t, issue1, issue2) // Both repos converged\n}\n```\n\n### 4. Concurrent Modification Same Field (Conflict)\n\n```go\nfunc TestConcurrentModificationSameField(t *testing.T) {\n repo1, repo2 := setupTwoClones(t)\n \n // Create initial issue\n bd(repo1, \"create\", \"Issue 1\")\n bd(repo1, \"sync\")\n bd(repo2, \"sync\")\n \n // Both update title\n bd(repo1, \"update\", \"bd-1\", \"--title\", \"Repo1 title\")\n bd(repo2, \"update\", \"bd-1\", \"--title\", \"Repo2 title\")\n \n // Sync\n bd(repo1, \"sync\")\n bd(repo2, \"sync\")\n bd(repo1, \"sync\")\n \n // Verify conflict resolved (newest wins)\n issue1 := getIssue(repo1, \"bd-1\")\n issue2 := getIssue(repo2, \"bd-1\")\n assert.Equal(t, issue1.Title, issue2.Title) // Converged to same value\n}\n```\n\n### 5. Create-Create Collision\n\n```go\nfunc TestCreateCreateCollision(t *testing.T) {\n repo1, repo2 := setupTwoClones(t)\n \n // Both create with same ID\n bd(repo1, \"create\", \"Issue from repo1\", \"--id\", \"bd-100\")\n bd(repo2, \"create\", \"Issue from repo2\", \"--id\", \"bd-100\")\n \n // Sync with collision resolution\n bd(repo1, \"sync\")\n bd(repo2, \"sync\", \"--rename-on-import\")\n bd(repo1, \"sync\")\n \n // Verify one was remapped\n issues := listIssues(repo1)\n assert.Len(t, issues, 2)\n \n ids := []string{issues[0].ID, issues[1].ID}\n assert.Contains(t, ids, \"bd-100\")\n assert.Contains(t, ids, \"bd-101\") // One remapped\n}\n```\n\n### 6. Delete-Modify Conflict\n\n```go\nfunc TestDeleteModifyConflict(t *testing.T) {\n repo1, repo2 := setupTwoClones(t)\n \n // Create issue\n bd(repo1, \"create\", \"Issue 1\")\n bd(repo1, \"sync\")\n bd(repo2, \"sync\")\n \n // Repo1: Delete\n bd(repo1, \"delete\", \"bd-1\")\n \n // Repo2: Modify\n bd(repo2, \"update\", \"bd-1\", \"--title\", \"Modified\")\n \n // Sync\n bd(repo1, \"sync\")\n bd(repo2, \"sync\")\n bd(repo1, \"sync\")\n \n // Verify resolution (modification wins over deletion)\n issues1 := listIssues(repo1)\n issues2 := listIssues(repo2)\n assert.Len(t, issues1, 1) // Deletion reverted\n assert.Len(t, issues2, 1)\n}\n```\n\n### 7. Three-Clone Convergence\n\n```go\nfunc TestThreeCloneConvergence(t *testing.T) {\n repo1, repo2, repo3 := setupThreeClones(t)\n \n // Each creates an issue\n bd(repo1, \"create\", \"Issue 1\")\n bd(repo2, \"create\", \"Issue 2\")\n bd(repo3, \"create\", \"Issue 3\")\n \n // Sync all (multiple rounds)\n for i := 0; i \u003c 3; i++ {\n bd(repo1, \"sync\")\n bd(repo2, \"sync\")\n bd(repo3, \"sync\")\n }\n \n // Verify all have all issues\n assert.Len(t, listIssues(repo1), 3)\n assert.Len(t, listIssues(repo2), 3)\n assert.Len(t, listIssues(repo3), 3)\n}\n```\n\n### 8. Daemon Auto-Sync Test\n\n```go\nfunc TestDaemonAutoSync(t *testing.T) {\n repo1, repo2 := setupTwoClones(t)\n \n // Start daemons\n daemon1 := startDaemon(repo1, \"--auto-commit\", \"--auto-push\", \"--interval\", \"2s\")\n defer daemon1.Stop()\n \n daemon2 := startDaemon(repo2, \"--auto-commit\", \"--auto-push\", \"--interval\", \"2s\")\n defer daemon2.Stop()\n \n // Create issue in repo1\n bd(repo1, \"create\", \"Issue 1\")\n \n // Wait for sync\n time.Sleep(10 * time.Second)\n \n // Verify appeared in repo2\n issues := listIssues(repo2)\n assert.Len(t, issues, 1)\n assert.Equal(t, \"Issue 1\", issues[0].Title)\n}\n```\n\n### 9. Database Divergence Recovery\n\n```go\nfunc TestDatabaseDivergenceRecovery(t *testing.T) {\n repo1, repo2 := setupTwoClones(t)\n \n // Create divergence (simulate the bd-160 bug)\n for i := 0; i \u003c 10; i++ {\n bd(repo1, \"create\", fmt.Sprintf(\"Issue %d\", i))\n }\n \n // Force divergence (don't sync)\n for i := 0; i \u003c 10; i++ {\n bd(repo2, \"create\", fmt.Sprintf(\"Other %d\", i))\n }\n \n // Now sync and verify recovery\n bd(repo1, \"sync\")\n bd(repo2, \"sync\")\n bd(repo1, \"sync\")\n \n // Should converge\n count1 := len(listIssues(repo1))\n count2 := len(listIssues(repo2))\n assert.Equal(t, count1, count2)\n assert.Equal(t, 20, count1)\n}\n```\n\n### 10. Timestamp-Only Changes Don't Export\n\n```go\nfunc TestTimestampOnlyNoExport(t *testing.T) {\n repo := setupTestRepo(t)\n \n // Create issue\n bd(repo, \"create\", \"Issue 1\")\n bd(repo, \"sync\")\n \n // Get commit count\n commits1 := gitCommitCount(repo)\n \n // Touch database (simulate timestamp update)\n touchDatabase(repo)\n \n // Wait for daemon cycle\n time.Sleep(10 * time.Second)\n \n // Verify no new commit\n commits2 := gitCommitCount(repo)\n assert.Equal(t, commits1, commits2)\n}\n```\n\n## Test Infrastructure\n\n**File**: test/integration/helpers.go\n\n```go\nfunc setupTestRepo(t *testing.T, name string) string {\n dir := t.TempDir()\n run(dir, \"git\", \"init\")\n run(dir, \"bd\", \"init\")\n return dir\n}\n\nfunc cloneRepo(t *testing.T, source, name string) string {\n dir := t.TempDir()\n run(dir, \"git\", \"clone\", source, name)\n return filepath.Join(dir, name)\n}\n\nfunc bd(repo string, args ...string) {\n cmd := exec.Command(\"bd\", args...)\n cmd.Dir = repo\n output, err := cmd.CombinedOutput()\n if err != nil {\n panic(fmt.Sprintf(\"bd command failed: %v\\n%s\", err, output))\n }\n}\n\nfunc listIssues(repo string) []*types.Issue {\n cmd := exec.Command(\"bd\", \"list\", \"--json\")\n cmd.Dir = repo\n output, _ := cmd.Output()\n \n var issues []*types.Issue\n json.Unmarshal(output, \u0026issues)\n return issues\n}\n```\n\n## CI Integration\n\n**File**: .github/workflows/multi-clone-tests.yml\n\n```yaml\nname: Multi-Clone Integration Tests\n\non: [push, pull_request]\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v3\n - uses: actions/setup-go@v4\n with:\n go-version: '1.21'\n \n - name: Run multi-clone tests\n run: |\n go test -v ./test/integration/... -tags=integration\n \n - name: Run stress tests\n run: |\n go test -v ./test/stress/... -race -timeout=30m\n```\n\n## Success Criteria\n\n- All 10 test scenarios pass\n- Tests run in CI on every commit\n- Zero flaky tests\n- Coverage \u003e80% for sync-related code\n- Stress tests validate 100+ concurrent operations\n\n## Estimated Effort\n\n8-10 hours\n\n## Priority\n\nP1 - Required to validate bd-160 fixes","status":"open","priority":1,"issue_type":"task","created_at":"2025-10-26T19:58:40.735773-07:00","updated_at":"2025-10-26T19:58:40.735773-07:00","dependencies":[{"issue_id":"bd-169","depends_on_id":"bd-160","type":"blocks","created_at":"2025-10-26T19:58:40.736466-07:00","created_by":"daemon"}]}
{"id":"bd-17","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.\n\n**Update needed:**\n1. Add section showing UnderlyingDB() usage:\n ```go\n store, err := beads.NewSQLiteStorage(dbPath)\n db := store.UnderlyingDB()\n // Create extension tables using db\n ```\n\n2. Document when to use UnderlyingDB() vs direct sql.Open():\n - Use UnderlyingDB() when you want to share the storage connection\n - Use sql.Open() when you need independent connection management\n\n3. Add safety warnings (cross-reference from UnderlyingDB() docs):\n - Don't close the DB\n - Don't modify pool settings\n - Keep transactions short\n\n4. Update the VC example to show UnderlyingDB() pattern\n\n5. Explain beads.Storage.UnderlyingDB() in the API section","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-22T17:07:56.820056-07:00","updated_at":"2025-10-25T23:15:33.478579-07:00","closed_at":"2025-10-22T19:41:19.895847-07:00","dependencies":[{"issue_id":"bd-17","depends_on_id":"bd-10","type":"discovered-from","created_at":"2025-10-24T13:17:40.32522-07:00","created_by":"renumber"}]}
{"id":"bd-170","title":"Documentation for multi-clone workflows and conflict resolution","description":"## Problem\n\nMulti-clone sync is now fixed (bd-160), but users need documentation on:\n- How to set up multi-clone workflows\n- What to do when conflicts occur\n- Best practices for team collaboration\n- Recovery procedures for divergence\n\n## Documentation Sections\n\n### 1. Multi-Clone Setup Guide\n\n**File**: docs/multi-clone-setup.md\n\n```markdown\n# Multi-Clone Workflow Setup\n\n## Prerequisites\n\n- Git repository with remote configured\n- Beads v0.x.x or later (includes bd-160 fixes)\n\n## Setup Steps\n\n### 1. Initialize First Clone\n\n```bash\ncd ~/projects/myapp\ngit init\nbd init\nbd create \"First issue\"\nbd sync\ngit remote add origin git@github.com:user/myapp.git\ngit push -u origin main\n```\n\n### 2. Clone to Another Location\n\n```bash\ncd ~/work/myapp\ngit clone git@github.com:user/myapp.git\ncd myapp\nbd init # Initializes database from JSONL\n```\n\n### 3. Start Daemons (Optional)\n\nFor automatic sync:\n\n```bash\n# In first clone\ncd ~/projects/myapp\nbd daemon --auto-commit --auto-push\n\n# In second clone\ncd ~/work/myapp\nbd daemon --auto-commit --auto-push\n```\n\n## Verification\n\nCheck both clones have same issues:\n\n```bash\ncd ~/projects/myapp \u0026\u0026 bd list\ncd ~/work/myapp \u0026\u0026 bd list\n# Should show identical output\n```\n\n## Troubleshooting\n\nIf clones diverge:\n1. Stop daemons: `bd daemon --stop`\n2. Force sync: `bd sync --force`\n3. Check diff: `git diff origin/main .beads/beads.jsonl`\n```\n\n### 2. Conflict Resolution Guide\n\n**File**: docs/conflict-resolution.md\n\n```markdown\n# Handling Sync Conflicts\n\n## Types of Conflicts\n\n### Auto-Mergeable (No Action Needed)\n\nDifferent fields modified:\n```\nClone A: Update title\nClone B: Update description\nResult: Both changes merged automatically\n```\n\n### Same-Field Conflict (Newest Wins)\n\nBoth modify same field:\n```\nClone A: Update title to \"A\" at 14:00\nClone B: Update title to \"B\" at 14:05\nResult: \"B\" wins (newer timestamp)\n```\n\n### Interactive Conflict\n\nWhen using manual sync (`bd sync`):\n```\n=== MERGE CONFLICT ===\nIssue: bd-42\nField: title\n Local: \"Fix the bug\"\n Remote: \"Resolve the issue\"\n\nChoose resolution:\n 1) Use local\n 2) Use remote\n 3) Edit manually\nChoice: _\n```\n\n## Manual Resolution\n\n1. Stop daemon: `bd daemon --stop`\n2. Sync with interactive mode: `bd sync`\n3. Resolve conflicts as prompted\n4. Restart daemon: `bd daemon --auto-commit --auto-push`\n\n## Viewing Conflict History\n\n```bash\n# Show version history\nbd show bd-42 --versions\n\n# Show who modified\nbd show bd-42 --json | jq '.modified_by, .version'\n```\n```\n\n### 3. Best Practices\n\n**File**: docs/best-practices.md\n\n```markdown\n# Multi-Clone Best Practices\n\n## Do's\n\n✅ **Always sync before starting work**\n```bash\nbd sync # Pull latest changes\n```\n\n✅ **Use descriptive commit messages**\n```bash\nbd sync -m \"Close bd-123: Fix memory leak\"\n```\n\n✅ **Enable daemon for automatic sync**\n```bash\nbd daemon --auto-commit --auto-push --interval 30s\n```\n\n✅ **Use atomic operations**\n```bash\n# Good: One logical change\nbd update bd-42 --title \"New title\" --description \"New desc\"\n\n# Avoid: Multiple separate updates\nbd update bd-42 --title \"New title\"\nbd update bd-42 --description \"New desc\" # Creates conflict window\n```\n\n## Don'ts\n\n❌ **Don't copy .beads directories between repos**\n```bash\n# WRONG - causes database mismatch errors\ncp -r ~/project1/.beads ~/project2/\n```\n\n❌ **Don't manually edit JSONL files**\n```bash\n# WRONG - use bd commands instead\nvim .beads/beads.jsonl\n```\n\n❌ **Don't use different database names**\n```bash\n# WRONG - all clones must use beads.db\nmv .beads/beads.db .beads/custom.db\n```\n\n❌ **Don't force push**\n```bash\n# WRONG - can lose other clones' changes\ngit push --force\n```\n\n## Team Workflows\n\n### Option 1: Daemon Auto-Sync (Recommended)\n\nEveryone runs daemon with auto-commit/auto-push. Changes sync automatically within seconds.\n\n**Pros**: Zero manual intervention, always in sync\n**Cons**: Requires stable internet, more git noise\n\n### Option 2: Manual Sync\n\nEveryone runs `bd sync` before/after work sessions.\n\n**Pros**: Fewer git commits, works offline\n**Cons**: Must remember to sync, conflicts more likely\n\n### Option 3: Hybrid\n\nDaemon without auto-push, manual push at milestones.\n\n**Pros**: Auto-import, controlled pushes\n**Cons**: Requires both daemon and manual sync\n```\n\n### 4. Recovery Procedures\n\n**File**: docs/recovery.md\n\n```markdown\n# Recovery from Sync Issues\n\n## Scenario 1: Database Diverged (Different Issue Counts)\n\n```bash\n# Clone A: 100 issues\n# Clone B: 95 issues\n\n# Recovery:\ncd clone-a\nbd export -o /tmp/clone-a.jsonl\n\ncd clone-b\nbd export -o /tmp/clone-b.jsonl\n\n# Compare\ndiff \u003c(jq -r .id /tmp/clone-a.jsonl | sort) \\\n \u003c(jq -r .id /tmp/clone-b.jsonl | sort)\n\n# Import missing issues\ncd clone-b\nbd import -i /tmp/clone-a.jsonl --resolve-collisions\nbd sync\n```\n\n## Scenario 2: Database Corruption\n\n```bash\n# Rebuild from JSONL\nrm .beads/beads.db\nbd init # Recreates database from JSONL\nbd list # Verify issues restored\n```\n\n## Scenario 3: Accidental Force Push\n\n```bash\n# Restore from reflog\ngit reflog\ngit reset --hard HEAD@{1}\nbd import # Re-import from restored JSONL\n```\n\n## Scenario 4: Merge Conflict in JSONL\n\n```bash\n# After git pull conflict\ngit status # Shows .beads/beads.jsonl as conflicted\n\n# Resolve by importing both sides\ngit show :2:.beads/beads.jsonl \u003e /tmp/ours.jsonl\ngit show :3:.beads/beads.jsonl \u003e /tmp/theirs.jsonl\n\n# Import both (collision resolution will merge)\nbd import -i /tmp/ours.jsonl --resolve-collisions\nbd import -i /tmp/theirs.jsonl --resolve-collisions\n\n# Export merged state\nbd export -o .beads/beads.jsonl\ngit add .beads/beads.jsonl\ngit commit -m \"Resolve JSONL merge conflict\"\n```\n```\n\n### 5. Architecture Documentation\n\n**File**: docs/architecture/sync.md\n\n```markdown\n# Sync Architecture\n\n## Components\n\n```\n┌─────────────┐\n│ Git JSONL │ ← Source of truth\n└─────────────┘\n ↕\n┌─────────────┐\n│ bd sync │ ← Orchestrator\n└─────────────┘\n ↕\n┌─────────────┐\n│ Database │ ← Local cache\n└─────────────┘\n ↕\n┌─────────────┐\n│ Daemon │ ← Auto-sync (optional)\n└─────────────┘\n```\n\n## Sync Flow\n\n1. **Export**: DB → JSONL\n2. **Commit**: JSONL → Git\n3. **Pull**: Git remote → Local\n4. **Import**: JSONL → DB (with conflict resolution)\n5. **Push**: Local Git → Remote\n\n## Conflict Resolution\n\nUses three-way merge:\n- **Base**: Last common version (from issue_versions table)\n- **Local**: Current database state\n- **Remote**: Incoming JSONL state\n\nAuto-merge strategy:\n- Different fields changed → Merge both\n- Same field changed → Newest wins (by modified_at)\n- Unresolvable → Interactive prompt (manual sync only)\n\n## Version Tracking\n\nEach issue has:\n- `version`: Incremented on each update\n- `modified_by`: Clone ID that made change\n- `modified_at`: Timestamp of change\n\nEnables:\n- Conflict detection\n- History tracking\n- LWW resolution\n```\n\n## Update Existing Docs\n\n**Files to update**:\n- README.md - Add multi-clone section\n- docs/commands.md - Document sync flags\n- docs/daemon.md - Update with conflict resolution\n- TROUBLESHOOTING.md - Add sync issues section\n\n## Examples Repository\n\n**File**: examples/multi-clone-demo.sh\n\n```bash\n#!/bin/bash\n# Multi-clone demonstration script\n\nset -e\n\necho \"=== Multi-Clone Sync Demo ===\"\n\n# Setup\nmkdir -p /tmp/bd-demo \u0026\u0026 cd /tmp/bd-demo\nrm -rf clone1 clone2\n\n# Create first clone\nmkdir clone1 \u0026\u0026 cd clone1\ngit init\nbd init\nbd create \"First issue\"\nbd sync\ncd ..\n\n# Create second clone\ngit clone clone1 clone2\ncd clone2\nbd init\nbd list # Shows first issue\n\n# Make concurrent changes\ncd ../clone1\nbd create \"Issue from clone1\"\nbd sync\n\ncd ../clone2\nbd create \"Issue from clone2\"\nbd sync\n\n# Sync both\ncd ../clone1\nbd sync\n\n# Verify convergence\necho \"Clone 1 issues:\"\nbd list\n\ncd ../clone2\necho \"Clone 2 issues:\"\nbd list\n\necho \"✓ Demo complete - both clones have 3 issues\"\n```\n\n## Success Criteria\n\n- All documentation sections complete\n- Examples tested and working\n- Troubleshooting covers common scenarios\n- Clear diagrams for sync flow\n- Published to docs site\n\n## Estimated Effort\n\n4-6 hours\n\n## Priority\n\nP1 - Critical for user adoption of multi-clone workflows","status":"open","priority":1,"issue_type":"task","created_at":"2025-10-26T19:59:35.553665-07:00","updated_at":"2025-10-26T19:59:35.553665-07:00","dependencies":[{"issue_id":"bd-170","depends_on_id":"bd-160","type":"blocks","created_at":"2025-10-26T19:59:35.554368-07:00","created_by":"daemon"}]}
{"id":"bd-18","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.\n\n**Proposal:** Add optional UnderlyingConn(ctx) (*sql.Conn, error) method that:\n- Returns a scoped connection via s.db.Conn(ctx)\n- Encourages lifetime-bounded usage\n- Reduces temptation to tune global pool settings\n- Better for one-time DDL operations like CREATE TABLE\n\n**Implementation:**\n```go\n// UnderlyingConn returns a single connection from the pool for scoped use\n// Useful for migrations and DDL. Close the connection when done.\nfunc (s *SQLiteStorage) UnderlyingConn(ctx context.Context) (*sql.Conn, error) {\n return s.db.Conn(ctx)\n}\n```\n\n**Benefits:**\n- Safer for migrations (explicit scope)\n- Complements UnderlyingDB() for different use cases\n- Low implementation cost\n\n**Trade-off:** Adds another method to maintain, but Oracle considers this balanced compromise between safety and flexibility.\n\n**Decision:** This is optional - evaluate based on VC's actual usage patterns.","status":"closed","priority":3,"issue_type":"feature","created_at":"2025-10-22T17:07:56.832638-07:00","updated_at":"2025-10-25T23:15:33.479496-07:00","closed_at":"2025-10-22T22:02:18.479512-07:00","dependencies":[{"issue_id":"bd-18","depends_on_id":"bd-10","type":"related","created_at":"2025-10-24T13:17:40.325463-07:00","created_by":"renumber"}]}
{"id":"bd-19","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.\n\nImpact: All MCP-based close operations are broken. Workaround: Use bd CLI directly.\n\nError: BdDaemonClient.close() takes 1 positional argument but 2 were given\n\nRoot cause: BdDaemonClient.close() only accepts self, but MCP tool passes issue_id and reason.\n\nAdditional issue: CLI close has FOREIGN KEY constraint error when recording reason parameter.\n\nSee GitHub issue #107 for full details.","status":"closed","priority":0,"issue_type":"bug","created_at":"2025-10-22T17:25:34.67056-07:00","updated_at":"2025-10-25T23:15:33.480292-07:00","closed_at":"2025-10-22T17:36:55.463445-07:00"}
{"id":"bd-2","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.","status":"closed","priority":3,"issue_type":"bug","created_at":"2025-10-21T23:53:44.31362-07:00","updated_at":"2025-10-25T23:15:33.462194-07:00","closed_at":"2025-10-18T09:41:18.209717-07:00"}
{"id":"bd-20","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:\n\nFailing tests:\n- test_create_and_show_issue: show returns array, expects dict\n- test_update_issue: update returns array, expects dict \n- test_add_dependency: show returns array, expects dict\n- test_invalid_issue_id: show returns empty dict instead of error\n- test_dependency_types: show returns array, expects dict\n- test_show_issue_tool: show returns array, expects dict\n- test_update_issue_tool: update returns array, expects dict\n- test_update_partial_fields: update returns array, expects dict\n- test_client_lazy_initialization: BdClient import issue\n\nRoot cause: bd CLI commands like 'bd show' and 'bd update' output JSON arrays, but BdCliClient.show() and BdCliClient.update() expect single dict objects.\n\nExample:\n```bash\nbd show test-1 --json\n[{\"id\":\"test-1\",...}] # Array, not dict\n```\n\nFix needed: Update bd_client.py to handle array responses and extract first element, or change CLI to return single object for single-ID operations.","status":"closed","priority":1,"issue_type":"bug","created_at":"2025-10-22T17:43:23.29302-07:00","updated_at":"2025-10-25T23:15:33.481154-07:00","closed_at":"2025-10-22T20:05:49.3826-07:00"}
{"id":"bd-21","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.","status":"closed","priority":1,"issue_type":"bug","created_at":"2025-10-22T17:54:24.473508-07:00","updated_at":"2025-10-25T23:15:33.481941-07:00","closed_at":"2025-10-22T17:57:46.973029-07:00"}
{"id":"bd-22","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.","status":"closed","priority":1,"issue_type":"bug","created_at":"2025-10-22T19:17:05.429429-07:00","updated_at":"2025-10-25T23:15:33.482758-07:00","closed_at":"2025-10-22T19:19:54.601153-07:00"}
{"id":"bd-23","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).\n\nShould include:\n- Latest beads version\n- Updated documentation\n- Any new features or bug fixes","status":"closed","priority":2,"issue_type":"task","created_at":"2025-10-22T22:29:11.293161-07:00","updated_at":"2025-10-25T23:15:33.483625-07:00","closed_at":"2025-10-23T22:27:37.671065-07:00"}
{"id":"bd-24","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). \n\n**Root cause:** Git worktrees share the same .beads directory, so the daemon/MCP server doesn't know which branch the worktree has checked out.\n\n**Current state:**\n- Daemon mode: Cannot work properly with worktrees (fundamental limitation - shared .beads, unknown branch)\n- CLI with --no-daemon: Should work but needs verification\n\n**Action items:**\n1. Test and verify --no-daemon works correctly in worktrees\n2. Document the limitation in README/AGENTS.md\n3. Add clear error/warning when using daemon with worktrees\n4. Consider if MCP server can detect worktree usage and auto-disable daemon\n\n**Workaround for users:**\nUse --no-daemon flag when working in worktrees, or set BEADS_AUTO_DAEMON=false\n\n**Related:** GH issue #55","notes":"**Implementation completed with oracle review improvements:**\n\n1. **Robust detection** - Changed from substring check to canonical git-dir vs git-common-dir comparison\n2. **Correct warning gate** - Now only checks isGitWorktree() and only called when daemon is actually connected\n3. **Complete coverage** - Added warning to `bd daemon` command start path\n4. **Better UX** - Shows shared database path and clarifies BEADS_AUTO_START_DAEMON behavior\n5. **Improved tests** - Validates canonical detection method and path truncation\n\n**Files changed:**\n- cmd/bd/worktree.go - Improved detection and warning\n- cmd/bd/worktree_test.go - Better test coverage\n- cmd/bd/main.go - Warning after daemon connection (2 places)\n- cmd/bd/daemon.go - Warning when starting daemon\n- README.md \u0026 AGENTS.md - Documented limitations and solutions","status":"closed","priority":2,"issue_type":"bug","created_at":"2025-10-22T22:38:52.438601-07:00","updated_at":"2025-10-25T23:15:33.484321-07:00","closed_at":"2025-10-22T22:51:45.464598-07:00"}
{"id":"bd-25","title":"Investigate jujutsu integration for beads","description":"Research and document how beads could integrate with jujutsu (jj), the next-generation VCS. Key areas to explore:\n- How jj's operation model differs from git (immutable operations, working-copy-as-commit)\n- JSONL sync strategy with jj's conflict resolution model\n- Daemon compatibility with jj's more frequent rewrites\n- Whether auto-import/export needs changes for jj workflows\n- Example configurations and documentation updates needed","status":"open","priority":3,"issue_type":"task","created_at":"2025-10-23T09:23:23.582009-07:00","updated_at":"2025-10-25T23:15:33.484928-07:00"}
{"id":"bd-26","title":"Add description parameter to bd update command and MCP server","description":"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.","status":"closed","priority":1,"issue_type":"feature","created_at":"2025-10-23T10:46:00.481647-07:00","updated_at":"2025-10-25T23:15:33.485577-07:00","closed_at":"2025-10-23T10:52:49.825354-07:00"}
{"id":"bd-27","title":"Add integration tests for worktree workflow with separate databases","description":"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.","status":"closed","priority":2,"issue_type":"task","created_at":"2025-10-23T13:05:57.195044-07:00","updated_at":"2025-10-25T23:15:33.485992-07:00","closed_at":"2025-10-23T13:06:05.258164-07:00"}
{"id":"bd-28","title":"Migrate to Viper for unified configuration management","description":"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).","design":"Hybrid architecture:\n- Viper: Tool-level user preferences (global defaults for --json, --no-daemon, etc) from ~/.config/bd/config.yaml, env vars, flags\n- bd config: Project-level integration data (jira.url, linear.token) in database - version-controlled, team-shared\n\nThis 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.","status":"closed","priority":2,"issue_type":"feature","created_at":"2025-10-23T16:44:43.537822-07:00","updated_at":"2025-10-25T23:15:33.486264-07:00","closed_at":"2025-10-23T17:06:05.007958-07:00"}
{"id":"bd-29","title":"Add viper dependency and initialize singleton","description":"go get github.com/spf13/viper, create viper instance in main, set up config file paths (.beads/config.yaml, ~/.config/bd/config.yaml)","status":"closed","priority":2,"issue_type":"task","created_at":"2025-10-23T16:44:48.863208-07:00","updated_at":"2025-10-25T23:15:33.486651-07:00","closed_at":"2025-10-23T17:02:13.818118-07:00","dependencies":[{"issue_id":"bd-29","depends_on_id":"bd-28","type":"parent-child","created_at":"2025-10-24T13:17:40.32675-07:00","created_by":"renumber"}]}
{"id":"bd-3","title":"Make maxDepth configurable in bd dep tree command","description":"Currently maxDepth is hardcoded to 50 in GetDependencyTree. Add --max-depth flag to bd dep tree command to allow users to control recursion depth. Default should remain 50 for safety, but users with very deep trees or wanting shallow views should be able to configure it.","status":"closed","priority":4,"issue_type":"feature","created_at":"2025-10-21T23:53:44.31362-07:00","updated_at":"2025-10-25T23:15:33.463107-07:00","closed_at":"2025-10-19T08:59:59.596748-07:00"}
{"id":"bd-30","title":"Bind all global flags to viper","description":"Migrate --db, --actor, --json, --no-daemon, --no-auto-flush, --no-auto-import to viper with automatic env binding (BD_DB, BD_ACTOR, etc)","status":"closed","priority":2,"issue_type":"task","created_at":"2025-10-23T16:44:53.547159-07:00","updated_at":"2025-10-25T23:15:33.487238-07:00","closed_at":"2025-10-23T17:03:25.133499-07:00","dependencies":[{"issue_id":"bd-30","depends_on_id":"bd-28","type":"parent-child","created_at":"2025-10-24T13:17:40.325689-07:00","created_by":"renumber"}]}
{"id":"bd-31","title":"Replace manual env var handling with viper","description":"Remove os.Getenv() calls for BD_* variables, use viper.GetString() etc. Update CONFIG.md with viper precedence order","status":"closed","priority":2,"issue_type":"task","created_at":"2025-10-23T16:44:58.242662-07:00","updated_at":"2025-10-25T23:15:33.487741-07:00","closed_at":"2025-10-23T17:03:25.139194-07:00","dependencies":[{"issue_id":"bd-31","depends_on_id":"bd-28","type":"parent-child","created_at":"2025-10-24T13:17:40.323778-07:00","created_by":"renumber"}]}
{"id":"bd-32","title":"Keep bd config independent from Viper","description":"Update config.go to use viper for get/set/list operations. Consider whether to keep db-stored config or migrate fully to file-based","design":"Keep bd config independent from Viper. Two separate systems:\n- Viper: tool-level preferences (global flags, env vars, ~/.config/bd/config.yaml) - user settings like default --json, --no-daemon\n- bd config: project-level integration config (jira.url, linear.token) - stored in database, version-controlled, team-shared\n\nRationale: 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.","status":"closed","priority":2,"issue_type":"task","created_at":"2025-10-23T16:45:04.078518-07:00","updated_at":"2025-10-25T23:15:33.488273-07:00","closed_at":"2025-10-23T17:04:01.161921-07:00","dependencies":[{"issue_id":"bd-32","depends_on_id":"bd-28","type":"parent-child","created_at":"2025-10-24T13:17:40.328628-07:00","created_by":"renumber"}]}
{"id":"bd-33","title":"Add tests for viper configuration","description":"Test config precedence (defaults \u003c config file \u003c env vars \u003c flags), test config file discovery, test env binding","status":"closed","priority":2,"issue_type":"task","created_at":"2025-10-23T16:45:08.629325-07:00","updated_at":"2025-10-25T23:15:33.488934-07:00","closed_at":"2025-10-23T17:06:05.000166-07:00","dependencies":[{"issue_id":"bd-33","depends_on_id":"bd-28","type":"parent-child","created_at":"2025-10-24T13:17:40.326967-07:00","created_by":"renumber"}]}
{"id":"bd-34","title":"Auto-import updates all issue timestamps causing perpetually dirty JSONL","description":"**Problem:**\nEvery 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.\n\n**Root Cause:**\nAuto-import (autoImportIfNewer) imports issues and the import process updates `updated_at` timestamps on every issue, even when the issue data is identical. This causes:\n1. Import updates all 83 issues' timestamps (e.g., 2025-10-23T11:01:13.xxx)\n2. Export writes JSONL with new timestamps\n3. Git shows JSONL as modified with 200+ line changes\n4. User commits changes\n5. Next command triggers auto-import again\n6. Cycle repeats\n\n**Evidence:**\n```bash\ngit diff .beads/beads.jsonl | grep 'updated_at' | wc -l\n# Shows 200+ lines changed (every issue touched)\n\ngit diff .beads/beads.jsonl | grep 'updated_at' | sed 's/.*updated_at[^:]*:\\s*\"\\([^\"]*\\)\".*/\\1/' | sort -u\n# All timestamps identical, proving bulk update\n```\n\n**Expected Behavior:**\nImport should only update `updated_at` when issue data actually changes. Idempotent imports should not modify timestamps.\n\n**Impact:**\n- Frustrating UX: \"always conclude sessions with dirty beads.jsonl\"\n- Pollutes git history with timestamp-only changes\n- Makes actual changes hard to detect in git diff\n- Wastes CI/CD time on false changes\n\n**Related:**\n- bd-17 fixed import to preserve timestamps, but doesn't address this issue\n- May be related to how UpdateIssue works vs just inserting/replacing","status":"closed","priority":1,"issue_type":"bug","assignee":"amp","created_at":"2025-10-23T17:42:41.419893-07:00","updated_at":"2025-10-25T23:15:33.489598-07:00","closed_at":"2025-10-23T17:50:54.883229-07:00"}
{"id":"bd-35","title":"Add GoReleaser workflow for cross-platform binary releases","description":"GitHub issue #89 requests pre-compiled binaries for vendoring.\n\nCurrently users must have Go installed to use beads via 'go install'. Publishing release binaries would:\n- Enable vendoring (user's use case) \n- Support users without Go\n- Enable version pinning\n- Simplify CI/CD integration\n\nImplementation:\n1. Add .goreleaser.yml config\n2. Add .github/workflows/release.yml for tag pushes\n3. Build matrix: darwin (amd64/arm64), linux (amd64/arm64), windows (amd64)\n4. Generate checksums\n5. Create GitHub releases automatically\n6. Update install.sh to download from releases\n\nReference: https://github.com/steveyegge/beads/issues/89","status":"closed","priority":2,"issue_type":"feature","created_at":"2025-10-23T18:58:30.701929-07:00","updated_at":"2025-10-25T23:15:33.489902-07:00","closed_at":"2025-10-23T19:02:16.463059-07:00"}
{"id":"bd-36","title":"Add RPC support for epic commands in daemon mode","description":"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.\n\nLocations:\n- cmd/bd/epic.go:26 (epic status command)\n- cmd/bd/epic.go:106 (epic close-eligible command)","status":"closed","priority":2,"issue_type":"feature","created_at":"2025-10-23T19:33:34.552261-07:00","updated_at":"2025-10-25T23:15:33.490215-07:00","closed_at":"2025-10-23T21:56:33.732039-07:00"}
{"id":"bd-37","title":"bd import reports \"0 created, 0 updated\" when successfully importing issues","description":"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.\n\nThis appears to be a bug in the reporting logic that counts and displays the number of issues created/updated during import.","status":"closed","priority":2,"issue_type":"bug","created_at":"2025-10-23T22:28:40.391453-07:00","updated_at":"2025-10-25T23:15:33.490479-07:00","closed_at":"2025-10-23T23:05:57.413177-07:00"}
{"id":"bd-38","title":"Auto-detect and kill old daemon versions","description":"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.\n\n**Current behavior:**\n- `bd version --daemon` shows mismatch but requires manual intervention\n- Old daemons keep running after binary upgrades\n- MCP server may connect to old daemon\n- Results in dirty working tree after commits, stale data\n\n**Proposed solution:**\n\nKey lifecycle points to check/restart daemon:\n1. **On first command after version mismatch**: Check daemon version, auto-restart if incompatible\n2. **On daemon start**: Check for existing daemons, kill old ones before starting\n3. **After brew upgrade/install**: Add post-install hook to kill old daemons\n4. **On `bd init`**: Ensure fresh daemon\n\n**Detection logic:**\n```go\n// PersistentPreRun: check daemon version\nif daemonVersion != clientVersion {\n log.Warn(\"Daemon version mismatch, restarting...\")\n killDaemon()\n startDaemon()\n}\n```\n\n**Considerations:**\n- Should we be aggressive (always kill mismatched) or conservative (warn first)?\n- What about multiple workspaces with different bd versions?\n- Should this be opt-in via config flag?\n- How to handle graceful shutdown vs force kill?\n\n**Related issues:**\n- Race condition with auto-flush (see bd-38)\n- Version mismatch confusion for users\n- Stale daemon after upgrades","notes":"## Implementation Summary\n\nImplemented automatic daemon version detection and restart in v0.16.0.\n\n### Changes Made\n\n**1. Auto-restart on version mismatch (main.go PersistentPreRun)**\n- Check daemon version during health check\n- If incompatible, automatically stop old daemon and start new one\n- Falls back to direct mode if restart fails\n- Transparent to users - no manual intervention needed\n\n**2. Auto-stop old daemon on startup (daemon.go)**\n- When starting daemon, check if existing daemon has compatible version\n- If versions are incompatible, auto-stop old daemon before starting new one\n- Prevents \"daemon already running\" errors after upgrades\n\n**3. Robust restart implementation**\n- Sets correct working directory so daemon finds right database\n- Cleans up stale socket files after force kill\n- Properly reaps child process to avoid zombies\n- Uses waitForSocketReadiness helper for reliable startup detection\n- 5-second readiness timeout\n\n### Key Features\n\n- **Automatic**: No user action required after upgrading bd\n- **Transparent**: Works with both MCP server and CLI\n- **Safe**: Falls back to direct mode if restart fails\n- **Tested**: All existing tests pass\n\n### Related\n- Addresses race conditions mentioned in bd-39\n- Uses semver compatibility checking from internal/rpc/server.go","status":"closed","priority":1,"issue_type":"feature","created_at":"2025-10-23T23:15:59.764705-07:00","updated_at":"2025-10-25T23:15:33.519223-07:00","closed_at":"2025-10-23T23:28:06.611221-07:00"}
{"id":"bd-39","title":"Race condition between git commit and auto-flush debounce","description":"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.\n\n**Example scenario:**\n1. User closes issue via MCP → daemon schedules flush (5 sec delay)\n2. User commits code changes → JSONL appears clean\n3. Daemon flush fires → JSONL modified after commit\n4. Result: dirty working tree showing JSONL changes\n\n**Root cause:**\n- Auto-flush uses 5-second debounce to batch changes\n- Git commits happen immediately\n- No coordination between flush schedule and git operations\n\n**Possible solutions:**\n\n1. **Immediate flush before git operations**\n - Detect git commands (commit, status, push)\n - Force immediate flush if pending\n - Pros: Clean working tree guaranteed\n - Cons: Requires hooking git, may be slow\n\n2. **Commit includes pending flushes**\n - Add `bd sync` to commit workflow\n - Wait for flush to complete before committing\n - Pros: Simple, explicit\n - Cons: Requires user discipline\n\n3. **Git hooks integration**\n - pre-commit hook: `bd sync --wait`\n - Ensures JSONL is up-to-date before commit\n - Pros: Automatic, reliable\n - Cons: Requires hook installation\n\n4. **Reduce debounce delay**\n - Lower from 5s to 1s or 500ms\n - Pros: Faster sync, less likely to race\n - Cons: More frequent I/O, doesn't eliminate race\n\n5. **Lock-based coordination**\n - Daemon holds lock while flush pending\n - Git operations wait for lock\n - Pros: Guarantees ordering\n - Cons: Complex, may block operations\n\n**Recommended approach:**\nCombine #2 and #3:\n- Add `bd sync` command to explicitly flush\n- Provide git hooks in `examples/git-hooks/`\n- Document workflow in AGENTS.md\n- Keep 5s debounce for normal operations\n\n**Related:**\n- bd-38 (daemon version detection)","status":"closed","priority":1,"issue_type":"bug","created_at":"2025-10-23T23:16:29.502191-07:00","updated_at":"2025-10-25T23:15:33.519467-07:00","closed_at":"2025-10-24T22:17:18.871457-07:00"}
{"id":"bd-4","title":"Add transaction support to storage layer for atomic multi-operation workflows","description":"Currently each storage method (CreateIssue, UpdateIssue, etc.) starts its own transaction. This makes it impossible to perform atomic multi-step operations like collision resolution. Add support for passing *sql.Tx through the storage interface, or create transaction-aware versions of methods. This would make remapCollisions and other batch operations truly atomic.","status":"closed","priority":4,"issue_type":"feature","created_at":"2025-10-21T23:53:44.31362-07:00","updated_at":"2025-10-25T23:15:33.463957-07:00","closed_at":"2025-10-14T02:51:52.199176-07:00"}
{"id":"bd-40","title":"Clean up linter errors (914 total issues)","description":"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.","design":"Break down by linter category, prioritizing high-impact issues:\n1. dupl (7) - Code duplication\n2. goconst (12) - Repeated strings\n3. gocyclo (11) - High complexity functions\n4. revive (78) - Style issues\n5. gosec (102) - Security warnings\n6. errcheck (683) - Unchecked errors (many in tests)","acceptance_criteria":"All linter categories reduced to acceptable levels, with remaining baseline documented in LINTING.md","notes":"Reduced from 56 to 41 issues locally, then to 0 issues.\n\n**Fixed in commits:**\n- c2c7eda: Fixed 15 actual errors (dupl, gosec, revive, staticcheck, unparam)\n- 963181d: Configured exclusions to get to 0 issues locally\n\n**Current status:**\n- ✅ Local: golangci-lint reports 0 issues\n- ❌ CI: Still failing (see bd-50)\n\n**Problem:**\nConfig v2 format or golangci-lint-action@v8 compatibility issue causing CI to fail despite local success.\n\n**Next:** Debug bd-50 to fix CI/local discrepancy","status":"in_progress","priority":2,"issue_type":"epic","created_at":"2025-10-24T01:01:12.997982-07:00","updated_at":"2025-10-25T23:15:33.51966-07:00"}
{"id":"bd-41","title":"Fix code duplication in label.go (dupl)","description":"Lines 72-120 duplicate lines 122-170 in cmd/bd/label.go. The add and remove commands have nearly identical structure.","design":"Extract common batch operation logic into a shared helper function that takes the operation type as a parameter.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-24T01:01:36.971666-07:00","updated_at":"2025-10-25T23:15:33.491595-07:00","closed_at":"2025-10-24T12:40:43.046348-07:00","dependencies":[{"issue_id":"bd-41","depends_on_id":"bd-40","type":"parent-child","created_at":"2025-10-24T13:17:40.325899-07:00","created_by":"renumber"}]}
{"id":"bd-42","title":"Refactor high complexity functions (gocyclo)","description":"11 functions exceed cyclomatic complexity threshold (\u003e30): runDaemonLoop (42), importIssuesCore (71), TestLabelCommands (67), issueDataChanged (39), etc.","design":"Break down complex functions into smaller, testable units. Extract validation, error handling, and business logic into separate functions.","notes":"Refactored issueDataChanged from complexity 39 → 11 by extracting into fieldComparator struct with methods for each comparison type.\n\nRefactored runDaemonLoop from complexity 42 → 7 by extracting:\n- setupDaemonLogger: Logger initialization logic\n- setupDaemonLock: Lock and PID file management\n- startRPCServer: RPC server startup with error handling\n- runGlobalDaemon: Global daemon mode handling\n- createSyncFunc: Sync cycle logic (export, commit, pull, import, push)\n- runEventLoop: Signal handling and main event loop\n\nCode review fixes:\n- Fixed sync overlap: Changed initial sync from `go doSync()` to synchronous `doSync()` to prevent race with ticker\n- Fixed resource cleanup: Replaced `os.Exit(1)` with `return` after acquiring locks to ensure defers run and clean up PID files/locks\n- Added signal.Stop(sigChan) in runEventLoop and runGlobalDaemon to prevent lingering notifications\n- Added server.Stop() in serverErrChan case for consistent cleanup\n\nRefactored TestLabelCommands from complexity 67 → \u003c10 by extracting labelTestHelper with methods:\n- createIssue: Issue creation helper\n- addLabel/addLabels: Label addition helpers\n- removeLabel: Label removal helper\n- getLabels: Label retrieval helper\n- assertLabelCount/assertHasLabel/assertHasLabels/assertNotHasLabel: Assertion helpers\n- assertLabelEvent: Event verification helper\n\nRefactored TestReopenCommand from complexity 37 → \u003c10 by extracting reopenTestHelper with methods:\n- createIssue: Issue creation helper\n- closeIssue/reopenIssue: State transition helpers\n- getIssue: Issue retrieval helper\n- addComment: Comment addition helper\n- assertStatus/assertClosedAtSet/assertClosedAtNil: Status assertion helpers\n- assertCommentEvent: Event verification helper\n\nRefactored tryAutoStartDaemon from complexity 34 → \u003c10 by extracting:\n- debugLog: Centralized debug logging helper\n- isDaemonHealthy: Fast-path health check\n- acquireStartLock: Lock acquisition with wait/retry logic\n- handleStaleLock: Stale lock detection and retry\n- handleExistingSocket: Socket cleanup and validation\n- determineSocketMode: Global vs local daemon logic\n- startDaemonProcess: Process spawning and readiness wait\n- setupDaemonIO: I/O redirection setup\n\nRefactored DeleteIssues from complexity 37 → \u003c10 by extracting:\n- buildIDSet: ID deduplication\n- resolveDeleteSet: Cascade/force/validation mode routing\n- expandWithDependents: Recursive dependent collection\n- validateNoDependents: Dependency validation\n- checkSingleIssueValidation: Per-issue dependent check\n- trackOrphanedIssues: Force-mode orphan tracking\n- collectOrphansForID: Per-issue orphan collection\n- buildSQLInClause: SQL placeholder generation\n- populateDeleteStats: Dry-run statistics collection\n- executeDelete: Actual deletion execution\n\nCode review fix (via oracle):\n- Added rows.Err() check in checkSingleIssueValidation to catch iterator errors\n\nRefactored TestLibraryIntegration from complexity 32 → \u003c10 by extracting integrationTestHelper with methods:\n- createIssue/createFullIssue: Issue creation helpers\n- updateIssue/closeIssue: Issue modification helpers\n- addDependency/addLabel/addComment: Relationship helpers\n- getIssue/getDependencies/getLabels/getComments: Retrieval helpers\n- assertID/assertEqual/assertNotNil/assertCount: Assertion helpers\n\nRefactored TestExportImport from complexity 31 → \u003c10 by extracting exportImportHelper with methods:\n- createIssue/createFullIssue: Issue creation helpers\n- searchIssues/getIssue/updateIssue: Storage operations\n- encodeJSONL/validateJSONLines: JSONL encoding and validation\n- assertCount/assertEqual/assertSorted: Assertion helpers\n\nRefactored TestListCommand from complexity 31 → \u003c10 by extracting listTestHelper with methods:\n- createTestIssues: Batch test data creation\n- addLabel: Label addition\n- search: Issue search with filters\n- assertCount/assertEqual/assertAtMost: Assertion helpers\n\nRefactored TestGetEpicsEligibleForClosure from complexity 32 → \u003c10 by extracting epicTestHelper with methods:\n- createEpic/createTask: Issue creation\n- addParentChildDependency/closeIssue: Issue relationships\n- getEligibleEpics/findEpic: Epic status queries\n- assertEpicStats/assertEpicFound/assertEpicNotFound: Epic-specific assertions\n\nRefactored TestCreateIssues from complexity 35 → \u003c10 by extracting createIssuesTestHelper with methods:\n- newIssue: Issue construction helper\n- createIssues: Batch issue creation\n- assertNoError/assertError: Error assertions\n- assertCount/assertIDSet/assertTimestampSet: Field assertions\n- assertUniqueIDs/assertEqual/assertNotNil: Validation helpers\n- assertNoAutoGenID: Error-case validation\n\nAll tests pass after refactoring. ✅\n\n**importIssuesCore was already refactored** (complexity 71 → ~10) using phase-based extraction:\n- getOrCreateStore, handlePrefixMismatch, handleCollisions\n- upsertIssues, importDependencies, importLabels, importComments\n\n**Status:** All 11 high-complexity functions have been refactored to \u003c10 complexity.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-24T01:01:36.989066-07:00","updated_at":"2025-10-25T23:15:33.491926-07:00","closed_at":"2025-10-25T13:16:42.865768-07:00","dependencies":[{"issue_id":"bd-42","depends_on_id":"bd-40","type":"parent-child","created_at":"2025-10-24T13:17:40.323992-07:00","created_by":"renumber"}]}
{"id":"bd-43","title":"Fix revive style issues (78 issues)","description":"Style violations: unused parameters (many cmd/args in cobra commands), missing exported comments, stuttering names (SQLiteStorage), indent-error-flow issues.","design":"Rename unused params to _, add godoc comments to exported types, fix stuttering names, simplify control flow.","notes":"Fixed 19 revive issues:\n- 14 unused-parameter (renamed to _)\n- 2 redefines-builtin-id (max→maxCount, min→minInt)\n- 3 indent-error-flow (gofmt fixed 2, skipped 1 complex nested one)\n\nRemaining issues are acceptable: 11 unused-params in deeper code, 2 empty-blocks with comments, 1 complex indent case, 1 superfluous-else in test.","status":"closed","priority":3,"issue_type":"task","created_at":"2025-10-24T01:01:36.99984-07:00","updated_at":"2025-10-25T23:15:33.492672-07:00","closed_at":"2025-10-25T18:13:45.059903-07:00","dependencies":[{"issue_id":"bd-43","depends_on_id":"bd-40","type":"parent-child","created_at":"2025-10-24T13:17:40.322412-07:00","created_by":"renumber"}]}
{"id":"bd-44","title":"Handle unchecked errors (errcheck - 683 issues)","description":"683 unchecked error returns, mostly in tests (Close, Rollback, RemoveAll). Many already excluded in config but still showing up.","design":"Review .golangci.yml exclude-rules. Most defer Close/Rollback errors in tests can be ignored. Add systematic exclusions or explicit _ = assignments where appropriate.","notes":"Fixed all errcheck warnings in production code:\n- Enabled errcheck linter (was disabled)\n- Set tests: false in .golangci.yml to focus on production code\n- Fixed 27 total errors in production code using Oracle guidance:\n * Database patterns: defer func() { _ = rows.Close() }() and defer func() { _ = tx.Rollback() }()\n * Best-effort closers: _ = store.Close(), _ = client.Close()\n * Proper error handling for file writes, fmt.Scanln(), os.Remove()\n- All tests pass\n- Only 2 \"unused\" linter warnings remain (not errcheck)","status":"closed","priority":3,"issue_type":"task","created_at":"2025-10-24T01:01:37.018404-07:00","updated_at":"2025-10-25T23:15:33.493306-07:00","closed_at":"2025-10-25T18:44:01.656877-07:00","dependencies":[{"issue_id":"bd-44","depends_on_id":"bd-40","type":"parent-child","created_at":"2025-10-24T13:17:40.324423-07:00","created_by":"renumber"}]}
{"id":"bd-45","title":"Update LINTING.md with current baseline","description":"After cleanup, document the remaining acceptable baseline in LINTING.md so we can track regression.","status":"open","priority":2,"issue_type":"task","created_at":"2025-10-24T01:01:37.02745-07:00","updated_at":"2025-10-25T23:15:33.493801-07:00","dependencies":[{"issue_id":"bd-45","depends_on_id":"bd-40","type":"parent-child","created_at":"2025-10-24T13:17:40.327184-07:00","created_by":"renumber"},{"issue_id":"bd-45","depends_on_id":"bd-41","type":"blocks","created_at":"2025-10-24T13:17:40.327422-07:00","created_by":"renumber"},{"issue_id":"bd-45","depends_on_id":"bd-42","type":"blocks","created_at":"2025-10-24T13:17:40.327827-07:00","created_by":"renumber"},{"issue_id":"bd-45","depends_on_id":"bd-43","type":"blocks","created_at":"2025-10-24T13:17:40.32803-07:00","created_by":"renumber"},{"issue_id":"bd-45","depends_on_id":"bd-44","type":"blocks","created_at":"2025-10-24T13:51:54.447799-07:00","created_by":"renumber"}]}
{"id":"bd-46","title":"Fix Windows CI test failures (5 failing tests)","description":"Windows CI has 5 flaky/failing tests: TestTryDaemonLockDetectsRunning, TestIsDaemonRunning_CurrentProcess (PID detection issues), TestScripts/import, TestMetricsSnapshot/uptime, TestSocketCleanup (socket in use).","design":"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.","status":"closed","priority":1,"issue_type":"bug","created_at":"2025-10-24T09:28:17.976175-07:00","updated_at":"2025-10-25T23:15:33.494121-07:00","closed_at":"2025-10-24T09:36:59.351114-07:00"}
{"id":"bd-47","title":"Investigate GH#144: FOREIGN KEY regression in v0.16.0","description":"v0.16.0 introduced FOREIGN KEY constraint error when closing issues via MCP (daemon mode). CLI works fine.\n\n**Key Finding**: Only change between v0.15.0 and v0.16.0 that could affect FK behavior is:\n- modernc.org/sqlite bumped from 1.38.2 to 1.39.1 (commit fbe63bf)\n\n**Evidence**:\n- User reports v0.15.0 worked perfectly (Oct 24, 04:35 UTC)\n- v0.16.0 fails with 'constraint failed: FOREIGN KEY constraint failed (787)'\n- Error occurs in both close() tool and update(status=closed) smart routing\n- CLI 'bd close' works fine, only MCP/daemon fails\n- No changes to CloseIssue() implementation between versions\n- No changes to schema or RPC server handlers\n\n**Next Steps**:\n1. Test downgrading sqlite to 1.38.2\n2. Check modernc.org/sqlite changelog for FK-related changes\n3. Reproduce locally with MCP\n4. If sqlite is the culprit, either fix or pin version\n\n**Related**: GH #144","status":"closed","priority":0,"issue_type":"bug","created_at":"2025-10-24T11:24:39.423407-07:00","updated_at":"2025-10-25T23:15:33.494392-07:00","closed_at":"2025-10-24T11:49:16.683734-07:00"}
{"id":"bd-48","title":"Test FK regression fix","description":"","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-24T11:25:36.132893-07:00","updated_at":"2025-10-25T23:15:33.494661-07:00","closed_at":"2025-10-24T11:25:38.270206-07:00"}
{"id":"bd-49","title":"Investigate and upgrade to modernc.org/sqlite 1.39.1+","description":"We had to pin modernc.org/sqlite to v1.38.2 due to a FOREIGN KEY constraint regression in v1.39.1 (SQLite 3.50.4).\n\n**Issue:** bd-47, GH #144\n\n**Symptom:** CloseIssue fails with \"FOREIGN KEY constraint failed (787)\" when called via MCP/daemon, but works fine via CLI.\n\n**Root Cause:** Unknown - likely stricter FK enforcement in SQLite 3.50.4 or modernc.org wrapper changes.\n\n**Workaround:** Pinned to v1.38.2 (SQLite 3.49.x)\n\n**TODO:**\n1. Monitor modernc.org/sqlite releases for fixes\n2. Check SQLite 3.50.5+ changelogs for FK-related fixes\n3. Investigate why daemon mode fails but CLI succeeds (connection reuse? transaction isolation?)\n4. Consider filing upstream issue with reproducible test case\n5. Upgrade when safe","status":"open","priority":2,"issue_type":"task","created_at":"2025-10-24T11:49:12.836292-07:00","updated_at":"2025-10-25T23:15:33.520001-07:00","dependencies":[{"issue_id":"bd-49","depends_on_id":"bd-47","type":"discovered-from","created_at":"2025-10-24T13:17:40.321578-07:00","created_by":"renumber"}]}
{"id":"bd-5","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","status":"closed","priority":3,"issue_type":"task","created_at":"2025-10-21T23:53:44.31362-07:00","updated_at":"2025-10-25T23:15:33.464905-07:00","closed_at":"2025-10-14T02:51:52.198988-07:00"}
{"id":"bd-50","title":"CI still failing despite local lint passing - config v2 issue","description":"Despite fixing all lint issues locally (golangci-lint reports 0 issues), CI continues to fail for dependabot PRs and test/lint checks.\n\n**Local environment:**\n- golangci-lint v2.5.0 \n- .golangci.yml version: \"2\" (v2 config format)\n- Result: 0 issues ✅\n\n**CI environment:**\n- golangci/golangci-lint-action@v8\n- golangci-lint version: v2.5.0\n- Result: FAILING ❌\n\n**Root cause suspects:**\n\n1. **Config v2 compatibility**: The golangci-lint-action@v8 may not properly support config version \"2\" format, causing exclusion rules to be ignored\n\n2. **Environment differences**: \n - CI runs on Ubuntu (linux/amd64)\n - Local runs on macOS (darwin/arm64)\n - Pattern matching in exclusions might behave differently\n\n3. **Default linters**: CI might enable different default linters that aren't covered by our exclusions\n\n4. **Config parsing**: The action might not properly read .golangci.yml or apply settings correctly\n\n**Evidence:**\n- Commits 963181d and c2c7eda fixed issues locally\n- git push succeeded\n- But CI still showing failures on dependabot PRs","design":"**Investigation steps:**\n\n1. Access actual CI logs from failing runs to see exact error messages\n2. Test exact CI command locally: `golangci-lint run --timeout=5m ./...`\n3. Check if .golangci.yml is being loaded by adding debug output\n4. Compare default linters between local and CI: `golangci-lint linters`\n5. Test config v1 format vs v2 format\n\n**Potential fixes:**\n\nA. **Switch to config v1**: Revert .golangci.yml to version 1 format (older but more stable)\n\nB. **Explicit linter control**: Use `disable-all: true` and only enable specific linters\n\nC. **Update action version**: Try newer golangci-lint-action or pin different golangci-lint version\n\nD. **Inline exclusions**: Move exclusions from YAML to nolint directives in code\n\nE. **CI override**: Add `args: --disable=gocyclo,gosec` to CI workflow","acceptance_criteria":"- CI passes lint checks with 0 issues\n- Dependabot PRs can merge successfully \n- Local and CI environments report same lint results\n- Config is maintainable and exclusions work reliably","notes":"Fixed: added 'version: \"2\"' to .golangci.yml and upgraded golangci-lint-action from v6 to v8 with version: latest","status":"closed","priority":1,"issue_type":"bug","created_at":"2025-10-24T13:01:08.700153-07:00","updated_at":"2025-10-25T23:15:33.495203-07:00","closed_at":"2025-10-24T22:04:29.560073-07:00"}
{"id":"bd-51","title":"Add findByExternalRef query and database index","description":"Implement storage layer support for looking up issues by external_ref field.\n\n## Tasks\n- Add findByExternalRef(ctx, externalRef) method to SQLiteStorage\n- Add database index: CREATE INDEX IF NOT EXISTS idx_issues_external_ref ON issues(external_ref)\n- Handle nil/empty external_ref cases properly\n- Add unit tests for the new query method","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-24T13:08:46.347089-07:00","updated_at":"2025-10-25T23:15:33.495455-07:00","closed_at":"2025-10-24T13:35:23.287814-07:00"}
{"id":"bd-52","title":"Modify collision detection to check external_ref first","description":"Update DetectCollisions in collision.go to use external_ref as primary matching key.\n\n## Changes\n- In DetectCollisions: before checking issue ID, check if incoming has external_ref\n- If external_ref is set, call findByExternalRef to find existing issue\n- If found by external_ref, compare content:\n - If matches: add to ExactMatches\n - If differs: treat as UPDATE (not collision)\n- Only fall back to ID-based matching if no external_ref\n- Add comprehensive tests for all matching scenarios","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-24T13:08:46.35339-07:00","updated_at":"2025-10-25T23:15:33.497074-07:00","closed_at":"2025-10-24T13:35:23.28803-07:00"}
{"id":"bd-53","title":"Update import flow to handle external_ref updates","description":"Modify importIssuesCore in import_shared.go to handle external_ref-based updates.\n\n## Changes\n- Phase 4: When processing issues, check collision result for external_ref matches\n- Track external_ref updates separately from ID-based updates\n- Ensure local issues (no external_ref) are never overwritten by imports\n- Handle ID conflicts when external issue ID matches local issue ID (auto-remap)\n- Update result reporting to show external_ref updates vs ID updates","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-24T13:08:46.365581-07:00","updated_at":"2025-10-25T23:15:33.497368-07:00","closed_at":"2025-10-24T13:35:23.288208-07:00"}
{"id":"bd-54","title":"Write comprehensive tests for external_ref import scenarios","description":"Create test suite covering all external_ref import behaviors.\n\n## Test Cases\n1. Import with external_ref → creates new issue\n2. Re-import same external_ref with changes → updates existing\n3. Re-import same external_ref unchanged → idempotent (no update)\n4. Import external issue with ID collision → auto-remaps external issue\n5. Import without external_ref → uses current ID-based logic\n6. Mixed batch: some with external_ref, some without\n7. External_ref match + ID mismatch → updates by external_ref\n8. Local issue (no external_ref) never matched by external import\n9. Performance test with external_ref index\n\nAdd tests to:\n- cmd/bd/import_shared_test.go\n- internal/storage/sqlite/collision_test.go","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-24T13:08:46.376432-07:00","updated_at":"2025-10-25T23:15:33.497618-07:00","closed_at":"2025-10-24T13:35:23.28838-07:00"}
{"id":"bd-55","title":"Update documentation for external_ref import behavior","description":"Document the new external_ref-based import matching behavior.\n\n## Files to Update\n- README.md: Add external_ref import section\n- QUICKSTART.md: Add example of Jira/GitHub integration workflow\n- AGENTS.md: Document external_ref import behavior for AI agents\n- FAQ.md: Add Q\u0026A about external system integration\n- Add examples/ directory entry showing Jira/GitHub/Linear integration\n\n## Key Points to Document\n- How external_ref matching works\n- That local issues are protected from external imports\n- Example workflow: import → add local tasks → re-import updates\n- ID conflict resolution behavior","status":"closed","priority":2,"issue_type":"task","created_at":"2025-10-24T13:08:46.390992-07:00","updated_at":"2025-10-25T23:15:33.497871-07:00","closed_at":"2025-10-24T13:35:23.288575-07:00"}
{"id":"bd-56","title":"Code review: external_ref import feature","description":"Comprehensive code review of external_ref import implementation.\n\n## Review Checklist\n- [ ] Storage layer changes are correct and efficient\n- [ ] Index created properly on external_ref column\n- [ ] Collision detection logic handles all edge cases\n- [ ] Import flow correctly distinguishes external vs local issues\n- [ ] No breaking changes to existing workflows\n- [ ] Tests cover all scenarios (see bd-54)\n- [ ] Documentation is clear and complete (see bd-55)\n- [ ] Performance impact is acceptable\n- [ ] Error messages are helpful\n- [ ] Logging is appropriate for debugging\n\n## Oracle Review\nUse oracle tool to analyze implementation for correctness, edge cases, and potential issues.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-24T13:08:46.395433-07:00","updated_at":"2025-10-25T23:15:33.520273-07:00","closed_at":"2025-10-24T13:35:23.288755-07:00"}
{"id":"bd-57","title":"Warn when multiple beads databases detected in workspace hierarchy","description":"Add detection and warning when multiple .beads directories exist in the workspace hierarchy to prevent confusion and database pollution.\n\n## Problem\nUsers can accidentally work in the wrong beads database when multiple exist (e.g., ~/src/beads and ~/src/fred/beads), leading to:\n- Database pollution from cross-contamination\n- Lost work when changes go to wrong database\n- Confusion about which database is active\n\n## Solution\nOn startup, scan parent directories for additional .beads directories and:\n- Warn if multiple found\n- Show which database is currently active\n- Suggest consolidation or cleanup\n\n## Detection Strategy\n1. Walk up directory tree from CWD\n2. Check for .beads/bd.db in each level\n3. If multiple found, show warning with paths\n4. Optionally: check common sibling directories\n\n## Example Warning\n```\n⚠ Multiple beads databases detected:\n - /Users/stevey/src/beads/.beads (ACTIVE - 111 issues)\n - /Users/stevey/src/fred/beads/.beads (202 issues)\n \nConsider consolidating or removing unused databases.\n```","status":"closed","priority":2,"issue_type":"feature","created_at":"2025-10-24T13:17:08.772366-07:00","updated_at":"2025-10-25T23:15:33.498578-07:00","closed_at":"2025-10-24T15:27:50.97772-07:00"}
{"id":"bd-58","title":"Optimize auto-flush to use incremental updates","description":"Every flush exports ALL issues and ALL dependencies, even if only one issue changed. For large projects (1000+ issues), this could be expensive. Current approach guarantees consistency, which is fine for MVP, but future optimization could track which issues changed and use incremental updates. Located in cmd/bd/main.go:255-276.","status":"closed","priority":3,"issue_type":"feature","created_at":"2025-10-24T13:31:30.813833-07:00","updated_at":"2025-10-25T23:15:33.498951-07:00","closed_at":"2025-10-14T02:51:52.200141-07:00"}
{"id":"bd-59","title":"Fix flaky TestMetricsSnapshot/memory_stats on Linux","description":"Linux CI test TestMetricsSnapshot/memory_stats fails with \"Expected non-zero memory allocation\". Appears to be a flaky test - metrics_test.go:168.","design":"Add retry logic or wait for GC stats to populate, or adjust test expectations for timing.","status":"closed","priority":2,"issue_type":"bug","created_at":"2025-10-24T13:31:30.814562-07:00","updated_at":"2025-10-25T23:15:33.499152-07:00","closed_at":"2025-10-25T17:53:23.145785-07:00"}
{"id":"bd-6","title":"Simplify getNextID SQL query parameters","description":"Query passes prefix four times to same SQL query. Works but fragile if query changes. Consider simplifying SQL to require fewer parameters. Location: internal/storage/sqlite/sqlite.go:73-78","status":"closed","priority":3,"issue_type":"task","created_at":"2025-10-21T23:53:44.31362-07:00","updated_at":"2025-10-25T23:15:33.465776-07:00","closed_at":"2025-10-16T10:07:34.038708-07:00"}
{"id":"bd-60","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-29 design.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-24T13:31:30.814825-07:00","updated_at":"2025-10-25T23:15:33.520455-07:00","closed_at":"2025-10-22T01:07:14.145014-07:00"}
{"id":"bd-61","title":"Update export/import for merge fields","description":"Include merged_into in JSONL export format. Handle merge relationships on import.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-24T13:31:30.81511-07:00","updated_at":"2025-10-25T23:15:33.499572-07:00","closed_at":"2025-10-22T01:07:14.146226-07:00"}
{"id":"bd-62","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.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-24T13:31:30.815356-07:00","updated_at":"2025-10-25T23:15:33.499776-07:00","closed_at":"2025-10-22T01:07:04.718151-07:00"}
{"id":"bd-63","title":"Add CLI merge command and flags","description":"Implement bd merge command with: multiple sources, --into target, --dry-run, --json flags. Add interactive confirmation.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-24T13:31:30.815605-07:00","updated_at":"2025-10-25T23:15:33.499984-07:00","closed_at":"2025-10-22T01:07:04.719421-07:00"}
{"id":"bd-64","title":"Document label best practices and use cases","description":"Create documentation covering:\n- When to use labels vs structured fields\n- Common label sets (coding agents, open source, product dev, SRE)\n- Naming conventions (kebab-case, specificity, present tense)\n- Anti-patterns (too many labels, overlapping, personal labels)\n- Label lifecycle management\n\nContent from LABELS.md analysis document.","status":"closed","priority":3,"issue_type":"task","created_at":"2025-10-24T13:31:30.815861-07:00","updated_at":"2025-10-25T23:15:33.50022-07:00","closed_at":"2025-10-19T23:11:46.125417-07:00"}
{"id":"bd-65","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","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-24T13:31:30.816373-07:00","updated_at":"2025-10-25T23:15:33.500429-07:00","closed_at":"2025-10-22T01:07:04.720032-07:00"}
{"id":"bd-66","title":"Fix flaky CI tests in compactor and daemon modules","description":"Multiple test failures observed in CI:\n- TestCompactTier1_DryRun \n- TestCompactTier1Batch_DryRun\n- TestCompactTier1Batch_WithIneligible\n- TestMockAPI_CompactTier1\n- TestBatchOperations_ErrorHandling\n- TestCommentOperationsViaRPC\n- TestMemoryPressureDetection\n- TestPing\n\nAll failures related to 'issue has open dependents or not closed long enough' eligibility checks.\n\nSee CI run: https://github.com/steveyegge/beads/actions/runs/18688772658","notes":"Fixed race condition in compactor_test.go. The createClosedIssue helper was setting ClosedAt to time.Now(), but the eligibility check uses '\u003c= datetime(now, -0 days)'. Changed to now.Add(-1*time.Second) to ensure issues are always eligible. All tests now passing.","status":"closed","priority":1,"issue_type":"bug","created_at":"2025-10-24T13:31:30.816605-07:00","updated_at":"2025-10-25T23:15:33.500636-07:00","closed_at":"2025-10-22T09:59:41.419442-07:00"}
{"id":"bd-67","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.\n\nThe daemon RPC interface doesn't properly expose the compact command, even though the daemon itself uses SQLite storage.\n\nReproduction:\n1. Ensure daemon is running (bd daemon status)\n2. Run: bd compact --stats\n Result: Error: compact requires SQLite storage\n3. Run: bd compact --stats --no-daemon\n Result: Works correctly, shows statistics\n\nExpected behavior:\nThe compact command should work through the daemon RPC interface just like other commands (list, create, update, delete, renumber, etc.)\n\nImpact:\nUsers cannot use compact operations in the normal workflow. They must use --no-daemon which bypasses the daemon entirely.\n\nSuggested fix:\nAdd compact operation support to the daemon RPC interface, similar to how renumber and other operations are exposed.","status":"closed","priority":1,"issue_type":"bug","created_at":"2025-10-24T13:31:30.816874-07:00","updated_at":"2025-10-25T23:15:33.500853-07:00","closed_at":"2025-10-22T19:46:55.793852-07:00"}
{"id":"bd-68","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.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-24T13:31:30.817436-07:00","updated_at":"2025-10-25T23:15:33.501083-07:00","closed_at":"2025-10-22T01:05:59.461242-07:00"}
{"id":"bd-69","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.\n\nDiscovered during execution of vc-228 (dogfooding run #14/15).","design":"Implement a pre-commit hook that:\n1. Detects changes to internal/storage/storage.go\n2. Runs scripts/find-storage-mocks.sh to find all mock implementations\n3. Attempts to compile all test files with mocks\n4. Blocks commit if compilation fails\n\nTools: husky, pre-commit framework, or simple .git/hooks/pre-commit script","acceptance_criteria":"- Pre-commit hook installed and documented\n- Hook detects Storage interface changes\n- Hook validates all mocks compile\n- Hook can be bypassed with --no-verify if needed\n- Documentation updated with installation instructions","status":"closed","priority":2,"issue_type":"feature","created_at":"2025-10-24T13:31:30.817945-07:00","updated_at":"2025-10-25T23:15:33.50129-07:00","closed_at":"2025-10-22T21:57:59.266619-07:00"}
{"id":"bd-7","title":"Refactor parseMarkdownFile to reduce cyclomatic complexity","description":"The parseMarkdownFile function in cmd/bd/markdown.go has a cyclomatic complexity of 38, which exceeds the recommended threshold of 30. This makes the function harder to understand, test, and maintain.","design":"Split the function into smaller, focused units:\n\n1. parseMarkdownFile(filepath) - Main entry point, handles file I/O\n2. parseMarkdownContent(scanner) - Core parsing logic\n3. processIssueSection(issue, section, content) - Handle section finalization (current switch statement)\n4. parseLabels(content) []string - Extract labels from content\n5. parseDependencies(content) []string - Extract dependencies from content\n6. parsePriority(content) int - Parse and validate priority\n\nBenefits:\n- Each function has a single responsibility\n- Easier to test individual components\n- Lower cognitive load when reading code\n- Better encapsulation of parsing logic","acceptance_criteria":"- parseMarkdownFile complexity \u003c 15\n- New helper functions each have complexity \u003c 10\n- All existing tests still pass\n- No change in functionality or behavior\n- Code coverage maintained or improved","status":"closed","priority":3,"issue_type":"task","created_at":"2025-10-21T23:53:44.31362-07:00","updated_at":"2025-10-25T23:15:33.466753-07:00","closed_at":"2025-10-14T14:37:17.463352-07:00"}
{"id":"bd-70","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.\n\nExamples:\n bd compact --all --older-than 60h\n bd compact --all --older-than 2.5d\n bd compact --all --tier 1 --age 48h\n\nThis would allow users to set their own compaction schedules based on their workflow needs.","status":"closed","priority":2,"issue_type":"feature","created_at":"2025-10-24T13:31:30.818447-07:00","updated_at":"2025-10-25T23:15:33.501493-07:00","closed_at":"2025-10-22T21:58:51.119025-07:00"}
{"id":"bd-71","title":"Add --id flag to bd list for filtering by specific issue IDs","description":"","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.","status":"closed","priority":2,"issue_type":"feature","created_at":"2025-10-24T13:31:30.818661-07:00","updated_at":"2025-10-25T23:15:33.501735-07:00","closed_at":"2025-10-22T21:31:01.770796-07:00"}
{"id":"bd-72","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.\n\n**Reproduction:**\n```bash\n# With daemon running\n./bd sync\n```\n\n**Error:**\n```\npanic: runtime error: invalid memory address or nil pointer dereference\n[signal SIGSEGV: segmentation violation code=0x2 addr=0x120 pc=0x1012314ac]\n\ngoroutine 1 [running]:\nmain.exportToJSONL({0x1014ec2e0, 0x101a49900}, {0x14000028db0, 0x30})\n /Users/stevey/src/fred/beads/cmd/bd/sync.go:245 +0x4c\n```\n\n**Root cause:**\nThe 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:\n1. Use daemon RPC when daemon is running, or\n2. Force direct mode for sync operations\n\n**Workaround:**\nUse `--no-daemon` flag: `bd sync --no-daemon`","status":"closed","priority":0,"issue_type":"bug","created_at":"2025-10-24T13:31:30.819041-07:00","updated_at":"2025-10-25T23:15:33.50194-07:00","closed_at":"2025-10-22T00:09:12.615536-07:00"}
{"id":"bd-73","title":"Optimize export dependency queries (N+1 problem)","description":"Export triggers separate GetDependencyRecords() per issue. For large DBs (1000+ issues), this is N+1 queries. Add GetAllDependencyRecords() to fetch all dependencies in one query. Location: cmd/bd/export.go:52-59, import.go:138-142","status":"closed","priority":3,"issue_type":"task","created_at":"2025-10-24T13:31:30.819234-07:00","updated_at":"2025-10-25T23:15:33.502151-07:00","closed_at":"2025-10-14T02:51:52.19905-07:00"}
{"id":"bd-74","title":"Add workspace config file for multi-repo management (optional enhancement)","description":"For users who want explicit control over multi-repo setup without daemon, add optional workspace config file.\n\nConfig file: ~/.beads/workspaces.toml\n\nExample:\n[workspaces]\ncurrent = \"global\"\n\n[workspace.global]\ndb = \"~/.beads/global.db\"\ndescription = \"System-wide tasks\"\n\n[workspace.project1] \ndb = \"~/src/project1/.beads/db.sqlite\"\ndescription = \"Main product\"\n\n[workspace.project2]\ndb = \"~/src/project2/.beads/db.sqlite\"\ndescription = \"Internal tools\"\n\nCommands:\nbd workspace list # Show all workspaces\nbd workspace add NAME PATH # Add workspace\nbd workspace remove NAME # Remove workspace \nbd workspace use NAME # Switch active workspace\nbd workspace current # Show current workspace\nbd --workspace NAME \u003ccommand\u003e # Override for single command\n\nImplementation:\n- Load config in PersistentPreRun\n- Override dbPath based on current workspace\n- Store workspace state in config file\n- Support both workspace config AND auto-discovery\n- Workspace config takes precedence over auto-discovery\n\nPriority rationale:\n- Priority 3 (low) because daemon approach already solves this\n- Only implement if users request explicit workspace management\n- Adds complexity vs daemon's automatic discovery\n\nAlternative: Users can use BEADS_DB env var for manual workspace switching today.","status":"closed","priority":3,"issue_type":"feature","created_at":"2025-10-24T13:31:30.81943-07:00","updated_at":"2025-10-25T23:15:33.502357-07:00","closed_at":"2025-10-20T16:04:27.216482-07:00"}
{"id":"bd-75","title":"Use safer placeholder pattern in replaceIDReferences","description":"Currently uses bd-313 which could theoretically collide with user text. Use a truly unique placeholder like null bytes: \\x00REMAP\\x00_0_\\x00 which are unlikely to appear in normal text. Located in collision.go:324. Very low probability issue but worth fixing for completeness.","status":"closed","priority":3,"issue_type":"task","created_at":"2025-10-24T13:31:30.819616-07:00","updated_at":"2025-10-25T23:15:33.502563-07:00","closed_at":"2025-10-18T09:43:18.250156-07:00"}
{"id":"bd-76","title":"Implement full cross-type cycle prevention in AddDependency","description":"Expand cycle prevention in AddDependency to check for cycles across ALL dependency types, not just 'blocks'. Currently only 'blocks' type dependencies are checked for cycles, allowing cross-type circular dependencies to form (e.g., A blocks B, B parent-child A). This can cause semantic confusion and is a maintenance hazard for future operations that traverse dependencies.","design":"Implementation approach:\n1. Modify the cycle check in AddDependency (postgres.go:559-599)\n2. Remove the 'type = blocks' filter from the recursive CTE\n3. Check for cycles regardless of dependency type being added\n4. Return a clear error message indicating which types form the cycle\n\nTrade-offs to consider:\n- This is more mathematically correct (no cycles in dependency DAG)\n- May break legitimate use cases where cross-type cycles are intentional\n- Need to evaluate whether ANY cross-type cycles are valid in practice\n- Alternative: make this configurable with a --allow-cycle flag\n\nBefore implementing, should investigate:\n- Are there legitimate reasons for cross-type cycles?\n- What's the performance impact on large graphs (1000+ issues)?\n- Should certain type combinations be allowed to cycle?","acceptance_criteria":"- AddDependency prevents cycles across all dependency types, not just 'blocks'\n- Clear error message when cycle would be created, including dependency types\n- All existing tests pass\n- Performance benchmarked on large dependency graphs (100+ issues)\n- Decision documented on whether to add --allow-cycle flag or exception rules","status":"closed","priority":3,"issue_type":"task","created_at":"2025-10-24T13:31:30.819813-07:00","updated_at":"2025-10-25T23:15:33.502761-07:00","closed_at":"2025-10-16T20:31:19.174534-07:00"}
{"id":"bd-77","title":"Refactor duplicate flush logic in PersistentPostRun","description":"PersistentPostRun contains a complete copy of the flush logic instead of calling flushToJSONL(). This violates DRY principle and makes maintenance harder. Refactor to use flushToJSONL() with a force parameter to bypass isDirty check, or extract shared logic into a helper function. Located in cmd/bd/main.go:104-138.","status":"closed","priority":3,"issue_type":"task","created_at":"2025-10-24T13:31:30.820022-07:00","updated_at":"2025-10-25T23:15:33.502974-07:00","closed_at":"2025-10-18T09:44:24.167574-07:00"}
{"id":"bd-78","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.\n\nExample output:\n Tier 1 candidates: 15 issues\n Current size: 2.4 MB\n After compaction: ~1.7 MB (70% reduction, 0.7 MB saved)\n \nThis helps users understand impact before compacting.","status":"closed","priority":3,"issue_type":"feature","created_at":"2025-10-24T13:31:30.820758-07:00","updated_at":"2025-10-25T23:15:33.503199-07:00","closed_at":"2025-10-22T21:59:19.990804-07:00"}
{"id":"bd-79","title":"Add EXPLAIN QUERY PLAN tests for ready work query","description":"Verify that the hierarchical blocking query uses proper indexes and doesn't do full table scans.\n\n**Queries to analyze:**\n1. The recursive CTE (both base case and recursive case)\n2. The final SELECT with NOT EXISTS\n3. Impact of various filters (status, priority, assignee)\n\n**Implementation:**\nAdd test function that:\n- Runs EXPLAIN QUERY PLAN on GetReadyWork query\n- Parses output to verify no SCAN TABLE operations\n- Documents expected query plan in comments\n- Fails if query plan degrades\n\n**Benefits:**\n- Catch performance regressions in tests\n- Document expected query behavior\n- Ensure indexes are being used\n\nRelated to: bd-36 (composite index on depends_on_id, type)","status":"closed","priority":3,"issue_type":"task","created_at":"2025-10-24T13:31:30.821538-07:00","updated_at":"2025-10-25T23:15:33.520822-07:00","closed_at":"2025-10-18T12:47:44.284846-07:00"}
{"id":"bd-8","title":"Add --show-all-paths flag to bd dep tree","description":"Currently bd dep tree deduplicates nodes when multiple paths exist (diamond dependencies). Add optional --show-all-paths flag to display the full graph with all paths, showing duplicates. Useful for debugging complex dependency structures and understanding all relationships.","status":"closed","priority":3,"issue_type":"feature","created_at":"2025-10-21T23:53:44.31362-07:00","updated_at":"2025-10-25T23:15:33.467785-07:00","closed_at":"2025-10-18T10:11:38.985862-07:00"}
{"id":"bd-80","title":"Add performance benchmarks document","description":"Document actual performance metrics with hyperfine tests","status":"closed","priority":3,"issue_type":"task","created_at":"2025-10-24T13:31:30.82171-07:00","updated_at":"2025-10-25T23:15:33.503621-07:00","closed_at":"2025-10-18T10:09:23.532938-07:00"}
{"id":"bd-81","title":"Investigate vector/semantic search for issue discovery","description":"From GH issue #2 RFC discussion: Evaluate if vector/semantic search over issues would provide value for beads.\n\n**Use case:** Find semantically related issues (e.g., 'login broken' finds 'authentication failure', 'session expired').\n\n**Questions to answer:**\n1. What workflows would this enable that we can't do now?\n2. Is dataset size (typically 50-200 issues) large enough to benefit?\n3. Do structured features (deps, tags, types) already provide better relationships?\n4. What's the maintenance cost (embeddings, storage, recomputation)?\n\n**Alternatives to consider:**\n- Improve 'bd list' filtering with regex/boolean queries\n- Add 'bd related \u003cid\u003e' showing deps + mentions + same tags\n- Export to JSON and pipe to external AI tools\n\n**Decision:** Only implement if clear use case emerges. Don't add complexity for theoretical benefits.\n\n**Context:** Part of evaluating Turso RFC ideas (GH #2). Vector search was proposed but unclear if needed for typical beads usage.","status":"closed","priority":3,"issue_type":"task","created_at":"2025-10-24T13:31:30.82189-07:00","updated_at":"2025-10-25T23:15:33.503824-07:00","closed_at":"2025-10-18T10:09:23.532858-07:00"}
{"id":"bd-82","title":"Add visual indicators for nodes with multiple parents in dep tree","description":"When a node appears in the dependency tree via multiple paths (diamond dependencies), add a visual indicator like (*) or (multiple parents) to help users understand the graph structure. This would make it clear when deduplication has occurred. Example: 'bd-503: Shared dependency (*) [P1] (open)'","status":"closed","priority":3,"issue_type":"feature","created_at":"2025-10-24T13:31:30.822073-07:00","updated_at":"2025-10-25T23:15:33.50409-07:00","closed_at":"2025-10-20T14:34:52.483358-07:00"}
{"id":"bd-83","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":"closed","priority":1,"issue_type":"task","created_at":"2025-10-24T13:31:30.82284-07:00","updated_at":"2025-10-25T23:15:33.504325-07:00","closed_at":"2025-10-22T01:07:04.72062-07:00"}
{"id":"bd-84","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.","status":"closed","priority":4,"issue_type":"chore","created_at":"2025-10-24T13:31:30.82441-07:00","updated_at":"2025-10-25T23:15:33.504524-07:00","closed_at":"2025-10-19T19:22:19.172983-07:00"}
{"id":"bd-85","title":"Document merge command and AI integration","description":"Update README, AGENTS.md with merge command examples. Document AI agent duplicate detection workflow.","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-24T13:31:30.824587-07:00","updated_at":"2025-10-25T23:15:33.504759-07:00","closed_at":"2025-10-22T11:37:41.104918-07:00"}
{"id":"bd-86","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.","status":"closed","priority":0,"issue_type":"bug","assignee":"amp","created_at":"2025-10-24T13:31:30.824773-07:00","updated_at":"2025-10-25T23:15:33.504967-07:00","closed_at":"2025-10-22T00:35:00.620546-07:00"}
{"id":"bd-87","title":"Add cross-repo issue references (future enhancement)","description":"Support referencing issues across different beads repositories. Useful for tracking dependencies between separate projects.\n\nProposed syntax:\n- Local reference: bd-28 (current behavior)\n- Cross-repo by path: ~/src/other-project#bd-456\n- Cross-repo by workspace name: @project2:bd-789\n\nUse cases:\n1. Frontend project depends on backend API issue\n2. Shared library changes blocking multiple projects\n3. System administrator tracking work across machines\n4. Monorepo with separate beads databases per component\n\nImplementation challenges:\n- Storage layer needs to query external databases\n- Dependency resolution across repos\n- What if external repo not available?\n- How to handle in JSONL export/import?\n- Security: should repos be able to read others?\n\nDesign questions to resolve first:\n1. Read-only references vs full cross-repo dependencies?\n2. How to handle repo renames/moves?\n3. Absolute paths vs workspace names vs git remotes?\n4. Should bd-27 auto-discover related repos?\n\nRecommendation: \n- Gather user feedback first\n- Start with read-only references\n- Implement as plugin/extension?\n\nContext: This is mentioned in bd-27 as approach #2. Much more complex than daemon multi-repo approach. Only implement if there's strong user demand.\n\nPriority: Backlog (4) - wait for user feedback before designing","status":"closed","priority":4,"issue_type":"feature","created_at":"2025-10-24T13:31:30.824965-07:00","updated_at":"2025-10-25T23:15:33.521043-07:00","closed_at":"2025-10-20T22:00:31.966891-07:00"}
{"id":"bd-88","title":"Add rule-based compaction (e.g., compact children of closed epics)","description":"Support semantic compaction rules beyond just time-based, such as:\n- Compact all children of closed epics\n- Compact by priority level (e.g., all P3/P4 closed issues)\n- Compact by label (e.g., all issues labeled 'archive')\n- Compact by type (e.g., all closed chores)\n\nThis would allow smarter database size management based on semantic meaning rather than just age.","status":"closed","priority":3,"issue_type":"feature","created_at":"2025-10-24T13:31:30.825312-07:00","updated_at":"2025-10-25T23:15:33.505393-07:00","closed_at":"2025-10-22T21:59:19.989241-07:00"}
{"id":"bd-89","title":"Add automated duplicate detection tool for post-import cleanup","description":"After collision resolution with --resolve-collisions, we can end up with content duplicates (different IDs, identical content) when parallel work creates the same issues.\n\n## Problem\nCurrent situation:\n- `deduplicateIncomingIssues()` only deduplicates within the import batch\n- Doesn't detect duplicates between DB and incoming issues\n- Doesn't detect duplicates across the entire database post-import\n- Manual detection: `bd list --json | jq 'group_by(.title) | map(select(length \u003e 1))'`\n\n## Real Example\nAfter import with collision resolution, we had 7 duplicate pairs:\n--196/bd-67: Same external_ref epic\n--196-196: Same findByExternalRef task\n--196-196: Same collision detection task\n--196-196: Same import flow task\n--196-196: Same test writing task\n--196-196: Same documentation task\n--196-196: Same code review task\n\n## Proposed Solution\nAdd `bd duplicates` command that:\n1. Groups all issues by content hash (title + description + design + acceptance_criteria)\n2. Reports duplicate groups with suggested merge target (lowest ID or most references)\n3. Optionally auto-merge with `--auto-merge` flag\n4. Respects status (don't merge open with closed)\n\n## Example Output\n```\n🔍 Found 7 duplicate groups:\n\nGroup 1: \"Feature: Use external_ref as primary matching key\"\n --196 (open, P1, 0 references)\n - bd-67 (open, P1, 0 references)\n Suggested merge: bd merge-196 --into bd-67\n\nGroup 2: \"Add findByExternalRef query\"\n --196 (open, P1, 0 references) \n --196 (open, P1, 0 references)\n Suggested merge: bd merge-196 --into-196\n...\n\nRun with --auto-merge to execute all suggested merges\n```\n\n## Implementation Notes\n- Use same content hashing as deduplicateIncomingIssues\n- Consider reference counts when choosing merge target\n- Skip duplicates with different status (open vs closed)\n- Add --dry-run mode\n- Integration with import: `bd import --resolve-collisions --dedupe-after`","status":"closed","priority":2,"issue_type":"feature","created_at":"2025-10-24T13:35:14.97041-07:00","updated_at":"2025-10-25T23:15:33.505601-07:00","closed_at":"2025-10-24T13:44:05.529998-07:00"}
{"id":"bd-9","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.","status":"closed","priority":4,"issue_type":"chore","created_at":"2025-10-21T23:53:44.31362-07:00","updated_at":"2025-10-25T23:15:33.468661-07:00","closed_at":"2025-10-19T19:27:34.230312-07:00"}
{"id":"bd-90","title":"Make merge command idempotent for safe retry after partial failures","description":"The merge command currently performs 3 operations without an outer transaction:\n1. Migrate dependencies from source → target\n2. Update text references across all issues\n3. Close source issues\n\nIf merge fails mid-operation (network issue, daemon crash, etc.), a retry will fail or produce incorrect results because some operations already succeeded.\n\n**Goal:** Make merge idempotent so retrying after partial failure is safe and completes the remaining work.\n\n**Idempotency checks needed:**\n- Skip dependency migration if target already has the dependency\n- Skip text reference updates if already updated\n- Skip closing source issues if already closed\n- Report which operations were skipped vs performed\n\n**Example output:**\n```\n✓ Merged 2 issue(s) into bd-48\n - Dependencies: 3 migrated, 2 already existed\n - Text references: 5 updated, 0 already correct\n - Source issues: 1 closed, 1 already closed\n```\n\n**Related:** bd-1 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:\n- Dependency migration checks `alreadyExists` before adding (line ~145-151 in merge.go)\n- Text reference updates are naturally idempotent (replacing bd-X with bd-Y twice has same result)\n\nMissing idempotency:\n- CloseIssue fails if source already closed\n- Error messages don't distinguish \"already done\" from \"real failure\"\n\nImplementation:\n1. Check source issue status before closing - skip if already closed\n2. Track which operations succeeded/skipped\n3. Return detailed results for user visibility\n4. Consider adding --dry-run output showing what would be done vs skipped","status":"closed","priority":2,"issue_type":"feature","created_at":"2025-10-24T13:35:23.107034-07:00","updated_at":"2025-10-25T23:15:33.521286-07:00","closed_at":"2025-10-22T11:56:36.526276-07:00"}
{"id":"bd-91","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.\n\n**Reproduction**:\n1. Start daemon: `bd daemon`\n2. Run bd stats → shows N issues\n3. Delete database: `rm .beads/bd.db` \n4. Reinit and import: `bd init \u0026\u0026 bd import -i .beads/issues.jsonl`\n5. Run bd stats → shows 0 issues (wrong!)\n6. Direct query: `sqlite3 .beads/bd.db 'SELECT COUNT(*) FROM issues'` → shows correct count\n7. Restart daemon: `bd daemon --stop` then retry stats → now shows correct count\n\n**Root cause**: \n- server.go:1410-1414 retrieves cached storage without checking if DB file changed\n- Cache only evicts based on TTL (30min) or LRU, never on external modifications\n- Direct file operations bypass daemon, leaving cache stale\n\n**Impact**:\n- Users see incorrect/stale data after external DB operations\n- Confusing behavior with no clear indication cache is stale\n- Requires daemon restart to fix\n\n**Proposed fixes**:\n1. Check mtime on cache hit, invalidate if file changed\n2. Add cache eviction API (bd cache --clear)\n3. Use file locking to prevent external modifications while daemon running\n4. SQLite WAL mode change notifications","design":"**Better approach: Check DB file mtime on cache lookup**\n\nToo 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.\n\n**Implementation:**\n\n1. Add `dbMtime time.Time` field to `StorageCacheEntry`\n2. In `getStorageForRequest()` on cache hit:\n - Stat the DB file to get current mtime\n - If mtime changed since cached, evict entry and reopen\n - Otherwise return cached connection\n3. Store mtime when initially caching\n\n**Code location:**\n- `internal/rpc/server.go:1410-1414` (cache hit path)\n- `internal/rpc/server.go:49-52` (StorageCacheEntry struct)\n\n**Benefits:**\n- Simple, centralized check\n- Works for all commands that bypass daemon\n- Works for external tools modifying DB\n- No need to update every command\n- Minimal performance overhead (one stat() call on cache hit)\n\n**Trade-offs:**\n- Small overhead on every cache hit (negligible - stat is fast)\n- mtime granularity may miss rapid changes (unlikely in practice)","status":"closed","priority":1,"issue_type":"bug","created_at":"2025-10-24T13:35:23.108829-07:00","updated_at":"2025-10-25T23:15:33.506573-07:00","closed_at":"2025-10-21T21:51:22.331957-07:00"}
{"id":"bd-92","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.","notes":"After review, we already have good context tools: bd stats, bd list, bd ready, and the AGENTS.md onboarding section. Adding bd quickstart would be redundant and doesn't add enough value to justify maintenance cost. Closing as won't implement.","status":"closed","priority":2,"issue_type":"feature","created_at":"2025-10-24T13:35:23.109187-07:00","updated_at":"2025-10-25T23:15:33.506924-07:00","closed_at":"2025-10-22T21:30:29.491988-07:00"}
{"id":"bd-93","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-27 where global daemon won't open a DB).\n\nOptions:\n1. Warn and ignore the flags in global mode\n2. Error out with clear message\n\nLine 87-91 already checks autoPush, but should skip check entirely for global mode. Add user-friendly messaging about flag incompatibility.","status":"closed","priority":3,"issue_type":"feature","created_at":"2025-10-24T13:35:23.10938-07:00","updated_at":"2025-10-25T23:15:33.521501-07:00","closed_at":"2025-10-17T23:04:30.223432-07:00"}
{"id":"bd-94","title":"Convert repeated strings to constants (goconst)","description":"12 instances of repeated strings that should be constants: \"alice\", \"windows\", \"bd-2\", \"daemon\", \"import\", \"healthy\", \"unhealthy\", \"1.0.0\", \"custom-1\", \"custom-2\"","design":"Create package-level or test-level constants for frequently used test strings and command names.","status":"closed","priority":2,"issue_type":"task","created_at":"2025-10-24T13:35:23.109555-07:00","updated_at":"2025-10-25T23:15:33.521665-07:00","closed_at":"2025-10-25T18:02:26.966923-07:00"}
{"id":"bd-95","title":"Auto-flush writes test pollution and session work to git-tracked issues.jsonl","description":"Auto-flush exports ALL issues from DB to issues.jsonl every 5 seconds, including:\n- Test issues (bd-4053 through bd-4059 were version test junk)\n- Issues created during debugging sessions\n- Test pollution from stress tests\n- Temporary diagnostic issues\n\nThis pollutes the git-tracked issues.jsonl with garbage that shouldn't be committed.\n\nExample from today:\n- Git had 49 clean issues\n- Our DB grew to 100+ with test junk and session work\n- Auto-flush wrote all 100+ to issues.jsonl\n- Git status showed modified issues.jsonl with 50+ unwanted issues\n\nImpact:\n- Pollutes git history with test/debug garbage\n- Makes code review difficult (noise in diffs)\n- Can't distinguish real work from session artifacts\n- Other team members pull polluted issues\n\nSolutions to consider:\n1. Disable auto-flush by default (require explicit --enable-auto-flush)\n2. Add .beadsignore to exclude issue ID patterns\n3. Make auto-flush only export 'real' issues (exclude test-*)\n4. Require manual 'bd sync' for git commit\n5. Auto-flush to separate file (.beads/session.jsonl vs issues.jsonl)\n\nRelated: bd-8 (test pollution), isolation_test.go (test DB separation)","status":"closed","priority":1,"issue_type":"bug","created_at":"2025-10-24T13:35:23.109731-07:00","updated_at":"2025-10-25T23:15:33.52183-07:00","closed_at":"2025-10-22T01:05:59.459797-07:00"}
{"id":"bd-96","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:\n- Import from JSONL leaves counter at old high value\n- Test pollution increments counter but cleanup doesn't decrement it\n- Delete issues doesn't update counter\n- Only fix is 'rm -rf .beads' which is destructive\n\nExamples from today's session:\n- Had 48 issues but counter at 7714 after test pollution\n- Import from git didn't reset counter\n- Next new issue would be bd-7715 instead of bd-8\n\nProposed fixes:\n1. Auto-recalculate counter from max(issue_id) on import\n2. Add 'bd fix-counter' command\n3. Make counter lazy (always compute from DB, don't store)\n4. Import should reset counter to match imported data\n\nRelated:-254 (test isolation), bd-12 (init timestamp bug)","status":"closed","priority":1,"issue_type":"bug","created_at":"2025-10-24T13:35:23.109915-07:00","updated_at":"2025-10-25T23:15:33.522009-07:00","closed_at":"2025-10-21T23:13:04.249149-07:00"}
{"id":"bd-97","title":"Counter not synced after import on existing DB with populated issue_counters table","description":"The counter sync fix in counter_sync_test.go only syncs during initial migration when issue_counters table is empty (migrateIssueCountersTable checks count==0). For existing databases with stale counters:\n\n- Import doesn't resync the counter\n- Delete doesn't update counter \n- Renumber doesn't fix counter\n- Counter remains stuck at old high value\n\nExample from today:\n- Had 49 issues after clean import\n- Counter stuck at 4106 from previous test pollution\n- Next issue would be bd-4107 instead of bd-12\n- Even after renumber, counter stayed at 4106\n\nRoot cause: Migration only syncs if table is empty (line 182 in sqlite.go). Once populated, never resyncs.\n\nFix needed: \n1. Sync counter after import operations (not just empty table)\n2. Add counter resync after renumber\n3. Daemon caches counter value - needs to reload after external changes\n\nRelated: bd-8 (original counter sync fix), bd-9 (daemon cache staleness)","notes":"## Investigation Results\n\nAfter thorough code review, all the fixes mentioned in the issue description have ALREADY been implemented:\n\n### ✅ Fixes Already in Place:\n\n1. **Import DOES resync counters**\n - `cmd/bd/import_shared.go:253` calls `SyncAllCounters()` after batch import\n - Verified with new test `TestCounterSyncAfterImport`\n\n2. **Delete DOES update counters**\n - `internal/storage/sqlite/sqlite.go:1424` calls `SyncAllCounters()` after deletion\n - Both single delete and batch delete sync properly\n - Verified with existing tests: `TestCounterSyncAfterDelete`, `TestCounterSyncAfterBatchDelete`\n\n3. **Renumber DOES fix counters**\n - `cmd/bd/renumber.go:298-304` calls `ResetCounter()` then `SyncAllCounters()`\n - Forces counter to actual max ID (not just MAX with stale value)\n\n4. **Daemon cache DOES detect external changes**\n - `internal/rpc/server.go:1466-1487` checks file mtime and evicts stale cache\n - When DB file changes externally, cached storage is evicted and reopened\n\n### Tests Added:\n\n- `TestCounterSyncAfterImport`: Confirms import syncs counters from stale value (4106) to actual max (49)\n- `TestCounterNotSyncedWithoutExplicitSync`: Documents what would happen without the fix (bd-4107 instead of bd-12)\n\n### Conclusion:\n\nThe issue described in bd-12 has been **fully resolved**. All operations (import, delete, renumber) now properly sync counters. The daemon correctly detects external DB changes via file modification time.\n\nThe root cause (migration only syncing empty tables) was fixed by adding explicit `SyncAllCounters()` calls after import, delete, and renumber operations.","status":"closed","priority":1,"issue_type":"bug","created_at":"2025-10-24T13:35:23.110118-07:00","updated_at":"2025-10-25T23:15:33.522231-07:00","closed_at":"2025-10-22T00:03:46.697918-07:00"}
{"id":"bd-98","title":"Re-land TestDatabaseReinitialization after fixing Windows/Nix issues","description":"TestDatabaseReinitialization test was reverted due to CI failures:\n- Windows: JSON parse errors, missing files \n- Nix: git not available in build environment\n\nNeed to fix and re-land:\n1. Make test work on Windows (path separators, file handling)\n2. Skip test in Nix environment or mock git\n3. Fix JSON parsing issues","status":"closed","priority":1,"issue_type":"task","created_at":"2025-10-24T15:06:27.385396-07:00","updated_at":"2025-10-25T23:15:33.508271-07:00","closed_at":"2025-10-25T17:48:52.214323-07:00"}
{"id":"bd-99","title":"Feature: Use external_ref as primary matching key for import updates","description":"Implement external_ref-based matching for imports to enable hybrid workflows with external systems (Jira, GitHub, Linear).\n\n## Problem\nCurrent import collision detection treats any content change as a collision, preventing users from syncing updates from external systems without creating duplicates.\n\n## Solution\nUse external_ref field as primary matching key during imports. When an incoming issue has external_ref set:\n- Search for existing issue with same external_ref\n- If found, UPDATE (not collision)\n- If not found, create new issue\n- Never match local issues (without external_ref)\n\n## Use Cases\n- Jira integration: Import backlog, add local tasks, re-sync updates\n- GitHub integration: Import issues, track with local subtasks, sync status\n- Linear integration: Team coordination with local breakdown\n\n## Reference\nGitHub issue #142: https://github.com/steveyegge/beads/issues/142","status":"closed","priority":1,"issue_type":"epic","created_at":"2025-10-24T22:10:24.862547-07:00","updated_at":"2025-10-25T23:15:33.508456-07:00","closed_at":"2025-10-25T10:17:33.543504-07:00"}