Commit Graph

70 Commits

Author SHA1 Message Date
Steve Yegge
f3e1268b33 refactor: remove deprecated global daemon support
Global daemon support has been deprecated for most of the project's
lifetime. This change removes the dead code entirely:

- Remove --global and --migrate-to-global daemon flags
- Remove runGlobalDaemon() and migrateToGlobalDaemon() functions
- Remove shouldUseGlobalDaemon() and getGlobalBeadsDir() functions
- Simplify functions that had global bool parameters
- Remove warning about old global socket in getSocketPath()

This reduces code complexity and removes 238 net lines of unused code.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-24 23:39:54 -08:00
Steve Yegge
2560b11f80 feat: Add --start flag to bd daemon, show help with no args
Currently 'bd daemon' with no args immediately starts the daemon. This is
inconsistent with other daemon management commands like --stop, --status,
etc. and makes the command less discoverable for new users.

Changes:
- Add --start flag to explicitly start daemon
- Show help text when no operation flags provided
- Update auto-start logic to use --start flag
- Update startDaemon() to pass --start when forking
- Update all documentation to use 'bd daemon --start'
- Update MCP Python client error messages

The MCP docs already incorrectly showed 'bd daemon start' which doesn't
work, so this change fixes that documentation bug while improving UX.

Auto-start still works correctly - it now passes --start internally.

Fixes bd-gfu

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-24 00:03:07 -08:00
Charles P. Cross
9a2345f706 Fix: Daemon respects auto-commit/auto-push DB config (#360)
Fixes #358

The daemon was ignoring daemon.auto_commit and daemon.auto_push configuration values stored in the database unless the corresponding CLI flags were explicitly provided. This prevented bd init --team configuration from working as expected.

Changes:
- Modified cmd/bd/daemon.go to check database config when flags are not explicitly set
- Uses beads.FindDatabasePath() to locate the database and sqlite.New() to read config
- Only applies when starting daemon (skips for --stop, --status, --health, etc.)

Co-authored-by: Charles P. Cross <cpdata@users.noreply.github.com>
2025-11-22 16:57:23 -08:00
Steve Yegge
57253f93a3 Context propagation with graceful cancellation (bd-rtp, bd-yb8, bd-2o2)
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>
2025-11-20 21:57:23 -05:00
Charles P. Cross
68f9bef98c fix: prevent daemon from exiting when launcher process exits (issue #278) 2025-11-19 05:07:16 -05:00
Steve Yegge
f4a2f87aff Fix #274: Add automatic .beads/.gitignore upgrade (#300)
* Fix #274: Add automatic .beads/.gitignore upgrade

Implements three mechanisms to ensure users get updated gitignore:

1. bd doctor --fix: Manually upgrade gitignore
2. Daemon auto-upgrade: Upgrades on startup if outdated
3. bd init idempotent: Safe to re-run, always updates gitignore

The gitignore template now lives in cmd/bd/doctor/gitignore.go
for consistent updates across all three mechanisms.

Fixes: #274

* Remove test binary

Amp-Thread-ID: https://ampcode.com/threads/T-7042cfcc-ac97-43d7-a40f-3fa1bb4e1c2b
Co-authored-by: Amp <amp@ampcode.com>

* Fix critical issues: remove merge artifact and apply gitignore template

- Remove .beads/beads.left.jsonl (merge artifact that shouldn't be committed)
- Apply new gitignore template to .beads/.gitignore (was missing patterns)

Amp-Thread-ID: https://ampcode.com/threads/T-7042cfcc-ac97-43d7-a40f-3fa1bb4e1c2b
Co-authored-by: Amp <amp@ampcode.com>

* bd sync: 2025-11-12 11:09:30

* Retrigger CI

Amp-Thread-ID: https://ampcode.com/threads/T-8d532264-6d5e-4b68-88e9-e4511851b64a
Co-authored-by: Amp <amp@ampcode.com>

* Fix duplicate DoctorCheck type definition

* Trigger CI after fixing type conflict

Amp-Thread-ID: https://ampcode.com/threads/T-8d532264-6d5e-4b68-88e9-e4511851b64a
Co-authored-by: Amp <amp@ampcode.com>

---------

Co-authored-by: Amp <amp@ampcode.com>
2025-11-12 12:46:27 -08:00
Steve Yegge
00f045a972 bd-vcg5: Add daemon crash recovery with panic handler + socket cleanup
Improvements:
1. Added top-level panic recovery in runDaemonLoop
   - Captures stack trace and logs to daemon.log
   - Writes daemon-error file with crash details for user visibility
   - Cleans up PID file on panic
2. Replaced os.Exit calls with return statements where possible
   - Allows deferred cleanup to run (lock release, socket removal, etc)
   - Improves graceful shutdown on errors
3. Enhanced stopDaemon forced-kill path
   - Removes stale socket file after process.Kill()
   - Prevents socket artifacts from accumulating
4. Added integration tests for crash recovery

Closes bd-vcg5
2025-11-07 21:17:24 -08:00
Steve Yegge
7fa0c93195 Fix daemon orphaning: track parent PID and exit when parent dies
- Add ParentPID field to DaemonLockInfo struct
- Daemon monitors parent process every 10 seconds
- Gracefully exits when parent process dies
- Prevents accumulation of orphaned daemons from dead sessions
- Fixes race conditions from multiple daemons on same database

Closes bd-zpnq
2025-11-07 18:57:43 -08:00
Steve Yegge
584c266684 Reorganize project structure: move Go files to internal/beads, docs to docs/
Amp-Thread-ID: https://ampcode.com/threads/T-7a71671d-dd5c-4c7c-b557-fa427fceb04f
Co-authored-by: Amp <amp@ampcode.com>
2025-11-05 21:04:00 -08:00
Steve Yegge
fc0223854c Add remaining multi-repo files from bd-307 2025-11-04 23:12:41 -08:00
Steve Yegge
15affbe11e fix: Suppress gosec warnings with nolint comments
- Add nolint:gosec comments for safe file operations
- G304: File reads from validated/secure paths
- G306/G302: JSONL/error files need 0644 for sharing/debugging
- G204: Subprocess launches with validated arguments
- G104: Deferred file close errors are non-critical
- G115: Safe integer conversions in backoff
- G201: SQL placeholders for IN clause expansion

All warnings are for intentional behavior that is safe in context.

Amp-Thread-ID: https://ampcode.com/threads/T-d78f2780-4709-497f-97b0-035ca8c809e1
Co-authored-by: Amp <amp@ampcode.com>
2025-11-02 08:09:58 -08:00
Steve Yegge
a708c321fb Fix bd-11e0: Auto-upgrade database version in daemon instead of exiting 2025-11-01 19:28:37 -07:00
Steve Yegge
eb00ab8005 Refactor daemon.go for testability and maintainability (bd-2b34)
- Split 1567-line daemon.go into 5 focused modules
- daemon_config.go (122 lines): config/path resolution
- daemon_lifecycle.go (451 lines): start/stop/status/health/metrics
- daemon_sync.go (510 lines): export/import/sync logic
- daemon_server.go (115 lines): RPC server setup
- daemon_logger.go (43 lines): logging utilities
- Reduced main daemon.go to 389 lines (75% reduction)
- All tests pass, improved code organization

Amp-Thread-ID: https://ampcode.com/threads/T-7504c501-f962-4b82-a6d9-8e33f547757d
Co-authored-by: Amp <amp@ampcode.com>
2025-11-01 19:20:01 -07:00
Steve Yegge
b5839b656d Fix compilation errors in internal/daemonrunner package
Created missing files:
- logger.go: Logger type, setupLogger method, and env helpers
- signals_unix.go: Unix signal definitions (SIGTERM, SIGINT, SIGHUP)
- signals_windows.go: Windows signal definitions
- sync.go: Sync loop implementation with export/import/validation helpers

Fixed errors:
- Added missing 'version' parameter to acquireDaemonLock call
- Removed duplicate setupLock method from process.go (kept in daemon.go)
- Removed duplicate startRPCServer from daemon.go (kept in rpc.go)
- Fixed LogPath -> LogFile config field reference
- Removed unused 'io' import from process.go

Implementation notes:
- exportToJSONL: Full implementation with dependencies, labels, comments
- importFromJSONL: Placeholder (TODO: extract from cmd/bd/import.go)
- countDBIssues: Uses SQL COUNT(*) optimization with fallback
- validatePostImport: Checks for data loss
- runSyncLoop/runEventLoop: Main daemon event loops with signal handling

All packages now compile successfully with 'go build ./...'

Amp-Thread-ID: https://ampcode.com/threads/T-36a7f730-3420-426f-9e23-f13d5fa089c4
Co-authored-by: Amp <amp@ampcode.com>
2025-11-01 19:10:27 -07:00
Steve Yegge
acb731a4ec bd sync: 2025-10-31 22:39:53 2025-10-31 22:39:53 -07:00
Steve Yegge
079effdaeb Fix bd-373c: Surface daemon errors when multiple .db files exist
When daemon detects multiple .db files (after filtering .backup and vc.db),
it now writes detailed error to .beads/daemon-error file before exiting.

The error file is checked and displayed when:
- Daemon discovery fails to connect
- Auto-start fails to yield a running daemon
- User runs 'bd daemons list'

This makes the error immediately visible without requiring users to check
daemon logs.

Changes:
- cmd/bd/daemon.go: Write daemon-error file on multiple .db detection
- internal/daemon/discovery.go: Read and surface daemon-error in DaemonInfo.Error
- cmd/bd/main.go: Display daemon-error when auto-start fails

Amp-Thread-ID: https://ampcode.com/threads/T-1005a8d1-7a5a-4844-ad2d-2b8a6145825f
Co-authored-by: Amp <amp@ampcode.com>
2025-10-31 22:01:45 -07:00
Steve Yegge
31fcb06059 Fix daemon crash when backup/vc.db files exist
- Changed backup file filtering from checking file extension (.backup) to checking if filename contains '.backup'
- This now properly filters files like 'beads.backup-pre-hash-20251030-171258.db'
- Also exclude vc.db from database detection
- Add strings import to beads.go
- Improve error message to suggest manual removal

Fixes bd-373c
2025-10-31 21:18:08 -07:00
Steve Yegge
8cbcde134a Make event-driven mode the default
Event-driven daemon is now production-ready after hardening fixes in
commit 349b892. Making it the default for v0.21.0.

Users can still opt back to polling mode with BEADS_DAEMON_MODE=poll
if needed.

Benefits:
- <500ms sync latency (vs 5000ms with polling)
- ~60% less CPU usage
- Instant reactivity to mutations and file changes
- Fallback polling when file watcher unavailable

Amp-Thread-ID: https://ampcode.com/threads/T-a9a67394-37ca-4b79-aa23-c5c011f9c0cd
Co-authored-by: Amp <amp@ampcode.com>
2025-10-31 20:20:44 -07:00
Steve Yegge
349b892123 Harden event-driven daemon for production
Three critical fixes to make event-driven mode production-ready:

1. Skip redundant imports: Check JSONL mtime vs DB mtime to avoid
   self-triggered import loops after export writes JSONL

2. Add server.Stop() in serverErrChan case: Ensures clean RPC
   server shutdown on errors

3. Fallback ticker (60s): When file watcher unavailable (e.g., network
   filesystems), fall back to periodic polling to detect remote changes

These minimal fixes address Oracle's concerns without over-engineering.
Event-driven mode is now safe for default.

Amp-Thread-ID: https://ampcode.com/threads/T-a9a67394-37ca-4b79-aa23-c5c011f9c0cd
Co-authored-by: Amp <amp@ampcode.com>
2025-10-31 20:18:05 -07:00
Steve Yegge
0725c33fcc Remove vestigial --resolve-collisions flag
Hash-based IDs make collision resolution unnecessary. The flag was
already non-functional (handleCollisions returns error on collision
regardless of flag value).

Removed:
- --resolve-collisions flag from bd import
- ResolveCollisions field from ImportOptions and importer.Options
- All references in daemon, auto-import, and tests
- Updated error messages to reflect hash IDs don't collide

All import tests pass.

Amp-Thread-ID: https://ampcode.com/threads/T-47dfa0cc-bb71-4467-ac86-f0966a7c5d58
Co-authored-by: Amp <amp@ampcode.com>
2025-10-31 01:07:42 -07:00
Steve Yegge
dacf8de993 Implement daemon registry system (bd-07b8c8)
- Created global daemon registry at ~/.beads/registry.json
- Daemons auto-register on start, unregister on graceful shutdown
- DiscoverDaemons() now uses registry instead of filesystem scan
- Instant daemon discovery (35ms vs indefinite hang)
- Auto-cleanup of stale registry entries
- Full test coverage

Closes bd-07b8c8, bd-acb971c7
2025-10-30 18:37:12 -07:00
Steve Yegge
fea86f9b31 Implement event-driven daemon improvements for bd-85
- Add mutation events for label/dep/comment operations
- Create separate export-only and import-only functions
- Add dropped events counter with safety net export
- Complete bd-80 mutation channel implementation

Event-driven mode now:
- Emits mutation events for ALL write operations (not just create/update/close)
- Uses createExportFunc() for mutations (export+commit/push only, no pull)
- Uses createAutoImportFunc() for file changes (pull+import only, no export)
- Tracks dropped events and triggers safety export every 60s if any dropped
- Achieves <500ms latency target by avoiding full sync on each trigger

Behind BEADS_DAEMON_MODE=events flag (poll is still default)
2025-10-29 11:22:29 -07:00
Steve Yegge
781e300d33 Add event-driven daemon architecture (Phase 1 foundation)
- Add fsnotify dependency for file watching
- Create daemon_debouncer.go: batch rapid events (500ms window)
- Create daemon_watcher.go: monitor JSONL and git refs changes
- Create daemon_event_loop.go: event-driven sync loop
- Add mutation channel to RPC server (create/update/close events)
- Add BEADS_DAEMON_MODE env var (poll/events, default: poll)

Phase 1 implementation: opt-in via BEADS_DAEMON_MODE=events
Target: <500ms latency (vs 5000ms), ~60% CPU reduction

Related: bd-49 (epic), bd-50, bd-51, bd-53, bd-54, bd-55, bd-56
Amp-Thread-ID: https://ampcode.com/threads/T-35a3d0d7-4e19-421d-8392-63755035036e
Co-authored-by: Amp <amp@ampcode.com>
2025-10-28 13:12:37 -07:00
Steve Yegge
322ab63b10 Remove daemon storage cache (bd-33, bd-34, bd-35)
- Deleted server_cache_storage.go (~300 lines)
- Removed cache fields from Server struct
- Simplified database routing to use s.storage directly
- Removed cache metrics from health and metrics endpoints
- Deleted server_eviction_test.go (cache eviction tests)
- Cleaned up limits_test.go (removed cache assertions)
- All tests passing
2025-10-28 10:33:19 -07:00
Steve Yegge
648ecfafe7 Address gosec security warnings (bd-102)
- Enable gosec linter in .golangci.yml
- Tighten file permissions: 0755→0750 for directories, 0644→0600 for configs
- Git hooks remain 0700 (executable, user-only access)
- Add #nosec comments for safe cases with justifications:
  - G204: Safe subprocess launches (git show, bd daemon)
  - G304: File inclusions with controlled paths
  - G201: SQL formatting with controlled column names
  - G115: Integer conversions with controlled values

All gosec warnings resolved (20→0). All tests passing.

Amp-Thread-ID: https://ampcode.com/threads/T-d7166b9e-cbbe-4c7b-9e48-3df36b20f0d0
Co-authored-by: Amp <amp@ampcode.com>
2025-10-26 22:48:19 -07:00
Steve Yegge
79b7a48a73 Add database fingerprinting and validation (bd-166)
- Add fingerprint.go with robust URL canonicalization
  - Handles git@, ssh://, https://, http://, file://, and local paths
  - Normalizes URLs to produce consistent repo_id across formats
  - Clone ID uses git repo root for stability

- Update init.go to store repo_id and clone_id metadata
  - repo_id: SHA256 hash of canonical git remote URL
  - clone_id: SHA256 hash of hostname + repo root path

- Add daemon validation to prevent database mismatches
  - Validates repo_id on daemon start
  - Fails on legacy databases (requires explicit migration)
  - Clear error messages with actionable solutions

- Add migrate --update-repo-id command
  - Updates repo_id after remote URL changes
  - Confirmation prompt (can bypass with --yes)
  - Supports --dry-run

Prevents accidental database mixing across repos and provides
migration path for remote URL changes or bd upgrades.

Closes bd-166

Amp-Thread-ID: https://ampcode.com/threads/T-a9d9dab1-5808-4f62-93ea-75a16cca978b
Co-authored-by: Amp <amp@ampcode.com>
2025-10-26 21:15:57 -07:00
Steve Yegge
f24573a5f8 Enforce canonical database naming (beads.db) - bd-165
- Added CanonicalDatabaseName constant (beads.db) and LegacyDatabaseNames list
- Updated bd init to use canonical name via constant
- Added daemon validation to reject non-canonical database names
- Updated bd migrate to use canonical name constant
- Enhanced FindDatabasePath to warn when using legacy database names
- All database discovery now prefers beads.db with backward compatibility

Closes bd-165
2025-10-26 20:42:18 -07:00
Steve Yegge
6271b521b4 bd-162: Add database integrity checks with oracle review fixes
- 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
2025-10-26 20:17:48 -07:00
Steve Yegge
b893be7d0e Fix bd-161: Implement daemon JSONL import (fix NO-OP stub)
Replace the NO-OP importToJSONLWithStore() stub with full implementation:
- Reads and parses JSONL file line by line using bufio.Scanner
- Uses importIssuesCore() with auto-collision resolution enabled
- Integrates with existing import infrastructure
- Fixes PRIMARY root cause of bd-160 multi-clone sync failure

The daemon now properly imports remote changes pulled from git instead
of ignoring them, allowing databases to converge across clones.

Amp-Thread-ID: https://ampcode.com/threads/T-9b92c2dc-e0e2-4d77-b562-136da8c3f64e
Co-authored-by: Amp <amp@ampcode.com>
2025-10-26 20:05:31 -07:00
Steve Yegge
7591a3bf81 Add bd migrate command for database upgrades (bd-164)
- Implement bd migrate command with detection, version checking, and cleanup
- Update daemon to suggest bd migrate for version mismatches
- Enhance CLI version warnings to recommend bd migrate
- Add comprehensive tests for migration scenarios
- Document migration workflow in QUICKSTART.md and AGENTS.md

Completes bd-164 and epic bd-159

Amp-Thread-ID: https://ampcode.com/threads/T-34ea4682-8c48-44c2-8421-dc40f867773b
Co-authored-by: Amp <amp@ampcode.com>
2025-10-26 19:20:59 -07:00
Steve Yegge
7549bd86bc Implement stricter daemon lock file validation (bd-161)
- Add JSON format to daemon.lock with database path, version, PID, and timestamp
- Validate database path on client connection (fail if mismatch)
- Backward compatible with old plain-PID lock files
- Add comprehensive tests for JSON format and validation
- Update all lock acquisition callsites to pass database path

Amp-Thread-ID: https://ampcode.com/threads/T-137e6a9c-b690-4ade-9bec-13fcd7d0e4ed
Co-authored-by: Amp <amp@ampcode.com>
2025-10-26 18:37:25 -07:00
Steve Yegge
cd86d7d2ba Implement bd-160: Add database schema versioning
- Added version validation on daemon startup
- Daemon checks bd_version metadata matches current version
- Clear error messages for version mismatches with 3 resolution options
- Auto-sets missing version metadata for old databases
- Added BEADS_IGNORE_VERSION_MISMATCH=1 override for emergencies
- Tested version mismatch detection, override flag, and missing metadata handling
2025-10-26 18:28:15 -07:00
Steve Yegge
ae5aee279b Implement bd-162: Enforce canonical database name (beads.db)
- Changed bd init to always create beads.db instead of {prefix}.db
- Added migration logic to detect and rename old databases
- Updated findDatabaseInTree to prefer beads.db and warn on multiple .db files
- Daemon now refuses to start if multiple .db files exist (ambiguity error)
- Updated tests to expect beads.db instead of prefix-based naming
- Tested migration, ambiguity detection, and warning messages
2025-10-26 18:16:27 -07:00
Steve Yegge
c61ca494fe feat(daemons): implement discovery and list command (bd-146, bd-147)
- Add daemon discovery mechanism with socket scanning
- Implement depth-limited filesystem walk to avoid hangs
- Add DaemonInfo struct with metadata collection
- Create 'bd daemons list' command with table and JSON output
- Add FindDaemonByWorkspace and CleanupStaleSockets utilities
- Fix workspace path to be parent of .beads directory
- Add comprehensive tests for discovery functionality

Closes bd-146
Closes bd-147
2025-10-26 18:10:24 -07:00
Steve Yegge
75c959e69c feat(daemon): add GET /status endpoint (bd-148)
- Add OpStatus operation and StatusResponse type to RPC protocol
- Add workspacePath and dbPath fields to Server struct
- Implement handleStatus() handler with daemon metadata
- Track last activity time with atomic.Value
- Add client.Status() method
- Check for exclusive locks via ShouldSkipDatabase()
- Update all test files to use new NewServer signature
- Add comprehensive status endpoint test

Closes bd-148
2025-10-26 17:55:39 -07:00
Steve Yegge
e910d96bc6 Adjust sync timings for better batching behavior
- Increase flush debounce from 1s to 30s (provides transaction window for batch operations)
- Increase daemon poll from 2s to 5s (reduces commit spam)
- Agents should run 'bd sync' at end of session to force immediate commit
- Prevents creating dozens of commits when making multiple issue changes
2025-10-26 17:15:39 -07:00
Steve Yegge
fcff20a735 Reduce auto-sync delays for better UX
- Reduce flush debounce from 5s to 1s (BEADS_FLUSH_DEBOUNCE)
- Reduce daemon poll interval from 10s to 2s
- Makes issue changes sync much faster to JSONL and git
2025-10-26 17:14:25 -07:00
Steve Yegge
e657931186 Fix two daemon bugs: race condition on deletion (bd-155) and wrong project context (bd-156)
- bd-155: Add pre-import flush in daemon sync cycle to prevent deleted issues from being re-imported
- bd-155: Reduce default daemon polling interval from 5 minutes to 10 seconds
- bd-156: Fix hardcoded 'vc.db' - now properly detects existing .db files in local .beads/ directory
2025-10-26 17:09:20 -07:00
Steve Yegge
0ee45bf7de fix: Auto-sync RPC client/server versions from CLI version
- Set rpc.ServerVersion from Version in daemon startup
- Set rpc.ClientVersion from Version in main.go startup
- Eliminates need to manually update RPC versions
- Both now use 0.0.0 placeholder, overridden at runtime

Amp-Thread-ID: https://ampcode.com/threads/T-03c37f7f-f41e-4b87-8700-d346c21bad30
Co-authored-by: Amp <amp@ampcode.com>
2025-10-26 14:18:35 -07:00
Steve Yegge
3a42ca252d Implement exclusive lock protocol for daemon/external tool coexistence
- Add ExclusiveLock struct with JSON marshaling and validation
- Implement IsProcessAlive() with EPERM fail-safe behavior
- Add ShouldSkipDatabase() with stale lock cleanup
- Integrate lock checking into daemon sync cycle
- Return holder name on stale removal for better logging
- Case-insensitive hostname comparison
- Comprehensive unit tests (89.3% coverage)
- Documentation updates (ADVANCED.md, AGENTS.md)
- Add .beads/.exclusive-lock to .gitignore

Closes bd-115, bd-116, bd-117, bd-118, bd-119, bd-120, bd-121, bd-122

Amp-Thread-ID: https://ampcode.com/threads/T-0b835739-0d79-4ef9-aa62-8446a368c42d
Co-authored-by: Amp <amp@ampcode.com>
2025-10-25 23:32:47 -07:00
Steve Yegge
bb33007036 Fix revive style issues (bd-56)
- Fix 14 unused-parameter warnings (rename to _)
- Fix 2 redefines-builtin-id (max→maxCount, min→minInt)
- Fix 3 indent-error-flow issues with gofmt
- Merged duplicate bd-126 into bd-116
2025-10-25 18:13:49 -07:00
Steve Yegge
de03466da9 Fix bd-143: Prevent daemon auto-sync from wiping out issues.jsonl with empty database
- 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>
2025-10-25 16:36:18 -07:00
Steve Yegge
36c1c648fc Refactor TestLabelCommands and TestReopenCommand to reduce complexity
- TestLabelCommands: 67 → <10 using labelTestHelper
- TestReopenCommand: 37 → <10 using reopenTestHelper
- All tests pass
- Progress on bd-55

Amp-Thread-ID: https://ampcode.com/threads/T-0a5a623d-42f0-4b36-96ed-809285a748cb
Co-authored-by: Amp <amp@ampcode.com>
2025-10-25 11:27:24 -07:00
Steve Yegge
b405eefbe0 Fix daemon auto-start reliability
- Run initial sync in background so daemon becomes responsive immediately
- Skip daemon-running check for forked child process (BD_DAEMON_FOREGROUND=1)
- Fix PID file conflict between acquireDaemonLock and runDaemonLoop
- Daemon now starts reliably even with slow/failing git pulls

Fixes issue where daemon would timeout during auto-start because it was
blocked on git pull in the initial sync cycle. Now the RPC server starts
immediately and sync runs asynchronously.

Amp-Thread-ID: https://ampcode.com/threads/T-57f3c00a-02b4-4878-adba-c7d1649759b4
Co-authored-by: Amp <amp@ampcode.com>
2025-10-24 21:51:30 -07:00
Steve Yegge
d6a8659c76 Revert database reinitialization test - breaking CI on Windows and Nix
The TestDatabaseReinitialization test added in 14895bf is failing:
- Windows: JSON parse errors, missing files
- Nix: git not available in build environment

Reverting to unblock CI and dependabot PRs. Will fix and re-land later.

Amp-Thread-ID: https://ampcode.com/threads/T-908f1690-937c-499f-bf51-ee35a9241eb2
Co-authored-by: Amp <amp@ampcode.com>
2025-10-24 15:06:27 -07:00
Steve Yegge
14895bf97a Fix critical P0 database reinitialization bug (bd-130)
Fixes silent data loss when .beads/ directory removed and daemon auto-starts.

Root cause: checkGitForIssues() hardcoded 'issues.jsonl' but git tracks 'beads.jsonl'

Changes:
- Fix A (bd-131): checkGitForIssues() tries beads.jsonl first, then issues.jsonl
- Fix B (bd-132): Immediate export after import in bd init to prevent daemon race
- Fix C (bd-133): Safety check that fails loudly if import fails
- Fix D (bd-134): Daemon startup auto-import when DB empty but git has issues
- Tests (bd-135): Comprehensive integration test suite

Oracle-recommended improvements:
- Export to exact git-relative path (prevents path drift)
- filepath.ToSlash for Windows git compatibility
- 64MB scanner buffer for large JSONL lines
- Improved safety check messages (only suggest local file if exists)

All tests passing. No regressions.

Amp-Thread-ID: https://ampcode.com/threads/T-0e31dc6a-a0d9-46c6-87b2-cfdebe829a52
Co-authored-by: Amp <amp@ampcode.com>
2025-10-24 14:52:24 -07:00
Steve Yegge
9dcb86ebfb Fix lint errors: handle errors, use fmt.Fprintf, apply De Morgan's law, use switch statements
Amp-Thread-ID: https://ampcode.com/threads/T-afcf56b0-a8bc-4310-bb59-1b63e1d70c89
Co-authored-by: Amp <amp@ampcode.com>
2025-10-24 12:27:07 -07:00
Steve Yegge
09b54d1b22 Fix remaining errcheck warnings in daemon.go, daemon_lock.go, delete.go
- daemon.go: fix os.Remove() in stopDaemon (line 602)
- daemon_lock.go: fix f.Close() and fmt.Fprintf() calls
- delete.go: fix cmd.Usage(), out.Close(), and os.Remove() calls

All error returns now properly handled or explicitly ignored.

Amp-Thread-ID: https://ampcode.com/threads/T-56b6d9f4-16a4-4c50-b7b9-dde1c3774650
Co-authored-by: Amp <amp@ampcode.com>
2025-10-24 11:17:11 -07:00
Steve Yegge
beb5dd91bf Fix errcheck warnings in cmd/bd/daemon.go
- Check error returns for client.Close() calls (3 instances)
- Check error returns for devNull.Close() calls (3 instances)
- Check error returns for tempFile.Close()
- Check error returns for logF.Close()
- Check error returns for fmt.Fprintf() calls (2 instances)
- Check error returns for lock.Close()
- Check error returns for f.Close()
- Check error returns for store.Close()
- Check error returns for os.Remove() calls (2 instances)

All errors are now properly handled or explicitly ignored with _.
This fixes the linting failures in CI.

Amp-Thread-ID: https://ampcode.com/threads/T-56b6d9f4-16a4-4c50-b7b9-dde1c3774650
Co-authored-by: Amp <amp@ampcode.com>
2025-10-24 10:34:42 -07:00
Steve Yegge
42480014b3 Additional Windows CI fixes (bd-99)
- Write PID to daemon.pid when acquiring lock for Windows compatibility
- Increase socket cleanup timeout to 5s for Windows
- Windows can't read locked files, so PID file is required fallback
2025-10-24 10:12:59 -07:00