Verify and test Claude Code plugin

Address remaining items from code review:

Critical:
1. Test plugin installation locally with /plugin marketplace add
2. Verify ${CLAUDE_PLUGIN_ROOT} variable works correctly
3. Test each slash command works
4. Test @task-agent execution
5. Verify MCP server connects properly

Documentation:
1. Clarify 'one-command installation' vs prerequisites
2. Add note about plugin development status
3. Verify all paths and examples work

Nice-to-have:
1. Add icon for marketplace (optional)
2. Add categories field to plugin.json
3. Add engines field for version compatibility

PLUGIN IMPLEMENTATION COMPLETE - READY FOR TESTING

What was built:
✅ .claude-plugin/plugin.json - Plugin metadata with MCP server config
✅ .claude-plugin/marketplace.json - Marketplace configuration
✅ 9 slash commands in .claude-plugin/commands/:
   - bd-ready, bd-create, bd-show, bd-update, bd-close
   - bd-workflow, bd-init, bd-stats, bd-version
✅ Task agent in .claude-plugin/agents/task-agent.md
✅ PLUGIN.md - Comprehensive documentation
✅ README.md - Updated with plugin section
✅ Version sync - All components at 0.9.2

Testing Instructions for Next Agent:
=====================================

1. INSTALL PLUGIN FROM GITHUB:
   /plugin marketplace add steveyegge/beads
   /plugin install beads

2. RESTART CLAUDE CODE (required for MCP server)

3. TEST SLASH COMMANDS:
   /bd-version        # Check versions (should show 0.9.2)
   /bd-workflow       # Show workflow guide
   /bd-stats          # Show project stats
   /bd-ready          # Find ready work
   /bd-create "Test plugin" task 2
   /bd-show bd-<id>

4. TEST MCP SERVER:
   /mcp               # Verify 'beads' server appears

5. TEST TASK AGENT:
   @task-agent        # If supported in Claude Code

6. VERIFY:
   - All commands work without errors
   - MCP tools are accessible
   - Version checking works
   - Documentation is accurate

Expected Issues:
- May need to adjust MCP server path variable (${CLAUDE_PLUGIN_ROOT})
- Task agent syntax might differ
- Some commands may need refinement based on actual usage

If testing fails, check:
- bd CLI is in PATH: which bd
- uv is installed: which uv
- MCP server logs in Claude Code
- PLUGIN.md troubleshooting section

Commit references:
- 9f38375: feat: Add Claude Code plugin for beads
- d25fc53: feat: Add version compatibility checking
- c0f1044: fix: Sync all component versions to 0.9.2
- a5c71f0: feat: Add version bump script
- a612b92: docs: Add version management to CLAUDE.md


Agent 5 Issue 51

Created by agent 5


Agent 5 Issue 52

Created by agent 5


Agent 5 Issue 53

Created by agent 5


Agent 5 Issue 54

Created by agent 5


Agent 5 Issue 55

Created by agent 5


Agent 5 Issue 56

Created by agent 5


Agent 5 Issue 57

Created by agent 5


Agent 5 Issue 58

Created by agent 5


Agent 5 Issue 59

Created by agent 5


Agent 5 Issue 60

Created by agent 5


Update ready_issues VIEW to use hierarchical blocking

The ready_issues VIEW (schema.go:97-108) uses the OLD blocking logic that doesn't propagate through parent-child hierarchies.

**Problem:**
- GetReadyWork() function now uses recursive CTE with propagation
- But the ready_issues VIEW still uses simple NOT EXISTS check
- Any code using the VIEW will get DIFFERENT results than GetReadyWork()
- This creates inconsistency and confusion

**Impact:**
- Unknown if the VIEW is actually used anywhere in the codebase
- If it is used, it's returning incorrect results (showing children as ready when parent is blocked)

**Solution:**
Either:
1. Update VIEW to match GetReadyWork logic (complex CTE in a view)
2. Drop the VIEW entirely if unused
3. Make VIEW call GetReadyWork as a function (if SQLite supports it)

**Investigation needed:**
Grep for 'ready_issues' to see if the view is actually used.

**Investigation results:**
Grepped the codebase - the ready_issues VIEW appears in:
- schema.go (definition)
- WORKFLOW.md, DESIGN.md (documentation)
- No actual Go code queries it directly

**Conclusion:** The VIEW is defined but appears UNUSED by actual code. GetReadyWork() function is used instead.

**Recommended solution:** Drop the VIEW entirely to avoid confusion. It serves no purpose if unused and creates a maintenance burden (needs to stay in sync with GetReadyWork logic).

**Alternative:** If we want to keep it for direct SQL access, update the VIEW definition to match the new recursive CTE logic.


Agent 5 Issue 61

Created by agent 5


Agent 5 Issue 62

Created by agent 5


Agent 5 Issue 63

Created by agent 5


Agent 5 Issue 64

Created by agent 5


Test database naming


Agent 5 Issue 65

Created by agent 5


Agent 5 Issue 66

Created by agent 5


Agent 5 Issue 67

Created by agent 5


Agent 5 Issue 68

Created by agent 5


Agent 5 Issue 69

Created by agent 5


Agent 5 Issue 70

Created by agent 5


Add composite index on dependencies(depends_on_id, type)

The hierarchical blocking query does:
JOIN dependencies d ON d.depends_on_id = bt.issue_id
WHERE d.type = 'parent-child'

Currently we only have idx_dependencies_depends_on (line 41 in schema.go), which covers depends_on_id but not the type filter.

**Impact:**
- Query has to scan ALL dependencies for a given depends_on_id, then filter by type
- With 10k+ issues and many dependencies, this could cause slowdowns
- The blocker propagation happens recursively, amplifying the cost

**Solution:**
Add composite index: CREATE INDEX idx_dependencies_depends_on_type ON dependencies(depends_on_id, type)

**Testing:**
Run EXPLAIN QUERY PLAN on GetReadyWork query before/after to verify index usage.


Agent 5 Issue 71

Created by agent 5


Agent 5 Issue 72

Created by agent 5


Agent 5 Issue 73

Created by agent 5


Agent 5 Issue 74

Created by agent 5


Agent 5 Issue 75

Created by agent 5


Agent 5 Issue 76

Created by agent 5


Agent 5 Issue 77

Created by agent 5


Agent 0 Issue 0

Created by agent 0


Agent 0 Issue 1

Created by agent 0


Agent 0 Issue 2

Created by agent 0


Parent's blocker should block children in ready work calculation

GitHub issue #19: If epic1 blocks epic2, children of epic2 should also be considered blocked when calculating ready work. Currently epic2's children show as ready even though their parent is blocked. This breaks the natural hierarchy of dependencies and can cause agents to work on tasks out of order.

Expected: ready work calculation should traverse up parent-child hierarchy and check if any ancestor has blocking dependencies.

See: https://github.com/anthropics/claude-code/issues/19


Agent 0 Issue 3

Created by agent 0


Agent 0 Issue 4

Created by agent 0


Agent 0 Issue 5

Created by agent 0


Agent 0 Issue 6

Created by agent 0


Agent 0 Issue 7

Created by agent 0


Agent 0 Issue 8

Created by agent 0


Agent 0 Issue 9

Created by agent 0


Agent 0 Issue 10

Created by agent 0


Agent 0 Issue 11

Created by agent 0


Agent 0 Issue 12

Created by agent 0


Add design/notes/acceptance_criteria fields to update command

Currently bd update only supports status, priority, title, assignee. Add support for --design, --notes, --acceptance-criteria flags. This makes it easier to add detailed designs to issues after creation.


Agent 0 Issue 13

Created by agent 0


Agent 0 Issue 14

Created by agent 0


Agent 0 Issue 15

Created by agent 0


Agent 0 Issue 16

Created by agent 0


Agent 0 Issue 17

Created by agent 0


Agent 0 Issue 18

Created by agent 0


Agent 0 Issue 19

Created by agent 0


Agent 0 Issue 20

Created by agent 0


Agent 0 Issue 21

Created by agent 0


Agent 0 Issue 22

Created by agent 0


Workaround for FastMCP outputSchema bug in Claude Code

The beads MCP server (v0.23.1) successfully connects to Claude Code, but all tools fail to load with a schema validation error due to a bug in FastMCP 2.13.1.

Error: "Invalid literal value, expected \"object\"" in outputSchema.

Root Cause: FastMCP generates outputSchema with $ref at root level without "type": "object" for self-referential models (Issue).

Workaround: Use slash commands (/beads:ready) or wait for FastMCP fix.


Fix failing integration tests in beads-mcp

The `beads-mcp` test suite has failures in `tests/test_bd_client_integration.py` (assertion error in `test_init_creates_beads_directory`) and errors in `tests/test_worktree_separate_dbs.py` (setup failures finding database). These need to be investigated and fixed to ensure a reliable CI baseline.


bd resolve-conflicts - Git merge conflict resolver

Automatically resolve JSONL merge conflicts.

Modes:
- Mechanical: ID remapping (no AI)
- AI-assisted: Smart merge/keep decisions
- Interactive: Review each conflict

Handles <<<<<<< conflict markers in .beads/beads.jsonl

Files: cmd/bd/resolve_conflicts.go (new)


Update docs with multi-repo patterns

Update AGENTS.md, README.md, QUICKSTART.md with multi-repo patterns. Document: config options, routing behavior, backward compatibility, troubleshooting, best practices.


Implement content-hash based collision resolution for deterministic convergence

The current collision resolution uses creation timestamps to decide which issue to keep vs. remap. This is non-deterministic when two clones create issues at nearly the same time.

Root cause of bd-71107098:
- Clone A creates test-1="Issue from clone A" at T0
- Clone B creates test-1="Issue from clone B" at T0+30ms
- Clone B syncs first, remaps Clone A's to test-2
- Clone A syncs second, sees collision, remaps Clone B's to test-2
- Result: titles are swapped between clones

Solution:
- Use content-based hashing (title + description + priority + type)
- Deterministic winner: always keep issue with lower hash
- Same collision on different clones produces same result (idempotent)

Implementation:
- Modify ScoreCollisions in internal/storage/sqlite/collision.go
- Replace timestamp-based scoring with content hash comparison
- Ensure hash function is stable across platforms

Rename detection successfully implemented and tested!

**What was implemented:**
1. Content-hash based rename detection in DetectCollisions
2. When importing JSONL, if an issue has different ID but same content as DB issue, treat as rename
3. Delete old ID and accept new ID from JSONL
4. Added post-import re-export in sync command to flush rename changes
5. Added post-import commit to capture rename changes

**Test results:**
TestTwoCloneCollision now shows full convergence:
- Clone A: test-2="Issue from clone A", test-1="Issue from clone B"
- Clone B: test-1="Issue from clone B", test-2="Issue from clone A"

Both clones have **identical content** (titles match IDs correctly). Only timestamps differ (expected).

**What remains:**
- Test still expects exact JSON match including timestamps
- Could normalize timestamp comparison, but content convergence is the critical success metric
- The two-clone collision workflow now works without data corruption!


bd delete fails to find closed issues

## Steps to Reproduce
1. Close some issues with `bd close`
2. Try to delete them with `bd delete <ids> --force`
3. Get error "issues not found"

## Expected Behavior
Should delete the closed issues

## Actual Behavior
```
Error: issues not found: bd-74ee, bd-9b13, bd-72w, bd-149, bd-5iv, bd-78w
```

But `bd list --status closed --json` shows they exist.

## Root Cause
Likely the delete command is only looking for open issues, or there's a race condition with auto-import.


Test graceful degradation when server unavailable

Verify that agents continue working normally when Agent Mail server is stopped or unreachable.

Acceptance Criteria:
- Agent detects server unavailable on startup
- Logs "falling back to Beads-only mode"
- All bd commands work normally
- Agent can claim issues (no reservations, like today)
- Git sync operates as normal
- No errors or crashes

Success Metric: Zero functional difference when Agent Mail unavailable


Add tests for internal/utils package

Currently 0.0% coverage. Need tests for utility functions including issue ID parsing and validation.


Investigate and upgrade to modernc.org/sqlite 1.39.1+

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

**Issue:** [deleted:bd-cb64c226.2], GH #144

**Symptom:** CloseIssue fails with "FOREIGN KEY constraint failed (787)" when called via MCP/daemon, but works fine via CLI.

**Root Cause:** Unknown - likely stricter FK enforcement in SQLite 3.50.4 or modernc.org wrapper changes.

**Workaround:** Pinned to v1.38.2 (SQLite 3.49.x)

**TODO:**
1. Monitor modernc.org/sqlite releases for fixes
2. Check SQLite 3.50.5+ changelogs for FK-related fixes
3. Investigate why daemon mode fails but CLI succeeds (connection reuse? transaction isolation?)
4. Consider filing upstream issue with reproducible test case
5. Upgrade when safe


Add test case for symmetric collision (both clones create same ID simultaneously)

TestTwoCloneCollision demonstrates the problem, but we need a simpler unit test for the collision resolver itself.

Test should verify:
- Two issues with same ID, different content
- Content hash determines winner deterministically
- Result is same regardless of which clone imports first
- No title swapping occurs

This can be a simpler test than the full integration test.


Widespread double JSON encoding bug in daemon mode RPC calls

Multiple CLI commands had the same double JSON encoding bug found in bd-1048. All commands that called ResolveID via RPC used string(resp.Data) instead of properly unmarshaling the JSON response. This caused IDs to retain JSON quotes ("bd-1048" instead of bd-1048), which then got double-encoded when passed to subsequent RPC calls.

Affected commands:
- bd show (3 instances)
- bd dep add/remove/tree (5 instances)
- bd label add/remove/list (3 instances)
- bd reopen (1 instance)

Root cause: resp.Data is json.RawMessage (already JSON-encoded), so string() conversion preserves quotes.

Fix: Replace all string(resp.Data) with json.Unmarshal(resp.Data, &id) for proper deserialization.

All commands now tested and working correctly with daemon mode.


Test auto-start in fred


Fix CI failures before 0.21.3 release

CI is failing on multiple jobs:
1. Nix flake: Tests fail due to missing git in build environment
2. Windows tests: Need to check what's failing
3. Linux tests: Need to check what's failing
4. Linter errors: Many unchecked errors need fixing

Need to fix before tagging v0.21.3 release.

Fixed linter errors (errcheck, misspell), Nix flake git dependency, and import database discovery bug. Tests still failing - need to investigate further.


Multi-repo contributor workflow support

Implement separate repository support for OSS contributors to prevent PR pollution while maintaining git ledger and multi-clone sync. Based on contributor-workflow-analysis.md Solution #4.

See docs/contributor-workflow-analysis.md for complete design rationale.

Key architecture:
- N ≥ 1 repos (single repo default, multi-repo opt-in)
- VCS-agnostic (git, jj, hg, sapling)
- Config-based routing (no schema changes)
- Smart caching (file mtime tracking, SQLite cache)
- Global namespace (hash-based IDs)
- Cross-repo dependencies supported

1. Zero PR pollution - contributor planning never reaches upstream
2. Git ledger preserved - all repos VCS-tracked
3. Backward compatible - existing single-repo workflows unchanged
4. Sub-second query performance with polling
5. Library API stable - transparent to downstream consumers like VC


bd-hv01: Multi-repo mode not tested with deletion tracking

Problem: Test suite has no coverage for multi-repo mode. ExportToMultiRepo creates multiple JSONL files but snapshot files are hardcoded to single JSONL location.

Impact: Deletion tracking likely silently broken for multi-repo users, could cause data loss.

Fix: Add test and update snapshot logic to handle multiple JSONL files.

Files: cmd/bd/deletion_tracking_test.go, cmd/bd/deletion_tracking.go, cmd/bd/daemon_sync.go:24-34


Test parent issue


Test child direct


Test child daemon mode


Clarify JSONL size bounds with multi-repo

The contributor-workflow-analysis.md states (line 226): 'Keep beads.jsonl small enough for agents to read (<25k)'

With multi-repo hydration, it's unclear whether this bound applies to:
- Each individual JSONL file (likely intention)
- The total hydrated size across all repos (unclear)
- Both (most conservative)

Clarification needed because:
- VC monitors .beads/issues.jsonl size to stay under limit
- With multi-repo, VC needs to know if each additional repo also has 25k limit
- Agents reading hydrated data need to know total size bounds
- Performance characteristics depend on total vs per-repo limits

Example scenario:
- Primary repo: 20k JSONL
- Planning repo: 15k JSONL
- Total hydrated: 35k
Is this acceptable or does it violate the <25k principle?

- Documentation explicitly states size bound applies per-repo or total
- Rationale explained (why that bound matters)
- Guidance for monitoring size with multi-repo
- If total bound exists, formula provided (e.g., sum of all repos <25k)


Make maxDepth configurable in bd dep tree command

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


Test plugin installation and functionality

Verify the plugin works end-to-end.

Test cases:
- Fresh installation via /plugin command
- All slash commands work correctly
- MCP server tools are accessible
- Configuration options work
- Documentation is accurate
- Works in both terminal and VS Code


Agent 0 Issue 23

Created by agent 0


Agent 0 Issue 24

Created by agent 0


Agent 0 Issue 25

Created by agent 0


Add comprehensive tests for sync branch daemon logic

The daemon sync branch functionality (bd-6545) was implemented but needs proper end-to-end testing.

Current implementation:
- daemon_sync_branch.go has syncBranchCommitAndPush() and syncBranchPull()
- daemon_sync.go has been updated to use these functions when sync.branch is configured
- All daemon tests pass, but no specific tests for sync branch behavior

Testing needed:
- Test that daemon commits to sync branch when sync.branch is configured
- Test that daemon commits to current branch when sync.branch is NOT configured (backward compatibility)
- Test that daemon pulls from sync branch and syncs JSONL back to main repo
- Test worktree creation and health checks during daemon operations
- Test error handling (missing branch, worktree corruption, etc.)

Key challenge: Tests need to run in the context of the git repo (getGitRoot() uses current working directory), so test setup needs to properly change directory or mock the git root detection.

Reference existing daemon tests in daemon_test.go and daemon_autoimport_test.go for patterns.


Agent 0 Issue 26

Created by agent 0


Agent 0 Issue 27

Created by agent 0


Agent 0 Issue 28

Created by agent 0


Agent 0 Issue 29

Created by agent 0


Agent 0 Issue 30

Created by agent 0


Agent 0 Issue 31

Created by agent 0


Agent 0 Issue 32

Created by agent 0


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

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


Agent 0 Issue 33

Created by agent 0


Agent 0 Issue 34

Created by agent 0


Agent 0 Issue 35

Created by agent 0


Agent 0 Issue 36

Created by agent 0


Agent 0 Issue 37

Created by agent 0


Agent 0 Issue 38

Created by agent 0


Agent 0 Issue 39

Created by agent 0


Agent 0 Issue 40

Created by agent 0


Agent 0 Issue 41

Created by agent 0


Agent 0 Issue 42

Created by agent 0


Feature P1


Write plugin documentation

Create comprehensive documentation for the plugin.

Contents:
- Installation instructions
- Available commands
- MCP tools reference
- Configuration options
- Examples and workflows
- Troubleshooting guide


Agent 0 Issue 43

Created by agent 0


Agent 0 Issue 44

Created by agent 0


Agent 0 Issue 45

Created by agent 0


Agent 0 Issue 46

Created by agent 0


Agent 0 Issue 47

Created by agent 0


Agent 0 Issue 48

Created by agent 0


Agent 0 Issue 49

Created by agent 0


Agent 0 Issue 50

Created by agent 0


Agent 0 Issue 51

Created by agent 0


Agent 0 Issue 52

Created by agent 0


Design and implement slash commands

Create useful slash commands for beads workflow.

Proposed commands:
- /bd-ready - Show ready work
- /bd-create - Create new issue interactively
- /bd-show - Show issue details
- /bd-update - Update issue status
- /bd-close - Close issue
- /bd-workflow - Show full agent workflow guide

Each command should provide a good UX and leverage the MCP server tools.


Agent 0 Issue 53

Created by agent 0


Agent 0 Issue 54

Created by agent 0


bd detect-pollution - Test pollution detector

Detect test issues that leaked into production DB.

Pattern matching for:
- Titles starting with 'test', 'benchmark', 'sample'
- Sequential numbering (test-1, test-2)
- Generic descriptions
- Created in rapid succession

Optional AI scoring for confidence.

Files: cmd/bd/detect_pollution.go (new)


Agent 0 Issue 55

Created by agent 0


Agent 0 Issue 56

Created by agent 0


Agent 0 Issue 57

Created by agent 0


Agent 0 Issue 58

Created by agent 0


Agent 0 Issue 59

Created by agent 0


Agent 0 Issue 60

Created by agent 0


Add external_ref change tracking and auditing

Currently we don't track when external_ref is added, removed, or changed. This would be useful for debugging and auditing.

Proposed features:
- Log event when external_ref changes
- Track in events table with old/new values
- Add query to find issues where external_ref changed
- Add metrics: issues with external_ref vs without

Use cases:
- Debugging import issues
- Understanding which issues are externally managed
- Auditing external system linkage

Related: bd-1022


Agent 0 Issue 61

Created by agent 0


Agent 0 Issue 62

Created by agent 0


Create plugin metadata files

Create .claude-plugin/plugin.json and marketplace.json.

Requirements:
- Name, description, version, author
- MCP server configuration bundling
- License and repository info
- Installation instructions


Agent 0 Issue 63

Created by agent 0


Agent 0 Issue 64

Created by agent 0


Agent 0 Issue 65

Created by agent 0


Agent 0 Issue 66

Created by agent 0


Agent 0 Issue 67

Created by agent 0


Agent 0 Issue 68

Created by agent 0


Agent 0 Issue 69

Created by agent 0


Agent 0 Issue 70

Created by agent 0


Agent 0 Issue 71

Created by agent 0


Agent 0 Issue 72

Created by agent 0


Research Claude Code plugin structure and requirements

Study the plugin format, required files, and best practices.

Tasks:
- Review official plugin documentation
- Examine example plugins if available
- Document plugin.json schema
- Understand marketplace.json requirements
- Identify slash command format


Agent 0 Issue 73

Created by agent 0


Agent 0 Issue 74

Created by agent 0


Agent 0 Issue 75

Created by agent 0


Agent 0 Issue 76

Created by agent 0


Agent 0 Issue 77

Created by agent 0


Agent 0 Issue 78

Created by agent 0


Agent 0 Issue 79

Created by agent 0


Agent 0 Issue 80

Created by agent 0


Agent 0 Issue 81

Created by agent 0


Agent 0 Issue 82

Created by agent 0


Fix TestListCommand duplicate dependency constraint violation


Create Claude Code plugin for beads

Package beads as a Claude Code plugin for easy installation via /plugin command.

Context: GitHub issue #28 - https://github.com/steveyegge/beads/issues/28

Current state:
- MCP server exists in integrations/beads-mcp/
- No plugin packaging yet

Deliverables:
1. .claude-plugin/plugin.json with metadata
2. .claude-plugin/marketplace.json for distribution
3. Custom slash commands (/bd-ready, /bd-create, /bd-show, etc.)
4. Bundle MCP server configuration
5. Optional: Pre-configured hooks for auto-sync
6. Documentation for installation and usage

Benefits:
- Makes beads instantly discoverable in Claude Code ecosystem
- Single-command installation vs. manual setup
- Bundled cohesive experience
- Lowers adoption barrier significantly

References:
- https://www.anthropic.com/news/claude-code-plugins
- https://docs.claude.com/en/docs/claude-code/plugins


Agent 0 Issue 83

Created by agent 0


Agent 0 Issue 84

Created by agent 0


Agent 0 Issue 85

Created by agent 0


Agent 0 Issue 86

Created by agent 0


Agent 0 Issue 87

Created by agent 0


Agent 0 Issue 88

Created by agent 0


Agent 0 Issue 89

Created by agent 0


Agent 0 Issue 90

Created by agent 0


Agent 0 Issue 91

Created by agent 0


Agent 0 Issue 92

Created by agent 0


Another explicit ID


Agent 0 Issue 93

Created by agent 0


Agent 0 Issue 94

Created by agent 0


Agent 0 Issue 95

Created by agent 0


Agent 0 Issue 96

Created by agent 0


Agent 0 Issue 97

Created by agent 0


Agent 0 Issue 98

Created by agent 0


Agent 0 Issue 99

Created by agent 0


Agent 5 Issue 78

Created by agent 5


Agent 5 Issue 79

Created by agent 5


Agent 5 Issue 80

Created by agent 5


Reach 1.0 release milestone

Stabilize API, finalize documentation, comprehensive testing


Agent 5 Issue 81

Created by agent 5


Agent 5 Issue 82

Created by agent 5


bd find-duplicates - AI-powered duplicate detection

Find semantically duplicate issues.

Approaches:
1. Mechanical: Exact title/description matching
2. Embeddings: Cosine similarity (cheap, scalable)
3. AI: LLM-based semantic comparison (expensive, accurate)

Uses embeddings by default for >100 issues.

Files: cmd/bd/find_duplicates.go (new)


Agent 5 Issue 83

Created by agent 5


Agent 5 Issue 84

Created by agent 5


Agent 5 Issue 85

Created by agent 5


Agent 5 Issue 86

Created by agent 5


Agent 5 Issue 87

Created by agent 5


Agent 5 Issue 88

Created by agent 5


Agent 5 Issue 89

Created by agent 5


Agent 5 Issue 90

Created by agent 5


Fix revive style issues (78 issues)

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

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

Fixed 19 revive issues:
- 14 unused-parameter (renamed to _)
- 2 redefines-builtin-id (max→maxCount, min→minInt)
- 3 indent-error-flow (gofmt fixed 2, skipped 1 complex nested one)

Remaining issues are acceptable: 11 unused-params in deeper code, 2 empty-blocks with comments, 1 complex indent case, 1 superfluous-else in test.


Fix transaction conflict in TryResurrectParent

Integration test TestImportWithDeletedParent fails with 'database is locked' error when resurrection happens inside CreateIssue.

Root cause: TryResurrectParent calls conn.Get() and insertIssue() which conflicts with existing transaction in CreateIssue.

Error: failed to create tombstone for parent bd-parent: failed to insert issue: sqlite3: database is locked

Solution: Refactor resurrection to accept optional transaction parameter, use existing transaction when available instead of creating new connection.

Impact: Blocks resurrection from working in CreateIssue flow, only works in EnsureIDs (which may not have active transaction).


Implement collision detection in import

Create collision.go with detectCollisions() function. Compare incoming JSONL issues against DB state. Distinguish between: (1) exact match (idempotent), (2) ID match but different content (collision), (3) new issue. Return list of colliding issues.


Agent 5 Issue 91

Created by agent 5


Agent 5 Issue 92

Created by agent 5


Agent 5 Issue 93

Created by agent 5


Agent 5 Issue 94

Created by agent 5


Agent 5 Issue 95

Created by agent 5


Agent 5 Issue 96

Created by agent 5


Agent 5 Issue 97

Created by agent 5


Agent 5 Issue 98

Created by agent 5


Agent 5 Issue 99

Created by agent 5


Agent 2 Issue 0

Created by agent 2


Test parent issue


Add TestNWayCollision for 5+ clones

## Overview
Add comprehensive tests for N-way (5+) collision resolution to verify the solution scales beyond 3 clones.

## Purpose
While TestThreeCloneCollision validates the basic N-way case, we need to verify:
1. Solution scales to arbitrary N
2. Performance is acceptable with more clones
3. Convergence time is bounded
4. No edge cases in larger collision groups

## Implementation Tasks

### 1. Create TestFiveCloneCollision
File: beads_twoclone_test.go (or new beads_nway_test.go)

```go
func TestFiveCloneCollision(t *testing.T) {
    // Test with 5 clones creating same ID with different content
    // Verify all 5 clones converge after sync rounds

    t.Run("SequentialSync", func(t *testing.T) {
        testNCloneCollision(t, 5, "A", "B", "C", "D", "E")
    })

    t.Run("ReverseSync", func(t *testing.T) {
        testNCloneCollision(t, 5, "E", "D", "C", "B", "A")
    })

    t.Run("RandomSync", func(t *testing.T) {
        testNCloneCollision(t, 5, "C", "A", "E", "B", "D")
    })
}
```

### 2. Implement generalized testNCloneCollision
Generalize the 3-clone test to handle arbitrary N:

```go
func testNCloneCollision(t *testing.T, numClones int, syncOrder ...string) {
    t.Helper()

    if len(syncOrder) != numClones {
        t.Fatalf("syncOrder length (%d) must match numClones (%d)",
            len(syncOrder), numClones)
    }

    tmpDir := t.TempDir()

    // Setup remote and N clones
    remoteDir := setupBareRepo(t, tmpDir)
    cloneDirs := make(map[string]string)

    for i := 0; i < numClones; i++ {
        name := string(rune('A' + i))
        cloneDirs[name] = setupClone(t, tmpDir, remoteDir, name)
    }

    // Each clone creates issue with same ID but different content
    for name, dir := range cloneDirs {
        createIssue(t, dir, fmt.Sprintf("Issue from clone %s", name))
    }

    // Sync in specified order
    for _, name := range syncOrder {
        syncClone(t, cloneDirs[name], name)
    }

    // Final pull for convergence
    for name, dir := range cloneDirs {
        finalPull(t, dir, name)
    }

    // Verify all clones have all N issues
    expectedTitles := make(map[string]bool)
    for i := 0; i < numClones; i++ {
        name := string(rune('A' + i))
        expectedTitles[fmt.Sprintf("Issue from clone %s", name)] = true
    }

    for name, dir := range cloneDirs {
        titles := getTitles(t, dir)
        if !compareTitleSets(titles, expectedTitles) {
            t.Errorf("Clone %s missing issues: expected %v, got %v",
                name, expectedTitles, titles)
        }
    }

    t.Log("✓ All", numClones, "clones converged successfully")
}
```

### 3. Add performance benchmarks
Test convergence time and memory usage:

```go
func BenchmarkNWayCollision(b *testing.B) {
    for _, n := range []int{3, 5, 10, 20} {
        b.Run(fmt.Sprintf("N=%d", n), func(b *testing.B) {
            for i := 0; i < b.N; i++ {
                // Run N-way collision and measure time
                testNCloneCollisionBench(b, n)
            }
        })
    }
}
```

### 4. Add convergence time tests
Verify bounded convergence:

```go
func TestConvergenceTime(t *testing.T) {
    // Test that convergence happens within expected rounds
    // For N clones, should converge in at most N-1 sync rounds

    for n := 3; n <= 10; n++ {
        t.Run(fmt.Sprintf("N=%d", n), func(t *testing.T) {
            rounds := measureConvergenceRounds(t, n)
            maxExpected := n - 1
            if rounds > maxExpected {
                t.Errorf("Convergence took %d rounds, expected ≤ %d",
                    rounds, maxExpected)
            }
        })
    }
}
```

### 5. Add edge case tests
Test boundary conditions:
- All N clones have identical content (dedup works)
- N-1 clones have same content, 1 differs
- All N clones have unique content
- Mix of collisions and non-collisions

## Acceptance Criteria
- TestFiveCloneCollision passes with all sync orders
- All 5 clones converge to identical content
- Performance is acceptable (< 5 seconds for 5 clones)
- Convergence time is bounded (≤ N-1 rounds)
- Edge cases handled correctly
- Benchmarks show scalability to 10+ clones

## Files to Create/Modify
- beads_twoclone_test.go or beads_nway_test.go
- Add helper functions for N-clone setup

## Testing Strategy

### Test Matrix
| N Clones | Sync Orders | Expected Result |
|----------|-------------|-----------------|
| 3        | A→B→C       | Pass            |
| 3        | C→B→A       | Pass            |
| 5        | A→B→C→D→E   | Pass            |
| 5        | E→D→C→B→A   | Pass            |
| 5        | Random      | Pass            |
| 10       | Sequential  | Pass            |

### Performance Targets
- 3 clones: < 2 seconds
- 5 clones: < 5 seconds
- 10 clones: < 15 seconds

## Dependencies
- Requires bd-cbed9619.5, bd-cbed9619.4, bd-cbed9619.3, bd-dcd6f14b to be completed
- TestThreeCloneCollision must pass first

## Success Metrics
- All tests pass for N ∈ {3, 5, 10}
- Convergence time scales linearly (O(N))
- Memory usage reasonable (< 100MB for 10 clones)
- No data corruption or loss in any scenario


Fix remaining FK constraint failures in AddComment and ApplyCompaction

Follow-up to PR #348 (Fix FOREIGN KEY constraint failed).

The initial fix addressed CloseIssue, UpdateIssueID, and RemoveLabel.
However, `AddComment` (in internal/storage/sqlite/events.go) and `ApplyCompaction` (in internal/storage/sqlite/compact.go) still suffer from the same pattern: inserting an event after an UPDATE without verifying the UPDATE affected any rows.

This causes "FOREIGN KEY constraint failed" errors when operating on non-existent issues, instead of clean "issue not found" errors.

Task:
1. Apply the same fix pattern to `AddComment` and `ApplyCompaction`: check RowsAffected() after UPDATE and before event INSERT.
2. Ensure error messages are consistent ("issue %s not found").
3. Verify with reproduction tests (create a test that calls these methods with a non-existent ID).


Batch test 5


Add tests for helper functions (GetDirtyIssueHash, GetAllDependencyRecords, export hashes)

Several utility functions have 0% coverage:
- GetDirtyIssueHash (dirty.go)
- GetAllDependencyRecords (dependencies.go)
- GetExportHash, SetExportHash, ClearAllExportHashes (hash.go)

These are lower priority but should have basic coverage.


Test all core bd commands in WASM for feature parity

Comprehensive testing of bd-wasm against native bd:
- Test all CRUD operations (create, update, show, close)
- Test dependency management (dep add, dep tree)
- Test sync operations (sync, import, export)
- Verify JSONL output matches native bd
- Run existing Go test suite in WASM if possible
- Benchmark performance (should be within 2x of native)


VCS-agnostic sync support

Make bd sync work with multiple VCS types (git, jujutsu, mercurial, sapling) by detecting VCS per repo and using appropriate sync commands, supporting mixed-VCS multi-repo configs.

Features:
- Detect VCS type per repo (.git, .jj, .hg, .sl)
- Sync adapters for each VCS type
- bd sync runs appropriate commands per repo
- Handle mixed-VCS configs (git + jj + hg)
- Fallback to manual sync if no VCS detected

Example:
bd sync auto-detects:
- . is git → git pull
- ~/.beads-planning is jj → jj git fetch && jj rebase
- ~/other is hg → hg pull && hg update

1. Detect VCS type per configured repo
2. bd sync works with git, jj, hg, sapling
3. Mixed-VCS configs supported
4. Graceful fallback if no VCS detected
5. Error messages guide user on manual sync
6. Pure git workflows unchanged


Document protected branch workflow

Create comprehensive documentation for protected branch workflow.

Tasks:
- Add "Protected Branch Workflow" section to AGENTS.md
- Create docs/PROTECTED_BRANCHES.md guide
- Update README.md quick start
- Add examples to examples/protected-branch/
- Update bd init --help documentation
- Add troubleshooting guide
- Add migration guide for existing users
- Record demo video (optional)

Estimated effort: 2-3 days

- Clear quick start (< 2 minutes to set up)
- Detailed guide covers all scenarios
- Examples work end-to-end
- Troubleshooting answers common questions
- Platform-agnostic (not GitHub-specific)

Completed protected branch workflow documentation. Created comprehensive guide (docs/PROTECTED_BRANCHES.md), updated AGENTS.md with workflow section, added feature to README.md, and created working example (examples/protected-branch/). All commands verified working (bd init --branch, bd sync --status, bd sync --merge, bd config get/set sync.branch).


Export deduplication breaks when JSONL and export_hashes table diverge

## Problem

The export deduplication feature (timestamp-only skipping) breaks when the JSONL file and export_hashes table get out of sync, causing exports to skip issues that aren't actually in the file.

## Symptoms

- `bd export` reports "Skipped 128 issue(s) with timestamp-only changes"
- JSONL file only has 38 lines but DB has 149 issues
- export_hashes table has 149 entries
- Auto-import doesn't trigger (hash matches despite missing data)
- Two repos on same commit show different issue counts

## Root Cause

shouldSkipExport() in autoflush.go compares current issue hash with stored export_hashes entry. If they match, it skips export assuming the issue is already in the JSONL.

This assumption fails when:
1. Git operations (pull, reset, checkout) change JSONL without clearing export_hashes
2. Manual JSONL edits or corruption
3. Import operations that modify DB but don't update export_hashes
4. Partial exports that update export_hashes but don't complete

## Impact

- **Critical data loss risk**: Issues appear to be tracked but aren't persisted to git
- Breaks multi-repo sync (root cause of today's debugging session)
- Auto-import fails to detect staleness (hash matches despite missing data)
- Silent data corruption (no error messages, just missing issues)

## Reproduction

1. Have DB with 149 issues, all in export_hashes table
2. Truncate JSONL to 38 lines (simulate git reset or corruption)
3. Run `bd export` - it skips 128 issues
4. JSONL still has only 38 lines but export thinks it succeeded

## Current Workaround

```bash
sqlite3 .beads/beads.db "DELETE FROM export_hashes"
bd export -o .beads/beads.jsonl
```

## Proposed Solutions

**Option 1: Verify JSONL integrity before skipping**
- Count lines in JSONL, compare with export_hashes count
- If mismatch, clear export_hashes and force full export
- Safe but adds I/O overhead

**Option 2: Hash-based JSONL validation**
- Store hash of entire JSONL file in metadata
- Before export, check if JSONL hash matches
- If mismatch, clear export_hashes
- More efficient, detects any JSONL corruption

**Option 3: Disable timestamp-only deduplication**
- Remove the feature entirely
- Always export all issues
- Simplest and safest, but creates larger git commits

**Option 4: Clear export_hashes on git operations**
- Add post-merge hook to clear export_hashes
- Clear on any import operation
- Defensive approach but may over-clear

## Recommended Fix

Combination of Options 2 + 4:
1. Store JSONL file hash in metadata after export
2. Check hash before export, clear export_hashes if mismatch
3. Clear export_hashes on import operations
4. Add `bd validate` check for JSONL/export_hashes sync

## Files Involved

- cmd/bd/autoflush.go (shouldSkipExport)
- cmd/bd/export.go (export with deduplication)
- internal/storage/sqlite/metadata.go (export_hashes table)

## Recovery Session (2025-10-29 21:30)

### What Happened
- Created 14 new hash ID issues (bd-f8b764c9 through bd-f8b764c9.1)
- bd sync appeared to succeed
- Canonical repo (~/src/beads): 162 issues in DB + JSONL ✓
- Secondary repo (fred/beads): Only 145 issues vs 162 in canonical ✗
- Both repos on same git commit but different issue counts!

### Bug Manifestation During Recovery

1. **Initial state**: fred/beads had 145 issues, 145 lines in JSONL, 145 export_hashes entries

2. **After git reset --hard origin/main**:
   - JSONL: 162 lines (from git)
   - DB: 150 issues (auto-import partially worked)
   - Auto-import failed with UNIQUE constraint error

3. **After manual import --resolve-collisions**:
   - DB: 160 issues
   - JSONL: Still 162 lines
   - export_hashes: 159 entries

4. **After bd export**:
   - **JSONL reduced to 17 lines!** ← The bug in action
   - export_hashes: 159 entries (skipped exporting 142 issues)
   - Silent data loss - no error message

5. **After clearing export_hashes and re-export**:
   - JSONL: 159 lines (missing 3 issues still)
   - DB: 159 issues
   - Still diverged from canonical

### The Bug Loop
Once export_hashes and JSONL diverge:
- Export skips issues already in export_hashes
- But those issues aren't actually in JSONL
- This creates corrupt JSONL with missing issues
- Auto-import can't detect the problem (file hash matches what was exported)
- Data is lost with no error messages

### Recovery Solution
Couldn't break the loop with export alone. Had to:
1. Copy .beads/beads.db from canonical repo
2. Clear export_hashes
3. Full re-export
4. Finally converged to 162 issues

### Key Learnings

1. **The bug is worse than we thought**: It can create corrupt exports (17 lines instead of 162!)

2. **Auto-import can't save you**: Once export is corrupt, auto-import just imports the corrupt data

3. **Silent failure**: No warnings, no errors, just missing issues

4. **Git operations trigger it**: git reset, git pull, etc. change JSONL without clearing export_hashes

5. **Import operations populate export_hashes**: Even manual imports update export_hashes, setting up future export failures

### Immediate Action Required

**DISABLE EXPORT DEDUPLICATION NOW**

This feature is fundamentally broken and causes data loss. Should be disabled until properly fixed.

Quick fix options:
- Set environment variable to disable feature
- Comment out shouldSkipExport check
- Always clear export_hashes before export
- Add validation that DB count == JSONL line count before allowing export

### Long-term Fix

Need Option 2 + 4 from proposed solutions:
1. Store JSONL file hash after every successful export
2. Before export, verify JSONL hash matches expected
3. If mismatch, log WARNING and clear export_hashes
4. Clear export_hashes on every import operation
5. Add git post-merge hook to clear export_hashes
6. Add `bd validate` command to detect divergence


Issue with desc

This is a description


Refactor daemon.go into internal/daemonrunner

Extract daemon runtime from daemon.go (1,565 lines) into internal/daemonrunner with focused modules: config.go, daemon.go, process.go, rpc_server.go, sync.go, git.go. Keep cobra command thin.

New structure:
- internal/daemonrunner/config.go: Config struct
- internal/daemonrunner/daemon.go: Daemon struct + Start/Stop
- internal/daemonrunner/process.go: PID/lock/socket handling
- internal/daemonrunner/rpc_server.go: RPC lifecycle
- internal/daemonrunner/sync.go: Export/import/commit/push logic
- internal/daemonrunner/git.go: Git operations interface
- cmd/bd/daemon.go: Thin cobra command


Implement bd resolve-conflicts (git merge conflicts in JSONL)

Automatically detect and resolve git merge conflicts in .beads/issues.jsonl file.

Features:
- Detect conflict markers in JSONL
- Parse conflicting issues from HEAD and BASE
- Provide mechanical resolution (remap duplicate IDs)
- Support AI-assisted resolution (requires internal/ai package)

See repair_commands.md lines 125-353 for design.


Latency test 1


Test Epic

## Overview

[Describe the high-level goal and scope of this epic]

## Success Criteria

- [ ] Criteria 1
- [ ] Criteria 2
- [ ] Criteria 3

## Background

[Provide context and motivation]

## Scope

**In Scope:**
- Item 1
- Item 2

**Out of Scope:**
- Item 1
- Item 2

## Architecture

[Describe the overall architecture and approach]

## Components

- Component 1: [description]
- Component 2: [description]

## Dependencies

[List external dependencies or constraints]

- [ ] All child issues are completed
- [ ] Integration tests pass
- [ ] Documentation is updated
- [ ] Code review completed


Add integration tests for adapter library

Test suite for beads_mail_adapter.py covering all scenarios.

Acceptance Criteria:
- Test enabled mode (server available)
- Test disabled mode (server unavailable)
- Test graceful degradation (server dies mid-operation)
- Test reservation conflicts
- Test message sending/receiving
- Mock HTTP server for testing
- 90%+ code coverage

File: lib/test_beads_mail_adapter.py

Test suite completed with 29 comprehensive tests covering:
- Enabled mode (server available): 10 tests
- Disabled mode (server unavailable): 2 tests
- Graceful degradation: 4 tests
- Reservation conflicts: 2 tests
- Configuration: 5 tests
- Health check scenarios: 3 tests
- HTTP error handling: 3 tests

**Performance**: All tests run in 10ms (fast!)

**Coverage highlights**:
✅ Server health checks (ok, degraded, error, timeout)
✅ All API operations (reserve, release, notify, check_inbox, get_reservations)
✅ HTTP errors (404, 409 conflict, 500, 503)
✅ Network errors (timeout, connection refused)
✅ Malformed responses (bad JSON, empty body, plain text errors)
✅ Environment variable configuration
✅ Graceful degradation when server dies mid-operation
✅ Conflict handling with both JSON and plain text errors
✅ Dict wrapper responses ({"messages": [...]} and {"reservations": [...]})
✅ Custom TTL for reservations
✅ Default agent name fallback

No external dependencies, no slow integration tests, just fast unit tests with mocks.


Issue to reopen with reason


SearchIssues N+1 query causes context timeout with GetLabels

scanIssues() calls GetLabels in a loop for every issue, causing N+1 queries and context deadline exceeded errors when used with short timeouts or in-memory databases. This is especially problematic since SearchIssues already supports label filtering via SQL WHERE clauses.

- Optimize scanIssues to batch-load labels for all issues in one query
- Or make label loading optional/lazy
- Add test that calls SearchIssues repeatedly with label filters and short context timeouts


Optimize GetReadyWork performance - 752ms on 10K database (target: <50ms)

# Performance Analysis (10K Issue Database)

Analyzed using CPU profiles from benchmark suite on Apple M2 Pro.

## Operation Performance

| Operation                        | Time    | Allocations | Memory |
|----------------------------------|---------|-------------|--------|
| bd ready (GetReadyWork)          | ~752ms  | 167,466     | 16MB   |
| bd list (SearchIssues no filter) | ~11.6ms | 89,214      | 5.8MB  |
| bd list (SearchIssues filtered)  | ~9.2ms  | 62,365      | 3.5MB  |
| bd create (CreateIssue)          | ~2.6ms  | 146         | 8.6KB  |
| bd update (UpdateIssue)          | ~0.32ms | 364         | 15KB   |
| bd close (UpdateIssue)           | ~0.32ms | 364         | 15KB   |

**Target: <50ms for all operations on 10K database**

**Current issue: GetReadyWork is 15x over target (752ms vs 50ms)**

## Root Cause

GetReadyWork (internal/storage/sqlite/ready.go:90-128) uses recursive CTE to propagate blocking:
- 65x slower than SearchIssues
- Recalculates entire blocked issue tree on every call
- Algorithm:
  1. Find directly blocked issues via 'blocks' dependencies
  2. Recursively propagate blockage to descendants (max depth: 50)
  3. Exclude all blocked issues from results

## CPU Profile Analysis

- Database syscalls (pthread_cond_signal, syscall6): ~75%
- SQLite engine overhead: inherent to recursive CTE
- Application code (query construction): <1%

**Bottleneck is the recursive CTE query execution, not application code.**

## Optimization Recommendations

### High Impact (Likely to achieve <50ms target)

1. **Cache blocked issue calculation**
   - Add `blocked_issues` table updated on dependency changes
   - Trade write complexity for read speed (ready called >> dependency changes)
   - Eliminates recursive CTE on every read

2. **Add/verify database indexes**
   ```sql
   CREATE INDEX IF NOT EXISTS idx_dependencies_blocked
     ON dependencies(issue_id, type, depends_on_id);
   CREATE INDEX IF NOT EXISTS idx_issues_status
     ON issues(status);
   ```

### Medium Impact

3. **Reduce allocations** (167K allocations for GetReadyWork)
   - Profile `scanIssues()` for object pooling opportunities
   - Reuse slice capacity for repeated calls

### Low Impact (Not recommended)
- Query optimization for CRUD operations (already <3ms)
- Connection pooling tuning (not showing in profiles)

## Verification

Run benchmarks to validate optimization:
```bash
make bench-quick
go tool pprof -http=:8080 internal/storage/sqlite/bench-cpu-*.prof
```

Profile files automatically generated in `internal/storage/sqlite/`.


Add --show-all-paths flag to bd dep tree

Currently bd dep tree deduplicates nodes when multiple paths exist (diamond dependencies). Add optional --show-all-paths flag to display the full graph with all paths, showing duplicates. Useful for debugging complex dependency structures and understanding all relationships.


Implement reference scoring algorithm

Count references for each colliding issue: text mentions in descriptions/notes/design fields + dependency references. Sort collisions by score ascending (fewest refs first). This minimizes total updates during renumbering.


Agent 2 Issue 1

Created by agent 2


Agent 2 Issue 2

Created by agent 2


Agent 2 Issue 3

Created by agent 2


Agent 2 Issue 4

Created by agent 2


Agent 2 Issue 5

Created by agent 2


bd doctor --json flag not working

The --json flag on bd doctor command doesn't produce JSON output. It continues to show human-readable output instead. The flag is registered locally on doctorCmd but the code uses the global jsonOutput variable set by PersistentPreRun. Need to investigate why the flag isn't being honored.

Fixed by removing the local --json flag definition in doctor.go that was shadowing the persistent --json flag from main.go. The doctor command now correctly uses the global jsonOutput variable.


Agent 2 Issue 6

Created by agent 2


Agent 2 Issue 7

Created by agent 2


Agent 2 Issue 8

Created by agent 2


Agent 2 Issue 9

Created by agent 2


Agent 2 Issue 10

Created by agent 2


Implement ID remapping with reference updates

Allocate new IDs for colliding issues. Update all text field references using word-boundary regex (\bbd-10\b). Update dependency records. Build id_mapping for reporting. Handle chain dependencies properly.


Agent 2 Issue 11

Created by agent 2


Agent 2 Issue 12

Created by agent 2


Agent 2 Issue 13

Created by agent 2


Agent 2 Issue 14

Created by agent 2


Agent 2 Issue 15

Created by agent 2


Agent 2 Issue 16

Created by agent 2


Agent 2 Issue 17

Created by agent 2


Agent 2 Issue 18

Created by agent 2


Agent 2 Issue 19

Created by agent 2


Agent 2 Issue 20

Created by agent 2


Add --resolve-collisions flag and user reporting

Add import flags: --resolve-collisions (auto-fix) and --dry-run (preview). Display clear report: collisions detected, remappings applied (old→new with scores), reference counts updated. Default behavior: fail on collision (safe).


Agent 2 Issue 21

Created by agent 2


Agent 2 Issue 22

Created by agent 2


Split internal/rpc/server.go into focused modules

The file `internal/rpc/server.go` is 2,273 lines with 50+ methods, making it difficult to navigate and prone to merge conflicts. Split into 8 focused files with clear responsibilities.

Current structure: Single 2,273-line file with:
- Connection handling
- Request routing
- All 40+ RPC method implementations
- Storage caching
- Health checks & metrics
- Cleanup loops

Target structure:
```
internal/rpc/
├── server.go          # Core server, connection handling (~300 lines)
├── methods_issue.go   # Issue operations (~400 lines)
├── methods_deps.go    # Dependency operations (~200 lines)
├── methods_labels.go  # Label operations (~150 lines)
├── methods_ready.go   # Ready work queries (~150 lines)
├── methods_compact.go # Compaction operations (~200 lines)
├── methods_comments.go # Comment operations (~150 lines)
├── storage_cache.go   # Storage caching logic (~300 lines)
└── health.go          # Health & metrics (~200 lines)
```

Migration strategy:
1. Create new files with appropriate methods
2. Keep `server.go` as main file with core server logic
3. Test incrementally after each file split
4. Final verification with full test suite

- All 50 methods split into appropriate files
- Each file <500 LOC
- All methods remain on `*Server` receiver (no behavior change)
- All tests pass: `go test ./internal/rpc/...`
- Verify daemon works: start daemon, run operations, check health
- Update internal documentation if needed
- No change to public API


Agent 2 Issue 23

Created by agent 2


Optimize cmd/bd test suite performance (currently 30+ minutes)

CLI test suite is extremely slow (~30+ minutes for full run). Tests are poorly designed and need performance optimization before expanding coverage.

Current coverage: 24.8% (improved from 20.2%)

**Problem**: Tests take far too long to run, making development iteration painful.

**Priority**: Fix test performance FIRST, then consider increasing coverage.

**Investigation needed**:
- Profile test execution to identify bottlenecks
- Look for redundant git operations, database initialization, or daemon operations
- Identify opportunities for test parallelization
- Consider mocking or using in-memory databases where appropriate
- Review test design patterns

**Related**: bd-ktng mentions 13 CLI tests with redundant git init calls (31s total)

**Goal**: Get full test suite under 1-2 minutes before adding more tests.


Agent 2 Issue 24

Created by agent 2


Agent 2 Issue 25

Created by agent 2


Agent 2 Issue 26

Created by agent 2


Agent 2 Issue 27

Created by agent 2


Agent 2 Issue 28

Created by agent 2


AI-supervised database migrations for safer schema evolution

## Problem

Database migrations can lose user data through edge cases that are hard to anticipate (e.g., GH #201 where bd migrate failed to set issue_prefix, or bd-d355a07d false positive data loss warnings). Since beads is designed to be run by AI agents, we should leverage AI to make migrations safer.

## Current State

Migrations run blindly with:
- No pre-flight validation
- No data integrity verification
- No rollback on failure
- Limited post-migration testing

Recent issues:
- GH #201: Migration didn't set issue_prefix config, breaking commands
- bd-d355a07d: False positive "data loss" warnings on collision resolution
- Users reported migration data loss (fixed but broader problem remains)

## Proposal: AI-Supervised Migration Framework

Use AI to supervise migrations through structured verification:

### 1. Pre-Migration Analysis
- AI reads migration code and current schema
- Identifies potential data loss scenarios
- Generates validation queries to verify assumptions
- Creates snapshot queries for before/after comparison

### 2. Migration Execution
- Take database backup/snapshot
- Run validation queries (pre-state)
- Execute migration in transaction
- Run validation queries (post-state)

### 3. Post-Migration Verification
- AI compares pre/post snapshots
- Verifies data integrity invariants
- Checks for unexpected data loss
- Validates config completeness (like issue_prefix)

### 4. Rollback on Anomalies
- If AI detects data loss, rollback transaction
- Present human-readable error report
- Suggest fix before retrying

## Example Flow

```
$ bd migrate

→ Analyzing migration plan...
→ AI identified 3 potential data loss scenarios
→ Generating validation queries...
→ Creating pre-migration snapshot...
→ Running migration in transaction...
→ Verifying post-migration state...
✓ All 247 issues accounted for
✓ Config table complete (issue_prefix: "mcp")
✓ Dependencies intact (342 relationships verified)
→ Migration successful!
```

If something goes wrong:
```
$ bd migrate

→ Analyzing migration plan...
→ AI identified issue: Missing issue_prefix config after migration
→ Recommendation: Add prefix detection step
→ Aborting migration - database unchanged
```

## Implementation Ideas

### A. Migration Validator Tool
Create `bd migrate --validate` that:
- Simulates migration on copy of database
- Uses AI to verify data integrity
- Reports potential issues before real migration

### B. Migration Test Generator
AI generates test cases for migrations:
- Edge cases (empty DB, large DB, missing config)
- Data integrity checks
- Regression tests

### C. Migration Invariants
Define invariants that AI checks:
- Issue count should not decrease (unless collision resolution)
- All required config keys present
- Foreign key relationships intact
- No orphaned dependencies

### D. Self-Healing Migrations
AI detects incomplete migrations and suggests fixes:
- Missing config values (like GH #201)
- Orphaned data
- Index inconsistencies

## Benefits

1. **Catch edge cases**: AI explores scenarios humans miss
2. **Self-documenting**: AI explains what migration does
3. **Agent-friendly**: Agents can run migrations confidently
4. **Fewer rollbacks**: Detect issues before committing
5. **Better testing**: AI generates comprehensive test suites

## Open Questions

1. Which AI model? (Fast: Haiku, Thorough: Sonnet/GPT-4)
2. How to balance safety vs migration speed?
3. Should AI validation be required or optional?
4. How to handle offline scenarios (no API access)?
5. What invariants should always be checked?

## Related Work

- bd-b245: Migration registry (makes migrations introspectable)
- GH #201: issue_prefix migration bug (motivating example)
- bd-d355a07d: False positive data loss warnings

## Architecture: Agent-Supervised Migrations (Inversion of Control)

**Key principle:** Beads provides observability and validation primitives. AI agents supervise using their own reasoning. Beads NEVER makes AI API calls.

## Phase 1: Migration Invariants (Pure Validation)

Create `internal/storage/sqlite/migration_invariants.go`:

```go
type MigrationInvariant struct {
    Name        string
    Description string
    Check       func(*sql.DB, *Snapshot) error
}

type Snapshot struct {
    IssueCount      int
    ConfigKeys      []string
    DependencyCount int
    LabelCount      int
}

var invariants = []MigrationInvariant{
    {
        Name: "required_config_present",
        Description: "Required config keys must exist",
        Check: checkRequiredConfig, // Would have caught GH #201
    },
    {
        Name: "foreign_keys_valid",
        Description: "No orphaned dependencies or labels",
        Check: checkForeignKeys,
    },
    {
        Name: "issue_count_stable",
        Description: "Issue count should not decrease unexpectedly",
        Check: checkIssueCount,
    },
}

func checkRequiredConfig(db *sql.DB, snapshot *Snapshot) error {
    required := []string{"issue_prefix", "schema_version"}
    for _, key := range required {
        var value string
        err := db.QueryRow("SELECT value FROM config WHERE key = ?", key).Scan(&value)
        if err != nil || value == "" {
            return fmt.Errorf("required config key missing: %s", key)
        }
    }
    return nil
}
```

## Phase 2: Dry-Run & Inspection Tools

Add `bd migrate --dry-run --json`:

```json
{
  "pending_migrations": [
    {"name": "dirty_issues_table", "description": "Adds dirty_issues table"},
    {"name": "content_hash_column", "description": "Adds content_hash for collision resolution"}
  ],
  "current_state": {
    "schema_version": "0.9.9",
    "issue_count": 247,
    "config": {"schema_version": "0.9.9"},
    "missing_config": ["issue_prefix"]
  },
  "warnings": [
    "issue_prefix config not set - may break commands after migration"
  ],
  "invariants_to_check": [
    "required_config_present",
    "foreign_keys_valid",
    "issue_count_stable"
  ]
}
```

Add `bd info --schema --json`:

```json
{
  "tables": ["issues", "dependencies", "labels", "config"],
  "schema_version": "0.9.9",
  "config": {},
  "sample_issue_ids": ["mcp-1", "mcp-2"],
  "detected_prefix": "mcp"
}
```

## Phase 3: Pre/Post Snapshots with Rollback

Update `RunMigrations()`:

```go
func RunMigrations(db *sql.DB) error {
    // Capture pre-migration snapshot
    snapshot := captureSnapshot(db)

    // Run migrations in transaction
    tx, err := db.Begin()
    if err != nil {
        return err
    }
    defer tx.Rollback()

    for _, migration := range migrations {
        if err := migration.Func(tx); err != nil {
            return fmt.Errorf("migration %s failed: %w", migration.Name, err)
        }
    }

    // Verify invariants before commit
    if err := verifyInvariants(tx, snapshot); err != nil {
        return fmt.Errorf("post-migration validation failed (rolled back): %w", err)
    }

    return tx.Commit()
}
```

## Phase 4: MCP Tools for Agent Supervision

Add to beads-mcp:

```python
@server.tool()
async def inspect_migration(workspace_root: str) -> dict:
    """Get migration plan and current state for agent analysis.

    Agent should:
    1. Review pending migrations
    2. Check for warnings (missing config, etc.)
    3. Verify invariants will pass
    4. Decide whether to run bd migrate
    """
    result = run_bd(["migrate", "--dry-run", "--json"], workspace_root)
    return json.loads(result.stdout)

@server.tool()
async def get_schema_info(workspace_root: str) -> dict:
    """Get current database schema for migration analysis."""
    result = run_bd(["info", "--schema", "--json"], workspace_root)
    return json.loads(result.stdout)
```

## Agent Workflow Example

```python
# Agent detects user wants to migrate
migration_plan = inspect_migration("/path/to/workspace")

# Agent analyzes (using its own reasoning, no API calls from beads)
if "issue_prefix" in migration_plan["missing_config"]:
    schema = get_schema_info("/path/to/workspace")
    detected_prefix = schema["detected_prefix"]

    # Agent fixes issue before migration
    run_bd(["config", "set", "issue_prefix", detected_prefix])

# Now safe to migrate
run_bd(["migrate"])
```

## What Beads Provides

✅ Deterministic validation (invariants)
✅ Structured inspection (--dry-run, --explain)
✅ Rollback on invariant failure
✅ JSON output for agent parsing

## What Beads Does NOT Do

❌ No AI API calls
❌ No external model access
❌ No agent invocation

Agents supervise migrations using their own reasoning and the inspection tools beads provides.

Phase 1: Migration invariants implemented and tested, checked after every migration, clear error messages when invariants fail.

Phase 2: Snapshot capture before migrations, comparison after, rollback on verification failure.

Phase 3 (stretch): AI validation optional flag implemented, AI can analyze migration code and generate custom validation queries.

Phase 4 (stretch): Migration test fixtures created, all fixtures pass migrations, CI runs migration tests.

## Progress

### ✅ Phase 1: Migration Invariants (COMPLETED)

**Implemented:**
- Created internal/storage/sqlite/migration_invariants.go with 3 invariants
- Updated RunMigrations() to verify invariants after migrations
- All tests pass ✓

### ✅ Phase 2: Inspection Tools (COMPLETED & PUSHED)

**Commit:** 1abe4e7 - "Add migration inspection tools for AI agents (bd-627d Phase 2)"

**Implemented:**
1. ✅ bd migrate --inspect --json - Shows migration plan
2. ✅ bd info --schema --json - Returns schema details
3. ✅ Migration warnings system
4. ✅ Documentation updated in AGENTS.md
5. ✅ All tests pass

### ✅ Phase 3: MCP Tools (COMPLETED & PUSHED)

**Commit:** 2493693 - "Add MCP tools for migration inspection (bd-627d Phase 3)"

**Implemented:**
1. ✅ inspect_migration(workspace_root) tool in beads-mcp
2. ✅ get_schema_info(workspace_root) tool in beads-mcp
3. ✅ Abstract methods in BdClientBase
4. ✅ CLI client implementations
5. ✅ All tests pass

**All phases complete!** Migration inspection fully integrated into MCP server.


Agent 2 Issue 29

Created by agent 2


Agent 2 Issue 30

Created by agent 2


Create WASM build infrastructure (Makefile, scripts)

Set up build tooling for WASM compilation:
- Add GOOS=js GOARCH=wasm build target
- Copy wasm_exec.js from Go distribution
- Create wrapper script for Node.js execution
- Add build task to Makefile or build script


Write comprehensive collision resolution tests

Test cases: simple collision, multiple collisions, dependency updates, text reference updates, chain dependencies, edge cases (partial ID matches, case sensitivity, triple merges). Add to import_test.go and collision_test.go.


Agent 2 Issue 31

Created by agent 2


Agent 2 Issue 32

Created by agent 2


Agent 2 Issue 33

Created by agent 2


Agent 2 Issue 34

Created by agent 2


Agent 2 Issue 35

Created by agent 2


Agent 2 Issue 36

Created by agent 2


Agent 2 Issue 37

Created by agent 2


Agent 2 Issue 38

Created by agent 2


Agent 2 Issue 39

Created by agent 2


Agent 2 Issue 40

Created by agent 2


Fix Nix flake build test failures

Nix build is failing during test phase with same test errors as Windows.

**Error:**
```
error: Cannot build '/nix/store/rgyi1j44dm6ylrzlg2h3z97axmfq9hzr-beads-0.9.9.drv'.
Reason: builder failed with exit code 1.
FAIL github.com/steveyegge/beads/cmd/bd 16.141s
```

This may be related to test environment setup or the same issues affecting Windows tests.


Update documentation for collision resolution

Update README.md with collision resolution section. Update CLAUDE.md with new workflow. Document --resolve-collisions and --dry-run flags. Add example scenarios showing branch merge workflows.


Agent 2 Issue 41

Created by agent 2


Agent 2 Issue 42

Created by agent 2


Agent 2 Issue 43

Created by agent 2


Agent 2 Issue 44

Created by agent 2


Agent 2 Issue 45

Created by agent 2


Agent 2 Issue 46

Created by agent 2


Agent 2 Issue 47

Created by agent 2


Agent 2 Issue 48

Created by agent 2


Agent 2 Issue 49

Created by agent 2


Agent 2 Issue 50

Created by agent 2


Multi-clone collision resolution testing and documentation

Epic to track improvements to multi-clone collision resolution based on ultrathinking analysis of-3d844c58 and [deleted:bd-71107098].

Current state:
- 2-clone collision resolution is SOUND and working correctly
- Hash-based deterministic collision resolution works
- Test fails due to timestamp comparison, not actual logic issues

Work needed:
1. Fix TestTwoCloneCollision to compare content not timestamps
2. Add TestThreeCloneCollision for regression protection
3. Document 3-clone ID non-determinism as known behavior


Fix TestTwoCloneCollision to compare content not timestamps

The test at beads_twoclone_test.go:204-207 currently compares full JSON output including timestamps, causing false negative failures.

Current behavior:
- Both clones converge to identical semantic content
- Clone A: test-2="Issue from clone A", test-1="Issue from clone B"
- Clone B: test-1="Issue from clone B", test-2="Issue from clone A"
- Titles match IDs correctly, no data corruption
- Only timestamps differ (expected and acceptable)

Fix needed:
- Replace exact JSON comparison with content-aware comparison
- Normalize or ignore timestamp fields when asserting convergence
- Test should PASS after this fix

This blocks completion of bd-71107098.

- Test compares issue content (title, description, status, priority) not timestamps
- TestTwoCloneCollision passes
- Both clones shown to have identical semantic content
- Timestamps explicitly documented as acceptable difference


Document 3-clone ID non-determinism in collision resolution

Document the known behavior of 3+ way collision resolution where ID assignments may vary based on sync order, even though content always converges correctly.

Updates needed:
- Update bd-71107098 notes to mark 2-clone case as solved
- Document 3-clone ID non-determinism as known limitation
- Add explanation to ADVANCED.md or collision resolution docs
- Explain why this happens (pairwise hash comparison is deterministic, but multi-way ID allocation uses sync-order dependent counters)
- Clarify trade-offs: content convergence ✅ vs ID stability ❌

Key points to document:
- Hash-based resolution is pairwise deterministic
- Content always converges correctly (all issues present with correct data)
- Numeric ID assignments in 3+ way collisions depend on sync order
- This is acceptable for most use cases (content convergence is primary goal)
- Full determinism would require complex multi-way comparison

- bd-71107098 updated with notes about 2-clone solution being complete
- 3-clone ID non-determinism documented in ADVANCED.md or similar
- Explanation includes why it happens and trade-offs
- Links to TestThreeCloneCollision as demonstration
- Users understand this is expected behavior, not a bug


Add TestThreeCloneCollision for regression protection

Add a 3-clone collision test to document behavior and provide regression protection.

Purpose:
- Verify content convergence regardless of sync order
- Document the ID non-determinism behavior (IDs may be assigned differently based on sync order)
- Provide regression protection for multi-way collisions

Test design:
- 3 clones create same ID with different content
- Test two different sync orders (A→B→C vs C→A→B)
- Assert content sets match (ignore specific ID assignments)
- Add comment explaining ID non-determinism is expected behavior

Known limitation:
- Content always converges correctly (all issues present with correct titles)
- Numeric ID assignments (test-2 vs test-3) depend on sync order
- This is acceptable if content convergence is the primary goal

- TestThreeCloneCollision added to beads_twoclone_test.go (or new file)
- Tests 3 clones with same ID collision
- Tests two different sync orders
- Asserts content convergence (all issues present, correct titles)
- Documents ID non-determinism in test comments
- Test passes consistently


Assigned issue


bd should auto-detect .beads/*.db in current directory

When bd is run without --db flag, it defaults to beads' own database instead of looking for a .beads/*.db file in the current working directory. This causes confusion when working on other projects that use beads for issue tracking (like vc).

Expected behavior: bd should search for .beads/*.db in cwd and use that if found, before falling back to default beads database.

Example: Running 'bd ready' in /Users/stevey/src/vc/vc/ should automatically find and use .beads/vc.db without requiring --db flag every time.


Agent 2 Issue 51

Created by agent 2


Agent 2 Issue 52

Created by agent 2


Agent 2 Issue 53

Created by agent 2


Agent 2 Issue 54

Created by agent 2


Agent 2 Issue 55

Created by agent 2


Update daemon commit logic for separate branch

Modify daemon to use worktree for commits when sync.branch configured.

Tasks:
- Update internal/daemon/server_export_import_auto.go
- Detect sync.branch configuration
- Ensure worktree exists before commit
- Sync JSONL to worktree
- Commit in worktree context
- Push to configured branch
- Fallback to current behavior if sync.branch not set
- Handle git errors (network, permissions, conflicts)

Estimated effort: 3-4 days

- When sync.branch configured, commits go to separate branch
- When sync.branch not configured, commits to current branch (backward compatible)
- No disruption to primary worktree
- Git errors handled gracefully with retry
- Daemon logs show which branch was used


Agent 2 Issue 56

Created by agent 2


Agent 2 Issue 57

Created by agent 2


Agent 2 Issue 58

Created by agent 2


Agent 2 Issue 59

Created by agent 2


Agent 2 Issue 60

Created by agent 2


Document or automate JSONL sync workflow for git collaboration

When using beads across multiple machines/environments via git, there's a workflow gap:

1. Machine A: Create issues → stored in .beads/project.db
2. Machine A: bd export -o .beads/issues.jsonl
3. Machine A: git add .beads/issues.jsonl && git commit && git push
4. Machine B: git pull
5. Machine B: ??? issues.jsonl exists but project.db is empty/stale

The missing step is: bd import --db .beads/project.db -i .beads/issues.jsonl

This needs to be either:
a) Documented clearly in workflow docs
b) Automated (e.g., git hook, or bd auto-imports if jsonl is newer than db)
c) Both

Real-world impact: User had Claude Code on GCP VM create vc issues from BOOTSTRAP.md. They were exported to issues.jsonl and committed. But on local machine, vc.db was empty until manual import was run.


Agent 2 Issue 61

Created by agent 2


Agent 2 Issue 62

Created by agent 2


Agent 2 Issue 63

Created by agent 2


Agent 2 Issue 64

Created by agent 2


Agent 2 Issue 65

Created by agent 2


Agent 2 Issue 66

Created by agent 2


Agent 2 Issue 67

Created by agent 2


Agent 2 Issue 68

Created by agent 2


Agent 2 Issue 69

Created by agent 2


Agent 2 Issue 70

Created by agent 2


Root issue for dep tree test


Agent 2 Issue 71

Created by agent 2


Agent 2 Issue 72

Created by agent 2


Agent 2 Issue 73

Created by agent 2


Agent 2 Issue 74

Created by agent 2


Agent 2 Issue 75

Created by agent 2


Agent 4 Issue 0

Created by agent 4


Agent 4 Issue 1

Created by agent 4


Agent 4 Issue 2

Created by agent 4


Agent 4 Issue 3

Created by agent 4


Agent 4 Issue 4

Created by agent 4


Dependency A


Agent 4 Issue 5

Created by agent 4


Agent 4 Issue 6

Created by agent 4


Agent 4 Issue 7

Created by agent 4


Agent 4 Issue 8

Created by agent 4


Agent 4 Issue 9

Created by agent 4


Agent 4 Issue 10

Created by agent 4


Agent 4 Issue 11

Created by agent 4


Agent 4 Issue 12

Created by agent 4


Agent 4 Issue 13

Created by agent 4


Agent 4 Issue 14

Created by agent 4


Dependency B


Agent 4 Issue 15

Created by agent 4


Agent 4 Issue 16

Created by agent 4


Agent 4 Issue 17

Created by agent 4


Agent 4 Issue 18

Created by agent 4


Agent 4 Issue 19

Created by agent 4


Agent 4 Issue 20

Created by agent 4


Agent 4 Issue 21

Created by agent 4


Agent 4 Issue 22

Created by agent 4


Agent 4 Issue 23

Created by agent 4


Agent 4 Issue 24

Created by agent 4


Platform tests: Linux, macOS, Windows

Test event-driven mode on all platforms. Verify inotify (Linux), FSEvents (macOS), ReadDirectoryChangesW (Windows). Test fallback behavior on each.


Implement "bd daemons logs" subcommand

Add command to view daemon logs for a specific workspace. Requires daemon logging to file (may need separate issue for log infrastructure).


Create cmd/bd/daemon_event_loop.go (~200 LOC)

Implement runEventDrivenLoop to replace polling ticker. Coordinate FileWatcher, mutation events, debouncer. Include health check ticker (60s) for daemon validation.


Rapid 1


bd info shows 'auto_start_disabled' even when daemon is crashed/missing


Fix MCP tools failing to load in Claude Code (GH#346)

Fix FastMCP schema generation bug by refactoring `Issue` model to avoid recursion.

    - Refactored `Issue` in `models.py` to use `LinkedIssue` for dependencies/dependents.
    - Restored missing `Mail*` models to `models.py`.
    - Fixed `tests/test_mail.py` mock assertion.

    Fixes GH#346.


CRDT-based architecture for guaranteed convergence (v2.0)

## Vision
Redesign beads around Conflict-Free Replicated Data Types (CRDTs) to provide mathematical guarantees for N-way collision resolution at arbitrary scale.

## Current Limitations
- Content-hash based collision resolution fails at 5+ clones
- Non-deterministic convergence in multi-round scenarios
- UNIQUE constraint violations during rename operations
- No formal proof of convergence properties

## CRDT Benefits
- Provably convergent (Strong Eventual Consistency)
- Commutative/Associative/Idempotent operations
- No coordination required between clones
- Scales to 100+ concurrent workers
- Well-understood mathematical foundations

## Proposed Architecture

### 1. UUID-Based IDs
Replace sequential IDs with UUIDs:
- Current: bd-1c63eb84, bd-9063acda, bd-4d80b7b1
- CRDT: bd-a1b2c3d4-e5f6-7890-abcd-ef1234567890
- Human aliases maintained separately: #42 maps to UUID

### 2. Last-Write-Wins (LWW) Elements
Each field becomes an LWW register:
- title: (timestamp, clone_id, value)
- status: (timestamp, clone_id, value)
- Deterministic conflict resolution via Lamport timestamp + clone_id tiebreaker

### 3. Operation Log
Track all operations as CRDT ops:
- CREATE(uuid, timestamp, clone_id, fields)
- UPDATE(uuid, field, timestamp, clone_id, value)
- DELETE(uuid, timestamp, clone_id) - tombstone, not hard delete

### 4. Sync as Merge
Syncing becomes merging two CRDT states:
- No merge conflicts possible
- Deterministic merge function
- Guaranteed convergence

## Implementation Phases

### Phase 1: Research & Design (4 weeks)
- Study existing CRDT implementations (Automerge, Yjs, Loro)
- Design schema for CRDT-based issue tracking
- Prototype LWW-based Issue CRDT
- Benchmark performance vs current system

### Phase 2: Parallel Implementation (6 weeks)
- Implement CRDT storage layer alongside SQLite
- Build conversion tools: SQLite ↔ CRDT
- Maintain backward compatibility with v1.x format
- Migration path for existing databases

### Phase 3: Testing & Validation (4 weeks)
- Formal verification of convergence properties
- Stress testing with 100+ clone scenario
- Performance profiling and optimization
- Documentation and examples

### Phase 4: Migration & Rollout (4 weeks)
- Release v2.0-beta with CRDT backend
- Gradual migration from v1.x
- Monitoring and bug fixes
- Final v2.0 release

## Risks & Mitigations

**Risk 1: Performance overhead**
- Mitigation: Benchmark early, optimize hot paths
- CRDTs can be slower than append-only logs
- May need compaction strategy

**Risk 2: Storage bloat**
- Mitigation: Implement operation log compaction
- Tombstone garbage collection for deleted issues
- Periodic snapshots to reduce log size

**Risk 3: Breaking changes**
- Mitigation: Maintain v1.x compatibility layer
- Gradual migration tools
- Dual-mode operation during transition

**Risk 4: Complexity**
- Mitigation: Use battle-tested CRDT libraries
- Comprehensive documentation
- Clear migration guide

## Success Criteria
- 100-clone collision test passes without failures
- Formal proof of convergence properties
- Performance within 2x of current system
- Zero manual conflict resolution required
- Backward compatible with v1.x databases

## Timeline
18-20 weeks total (4-5 months)

## References
- Automerge: https://automerge.org
- Yjs: https://docs.yjs.dev
- Loro: https://loro.dev
- CRDT theory: Shapiro et al, A comprehensive study of CRDTs
- Related issues: bd-e6d71828, bd-7a2b58fc, bd-81abb639


Fixture Generator for Realistic Test Data

Create internal/testutil/fixtures/fixtures.go with functions to generate realistic test data at scale.

Functions:
- LargeSQLite(storage) - 10K issues, native SQLite
- XLargeSQLite(storage) - 20K issues, native SQLite
- LargeFromJSONL(storage) - 10K issues imported from JSONL
- XLargeFromJSONL(storage) - 20K issues imported from JSONL

Data characteristics:
- Epic hierarchies (depth 4): Epic → Feature → Task → Subtask
- Cross-linked dependencies (tasks blocking across epics)
- Realistic status/priority/label distribution
- Representative assignees and temporal data

Implementation:
- Single file: internal/testutil/fixtures/fixtures.go
- No config structs, simple direct functions
- Seeded RNG for reproducibility
- Reusable by both benchmarks and tests


Remove unreachable utility functions

Several small utility functions are unreachable:

Files to clean:
1. `internal/storage/sqlite/hash.go` - `computeIssueContentHash` (line 17)
   - Check if entire file can be deleted if only contains this function

2. `internal/config/config.go` - `FileUsed` (line 151)
   - Delete unused config helper

3. `cmd/bd/git_sync_test.go` - `verifyIssueOpen` (line 300)
   - Delete dead test helper

4. `internal/compact/haiku.go` - `HaikuClient.SummarizeTier2` (line 81)
   - Tier 2 summarization not implemented
   - Options: implement feature OR delete method

Impact: Removes 50-100 LOC depending on decisions

- Remove unreachable functions
- If entire files can be deleted (like hash.go), delete them
- For SummarizeTier2: decide to implement or delete, document decision
- All tests pass: `go test ./...`
- Verify no callers exist for each function


Test exclusive file reservations with two agents

Simulate two agents racing to claim the same issue and verify that exclusive reservations prevent collision.

Acceptance Criteria:
- Agent A reserves bd-123 → succeeds
- Agent B tries to reserve bd-123 → fails with clear error message
- Agent B can see who has the reservation
- Reservation expires after TTL
- Agent B can claim after expiration

Successfully tested file reservations:
- Agent BrownBear reserved bd-123 → granted
- Agent ChartreuseHill tried same → conflicts returned
- System correctly prevents collision


Fix TestMigrateHashIDs test failure

Test failure in cmd/bd/migrate_hash_ids_test.go:100 - New ID bd-09970281 for bd-1 is not a hash ID. This test is validating the hash ID migration but the generated ID doesn't match the expected format.


Split test suites: fast vs. integration

Reorganize tests into separate packages/files for fast unit tests vs slow integration tests.

Benefits:
- Clear separation of concerns
- Easier to run just fast tests during development
- Can parallelize CI jobs better

Files to organize:
- beads_hash_multiclone_test.go (slow integration tests)
- beads_integration_test.go (medium-speed integration tests)
- Other test files (fast unit tests)


Issue to close


Message System Improvements

Consolidate improvements to the bd message command including core functionality (message reading), reliability (timeouts), validation, and code quality refactoring


Auto-detect scenarios and prompt users

Detect when user is in fork/contributor scenario and prompt with helpful suggestions. Check: git remote relationships, existing .beads config, repo ownership. Suggest appropriate wizard.


Refactor parseMarkdownFile to reduce cyclomatic complexity

The parseMarkdownFile function in cmd/bd/markdown.go has a cyclomatic complexity of 38, which exceeds the recommended threshold of 30. This makes the function harder to understand, test, and maintain.

Split the function into smaller, focused units:

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

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

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


Shared dependency C


Agent 4 Issue 25

Created by agent 4


Agent 4 Issue 26

Created by agent 4


Agent 4 Issue 27

Created by agent 4


Agent 4 Issue 28

Created by agent 4


Agent 4 Issue 29

Created by agent 4


Export deduplication breaks when JSONL and export_hashes table diverge

## Problem

The export deduplication feature (timestamp-only skipping) breaks when the JSONL file and export_hashes table get out of sync, causing exports to skip issues that aren't actually in the file.

## Symptoms

- `bd export` reports "Skipped 128 issue(s) with timestamp-only changes"
- JSONL file only has 38 lines but DB has 149 issues
- export_hashes table has 149 entries
- Auto-import doesn't trigger (hash matches despite missing data)
- Two repos on same commit show different issue counts

## Root Cause

shouldSkipExport() in autoflush.go compares current issue hash with stored export_hashes entry. If they match, it skips export assuming the issue is already in the JSONL.

This assumption fails when:
1. Git operations (pull, reset, checkout) change JSONL without clearing export_hashes
2. Manual JSONL edits or corruption
3. Import operations that modify DB but don't update export_hashes
4. Partial exports that update export_hashes but don't complete

## Impact

- **Critical data loss risk**: Issues appear to be tracked but aren't persisted to git
- Breaks multi-repo sync (root cause of today's debugging session)
- Auto-import fails to detect staleness (hash matches despite missing data)
- Silent data corruption (no error messages, just missing issues)

## Reproduction

1. Have DB with 149 issues, all in export_hashes table
2. Truncate JSONL to 38 lines (simulate git reset or corruption)
3. Run `bd export` - it skips 128 issues
4. JSONL still has only 38 lines but export thinks it succeeded

## Current Workaround

```bash
sqlite3 .beads/beads.db "DELETE FROM export_hashes"
bd export -o .beads/beads.jsonl
```

## Proposed Solutions

**Option 1: Verify JSONL integrity before skipping**
- Count lines in JSONL, compare with export_hashes count
- If mismatch, clear export_hashes and force full export
- Safe but adds I/O overhead

**Option 2: Hash-based JSONL validation**
- Store hash of entire JSONL file in metadata
- Before export, check if JSONL hash matches
- If mismatch, clear export_hashes
- More efficient, detects any JSONL corruption

**Option 3: Disable timestamp-only deduplication**
- Remove the feature entirely
- Always export all issues
- Simplest and safest, but creates larger git commits

**Option 4: Clear export_hashes on git operations**
- Add post-merge hook to clear export_hashes
- Clear on any import operation
- Defensive approach but may over-clear

## Recommended Fix

Combination of Options 2 + 4:
1. Store JSONL file hash in metadata after export
2. Check hash before export, clear export_hashes if mismatch
3. Clear export_hashes on import operations
4. Add `bd validate` check for JSONL/export_hashes sync

## Files Involved

- cmd/bd/autoflush.go (shouldSkipExport)
- cmd/bd/export.go (export with deduplication)
- internal/storage/sqlite/metadata.go (export_hashes table)


Agent 4 Issue 30

Created by agent 4


Agent 4 Issue 31

Created by agent 4


Agent 4 Issue 32

Created by agent 4


Agent 4 Issue 33

Created by agent 4


Agent 4 Issue 34

Created by agent 4


Implement reserved database name _.db

Auto-detection now skips .beads/_.db to prevent pollution when beads dogfoods itself. This allows beads to use its own issue tracker without interfering with other projects using beads in the same directory tree. Implementation includes filtering in findDatabase(), stopping directory walk when .beads/ is found, and documentation in README.md and CLAUDE.md.


Agent 4 Issue 35

Created by agent 4


## Vision
Redesign beads around Conflict-Free Replicated Data Types (CRDTs) to provide mathematical guarantees for N-way collision resolution at arbitrary scale.

## Current Limitations
- Content-hash based collision resolution fails at 5+ clones
- Non-deterministic convergence in multi-round scenarios
- UNIQUE constraint violations during rename operations
- No formal proof of convergence properties

## CRDT Benefits
- Provably convergent (Strong Eventual Consistency)
- Commutative/Associative/Idempotent operations
- No coordination required between clones
- Scales to 100+ concurrent workers
- Well-understood mathematical foundations

## Proposed Architecture

### 1. UUID-Based IDs
Replace sequential IDs with UUIDs:
- Current: bd-1c63eb84, bd-9063acda, bd-4d80b7b1
- CRDT: bd-a1b2c3d4-e5f6-7890-abcd-ef1234567890
- Human aliases maintained separately: #42 maps to UUID

### 2. Last-Write-Wins (LWW) Elements
Each field becomes an LWW register:
- title: (timestamp, clone_id, value)
- status: (timestamp, clone_id, value)
- Deterministic conflict resolution via Lamport timestamp + clone_id tiebreaker

### 3. Operation Log
Track all operations as CRDT ops:
- CREATE(uuid, timestamp, clone_id, fields)
- UPDATE(uuid, field, timestamp, clone_id, value)
- DELETE(uuid, timestamp, clone_id) - tombstone, not hard delete

### 4. Sync as Merge
Syncing becomes merging two CRDT states:
- No merge conflicts possible
- Deterministic merge function
- Guaranteed convergence

## Implementation Phases

### Phase 1: Research & Design (4 weeks)
- Study existing CRDT implementations (Automerge, Yjs, Loro)
- Design schema for CRDT-based issue tracking
- Prototype LWW-based Issue CRDT
- Benchmark performance vs current system

### Phase 2: Parallel Implementation (6 weeks)
- Implement CRDT storage layer alongside SQLite
- Build conversion tools: SQLite ↔ CRDT
- Maintain backward compatibility with v1.x format
- Migration path for existing databases

### Phase 3: Testing & Validation (4 weeks)
- Formal verification of convergence properties
- Stress testing with 100+ clone scenario
- Performance profiling and optimization
- Documentation and examples

### Phase 4: Migration & Rollout (4 weeks)
- Release v2.0-beta with CRDT backend
- Gradual migration from v1.x
- Monitoring and bug fixes
- Final v2.0 release

## Risks & Mitigations

**Risk 1: Performance overhead**
- Mitigation: Benchmark early, optimize hot paths
- CRDTs can be slower than append-only logs
- May need compaction strategy

**Risk 2: Storage bloat**
- Mitigation: Implement operation log compaction
- Tombstone garbage collection for deleted issues
- Periodic snapshots to reduce log size

**Risk 3: Breaking changes**
- Mitigation: Maintain v1.x compatibility layer
- Gradual migration tools
- Dual-mode operation during transition

**Risk 4: Complexity**
- Mitigation: Use battle-tested CRDT libraries
- Comprehensive documentation
- Clear migration guide

## Success Criteria
- 100-clone collision test passes without failures
- Formal proof of convergence properties
- Performance within 2x of current system
- Zero manual conflict resolution required
- Backward compatible with v1.x databases

## Timeline
18-20 weeks total (4-5 months)

## References
- Automerge: https://automerge.org
- Yjs: https://docs.yjs.dev
- Loro: https://loro.dev
- CRDT theory: Shapiro et al, A comprehensive study of CRDTs
- Related issues: bd-e6d71828, bd-7a2b58fc,-1


Agent 4 Issue 36

Created by agent 4


Make two-clone workflow actually work (no hacks)

TestTwoCloneCollision proves beads CANNOT handle two independent clones filing issues simultaneously. This is the basic collaborative workflow and it must work cleanly.

Test location: beads_twoclone_test.go

The test creates two git clones, both file issues with same ID (test-1), --resolve-collisions remaps clone B's to test-2, but after sync:
- Clone A has test-1="Issue from clone A", test-2="Issue from clone B"
- Clone B has test-1="Issue from clone B", test-2="Issue from clone A"

The TITLES are swapped! Both clones have 2 issues but with opposite title assignments.

We've tried many fixes (per-project daemons, auto-sync, lamport hashing, precommit hooks) but nothing has made the test pass.

Goal: Make the test pass WITHOUT hacks. The two clones should converge to identical state after sync.

1. TestTwoCloneCollision passes without EXPECTED FAILURE
2. Both clones converge to identical issue database
3. No manual conflict resolution required
4. Git status clean in both clones
5. bd ready output identical in both clones

**Major progress achieved!** The two-clone workflow now converges correctly.

**What was fixed:**
--3d844c58: Implemented content-hash based rename detection
- bd-64c05d00.1: Fixed test to compare content not timestamps
- Both clones now converge to identical issue databases
- test-1 and test-2 have correct titles in both clones
- No more title swapping!

**Current status (VERIFIED):**
✅ Acceptance criteria 1: TestTwoCloneCollision passes (confirmed Oct 28)
✅ Acceptance criteria 2: Both clones converge to identical issue database (content matches)
✅ Acceptance criteria 3: No manual conflict resolution required (automatic)
✅ Acceptance criteria 4: Git status clean
✅ Acceptance criteria 5: bd ready output identical (timestamps are expected difference)

**ALL ACCEPTANCE CRITERIA MET!** This issue is complete and can be closed.


Agent 4 Issue 37

Created by agent 4


Agent 4 Issue 38

Created by agent 4


Agent 4 Issue 39

Created by agent 4


Agent 4 Issue 40

Created by agent 4


Agent 4 Issue 41

Created by agent 4


Agent 4 Issue 42

Created by agent 4


Agent 4 Issue 43

Created by agent 4


Agent 4 Issue 44

Created by agent 4


Fix bd --version and bd completion to work without database


Epic test


Agent 4 Issue 45

Created by agent 4


Agent 4 Issue 46

Created by agent 4


Agent 4 Issue 47

Created by agent 4


Agent 4 Issue 48

Created by agent 4


Agent 4 Issue 49

Created by agent 4


Agent 4 Issue 50

Created by agent 4


Agent 4 Issue 51

Created by agent 4


Agent 4 Issue 52

Created by agent 4


Agent 4 Issue 53

Created by agent 4


Agent 4 Issue 54

Created by agent 4


Q4 Platform Improvements

## Overview

[Describe the high-level goal and scope of this epic]

## Success Criteria

- [ ] Criteria 1
- [ ] Criteria 2
- [ ] Criteria 3

## Background

[Provide context and motivation]

## Scope

**In Scope:**
- Item 1
- Item 2

**Out of Scope:**
- Item 1
- Item 2


Add test for deep hierarchy blocking (50+ levels)

Current tests verify 2-level depth (grandparent → parent → child). The depth limit is hardcoded to 50 in the recursive CTE, but we don't test edge cases near that limit.

**Test cases needed:**
1. Verify 50-level deep hierarchy works correctly
2. Verify depth limit prevents runaway recursion
3. Measure performance impact of deep hierarchies
4. Consider if 50 is the right limit (why not 100? why not 20?)

**Rationale:**
- Most hierarchies are 2-5 levels deep
- But pathological cases (malicious or accidental) could create 50+ level nesting
- Need to ensure graceful degradation, not catastrophic failure

**Implementation:**
Add TestDeepHierarchyBlocking to ready_test.go


Agent 4 Issue 55

Created by agent 4


Agent 4 Issue 56

Created by agent 4


Add validation for duplicate external_ref in batch imports

Currently, if a batch import contains multiple issues with the same external_ref, the behavior is undefined. We should detect and handle this case.

Current behavior:
- No validation for duplicate external_ref within a batch
- Last-write-wins or non-deterministic behavior

Proposed solution:
- Detect duplicate external_ref values in incoming batch
- Fail with clear error message OR
- Merge duplicates intelligently (use newest timestamp)
- Add test case for this scenario

Related: bd-1022


Agent 4 Issue 57

Created by agent 4


Add is_tombstone flag to schema

Optionally add is_tombstone boolean field to issues table. Marks resurrected parents that were deleted. Allows distinguishing tombstones from normal deleted issues. Update schema.go and create migration.


Agent 4 Issue 58

Created by agent 4


Agent 4 Issue 59

Created by agent 4


Agent 4 Issue 60

Created by agent 4


Agent 4 Issue 61

Created by agent 4


Refactor path canonicalization into helper function

The path canonicalization logic (filepath.Abs + EvalSymlinks) is duplicated in 3 places:
- beads.go:131-137 (BEADS_DIR handling)
- cmd/bd/main.go:446-451 (--no-db cleanup)
- cmd/bd/nodb.go:26-31 (--no-db initialization)

Refactoring suggestion:
Extract to a helper function like:
  func canonicalizePath(path string) string

This would:
- Reduce code duplication
- Make the logic easier to maintain
- Ensure consistent behavior across all path handling

Related to bd-e16b implementation.


Agent 4 Issue 62

Created by agent 4


Agent 4 Issue 63

Created by agent 4


Agent 4 Issue 64

Created by agent 4


Test issue 1


Blocking issue


Task B under epic


Agent 4 Issue 65

Created by agent 4


Agent 4 Issue 66

Created by agent 4


Agent 4 Issue 67

Created by agent 4


Agent 4 Issue 68

Created by agent 4


Agent 4 Issue 69

Created by agent 4


Agent 4 Issue 70

Created by agent 4


Agent 4 Issue 71

Created by agent 4


Agent 4 Issue 72

Created by agent 4


Agent 4 Issue 73

Created by agent 4


Agent 4 Issue 74

Created by agent 4


Frontend task


Test issue with explicit ID


Agent 4 Issue 75

Created by agent 4


Agent 4 Issue 76

Created by agent 4


Agent 4 Issue 77

Created by agent 4


Agent 4 Issue 78

Created by agent 4


Agent 4 Issue 79

Created by agent 4


Agent 4 Issue 80

Created by agent 4


Agent 4 Issue 81

Created by agent 4


Agent 4 Issue 82

Created by agent 4


Agent 4 Issue 83

Created by agent 4


Agent 4 Issue 84

Created by agent 4


Sub-task under B


Agent 4 Issue 85

Created by agent 4


Agent 4 Issue 86

Created by agent 4


Agent 4 Issue 87

Created by agent 4


Agent 4 Issue 88

Created by agent 4


~/src/beads daemon has 'sql: database is closed' errors - zombie daemon


Agent 4 Issue 89

Created by agent 4


Agent 4 Issue 90

Created by agent 4


Agent 4 Issue 91

Created by agent 4


Agent 4 Issue 92

Created by agent 4


Agent 4 Issue 93

Created by agent 4


Agent 4 Issue 94

Created by agent 4


Issue 2


Auto-flush JSONL on CRUD operations with 5-second debounce

Implemented automatic write-through from SQLite to JSONL with 5-second debouncing. After any CRUD operation (create, update, close, dep add/remove), changes are scheduled to flush to JSONL after 5 seconds of inactivity. On process exit, any pending changes are flushed immediately. This prevents .db and .jsonl from getting out of sync, solving the workflow gap where agents forget to run 'bd export'. Can be disabled with --no-auto-flush flag. Addresses bd-48.


Agent 4 Issue 95

Created by agent 4


Agent 4 Issue 96

Created by agent 4


Agent 4 Issue 97

Created by agent 4


Agent 4 Issue 98

Created by agent 4


Agent 4 Issue 99

Created by agent 4


Agent 2 Issue 76

Created by agent 2


Agent 2 Issue 77

Created by agent 2


Agent 2 Issue 78

Created by agent 2


Agent 2 Issue 79

Created by agent 2


Agent 2 Issue 80

Created by agent 2


Import reports misleading '0 created, 0 updated' when actually importing all issues

When running 'bd import' on a fresh database (no existing issues), the command reports 'Import complete: 0 created, 0 updated' even though it successfully imported all issues from the JSONL file.

**Steps to reproduce:**
1. Delete .beads/beads.db
2. Run: bd import .beads/issues.jsonl
3. Observe output: 'Import complete: 0 created, 0 updated'
4. Run: bd list
5. Confirm: All issues are actually present in the database

**Expected behavior:**
Report the actual number of issues imported, e.g., 'Import complete: 523 created, 0 updated'

**Actual behavior:**
'Import complete: 0 created, 0 updated' (misleading - makes user think import failed)

**Impact:**
- Users think import failed when it succeeded
- Confusing during database sync operations (e.g., after git pull)
- Makes debugging harder (can't tell if import actually worked)

**Context:**
Discovered during VC session when syncing database after git pull. The misleading message caused confusion about whether the database was properly synced with the canonical JSONL file.

- Import command reports accurate count of created/updated issues
- Fresh database import shows 'N created' where N is the actual number
- Update operations show 'N updated' where N is the actual number changed
- Message clearly indicates success vs failure


Final test

Testing with new binary


Agent 2 Issue 81

Created by agent 2


Agent 2 Issue 82

Created by agent 2


Agent 2 Issue 83

Created by agent 2


Agent 2 Issue 84

Created by agent 2