* feat(daemon): unify auto-sync config for simpler agent workflows
## Problem
Agents running `bd sync` at session end caused delays in the Claude Code
"event loop", slowing development. The daemon was already auto-exporting
DB→JSONL instantly, but auto-commit and auto-push weren't enabled by
default when sync-branch was configured - requiring manual `bd sync`.
Additionally, having three separate config options (auto-commit, auto-push,
auto-pull) was confusing and could get out of sync.
## Solution
Simplify to two intuitive sync modes:
1. **Read/Write Mode** (`daemon.auto-sync: true` or `BEADS_AUTO_SYNC=true`)
- Enables auto-commit + auto-push + auto-pull
- Full bidirectional sync - eliminates need for manual `bd sync`
- Default when sync-branch is configured
2. **Read-Only Mode** (`daemon.auto-pull: true` or `BEADS_AUTO_PULL=true`)
- Only receives updates from team
- Does NOT auto-publish changes
- Useful for experimental work or manual review before sharing
## Benefits
- **Faster agent workflows**: No more `bd sync` delays at session end
- **Simpler config**: Two modes instead of three separate toggles
- **Backward compatible**: Legacy auto_commit/auto_push settings still work
(treated as auto-sync=true)
- **Adaptive `bd prime`**: Session close protocol adapts when daemon is
auto-syncing (shows simplified 4-step git workflow, no `bd sync`)
- **Doctor warnings**: `bd doctor` warns about deprecated legacy config
## Changes
- cmd/bd/daemon.go: Add loadDaemonAutoSettings() with unified config logic
- cmd/bd/doctor.go: Add CheckLegacyDaemonConfig call
- cmd/bd/doctor/daemon.go: Add CheckDaemonAutoSync, CheckLegacyDaemonConfig
- cmd/bd/init_team.go: Use daemon.auto-sync in team wizard
- cmd/bd/prime.go: Detect daemon auto-sync, adapt session close protocol
- cmd/bd/prime_test.go: Add stubIsDaemonAutoSyncing for testing
* docs: add comprehensive daemon technical analysis
Add daemon-summary.md documenting the beads daemon architecture,
memory analysis (explaining the 30-35MB footprint), platform support
comparison, historical problems and fixes, and architectural guidance
for other projects implementing similar daemon patterns.
Key sections:
- Architecture deep dive with component diagrams
- Memory breakdown (SQLite WASM runtime is the main contributor)
- Platform support matrix (macOS/Linux full, Windows partial)
- Historical bugs and their fixes with reusable patterns
- Analysis of daemon usefulness without database (verdict: low value)
- Expert-reviewed improvement proposals (3 recommended, 3 skipped)
- Technical design patterns for other implementations
* feat: add cross-platform CI matrix and dual-mode test framework
Cross-Platform CI:
- Add Windows, macOS, Linux matrix to catch platform-specific bugs
- Linux: full tests with race detector and coverage
- macOS: full tests with race detector
- Windows: full tests without race detector (performance)
- Catches bugs like GH#880 (macOS path casing) and GH#387 (Windows daemon)
Dual-Mode Test Framework (cmd/bd/dual_mode_test.go):
- Runs tests in both direct mode and daemon mode
- Prevents recurring bug pattern (GH#719, GH#751, bd-fu83)
- Provides DualModeTestEnv with helper methods for common operations
- Includes 5 example tests demonstrating the pattern
Documentation:
- Add dual-mode testing section to CONTRIBUTING.md
- Document RunDualModeTest API and available helpers
Test Fixes:
- Fix sync_local_only_test.go gitPull/gitPush calls
- Add gate_no_daemon_test.go for beads-70c4 investigation
* fix(test): isolate TestFindBeadsDir tests with BEADS_DIR env var
The tests were finding the real project's .beads directory instead of
the temp directory because FindBeadsDir() walks up the directory tree.
Using BEADS_DIR env var provides proper test isolation.
* fix(test): stop daemon before running test suite guard
The test suite guard checks that tests don't modify the real repo's .beads
directory. However, a background daemon running auto-sync would touch
issues.jsonl during test execution, causing false positives.
Changes:
- Set BEADS_NO_DAEMON=1 to prevent daemon auto-start from tests
- Stop any running daemon for the repo before taking the "before" snapshot
- Uses exec to call `bd daemon --stop` to avoid import cycle issues
* chore: revert .beads/issues.jsonl to upstream/main
Per CONTRIBUTING.md, .beads/issues.jsonl should not be modified in PRs.
Add CheckSyncDivergence doctor check that detects:
- JSONL on disk differs from git HEAD version
- SQLite last_import_time does not match JSONL mtime
- Uncommitted .beads/ changes exist
Each issue includes auto-fix suggestions (bd sync, bd export, git commit).
Multiple divergence issues result in error status.
Part of GH#885 recovery mechanism.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
When not in a git repository:
- Daemon startup now shows clear message immediately instead of waiting
5 seconds: "Note: No git repository initialized — running without
background sync"
- Added new doctor check "Git Sync Setup" that explains the situation
Doctor check now shows three states:
1. No git repo → Warning with fix: "Run 'git init' to enable background sync"
2. Git repo, no sync-branch → OK with hint about team collaboration benefits
3. Git repo + sync-branch → OK, fully configured
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
When sync.branch is configured, issues.jsonl appears modified in git status
even though changes go to the sync branch. This is confusing for users and
risks accidental commits to the wrong branch.
Implementation:
- Added SyncBranchGitignore() to set git index flags (assume-unchanged,
skip-worktree) on issues.jsonl when sync.branch is configured
- For untracked files, adds to .git/info/exclude instead
- Called automatically from bd sync after successful sync-branch sync
- Added bd doctor check and fix for this issue
- Added HasSyncBranchGitignoreFlags() to check current flag state
- Added ClearSyncBranchGitignore() to remove flags when sync.branch disabled
Fixes: GH#870 (duplicate of GH#797, GH#801)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Executed-By: beads/crew/dave
Rig: beads
Role: crew
Add support for Gemini CLI hook-based integration, similar to Claude Code:
- bd setup gemini: Install SessionStart/PreCompress hooks
- bd setup gemini --check: Verify installation
- bd setup gemini --remove: Remove hooks
- bd setup gemini --project: Project-only installation
- bd setup gemini --stealth: Use bd prime --stealth
Also adds Gemini CLI integration check to bd doctor.
Gemini CLI's hook system is nearly identical to Claude Code's,
making this a clean, low-maintenance addition.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add redirect to GitignoreTemplate with explanatory comment
- Add redirect to requiredPatterns for outdated gitignore detection
- Add CheckRedirectNotTracked() to detect already-tracked redirect files
- Add FixRedirectTracking() to untrack via git rm --cached
- Register check in bd doctor under Git Integration category
- Add 6 tests for the new functionality
The redirect file contains a relative path that only works in the
original worktree. When committed, it causes warnings in other clones:
"Warning: redirect target does not exist"
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Completes the work from #813 by actually calling the new functions:
- Add Check 14b in doctor.go for redirect file tracking detection
- Add Redirect Not Tracked case in doctor_fix.go switch statement
Without this wiring, bd doctor would not detect or fix already-tracked
redirect files, only prevent new ones via the updated .gitignore template.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Executed-By: beads/crew/dave
Rig: beads
Role: crew
Add comprehensive database corruption recovery capabilities to bd doctor.
## Changes
### New Command Flags
- --force: Force repair mode that bypasses database validation
- --source: Choose source of truth (auto/jsonl/db) for recovery
### Enhanced Error Classification
Improved CheckDatabaseIntegrity() to detect and classify:
- Database locked errors (suggests killing processes, removing locks)
- Invalid SQLite files (suggests JSONL recovery with exact commands)
- Migration/validation failures (orphaned dependencies, etc.)
- Generic database errors (context-aware suggestions)
Each error type provides:
- Specific diagnosis
- Step-by-step recovery instructions
- Appropriate command examples with new flags
### Force Recovery Implementation
New DatabaseCorruptionRecoveryWithOptions() function:
- Bypasses database validation when --force is used
- Supports explicit source of truth selection
- Auto-detects best recovery path when source=auto
- Comprehensive rollback on failure
- Uses --force --no-git-history in import during force mode
### Integration
Updated fix orchestration to pass force and source flags to recovery.
## Usage Examples
```bash
# Unopenable database with validation errors
bd doctor --fix --force --source=jsonl
# Choose specific source of truth
bd doctor --fix --source=jsonl # Trust JSONL
bd doctor --fix --source=db # Trust database
bd doctor --fix --source=auto # Auto-detect (default)
# Force recovery with auto-detection
bd doctor --fix --force
```
## Problem Solved
Before: When database had validation errors (orphaned dependencies,
foreign key violations), all bd commands failed in a catch-22 situation.
Could not open database to fix database. Users had to manually delete
database files and reinit.
After: bd doctor --fix --force detects unopenable databases, provides
clear recovery steps, and forces rebuild from JSONL even when database
validation fails.
## Backward Compatibility
- All new flags are optional with safe defaults
- --source defaults to 'auto' (existing behavior)
- --force is opt-in only
- Existing bd doctor behavior unchanged when flags not used
- DatabaseCorruptionRecovery() still exists for compatibility
Fixes: bd-pgza
Safeguard for users with global gitignore patterns like *.jsonl that
could cause issues.jsonl to be ignored, breaking bd sync.
The check runs git check-ignore and warns if issues.jsonl would be
ignored by any gitignore rule (global, parent directory, etc).
- Add resolveBeadsDir helper to fix/common.go to follow redirect files
- Update OrphanedDependencies, ChildParentDependencies, and MergeArtifacts
to use resolveBeadsDir instead of hardcoded .beads path
- Add --verbose/-v flag to bd doctor command
- Only print individual items if verbose or count < 20, always show summary
(bd-dq74, bd-v55y)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Strip (bd-xxx), (gt-xxx) suffixes from code comments and changelog
entries. The descriptions remain meaningful without the ephemeral
issue IDs.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add a --deep flag to bd doctor that runs comprehensive graph integrity
checks on the beads database:
- Parent consistency: verify parent-child deps point to existing issues
- Dependency integrity: all dependencies reference valid issues
- Epic completeness: find epics ready to close (all children closed)
- Agent bead integrity: validate agent beads have valid state values
- Mail thread integrity: verify thread_id references exist
- Molecule integrity: check molecules have valid parent-child structures
The deep validation mode warns about potential slowness on large databases
and provides both human-readable and JSON output formats.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add Phase field to Formula type to indicate recommended instantiation phase
- Add warning in 'bd mol pour' when formula has phase="vapor"
- Improve pour/wisp help text with clear comparison of when to use each
- Add CheckPersistentMolIssues doctor check to detect mol- issues in JSONL
- Update beads-release.formula.json with phase="vapor"
This helps prevent accidental persistence of ephemeral workflow issues.
- Add --check flag to doctor for specific check modes
- Add --check=pollution to run detailed pollution detection
- Add --clean flag to delete detected test issues
- Mark detect-pollution command as hidden (deprecated)
- Update fix messages to point to new doctor --check=pollution
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Analysis found these commands are dead code:
- gt never calls `bd pin` - uses `bd update --status=pinned` instead
- Beads.Pin() wrapper exists but is never called
- bd hook functionality duplicated by gt mol status
- Code comment says "pinned field is cosmetic for bd hook visibility"
Removed:
- cmd/bd/pin.go
- cmd/bd/unpin.go
- cmd/bd/hook.go
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Adds automatic database recovery when bd doctor --fix detects corruption:
- Detects SQLite corruption (malformed database, SQLITE_CORRUPT errors)
- Backs up corrupted database before recovery attempt
- Rebuilds from JSONL if available (issues.jsonl, deletions.jsonl)
- Falls back to fresh database if JSONL unavailable
- Reports recovery results (issues imported, success/failure)
Recovery is triggered automatically by --fix when corruption is detected.
No manual intervention required.
GH#740: bd doctor --fix was auto-removing child→parent dependencies,
calling them an 'anti-pattern'. While these often indicate modeling
mistakes (deadlock), they may be intentional in some workflows.
Changes:
- Add --fix-child-parent flag (required to remove child→parent deps)
- Remove ChildParentDependencies from default --fix set
- Update warning message to reference new flag
- Update comments to reflect more nuanced understanding
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Extends bd doctor to detect complete-but-unclosed molecules (epics where
all children are closed but root is still open).
- Added CheckStaleMolecules() to doctor/maintenance.go
- Added resolveBeadsDir() helper to follow Gas Town redirect files
- Check appears in Maintenance category with warning severity
- Shows example IDs and suggests 'bd mol stale' for review
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This prevents a common mistake where users add dependencies from child
issues to their parent epics. This creates a deadlock:
- Child can't start (blocked by open parent)
- Parent can't close (children not done)
Changes:
- dep.go: Reject child→parent deps at creation time with clear error
- server_labels_deps_comments.go: Same check for daemon RPC
- doctor/validation.go: New check detects existing bad deps
- doctor/fix/validation.go: Auto-fix removes bad deps
- doctor.go: Wire up check and fix handler
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add --verbose/-v flag to show all checks including passed
- Show summary at top with counts (passed/warnings/errors)
- Default mode collapses passed checks with hint to use --verbose
- Group passed checks by category in verbose mode
- Errors shown first, then warnings, then passed
- Visual separators between sections
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
feat(doctor): add count-based database size check
Adds CheckDatabaseSize (Check 29) that warns when closed issues exceed a configurable threshold (default: 5000). The check is informational only - no auto-fix since pruning is destructive.
Also improves fix guidance for sync-branch hook compatibility and legacy JSONL filename checks.
PR #724 by @rsnodgrass
Add new Maintenance category to bd doctor with checks for:
- Stale closed issues (older than 30 days)
- Expired tombstones (older than TTL)
- Compaction candidates (info only)
Add fix handlers for cleanup and tombstone pruning via bd doctor --fix.
Add deprecation hints to cleanup, compact, and detect-pollution commands
suggesting users try bd doctor instead.
This consolidation reduces cognitive load - users just need to remember
'bd doctor' for health checks and 'bd doctor --fix' for maintenance.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Modernize sorting code to use Go 1.21+ slices package:
- Replace sort.Slice with slices.SortFunc across 16 files
- Use cmp.Compare for orderable types (strings, ints)
- Use time.Time.Compare for time comparisons
- Use cmp.Or for multi-field sorting
- Use slices.SortStableFunc where stability matters
Benefits: cleaner 3-way comparison, slightly better performance,
modern idiomatic Go.
Part of GH#692 refactoring epic.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* fix(doctor): UX improvements for diagnostics and daemon
- Add Repo Fingerprint check to detect when database belongs to a
different repository (copied .beads dir or git remote URL change)
- Add interactive fix for repo fingerprint with options: update repo ID,
reinitialize database, or skip
- Add visible warning when daemon takes >5s to start, recommending
'bd doctor' for diagnosis
- Detect install method (Homebrew vs script) and show only relevant
upgrade command
- Improve WARNINGS section:
- Add icons (⚠ or ✖) next to each item
- Color numbers by severity (yellow for warnings, red for errors)
- Render entire error lines in red
- Sort by severity (errors first)
- Fix alignment with checkmarks above
- Use heavier fail icon (✖) for better visibility
- Add integration and validation tests for doctor fixes
* fix(lint): address errcheck and gosec warnings
- mol_bond.go: explicitly ignore ephStore.Close() error
- beads.go: add nosec for .gitignore file permissions (0644 is standard)
- Add CheckOrphanedIssues to detect issues referenced in commits but still open
- Pattern matches (prefix-xxx) in git log against open issues in database
- Reports warning with issue IDs and commit hashes
- Add 8 comprehensive tests for the new check
Also:
- Add tests for mol spawn --attach functionality (bd-f7p1)
- Document commit message convention in AGENT_INSTRUCTIONS.md
- Fix CheckpointWAL to use wrapDBError for consistency
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Replace all fatih/color usages with internal/ui package that provides:
- Semantic color tokens (Pass, Warn, Fail, Accent, Muted)
- Adaptive light/dark mode support via Lipgloss AdaptiveColor
- Ayu theme colors for consistent, accessible output
- Tufte-inspired data-ink ratio principles
Files migrated: 35 command files in cmd/bd/
Add docs/ui-philosophy.md documenting:
- Semantic token usage guidelines
- Light/dark terminal optimization rationale
- Tufte and perceptual UI/UX theory application
- When to use (and not use) color in CLI output
* test(doctor): add comprehensive tests for fix and check functions
Add edge case tests, e2e tests, and improve test coverage for:
- database_test.go: database integrity and sync checks
- git_test.go: git hooks, merge driver, sync branch tests
- gitignore_test.go: gitignore validation
- prefix_test.go: ID prefix handling
- fix/fix_test.go: fix operations
- fix/e2e_test.go: end-to-end fix scenarios
- fix/fix_edge_cases_test.go: edge case handling
* docs: add testing philosophy and anti-patterns guide
- Create TESTING_PHILOSOPHY.md covering test pyramid, priority matrix,
what NOT to test, and 5 anti-patterns with code examples
- Add cross-reference from README_TESTING.md
- Document beads-specific guidance (well-covered areas vs gaps)
- Include target metrics (test-to-code ratio, execution time targets)
* chore: revert .beads/ to upstream/main state
* refactor(doctor): add category grouping and Ayu theme colors
- Add Category field to DoctorCheck for organizing checks by type
- Define category constants: Core, Git, Runtime, Data, Integration, Metadata
- Update thanks command to use shared Ayu color palette from internal/ui
- Simplify test fixtures by removing redundant test cases
* fix(doctor): prevent test fork bomb and fix test failures
- Add ErrTestBinary guard in getBdBinary() to prevent tests from
recursively executing the test binary when calling bd subcommands
- Update claude_test.go to use new check names (CLI Availability,
Prime Documentation)
- Fix syncbranch test path comparison by resolving symlinks
(/var vs /private/var on macOS)
- Fix permissions check to use exact comparison instead of bitmask
- Fix UntrackedJSONL to use git commit --only to preserve staged changes
- Fix MergeDriver edge case test by making both .git dir and config
read-only
- Add skipIfTestBinary helper for E2E tests that need real bd binary
* test(doctor): skip read-only config test in CI environments
GitHub Actions containers may have CAP_DAC_OVERRIDE or similar
capabilities that allow writing to read-only files, causing
the test to fail. Skip the test when CI=true or GITHUB_ACTIONS=true.
* refactor(doctor): split doctor.go into modular package files
Split the 3,171-line doctor.go into logical sub-files within the
cmd/bd/doctor/ package, reducing the main file to 834 lines (74% reduction).
New package structure:
- types.go: DoctorCheck struct and status constants
- installation.go: CheckInstallation, CheckMultipleDatabases, CheckPermissions
- git.go: CheckGitHooks, CheckMergeDriver, CheckSyncBranch* checks
- database.go: CheckDatabaseVersion, CheckSchemaCompatibility, CheckDatabaseJSONLSync
- version.go: CheckCLIVersion, CheckMetadataVersionTracking, CompareVersions
- integrity.go: CheckIDFormat, CheckDependencyCycles, CheckTombstones
- daemon.go: CheckDaemonStatus, CheckVersionMismatch
- quick.go: Quick checks for sync-branch and hooks
Updated tests to use exported doctor.CheckXxx() functions and
doctor.StatusXxx constants.
* fix(doctor): suppress gosec G204 false positives
Add #nosec G204 comments to exec.Command calls in CheckSyncBranchHealth
where variables come from trusted sources (config files or hardcoded
values like "main"/"master"/"origin"), not untrusted user input.
When sync.branch is set to the current branch (e.g., main), bd sync
now commits directly instead of failing with a worktree error.
Changes:
- sync.go: Detect when current branch == sync branch and skip worktree
- sync.go: Show appropriate messages for direct-mode commits/pulls
- doctor.go: Change from Error to OK status when on sync branch
The fix allows users to work directly on the sync branch without
having to switch to a different branch for bd sync to work.
Closes: GH#519
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
When `bd doctor --fix` fails to apply a fix, it was showing
"Manual fix: Run 'bd doctor --fix' ..." which is circular and unhelpful.
Now extracts just the manual command from the fix message:
- "..., or manually: <cmd>" -> extracts <cmd>
- "bd doctor --fix or <alt>" -> extracts <alt>
- No alternative available -> shows nothing
Closes GH#403
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
When bd doctor detects legacy deletions.jsonl, --fix now runs the
tombstone migration automatically instead of requiring users to
manually run bd migrate-tombstones.
This makes the migration smoother for multi-clone scenarios where
only one clone needs to do the actual migration, but other clones
may still have local deletions.jsonl files that need cleanup.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Extract two helper functions from checkSyncBranchHookQuick and
checkSyncBranchHookCompatibility to reduce code duplication:
1. getPrePushHookPath(path) - resolves pre-push hook path handling
both standard .git/hooks and shared hooks via core.hooksPath
2. extractBdHookVersion(content) - parses version from hook content
looking for bd-hooks-version: marker
Also documented the intentional behavior difference:
- Quick check: returns OK for custom hooks (silent)
- Full check: returns Warning for custom hooks (user awareness)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>