title: Add export/import commands

description: Support bd export --format=jsonl and bd import for text-based git workflow

status: closed

issue_type: feature


title: Extend export to include dependencies in JSONL

description: Modify export.go to include dependencies array in each issue's JSONL output. This makes JSONL self-contained and enables proper collision resolution. Format: {"id":"bd-10","dependencies":[{"depends_on_id":"bd-5","type":"blocks"}]}

issue_type: task

type: parent-child

created_by: stevey


title: Test issue to verify fix

description: This should be bd-11 if the fix works


title: Implement collision detection in import

description: 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.


title: Implement reference scoring algorithm

description: 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.


title: Implement ID remapping with reference updates

description: 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.


title: Add --resolve-collisions flag and user reporting

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


title: Write comprehensive collision resolution tests

description: 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.


title: Update documentation for collision resolution

description: 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.


title: Add design/notes/acceptance_criteria fields to update command

description: 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.


title: Fix import zero-value field handling

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

issue_type: bug


title: Add PostgreSQL backend

description: Implement PostgreSQL storage backend as alternative to SQLite for larger teams


title: Add --strict flag for dependency import failures

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


title: Simplify getNextID SQL query parameters

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


title: Add validation/warning for malformed issue IDs

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


title: Optimize export dependency queries (N+1 problem)

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


title: Support ID space partitioning for parallel worker agents

description: 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.


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

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


title: Optimize reference updates to avoid loading all issues into memory

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

status: open


title: Cache compiled regexes in replaceIDReferences for performance

description: 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.


title: Improve error handling in dependency removal during remapping

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


title: Use safer placeholder pattern in replaceIDReferences

description: 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.


title: Document git workflow in README

description: Add Git Workflow section to README explaining binary vs text approaches

issue_type: chore


title: Remove unused issueMap in scoreCollisions

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


title: Test issue for design field

description: Testing the new update flags

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

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

notes: Implementation complete. All tests passing.


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

description:
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.


title: Document or automate JSONL sync workflow for git collaboration

description:
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.


title: Implement reserved database name _.db

description: 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.


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

description: 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.


title: Handle missing JSONL directory in findJSONLPath

description: 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.


title: Refactor duplicate flush logic in PersistentPostRun

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


title: Add visibility for auto-flush failures

description: 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.


title: Optimize auto-flush to use incremental updates

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


title: Add demo GIF/video showing bd quickstart in action

description: Record asciinema or create animated GIF showing the full workflow


title: Make auto-flush debounce duration configurable

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


title: Add godoc comments for auto-flush functions

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


title: Add test coverage for auto-flush feature

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


title: Test auto-sync feature


title: Regular auto-ID issue


title: Test flush tracking


title: Test export cancels timer


title: Test incremental export

description: Testing bd-39 implementation


title: Test incremental 2


title: Final test

description: Testing with new binary


title: Implement MCP server for Claude Desktop

description: Complete the claude-desktop-mcp example with working TypeScript implementation


title: Test label dirty tracking


title: Auto-migrate dirty_issues table on startup

description:
The dirty_issues table was added in bd-39 for incremental export optimization. Existing databases created before this feature won't have the table, causing errors when trying to use dirty tracking.

Add migration logic to check for the dirty_issues table on startup and create it if missing. This should happen in sqlite.New() after opening the database connection but before returning the storage instance.

Implementation:
- Check if dirty_issues table exists (SELECT name FROM sqlite_master WHERE type='table' AND name='dirty_issues')
- If missing, execute the CREATE TABLE and CREATE INDEX statements from schema.go
- This makes bd-39 work seamlessly with existing databases without requiring manual migration

Location: internal/storage/sqlite/sqlite.go:28-58 (New() function)


title: Critical: TOCTOU bug in dirty tracking - ClearDirtyIssues race condition

description:
The GetDirtyIssues/ClearDirtyIssues pattern has a race condition. If a CRUD operation marks an issue dirty between GetDirtyIssues() and ClearDirtyIssues(), that change will be lost. The export will miss that issue until the next time it's modified.

Impact: Data loss - changes can be lost during concurrent operations
Location: internal/storage/sqlite/dirty.go:78-86
Suggested fix: Use a transaction-based approach or track which specific IDs were exported


title: Bug: Export with status filter clears all dirty issues incorrectly

description:
When exporting with a status filter (e.g., bd export --status open -o file.jsonl), the code clears ALL dirty issues even though only issues matching the filter were exported. This means dirty issues that don't match the filter are marked as clean despite not being exported.

Impact: Inconsistent export state, missing data in JSONL
Location: cmd/bd/export.go:86-92
Suggested fix: Only clear dirty flags for issues that were actually exported


title: Bug: Malformed ID detection query never finds malformed IDs

description:
The query checking for malformed IDs uses 'CAST(SUBSTR(...) AS INTEGER) IS NULL' but SQLite's CAST never returns NULL for invalid integers - it returns 0. This means malformed IDs with non-numeric suffixes are never detected or warned about.

Impact: Silent data quality issues, incorrect ID generation
Location: internal/storage/sqlite/sqlite.go:125-145
Suggested fix: Use a regex or check if the SUBSTR result matches '^[0-9]+$' pattern


title: Enhancement: Migration should validate dirty_issues table schema

description:
The migrateDirtyIssuesTable function only checks if the table exists, not if it has the correct schema. If someone created a dirty_issues table with a different schema, the migration would silently succeed and cause runtime errors later.

Impact: Silent schema inconsistencies, difficult debugging
Location: internal/storage/sqlite/sqlite.go:65-98
Suggested fix: Check table schema (column names/types) and either migrate or fail with clear error


title: Enhancement: Inconsistent dependency dirty marking can cause partial updates

description:
In AddDependency and RemoveDependency, both issues are marked dirty in sequence. If the transaction fails after marking the first issue but before marking the second, dirty state becomes inconsistent. While the transaction will rollback, this pattern is fragile.

Impact: Potential inconsistent dirty state on transaction failures
Location: internal/storage/sqlite/dependencies.go:113-131, 160-177
Suggested fix: Use MarkIssuesDirty() batch function instead of separate statements


title: Code quality: Remove dead code in GetDirtyIssueCount

description:
GetDirtyIssueCount checks for sql.ErrNoRows but SELECT COUNT(*) never returns ErrNoRows - it always returns 0 for empty tables. This is unnecessary dead code.

Impact: Code clarity, minor performance
Location: internal/storage/sqlite/dirty.go:88-96
Suggested fix: Remove the ErrNoRows check


title: Enhancement: Add observability for dirty tracking system

description:
No metrics or observability for the dirty tracking system. Difficult to debug production issues like: how many issues are typically dirty? How long do they stay dirty? How often do exports fail?

Impact: Poor debuggability, hard to tune performance
Suggested additions:
- Metrics for dirty count over time
- Duration tracking for dirty state
- Export success/failure rates
- Auto-flush statistics


title: Enhancement: Use consistent timestamps within transactions

description:
Multiple CRUD operations call time.Now() multiple times within a transaction. For consistency, should call once and reuse the same timestamp throughout the transaction so all operations have identical timestamps.

Impact: Minor timestamp inconsistencies, harder to debug event ordering
Locations: Multiple files in internal/storage/sqlite/
Suggested fix: Call time.Now() once at transaction start, pass to all operations


title: Add migration scripts for GitHub Issues

description: Create scripts to import from GitHub Issues API or exported JSON


title: Enhancement: Make auto-flush debounce configurable

description:
The 5-second debounce for auto-flush is hardcoded. For high-frequency operations or slow filesystems, this might not be optimal. Should be configurable via environment variable or config.

Impact: Flexibility for different use cases
Location: cmd/bd/main.go (flushDebounce variable)
Suggested fix: Add BEADS_FLUSH_DEBOUNCE env var or config option


title: Documentation: Transaction isolation levels should be documented

description:
All BeginTx(ctx, nil) calls use default isolation level. For SQLite with WAL mode, this is fine and gives us snapshot isolation. However, this should be documented in the code or in developer docs to make the concurrency guarantees explicit.

Impact: Developer understanding, maintainability
Locations: All BeginTx calls throughout codebase
Suggested fix: Add comment explaining isolation guarantees


title: Merge PR #8: Fix parallel issue creation race condition

description:
PR #8 fixes a critical race condition in parallel issue creation by replacing the in-memory ID counter with an atomic database-backed counter. However, it has conflicts with recent changes to main.

**PR Summary:**
- Adds issue_counters table for atomic ID generation
- Replaces in-memory nextID counter with getNextIDForPrefix()
- Adds SyncAllCounters() to prevent collisions after import
- Includes comprehensive tests for multi-process scenarios

**Conflicts with main:**
1. SQLiteStorage struct - PR removes nextID/idMu fields added to main
2. New() function - PR doesn't include migrateDirtyIssuesTable() added in f3a61a6
3. CreateIssue() - Both versions have dirty tracking but different ID generation
4. Schema - PR adds issue_counters, main added dirty_issues table
5. getNextID() - PR removes function that was recently fixed in 3aeeeb7 for bd-54

**Work needed:**
- Rebase PR #8 on current main
- Preserve dirty_issues table and migration
- Add issue_counters table with similar migration pattern
- Integrate atomic counter system with existing dirty tracking
- Ensure all tests pass
- Verify both features work together

**Context:**
- PR: https://github.com/steveyegge/beads/pull/8
- Closes: bd-6 (if issue exists)
- Related commits: f3a61a6, 3aeeeb7, bafb280


title: Test merged features


title: CRITICAL: Fix SyncAllCounters performance bottleneck in CreateIssue

description:
SyncAllCounters() is called on EVERY issue creation with auto-generated IDs (sqlite.go:143). This scans the entire issues table on every create, causing O(n) overhead.

**Impact:**
- With 1,000 issues: full table scan per create
- With 10,000 issues: massive performance hit
- Unacceptable for production use

**Root cause:** Lines 140-145 in internal/storage/sqlite/sqlite.go sync all counters to handle edge cases (DB created before fix, or issues imported without syncing).

**Solutions:**
1. **Lazy init (preferred)**: Only sync if counter doesn't exist for the prefix
2. **One-time at startup**: Call SyncAllCounters() once in New()
3. **Remove entirely**: import.go now syncs, edge cases are rare

**Recommended fix:** Add ensureCounterSynced() that checks if counter exists before syncing only that prefix.


title: Add migration for issue_counters table

description:
There's a migrateDirtyIssuesTable() function but no corresponding migration for issue_counters table.

**Problem:**
- Existing databases won't have the issue_counters table
- They rely on schema 'CREATE TABLE IF NOT EXISTS'
- Counter won't be initialized with existing issue IDs
- Could lead to ID collisions if issues already exist in DB

**Location:** internal/storage/sqlite/sqlite.go:48-51

**Solution:** Add migrateIssueCountersTable() similar to migrateDirtyIssuesTable():
1. Check if table exists
2. If not, create it
3. Sync counters from existing issues


title: Make import counter sync failure fatal instead of warning

description:
In cmd/bd/import.go:243, SyncAllCounters() failure is treated as a non-fatal warning:

```go
if err := sqliteStore.SyncAllCounters(ctx); err != nil {
    fmt.Fprintf(os.Stderr, "Warning: failed to sync ID counters: %v\n", err)
    // Don't exit - this is not fatal, just a warning
}
```

**Problem:** If counter sync fails, subsequent auto-generated IDs WILL collide with imported issues. This can corrupt data.

**Decision needed:**
1. Make it fatal (fail hard) - safer but less forgiving
2. Keep as warning but document the risk clearly
3. Add a --strict flag to control behavior

**Recommendation:** Make it fatal by default. Data integrity > convenience.


title: Update test comments to reflect post-fix state

description:
Test comments in internal/storage/sqlite/sqlite_test.go:264-266 refer to 'with the bug' but the bug is now fixed:

```go
// With the bug, we expect UNIQUE constraint errors
if len(errors) > 0 {
    t.Logf("Got %d errors (expected with current implementation):", len(errors))
```

**Issue:** This is confusing and suggests the bug still exists.

**Fix:** Update comments to say 'after the fix, no errors expected' and make the test fail hard if errors occur (lines 279-281).


title: Add performance benchmarks for CreateIssue with varying DB sizes

description:
Add benchmark tests to measure CreateIssue performance as database grows.

**Goal:** Catch performance regressions early, especially around ID generation.

**Test cases:**
- Benchmark with 10, 100, 1k, 10k existing issues
- Measure auto-generated ID creation time
- Measure explicit ID creation time
- Compare single vs concurrent operations

**Location:** internal/storage/sqlite/sqlite_test.go

**Related:** This would have caught the SyncAllCounters issue (bd-64) immediately.


title: Add metrics/logging for counter sync operations

description:
Add observability for ID counter operations to help diagnose issues and monitor performance.

**What to log:**
- When SyncAllCounters() is called
- How long it takes
- How many counters are synced
- Any collisions detected/prevented

**Use cases:**
- Debug ID generation issues
- Monitor performance impact of counter syncs
- Detect when databases need optimization

**Implementation:**
- Add structured logging (consider using slog)
- Make it optional (via flag or env var)
- Include in both CreateIssue and import flows


title: Add performance benchmarks document

description: Document actual performance metrics with hyperfine tests


title: Add EXPLAIN QUERY PLAN tests for counter queries

description:
Add tests to verify that counter-related SQL queries use proper indexes and don't cause full table scans.

**Queries to test:**
1. getNextIDForPrefix() - INSERT with ON CONFLICT
2. SyncAllCounters() - GROUP BY with MAX and CAST
3. Any new lazy init query added for bd-64

**Implementation:**
- Use SQLite's EXPLAIN QUERY PLAN
- Parse output to verify no SCAN TABLE operations
- Add to sqlite_test.go

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


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

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

notes: 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.

issue_type: epic


title: Test performance - issue 1


title: Performance test 1


title: Performance test 2


title: Performance test 3


title: Performance test 4


title: Performance test 5


title: Performance test 6


title: Performance test 7


title: Reach 1.0 release milestone

description: Stabilize API, finalize documentation, comprehensive testing


title: Performance test 8


title: Performance test 9


title: Performance test 10


title: Add external_ref field for tracking GitHub issues

description: 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.


title: Auto-import fails in git workflows due to mtime issues

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

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

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


title: GH-1: Fix bd dep tree graph display issues

description: 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.


title: GH-2: Evaluate optional Turso backend for collaboration

description: 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.


title: GH-3: Debug zsh killed error on bd init

description: 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.


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

description: 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?


title: GH-6: Fix race condition in parallel issue creation

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


title: Build collision resolution tooling for distributed branch workflows

description: 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.


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

description: 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.


title: GH-9: Support markdown files in bd create

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


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

description: 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.


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

description: 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.


title: Test issue with explicit ID


title: Another explicit ID