Critical bug


Add PostgreSQL backend

Implement PostgreSQL storage backend as alternative to SQLite for larger teams


parallel_test_10


parallel_test_3


parallel_test_8


parallel_test_9


parallel_26


parallel_31


parallel_32


parallel_33


parallel_28


parallel_29


Test issue to verify fix

This should be bd-11 if the fix works


parallel_27


parallel_30


parallel_35


parallel_34


stress_3


stress_5


stress_10


stress_2


stress_8


stress_13


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.


stress_14


stress_1


stress_7


stress_17


stress_6


stress_19


stress_20


stress_15


stress_24


stress_18


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.


stress_22


stress_28


stress_25


stress_29


stress_26


stress_9


stress_30


stress_32


stress_16


stress_27


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.


stress_31


stress_35


stress_37


stress_34


stress_36


stress_21


stress_38


stress_42


stress_43


stress_39


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


stress_45


stress_46


stress_48


stress_44


stress_40


stress_41


stress_12


stress_47


stress_49


stress_50


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.


stress_33


stress_23


stress_11


stress_4


Add visual indicators for nodes with multiple parents in dep tree

When a node appears in the dependency tree via multiple paths (diamond dependencies), add a visual indicator like (*) or (multiple parents) to help users understand the graph structure. This would make it clear when deduplication has occurred. Example: 'bd-503: Shared dependency (*) [P1] (open)'


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.


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 issue with --deps flag


Another test with multiple deps


Fix: bd init --prefix test -q flag not recognized

The init command doesn't recognize the -q flag. When running 'bd init --prefix test -q', it fails silently or behaves unexpectedly. The flag should either be implemented for quiet mode or removed from documentation if not supported.


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.


Add OAuth2 support

Implement OAuth2 authentication flow with support for Google and GitHub providers.

- Create OAuth2 provider interface
- Implement Google provider
- Implement GitHub provider
- Add callback handler
- Store tokens securely

- Users can authenticate with Google
- Users can authenticate with GitHub
- Tokens are stored securely in database
- Token refresh works automatically


Add rate limiting to auth endpoints

Auth endpoints are vulnerable to brute force attacks. Need to add rate limiting.


Improve session management

Current session management is basic. Need to improve with better expiration handling.


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


Add OAuth2 support


Add rate limiting to auth endpoints


Improve session management


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.


Investigate vector/semantic search for issue discovery

From GH issue #2 RFC discussion: Evaluate if vector/semantic search over issues would provide value for beads.

**Use case:** Find semantically related issues (e.g., 'login broken' finds 'authentication failure', 'session expired').

**Questions to answer:**
1. What workflows would this enable that we can't do now?
2. Is dataset size (typically 50-200 issues) large enough to benefit?
3. Do structured features (deps, tags, types) already provide better relationships?
4. What's the maintenance cost (embeddings, storage, recomputation)?

**Alternatives to consider:**
- Improve 'bd list' filtering with regex/boolean queries
- Add 'bd related <id>' showing deps + mentions + same tags
- Export to JSON and pipe to external AI tools

**Decision:** Only implement if clear use case emerges. Don't add complexity for theoretical benefits.

**Context:** Part of evaluating Turso RFC ideas (GH #2). Vector search was proposed but unclear if needed for typical beads usage.


Implement storage driver interface for pluggable backends

Create abstraction layer for storage to support multiple backends (SQLite, Postgres, Turso, in-memory testing, etc.).

**Current state:** All storage logic hardcoded to SQLite in internal/storage/sqlite/sqlite.go

**Proposed design:**

```go
// internal/storage/storage.go
type Store interface {
    // Issue CRUD
    CreateIssue(issue *Issue) error
    GetIssue(id string) (*Issue, error)
    UpdateIssue(id string, updates *Issue) error
    DeleteIssue(id string) error
    ListIssues(filter *Filter) ([]*Issue, error)

    // Dependencies
    AddDependency(from, to string, depType DependencyType) error
    RemoveDependency(from, to string, depType DependencyType) error
    GetDependencies(id string) ([]*Dependency, error)

    // Counters, stats
    GetNextID(prefix string) (string, error)
    GetStats() (*Stats, error)

    Close() error
}
```

**Benefits:**
- Better testing (mock/in-memory stores)
- Future flexibility (Postgres, cloud APIs, etc.)
- Clean architecture (business logic decoupled from storage)
- Enable Turso or other backends without refactoring everything

**Implementation steps:**
1. Define Store interface in internal/storage/storage.go
2. Refactor SQLiteStore to implement interface
3. Update all commands to use interface, not concrete type
4. Add MemoryStore for testing
5. Add driver selection via config (storage.driver = sqlite|turso|postgres)
6. Update tests to use interface

**Note:** This is valuable even without adopting Turso. Good architecture practice.

**Context:** From GH issue #2 RFC evaluation. Driver interface is low-cost, high-value regardless of whether we add alternative backends.


Investigate auto-export debounce not triggering

Auto-export to JSONL did not trigger automatically after creating bd-180 and bd-181. Had to manually run 'bd export' to sync.

**Expected behavior:** Auto-export should trigger ~5 seconds after CRUD operations (per CLAUDE.md documentation).

**Actual behavior:** Issues bd-180 and bd-181 were created but JSONL was not updated until manual 'bd export' was run.

**Investigation needed:**
1. Check if auto-flush goroutine is running
2. Verify debounce timer is being triggered on CreateIssue()
3. Check for errors/panics in background export
4. Verify auto-flush is enabled by default
5. Check if there's a race condition with shutdown

**Impact:** HIGH - Data loss risk if users create issues and don't realize they haven't synced to Git.

**Testing:**
```bash
# Create issue and wait 10 seconds
bd create "Test" -p 4
sleep 10
grep "Test" .beads/issues.jsonl  # Should find it
```

**Workaround:** Manually run 'bd export' after CRUD operations.

**Context:** Discovered during GH issue #2 RFC evaluation while creating bd-180 and bd-181.

**Investigation Results:**

The auto-export feature IS working correctly in the current codebase (v0.9.5). Testing shows:

✅ Storage layer marks issues dirty correctly (lines 415-423, 593-601, 633-641 in sqlite.go)
✅ CLI calls markDirtyAndScheduleFlush() after CRUD operations (lines 766, 1000, 1055 in main.go)
✅ Debounce timer (5s) triggers and exports to JSONL successfully
✅ Tested: Created bd-196, auto-exported within 6 seconds

**Root Cause:**
The issue was caused by running an **old bd binary** that didn't have the complete auto-export implementation. After rebuilding (`go build -o bd ./cmd/bd`), auto-export works perfectly.

**Resolution:**
Users experiencing this issue need to:
1. Rebuild bd: `go build -o bd ./cmd/bd`
2. Install updated binary: `sudo mv bd /usr/local/bin/` (or appropriate path)
3. Verify: `bd version` should show 0.9.5+

**Additional Notes:**
- Auto-export uses 5-second debounce (configurable at main.go:36)
- Exports are atomic (writes to .tmp, then renames)
- Only dirty issues are exported (incremental updates)
- Works correctly in production use

**Follow-up:**
Consider adding a version check warning if user's binary is outdated (bd-408).


Plugin manifest has invalid 'engines' field causing marketplace install failure

The plugin.json manifest includes an 'engines' field that Claude Code doesn't recognize. This causes the plugin to fail validation when installed via /plugin marketplace add.

Error: Plugin beads has an invalid manifest file at .claude-plugin/plugin.json. Validation errors: : Unrecognized key(s) in object: 'engines'

Fix: Remove the 'engines' field from plugin.json

The engines field was added to specify minimum beads version requirements, but Claude Code's plugin manifest schema doesn't support it. We should document version requirements in PLUGIN.md instead.


race_test_4


race_test_8


race_test_5


race_test_16


race_test_17


race_test_10


Fix import zero-value field handling

Import uses zero-value checks (Priority != 0) to determine field updates. This prevents setting priority to 0 or clearing string fields. Export/import round-trip not fully idempotent for zero values. Consider JSON presence detection or explicit preserve-existing semantics. Location: cmd/bd/import.go:95-106


race_test_11


final_test_10


final_test_7


stress_test_5


stress_test_6


stress_test_1


Test2 auto-export


Add version mismatch warning for outdated binaries

When bd detects that the database was created/modified by a newer version, warn the user that they may be running an outdated binary.

**Problem:** Users may run old bd binaries without realizing it, leading to confusing behavior (e.g., missing features like auto-export).

**Solution:** Store schema version or bd version in metadata table, check on startup, warn if mismatch.

**Implementation:**
1. Add `schema_version` or `bd_version` to metadata table during init
2. Check version in PersistentPreRun (cmd/bd/main.go)
3. Warn if binary version < DB version
4. Suggest: 'Your bd binary (v0.9.3) is older than this database (v0.9.5). Rebuild: go build -o bd ./cmd/bd'

**Edge cases:**
- Dev builds (show commit hash?)
- Backwards compatibility (older DBs should work with newer binaries)
- Don't warn on every command (maybe once per session?)

**Related:** Fixes confusion from bd-182 (auto-export not working with old binary)

**Implementation Complete:**

✅ Added version metadata storage during `bd init` (init.go:59-63)
✅ Added `checkVersionMismatch()` function (main.go:301-345)
✅ Integrated version check into PersistentPreRun (main.go:98-99)
✅ Tested both scenarios:
   - Outdated binary: Clear warning with rebuild instructions
   - Newer binary: Info message that DB will be auto-upgraded
✅ No warnings on subsequent runs (version updated automatically)

**How it works:**
1. On `bd init`: Stores current version in metadata table
2. On every command: Checks stored version vs binary version
3. If mismatch:
   - Binary < DB version → Warn: outdated binary
   - Binary > DB version → Info: auto-upgrading DB
4. Always updates stored version to current (future-proof)

**Files modified:**
- cmd/bd/init.go: Store version on init
- cmd/bd/main.go: checkVersionMismatch() + integration

**Testing:**
```bash
# Simulate old binary
sqlite3 .beads/default.db "UPDATE metadata SET value='0.9.99' WHERE key='bd_version';"
bd ready  # Shows warning

# Normal use (versions match)
bd ready  # No warning
```

**Edge cases handled:**
- Empty version (old DB): Silently upgrade
- Metadata errors: Skip check (defensive)
- Dev builds: String comparison (works for 0.9.5 vs 0.9.6)

Fixes bd-182 confusion (users won't run outdated binaries unknowingly).


Verify auto-export works


Add --strict flag for dependency import failures

Currently dependency import errors are warnings (logged to stderr, execution continues). Missing targets or cycles may indicate JSONL corruption. Add --strict flag to fail on any dependency errors for data integrity validation. Location: cmd/bd/import.go:159-164


Simplify getNextID SQL query parameters

Query passes prefix four times to same SQL query. Works but fragile if query changes. Consider simplifying SQL to require fewer parameters. Location: internal/storage/sqlite/sqlite.go:73-78


Add validation/warning for malformed issue IDs

getNextID silently ignores non-numeric ID suffixes (e.g., bd-foo). CAST returns NULL for invalid strings. Consider detecting and warning about malformed IDs in database. Location: internal/storage/sqlite/sqlite.go:79-82


Optimize export dependency queries (N+1 problem)

Export triggers separate GetDependencyRecords() per issue. For large DBs (1000+ issues), this is N+1 queries. Add GetAllDependencyRecords() to fetch all dependencies in one query. Location: cmd/bd/export.go:52-59, import.go:138-142


Support ID space partitioning for parallel worker agents

Enable external orchestrators (like AI worker swarms) to control issue ID assignment. Add --id flag to 'bd create' for explicit ID specification. Optionally support 'bd config set next_id N' to set the starting point for auto-increment. Storage layer already supports pre-assigned IDs (sqlite.go:52-71), just need CLI wiring. This keeps beads simple while letting orchestrators implement their own ID partitioning strategies to minimize merge conflicts. Complementary to bd-9's collision resolution.


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.


Optimize reference updates to avoid loading all issues into memory

In updateReferences(), we call SearchIssues with no filter to get ALL issues for updating references. For large databases (10k+ issues), this loads everything into memory. Options: 1) Use batched processing with LIMIT/OFFSET, 2) Use SQL UPDATE with REPLACE() directly, 3) Stream results instead of loading all at once. Located in collision.go:266


Cache compiled regexes in replaceIDReferences for performance

replaceIDReferences() compiles the same regex patterns on every call. With 100 issues and 10 ID mappings, that's 1000 regex compilations. Pre-compile regexes once and reuse. Can use a struct with compiled regex, placeholder, and newID. Located in collision.go:329. Estimated performance improvement: 10-100x for large batches.


Improve error handling in dependency removal during remapping

In updateDependencyReferences(), RemoveDependency errors are caught and ignored with continue (line 392). Comment says 'if dependency doesn't exist' but this catches ALL errors including real failures. Should check error type with errors.Is(err, ErrDependencyNotFound) and only ignore not-found errors, returning other errors properly.


Use safer placeholder pattern in replaceIDReferences

Currently uses __PLACEHOLDER_0__ which could theoretically collide with user text. Use a truly unique placeholder like null bytes: \x00REMAP\x00_0_\x00 which are unlikely to appear in normal text. Located in collision.go:324. Very low probability issue but worth fixing for completeness.


Normal task


Remove unused issueMap in scoreCollisions

scoreCollisions() creates issueMap and populates it (lines 135-138) but never uses it. Either remove it or add a TODO comment explaining future use. Located in collision.go:135-138. Cosmetic cleanup.


Test issue for design field

Testing the new update flags

## Design Plan\n- Add flags to update command\n- Test thoroughly\n- Document changes

- All three fields (design, notes, acceptance-criteria) can be updated\n- Changes persist in database\n- bd show displays the fields correctly

Implementation complete. All tests passing.


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.


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.


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.


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


Handle missing JSONL directory in findJSONLPath

findJSONLPath() assumes the database directory exists. If someone runs bd init to create a new database but the .beads directory doesn't exist yet, the glob operations might fail silently. Add os.MkdirAll(dbDir, 0755) to ensure directory exists before globbing. Located in cmd/bd/main.go:188-201.


Refactor duplicate flush logic in PersistentPostRun

PersistentPostRun contains a complete copy of the flush logic instead of calling flushToJSONL(). This violates DRY principle and makes maintenance harder. Refactor to use flushToJSONL() with a force parameter to bypass isDirty check, or extract shared logic into a helper function. Located in cmd/bd/main.go:104-138.


Add visibility for auto-flush failures

flushToJSONL() writes warnings to stderr when flush fails, but calling code has no way to know if flush succeeded or failed. This means a command could return success even though JSONL is now out of sync. Consider maintaining a 'last flush status' variable or counter for failed flushes, and warn user after multiple consecutive failures (e.g., 3+). Located in cmd/bd/main.go:227-307.


Optimize auto-flush to use incremental updates

Every flush exports ALL issues and ALL dependencies, even if only one issue changed. For large projects (1000+ issues), this could be expensive. Current approach guarantees consistency, which is fine for MVP, but future optimization could track which issues changed and use incremental updates. Located in cmd/bd/main.go:255-276.


Low priority chore


Make auto-flush debounce duration configurable

flushDebounce is hardcoded to 5 seconds. Make it configurable via environment variable BEADS_FLUSH_DEBOUNCE (e.g., '500ms', '10s'). Current 5-second value is reasonable for interactive use, but CI/automated scenarios might want faster flush. Add getDebounceDuration() helper function. Located in cmd/bd/main.go:31.


Add godoc comments for auto-flush functions

Add comprehensive godoc comments for findJSONLPath(), markDirtyAndScheduleFlush(), and flushToJSONL() explaining behavior, concurrency considerations, and error handling. Include notes about debouncing behavior (timer resets on each write, flush occurs 5s after LAST operation) and flush-on-exit guarantees. Located in cmd/bd/main.go:188-307.


Add test coverage for auto-flush feature

Add comprehensive tests for auto-flush functionality:\n- Test that markDirtyAndScheduleFlush() is called after CRUD operations\n- Test debounce timing (rapid operations result in single flush)\n- Test --no-auto-flush flag disables feature\n- Test flush on program exit\n- Test concurrent operations don't cause races\n- Test error scenarios (disk full, permission denied, etc.)\n- Test import command triggers auto-flush\n\nCurrent implementation has no test coverage for the auto-flush feature. Located in cmd/bd/main_test.go (to be created).


Test auto-sync feature


Regular auto-ID issue


Test flush tracking


Test export cancels timer


Test incremental export

Testing bd-39 implementation


Test incremental 2


Final test

Testing with new binary


Test issue

Testing prefix


Test label dirty tracking


Test hash-based import


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


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


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


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.


Write plugin documentation

Create comprehensive documentation for the plugin.

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


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


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


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.


Add migration scripts for GitHub Issues

Create scripts to import from GitHub Issues API or exported JSON


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.


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


Document hierarchical blocking behavior in README

The fix for bd-58 changes user-visible behavior: children of blocked epics are now automatically blocked.

**What needs documenting:**
1. README.md dependency section should explain blocking propagation
2. Clarify that 'blocks' + 'parent-child' together create transitive blocking
3. Note that 'related' and 'discovered-from' do NOT propagate blocking
4. Add example showing epic → child blocking propagation

**Example to add:**
```bash
# If epic is blocked, children are too
bd create "Epic 1" -t epic -p 1
bd create "Task 1" -t task -p 1
bd dep add task-1 epic-1 --type parent-child

# Block the epic
bd create "Blocker" -t task -p 0
bd dep add epic-1 blocker-1 --type blocks

# Now both epic-1 AND task-1 are blocked
bd ready  # Neither will show up
```


Add EXPLAIN QUERY PLAN tests for ready work query

Verify that the hierarchical blocking query uses proper indexes and doesn't do full table scans.

**Queries to analyze:**
1. The recursive CTE (both base case and recursive case)
2. The final SELECT with NOT EXISTS
3. Impact of various filters (status, priority, assignee)

**Implementation:**
Add test function that:
- Runs EXPLAIN QUERY PLAN on GetReadyWork query
- Parses output to verify no SCAN TABLE operations
- Documents expected query plan in comments
- Fails if query plan degrades

**Benefits:**
- Catch performance regressions in tests
- Document expected query behavior
- Ensure indexes are being used

Related to: bd-59 (composite index on depends_on_id, type)


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


Document versioning and release strategy

Create comprehensive versioning strategy for beads ecosystem.

Components to document:
1. bd CLI (Go binary) - main version number
2. Plugin (Claude Code) - tracks CLI version
3. MCP server (Python) - bundled with plugin
4. Release workflow - how to sync all three

Decisions to make:
- Should plugin.json auto-update from bd CLI version?
- Should we have a VERSION file at repo root?
- How to handle breaking changes across components?
- What's the update notification strategy?

References:
- plugin.json engines field now requires bd >=0.9.0
- /bd-version command added for checking compatibility
- PLUGIN.md now documents update workflow


Sync versions to 0.9.2 across all components

Version mismatch discovered: bd CLI is 0.9.2 but other components still at 0.9.0 or 1.0.0.

Current state:
- bd CLI (cmd/bd/version.go): 0.9.2 ✓
- Plugin (.claude-plugin/plugin.json): 0.9.0 ✗
- MCP Server (integrations/beads-mcp): 1.0.0 ✗
- README.md: 0.9.0 ✗

Files to update:
1. .claude-plugin/plugin.json
2. integrations/beads-mcp/pyproject.toml
3. README.md (all mentions)
4. PLUGIN.md (if any mentions)
5. CHANGELOG.md (add 0.9.1 and 0.9.2 entries)

Root cause: Version bumps only updated version.go, not other components.
Solution needed: Script or process to sync versions across all files.


Create version bump script

Create scripts/bump-version.sh to automate version syncing across all components.

The script should:
1. Take a version number as argument (e.g., ./scripts/bump-version.sh 0.9.3)
2. Update all version files:
   - cmd/bd/version.go (Version constant)
   - .claude-plugin/plugin.json (version field)
   - .claude-plugin/marketplace.json (plugins[].version)
   - integrations/beads-mcp/pyproject.toml (version field)
   - README.md (Alpha version mention)
   - PLUGIN.md (version requirements)
3. Validate semantic versioning format
4. Show diff preview before applying
5. Optionally create git commit with standard message

This prevents the version mismatch issue that occurred when only version.go was updated.

Related: bd-66 (version sync issue)


Add system-wide/multi-repo support for beads

GitHub issue #4 requests ability to use beads across multiple projects and for system-wide task tracking.

Current limitation: beads is per-repository isolated. Each project has its own .beads/ directory and issues cannot reference issues in other projects.

Potential approaches:
1. Global beads instance in ~/.beads/global.db for cross-project work
2. Project references - allow issues to link across repos
3. Multi-project workspace support - one beads instance managing multiple repos
4. Integration with existing MCP server to provide remote multi-project access

Use cases:
- System administrators tracking work across multiple machines/repos
- Developers working on a dozen+ projects simultaneously
- Cross-cutting concerns that span multiple repositories
- Global todo list with project-specific subtasks

Related:
- GitHub issue #4: https://github.com/steveyegge/beads/issues/4
- Comparison to membank MCP which already supports multi-project via centralized server
- MCP server at integrations/beads-mcp/ could be extended for this

See also: Testing framework for plugins (also from GH #4)


Add coverage threshold to CI pipeline

Current CI runs tests with coverage but doesn't enforce minimum threshold. Add step to fail if coverage drops below target.

Current coverage: 60%
Recommended thresholds:
- Warn: 55%
- Fail: 50%

This prevents coverage regression while allowing gradual improvement toward 80% target for 1.0.

Implementation:
1. Add coverage check step after test run
2. Use 'go tool cover -func=coverage.out' to get total
3. Parse percentage and compare to threshold
4. Optionally: Use codecov's built-in threshold features

Related to test coverage improvement work (upcoming issue).


Add performance benchmarks document

Document actual performance metrics with hyperfine tests


Increase test coverage for auto-flush and auto-import features

Critical features have 0% test coverage despite being core workflow functionality.

**Uncovered areas (0% coverage):**

Auto-flush/Auto-import (dirty tracking):
- MarkIssueDirty / MarkIssuesDirty
- GetDirtyIssues / GetDirtyIssueCount
- ClearDirtyIssues / ClearDirtyIssuesByID
- Auto-flush debouncing logic
- Auto-import hash comparison

Database/file discovery:
- FindDatabasePath (finds .beads/*.db in directory tree)
- FindJSONLPath (finds issues.jsonl)
- findDatabaseInTree helper

Label operations:
- AddLabel / RemoveLabel
- GetLabels / GetIssuesByLabel

Events/Comments:
- AddComment
- GetEvents
- GetStatistics

Metadata storage:
- SetMetadata / GetMetadata (used for import hash tracking)

CLI output formatting:
- outputJSON
- printCollisionReport / printRemappingReport
- createIssuesFromMarkdown

**Priority areas:**
1. Auto-flush/import (highest risk - core workflow)
2. Database discovery (second - affects all operations)
3. Labels/events (lower priority - less commonly used)

**Test approach:**
- Add unit tests for dirty tracking in sqlite package
- Add integration tests for auto-flush timing and debouncing
- Add tests for import hash detection and idempotency
- Add tests for database discovery edge cases (permissions, nested dirs)

**Target:** Get overall coverage from 60% → 75%, focus on cmd/bd (currently 24.1%)

**Note:** These features work well in practice (dogfooding proves it) but edge cases (disk full, permissions, concurrent access, race conditions) are untested.

Test coverage significantly improved! Added comprehensive test suites:

**Tests Added:**
1. ✅ Dirty tracking (dirty_test.go): 8 tests
   - MarkIssueDirty, MarkIssuesDirty, GetDirtyIssues, ClearDirtyIssues
   - GetDirtyIssueCount, ClearDirtyIssuesByID
   - Ordering and timestamp update tests
   - Coverage: 75-100% for all functions

2. ✅ Metadata storage (sqlite_test.go): 4 tests
   - SetMetadata, GetMetadata with various scenarios
   - Coverage: 100%

3. ✅ Label operations (labels_test.go): 9 tests
   - AddLabel, RemoveLabel, GetLabels, GetIssuesByLabel
   - Duplicate handling, empty cases, dirty marking
   - Coverage: 71-82%

4. ✅ Events & Comments (events_test.go): 7 tests
   - AddComment, GetEvents with limits
   - Timestamp updates, dirty marking
   - Multiple event types in history
   - Coverage: 73-92%

5. ✅ Database/JSONL discovery (beads_test.go): 8 tests
   - FindDatabasePath with env var, tree search, home default
   - FindJSONLPath with existing files, defaults, multiple files
   - Coverage: 89-100%

**Coverage Results:**
- Overall: 70.3% (up from ~60%)
- beads package: 90.6%
- sqlite package: 74.7% (up from 60.8%)
- types package: 100%

**Impact:**
All priority 1 features now have solid test coverage. Auto-flush/import, metadata storage, labels, and events are thoroughly tested with edge cases covered.

Files created:
- internal/storage/sqlite/dirty_test.go (8 tests)
- internal/storage/sqlite/labels_test.go (9 tests)
- internal/storage/sqlite/events_test.go (7 tests)
- beads_test.go (8 tests)

Files modified:
- internal/storage/sqlite/sqlite_test.go (added 4 metadata tests)

**Next Steps (if desired):**
- CLI output formatting tests (outputJSON, printCollisionReport, etc.)
- Integration tests for auto-flush debouncing timing
- More edge cases for concurrent access


Code review follow-up: Post-PR #8 merge improvements

Follow-up tasks from the ultrathink code review of PR #8 merge (bd-62).

**Context:** PR #8 successfully merged atomic counter + dirty tracking. Core functionality is solid but several improvements identified.

**Critical (P0-P1):**
- bd-64: Fix SyncAllCounters performance bottleneck (P0)
- bd-65: Add migration for issue_counters table (P1)
- bd-66: Make import counter sync failure fatal (P1)

**Nice to have (P2-P3):**
- bd-67: Update test comments (P2)
- bd-68: Add performance benchmarks (P2)
- bd-69: Add metrics/logging (P3)
- bd-70: Add EXPLAIN QUERY PLAN tests (P3)

**Overall assessment:** 4/5 stars - Excellent implementation with one critical performance issue. After bd-64 is fixed, this becomes 5/5.

**Review document:** Available if needed

Status update: All P0-P1 critical tasks completed! bd-64 (performance), bd-65 (migration), bd-66 (fatal error), bd-67 (comments) are all done. Atomic counter implementation is now production-ready. Remaining tasks are P2-P3 enhancements.


Test performance - issue 1


Performance test 1


Performance test 2


Performance test 3


Performance test 4


Performance test 5


Performance test 6


Performance test 7


Reach 1.0 release milestone

Stabilize API, finalize documentation, comprehensive testing


Performance test 8


Performance test 9


Performance test 10


Add external_ref field for tracking GitHub issues

Add optional external_ref field to issues table to track external references like 'gh-9', 'jira-ABC', etc. Includes schema migration, CLI flags (--external-ref for create/update), and tests. This enables linking bd issues to GitHub issues for better workflow integration.


Auto-import fails in git workflows due to mtime issues

The auto-import mechanism (autoImportIfNewer) relies on file modification time comparison between JSONL and DB. This breaks in git workflows because git does not preserve original file modification times - pulled files get fresh mtimes based on checkout time.

Root causes:
1. Git checkout sets mtime to 'now', not original commit time
2. Auto-import compares JSONL mtime vs DB mtime (line 181 in main.go)
3. If DB was recently modified (agents working), mtime check fails
4. Auto-import silently returns without feedback
5. Agents continue with stale database state

This caused issues in VC project where 3 parallel agents:
- Pulled updated .beads/issues.jsonl from git
- Auto-import didn't trigger (JSONL appeared older than DB)
- Agents couldn't find their assigned issues
- Agents exported from wrong database, corrupting JSONL

Recommended approach: Checksum-based sync (option 3 from original design)

## Solution: Hash-based content comparison

Replace mtime comparison with JSONL content hash comparison:

1. **Compute JSONL hash on startup**:
   - SHA256 hash of .beads/issues.jsonl contents
   - Fast enough for typical repos (<1MB = ~20ms)
   - Only computed once per command invocation

2. **Store last import hash in DB**:
   - Add metadata table if not exists: CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT)
   - Store hash after successful import: INSERT OR REPLACE INTO metadata (key, value) VALUES ('last_import_hash', '<hash>')
   - Query on startup: SELECT value FROM metadata WHERE key = 'last_import_hash'

3. **Compare hashes instead of mtimes**:
   - If JSONL hash != stored hash: auto-import (content changed)
   - If JSONL hash == stored hash: skip import (no changes)
   - If no stored hash: fall back to mtime comparison (backward compat)

4. **Update autoImportIfNewer() in cmd/bd/main.go**:
   - Lines 155-279 currently use mtime comparison (line 181)
   - Replace with hash comparison
   - Keep mtime as fallback for old DBs without metadata table

## Implementation Details

### New storage interface method:
```go
// In internal/storage/storage.go
type Storage interface {
    // ... existing methods ...
    GetMetadata(ctx context.Context, key string) (string, error)
    SetMetadata(ctx context.Context, key, value string) error
}
```

### Migration:
```go
// In internal/storage/sqlite/sqlite.go init
CREATE TABLE IF NOT EXISTS metadata (
    key TEXT PRIMARY KEY,
    value TEXT NOT NULL
);
```

### Updated autoImportIfNewer():
```go
func autoImportIfNewer() {
    jsonlPath := findJSONLPath()

    // Check if JSONL exists
    jsonlData, err := os.ReadFile(jsonlPath)
    if err != nil {
        return // No JSONL, skip
    }

    // Compute current hash
    hasher := sha256.New()
    hasher.Write(jsonlData)
    currentHash := hex.EncodeToString(hasher.Sum(nil))

    // Get last import hash from DB
    ctx := context.Background()
    lastHash, err := store.GetMetadata(ctx, "last_import_hash")
    if err != nil {
        // No metadata support (old DB) - fall back to mtime comparison
        autoImportIfNewerByMtime()
        return
    }

    // Compare hashes
    if currentHash == lastHash {
        return // No changes, skip import
    }

    // Content changed - import
    if err := importJSONLSilent(jsonlPath, jsonlData); err != nil {
        return // Import failed, skip
    }

    // Store new hash
    _ = store.SetMetadata(ctx, "last_import_hash", currentHash)
}
```

## Benefits

- **Git-proof**: Works regardless of file timestamps
- **Universal**: Works with git, Dropbox, rsync, manual edits
- **Backward compatible**: Falls back to mtime for old DBs
- **Efficient**: SHA256 is fast (~20ms for 1MB)
- **Accurate**: Only imports when content actually changed
- **No user action**: Fully automatic, invisible

## Performance Optimization

For very large repos (>10MB JSONL):
- Only hash if mtime changed (combine both checks)
- Use incremental hashing if metadata table tracks line count
- Consider sampling hash (first 1MB + last 1MB)

But start simple - full hash is fast enough for 99% of use cases.

## Rollout Plan

1. Add metadata table + Get/SetMetadata methods (backward compatible)
2. Update autoImportIfNewer() with hash logic + mtime fallback
3. Test with old and new DBs
4. Ship in next minor version (v0.10.0)
5. Document in CHANGELOG as "more reliable auto-import"
6. Git hooks remain optional but unnecessary for most users

- Auto-import works correctly after git pull
- Agents in parallel workflows see consistent database state
- Clear feedback when import is needed
- Performance acceptable for large databases
- Works in both git and non-git workflows
- Documentation updated with multi-agent best practices


GH-1: Fix bd dep tree graph display issues

Tree display has several issues: 1) Epic items may not expand all sub-items, 2) Subitems repeat multiple times at same level, 3) Items with multiple blockers appear multiple times. The tree visualization doesn't properly handle graph structures with multiple dependencies.


GH-2: Evaluate optional Turso backend for collaboration

RFC proposal for optional Turso/libSQL backend to enable: database branching, near-real-time sync between agents/humans, native vector search, browser-ready persistence (WASM/OPFS), and concurrent writes. Would be opt-in, keeping current JSONL+SQLite as default. Requires storage driver interface.


GH-3: Debug zsh killed error on bd init

User reports 'zsh: killed bd init' when running bd init or just bd command. Likely a crash or signal. Need to reproduce and investigate cause.


GH-4: Consider system-wide/multi-repo beads usage

User wants to use beads across multiple repositories and for sysadmin tasks. Currently beads is project-scoped (.beads/ directory). Explore options for system-wide issue tracking that spans multiple repos. Related question: how does beads compare to membank MCP?


GH-6: Fix race condition in parallel issue creation

Creating multiple issues rapidly in parallel causes 'UNIQUE constraint failed: issues.id' error. The ID generation has a race condition. Reproducible with: for i in {26..35}; do ./bd create parallel_ 2>&1 & done


Build collision resolution tooling for distributed branch workflows

When branches diverge and both create issues, auto-incrementing IDs collide on merge. Build excellent tooling to detect collisions during import, auto-renumber issues with fewer dependencies, update all references in descriptions and dependency links, and provide clear user feedback. Goal: keep beautiful brevity of numeric IDs (bd-302) while handling distributed creation gracefully.


GH-7: Package available in AUR (beads-git)

Community member created AUR package for Arch Linux: https://aur.archlinux.org/packages/beads-git. This is informational - no action needed, but good to track for release process and documentation.


GH-9: Support markdown files in bd create

Request to support markdown files as input to bd create, which would parse the markdown and split it into multiple issues. Use case: developers keep feature drafts in markdown files in version control, then want to convert them into issues. Example: bd create -f feature-draft.md


GH-11: Add Docker support for hosted/shared instance

Request for Docker container hosting to use beads across multiple dev machines. Would need to consider: centralized database (PostgreSQL?), authentication, concurrent access, API server, etc. This is a significant architectural change from the current local-first model.


GH-18: Add --deps flag to bd create for one-command issue creation

Request to add dependency specification to bd create command instead of requiring separate 'bd dep add' command. Proposed syntax: bd create 'Fix bug' --deps discovered-from=bd-20. This would be especially useful for aider integration and reducing command verbosity.


parallel_test_1


parallel_test_4


parallel_test_7


parallel_test_6


parallel_test_5


parallel_test_2


Test issue with explicit ID


Root issue for dep tree test


Dependency A


Dependency B


Shared dependency C


Epic test


Task A under epic


Task B under epic


Sub-task under A


Sub-task under B


Another explicit ID