Files
beads/cmd/bd/test_repo_beads_guard_test.go
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

167 lines
4.2 KiB
Go

package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
)
// Guardrail: ensure the cmd/bd test suite does not touch the real repo .beads state.
// Disable with BEADS_TEST_GUARD_DISABLE=1 (useful when running tests while actively using beads).
func TestMain(m *testing.M) {
// Enable test mode that forces accessor functions to use legacy globals.
// This ensures backward compatibility with tests that manipulate globals directly.
enableTestModeGlobals()
// Prevent daemon auto-start and ensure tests don't interact with any running daemon.
// This prevents false positives in the test guard when a background daemon touches
// .beads files (like issues.jsonl via auto-sync) during test execution.
origNoDaemon := os.Getenv("BEADS_NO_DAEMON")
os.Setenv("BEADS_NO_DAEMON", "1")
defer func() {
if origNoDaemon != "" {
os.Setenv("BEADS_NO_DAEMON", origNoDaemon)
} else {
os.Unsetenv("BEADS_NO_DAEMON")
}
}()
if os.Getenv("BEADS_TEST_GUARD_DISABLE") != "" {
os.Exit(m.Run())
}
// Stop any running daemon for this repo to prevent false positives in the guard.
// The daemon auto-syncs and touches files like issues.jsonl, which would trigger
// the guard even though tests didn't cause the change.
repoRoot := findRepoRoot()
if repoRoot != "" {
stopRepoDaemon(repoRoot)
} else {
os.Exit(m.Run())
}
repoBeadsDir := filepath.Join(repoRoot, ".beads")
if _, err := os.Stat(repoBeadsDir); err != nil {
os.Exit(m.Run())
}
watch := []string{
"beads.db",
"beads.db-wal",
"beads.db-shm",
"beads.db-journal",
"issues.jsonl",
"beads.jsonl",
"metadata.json",
"interactions.jsonl",
"deletions.jsonl",
"molecules.jsonl",
"daemon.lock",
"daemon.pid",
"bd.sock",
}
before := snapshotFiles(repoBeadsDir, watch)
code := m.Run()
after := snapshotFiles(repoBeadsDir, watch)
if diff := diffSnapshots(before, after); diff != "" {
fmt.Fprintf(os.Stderr, "ERROR: test suite modified repo .beads state:\n%s\n", diff)
if code == 0 {
code = 1
}
}
os.Exit(code)
}
type fileSnap struct {
exists bool
size int64
modUnix int64
}
func snapshotFiles(dir string, names []string) map[string]fileSnap {
out := make(map[string]fileSnap, len(names))
for _, name := range names {
p := filepath.Join(dir, name)
info, err := os.Stat(p)
if err != nil {
out[name] = fileSnap{exists: false}
continue
}
out[name] = fileSnap{exists: true, size: info.Size(), modUnix: info.ModTime().UnixNano()}
}
return out
}
func diffSnapshots(before, after map[string]fileSnap) string {
var out string
for name, b := range before {
a := after[name]
if b.exists != a.exists {
out += fmt.Sprintf("- %s: exists %v → %v\n", name, b.exists, a.exists)
continue
}
if !b.exists {
continue
}
if b.size != a.size || b.modUnix != a.modUnix {
out += fmt.Sprintf("- %s: size %d → %d, mtime %s → %s\n",
name,
b.size,
a.size,
time.Unix(0, b.modUnix).UTC().Format(time.RFC3339Nano),
time.Unix(0, a.modUnix).UTC().Format(time.RFC3339Nano),
)
}
}
return out
}
func findRepoRoot() string {
wd, err := os.Getwd()
if err != nil {
return ""
}
for i := 0; i < 25; i++ {
if _, err := os.Stat(filepath.Join(wd, "go.mod")); err == nil {
return wd
}
parent := filepath.Dir(wd)
if parent == wd {
break
}
wd = parent
}
return ""
}
// stopRepoDaemon stops any running daemon for the given repository.
// This prevents false positives in the test guard when a background daemon
// touches .beads files during test execution. Uses exec to avoid import cycles.
func stopRepoDaemon(repoRoot string) {
beadsDir := filepath.Join(repoRoot, ".beads")
socketPath := filepath.Join(beadsDir, "bd.sock")
// Check if socket exists (quick check before shelling out)
if _, err := os.Stat(socketPath); err != nil {
return // no daemon running
}
// Shell out to bd daemon --stop. We can't call the daemon functions directly
// from TestMain because they have complex dependencies. Using exec is cleaner.
cmd := exec.Command("bd", "daemon", "--stop")
cmd.Dir = repoRoot
cmd.Env = append(os.Environ(), "BEADS_DIR="+beadsDir)
// Best-effort stop - ignore errors (daemon may not be running)
_ = cmd.Run()
// Give daemon time to shutdown gracefully
time.Sleep(500 * time.Millisecond)
}