Moved snapshot cleanup call to the end of successful sync, outside the
!noPull block. This ensures snapshot files (beads.base.jsonl, beads.left.jsonl)
are removed even when --no-pull is used.
Previously, captureLeftSnapshot was called before the pull block, but
cleanup was only inside the pull block, leaving orphaned files when
--no-pull was used.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Add cleanup call at end of successful sync to ensure snapshot files
(beads.base.jsonl, beads.left.jsonl) are removed even when --no-pull
is used. Previously, captureLeftSnapshot was called before the pull
block, but cleanup was only inside the !noPull block, leaving orphaned
files.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Add CloseReason field to Issue struct in types.go
- Add GetCloseReason() and batch GetCloseReasonsForIssues()
- Update issue loading to populate close reasons
- Update scanIssues() to include close_reason in JSONL export
- Update bd show to display close reason after status
Close reasons now survive sync between repos.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
The sync validation was incorrectly triggering 'data loss detected' when
issue count decreased after import, even for legitimate deletions recorded
in deletions.jsonl.
Changes:
- Modified validatePostImport to accept jsonlPath and check deletions manifest
- When issue count decreases, check if decrease is within recorded deletions
- Updated all call sites in sync.go and daemon_sync.go
- Added comprehensive tests for deletion-aware validation
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Changed gitCommitBeadsDir to explicitly stage only sync files
(issues.jsonl, deletions.jsonl, metadata.json) instead of the
entire .beads/ directory.
This prevents staging gitignored snapshot files (beads.*.jsonl,
*.meta.json) that may still be tracked from before they were
added to .gitignore, which could cause merge conflicts when
multiple polecats run bd sync concurrently.
The staleness check compares last_import_time against JSONL file mtime.
File mtime has nanosecond precision, but last_import_time was stored with
only second precision (RFC3339). This caused a race condition where the
stored time could be slightly earlier than the file mtime, triggering
false "Database out of sync" errors - particularly in git worktrees.
Changed all 6 locations that set last_import_time to use RFC3339Nano.
The CheckStaleness parser already handles both formats, so this is
backward compatible.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Fixes bd-0b2: The git history backfill mechanism was causing data loss
during JSONL filename migrations (beads.jsonl → issues.jsonl). When issues
existed in the old filename's git history, the backfill incorrectly treated
them as "deleted" and purged them from the database.
Changes:
- Add NoGitHistory field to importer.Options and ImportOptions structs
- Modify purgeDeletedIssues() to skip git history check when flag is set
- Add --no-git-history flag to bd import command
- Add --no-git-history flag to bd sync command
- Update purge_test.go to pass Options argument
Usage:
bd import -i .beads/issues.jsonl --no-git-history
bd sync --no-git-history
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Change default JSONL filename from beads.jsonl to issues.jsonl
- Add bd doctor check and fix to auto-migrate legacy beads.jsonl configs
- Update FindJSONLPath to prefer issues.jsonl over beads.jsonl
- Add CheckLegacyJSONLConfig and CheckLegacyJSONLFilename checks
- Add LegacyJSONLConfig fix to rename files and update config
- Update .gitattributes to reference issues.jsonl
- Fix tests to expect new canonical filename
- Add bd-6xd to v0.25.1 release notes
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Previously, bd sync would commit ALL staged files when committing beads
changes. This could lead to unintended commits of work-in-progress code
that users had staged but weren't ready to commit.
Changed gitCommitBeadsDir to use pathspec (-- .beads/) to explicitly
limit the commit to only .beads/ files.
Also added in previous commit (bd-pbj):
- New Untracked Files check in bd doctor for untracked .beads/*.jsonl
- bd doctor --fix can now stage and commit untracked JSONL files
Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>
Add JSONL sanitization after git pull to remove deleted issues that
git's 3-way merge may resurrect. Also add bd doctor check to hydrate
deletions.jsonl from git history for pre-v0.25.0 deletions.
Changes:
- Add sanitizeJSONLWithDeletions() in sync.go (Step 3.6)
- Add checkDeletionsManifest() in doctor.go (Check 18)
- Add HydrateDeletionsManifest() fix in doctor/fix/deletions.go
- Add looksLikeIssueID() validation to prevent false positives
- Add comprehensive tests for sanitization logic
🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>
bd sync was only committing beads.jsonl, leaving other tracked files
like metadata.json unstaged. This caused 'git pull --rebase' to fail
with 'You have unstaged changes' error.
Now checks and commits the entire .beads/ directory to ensure a clean
worktree before pulling.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Completes the deletion propagation epic (bd-imj) with all 9 subtasks:
- Cross-clone deletion propagation via deletions.jsonl
- bd deleted command for audit trail
- Auto-compact during sync (opt-in)
- Git history fallback with timeout and regex escaping
- JSON output for pruning results
- Integration tests for deletion scenarios
- Documentation in AGENTS.md, README.md, and docs/DELETIONS.md
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Add Count function to deletions package for fast line counting
- Add maybeAutoCompactDeletions to sync (opt-in via deletions.auto_compact config)
- Fix regex escaping in batchCheckGitHistory (bd-bgs)
- Add 30s timeout to git history commands (bd-f0n)
- Use git rev-parse --show-toplevel for proper repo root detection (bd-bhd)
- Add tests for Count and auto-compact functionality
Closes: bd-qsm, bd-bgs, bd-f0n, bd-bhd
Enables bd sync to work with local-only branches that don't have
upstream tracking. Auto-detects this case and syncs beads from
origin/main instead of requiring an upstream branch.
Also fixes hasJSONLConflict() to recognize both issues.jsonl and
beads.jsonl filenames.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
## Problem
When bd sync detected stale DB (>50% divergence), it would import JSONL to fix the DB,
but then immediately export the DB back to JSONL. This caused the stale DB to overwrite
the JSONL after a git pull, undoing cleanup work.
Example scenario:
1. Clone has 688 stale issues in DB (628 closed)
2. git pull brings JSONL with 62 issues (cleanup applied)
3. bd sync detects 1009.7% divergence and imports JSONL (DB → 62 issues) ✓
4. bd sync exports DB to JSONL (JSONL still 62 issues) ✓
5. But this marks JSONL as "changed" and commits/pushes it ✗
## Solution
After ZFC (JSONL First Consistency) import, set skipExport flag to prevent the export step.
JSONL is the source of truth after import - DB should sync to match, not export back.
## Changes
- cmd/bd/sync.go: Add skipExport flag, set it after ZFC import
- cmd/bd/sync.go: Wrap export logic in `if !skipExport` block
- CHANGELOG.md: Update ZFC entry with accurate description
- cmd/bd/sync_test.go: Add TestZFCSkipsExportAfterImport
Fixes #bd-l0r
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Reverted 'always import' - that would overwrite local DB changes.
Now: only import first if DB has >50% more issues than JSONL (stale DB).
Preserves local uncommitted changes while catching sora scenario.
- Add isInRebase() to detect rebase state
- Add hasJSONLConflict() to check for JSONL-only conflicts
- Add runGitRebaseContinue() to continue rebase after resolution
- Auto-export from DB and resolve conflict when detected
- Add comprehensive tests for auto-resolution logic
Implements bd-cwmt
- bd init now auto-sets sync.branch to current git branch
- Fixes 'bd sync --status' error after fresh bd init
- Changed all branch detection to use 'git symbolic-ref' instead of 'git rev-parse' to work in fresh repos without commits
- Updated init.go, init_team.go, sync.go, version.go
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Fixes daemon and bd sync to honor BEADS_SYNC_BRANCH environment variable
as documented in PROTECTED_BRANCHES.md for CI/CD temporary overrides.
Changes:
- Updated internal/syncbranch.Get() to prioritize env var over DB config
- Both daemon sync and bd sync CLI now use syncbranch.Get()
- Added comprehensive tests for env var override behavior
- Validates branch names using git-style rules
This enables CI/CD workflows to override sync branch per-job without
mutating database config.
Based on PR #364 by Charles P. Cross <cpdata@users.noreply.github.com>
Co-authored-by: Charles P. Cross <cpdata@users.noreply.github.com>
Git merge drivers only support three placeholders:
- %O (ancestor/base)
- %A (current version)
- %B (other branch's version)
The code was incorrectly using %L and %R, which don't exist in git,
causing them to be passed through literally and breaking JSONL merges.
Changes:
- Fixed merge driver config in init.go, merge.go, README.md, docs
- Added detection in bd doctor with clear error messages
- Added auto-fix in bd doctor --fix
- Added proactive warning in bd sync before git pull
- Added reactive error detection after merge failures
- Updated all tests to use correct placeholders
Now users get helpful guidance at every step:
1. bd doctor detects the issue
2. bd doctor --fix auto-corrects it
3. bd sync warns before pulling if misconfigured
4. Error messages suggest bd doctor --fix when merge fails
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
This commit addresses critical code review findings from bd-dvd and bd-ymj fixes:
## Completed Tasks
### bd-ar2.1: Extract duplicated metadata update code
- Created `updateExportMetadata()` helper function
- Eliminated 22-line duplication between createExportFunc and createSyncFunc
- Single source of truth for metadata updates
### bd-ar2.2: Add multi-repo support to export metadata updates
- Added per-repo metadata key tracking with keySuffix parameter
- Both export and sync functions now update metadata for all repos
### bd-ar2.3: Fix tests to use actual daemon functions
- TestExportUpdatesMetadata now calls updateExportMetadata() directly
- Added TestUpdateExportMetadataMultiRepo() for multi-repo testing
- Fixed export_mtime_test.go tests to call updateExportMetadata()
### bd-ar2.9: Fix variable shadowing in GetNextChildID
- Changed `err` to `resurrectErr` to avoid shadowing
- Improves code clarity and passes linter checks
### bd-ar2.10: Fix hasJSONLChanged to support per-repo keys
- Updated hasJSONLChanged() to accept keySuffix parameter
- Reads metadata with correct per-repo keys
- All callers updated (validatePreExport, daemon import, sync command)
### bd-ar2.11: Use stable repo identifiers instead of paths
- Added getRepoKeyForPath() helper function
- Uses stable identifiers like ".", "../frontend" instead of absolute paths
- Metadata keys now portable across machines and clones
- Prevents orphaned metadata when repos are moved
## Files Changed
- cmd/bd/daemon_sync.go: Helper functions, metadata updates
- cmd/bd/integrity.go: hasJSONLChanged() with keySuffix support
- cmd/bd/sync.go: Updated to use getRepoKeyForPath()
- cmd/bd/*_test.go: Tests updated for new signatures
- internal/storage/sqlite/hash_ids.go: Fixed variable shadowing
## Testing
All export, sync, and integrity tests pass.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Replace mtime-based staleness detection with content-based (SHA256 hash) to prevent
git operations from resurrecting deleted issues.
**Problem:**
Auto-import used file modification time to detect if JSONL was "newer" than database.
Git operations (checkout, merge, pull) restore old files with recent mtimes, causing
auto-import to load stale data over current database state, resurrecting deleted issues.
**Solution:**
- Added computeJSONLHash() to compute SHA256 of JSONL content
- Added hasJSONLChanged() with two-tier check:
1. Fast-path: Check mtime first (99% of checks are instant)
2. Slow-path: Compute hash only if mtime changed (catches git operations)
- Store metadata: last_import_hash, last_import_mtime, last_import_time
- Updated auto-import in daemon_sync.go to use content-based check
- Updated validatePreExport to use content-based check (bd-xwo)
- Graceful degradation: metadata failures are non-fatal warnings
**Changes:**
- cmd/bd/integrity.go: Add computeJSONLHash(), hasJSONLChanged()
- cmd/bd/integrity_test.go: Add comprehensive tests for new functions
- cmd/bd/import.go: Update metadata after import
- cmd/bd/sync.go: Use hasJSONLChanged() instead of isJSONLNewer()
- cmd/bd/daemon_sync.go: Use hasJSONLChanged() in auto-import
**Testing:**
- Unit tests pass (TestHasJSONLChanged with 7 scenarios)
- Integration test passes (test_bd_khnb_fix.sh)
- Verified git resurrection scenario prevented
Fixes: bd-khnb
Related: bd-3bg, bd-xwo, bd-39o, bd-56p, bd-m8t, bd-rfj, bd-t5o
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Complete implementation of signal-aware context propagation for graceful
cancellation across all commands and storage operations.
Key changes:
1. Signal-aware contexts (bd-rtp):
- Added rootCtx/rootCancel in main.go using signal.NotifyContext()
- Set up in PersistentPreRun, cancelled in PersistentPostRun
- Daemon uses same pattern in runDaemonLoop()
- Handles SIGINT/SIGTERM for graceful shutdown
2. Context propagation (bd-yb8):
- All commands now use rootCtx instead of context.Background()
- sqlite.New() receives context for cancellable operations
- Database operations respect context cancellation
- Storage layer propagates context through all queries
3. Cancellation tests (bd-2o2):
- Added import_cancellation_test.go with comprehensive tests
- Added export cancellation test in export_test.go
- Tests verify database integrity after cancellation
- All cancellation tests passing
Fixes applied during review:
- Fixed rootCtx lifecycle (removed premature defer from PersistentPreRun)
- Fixed test context contamination (reset rootCtx in test cleanup)
- Fixed export tests missing context setup
Impact:
- Pressing Ctrl+C during import/export now cancels gracefully
- No database corruption or hanging transactions
- Clean shutdown of all operations
Tested:
- go build ./cmd/bd ✓
- go test ./cmd/bd -run TestImportCancellation ✓
- go test ./cmd/bd -run TestExportCommand ✓
- Manual Ctrl+C testing verified
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Previously, bd sync would fail with "Pre-export validation failed:
refusing to export: JSONL is newer than database" when JSONL was
modified (e.g., after git pull).
Now bd sync intelligently handles this by:
- Detecting when JSONL is newer than the database
- Automatically importing before exporting
- Continuing with the normal sync flow
This makes the workflow much smoother - users can just run 'bd sync'
and it figures out what needs to be done.
Changes:
- Added isJSONLNewer() helper to check file timestamps
- Modified sync command to auto-import when JSONL is newer
- Extracted timestamp check logic for reusability
Resolves: bd-ca0b
🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>
After daemon auto-export, JSONL mtime could be newer than database mtime
due to SQLite WAL mode not updating beads.db until checkpoint. This caused
validatePreExport to incorrectly block subsequent exports with "JSONL is
newer than database" error, leading to daemon shutdown.
Solution: Call TouchDatabaseFile after all export operations to ensure
database mtime >= JSONL mtime. This prevents false positives in validation
- Add hasGitRemote() helper to detect if any remote exists
- Gracefully skip git pull/push when no remote configured
- Daemon now works in local-only mode (RPC, auto-flush, JSONL export)
- Add comprehensive test coverage for local-only workflows
- Fixes GH#279: daemon crash on repos without origin remote
Amp-Thread-ID: https://ampcode.com/threads/T-5dad0ca8-ac77-4ae0-8de6-208b23ea47af
Co-authored-by: Amp <amp@ampcode.com>
- Add 3-way merge deletion tracking using snapshot files
- Create .beads/beads.base.jsonl and .beads/beads.left.jsonl snapshots
- Integrate into both sync.go and daemon_sync.go
- Add comprehensive test suite in deletion_tracking_test.go
- Update .gitignore to exclude snapshot files
This fixes the resurrection bug where deleted issues come back after
multi-workspace git sync. Uses the beads-merge 3-way merge logic to
detect and apply deletions correctly.
- Added dbNeedsExport() to check if DB and JSONL are in sync
- Only re-export after import if DB has changes that differ from JSONL
- Prevents unconditional re-export that caused infinite dirty state
- Added comprehensive tests for sync validation
Fixes recurring dirty state after merge conflicts that plagued users for weeks.
Amp-Thread-ID: https://ampcode.com/threads/T-f4f8c8c6-07bc-4334-9109-4626b4fd7a24
Co-authored-by: Amp <amp@ampcode.com>
- Adds checkGitHooks() function to verify recommended hooks are installed
- Checks for pre-commit, post-merge, and pre-push hooks
- Warns if hooks are missing with install instructions
- Shows up early in diagnostics (even if .beads/ missing)
- Includes comprehensive test coverage
- Filed bd-6049 for broken --json flag
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Remove obsolete test file and update remaining tests to not use the
removed --resolve-collisions flag. Hash-based IDs make collision
resolution unnecessary.
Changes:
- Delete internal/rpc/server_autoimport_test.go (obsolete)
- Remove --resolve-collisions from beads_nway_test.go
- Remove --resolve-collisions from beads_twoclone_test.go
- Remove --resolve-collisions from cmd/bd/sync.go
All tests now pass.
- Added validatePreExport to prevent data loss
- Added checkDuplicateIDs to detect corruption
- Added checkOrphanedDeps to find orphaned dependencies (both sides)
- Added validatePostImport to ensure imports don't lose data
- CRITICAL FIX: Removed post-pull export that clobbered fresh JSONL
- Conservative checks when JSONL is unreadable
- Efficient COUNT(*) SQL path instead of loading all issues
- Comprehensive test coverage including edge cases
- Added safety check to exportToJSONLWithStore (daemon path)
- Refuses to export 0 issues over non-empty JSONL file
- Added --force flag to override safety check when intentional
- Added test coverage for empty database export protection
- Prevents data loss when daemon has wrong/empty database
Amp-Thread-ID: https://ampcode.com/threads/T-de18e0ad-bd17-46ec-994b-0581e257dcde
Co-authored-by: Amp <amp@ampcode.com>
- Changed file permissions from 0644 → 0600 for JSONL exports and config files
- Changed directory permissions from 0755 → 0750 in all test code
- Updated .golangci.yml with proper exclusions for false positives
- Reduced gosec warnings from 102 to 22 (all remaining are acceptable)
Closes bd-57
Amp-Thread-ID: https://ampcode.com/threads/T-f754d957-9e42-4e74-861e-57235c7e6436
Co-authored-by: Amp <amp@ampcode.com>
- Added --flush-only flag to bd sync command
- Created pre-commit hook to flush pending changes before commit
- Created post-merge hook to import changes after pull/merge
- Added install script for easy setup
- Updated AGENTS.md with git hooks workflow
- Resolves race condition where daemon auto-flush fires after commit
Amp-Thread-ID: https://ampcode.com/threads/T-00b80d3a-4194-4c75-a60e-25a318cf9f91
Co-authored-by: Amp <amp@ampcode.com>