126 Commits

Author SHA1 Message Date
gastown/crew/joe
a93c32b425 fix(dolt): add hook compatibility check and migration warning
Two improvements for Dolt backend users with stale git hooks:

1. Migration warning: When running 'bd migrate --to-dolt', warn if
   installed hooks lack the Dolt backend check and suggest reinstalling.

2. Doctor check: New CheckGitHooksDoltCompatibility() detects when
   hooks exist but lack the Dolt skip logic, surfacing the error with
   a clear fix message.

Both changes help users who migrated to Dolt but have pre-migration
hooks that try to run JSONL sync (which fails with Dolt backend).

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 11:54:30 -08:00
Peter Chanthamynavong
b7d650bd8e fix(init): respect BEADS_DIR environment variable (#1273)
* fix(sync): read sync.mode from yaml first, then database

bd config set sync.mode writes to config.yaml (because sync.* is a
yaml-only prefix), but GetSyncMode() only read from the database.

This caused dolt-native mode to be ignored - JSONL export still
happened because the database had no sync.mode value.

Now GetSyncMode() checks config.yaml first (via config.GetSyncMode()),
falling back to database for backward compatibility.

Fixes: oss-5ca279

* fix(init): respect BEADS_DIR environment variable

Problem:
- `bd init` ignored BEADS_DIR when checking for existing data
- `bd init` created database at CWD/.beads instead of BEADS_DIR
- Contributor wizard used ~/.beads-planning as default, ignoring BEADS_DIR

Solution:
- Add BEADS_DIR check in checkExistingBeadsData() (matches FindBeadsDir pattern)
- Compute beadsDirForInit early, before initDBPath determination
- Use BEADS_DIR as default in contributor wizard when set
- Preserve precedence: --db > BEADS_DB > BEADS_DIR > default

Impact:
- Users with BEADS_DIR set now get consistent behavior across all bd commands
- ACF-style fork tracking (external .beads directory) now works correctly

Fixes: steveyegge/beads#???

* fix(doctor): respect BEADS_DIR environment variable

Also updates documentation to reflect BEADS_DIR support in init and doctor.

Changes:
- doctor.go: Check BEADS_DIR before falling back to CWD
- doctor_test.go: Add tests for BEADS_DIR path resolution
- WORKTREES.md: Document simplified BEADS_DIR+init workflow
- CONTRIBUTOR_NAMESPACE_ISOLATION.md: Note init/doctor BEADS_DIR support

* test(init): add BEADS_DB > BEADS_DIR precedence test

Verifies that BEADS_DB env var takes precedence over BEADS_DIR
when both are set, ensuring the documented precedence order:
--db > BEADS_DB > BEADS_DIR > default

* chore: fill in GH#1277 placeholder in sync_mode comment
2026-01-24 17:10:05 -08:00
beads/crew/emma
66d994264b feat(doctor): add --server flag for Dolt server mode health checks (bd-dolt.2.3)
Adds bd doctor --server to diagnose Dolt server mode connections:
- Server reachability (TCP connect to host:port)
- Dolt version check (verifies it is Dolt, not vanilla MySQL)
- Database exists and is accessible
- Schema compatible (can query beads tables)
- Connection pool health metrics

Supports --json for machine-readable output.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 20:29:12 -08:00
Steve Yegge
be306b6c66 fix(routing): auto-enable hydration and flush JSONL after routed create (#1251)
* fix(routing): auto-enable hydration and flush JSONL after routed create

Fixes split-brain bug where issues routed to different repos (via routing.mode=auto)
weren't visible in bd list because JSONL wasn't updated and hydration wasn't configured.

**Problem**: When routing.mode=auto routes issues to a separate repo (e.g., ~/.beads-planning),
those issues don't appear in 'bd list' because:
1. Target repo's JSONL isn't flushed after create
2. Multi-repo hydration (repos.additional) not configured automatically
3. No doctor warnings about the misconfiguration

**Changes**:

1. **Auto-flush JSONL after routed create** (cmd/bd/create.go)
   - After routing issue to target repo, immediately flush to JSONL
   - Tries target daemon's export RPC first (if daemon running)
   - Falls back to direct JSONL export if no daemon
   - Ensures hydration can read the new issue immediately

2. **Enable hydration in bd init --contributor** (cmd/bd/init_contributor.go)
   - Wizard now automatically adds planning repo to repos.additional
   - Users no longer need to manually run 'bd repo add'
   - Routed issues appear in bd list immediately after setup

3. **Add doctor check for hydrated repo daemons** (cmd/bd/doctor/daemon.go)
   - New CheckHydratedRepoDaemons() warns if daemons not running
   - Without daemons, JSONL becomes stale and hydration breaks
   - Suggests: cd <repo> && bd daemon start --local

4. **Add doctor check for routing+hydration mismatch** (cmd/bd/doctor/config_values.go)
   - Validates routing targets are in repos.additional
   - Catches split-brain configuration before users encounter it
   - Suggests: bd repo add <routing-target>

**Testing**: Builds successfully. Unit/integration tests pending.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* test(routing): add comprehensive tests for routing fixes

Add unit tests for all 4 routing/hydration fixes:

1. **create_routing_flush_test.go** - Test JSONL flush after routing
   - TestFlushRoutedRepo_DirectExport: Verify direct JSONL export
   - TestPerformAtomicExport: Test atomic file operations
   - TestFlushRoutedRepo_PathExpansion: Test path handling
   - TestRoutingWithHydrationIntegration: E2E routing+hydration test

2. **daemon_test.go** - Test hydrated repo daemon check
   - TestCheckHydratedRepoDaemons: Test with/without daemons running
   - Covers no repos, daemons running, daemons missing scenarios

3. **config_values_test.go** - Test routing+hydration validation
   - Test routing without hydration (should warn)
   - Test routing with correct hydration (should pass)
   - Test routing target not in hydration list (should warn)
   - Test maintainer="." edge case (should pass)

All tests follow existing patterns and use t.TempDir() for isolation.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix(tests): fix test failures and refine routing validation logic

Fixes test failures and improves validation accuracy:

1. **Fix routing+hydration validation** (config_values.go)
   - Exclude "." from hasRoutingTargets check (current repo doesn't need hydration)
   - Prevents false warnings when maintainer="." or contributor="."

2. **Fix test ID generation** (create_routing_flush_test.go)
   - Use auto-generated IDs instead of hard-coded "beads-test1"
   - Respects test store prefix configuration (test-)
   - Fixed json.NewDecoder usage (file handle, not os.Open result)

3. **Fix config validation tests** (config_values_test.go)
   - Create actual directories for routing paths to pass path validation
   - Tests now verify both routing+hydration AND path existence checks

4. **Fix daemon test expectations** (daemon_test.go)
   - When database unavailable, check returns "No additional repos" not error
   - This is correct behavior (graceful degradation)

All tests now pass:
- TestFlushRoutedRepo* (3 tests)
- TestPerformAtomicExport
- TestCheckHydratedRepoDaemons (3 subtests)
- TestCheckConfigValues routing tests (5 subtests)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* docs: clarify when git config beads.role maintainer is needed

Clarify that maintainer role config is only needed in edge case:
- Using GitHub HTTPS URL without credentials
- But you have write access (are a maintainer)

In most cases, beads auto-detects correctly via:
- SSH URLs (git@github.com:owner/repo.git)
- HTTPS with credentials

This prevents confusion - users with SSH or credential-based HTTPS
don't need to manually configure their role.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix(lint): address linter warnings in routing flush code

- Add missing sqlite import in daemon.go
- Fix unchecked client.Close() error return
- Fix unchecked tempFile.Close() error returns
- Mark unused parameters with _ prefix
- Add nolint:gosec for safe tempPath construction

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Roland Tritsch <roland@ailtir.com>
Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-21 21:22:04 -08:00
emma
4a0f4abc70 feat(doctor): add patrol pollution detection and fix
Add CheckPatrolPollution to detect stale patrol beads:
- Patrol digests matching 'Digest: mol-*-patrol'
- Session ended beads matching 'Session ended: *'

Includes auto-fix via 'bd doctor --fix' to clean up pollution.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-20 23:15:37 -08:00
emma
1a7f8efc9e feat(doctor): add federation health checks (bd-wkumz.6)
Add 5 federation health checks:
- CheckFederationRemotesAPI: verifies remotesapi port accessibility
- CheckFederationPeerConnectivity: checks peer remote reachability
- CheckFederationSyncStaleness: detects commits behind peers
- CheckFederationConflicts: detects unresolved merge conflicts
- CheckDoltServerModeMismatch: detects embedded vs server mode mismatch

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-20 23:13:02 -08:00
Roland Tritsch
09355eee8c Add --gastown flag to bd doctor for gastown-specific checks (#1162)
When running in gastown multi-workspace mode, two checks produce false
positives that are expected behavior:

1. routes.jsonl is a valid configuration file (maps issue prefixes to
   rig directories), not a duplicate JSONL file
2. Duplicate issues are expected (ephemeral wisps from patrol cycles)
   and normal up to ~1000, with GC cleaning them up automatically

This commit adds flags to bd doctor for gastown-specific checks:
- --gastown: Skip routes.jsonl warning and enable duplicate threshold
- --gastown-duplicates-threshold=N: Set duplicate tolerance (default 1000)

Fixes false positive warnings:
  Multiple JSONL files found: issues.jsonl, routes.jsonl
  70 duplicate issue(s) in 30 group(s)

Changes:
- Add --gastown flag to bd doctor command
- Add --gastown-duplicates-threshold flag (default: 1000)
- Update CheckLegacyJSONLFilename to skip routes.jsonl when gastown mode active
- Update CheckDuplicateIssues to use configurable threshold when gastown mode active
- Add test cases for gastown mode behavior with various thresholds

Co-authored-by: Roland Tritsch <roland@ailtir.com>
Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-20 14:06:53 -08:00
Peter Chanthamynavong
460d2bf113 fix(doctor): improve diagnostic fix message output (#1187)
Problem:
- Diagnostic fix messages were restricted to single lines
- Inconsistent file path formatting in database sync issues
- Outdated cleanup command suggested in maintenance fixes

Solution:
- Implement multiline support for doctor fix messages
- Standardize issue file paths across database diagnostics
- Update maintenance fix instructions to use 'bd admin cleanup'

Impact:
- Clearer and more accurate recovery instructions for users
- Better readability of complex diagnostic output

Fixes: GH#1170, GH#1171, GH#1172
2026-01-19 10:10:57 -08:00
beads/crew/dave
3298c45e4b fix(sync): handle redirect + sync-branch incompatibility (bd-wayc3)
When a crew worker's .beads/ is redirected to another repo, bd sync
now detects this and skips all git operations (sync-branch worktree
manipulation). Instead, it just exports to JSONL and lets the target
repo's owner handle the git sync.

Changes:
- sync.go: Detect redirect early, skip git operations when active
- beads.go: Update GetRedirectInfo() to check git repo even when
  BEADS_DIR is pre-set (findLocalBdsDirInRepo helper)
- validation.go: Add doctor check for redirect + sync-branch conflict
- doctor.go: Register new check, remove undefined CheckMisclassifiedWisps

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

Executed-By: beads/crew/dave
Rig: beads
Role: crew
2026-01-14 20:36:30 -08:00
dennis
f703237c3d fix(ready): prevent wisps from appearing in bd ready
Add multiple layers of defense against misclassified wisps:
- Importer auto-detects -wisp- pattern and sets ephemeral flag
- GetReadyWork excludes -wisp- IDs via SQL LIKE clause
- Doctor check 26d detects misclassified wisps in JSONL

This addresses recurring issue where wisps with missing ephemeral
flag would pollute bd ready output after JSONL import.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-13 00:14:12 -08:00
beads/crew/emma
66c5c4d805 feat(doctor): add check for stale .beads/mq/ files (bd-dx2dc)
Add bd doctor check that detects legacy gastown merge queue JSON files
in .beads/mq/. These files are local-only remnants from the old mrqueue
implementation and can safely be deleted since gt done already creates
merge-request wisps in beads.

- CheckStaleMQFiles() detects .beads/mq/*.json files
- FixStaleMQFiles() removes the entire mq directory
- Comprehensive tests for check and fix

This is the first step toward removing the mrqueue side-channel from
gastown. The follow-up convoy will update Refinery/Witness to use
beads exclusively.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-12 19:42:51 -08:00
beads/crew/emma
3854bb29e9 feat(doctor): add check for last-touched file tracking
Add bd doctor check that warns if .beads/last-touched is tracked by git.
This file is local runtime state that should never be committed, as it
causes spurious diffs in other clones.

- CheckLastTouchedNotTracked() detects if file is git-tracked
- FixLastTouchedTracking() untracks with git rm --cached
- Comprehensive tests for all scenarios

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-12 19:37:57 -08:00
Steve Yegge
5a772dca44 feat(doctor): add redirect configuration health checks
Add three new bd doctor checks for redirect configuration health:

1. CheckRedirectTargetValid - Verifies redirect target exists and
   contains a valid beads database

2. CheckRedirectTargetSyncWorktree - Verifies redirect target has
   beads-sync worktree when using sync-branch mode

3. CheckNoVestigialSyncWorktrees - Detects unused .beads-sync
   worktrees in redirected repos that waste space

These checks help diagnose redirect configuration issues in
multi-clone setups like Gas Town polecats and crew workspaces.

Closes bd-b88x3

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 21:30:05 -08:00
beads/crew/emma
d452d32644 feat(doctor): add multi-repo custom types discovery (bd-62g22)
Adds a diagnostic check that discovers and reports custom types
used by child repos in multi-repo setups. This is the 'discover'
part of the 'trust + discover' pattern for federation.

The check:
- Lists custom types found in each child repo's config/DB
- Warns about hydrated issues using types not found anywhere
- Is informational only (doesn't fail overall doctor check)

Part of epic: bd-9ji4z

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-09 14:26:32 -08:00
Ryan
ffe0dca2a3 feat(daemon): unify auto-sync config for simpler agent workflows (#904)
* 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.
2026-01-06 12:52:19 -08:00
beads/crew/wolf
68f5bb24f8 feat(doctor): add sync divergence check for JSONL/SQLite/git (GH#885)
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>
2026-01-04 15:13:50 -08:00
kustrun
28b44edd13 fix(doctor): detect missing git repo and improve daemon startup message (#890)
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>
2026-01-04 11:13:48 -08:00
dave
6a5c289af3 fix: hide issues.jsonl from git status when sync.branch configured (GH#870)
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
2026-01-03 21:07:32 -08:00
beads/crew/wolf
a06b40bd48 feat: add bd setup gemini for Gemini CLI integration (#845)
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>
2026-01-02 00:02:38 -08:00
Steve Yegge
310d374264 fix: prevent .beads/redirect from being committed (GH#814)
- 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>
2025-12-30 18:29:03 -08:00
Steve Yegge
38a6097512 fix(doctor): wire up CheckRedirectNotTracked and FixRedirectTracking
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
2025-12-30 18:01:58 -08:00
Steve Yegge
c86bffc045 Merge pull request #805 from kraitsura/feature/bd-doctor-enhancements
feat: Enhance bd doctor with force repair and source selection
2025-12-30 10:34:41 -08:00
Steve Yegge
fb5fd88722 feat: integrate migration detection into bd doctor (bd-7l27)
Add a consolidated "Pending Migrations" check to bd doctor that:
- Detects sequential ID usage (suggests bd migrate hash-ids)
- Detects legacy deletions.jsonl (suggests bd migrate tombstones)
- Detects missing sync-branch config (suggests bd migrate sync)
- Detects database version mismatches (suggests bd migrate)

Also updates existing checks to use correct modern commands:
- CheckIDFormat: bd migrate hash-ids (was bd migrate --to-hash-ids)
- CheckDeletionsManifest: bd migrate tombstones (was bd migrate-tombstones)
- CheckSyncBranchConfig: bd migrate sync beads-sync (was config.yaml edit)

Removes TODO(bd-7l27) comments from migrate_*.go files.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-30 00:06:42 -08:00
kraitsura
602c59eb48 feat: Enhance bd doctor with force repair and source selection
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
2025-12-29 22:59:48 -08:00
Steve Yegge
2b90f51d0c feat: add doctor check for issues.jsonl git tracking (GH#796)
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).
2025-12-29 20:58:30 -08:00
Steve Yegge
24966bd1ce fix: Handle .beads/redirect files and limit verbose output in bd doctor --fix
- 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>
2025-12-29 12:59:19 -08:00
Steve Yegge
6c14fd2225 refactor: Split large cmd/bd files to meet 800-line limit (bd-xtf5)
Split 6 files exceeding 800 lines by extracting cohesive function groups:

- show.go (1592→578): extracted show_thread.go, close.go, edit.go, update.go
- doctor.go (1295→690): extracted doctor_fix.go, doctor_health.go, doctor_pollution.go
- sync.go (1201→749): extracted sync_git.go
- compact.go (1199→775): extracted compact_tombstone.go, compact_rpc.go
- linear.go (1190→641): extracted linear_sync.go, linear_conflict.go
- main.go (1148→800): extracted main_help.go, main_errors.go, main_daemon.go

All files now under 800-line acceptance criteria.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-28 18:43:09 -08:00
Steve Yegge
f46cc2e798 chore: remove issue ID references from comments and changelogs
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>
2025-12-28 10:05:16 -08:00
Steve Yegge
f3c663d31c feat: add bd doctor --deep for full graph integrity validation (bd-cwpl)
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>
2025-12-28 02:13:34 -08:00
Steve Yegge
dfc796589f feat: add pour warning for vapor-phase formulas, improve help text, add doctor check
- 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.
2025-12-28 01:34:01 -08:00
Steve Yegge
2c82acd10b feat: integrate detect-pollution into bd doctor --check=pollution (bd-kff0)
- 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>
2025-12-27 16:20:12 -08:00
Steve Yegge
1611f16751 refactor: remove unused bd pin/unpin/hook commands (bd-x0zl)
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>
2025-12-27 16:02:15 -08:00
Steve Yegge
c8b912cbe6 bd sync: 2025-12-27 15:56:42 2025-12-27 15:56:42 -08:00
Steve Yegge
05304e3ab1 Merge origin/main, fix test git init for modern git 2025-12-27 00:17:36 -08:00
Ryan Snodgrass
721ae70ccb feat(doctor): add database corruption recovery to --fix
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.
2025-12-26 18:55:07 -05:00
Jordan Hubbard
8166207eb4 doctor: add JSONL integrity check/fix and harden repairs
Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
2025-12-26 08:18:25 -04:00
Jordan Hubbard
1a4f06ef8c doctor: harden corruption repair and JSONL config
Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
2025-12-26 04:29:29 -04:00
Jordan Hubbard
1184bd1e59 doctor: add git hygiene checks and DB integrity auto-fix
Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
2025-12-25 21:35:44 -04:00
Steve Yegge
d2b1656c5d fix: Make child→parent dep fix opt-in with --fix-child-parent (bd-cuek)
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>
2025-12-25 14:05:55 -08:00
Steve Yegge
29501c7aeb feat: Add stale molecules check to bd doctor (bd-6a5z)
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>
2025-12-25 12:42:55 -08:00
Steve Yegge
ce2b05356a feat(deps): detect/prevent child→parent dependency anti-pattern (bd-nim5)
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>
2025-12-24 13:03:27 -08:00
Steve Yegge
e67f27c092 bd sync: 2025-12-23 23:38:57 2025-12-24 00:06:41 -08:00
Steve Yegge
2de1695615 bd sync: 2025-12-23 22:33:32 2025-12-23 22:33:33 -08:00
Steve Yegge
cf9e5a597b bd sync: 2025-12-23 20:50:50 2025-12-23 20:50:50 -08:00
Steve Yegge
9c8761abc9 bd sync: 2025-12-23 20:45:19 2025-12-23 20:45:19 -08:00
Steve Yegge
7b671662aa bd sync: 2025-12-23 13:49:07 2025-12-23 14:39:07 -08:00
Steve Yegge
81181994eb Improve bd doctor output formatting for readability (bd-4qfb)
- 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>
2025-12-23 13:39:03 -08:00
Ryan
297c696336 feat(doctor): add count-based database size check (#724)
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
2025-12-23 13:29:35 -08:00
Steve Yegge
aa1ce63156 feat: consolidate maintenance commands into bd doctor --fix (bd-bqcc)
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>
2025-12-23 01:31:18 -08:00
Ryan Snodgrass
cafc0b9dfb refactor(doctor): consolidate maintenance commands + improve daemon startup
Consolidate clean, repair-deps, validate into bd doctor:
- Add validation checks to doctor (merge artifacts, orphaned deps, duplicates, test pollution, git conflicts)
- Add auto-fix for merge artifacts and orphaned dependencies
- Delete obsolete command files: clean.go, repair_deps.go, validate.go
- Delete orphaned test files: clean_security_test.go, validate_test.go

Improve daemon startup performance:
- Add fast-fail detection when daemon crashed (check lock before retrying)
- Reduce graceful shutdown timeout from 5s to 1s
- Skip daemon connection for root command (just shows help)
- Extract shutdown timeout as constants (daemonShutdownTimeout, daemonShutdownPollInterval)

Other changes:
- Move rename-prefix command to Maintenance group in help
- Fix Makefile to inject git commit hash via ldflags

New files:
- cmd/bd/doctor/validation.go (5 check functions)
- cmd/bd/doctor/fix/validation.go (2 fix functions)
2025-12-22 20:21:30 -08:00