refactor: gut JSONL sync engine, keep simple manual import/export (bd-h0zvj.2)

Delete 11 production files and 19 test files (~12,900 lines):
- 3-way merge engine (sync_merge, sync_conflict, sync_manual)
- Sync mode infrastructure (sync_mode, sync_mode_cmd)
- Sync state tracking and backoff (sync_state)
- Sync branch/worktree operations (sync_branch, migrate_sync)
- Integrity checks (sync_check, sync_status)
- Bridge functions (sync_bridge)

Rewrite sync.go from 805 to 159 lines:
- Default: Dolt commit + push
- --import: JSONL → Dolt
- --export/--flush-only: Dolt → JSONL
- --pull: Pull from Dolt remote

Keep sync_helpers.go with core export/import functions.
Keep sync_git.go (used by init.go, restore.go).

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

Executed-By: beads/crew/emma
Rig: beads
Role: crew
This commit is contained in:
beads/crew/emma 2026-02-15 16:42:44 -08:00 • committed by Steve Yegge
commit 76b2f1e456
34 changed files with 153 additions and 12908 deletions

View file

@ -1,317 +0,0 @@
//go:build cgo && integration
package main
import (
"bytes"
"context"
"encoding/json"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/types"
)
// TestGitPullSyncIntegration tests the full git pull sync scenario
// Verifies that after git pull, both daemon and non-daemon modes pick up changes automatically
func TestGitPullSyncIntegration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
// Create temp directory for test repositories
tempDir := t.TempDir()
// Create "remote" repository
remoteDir := filepath.Join(tempDir, "remote")
if err := os.MkdirAll(remoteDir, 0750); err != nil {
t.Fatalf("Failed to create remote dir: %v", err)
}
// Initialize remote git repo
runGitCmd(t, remoteDir, "init", "--bare", "-b", "master")
// Create "clone1" repository
clone1Dir := filepath.Join(tempDir, "clone1")
runGitCmd(t, tempDir, "clone", remoteDir, clone1Dir)
configureGit(t, clone1Dir)
// Initialize beads in clone1
clone1BeadsDir := filepath.Join(clone1Dir, ".beads")
if err := os.MkdirAll(clone1BeadsDir, 0750); err != nil {
t.Fatalf("Failed to create .beads dir: %v", err)
}
clone1DBPath := filepath.Join(clone1BeadsDir, "test.db")
clone1Store := newTestStore(t, clone1DBPath)
defer clone1Store.Close()
ctx := context.Background()
if err := clone1Store.SetMetadata(ctx, "issue_prefix", "test"); err != nil {
t.Fatalf("Failed to set prefix: %v", err)
}
// Create and close an issue in clone1
issue := &types.Issue{
Title: "Test sync issue",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
if err := clone1Store.CreateIssue(ctx, issue, "test-user"); err != nil {
t.Fatalf("Failed to create issue: %v", err)
}
issueID := issue.ID
// Close the issue
if err := clone1Store.CloseIssue(ctx, issueID, "Test completed", "test-user", ""); err != nil {
t.Fatalf("Failed to close issue: %v", err)
}
// Export to JSONL
jsonlPath := filepath.Join(clone1BeadsDir, "issues.jsonl")
if err := exportIssuesToJSONL(ctx, clone1Store, jsonlPath); err != nil {
t.Fatalf("Failed to export: %v", err)
}
// Commit and push from clone1
runGitCmd(t, clone1Dir, "add", ".beads")
runGitCmd(t, clone1Dir, "commit", "-m", "Add closed issue")
runGitCmd(t, clone1Dir, "push", "origin", "master")
// Create "clone2" repository
clone2Dir := filepath.Join(tempDir, "clone2")
runGitCmd(t, tempDir, "clone", remoteDir, clone2Dir)
configureGit(t, clone2Dir)
// Initialize empty database in clone2
clone2BeadsDir := filepath.Join(clone2Dir, ".beads")
clone2DBPath := filepath.Join(clone2BeadsDir, "test.db")
clone2Store := newTestStore(t, clone2DBPath)
defer clone2Store.Close()
if err := clone2Store.SetMetadata(ctx, "issue_prefix", "test"); err != nil {
t.Fatalf("Failed to set prefix: %v", err)
}
// Import the existing JSONL (simulating initial sync)
clone2JSONLPath := filepath.Join(clone2BeadsDir, "issues.jsonl")
if err := importJSONLToStore(ctx, clone2Store, clone2DBPath, clone2JSONLPath); err != nil {
t.Fatalf("Failed to import: %v", err)
}
// Verify issue exists and is closed
verifyIssueClosed(t, clone2Store, issueID)
// Note: We don't commit in clone2 - it stays clean as a read-only consumer
// Now test git pull scenario: Clone1 makes a change (update priority)
if err := clone1Store.UpdateIssue(ctx, issueID, map[string]interface{}{
"priority": 0,
}, "test-user"); err != nil {
t.Fatalf("Failed to update issue: %v", err)
}
if err := exportIssuesToJSONL(ctx, clone1Store, jsonlPath); err != nil {
t.Fatalf("Failed to export after update: %v", err)
}
runGitCmd(t, clone1Dir, "add", ".beads/issues.jsonl")
runGitCmd(t, clone1Dir, "commit", "-m", "Update priority")
runGitCmd(t, clone1Dir, "push", "origin", "master")
// Clone2 pulls the change
runGitCmd(t, clone2Dir, "pull")
// Test auto-import in non-daemon mode
t.Run("NonDaemonAutoImport", func(t *testing.T) {
// Use a temporary local store for this test
localStore := newTestStore(t, clone2DBPath)
defer localStore.Close()
// Manually import to simulate auto-import behavior
startTime := time.Now()
if err := importJSONLToStore(ctx, localStore, clone2DBPath, clone2JSONLPath); err != nil {
t.Fatalf("Failed to auto-import: %v", err)
}
elapsed := time.Since(startTime)
// Verify priority was updated
issue, err := localStore.GetIssue(ctx, issueID)
if err != nil {
t.Fatalf("Failed to get issue: %v", err)
}
if issue.Priority != 0 {
t.Errorf("Expected priority 0 after auto-import, got %d", issue.Priority)
}
// Verify performance: import should be fast
if elapsed > 100*time.Millisecond {
t.Logf("Info: import took %v", elapsed)
}
})
// Test bd sync --import-only command
t.Run("BdSyncCommand", func(t *testing.T) {
// Make another change in clone1 (change priority back to 1)
if err := clone1Store.UpdateIssue(ctx, issueID, map[string]interface{}{
"priority": 1,
}, "test-user"); err != nil {
t.Fatalf("Failed to update issue: %v", err)
}
if err := exportIssuesToJSONL(ctx, clone1Store, jsonlPath); err != nil {
t.Fatalf("Failed to export: %v", err)
}
runGitCmd(t, clone1Dir, "add", ".beads/issues.jsonl")
runGitCmd(t, clone1Dir, "commit", "-m", "Update priority")
runGitCmd(t, clone1Dir, "push", "origin", "master")
// Clone2 pulls
runGitCmd(t, clone2Dir, "pull")
// Use a fresh store for import
syncStore := newTestStore(t, clone2DBPath)
defer syncStore.Close()
// Manually trigger import via in-process equivalent
if err := importJSONLToStore(ctx, syncStore, clone2DBPath, clone2JSONLPath); err != nil {
t.Fatalf("Failed to import via sync: %v", err)
}
// Verify priority was updated back to 1
issue, err := syncStore.GetIssue(ctx, issueID)
if err != nil {
t.Fatalf("Failed to get issue: %v", err)
}
if issue.Priority != 1 {
t.Errorf("Expected priority 1, got %d", issue.Priority)
}
})
}
// Helper functions
func runGitCmd(t *testing.T, dir string, args ...string) {
cmd := exec.Command("git", args...)
cmd.Dir = dir
cmd.Env = append(os.Environ(), "GIT_COMMITTER_DATE=2024-01-01T00:00:00", "GIT_AUTHOR_DATE=2024-01-01T00:00:00")
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git %v failed in %s: %v\n%s", args, dir, err, output)
}
}
func configureGit(t *testing.T, dir string) {
runGitCmd(t, dir, "config", "user.email", "test@example.com")
runGitCmd(t, dir, "config", "user.name", "Test User")
runGitCmd(t, dir, "config", "pull.rebase", "false")
// Create .gitignore to prevent test database files from being tracked
gitignorePath := filepath.Join(dir, ".gitignore")
gitignoreContent := `# Test database files
*.db
*.db-journal
*.db-wal
*.db-shm
`
if err := os.WriteFile(gitignorePath, []byte(gitignoreContent), 0644); err != nil {
t.Fatalf("Failed to create .gitignore: %v", err)
}
}
func exportIssuesToJSONL(ctx context.Context, store *dolt.DoltStore, jsonlPath string) error {
issues, err := store.SearchIssues(ctx, "", types.IssueFilter{})
if err != nil {
return err
}
// Populate dependencies
allDeps, err := store.GetAllDependencyRecords(ctx)
if err != nil {
return err
}
for _, issue := range issues {
issue.Dependencies = allDeps[issue.ID]
labels, _ := store.GetLabels(ctx, issue.ID)
issue.Labels = labels
}
f, err := os.Create(jsonlPath)
if err != nil {
return err
}
defer f.Close()
encoder := json.NewEncoder(f)
for _, issue := range issues {
if err := encoder.Encode(issue); err != nil {
return err
}
}
return nil
}
func importJSONLToStore(ctx context.Context, store *dolt.DoltStore, dbPath, jsonlPath string) error {
data, err := os.ReadFile(jsonlPath)
if err != nil {
return err
}
// Use the autoimport package's AutoImportIfNewer function
// For testing, we'll directly parse and import
var issues []*types.Issue
decoder := json.NewDecoder(bytes.NewReader(data))
for decoder.More() {
var issue types.Issue
if err := decoder.Decode(&issue); err != nil {
return err
}
issues = append(issues, &issue)
}
// Import each issue
for _, issue := range issues {
existing, _ := store.GetIssue(ctx, issue.ID)
if existing != nil {
// Update
updates := map[string]interface{}{
"status": issue.Status,
"priority": issue.Priority,
}
if err := store.UpdateIssue(ctx, issue.ID, updates, "import"); err != nil {
return err
}
} else {
// Create
if err := store.CreateIssue(ctx, issue, "import"); err != nil {
return err
}
}
}
// Set last_import_time metadata so staleness check works
if err := store.SetMetadata(ctx, "last_import_time", time.Now().Format(time.RFC3339)); err != nil {
return err
}
return nil
}
func verifyIssueClosed(t *testing.T, store *dolt.DoltStore, issueID string) {
issue, err := store.GetIssue(context.Background(), issueID)
if err != nil {
t.Fatalf("Failed to get issue %s: %v", issueID, err)
}
if issue.Status != types.StatusClosed {
t.Errorf("Expected issue %s to be closed, got status %s", issueID, issue.Status)
}
}

View file

@ -1,164 +0,0 @@
// Package main provides the bd CLI commands.
package main
import (
"strings"
"testing"
)
// TestGenerateUniqueIssueIDs verifies IDs are unique even when generated rapidly.
func TestGenerateUniqueIssueIDs(t *testing.T) {
seen := make(map[string]bool)
prefix := "bd"
// Generate 100 IDs rapidly
for i := 0; i < 100; i++ {
id := generateIssueID(prefix)
if seen[id] {
t.Errorf("Duplicate ID generated: %s", id)
}
seen[id] = true
}
}
// TestGenerateIssueIDHasRandomComponent verifies IDs include random bytes for restart safety.
// Without random bytes, counter reset on restart could cause ID collisions.
func TestGenerateIssueIDHasRandomComponent(t *testing.T) {
// Save current counter
oldCounter := issueIDCounter
defer func() { issueIDCounter = oldCounter }()
prefix := "test"
// Generate ID, reset counter (simulating restart), generate another
// Both generated at same counter value - should still be unique due to random component
issueIDCounter = 100
id1 := generateIssueID(prefix)
// Simulate restart by resetting counter to same value
issueIDCounter = 100
id2 := generateIssueID(prefix)
// Even with same counter, IDs should differ due to random component
if id1 == id2 {
t.Errorf("IDs should be unique even with counter reset: id1=%s, id2=%s", id1, id2)
}
// Verify format includes hex suffix (random bytes)
// Expected format: prefix-timestamp-counter-hex
parts := strings.Split(id1, "-")
if len(parts) != 4 {
t.Errorf("Expected 4 parts (prefix-timestamp-counter-random), got %d: %s", len(parts), id1)
}
}
// TestGetConflictStrategy verifies conflict strategy selection from flags.
func TestGetConflictStrategy(t *testing.T) {
tests := []struct {
name string
preferLocal bool
preferGitLab bool
preferNewer bool
wantStrategy ConflictStrategy
wantError bool
}{
{
name: "no flags - default to prefer-newer",
wantStrategy: ConflictStrategyPreferNewer,
},
{
name: "prefer-local",
preferLocal: true,
wantStrategy: ConflictStrategyPreferLocal,
},
{
name: "prefer-gitlab",
preferGitLab: true,
wantStrategy: ConflictStrategyPreferGitLab,
},
{
name: "prefer-newer explicit",
preferNewer: true,
wantStrategy: ConflictStrategyPreferNewer,
},
{
name: "multiple flags - error",
preferLocal: true,
preferGitLab: true,
wantError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
strategy, err := getConflictStrategy(tt.preferLocal, tt.preferGitLab, tt.preferNewer)
if tt.wantError {
if err == nil {
t.Error("expected error for multiple flags, got nil")
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if strategy != tt.wantStrategy {
t.Errorf("strategy = %q, want %q", strategy, tt.wantStrategy)
}
})
}
}
// TestParseGitLabSourceSystem verifies parsing source system string.
func TestParseGitLabSourceSystem(t *testing.T) {
tests := []struct {
name string
sourceSystem string
wantProjectID int
wantIID int
wantOK bool
}{
{
name: "valid gitlab source",
sourceSystem: "gitlab:123:42",
wantProjectID: 123,
wantIID: 42,
wantOK: true,
},
{
name: "different project",
sourceSystem: "gitlab:456:99",
wantProjectID: 456,
wantIID: 99,
wantOK: true,
},
{
name: "non-gitlab source",
sourceSystem: "linear:ABC-123",
wantProjectID: 0,
wantIID: 0,
wantOK: false,
},
{
name: "empty source",
sourceSystem: "",
wantProjectID: 0,
wantIID: 0,
wantOK: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
projectID, iid, ok := parseGitLabSourceSystem(tt.sourceSystem)
if ok != tt.wantOK {
t.Errorf("parseGitLabSourceSystem(%q) ok = %v, want %v", tt.sourceSystem, ok, tt.wantOK)
}
if projectID != tt.wantProjectID {
t.Errorf("parseGitLabSourceSystem(%q) projectID = %d, want %d", tt.sourceSystem, projectID, tt.wantProjectID)
}
if iid != tt.wantIID {
t.Errorf("parseGitLabSourceSystem(%q) iid = %d, want %d", tt.sourceSystem, iid, tt.wantIID)
}
})
}
}

View file

@ -134,10 +134,8 @@ func handleToDoltMigration(dryRun bool, autoYes bool) {
exitWithError("import_failed", importErr.Error(), "partial Dolt directory has been cleaned up")
}
// Set sync.mode to dolt-native in the DB so ShouldExportJSONL skips
// the expensive JSONL export. Without this, the migrated DB has no
// sync.mode set, defaulting to git-portable (10-25s export tax per write).
if err := doltStore.SetConfig(ctx, SyncModeConfigKey, SyncModeDoltNative); err != nil {
// Set sync.mode to dolt-native in the DB.
if err := doltStore.SetConfig(ctx, "sync.mode", "dolt-native"); err != nil {
printWarning(fmt.Sprintf("failed to set sync.mode in DB: %v", err))
} else {
printSuccess("Set sync.mode = dolt-native in database")

View file

@ -1,540 +0,0 @@
package main
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/git"
"github.com/steveyegge/beads/internal/syncbranch"
)
var migrateSyncCmd = &cobra.Command{
Use: "sync <branch-name>",
Short: "Migrate to sync.branch workflow for multi-clone setups",
Long: `Migrate to using a dedicated sync branch for beads data.
This command configures the repository to commit .beads changes to a separate
branch (e.g., "beads-sync") instead of the current working branch. This is
essential for multi-clone setups where multiple clones work independently
but need to sync beads data.
The command will:
1. Validate the current state (not already configured, not on sync branch)
2. Create the sync branch if it doesn't exist (from remote or locally)
3. Set up the git worktree for the sync branch
4. Set the sync.branch configuration
After migration, 'bd sync' will commit beads changes to the sync branch via
a git worktree, keeping your working branch clean of beads commits.
Examples:
# Basic migration to beads-sync branch
bd migrate-sync beads-sync
# Preview what would happen without making changes
bd migrate-sync beads-sync --dry-run
# Force migration even if already configured
bd migrate-sync beads-sync --force`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
ctx := rootCtx
branchName := args[0]
dryRun, _ := cmd.Flags().GetBool("dry-run")
force, _ := cmd.Flags().GetBool("force")
orphan, _ := cmd.Flags().GetBool("orphan")
if err := runMigrateSync(ctx, branchName, dryRun, force, orphan); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
},
}
func init() {
migrateSyncCmd.Flags().Bool("dry-run", false, "Preview migration without making changes")
migrateSyncCmd.Flags().Bool("force", false, "Force migration even if already configured")
migrateSyncCmd.Flags().Bool("orphan", false, "Migrate existing sync branch to orphan (deletes and recreates)")
migrateCmd.AddCommand(migrateSyncCmd)
// Backwards compatibility alias at root level (hidden)
migrateSyncAliasCmd := *migrateSyncCmd
migrateSyncAliasCmd.Use = "migrate-sync"
migrateSyncAliasCmd.Hidden = true
migrateSyncAliasCmd.Deprecated = "use 'bd migrate sync' instead (will be removed in v1.0.0)"
rootCmd.AddCommand(&migrateSyncAliasCmd)
}
func runMigrateSync(ctx context.Context, branchName string, dryRun, force, orphan bool) error {
// Validate branch name
if err := syncbranch.ValidateBranchName(branchName); err != nil {
return fmt.Errorf("invalid branch name: %w", err)
}
// Check if we're in a git repository
if !isGitRepo() {
return fmt.Errorf("not in a git repository")
}
// Get RepoContext for git operations
rc, err := beads.GetRepoContext()
if err != nil {
return fmt.Errorf("failed to get repository context: %w", err)
}
// Ensure store is initialized for config operations
if err := ensureDirectMode("migrate-sync requires direct database access"); err != nil {
return err
}
// Get current branch
currentBranch, err := getCurrentBranch(ctx)
if err != nil {
return fmt.Errorf("failed to get current branch: %w", err)
}
// Check if already on the sync branch
if currentBranch == branchName {
return fmt.Errorf("currently on branch '%s' - switch to your main working branch first (e.g., 'git checkout main')", branchName)
}
// Check if sync.branch is already configured
existingSyncBranch, err := syncbranch.Get(ctx, store)
if err != nil {
return fmt.Errorf("failed to check existing config: %w", err)
}
if existingSyncBranch != "" && !force {
if existingSyncBranch == branchName {
fmt.Printf("✓ Already configured to use sync branch '%s'\n", branchName)
fmt.Println(" Use --force to reconfigure anyway")
return nil
}
return fmt.Errorf("sync.branch already configured as '%s' (use --force to change to '%s')", existingSyncBranch, branchName)
}
// Check if we have a remote
hasRemote := hasGitRemote(ctx)
if !hasRemote {
fmt.Println("⚠ Warning: No git remote configured. Sync branch will only exist locally.")
}
// Get repo root (rc already initialized above)
repoRoot := rc.RepoRoot
// Find JSONL path
jsonlPath := findJSONLPath()
if jsonlPath == "" {
return fmt.Errorf("not in a bd workspace (no .beads directory found)")
}
// Check if sync branch exists (locally or remotely)
branchExistsLocally := branchExistsLocal(ctx, branchName)
branchExistsRemotely := branchExistsRemote(ctx, branchName)
if dryRun {
fmt.Println("=== DRY RUN - No changes will be made ===")
fmt.Println()
fmt.Printf("Current branch: %s\n", currentBranch)
fmt.Printf("Sync branch: %s\n", branchName)
fmt.Printf("Repository root: %s\n", repoRoot)
fmt.Printf("JSONL path: %s\n", jsonlPath)
fmt.Println()
if existingSyncBranch != "" {
fmt.Printf("→ Would change sync.branch from '%s' to '%s'\n", existingSyncBranch, branchName)
} else {
fmt.Printf("→ Would set sync.branch to '%s'\n", branchName)
}
if branchExistsLocally {
if orphan {
fmt.Printf("→ Would migrate existing branch '%s' to orphan (delete and recreate)\n", branchName)
} else {
fmt.Printf("→ Branch '%s' exists locally (will use as-is)\n", branchName)
}
} else if branchExistsRemotely {
if orphan {
fmt.Printf("→ Would create new orphan branch '%s' (ignoring remote non-orphan)\n", branchName)
} else {
fmt.Printf("→ Would create local branch '%s' from remote\n", branchName)
}
} else {
fmt.Printf("→ Would create new orphan branch '%s' (no shared history)\n", branchName)
}
// Use git-common-dir for worktree path to support bare repos and worktrees (GH#639)
gitCommonDir, err := git.GetGitCommonDir()
if err != nil {
return fmt.Errorf("not a git repository: %w", err)
}
worktreePath := filepath.Join(gitCommonDir, "beads-worktrees", branchName)
fmt.Printf("→ Would create worktree at: %s\n", worktreePath)
fmt.Println("\n=== END DRY RUN ===")
return nil
}
// Track preserved JSONL for orphan migration (set in migration block, used in sync)
var preservedJSONLPath string
var backupJSONLPath string // Backup file, deleted only on success
// Step 1: Create or migrate the sync branch
fmt.Printf("→ Setting up sync branch '%s'...\n", branchName)
// Helper function to create orphan branch using commit-tree (doesn't change HEAD)
createOrphanBranch := func() error {
fmt.Printf(" Creating orphan branch '%s' (no shared history)...\n", branchName)
// Create an empty tree object using --stdin for cross-platform compatibility
// (avoids /dev/null which doesn't exist on Windows)
emptyTreeCmd := rc.GitCmd(ctx, "hash-object", "-t", "tree", "--stdin")
emptyTreeCmd.Stdin = strings.NewReader("")
emptyTreeOutput, err := emptyTreeCmd.Output()
if err != nil {
return fmt.Errorf("failed to create empty tree: %w", err)
}
emptyTree := strings.TrimSpace(string(emptyTreeOutput))
// Create an orphan commit (no parents) with the empty tree
commitTreeCmd := rc.GitCmd(ctx, "commit-tree", emptyTree, "-m", "Initialize beads sync branch")
commitOutput, err := commitTreeCmd.Output()
if err != nil {
return fmt.Errorf("failed to create orphan commit: %w", err)
}
orphanCommit := strings.TrimSpace(string(commitOutput))
// Create branch pointing to the orphan commit
branchCmd := rc.GitCmd(ctx, "branch", branchName, orphanCommit)
if output, err := branchCmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to create branch: %w\n%s", err, output)
}
return nil
}
if !branchExistsLocally && !branchExistsRemotely {
// New branch: create as orphan (default behavior)
if err := createOrphanBranch(); err != nil {
return err
}
} else if branchExistsLocally && orphan {
// Migration: delete existing local branch and recreate as orphan
// Safety check: warn if branch has unpushed commits
if !force {
hasUnpushed, err := branchHasUnpushedCommits(ctx, rc, branchName)
if err != nil {
// If we can't check (no remote tracking), warn but continue
fmt.Printf(" Warning: Could not check for unpushed commits: %v\n", err)
} else if hasUnpushed {
return fmt.Errorf("branch '%s' has unpushed commits that would be lost.\n"+
" Run 'bd sync' first to export database to JSONL and push, or\n"+
" Use --force to proceed anyway (unpushed commits will be lost)", branchName)
}
}
fmt.Printf(" Migrating existing branch '%s' to orphan...\n", branchName)
// Check if branch is used by a worktree and preserve JSONL before removing
gitCommonDir, err := git.GetGitCommonDir()
if err != nil {
return fmt.Errorf("not a git repository: %w", err)
}
existingWorktreePath := filepath.Join(gitCommonDir, "beads-worktrees", branchName)
// Create backup of JSONL before any destructive operations
worktreeJSONL := filepath.Join(existingWorktreePath, ".beads", "issues.jsonl")
if _, err := os.Stat(worktreeJSONL); err == nil {
// Create backup file (kept until migration succeeds)
backupFile, err := os.CreateTemp("", "beads-backup-*.jsonl")
if err != nil {
return fmt.Errorf("failed to create backup file: %w", err)
}
_ = backupFile.Close() // Close before writing content
backupJSONLPath = backupFile.Name()
// Copy JSONL to backup
input, err := os.ReadFile(worktreeJSONL) // #nosec G304 - path constructed from git worktree
if err != nil {
return fmt.Errorf("failed to read JSONL for backup: %w", err)
}
// nolint:gosec // G306: JSONL needs 0644 for other tools to read
if err := os.WriteFile(backupJSONLPath, input, 0644); err != nil {
return fmt.Errorf("failed to create backup: %w", err)
}
fmt.Printf(" Backed up JSONL (%d bytes) to %s\n", len(input), backupJSONLPath)
// Also set as preserved path for restoration
preservedJSONLPath = backupJSONLPath
}
if _, err := os.Stat(existingWorktreePath); err == nil {
fmt.Printf(" Removing existing worktree at %s...\n", existingWorktreePath)
removeCmd := rc.GitCmd(ctx, "worktree", "remove", "--force", existingWorktreePath)
if output, err := removeCmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to remove existing worktree: %w\n%s", err, output)
}
}
fmt.Printf(" Deleting existing local branch...\n")
deleteCmd := rc.GitCmd(ctx, "branch", "-D", branchName)
if output, err := deleteCmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to delete existing branch: %w\n%s", err, output)
}
if err := createOrphanBranch(); err != nil {
return err
}
} else if !branchExistsLocally && branchExistsRemotely && orphan {
// Remote exists but user wants orphan: create local orphan (ignore remote)
fmt.Printf(" Creating local orphan branch (ignoring remote non-orphan)...\n")
if err := createOrphanBranch(); err != nil {
return err
}
} else if !branchExistsLocally && branchExistsRemotely {
// Fetch and create local tracking branch (preserve existing remote)
fmt.Printf(" Fetching remote branch '%s'...\n", branchName)
fetchCmd := rc.GitCmd(ctx, "fetch", "origin", branchName)
if output, err := fetchCmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to fetch remote branch: %w\n%s", err, output)
}
// Create local branch tracking remote
createCmd := rc.GitCmd(ctx, "branch", branchName, "origin/"+branchName)
if output, err := createCmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to create local tracking branch: %w\n%s", err, output)
}
} else {
// Branch exists locally, no --orphan flag: use as-is
fmt.Printf(" Branch '%s' already exists locally (using as-is)\n", branchName)
}
// Step 2: Create the worktree
// Use git-common-dir for worktree path to support bare repos and worktrees (GH#639)
gitCommonDir, err := git.GetGitCommonDir()
if err != nil {
return fmt.Errorf("not a git repository: %w", err)
}
worktreePath := filepath.Join(gitCommonDir, "beads-worktrees", branchName)
fmt.Printf("→ Creating worktree at %s...\n", worktreePath)
wtMgr := git.NewWorktreeManager(repoRoot)
if err := wtMgr.CreateBeadsWorktree(branchName, worktreePath); err != nil {
return fmt.Errorf("failed to create worktree: %w", err)
}
// Step 3: Sync current JSONL to worktree
fmt.Println("→ Syncing current beads data to worktree...")
jsonlRelPath, err := filepath.Rel(repoRoot, jsonlPath)
if err != nil {
return fmt.Errorf("failed to get relative JSONL path: %w", err)
}
// If we preserved JSONL during orphan migration, restore it directly
destPath := filepath.Join(worktreePath, ".beads", "issues.jsonl")
if preservedJSONLPath != "" {
if err := os.MkdirAll(filepath.Dir(destPath), 0755); err != nil {
return fmt.Errorf("failed to create .beads directory: %w", err)
}
input, err := os.ReadFile(preservedJSONLPath) // #nosec G304 - path from backup temp file
if err != nil {
return fmt.Errorf("failed to read preserved JSONL: %w", err)
}
// nolint:gosec // G306: JSONL needs 0644 for other tools to read
if err := os.WriteFile(destPath, input, 0644); err != nil {
return fmt.Errorf("failed to restore JSONL to worktree: %w", err)
}
fmt.Printf(" Restored JSONL (%d bytes) to worktree\n", len(input))
// Note: backup cleanup happens at end of successful migration
} else {
// Try normal sync first, fall back to main .beads/ if it fails
syncErr := wtMgr.SyncJSONLToWorktree(worktreePath, jsonlRelPath)
if syncErr != nil {
// Fallback: try copying from main .beads/ directory
mainJSONL := filepath.Join(repoRoot, ".beads", "issues.jsonl")
if _, err := os.Stat(mainJSONL); err == nil {
fmt.Printf(" Falling back to main .beads/issues.jsonl...\n")
if err := os.MkdirAll(filepath.Dir(destPath), 0755); err != nil {
return fmt.Errorf("failed to create .beads directory: %w", err)
}
input, err := os.ReadFile(mainJSONL) // #nosec G304 - path constructed from repoRoot
if err != nil {
return fmt.Errorf("failed to read main JSONL: %w", err)
}
// nolint:gosec // G306: JSONL needs 0644 for other tools to read
if err := os.WriteFile(destPath, input, 0644); err != nil {
return fmt.Errorf("failed to copy JSONL to worktree: %w", err)
}
fmt.Printf(" Copied JSONL (%d bytes) from main .beads/\n", len(input))
} else {
return fmt.Errorf("failed to sync JSONL to worktree: %w", syncErr)
}
}
}
// Also sync other beads files
beadsDir := filepath.Dir(jsonlPath)
for _, filename := range []string{"deletions.jsonl", "metadata.json"} {
srcPath := filepath.Join(beadsDir, filename)
if _, err := os.Stat(srcPath); err == nil {
relPath, err := filepath.Rel(repoRoot, srcPath)
if err == nil {
_ = wtMgr.SyncJSONLToWorktree(worktreePath, relPath)
}
}
}
// Step 4: Commit initial state to sync branch if there are changes
fmt.Println("→ Committing initial state to sync branch...")
worktreeJSONLPath := filepath.Join(worktreePath, jsonlRelPath)
hasChanges, err := hasChangesInWorktreeDir(ctx, worktreePath)
if err != nil {
fmt.Printf(" Warning: failed to check for changes: %v\n", err)
}
if hasChanges {
if err := commitInitialSyncState(ctx, worktreePath, jsonlRelPath); err != nil {
fmt.Printf(" Warning: failed to commit initial state: %v\n", err)
} else {
fmt.Println(" Initial state committed to sync branch")
}
} else {
// Check if .beads directory exists in worktree but no changes
worktreeBeadsDir := filepath.Join(worktreePath, ".beads")
if _, err := os.Stat(worktreeBeadsDir); os.IsNotExist(err) {
// .beads doesn't exist in worktree - this is a fresh setup
fmt.Println(" No existing beads data in sync branch")
} else {
fmt.Println(" Sync branch already has current beads data")
}
}
_ = worktreeJSONLPath // silence unused warning
// Step 5: Set sync.branch config
fmt.Printf("→ Setting sync.branch to '%s'...\n", branchName)
if err := syncbranch.Set(ctx, store, branchName); err != nil {
return fmt.Errorf("failed to set sync.branch config: %w", err)
}
// Step 6: Push sync branch to remote if we have one
if hasRemote {
fmt.Printf("→ Pushing sync branch '%s' to remote...\n", branchName)
pushCmd := exec.CommandContext(ctx, "git", "-C", worktreePath, "push", "--set-upstream", "origin", branchName)
output, err := pushCmd.CombinedOutput()
if err != nil {
// Non-fatal - branch might already be up to date or push might fail for other reasons
if !strings.Contains(string(output), "Everything up-to-date") {
fmt.Printf(" Warning: failed to push sync branch: %v\n", err)
fmt.Printf(" You may need to push manually: git push -u origin %s\n", branchName)
}
} else {
fmt.Printf(" Pushed '%s' to origin\n", branchName)
}
}
fmt.Println()
// Clean up backup file on success (best-effort, ignore errors)
if backupJSONLPath != "" {
_ = os.Remove(backupJSONLPath)
}
fmt.Println("✓ Migration complete!")
fmt.Println()
fmt.Printf(" sync.branch: %s\n", branchName)
fmt.Printf(" worktree: %s\n", worktreePath)
fmt.Println()
fmt.Println("Next steps:")
fmt.Println(" • 'bd sync' will now commit beads changes to the sync branch")
fmt.Println(" • Your working branch stays clean of beads commits")
fmt.Println(" • Other clones should also run 'bd migrate-sync " + branchName + "'")
return nil
}
// branchExistsLocal checks if a branch exists locally
func branchExistsLocal(ctx context.Context, branch string) bool {
rc, err := beads.GetRepoContext()
if err != nil {
return false
}
cmd := rc.GitCmd(ctx, "show-ref", "--verify", "--quiet", "refs/heads/"+branch)
return cmd.Run() == nil
}
// branchExistsRemote checks if a branch exists on origin remote
func branchExistsRemote(ctx context.Context, branch string) bool {
rc, err := beads.GetRepoContext()
if err != nil {
return false
}
// First fetch to ensure we have latest remote refs
fetchCmd := rc.GitCmd(ctx, "fetch", "origin", "--prune")
_ = fetchCmd.Run() // Best effort
cmd := rc.GitCmd(ctx, "show-ref", "--verify", "--quiet", "refs/remotes/origin/"+branch)
return cmd.Run() == nil
}
// branchHasUnpushedCommits checks if a local branch has commits not pushed to remote
func branchHasUnpushedCommits(ctx context.Context, rc *beads.RepoContext, branch string) (bool, error) {
// Check if remote tracking branch exists
remoteRef := "refs/remotes/origin/" + branch
checkCmd := rc.GitCmd(ctx, "show-ref", "--verify", "--quiet", remoteRef)
if err := checkCmd.Run(); err != nil {
// No remote tracking branch - can't determine if unpushed
return false, fmt.Errorf("no remote tracking branch for '%s'", branch)
}
// Count commits ahead of remote
// git rev-list --count origin/branch..branch
countCmd := rc.GitCmd(ctx, "rev-list", "--count", "origin/"+branch+".."+branch)
output, err := countCmd.Output()
if err != nil {
return false, fmt.Errorf("failed to count commits: %w", err)
}
count := strings.TrimSpace(string(output))
return count != "0", nil
}
// hasChangesInWorktreeDir checks if there are any uncommitted changes in the worktree
func hasChangesInWorktreeDir(ctx context.Context, worktreePath string) (bool, error) {
cmd := exec.CommandContext(ctx, "git", "-C", worktreePath, "status", "--porcelain")
output, err := cmd.Output()
if err != nil {
return false, fmt.Errorf("git status failed: %w", err)
}
return len(strings.TrimSpace(string(output))) > 0, nil
}
// commitInitialSyncState commits the initial beads state to the sync branch
func commitInitialSyncState(ctx context.Context, worktreePath, jsonlRelPath string) error {
beadsRelDir := filepath.Dir(jsonlRelPath)
// Stage all beads files
// Use --sparse to work correctly with sparse-checkout enabled worktrees (fixes #1076)
addCmd := exec.CommandContext(ctx, "git", "-C", worktreePath, "add", "--sparse", beadsRelDir)
if err := addCmd.Run(); err != nil {
return fmt.Errorf("git add failed: %w", err)
}
// Commit
commitCmd := exec.CommandContext(ctx, "git", "-C", worktreePath, "commit", "--no-verify", "-m", "bd migrate-sync: initial sync branch setup")
output, err := commitCmd.CombinedOutput()
if err != nil {
// Check if there's nothing to commit
if strings.Contains(string(output), "nothing to commit") {
return nil
}
return fmt.Errorf("git commit failed: %w\n%s", err, output)
}
return nil
}

View file

@ -1,622 +0,0 @@
package main
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/git"
)
func TestMigrateSyncValidation(t *testing.T) {
// Test invalid branch names
tests := []struct {
name string
branch string
wantErr bool
}{
{"valid simple", "beads-sync", false},
{"valid with slash", "beads/sync", false},
{"valid with dots", "beads.sync", false},
{"invalid empty", "", true},
{"invalid HEAD", "HEAD", true},
{"invalid dots", "..", true},
{"invalid leading slash", "/beads", true},
{"invalid trailing slash", "beads/", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// We can't easily test the full command without a git repo,
// but we can test branch validation indirectly
if tt.branch == "" {
// Empty branch should fail at args validation level
return
}
})
}
}
func TestMigrateSyncDryRun(t *testing.T) {
// Create a temp directory with a git repo
tmpDir, err := os.MkdirTemp("", "bd-migrate-sync-test")
if err != nil {
t.Fatalf("failed to create temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
// Copy cached git template (bd-ktng optimization)
initGitTemplate()
if gitTemplateErr != nil {
t.Fatalf("git template init failed: %v", gitTemplateErr)
}
if err := copyGitDir(gitTemplateDir, tmpDir); err != nil {
t.Fatalf("failed to copy git template: %v", err)
}
// Create initial commit
testFile := filepath.Join(tmpDir, "test.txt")
if err := os.WriteFile(testFile, []byte("test"), 0644); err != nil {
t.Fatalf("failed to create test file: %v", err)
}
cmd := exec.Command("git", "add", ".")
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to git add: %v", err)
}
cmd = exec.Command("git", "commit", "-m", "initial")
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to git commit: %v", err)
}
// Create .beads directory and initialize
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0750); err != nil {
t.Fatalf("failed to create .beads dir: %v", err)
}
// Create minimal issues.jsonl
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
if err := os.WriteFile(jsonlPath, []byte(""), 0644); err != nil {
t.Fatalf("failed to create issues.jsonl: %v", err)
}
// Test that branchExistsLocal returns false for non-existent branch
// Note: We need to run this from tmpDir context since branchExistsLocal uses git in cwd
ctx := context.Background()
t.Chdir(tmpDir)
// Reset caches so RepoContext picks up new CWD
beads.ResetCaches()
git.ResetCaches()
defer func() {
beads.ResetCaches()
git.ResetCaches()
}()
if branchExistsLocal(ctx, "beads-sync") {
t.Error("branchExistsLocal should return false for non-existent branch")
}
// Create the branch
cmd = exec.Command("git", "branch", "beads-sync")
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to create branch: %v", err)
}
// Now it should exist
if !branchExistsLocal(ctx, "beads-sync") {
t.Error("branchExistsLocal should return true for existing branch")
}
}
func TestMigrateSyncOrphan(t *testing.T) {
// Create a temp directory with a git repo
tmpDir, err := os.MkdirTemp("", "bd-migrate-sync-orphan-test")
if err != nil {
t.Fatalf("failed to create temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
// Copy cached git template (bd-ktng optimization)
initGitTemplate()
if gitTemplateErr != nil {
t.Fatalf("git template init failed: %v", gitTemplateErr)
}
if err := copyGitDir(gitTemplateDir, tmpDir); err != nil {
t.Fatalf("failed to copy git template: %v", err)
}
// Create initial commit on main branch
testFile := filepath.Join(tmpDir, "test.txt")
if err := os.WriteFile(testFile, []byte("test content"), 0644); err != nil {
t.Fatalf("failed to create test file: %v", err)
}
cmd := exec.Command("git", "add", ".")
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to git add: %v", err)
}
cmd = exec.Command("git", "commit", "-m", "initial commit")
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to git commit: %v", err)
}
// Get current branch name (could be main or master)
cmd = exec.Command("git", "branch", "--show-current")
cmd.Dir = tmpDir
output, err := cmd.Output()
if err != nil {
t.Fatalf("failed to get current branch: %v", err)
}
mainBranch := strings.TrimSpace(string(output))
// Create .beads directory
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0750); err != nil {
t.Fatalf("failed to create .beads dir: %v", err)
}
// Create minimal issues.jsonl
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
if err := os.WriteFile(jsonlPath, []byte(""), 0644); err != nil {
t.Fatalf("failed to create issues.jsonl: %v", err)
}
// Change to test directory
t.Chdir(tmpDir)
beads.ResetCaches()
git.ResetCaches()
defer func() {
beads.ResetCaches()
git.ResetCaches()
}()
// Test 1: Verify orphan branch has no merge-base with main
t.Run("orphan branch has no merge-base", func(t *testing.T) {
orphanBranch := "test-orphan"
// Create orphan branch using git directly (simulating what runMigrateSync does)
cmd := exec.Command("git", "checkout", "--orphan", orphanBranch)
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to create orphan branch: %v", err)
}
// Remove all files from index (orphan starts with staged files)
cmd = exec.Command("git", "rm", "-rf", "--cached", ".")
cmd.Dir = tmpDir
_ = cmd.Run() // May fail if nothing staged
// Clean working directory (like runMigrateSync does)
cmd = exec.Command("git", "clean", "-fd")
cmd.Dir = tmpDir
_ = cmd.Run() // Best effort
// Create .beads directory on orphan branch
orphanBeadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(orphanBeadsDir, 0750); err != nil {
t.Fatalf("failed to create .beads dir on orphan: %v", err)
}
// Create a commit on the orphan branch
orphanFile := filepath.Join(orphanBeadsDir, "test.txt")
if err := os.WriteFile(orphanFile, []byte("orphan content"), 0644); err != nil {
t.Fatalf("failed to create orphan file: %v", err)
}
cmd = exec.Command("git", "add", ".beads/test.txt")
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to git add on orphan: %v", err)
}
cmd = exec.Command("git", "commit", "-m", "orphan initial")
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to commit on orphan: %v", err)
}
// Switch back to main branch (force to handle any conflicts)
cmd = exec.Command("git", "checkout", "-f", mainBranch)
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to switch back to %s: %v", mainBranch, err)
}
// Verify orphan branch has no merge-base with main
// git merge-base should FAIL (exit code 1) for orphan branches
cmd = exec.Command("git", "merge-base", mainBranch, orphanBranch)
cmd.Dir = tmpDir
err := cmd.Run()
if err == nil {
t.Error("orphan branch should have no merge-base with main, but merge-base succeeded")
}
})
// Test 2: Verify regular branch (non-orphan) DOES have merge-base
t.Run("regular branch has merge-base", func(t *testing.T) {
regularBranch := "test-regular"
// Create a regular branch (inherits history)
cmd := exec.Command("git", "branch", regularBranch)
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to create regular branch: %v", err)
}
// Verify regular branch DOES have a merge-base with main
cmd = exec.Command("git", "merge-base", mainBranch, regularBranch)
cmd.Dir = tmpDir
err := cmd.Run()
if err != nil {
t.Error("regular branch should have merge-base with main, but merge-base failed")
}
})
}
func TestMigrateSyncOrphanWorktree(t *testing.T) {
// This test verifies that git worktrees can be created from orphan branches
// which is essential for orphan branches (now the default) to work with sparse checkout
tmpDir, err := os.MkdirTemp("", "bd-migrate-sync-orphan-worktree-test")
if err != nil {
t.Fatalf("failed to create temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
// Copy cached git template (bd-ktng optimization)
initGitTemplate()
if gitTemplateErr != nil {
t.Fatalf("git template init failed: %v", gitTemplateErr)
}
if err := copyGitDir(gitTemplateDir, tmpDir); err != nil {
t.Fatalf("failed to copy git template: %v", err)
}
// Create initial commit on main
testFile := filepath.Join(tmpDir, "test.txt")
if err := os.WriteFile(testFile, []byte("main content"), 0644); err != nil {
t.Fatalf("failed to create test file: %v", err)
}
cmd := exec.Command("git", "add", ".")
cmd.Dir = tmpDir
_ = cmd.Run()
cmd = exec.Command("git", "commit", "-m", "initial")
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to git commit: %v", err)
}
// Get main branch name
cmd = exec.Command("git", "branch", "--show-current")
cmd.Dir = tmpDir
output, _ := cmd.Output()
mainBranch := strings.TrimSpace(string(output))
// Create orphan branch
orphanBranch := "orphan-sync"
cmd = exec.Command("git", "checkout", "--orphan", orphanBranch)
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to create orphan branch: %v", err)
}
// Clean orphan branch
cmd = exec.Command("git", "rm", "-rf", "--cached", ".")
cmd.Dir = tmpDir
_ = cmd.Run()
cmd = exec.Command("git", "clean", "-fd")
cmd.Dir = tmpDir
_ = cmd.Run()
// Create .beads content on orphan branch
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0750); err != nil {
t.Fatalf("failed to create .beads: %v", err)
}
if err := os.WriteFile(filepath.Join(beadsDir, "issues.jsonl"), []byte(""), 0644); err != nil {
t.Fatalf("failed to create issues.jsonl: %v", err)
}
cmd = exec.Command("git", "add", ".beads")
cmd.Dir = tmpDir
_ = cmd.Run()
cmd = exec.Command("git", "commit", "-m", "orphan initial")
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to commit on orphan: %v", err)
}
// Switch back to main
cmd = exec.Command("git", "checkout", "-f", mainBranch)
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to switch to main: %v", err)
}
t.Run("worktree can be created from orphan branch", func(t *testing.T) {
worktreePath := filepath.Join(tmpDir, ".worktrees", orphanBranch)
// Create worktree from orphan branch
cmd := exec.Command("git", "worktree", "add", worktreePath, orphanBranch)
cmd.Dir = tmpDir
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("failed to create worktree from orphan branch: %v\n%s", err, output)
}
// Verify worktree exists
if _, err := os.Stat(worktreePath); os.IsNotExist(err) {
t.Error("worktree directory should exist")
}
// Verify .beads exists in worktree (from orphan branch)
wtBeadsDir := filepath.Join(worktreePath, ".beads")
if _, err := os.Stat(wtBeadsDir); os.IsNotExist(err) {
t.Error(".beads should exist in worktree from orphan branch")
}
// Verify main branch's test.txt does NOT exist in worktree
// (because orphan branch has no shared history)
wtTestFile := filepath.Join(worktreePath, "test.txt")
if _, err := os.Stat(wtTestFile); err == nil {
t.Error("test.txt from main branch should NOT exist in orphan worktree")
}
// Cleanup worktree
cmd = exec.Command("git", "worktree", "remove", "--force", worktreePath)
cmd.Dir = tmpDir
_ = cmd.Run()
})
}
func TestMigrateSyncExistingBranchPreserved(t *testing.T) {
// This test verifies that existing sync branches (even non-orphan) are used as-is
// This ensures existing users aren't affected by the orphan-by-default change
tmpDir, err := os.MkdirTemp("", "bd-migrate-sync-existing-test")
if err != nil {
t.Fatalf("failed to create temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
// Copy cached git template (bd-ktng optimization)
initGitTemplate()
if gitTemplateErr != nil {
t.Fatalf("git template init failed: %v", gitTemplateErr)
}
if err := copyGitDir(gitTemplateDir, tmpDir); err != nil {
t.Fatalf("failed to copy git template: %v", err)
}
// Create initial commit on main
testFile := filepath.Join(tmpDir, "test.txt")
if err := os.WriteFile(testFile, []byte("main content"), 0644); err != nil {
t.Fatalf("failed to create test file: %v", err)
}
cmd := exec.Command("git", "add", ".")
cmd.Dir = tmpDir
_ = cmd.Run()
cmd = exec.Command("git", "commit", "-m", "initial")
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to git commit: %v", err)
}
// Get main branch name
cmd = exec.Command("git", "branch", "--show-current")
cmd.Dir = tmpDir
output, _ := cmd.Output()
mainBranch := strings.TrimSpace(string(output))
// Create a REGULAR (non-orphan) branch to simulate existing setup
existingBranch := "existing-sync"
cmd = exec.Command("git", "branch", existingBranch)
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to create existing branch: %v", err)
}
t.Run("existing non-orphan branch has merge-base", func(t *testing.T) {
// Verify the existing branch HAS a merge-base with main (it's not orphan)
cmd := exec.Command("git", "merge-base", mainBranch, existingBranch)
cmd.Dir = tmpDir
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Expected merge-base to exist for non-orphan branch, but got error: %v\n%s", err, output)
}
mergeBase := strings.TrimSpace(string(output))
if mergeBase == "" {
t.Fatal("Expected non-empty merge-base for non-orphan branch")
}
// This proves the branch is NOT orphan, so if migrate sync uses it,
// it won't break existing user setups
})
t.Run("git show-ref detects existing branch", func(t *testing.T) {
// Verify git show-ref (used by branchExistsLocal) detects the branch
// This is the check that prevents orphan creation for existing branches
cmd := exec.Command("git", "show-ref", "--verify", "--quiet", "refs/heads/"+existingBranch)
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatal("Expected git show-ref to find existing branch")
}
})
}
func TestMigrateSyncOrphanMigration(t *testing.T) {
// This test verifies that --orphan flag migrates existing non-orphan branch to orphan
// by deleting and recreating it
tmpDir, err := os.MkdirTemp("", "bd-migrate-sync-orphan-migration-test")
if err != nil {
t.Fatalf("failed to create temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
// Copy cached git template (bd-ktng optimization)
initGitTemplate()
if gitTemplateErr != nil {
t.Fatalf("git template init failed: %v", gitTemplateErr)
}
if err := copyGitDir(gitTemplateDir, tmpDir); err != nil {
t.Fatalf("failed to copy git template: %v", err)
}
// Create initial commit on main
testFile := filepath.Join(tmpDir, "test.txt")
if err := os.WriteFile(testFile, []byte("main content"), 0644); err != nil {
t.Fatalf("failed to create test file: %v", err)
}
cmd := exec.Command("git", "add", ".")
cmd.Dir = tmpDir
_ = cmd.Run()
cmd = exec.Command("git", "commit", "-m", "initial")
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to git commit: %v", err)
}
// Get main branch name
cmd = exec.Command("git", "branch", "--show-current")
cmd.Dir = tmpDir
output, _ := cmd.Output()
mainBranch := strings.TrimSpace(string(output))
// Create a REGULAR (non-orphan) branch
syncBranch := "beads-sync"
cmd = exec.Command("git", "branch", syncBranch)
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to create sync branch: %v", err)
}
t.Run("non-orphan branch has merge-base before migration", func(t *testing.T) {
// Verify it HAS merge-base (not orphan yet)
cmd := exec.Command("git", "merge-base", mainBranch, syncBranch)
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatal("Expected merge-base to exist before migration")
}
})
t.Run("migration converts to orphan", func(t *testing.T) {
// Simulate what --orphan flag does: delete and recreate as orphan
// Delete existing branch
cmd := exec.Command("git", "branch", "-D", syncBranch)
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to delete branch: %v", err)
}
// Create orphan branch
cmd = exec.Command("git", "checkout", "--orphan", syncBranch)
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to create orphan branch: %v", err)
}
// Remove staged files
cmd = exec.Command("git", "rm", "-rf", "--cached", ".")
cmd.Dir = tmpDir
_ = cmd.Run()
// Clean working directory
cmd = exec.Command("git", "clean", "-fd")
cmd.Dir = tmpDir
_ = cmd.Run()
// Create .beads and commit
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0750); err != nil {
t.Fatalf("failed to create .beads: %v", err)
}
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
if err := os.WriteFile(jsonlPath, []byte(""), 0644); err != nil {
t.Fatalf("failed to create issues.jsonl: %v", err)
}
cmd = exec.Command("git", "add", ".beads")
cmd.Dir = tmpDir
_ = cmd.Run()
cmd = exec.Command("git", "commit", "-m", "init beads on orphan")
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to commit on orphan: %v", err)
}
// Switch back to main
cmd = exec.Command("git", "checkout", mainBranch)
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to checkout main: %v", err)
}
// Verify NO merge-base after migration (orphan)
cmd = exec.Command("git", "merge-base", mainBranch, syncBranch)
cmd.Dir = tmpDir
output, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("Expected no merge-base after migration to orphan, but got: %s", output)
}
})
}
func TestHasChangesInWorktreeDir(t *testing.T) {
// Create a temp directory with a git repo
tmpDir, err := os.MkdirTemp("", "bd-worktree-changes-test")
if err != nil {
t.Fatalf("failed to create temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
// Copy cached git template (bd-ktng optimization)
initGitTemplate()
if gitTemplateErr != nil {
t.Fatalf("git template init failed: %v", gitTemplateErr)
}
if err := copyGitDir(gitTemplateDir, tmpDir); err != nil {
t.Fatalf("failed to copy git template: %v", err)
}
// Create and commit initial file
testFile := filepath.Join(tmpDir, "test.txt")
if err := os.WriteFile(testFile, []byte("test"), 0644); err != nil {
t.Fatalf("failed to create test file: %v", err)
}
cmd := exec.Command("git", "add", ".")
cmd.Dir = tmpDir
_ = cmd.Run()
cmd = exec.Command("git", "commit", "-m", "initial")
cmd.Dir = tmpDir
_ = cmd.Run()
ctx := context.Background()
// No changes initially
hasChanges, err := hasChangesInWorktreeDir(ctx, tmpDir)
if err != nil {
t.Fatalf("hasChangesInWorktreeDir failed: %v", err)
}
if hasChanges {
t.Error("should have no changes initially")
}
// Add uncommitted file
newFile := filepath.Join(tmpDir, "new.txt")
if err := os.WriteFile(newFile, []byte("new"), 0644); err != nil {
t.Fatalf("failed to create new file: %v", err)
}
hasChanges, err = hasChangesInWorktreeDir(ctx, tmpDir)
if err != nil {
t.Fatalf("hasChangesInWorktreeDir failed: %v", err)
}
if !hasChanges {
t.Error("should have changes after adding file")
}
}

View file

@ -1,131 +1,32 @@
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/gofrs/flock"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/syncbranch"
)
// SyncBranchContext holds sync-branch configuration detected from the store.
// This consolidates the repeated pattern of checking for sync-branch config.
type SyncBranchContext struct {
Branch string // Sync branch name, empty if not configured
RepoRoot string // Git repository root path
}
// IsConfigured returns true if a sync branch is configured.
func (s *SyncBranchContext) IsConfigured() bool {
return s.Branch != ""
}
// getSyncBranchContext detects sync-branch configuration from the store.
// Returns a context with empty Branch if not configured or on error.
func getSyncBranchContext(ctx context.Context) *SyncBranchContext {
sbc := &SyncBranchContext{}
if err := ensureStoreActive(); err != nil || store == nil {
return sbc
}
// Best effort: if syncbranch lookup fails, we proceed without sync branch info
if sb, _ := syncbranch.Get(ctx, store); sb != "" {
sbc.Branch = sb
if rc, err := beads.GetRepoContext(); err == nil {
sbc.RepoRoot = rc.RepoRoot
}
}
return sbc
}
// commitAndPushBeads commits and pushes .beads changes using the appropriate method.
// When sync-branch is configured, uses worktree-based commit/push.
// Otherwise, uses standard git commit/push on the current branch.
func commitAndPushBeads(ctx context.Context, sbc *SyncBranchContext, jsonlPath string, noPush bool, message string) error {
if sbc.IsConfigured() {
fmt.Printf("→ Committing to sync branch '%s'...\n", sbc.Branch)
commitResult, err := syncbranch.CommitToSyncBranch(ctx, sbc.RepoRoot, sbc.Branch, jsonlPath, !noPush)
if err != nil {
return fmt.Errorf("committing to sync branch: %w", err)
}
if commitResult.Committed {
fmt.Printf(" Committed: %s\n", commitResult.Message)
if commitResult.Pushed {
fmt.Println(" Pushed to remote")
}
} else {
fmt.Println("→ No changes to commit")
}
return nil
}
// Standard git workflow
hasChanges, err := gitHasBeadsChanges(ctx)
if err != nil {
return fmt.Errorf("checking git status: %w", err)
}
if hasChanges {
fmt.Println("→ Committing changes...")
if err := gitCommitBeadsDir(ctx, message); err != nil {
return fmt.Errorf("committing: %w", err)
}
} else {
fmt.Println("→ No changes to commit")
}
// Push to remote
if !noPush && hasChanges {
fmt.Println("→ Pushing to remote...")
if err := gitPush(ctx, ""); err != nil {
return fmt.Errorf("pushing: %w", err)
}
}
return nil
}
var syncCmd = &cobra.Command{
Use: "sync",
GroupID: "sync",
Short: "Export database to JSONL (sync with git)",
Long: `Export database to JSONL for git synchronization.
Short: "Sync Dolt database (commit, push, pull)",
Long: `Sync operations for the Dolt database.
By default, exports the current database state to JSONL.
Does NOT stage or commit - that's the user's job.
By default, commits pending changes and pushes to the Dolt remote.
Commands:
bd sync Export to JSONL (prep for push)
bd sync --import Import from JSONL (after pull)
bd sync --status Show sync state
bd sync --resolve Resolve conflicts (uses configured strategy)
bd sync --force Force full export/import (skip incremental)
bd sync --full Full sync: pull → merge → export → commit → push (legacy)
bd sync Commit and push to Dolt remote
bd sync --pull Pull from Dolt remote
bd sync --import Import from JSONL file into database
bd sync --export Export database to JSONL file
Conflict Resolution:
bd sync --resolve Use configured conflict.strategy
bd sync --resolve --ours Keep local versions
bd sync --resolve --theirs Keep remote versions
bd sync --resolve --manual Interactive resolution with prompts
The --manual flag shows a diff for each conflict and prompts you to choose:
l/local - Keep local version
r/remote - Keep remote version
m/merge - Auto-merge (LWW for scalars, union for collections)
s/skip - Skip (keep local, conflict remains for later)
a/all - Accept auto-merge for all remaining conflicts
q/quit - Quit and skip all remaining conflicts
d/diff - Show full JSON diff
The --full flag provides the legacy full sync behavior for backwards compatibility.`,
Examples:
bd sync # Commit + push
bd sync --pull # Pull from remote
bd sync --import # Import JSONL → Dolt
bd sync --export # Export Dolt → JSONL
bd sync -m "updated beads" # Custom commit message`,
Run: func(cmd *cobra.Command, _ []string) {
CheckReadonly("sync")
ctx := rootCtx
@ -133,673 +34,126 @@ The --full flag provides the legacy full sync behavior for backwards compatibili
message, _ := cmd.Flags().GetString("message")
dryRun, _ := cmd.Flags().GetBool("dry-run")
noPush, _ := cmd.Flags().GetBool("no-push")
noPull, _ := cmd.Flags().GetBool("no-pull")
renameOnImport, _ := cmd.Flags().GetBool("rename-on-import")
flushOnly, _ := cmd.Flags().GetBool("flush-only")
importOnly, _ := cmd.Flags().GetBool("import-only")
importFlag, _ := cmd.Flags().GetBool("import")
status, _ := cmd.Flags().GetBool("status")
merge, _ := cmd.Flags().GetBool("merge")
fromMain, _ := cmd.Flags().GetBool("from-main")
noGitHistory, _ := cmd.Flags().GetBool("no-git-history")
squash, _ := cmd.Flags().GetBool("squash")
checkIntegrity, _ := cmd.Flags().GetBool("check")
acceptRebase, _ := cmd.Flags().GetBool("accept-rebase")
fullSync, _ := cmd.Flags().GetBool("full")
resolve, _ := cmd.Flags().GetBool("resolve")
resolveOurs, _ := cmd.Flags().GetBool("ours")
resolveTheirs, _ := cmd.Flags().GetBool("theirs")
resolveManual, _ := cmd.Flags().GetBool("manual")
forceFlag, _ := cmd.Flags().GetBool("force")
importOnly, _ := cmd.Flags().GetBool("import-only")
exportFlag, _ := cmd.Flags().GetBool("export")
flushOnly, _ := cmd.Flags().GetBool("flush-only")
pullFlag, _ := cmd.Flags().GetBool("pull")
// --import is shorthand for --import-only
if importFlag {
importOnly = true
// Aliases
if importOnly {
importFlag = true
}
if flushOnly {
exportFlag = true
}
// If --no-push not explicitly set, check no-push config
if !cmd.Flags().Changed("no-push") {
noPush = config.GetBool("no-push")
}
// Ensure direct store is active for sync operations.
if err := ensureStoreActive(); err != nil {
FatalError("failed to initialize store: %v", err)
}
// Resolve noGitHistory based on fromMain (fixes #417)
noGitHistory = resolveNoGitHistoryForFromMain(fromMain, noGitHistory)
// Handle --set-mode flag
setMode, _ := cmd.Flags().GetString("set-mode")
if setMode != "" {
if err := SetSyncMode(ctx, store, setMode); err != nil {
FatalError("failed to set sync mode: %v", err)
// Import mode: JSONL → Dolt
if importFlag {
jsonlPath := findJSONLPath()
if jsonlPath == "" {
FatalError("no JSONL file found (no .beads directory)")
}
fmt.Printf("✓ Sync mode set to: %s (%s)\n", setMode, SyncModeDescription(setMode))
return
}
// Find JSONL path
jsonlPath := findJSONLPath()
if jsonlPath == "" {
FatalError("not in a bd workspace (no .beads directory found)")
}
// If status mode, show sync state (new format per spec)
if status {
if err := showSyncStateStatus(ctx, jsonlPath); err != nil {
FatalError("%v", err)
}
return
}
// If resolve mode, resolve conflicts
if resolve {
strategy := config.GetConflictStrategy() // use configured default
if resolveOurs {
strategy = config.ConflictStrategyOurs
} else if resolveTheirs {
strategy = config.ConflictStrategyTheirs
} else if resolveManual {
strategy = config.ConflictStrategyManual
}
if err := resolveSyncConflicts(ctx, jsonlPath, strategy, dryRun); err != nil {
FatalError("%v", err)
}
return
}
// If check mode, run pre-sync integrity checks
if checkIntegrity {
showSyncIntegrityCheck(ctx, jsonlPath)
return
}
// If merge mode, merge sync branch to main
if merge {
if err := mergeSyncBranch(ctx, dryRun); err != nil {
FatalError("%v", err)
}
return
}
// If from-main mode, one-way sync from main branch (gt-ick9: ephemeral branch support)
if fromMain {
if err := doSyncFromMain(ctx, jsonlPath, renameOnImport, dryRun, noGitHistory); err != nil {
FatalError("%v", err)
}
return
}
// If import-only mode, just import and exit
// Use inline import to avoid subprocess path resolution issues with .beads/redirect (bd-ysal)
if importOnly {
if dryRun {
fmt.Println("→ [DRY RUN] Would import from JSONL")
} else {
fmt.Println("→ Importing from JSONL...")
if err := importFromJSONLInline(ctx, jsonlPath, renameOnImport, noGitHistory, false); err != nil {
FatalError("importing: %v", err)
}
fmt.Println("✓ Import complete")
}
return
}
// If flush-only mode, just export and exit
if flushOnly {
if dryRun {
fmt.Println("→ [DRY RUN] Would export pending changes to JSONL")
} else {
if err := exportToJSONL(ctx, jsonlPath); err != nil {
FatalError("exporting: %v", err)
}
}
return
}
// If squash mode, export to JSONL but skip git operations
// This accumulates changes for a single commit later
if squash {
if dryRun {
fmt.Println("→ [DRY RUN] Would export pending changes to JSONL (squash mode)")
} else {
fmt.Println("→ Exporting pending changes to JSONL (squash mode)...")
if err := exportToJSONL(ctx, jsonlPath); err != nil {
FatalError("exporting: %v", err)
}
fmt.Println("✓ Changes accumulated in JSONL")
fmt.Println(" Run 'bd sync' (without --squash) to commit all accumulated changes")
}
return
}
// DEFAULT BEHAVIOR: Export to JSONL only (per spec)
// Does NOT stage or commit - that's the user's job.
// Use --full for legacy full sync behavior (pull → merge → export → commit → push)
if !fullSync {
if err := doExportSync(ctx, jsonlPath, forceFlag, dryRun); err != nil {
FatalError("%v", err)
}
return
}
// FULL SYNC MODE (--full flag): Legacy behavior
// Pull → Merge → Export → Commit → Push
// Check if we're in a git repository
if !isGitRepo() {
FatalErrorWithHint("not in a git repository", "run 'git init' to initialize a repository")
}
// Preflight: check for merge/rebase in progress
if inMerge, err := gitHasUnmergedPaths(); err != nil {
FatalError("checking git state: %v", err)
} else if inMerge {
FatalErrorWithHint("unmerged paths or merge in progress", "resolve conflicts, run 'bd import' if needed, then 'bd sync' again")
}
// GH#885: Preflight check for uncommitted JSONL changes
// This detects when a previous sync exported but failed before commit,
// leaving the JSONL in an inconsistent state across worktrees.
if hasUncommitted, err := gitHasUncommittedBeadsChanges(ctx); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to check for uncommitted changes: %v\n", err)
} else if hasUncommitted {
fmt.Println("→ Detected uncommitted JSONL changes (possible incomplete sync)")
fmt.Println("→ Re-exporting from database to reconcile state...")
// Force a fresh export to ensure JSONL matches current DB state
if err := exportToJSONL(ctx, jsonlPath); err != nil {
FatalError("re-exporting to reconcile state: %v", err)
}
fmt.Println("✓ State reconciled")
}
// GH#638: Check sync.branch BEFORE upstream check
// When sync.branch is configured, we should use worktree-based sync even if
// the current branch has no upstream (e.g., detached HEAD in jj, git worktrees)
sbc := getSyncBranchContext(ctx)
// GH#1166: Block sync if currently on the sync branch
// This must happen BEFORE worktree operations - after entering a worktree,
// GetCurrentBranch() would return the worktree's branch, not the original.
if sbc.IsConfigured() {
if syncbranch.IsSyncBranchSameAsCurrent(ctx, sbc.Branch) {
FatalError("Cannot sync to '%s': it's your current branch. "+
"Checkout a different branch first, or use a dedicated sync branch like 'beads-sync'.",
sbc.Branch)
}
}
// bd-wayc3: Check for redirect + sync-branch incompatibility
// Redirect and sync-branch are mutually exclusive:
// - Redirect says: "My database is in another repo (I am a client)"
// - Sync-branch says: "I own my database and sync it myself via worktree"
// When redirect is active, the sync-branch worktree operations fail because
// the beads files are in a different git repo than the current working directory.
redirectInfo := beads.GetRedirectInfo()
if redirectInfo.IsRedirected {
if sbc.IsConfigured() {
fmt.Printf("⚠️ Redirect active (-> %s), skipping sync-branch operations\n", redirectInfo.TargetDir)
fmt.Println(" Hint: Redirected clones should not have sync-branch configured")
fmt.Println(" The owner of the target .beads directory handles sync-branch")
} else {
fmt.Printf("→ Redirect active (-> %s)\n", redirectInfo.TargetDir)
}
// For redirected clones, just do import/export - skip all git operations
// The target repo's owner (e.g., mayor) handles git commit/push via sync-branch
if dryRun {
fmt.Println("→ [DRY RUN] Would export to JSONL (redirected clone, git operations skipped)")
fmt.Println("✓ Dry run complete (no changes made)")
} else {
fmt.Println("→ Exporting to JSONL (redirected clone, skipping git operations)...")
if err := exportToJSONL(ctx, jsonlPath); err != nil {
FatalError("exporting: %v", err)
}
fmt.Println("✓ Export complete (target repo owner handles git sync)")
}
return
}
// Preflight: check for upstream tracking
// If no upstream, automatically switch to --from-main mode (gt-ick9: ephemeral branch support)
// GH#638: Skip this fallback if sync.branch is explicitly configured
if !noPull && !gitHasUpstream() && !sbc.IsConfigured() {
if hasGitRemote(ctx) {
// Remote exists but no upstream - use from-main mode
fmt.Println("→ No upstream configured, using --from-main mode")
// Force noGitHistory=true for auto-detected from-main mode (fixes #417)
if err := doSyncFromMain(ctx, jsonlPath, renameOnImport, dryRun, true); err != nil {
FatalError("%v", err)
}
return
}
// If no remote at all, gitPull/gitPush will gracefully skip
fmt.Println("→ Importing from JSONL...")
if err := importFromJSONL(ctx, jsonlPath); err != nil {
FatalError("importing: %v", err)
}
fmt.Println("✓ Import complete")
return
}
// Pull-first sync: Pull → Merge → Export → Commit → Push
// This eliminates the export-before-pull data loss pattern (#911) by
// seeing remote changes before exporting local state.
if err := doPullFirstSync(ctx, jsonlPath, renameOnImport, noGitHistory, dryRun, noPush, noPull, message, acceptRebase, sbc); err != nil {
FatalError("%v", err)
// Export mode: Dolt → JSONL
if exportFlag {
jsonlPath := findJSONLPath()
if jsonlPath == "" {
FatalError("no JSONL file found (no .beads directory)")
}
if dryRun {
fmt.Println("→ [DRY RUN] Would export to JSONL")
return
}
fmt.Println("→ Exporting to JSONL...")
if err := exportToJSONL(ctx, jsonlPath); err != nil {
FatalError("exporting: %v", err)
}
fmt.Println("✓ Export complete")
return
}
// Pull mode: Pull from Dolt remote
if pullFlag {
if dryRun {
fmt.Println("→ [DRY RUN] Would pull from Dolt remote")
return
}
fmt.Println("→ Pulling from Dolt remote...")
if err := store.Pull(ctx); err != nil {
if strings.Contains(err.Error(), "remote") {
fmt.Println("⚠ No Dolt remote configured")
} else {
FatalError("dolt pull failed: %v", err)
}
} else {
fmt.Println("✓ Pulled from Dolt remote")
}
return
}
// Default: Commit + Push to Dolt remote
if dryRun {
fmt.Println("→ [DRY RUN] Would commit and push to Dolt remote")
return
}
// Commit
fmt.Println("→ Committing to Dolt...")
commandDidExplicitDoltCommit = true
commitMsg := message
if commitMsg == "" {
commitMsg = "bd sync"
}
if err := store.Commit(ctx, commitMsg); err != nil {
if !strings.Contains(err.Error(), "nothing to commit") {
FatalError("dolt commit failed: %v", err)
}
fmt.Println(" Nothing to commit")
}
// Push
if !noPush {
fmt.Println("→ Pushing to Dolt remote...")
if err := store.Push(ctx); err != nil {
if strings.Contains(err.Error(), "remote") {
fmt.Println("⚠ No Dolt remote configured, skipping push")
} else {
FatalError("dolt push failed: %v", err)
}
} else {
fmt.Println("✓ Pushed to Dolt remote")
}
}
fmt.Println("\n✓ Sync complete")
},
}
// doPullFirstSync implements the pull-first sync flow:
// Pull → Merge → Export → Commit → Push
//
// This eliminates the export-before-pull data loss pattern (#911) by
// seeing remote changes before exporting local state.
//
// The 3-way merge uses:
// - Base state: Last successful sync (.beads/sync_base.jsonl)
// - Local state: Current database contents
// - Remote state: JSONL after git pull
//
// When noPull is true, skips the pull/merge steps and just does:
// Export → Commit → Push
func doPullFirstSync(ctx context.Context, jsonlPath string, renameOnImport, noGitHistory, dryRun, noPush, noPull bool, message string, acceptRebase bool, sbc *SyncBranchContext) error {
beadsDir := filepath.Dir(jsonlPath)
_ = acceptRebase // Reserved for future sync branch force-push detection
if dryRun {
if noPull {
fmt.Println("→ [DRY RUN] Would export pending changes to JSONL")
fmt.Println("→ [DRY RUN] Would commit changes")
if !noPush {
fmt.Println("→ [DRY RUN] Would push to remote")
}
} else {
fmt.Println("→ [DRY RUN] Would pull from remote")
fmt.Println("→ [DRY RUN] Would load base state from sync_base.jsonl")
fmt.Println("→ [DRY RUN] Would merge base, local, and remote issues (3-way)")
fmt.Println("→ [DRY RUN] Would export merged state to JSONL")
fmt.Println("→ [DRY RUN] Would update sync_base.jsonl")
fmt.Println("→ [DRY RUN] Would commit and push changes")
}
fmt.Println("\n✓ Dry run complete (no changes made)")
return nil
}
// If noPull, use simplified export-only flow
if noPull {
return doExportOnlySync(ctx, jsonlPath, noPush, message)
}
// Step 1: Load local state from DB BEFORE pulling
// This captures the current DB state before remote changes arrive
if err := ensureStoreActive(); err != nil {
return fmt.Errorf("activating store: %w", err)
}
localIssues, err := store.SearchIssues(ctx, "", beads.IssueFilter{})
if err != nil {
return fmt.Errorf("loading local issues: %w", err)
}
fmt.Printf("→ Loaded %d local issues from database\n", len(localIssues))
// Acquire exclusive lock to prevent concurrent sync corruption
lockPath := filepath.Join(beadsDir, ".sync.lock")
lock := flock.New(lockPath)
locked, err := lock.TryLock()
if err != nil {
return fmt.Errorf("acquiring sync lock: %w", err)
}
if !locked {
// Check if lock file is stale (from a crashed sync process).
// On Unix, flock is released when a process exits, so TryLock normally
// succeeds after a crash. This handles edge cases (NFS, hung processes).
if cleanedUp := cleanStaleSyncLock(lockPath); cleanedUp {
lock = flock.New(lockPath)
locked, err = lock.TryLock()
if err != nil {
return fmt.Errorf("acquiring sync lock after stale cleanup: %w", err)
}
}
if !locked {
return fmt.Errorf("another sync is in progress (lock: %s)", lockPath)
}
}
defer func() { _ = lock.Unlock() }()
// Step 2: Load base state (last successful sync)
fmt.Println("→ Loading base state...")
baseIssues, err := loadBaseState(beadsDir)
if err != nil {
return fmt.Errorf("loading base state: %w", err)
}
if baseIssues == nil {
fmt.Println(" No base state found (first sync)")
} else {
fmt.Printf(" Loaded %d issues from base state\n", len(baseIssues))
}
// Step 3: Pull from remote
// Mode-specific pull behavior:
// - dolt-native/belt-and-suspenders with Dolt remote: Pull from Dolt
// - sync.branch configured: Pull from sync branch via worktree
// - Default (git-portable): Normal git pull
syncMode := GetSyncMode(ctx, store)
shouldUseDolt := ShouldUseDoltRemote(ctx, store)
if shouldUseDolt {
// Dolt pull for dolt-native and belt-and-suspenders modes
fmt.Println("→ Pulling from Dolt remote...")
if err := store.Pull(ctx); err != nil {
// Don't fail if no remote configured
if strings.Contains(err.Error(), "remote") {
fmt.Println("⚠ No Dolt remote configured, skipping Dolt pull")
} else {
return fmt.Errorf("dolt pull failed: %w", err)
}
} else {
fmt.Println("✓ Pulled from Dolt remote")
}
// For belt-and-suspenders, continue with git pull even if Dolt pull failed
}
// Git-based pull (for git-portable, belt-and-suspenders, or when Dolt not available)
// In dolt-native mode, skip git pull for JSONL (JSONL is export-only backup)
if syncMode != SyncModeDoltNative {
if sbc.IsConfigured() {
fmt.Printf("→ Pulling from sync branch '%s'...\n", sbc.Branch)
pullResult, err := syncbranch.PullFromSyncBranch(ctx, sbc.RepoRoot, sbc.Branch, jsonlPath, false)
if err != nil {
return fmt.Errorf("pulling from sync branch: %w", err)
}
// Display any safety warnings from the pull
for _, warning := range pullResult.SafetyWarnings {
fmt.Fprintln(os.Stderr, warning)
}
if pullResult.Merged {
fmt.Println(" Merged divergent sync branch histories")
} else if pullResult.FastForwarded {
fmt.Println(" Fast-forwarded to remote")
}
} else {
fmt.Println("→ Pulling from remote...")
if err := gitPull(ctx, ""); err != nil {
return fmt.Errorf("pulling: %w", err)
}
}
}
// For dolt-native mode, we're done after pulling from Dolt remote
// Dolt handles merging internally, no JSONL workflow needed
if syncMode == SyncModeDoltNative {
fmt.Println("\n✓ Sync complete (dolt-native mode)")
return nil
}
// Step 4: Load remote state from JSONL (after pull)
remoteIssues, err := loadIssuesFromJSONL(jsonlPath)
if err != nil {
return fmt.Errorf("loading remote issues from JSONL: %w", err)
}
fmt.Printf(" Loaded %d remote issues from JSONL\n", len(remoteIssues))
// Step 5: Perform 3-way merge
fmt.Println("→ Merging base, local, and remote issues (3-way)...")
mergeResult := MergeIssues(baseIssues, localIssues, remoteIssues)
// Report merge results
localCount, remoteCount, sameCount := 0, 0, 0
for _, strategy := range mergeResult.Strategy {
switch strategy {
case StrategyLocal:
localCount++
case StrategyRemote:
remoteCount++
case StrategySame:
sameCount++
}
}
fmt.Printf(" Merged: %d issues total\n", len(mergeResult.Merged))
fmt.Printf(" Local wins: %d, Remote wins: %d, Same: %d, Conflicts (LWW): %d\n",
localCount, remoteCount, sameCount, mergeResult.Conflicts)
// Display manual conflicts that need user resolution
if len(mergeResult.ManualConflicts) > 0 {
displayManualConflicts(mergeResult.ManualConflicts)
}
// Step 6: Import merged state to DB
// First, write merged result to JSONL so import can read it
fmt.Println("→ Writing merged state to JSONL...")
if err := writeMergedStateToJSONL(jsonlPath, mergeResult.Merged); err != nil {
return fmt.Errorf("writing merged state: %w", err)
}
fmt.Println("→ Importing merged state to database...")
if err := importFromJSONL(ctx, jsonlPath, renameOnImport, noGitHistory); err != nil {
return fmt.Errorf("importing merged state: %w", err)
}
// Step 7: Export from DB to JSONL (ensures DB is source of truth)
fmt.Println("→ Exporting from database to JSONL...")
if err := exportToJSONL(ctx, jsonlPath); err != nil {
return fmt.Errorf("exporting: %w", err)
}
// Step 8 & 9: Commit and push changes
if err := commitAndPushBeads(ctx, sbc, jsonlPath, noPush, message); err != nil {
return err
}
// Step 10: Update base state for next sync (after successful push)
// Base state only updates after confirmed push to ensure consistency
fmt.Println("→ Updating base state...")
// Reload from exported JSONL to capture any normalization from import/export cycle
finalIssues, err := loadIssuesFromJSONL(jsonlPath)
if err != nil {
return fmt.Errorf("reloading final state: %w", err)
}
if err := saveBaseState(beadsDir, finalIssues); err != nil {
return fmt.Errorf("saving base state: %w", err)
}
fmt.Printf(" Saved %d issues to base state\n", len(finalIssues))
// Step 11: Clear sync state on successful sync
if bd := beads.FindBeadsDir(); bd != "" {
_ = ClearSyncState(bd) // Best effort: stale state is harmless
}
fmt.Println("\n✓ Sync complete")
return nil
}
// doExportOnlySync handles the --no-pull case: just export, commit, and push
func doExportOnlySync(ctx context.Context, jsonlPath string, noPush bool, message string) error {
beadsDir := filepath.Dir(jsonlPath)
// Acquire exclusive lock to prevent concurrent sync corruption
lockPath := filepath.Join(beadsDir, ".sync.lock")
lock := flock.New(lockPath)
locked, err := lock.TryLock()
if err != nil {
return fmt.Errorf("acquiring sync lock: %w", err)
}
if !locked {
// Check if lock file is stale (from a crashed sync process).
if cleanedUp := cleanStaleSyncLock(lockPath); cleanedUp {
lock = flock.New(lockPath)
locked, err = lock.TryLock()
if err != nil {
return fmt.Errorf("acquiring sync lock after stale cleanup: %w", err)
}
}
if !locked {
return fmt.Errorf("another sync is in progress (lock: %s)", lockPath)
}
}
defer func() { _ = lock.Unlock() }()
// Pre-export integrity checks
if err := ensureStoreActive(); err == nil && store != nil {
if err := validatePreExport(ctx, store, jsonlPath); err != nil {
return fmt.Errorf("pre-export validation failed: %w", err)
}
if err := checkDuplicateIDs(ctx, store); err != nil {
return fmt.Errorf("database corruption detected: %w", err)
}
if orphaned, err := checkOrphanedDeps(ctx, store); err != nil {
fmt.Fprintf(os.Stderr, "Warning: orphaned dependency check failed: %v\n", err)
} else if len(orphaned) > 0 {
fmt.Fprintf(os.Stderr, "Warning: found %d orphaned dependencies: %v\n", len(orphaned), orphaned)
}
}
// Template validation before export
if err := validateOpenIssuesForSync(ctx); err != nil {
return err
}
// GH#1173: Detect sync-branch configuration and use appropriate commit method
sbc := getSyncBranchContext(ctx)
fmt.Println("→ Exporting pending changes to JSONL...")
if err := exportToJSONL(ctx, jsonlPath); err != nil {
return fmt.Errorf("exporting: %w", err)
}
// Commit and push using the appropriate method (sync-branch worktree or regular git)
if err := commitAndPushBeads(ctx, sbc, jsonlPath, noPush, message); err != nil {
return err
}
// Clear sync state on successful sync
if bd := beads.FindBeadsDir(); bd != "" {
_ = ClearSyncState(bd) // Best effort: stale state is harmless
}
fmt.Println("\n✓ Sync complete")
return nil
}
// writeMergedStateToJSONL writes merged issues to JSONL file
func writeMergedStateToJSONL(path string, issues []*beads.Issue) error {
tempPath := fmt.Sprintf("%s.tmp.%d.%d", path, os.Getpid(), time.Now().UnixNano())
file, err := os.Create(tempPath) //nolint:gosec // path is trusted internal beads path
if err != nil {
return err
}
encoder := json.NewEncoder(file)
encoder.SetEscapeHTML(false)
for _, issue := range issues {
if err := encoder.Encode(issue); err != nil {
_ = file.Close() // Best-effort cleanup
_ = os.Remove(tempPath)
return err
}
}
if err := file.Close(); err != nil {
_ = os.Remove(tempPath) // Best-effort cleanup
return err
}
return os.Rename(tempPath, path)
}
// doExportSync exports the current database state based on sync mode.
// - git-portable, realtime: Export to JSONL
// - dolt-native: Commit and push to Dolt remote (skip JSONL)
// - belt-and-suspenders: Both JSONL export and Dolt push
// Does NOT stage or commit to git - that's the user's job.
func doExportSync(ctx context.Context, jsonlPath string, _, dryRun bool) error {
if err := ensureStoreActive(); err != nil {
return fmt.Errorf("failed to initialize store: %w", err)
}
shouldExportJSONL := ShouldExportJSONL(ctx, store)
shouldUseDolt := ShouldUseDoltRemote(ctx, store)
if dryRun {
if shouldExportJSONL {
fmt.Println("→ [DRY RUN] Would export database to JSONL")
}
if shouldUseDolt {
fmt.Println("→ [DRY RUN] Would commit and push to Dolt remote")
}
return nil
}
// Handle Dolt remote operations for dolt-native and belt-and-suspenders modes
if shouldUseDolt {
fmt.Println("→ Committing to Dolt...")
// We are explicitly creating a Dolt commit inside sync; avoid redundant auto-commit in PersistentPostRun.
commandDidExplicitDoltCommit = true
if err := store.Commit(ctx, "bd sync: auto-commit"); err != nil {
// Ignore "nothing to commit" errors
if !strings.Contains(err.Error(), "nothing to commit") {
return fmt.Errorf("dolt commit failed: %w", err)
}
}
fmt.Println("→ Pushing to Dolt remote...")
if err := store.Push(ctx); err != nil {
// Don't fail if no remote configured
if !strings.Contains(err.Error(), "remote") {
return fmt.Errorf("dolt push failed: %w", err)
}
fmt.Println("⚠ No Dolt remote configured, skipping push")
} else {
fmt.Println("✓ Pushed to Dolt remote")
}
}
// Export to JSONL for git-portable, realtime, and belt-and-suspenders modes
if shouldExportJSONL {
fmt.Println("Exporting beads to JSONL...")
// Export to JSONL (uses incremental export for large repos)
result, err := exportToJSONLIncrementalDeferred(ctx, jsonlPath)
if err != nil {
return fmt.Errorf("exporting: %w", err)
}
// Finalize export (update metadata)
finalizeExport(ctx, result)
// Report results
totalCount := 0
if result != nil {
totalCount = len(result.ExportedIDs)
}
fmt.Printf("✓ Exported %d issues\n", totalCount)
fmt.Printf("✓ %s updated\n", jsonlPath)
}
return nil
}
func init() {
syncCmd.Flags().StringP("message", "m", "", "Commit message (default: auto-generated)")
syncCmd.Flags().StringP("message", "m", "", "Commit message (default: 'bd sync')")
syncCmd.Flags().Bool("dry-run", false, "Preview sync without making changes")
syncCmd.Flags().Bool("no-push", false, "Skip pushing to remote")
syncCmd.Flags().Bool("no-pull", false, "Skip pulling from remote")
syncCmd.Flags().Bool("rename-on-import", false, "Rename imported issues to match database prefix (updates all references)")
syncCmd.Flags().Bool("flush-only", false, "Only export pending changes to JSONL (skip git operations)")
syncCmd.Flags().Bool("squash", false, "Accumulate changes in JSONL without committing (run 'bd sync' later to commit all)")
syncCmd.Flags().Bool("import-only", false, "Only import from JSONL (skip git operations, useful after git pull)")
syncCmd.Flags().Bool("import", false, "Import from JSONL (shorthand for --import-only)")
syncCmd.Flags().Bool("status", false, "Show sync state (pending changes, last export, conflicts)")
syncCmd.Flags().Bool("merge", false, "Merge sync branch back to main branch")
syncCmd.Flags().Bool("from-main", false, "One-way sync from main branch (for ephemeral branches without upstream)")
syncCmd.Flags().Bool("no-git-history", false, "Skip git history backfill for deletions (use during JSONL filename migrations)")
syncCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output sync statistics in JSON format")
syncCmd.Flags().Bool("check", false, "Pre-sync integrity check: detect forced pushes, prefix mismatches, and orphaned issues")
syncCmd.Flags().Bool("accept-rebase", false, "Accept remote sync branch history (use when force-push detected)")
syncCmd.Flags().Bool("full", false, "Full sync: pull → merge → export → commit → push (legacy behavior)")
syncCmd.Flags().Bool("resolve", false, "Resolve pending sync conflicts")
syncCmd.Flags().Bool("ours", false, "Use 'ours' strategy for conflict resolution (with --resolve)")
syncCmd.Flags().Bool("theirs", false, "Use 'theirs' strategy for conflict resolution (with --resolve)")
syncCmd.Flags().Bool("manual", false, "Use interactive manual resolution for conflicts (with --resolve)")
syncCmd.Flags().Bool("force", false, "Force full export/import (skip incremental optimization)")
syncCmd.Flags().String("set-mode", "", "Set sync mode (git-portable, realtime, dolt-native, belt-and-suspenders)")
syncCmd.Flags().Bool("import", false, "Import from JSONL into database")
syncCmd.Flags().Bool("import-only", false, "Import from JSONL into database (alias for --import)")
syncCmd.Flags().Bool("export", false, "Export database to JSONL")
syncCmd.Flags().Bool("flush-only", false, "Export database to JSONL (alias for --export)")
syncCmd.Flags().Bool("pull", false, "Pull from Dolt remote")
syncCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
rootCmd.AddCommand(syncCmd)
}

View file

@ -1,358 +0,0 @@
package main
import (
"context"
"fmt"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/syncbranch"
)
// getCurrentBranch returns the name of the current git branch in the beads repo.
// Uses symbolic-ref instead of rev-parse to work in fresh repos without commits (bd-flil)
// GH#1110: Now uses RepoContext to ensure we query the beads repo, not CWD.
// Falls back to CWD-based query if no beads context found (for tests/standalone git).
func getCurrentBranch(ctx context.Context) (string, error) {
var cmd *exec.Cmd
if rc, err := beads.GetRepoContext(); err == nil {
cmd = rc.GitCmd(ctx, "symbolic-ref", "--short", "HEAD")
} else {
// Fallback to CWD for tests or repos without beads
cmd = exec.CommandContext(ctx, "git", "symbolic-ref", "--short", "HEAD")
}
output, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("failed to get current branch: %w", err)
}
return strings.TrimSpace(string(output)), nil
}
// getCurrentBranchOrHEAD returns the current branch name, or "HEAD" if in detached HEAD state.
// This is useful for jj/jujutsu compatibility where HEAD is always detached but we still
// need a reference for git operations like log and diff.
func getCurrentBranchOrHEAD(ctx context.Context) string {
branch, err := getCurrentBranch(ctx)
if err != nil {
// Detached HEAD - return "HEAD" as the reference
return "HEAD"
}
return branch
}
// getSyncBranch returns the configured sync branch name
func getSyncBranch(ctx context.Context) (string, error) {
// Ensure store is initialized
if err := ensureStoreActive(); err != nil {
return "", fmt.Errorf("failed to initialize store: %w", err)
}
syncBranch, err := syncbranch.Get(ctx, store)
if err != nil {
return "", fmt.Errorf("failed to get sync branch config: %w", err)
}
if syncBranch == "" {
return "", fmt.Errorf("sync.branch not configured (run 'bd config set sync.branch <branch-name>')")
}
return syncBranch, nil
}
// showSyncStatus shows the diff between sync branch and main branch.
// GH#1110: Now uses RepoContext to ensure git commands run in beads repo.
func showSyncStatus(ctx context.Context) error {
if !isGitRepo() {
return fmt.Errorf("not in a git repository")
}
rc, err := beads.GetRepoContext()
if err != nil {
return fmt.Errorf("failed to get repo context: %w", err)
}
currentBranch := getCurrentBranchOrHEAD(ctx)
syncBranch, err := getSyncBranch(ctx)
if err != nil {
return err
}
// Check if sync branch exists
checkCmd := rc.GitCmd(ctx, "show-ref", "--verify", "--quiet", "refs/heads/"+syncBranch)
if err := checkCmd.Run(); err != nil {
return fmt.Errorf("sync branch '%s' does not exist", syncBranch)
}
fmt.Printf("Current branch: %s\n", currentBranch)
fmt.Printf("Sync branch: %s\n\n", syncBranch)
// Show commit diff
fmt.Println("Commits in sync branch not in main:")
logCmd := rc.GitCmd(ctx, "log", "--oneline", currentBranch+".."+syncBranch)
logOutput, err := logCmd.CombinedOutput()
if err != nil {
return fmt.Errorf("failed to get commit log: %w\n%s", err, logOutput)
}
if len(strings.TrimSpace(string(logOutput))) == 0 {
fmt.Println(" (none)")
} else {
fmt.Print(string(logOutput))
}
fmt.Println("\nCommits in main not in sync branch:")
logCmd = rc.GitCmd(ctx, "log", "--oneline", syncBranch+".."+currentBranch)
logOutput, err = logCmd.CombinedOutput()
if err != nil {
return fmt.Errorf("failed to get commit log: %w\n%s", err, logOutput)
}
if len(strings.TrimSpace(string(logOutput))) == 0 {
fmt.Println(" (none)")
} else {
fmt.Print(string(logOutput))
}
// Show file diff for .beads/issues.jsonl
fmt.Println("\nFile differences in .beads/issues.jsonl:")
diffCmd := rc.GitCmd(ctx, "diff", currentBranch+"..."+syncBranch, "--", ".beads/issues.jsonl")
diffOutput, err := diffCmd.CombinedOutput()
if err != nil {
// diff returns non-zero when there are differences, which is fine
if len(diffOutput) == 0 {
return fmt.Errorf("failed to get diff: %w", err)
}
}
if len(strings.TrimSpace(string(diffOutput))) == 0 {
fmt.Println(" (no differences)")
} else {
fmt.Print(string(diffOutput))
}
return nil
}
// mergeSyncBranch merges the sync branch back to the main branch.
// GH#1110: Now uses RepoContext to ensure git commands run in beads repo.
func mergeSyncBranch(ctx context.Context, dryRun bool) error {
if !isGitRepo() {
return fmt.Errorf("not in a git repository")
}
rc, err := beads.GetRepoContext()
if err != nil {
return fmt.Errorf("failed to get repo context: %w", err)
}
currentBranch, err := getCurrentBranch(ctx)
if err != nil {
return err
}
syncBranch, err := getSyncBranch(ctx)
if err != nil {
return err
}
// Check if sync branch exists
checkCmd := rc.GitCmd(ctx, "show-ref", "--verify", "--quiet", "refs/heads/"+syncBranch)
if err := checkCmd.Run(); err != nil {
return fmt.Errorf("sync branch '%s' does not exist", syncBranch)
}
// Check if there are uncommitted changes
statusCmd := rc.GitCmd(ctx, "status", "--porcelain")
statusOutput, err := statusCmd.Output()
if err != nil {
return fmt.Errorf("failed to check git status: %w", err)
}
if len(strings.TrimSpace(string(statusOutput))) > 0 {
return fmt.Errorf("uncommitted changes detected - commit or stash them first")
}
// GH#1103: Skip-worktree conflict handling removed.
fmt.Printf("Merging sync branch '%s' into '%s'...\n", syncBranch, currentBranch)
if dryRun {
fmt.Println("→ [DRY RUN] Would merge sync branch")
// Show what would be merged
logCmd := rc.GitCmd(ctx, "log", "--oneline", currentBranch+".."+syncBranch)
logOutput, _ := logCmd.CombinedOutput()
if len(strings.TrimSpace(string(logOutput))) > 0 {
fmt.Println("\nCommits that would be merged:")
fmt.Print(string(logOutput))
} else {
fmt.Println("No commits to merge")
}
return nil
}
// Perform the merge
mergeCmd := rc.GitCmd(ctx, "merge", syncBranch, "-m", fmt.Sprintf("Merge sync branch '%s'", syncBranch))
mergeOutput, err := mergeCmd.CombinedOutput()
if err != nil {
return fmt.Errorf("merge failed: %w\n%s", err, mergeOutput)
}
fmt.Print(string(mergeOutput))
fmt.Println("\n✓ Merge complete")
// Suggest next steps
fmt.Println("\nNext steps:")
fmt.Println("1. Review the merged changes")
fmt.Println("2. Run 'bd sync --import-only' to sync the database with merged JSONL")
fmt.Println("3. Run 'bd sync' to push changes to remote")
return nil
}
// isExternalBeadsDir checks if the beads directory is in a different git repo than cwd.
// This is used to detect when BEADS_DIR points to a separate repository.
// Contributed by dand-oss (https://github.com/steveyegge/beads/pull/533)
//
// GH#810: Use git-common-dir for comparison instead of repo root.
// For bare repo worktrees, GetRepoRoot returns incorrect values, causing
// local worktrees to be incorrectly identified as "external". Using
// git-common-dir correctly identifies that worktrees of the same repo
// share the same git directory.
func isExternalBeadsDir(ctx context.Context, beadsDir string) bool {
// Get git common dir of cwd
cwdCommonDir, err := getGitCommonDir(ctx, ".")
if err != nil {
return false // Can't determine, assume local
}
// Get git common dir of beads dir
beadsCommonDir, err := getGitCommonDir(ctx, beadsDir)
if err != nil {
return false // Can't determine, assume local
}
return cwdCommonDir != beadsCommonDir
}
// getGitCommonDir returns the shared git directory for a path.
// For regular repos, this is the .git directory.
// For worktrees, this returns the shared git directory (common to all worktrees).
// This is the correct way to determine if two paths are in the same git repo,
// especially for bare repos and worktrees.
// GH#810: Added to fix bare repo worktree detection.
func getGitCommonDir(ctx context.Context, path string) (string, error) {
cmd := exec.CommandContext(ctx, "git", "-C", path, "rev-parse", "--git-common-dir")
output, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("failed to get git common dir for %s: %w", path, err)
}
result := strings.TrimSpace(string(output))
// Make absolute for reliable comparison
if !filepath.IsAbs(result) {
// Resolve the input path to absolute first
absPath, err := filepath.Abs(path)
if err != nil {
return "", fmt.Errorf("failed to get absolute path for %s: %w", path, err)
}
result = filepath.Join(absPath, result)
}
result = filepath.Clean(result)
// Resolve symlinks for consistent comparison (macOS /var -> /private/var)
if resolved, err := filepath.EvalSymlinks(result); err == nil {
result = resolved
}
return result, nil
}
// getRepoRootFromPath returns the git repository root for a given path.
// Unlike syncbranch.GetRepoRoot which uses cwd, this allows getting the repo root
// for any path.
// Contributed by dand-oss (https://github.com/steveyegge/beads/pull/533)
func getRepoRootFromPath(ctx context.Context, path string) (string, error) {
cmd := exec.CommandContext(ctx, "git", "-C", path, "rev-parse", "--show-toplevel")
output, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("failed to get git root for %s: %w", path, err)
}
return strings.TrimSpace(string(output)), nil
}
// detectAndClearSkipWorktree and restoreSkipWorktree were removed in GH#1103.
// commitToExternalBeadsRepo commits changes directly to an external beads repo.
// Used when BEADS_DIR points to a different git repository than cwd.
// This bypasses the worktree-based sync which fails when beads dir is external.
// Contributed by dand-oss (https://github.com/steveyegge/beads/pull/533)
func commitToExternalBeadsRepo(ctx context.Context, beadsDir, message string, push bool) (bool, error) {
repoRoot, err := getRepoRootFromPath(ctx, beadsDir)
if err != nil {
return false, fmt.Errorf("failed to get repo root: %w", err)
}
// Stage beads files (use relative path from repo root)
relBeadsDir, err := filepath.Rel(repoRoot, beadsDir)
if err != nil {
relBeadsDir = beadsDir // Fallback to absolute path
}
// Use --sparse to work correctly with sparse-checkout enabled worktrees (fixes #1076)
addCmd := exec.CommandContext(ctx, "git", "-C", repoRoot, "add", "--sparse", relBeadsDir) //nolint:gosec // paths from trusted sources
if output, err := addCmd.CombinedOutput(); err != nil {
return false, fmt.Errorf("git add failed: %w\n%s", err, output)
}
// Check if there are staged changes
diffCmd := exec.CommandContext(ctx, "git", "-C", repoRoot, "diff", "--cached", "--quiet") //nolint:gosec // repoRoot from git
if diffCmd.Run() == nil {
return false, nil // No changes to commit
}
// Commit with config-based author and signing options
// Use pathspec to commit ONLY beads files (bd-trgb fix)
// This prevents accidentally committing other staged files
if message == "" {
message = fmt.Sprintf("bd sync: %s", time.Now().Format("2006-01-02 15:04:05"))
}
commitArgs := buildGitCommitArgs(repoRoot, message, "--", relBeadsDir)
commitCmd := exec.CommandContext(ctx, "git", commitArgs...) //nolint:gosec // args from buildGitCommitArgs
if output, err := commitCmd.CombinedOutput(); err != nil {
return false, fmt.Errorf("git commit failed: %w\n%s", err, output)
}
// Push if requested
if push {
pushCmd := exec.CommandContext(ctx, "git", "-C", repoRoot, "push") //nolint:gosec // repoRoot from git
if pushOutput, err := runGitCmdWithTimeoutMsg(ctx, pushCmd, "git push", 5*time.Second); err != nil {
return true, fmt.Errorf("git push failed: %w\n%s", err, pushOutput)
}
}
return true, nil
}
// pullFromExternalBeadsRepo pulls changes in an external beads repo.
// Used when BEADS_DIR points to a different git repository than cwd.
// Contributed by dand-oss (https://github.com/steveyegge/beads/pull/533)
func pullFromExternalBeadsRepo(ctx context.Context, beadsDir string) error {
repoRoot, err := getRepoRootFromPath(ctx, beadsDir)
if err != nil {
return fmt.Errorf("failed to get repo root: %w", err)
}
// Check if remote exists
remoteCmd := exec.CommandContext(ctx, "git", "-C", repoRoot, "remote") //nolint:gosec // repoRoot from git
remoteOutput, err := remoteCmd.Output()
if err != nil || len(strings.TrimSpace(string(remoteOutput))) == 0 {
return nil // No remote, skip pull
}
pullCmd := exec.CommandContext(ctx, "git", "-C", repoRoot, "pull") //nolint:gosec // repoRoot from git
if output, err := pullCmd.CombinedOutput(); err != nil {
return fmt.Errorf("git pull failed: %w\n%s", err, output)
}
return nil
}

View file

@ -1,253 +0,0 @@
//go:build cgo
package main
import (
"context"
"os"
"os/exec"
"path/filepath"
"testing"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/syncbranch"
)
// TestSyncBranchConfigPriorityOverUpstream tests that when sync.branch is configured,
// bd sync should NOT fall back to --from-main mode even if the current branch has no upstream.
// This is the regression test for GH#638.
func TestSyncBranchConfigPriorityOverUpstream(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
ctx := context.Background()
t.Run("sync.branch configured without upstream should not fallback to from-main", func(t *testing.T) {
// Setup: Create a git repo with no upstream tracking
tmpDir, cleanup := setupGitRepo(t)
defer cleanup()
// Create beads database and configure sync.branch
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0750); err != nil {
t.Fatalf("Failed to create .beads dir: %v", err)
}
dbPath := filepath.Join(beadsDir, "beads.db")
testStore, err := dolt.New(ctx, &dolt.Config{Path: dbPath})
if err != nil {
t.Fatalf("Failed to create test database: %v", err)
}
defer testStore.Close()
// Configure sync.branch
if err := syncbranch.Set(ctx, testStore, "beads-sync"); err != nil {
t.Fatalf("Failed to set sync.branch: %v", err)
}
// Verify sync.branch is configured
syncBranch, err := syncbranch.Get(ctx, testStore)
if err != nil {
t.Fatalf("Failed to get sync.branch: %v", err)
}
if syncBranch != "beads-sync" {
t.Errorf("Expected sync.branch='beads-sync', got %q", syncBranch)
}
// Verify we have no upstream
if gitHasUpstream() {
t.Skip("Test requires no upstream tracking")
}
// The key assertion: hasSyncBranchConfig should be true
// which prevents fallback to from-main mode
var hasSyncBranchConfig bool
if syncBranch != "" {
hasSyncBranchConfig = true
}
if !hasSyncBranchConfig {
t.Error("hasSyncBranchConfig should be true when sync.branch is configured")
}
// With the fix, this condition should be false (should NOT fallback)
shouldFallbackToFromMain := !gitHasUpstream() && !hasSyncBranchConfig
if shouldFallbackToFromMain {
t.Error("Should NOT fallback to from-main when sync.branch is configured")
}
})
t.Run("no sync.branch and no upstream should fallback to from-main", func(t *testing.T) {
// Setup: Create a git repo with no upstream tracking
_, cleanup := setupGitRepo(t)
defer cleanup()
// No sync.branch configured, no upstream
hasSyncBranchConfig := false
// Verify we have no upstream
if gitHasUpstream() {
t.Skip("Test requires no upstream tracking")
}
// With no sync.branch, should fallback to from-main
shouldFallbackToFromMain := !gitHasUpstream() && !hasSyncBranchConfig
if !shouldFallbackToFromMain {
t.Error("Should fallback to from-main when no sync.branch and no upstream")
}
})
t.Run("detached HEAD with sync.branch should not fallback", func(t *testing.T) {
// Setup: Create a git repo and detach HEAD (simulating jj workflow)
tmpDir, cleanup := setupGitRepo(t)
defer cleanup()
// Get current commit hash
cmd := exec.Command("git", "rev-parse", "HEAD")
output, err := cmd.Output()
if err != nil {
t.Fatalf("Failed to get HEAD: %v", err)
}
commitHash := string(output[:len(output)-1]) // trim newline
// Detach HEAD
cmd = exec.Command("git", "checkout", "--detach", commitHash)
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to detach HEAD: %v", err)
}
// Create beads database and configure sync.branch
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0750); err != nil {
t.Fatalf("Failed to create .beads dir: %v", err)
}
dbPath := filepath.Join(beadsDir, "beads.db")
testStore, err := dolt.New(ctx, &dolt.Config{Path: dbPath})
if err != nil {
t.Fatalf("Failed to create test database: %v", err)
}
defer testStore.Close()
// Configure sync.branch
if err := syncbranch.Set(ctx, testStore, "beads-sync"); err != nil {
t.Fatalf("Failed to set sync.branch: %v", err)
}
// Verify detached HEAD has no upstream
if gitHasUpstream() {
t.Error("Detached HEAD should not have upstream")
}
// With sync.branch configured, should NOT fallback
hasSyncBranchConfig := true
shouldFallbackToFromMain := !gitHasUpstream() && !hasSyncBranchConfig
if shouldFallbackToFromMain {
t.Error("Detached HEAD with sync.branch should NOT fallback to from-main")
}
})
}
// TestSyncBranchBypassesGitHasBeadsChanges tests that when sync.branch is configured,
// bd sync bypasses gitHasBeadsChanges and always calls CommitToSyncBranch.
// This is the regression test for GH#812: when .beads/ is gitignored on code branches
// (but tracked on the sync branch), gitHasBeadsChanges would return false, causing
// sync to skip CommitToSyncBranch entirely - even though CommitToSyncBranch has its
// own internal change detection that checks the worktree where gitignore is different.
func TestSyncBranchBypassesGitHasBeadsChanges(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
ctx := context.Background()
t.Run("CommitToSyncBranch detects changes even when main repo has gitignored beads", func(t *testing.T) {
// Setup: Create a git repo with sync-branch configured
tmpDir, cleanup := setupGitRepo(t)
defer cleanup()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0750); err != nil {
t.Fatalf("Failed to create .beads dir: %v", err)
}
// Create a sync branch with initial content
syncBranch := "beads-sync"
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
// Write initial content
if err := os.WriteFile(jsonlPath, []byte(`{"id":"test-1","title":"Initial"}`+"\n"), 0600); err != nil {
t.Fatalf("Failed to write initial JSONL: %v", err)
}
// Create sync branch and commit the initial content
if err := exec.Command("git", "checkout", "-b", syncBranch).Run(); err != nil {
t.Fatalf("Failed to create sync branch: %v", err)
}
if err := exec.Command("git", "add", ".").Run(); err != nil {
t.Fatalf("Failed to add files: %v", err)
}
if err := exec.Command("git", "commit", "-m", "initial sync").Run(); err != nil {
t.Fatalf("Failed to commit: %v", err)
}
if err := exec.Command("git", "checkout", "main").Run(); err != nil {
t.Fatalf("Failed to checkout main: %v", err)
}
// Recreate .beads directory on main branch (it may not exist after checkout)
if err := os.MkdirAll(beadsDir, 0750); err != nil {
t.Fatalf("Failed to recreate .beads dir: %v", err)
}
// Now add a gitignore that ignores all beads files on the code branch
// (simulating the pattern from GH#812)
gitignorePath := filepath.Join(beadsDir, ".gitignore")
gitignoreContent := `# On code branches, ignore all data files.
# The beads-sync branch tracks issues.jsonl, etc.
*
!.gitignore
`
if err := os.WriteFile(gitignorePath, []byte(gitignoreContent), 0600); err != nil {
t.Fatalf("Failed to write .gitignore: %v", err)
}
if err := exec.Command("git", "add", gitignorePath).Run(); err != nil {
t.Fatalf("Failed to add .gitignore: %v", err)
}
if err := exec.Command("git", "commit", "-m", "add gitignore").Run(); err != nil {
t.Fatalf("Failed to commit .gitignore: %v", err)
}
// Now update the JSONL file (this change is gitignored on main branch)
newContent := `{"id":"test-1","title":"Initial"}` + "\n" + `{"id":"test-2","title":"New issue"}` + "\n"
if err := os.WriteFile(jsonlPath, []byte(newContent), 0600); err != nil {
t.Fatalf("Failed to update JSONL: %v", err)
}
// Verify gitHasBeadsChanges returns false (file is gitignored)
hasChanges, err := gitHasBeadsChanges(ctx)
if err != nil {
t.Fatalf("gitHasBeadsChanges error: %v", err)
}
if hasChanges {
t.Log("Note: gitHasBeadsChanges returned true (gitignore may not be working as expected in test env)")
// Continue test anyway - the key assertion is that CommitToSyncBranch works
} else {
t.Log("gitHasBeadsChanges correctly returned false (file is gitignored)")
}
// The key assertion: CommitToSyncBranch should still detect and commit changes
// because it checks the worktree where the gitignore is different
result, err := syncbranch.CommitToSyncBranch(ctx, tmpDir, syncBranch, jsonlPath, false)
if err != nil {
t.Fatalf("CommitToSyncBranch error: %v", err)
}
if !result.Committed {
t.Error("CommitToSyncBranch() Committed = false, want true")
t.Error("This indicates the GH#812 fix regression: sync branch worktree should detect changes even when main repo has files gitignored")
} else {
t.Log("CommitToSyncBranch correctly detected and committed changes to worktree")
}
})
}

View file

@ -1,248 +0,0 @@
package main
import (
"bufio"
"context"
"encoding/json"
"fmt"
"log/slog"
"os"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/validation"
)
// resolveNoGitHistoryForFromMain returns the effective noGitHistory flag.
// When fromMain is true, noGitHistory defaults to true (fixes #417).
func resolveNoGitHistoryForFromMain(fromMain, noGitHistory bool) bool {
if fromMain && !noGitHistory {
return true
}
return noGitHistory
}
// exportToJSONL exports the current database state to the JSONL file.
// Delegates to exportToJSONLWithStore using the global store.
func exportToJSONL(ctx context.Context, jsonlPath string) error {
if err := ensureStoreActive(); err != nil {
return fmt.Errorf("activating store: %w", err)
}
if err := exportToJSONLWithStore(ctx, store, jsonlPath); err != nil {
return err
}
// Update content hash metadata after successful export
repoKey := getRepoKeyForPath(jsonlPath)
updateExportMetadata(ctx, store, jsonlPath, slog.Default(), repoKey)
return nil
}
// importFromJSONL imports issues from a JSONL file into the database.
// Parameters renameOnImport and noGitHistory are accepted for API compatibility
// but are no longer used in the Dolt-only world.
func importFromJSONL(ctx context.Context, jsonlPath string, _, _ bool) error {
if err := ensureStoreActive(); err != nil {
return fmt.Errorf("activating store: %w", err)
}
return importToJSONLWithStore(ctx, store, jsonlPath)
}
// importFromJSONLInline imports issues from JSONL inline (without subprocess).
// This was the inline variant of importFromJSONL to avoid subprocess path resolution
// issues. In the Dolt-only world, both functions are equivalent.
func importFromJSONLInline(ctx context.Context, jsonlPath string, renameOnImport, noGitHistory, _ bool) error {
return importFromJSONL(ctx, jsonlPath, renameOnImport, noGitHistory)
}
// loadIssuesFromJSONL reads a JSONL file and returns the parsed issues.
func loadIssuesFromJSONL(jsonlPath string) ([]*types.Issue, error) {
file, err := os.Open(jsonlPath) // #nosec G304 - controlled path
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, fmt.Errorf("opening JSONL: %w", err)
}
defer file.Close()
var issues []*types.Issue
scanner := bufio.NewScanner(file)
const maxScannerBuffer = 1024 * 1024 // 1MB
scanner.Buffer(make([]byte, 0, maxScannerBuffer), maxScannerBuffer)
lineNum := 0
for scanner.Scan() {
lineNum++
line := scanner.Text()
if line == "" {
continue
}
var issue types.Issue
if err := json.Unmarshal([]byte(line), &issue); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to parse JSONL line %d: %v\n", lineNum, err)
continue
}
issues = append(issues, &issue)
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("reading JSONL: %w", err)
}
return issues, nil
}
// doSyncFromMain performs a one-way sync from the main branch.
// Reads the JSONL from main and imports it into the current database.
func doSyncFromMain(ctx context.Context, jsonlPath string, renameOnImport, dryRun, noGitHistory bool) error {
if dryRun {
fmt.Println("→ [DRY RUN] Would sync from main branch")
return nil
}
// Read JSONL from main branch via git
relPath, err := getRelativeGitPath(jsonlPath)
if err != nil {
return fmt.Errorf("getting relative path: %w", err)
}
mainData, err := readFromGitRef(relPath, "main")
if err != nil {
// Try "master" as fallback
mainData, err = readFromGitRef(relPath, "master")
if err != nil {
return fmt.Errorf("reading JSONL from main branch: %w", err)
}
}
// Write main branch content to a temp file for import
tmpFile, err := os.CreateTemp("", "bd-sync-from-main-*.jsonl")
if err != nil {
return fmt.Errorf("creating temp file: %w", err)
}
tmpPath := tmpFile.Name()
defer os.Remove(tmpPath)
if _, err := tmpFile.Write(mainData); err != nil {
tmpFile.Close()
return fmt.Errorf("writing temp file: %w", err)
}
tmpFile.Close()
// Import from the temp file
fmt.Println("→ Importing from main branch...")
if err := importFromJSONL(ctx, tmpPath, renameOnImport, noGitHistory); err != nil {
return fmt.Errorf("importing from main: %w", err)
}
// Export back to update local JSONL
fmt.Println("→ Exporting to JSONL...")
if err := exportToJSONL(ctx, jsonlPath); err != nil {
return fmt.Errorf("exporting: %w", err)
}
fmt.Println("✓ Synced from main branch")
return nil
}
// getRelativeGitPath converts an absolute path to a git-relative path.
func getRelativeGitPath(absPath string) (string, error) {
// Use the beads dir to find the git root
beadsDir := findJSONLPath()
if beadsDir == "" {
return absPath, nil // fallback
}
// Git show needs repo-relative paths
// Simple approach: try the path as-is and let git figure it out
return absPath, nil
}
// ExportResult describes the outcome of an incremental export operation.
type ExportResult struct {
ExportedIDs []string
}
// exportToJSONLIncrementalDeferred performs an export and returns the result.
// In the Dolt-only world, this delegates to the standard export.
func exportToJSONLIncrementalDeferred(ctx context.Context, jsonlPath string) (*ExportResult, error) {
if err := ensureStoreActive(); err != nil {
return nil, fmt.Errorf("activating store: %w", err)
}
// Get all issues for the result
issues, err := store.SearchIssues(ctx, "", types.IssueFilter{})
if err != nil {
return nil, fmt.Errorf("getting issues: %w", err)
}
// Perform the export
if err := exportToJSONLWithStore(ctx, store, jsonlPath); err != nil {
return nil, err
}
// Build result
result := &ExportResult{
ExportedIDs: make([]string, 0, len(issues)),
}
for _, issue := range issues {
result.ExportedIDs = append(result.ExportedIDs, issue.ID)
}
return result, nil
}
// validateOpenIssuesForSync checks that open issues pass template validation before sync.
// Controlled by the "validation.on-sync" config key:
// - "none" or "": skip validation (default)
// - "warn": validate and warn but don't block
// - "error": validate and block sync if issues fail
func validateOpenIssuesForSync(ctx context.Context) error {
mode := config.GetString("validation.on-sync")
if mode == "" || mode == "none" {
return nil
}
if err := ensureStoreActive(); err != nil {
return nil // Can't validate without store, skip
}
openStatus := types.StatusOpen
issues, err := store.SearchIssues(ctx, "", types.IssueFilter{Status: &openStatus})
if err != nil {
return nil // Skip validation on error
}
var invalidCount int
for _, issue := range issues {
// Skip chores - they don't have required sections
if issue.IssueType == types.TypeChore {
continue
}
if err := validation.ValidateTemplate(issue.IssueType, issue.Description); err != nil {
invalidCount++
if mode == "warn" || mode == "error" {
fmt.Fprintf(os.Stderr, "Warning: %s fails template validation: %v\n", issue.ID, err)
}
}
}
if invalidCount > 0 && mode == "error" {
return fmt.Errorf("%d open issue(s) fail template validation (set validation.on-sync=warn to allow)", invalidCount)
}
return nil
}
// finalizeExport updates metadata after a successful export.
func finalizeExport(ctx context.Context, result *ExportResult) {
if result == nil || store == nil {
return
}
jsonlPath := findJSONLPath()
if jsonlPath == "" {
return
}
repoKey := getRepoKeyForPath(jsonlPath)
updateExportMetadata(ctx, store, jsonlPath, slog.Default(), repoKey)
}

View file

@ -1,397 +0,0 @@
package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"strings"
"time"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/syncbranch"
)
// SyncIntegrityResult contains the results of a pre-sync integrity check.
type SyncIntegrityResult struct {
ForcedPush *ForcedPushCheck `json:"forced_push,omitempty"`
PrefixMismatch *PrefixMismatch `json:"prefix_mismatch,omitempty"`
OrphanedChildren *OrphanedChildren `json:"orphaned_children,omitempty"`
HasProblems bool `json:"has_problems"`
}
// ForcedPushCheck detects if sync branch has diverged from remote.
type ForcedPushCheck struct {
Detected bool `json:"detected"`
LocalRef string `json:"local_ref,omitempty"`
RemoteRef string `json:"remote_ref,omitempty"`
Message string `json:"message"`
}
// PrefixMismatch detects issues with wrong prefix in JSONL.
type PrefixMismatch struct {
ConfiguredPrefix string `json:"configured_prefix"`
MismatchedIDs []string `json:"mismatched_ids,omitempty"`
Count int `json:"count"`
}
// OrphanedChildren detects issues with parent that doesn't exist.
type OrphanedChildren struct {
OrphanedIDs []string `json:"orphaned_ids,omitempty"`
Count int `json:"count"`
}
// showSyncIntegrityCheck performs pre-sync integrity checks without modifying state.
// Detects forced pushes, prefix mismatches, and orphaned children.
// Exits with code 1 if problems are detected.
func showSyncIntegrityCheck(ctx context.Context, jsonlPath string) {
fmt.Println("Sync Integrity Check")
fmt.Println("====================")
result := &SyncIntegrityResult{}
// Check 1: Detect forced pushes on sync branch
forcedPush := checkForcedPush(ctx)
result.ForcedPush = forcedPush
if forcedPush.Detected {
result.HasProblems = true
}
printForcedPushResult(forcedPush)
// Check 2: Detect prefix mismatches in JSONL
prefixMismatch, err := checkPrefixMismatch(ctx, jsonlPath)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: prefix check failed: %v\n", err)
} else {
result.PrefixMismatch = prefixMismatch
if prefixMismatch != nil && prefixMismatch.Count > 0 {
result.HasProblems = true
}
printPrefixMismatchResult(prefixMismatch)
}
// Check 3: Detect orphaned children (parent issues that don't exist)
orphaned, err := checkOrphanedChildrenInJSONL(jsonlPath)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: orphaned check failed: %v\n", err)
} else {
result.OrphanedChildren = orphaned
if orphaned != nil && orphaned.Count > 0 {
result.HasProblems = true
}
printOrphanedChildrenResult(orphaned)
}
// Summary
fmt.Println("\nSummary")
fmt.Println("-------")
if result.HasProblems {
fmt.Println("Problems detected! Review above and consider:")
if result.ForcedPush != nil && result.ForcedPush.Detected {
fmt.Println(" - Force push: Reset local sync branch or use 'bd sync --from-main'")
}
if result.PrefixMismatch != nil && result.PrefixMismatch.Count > 0 {
fmt.Println(" - Prefix mismatch: Use 'bd import --rename-on-import' to fix")
}
if result.OrphanedChildren != nil && result.OrphanedChildren.Count > 0 {
fmt.Println(" - Orphaned children: Remove parent references or create missing parents")
}
os.Exit(1)
} else {
fmt.Println("No problems detected. Safe to sync.")
}
if jsonOutput {
data, _ := json.MarshalIndent(result, "", " ") // json.MarshalIndent on simple structs does not fail in practice
fmt.Println(string(data))
}
}
// checkForcedPush detects if the sync branch has diverged from remote.
// This can happen when someone force-pushes to the sync branch.
// GH#1110: Now uses RepoContext to ensure git commands run in beads repo.
func checkForcedPush(ctx context.Context) *ForcedPushCheck {
result := &ForcedPushCheck{
Detected: false,
Message: "No sync branch configured or no remote",
}
// Get RepoContext for beads repo
rc, err := beads.GetRepoContext()
if err != nil {
result.Message = fmt.Sprintf("Failed to get repo context: %v", err)
return result
}
// Get sync branch name
if err := ensureStoreActive(); err != nil {
return result
}
syncBranch, _ := syncbranch.Get(ctx, store) // Best effort: empty syncBranch means feature not configured
if syncBranch == "" {
return result
}
// Check if sync branch exists locally
checkLocalCmd := rc.GitCmd(ctx, "show-ref", "--verify", "--quiet", "refs/heads/"+syncBranch)
if checkLocalCmd.Run() != nil {
result.Message = fmt.Sprintf("Sync branch '%s' does not exist locally", syncBranch)
return result
}
// Get local ref
localRefCmd := rc.GitCmd(ctx, "rev-parse", syncBranch)
localRefOutput, err := localRefCmd.Output()
if err != nil {
result.Message = "Failed to get local sync branch ref"
return result
}
localRef := strings.TrimSpace(string(localRefOutput))
result.LocalRef = localRef
// Check if remote tracking branch exists
remote := "origin"
if configuredRemote, err := store.GetConfig(ctx, "sync.remote"); err == nil && configuredRemote != "" {
remote = configuredRemote
}
// Get remote ref
remoteRefCmd := rc.GitCmd(ctx, "rev-parse", remote+"/"+syncBranch)
remoteRefOutput, err := remoteRefCmd.Output()
if err != nil {
result.Message = fmt.Sprintf("Remote tracking branch '%s/%s' does not exist", remote, syncBranch)
return result
}
remoteRef := strings.TrimSpace(string(remoteRefOutput))
result.RemoteRef = remoteRef
// If refs match, no divergence
if localRef == remoteRef {
result.Message = "Sync branch is in sync with remote"
return result
}
// Check if local is ahead of remote (normal case)
aheadCmd := rc.GitCmd(ctx, "merge-base", "--is-ancestor", remoteRef, localRef)
if aheadCmd.Run() == nil {
result.Message = "Local sync branch is ahead of remote (normal)"
return result
}
// Check if remote is ahead of local (behind, needs pull)
behindCmd := rc.GitCmd(ctx, "merge-base", "--is-ancestor", localRef, remoteRef)
if behindCmd.Run() == nil {
result.Message = "Local sync branch is behind remote (needs pull)"
return result
}
// If neither is ancestor, branches have diverged - likely a force push
result.Detected = true
result.Message = fmt.Sprintf("Sync branch has DIVERGED from remote! Local: %s, Remote: %s. This may indicate a force push on the remote.", localRef[:8], remoteRef[:8])
return result
}
func printForcedPushResult(fp *ForcedPushCheck) {
fmt.Println("1. Force Push Detection")
if fp.Detected {
fmt.Printf(" [PROBLEM] %s\n", fp.Message)
} else {
fmt.Printf(" [OK] %s\n", fp.Message)
}
fmt.Println()
}
// checkPrefixMismatch detects issues in JSONL that don't match the configured prefix.
func checkPrefixMismatch(ctx context.Context, jsonlPath string) (*PrefixMismatch, error) {
result := &PrefixMismatch{
MismatchedIDs: []string{},
}
// Get configured prefix
if err := ensureStoreActive(); err != nil {
return nil, err
}
prefix, err := store.GetConfig(ctx, "issue_prefix")
if err != nil || prefix == "" {
prefix = "bd" // Default
}
result.ConfiguredPrefix = prefix
// Read JSONL and check each issue's prefix
f, err := os.Open(jsonlPath) // #nosec G304 - controlled path
if err != nil {
if os.IsNotExist(err) {
return result, nil // No JSONL, no mismatches
}
return nil, fmt.Errorf("failed to open JSONL: %w", err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
scanner.Buffer(make([]byte, 0, 64*1024), 10*1024*1024)
for scanner.Scan() {
line := scanner.Bytes()
if len(bytes.TrimSpace(line)) == 0 {
continue
}
var issue struct {
ID string `json:"id"`
}
if err := json.Unmarshal(line, &issue); err != nil {
continue // Skip malformed lines
}
// Check if ID starts with configured prefix
if !strings.HasPrefix(issue.ID, prefix+"-") {
result.MismatchedIDs = append(result.MismatchedIDs, issue.ID)
}
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("failed to read JSONL: %w", err)
}
result.Count = len(result.MismatchedIDs)
return result, nil
}
func printPrefixMismatchResult(pm *PrefixMismatch) {
fmt.Println("2. Prefix Mismatch Check")
if pm == nil {
fmt.Println(" [SKIP] Could not check prefix")
fmt.Println()
return
}
fmt.Printf(" Configured prefix: %s\n", pm.ConfiguredPrefix)
if pm.Count > 0 {
fmt.Printf(" [PROBLEM] Found %d issue(s) with wrong prefix:\n", pm.Count)
// Show first 10
limit := pm.Count
if limit > 10 {
limit = 10
}
for i := 0; i < limit; i++ {
fmt.Printf(" - %s\n", pm.MismatchedIDs[i])
}
if pm.Count > 10 {
fmt.Printf(" ... and %d more\n", pm.Count-10)
}
} else {
fmt.Println(" [OK] All issues have correct prefix")
}
fmt.Println()
}
// checkOrphanedChildrenInJSONL detects issues with parent references to non-existent issues.
func checkOrphanedChildrenInJSONL(jsonlPath string) (*OrphanedChildren, error) {
result := &OrphanedChildren{
OrphanedIDs: []string{},
}
// Read JSONL and build maps of IDs and parent references
f, err := os.Open(jsonlPath) // #nosec G304 - controlled path
if err != nil {
if os.IsNotExist(err) {
return result, nil
}
return nil, fmt.Errorf("failed to open JSONL: %w", err)
}
defer f.Close()
existingIDs := make(map[string]bool)
parentRefs := make(map[string]string) // child ID -> parent ID
scanner := bufio.NewScanner(f)
scanner.Buffer(make([]byte, 0, 64*1024), 10*1024*1024)
for scanner.Scan() {
line := scanner.Bytes()
if len(bytes.TrimSpace(line)) == 0 {
continue
}
var issue struct {
ID string `json:"id"`
Parent string `json:"parent,omitempty"`
Status string `json:"status"`
}
if err := json.Unmarshal(line, &issue); err != nil {
continue
}
existingIDs[issue.ID] = true
if issue.Parent != "" {
parentRefs[issue.ID] = issue.Parent
}
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("failed to read JSONL: %w", err)
}
// Find orphaned children (parent doesn't exist)
for childID, parentID := range parentRefs {
if !existingIDs[parentID] {
result.OrphanedIDs = append(result.OrphanedIDs, fmt.Sprintf("%s (parent: %s)", childID, parentID))
}
}
result.Count = len(result.OrphanedIDs)
return result, nil
}
// runGitCmdWithTimeoutMsg runs a git command and prints a helpful message if it takes too long.
// This helps when git operations hang waiting for credential/browser auth.
func runGitCmdWithTimeoutMsg(ctx context.Context, cmd *exec.Cmd, cmdName string, timeoutDelay time.Duration) ([]byte, error) {
// Use done channel to cleanly exit goroutine when command completes
done := make(chan struct{})
go func() {
select {
case <-time.After(timeoutDelay):
fmt.Fprintf(os.Stderr, "⏳ %s is taking longer than expected (possibly waiting for authentication). If this hangs, check for a browser auth prompt or run 'git status' in another terminal.\n", cmdName)
case <-done:
// Command completed, exit cleanly
case <-ctx.Done():
// Context canceled, don't print message
}
}()
output, err := cmd.CombinedOutput()
close(done)
return output, err
}
func printOrphanedChildrenResult(oc *OrphanedChildren) {
fmt.Println("3. Orphaned Children Check")
if oc == nil {
fmt.Println(" [SKIP] Could not check orphaned children")
fmt.Println()
return
}
if oc.Count > 0 {
fmt.Printf(" [PROBLEM] Found %d issue(s) with missing parent:\n", oc.Count)
limit := oc.Count
if limit > 10 {
limit = 10
}
for i := 0; i < limit; i++ {
fmt.Printf(" - %s\n", oc.OrphanedIDs[i])
}
if oc.Count > 10 {
fmt.Printf(" ... and %d more\n", oc.Count-10)
}
} else {
fmt.Println(" [OK] No orphaned children found")
}
fmt.Println()
}

View file

@ -1,354 +0,0 @@
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/config"
)
// SyncConflictState tracks pending sync conflicts.
type SyncConflictState struct {
Conflicts []SyncConflictRecord `json:"conflicts,omitempty"`
}
// SyncConflictRecord represents a conflict detected during sync.
type SyncConflictRecord struct {
IssueID string `json:"issue_id"`
Reason string `json:"reason"`
LocalVersion string `json:"local_version,omitempty"`
RemoteVersion string `json:"remote_version,omitempty"`
Strategy string `json:"strategy,omitempty"` // how it was resolved
}
// LoadSyncConflictState loads the sync conflict state from disk.
func LoadSyncConflictState(beadsDir string) (*SyncConflictState, error) {
path := filepath.Join(beadsDir, "sync_conflicts.json")
// #nosec G304 -- path is derived from the workspace .beads directory
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return &SyncConflictState{}, nil
}
return nil, err
}
var state SyncConflictState
if err := json.Unmarshal(data, &state); err != nil {
return nil, err
}
return &state, nil
}
// SaveSyncConflictState saves the sync conflict state to disk.
func SaveSyncConflictState(beadsDir string, state *SyncConflictState) error {
path := filepath.Join(beadsDir, "sync_conflicts.json")
data, err := json.MarshalIndent(state, "", " ")
if err != nil {
return err
}
return os.WriteFile(path, data, 0600)
}
// ClearSyncConflictState removes the sync conflict state file.
func ClearSyncConflictState(beadsDir string) error {
path := filepath.Join(beadsDir, "sync_conflicts.json")
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
return err
}
return nil
}
// resolveSyncConflicts resolves pending sync conflicts using the specified strategy.
// Strategies:
// - "newest": Keep whichever version has the newer updated_at timestamp (default)
// - "ours": Keep local version
// - "theirs": Keep remote version
// - "manual": Interactive resolution with user prompts
func resolveSyncConflicts(ctx context.Context, jsonlPath string, strategy config.ConflictStrategy, dryRun bool) error {
beadsDir := filepath.Dir(jsonlPath)
conflictState, err := LoadSyncConflictState(beadsDir)
if err != nil {
return fmt.Errorf("loading sync conflicts: %w", err)
}
if len(conflictState.Conflicts) == 0 {
fmt.Println("No conflicts to resolve")
return nil
}
if dryRun {
fmt.Printf("→ [DRY RUN] Would resolve %d conflicts using '%s' strategy\n", len(conflictState.Conflicts), strategy)
for _, c := range conflictState.Conflicts {
fmt.Printf(" - %s: %s\n", c.IssueID, c.Reason)
}
return nil
}
fmt.Printf("Resolving conflicts using '%s' strategy...\n", strategy)
// Load base, local, and remote states for merge
baseIssues, err := loadBaseState(beadsDir)
if err != nil {
return fmt.Errorf("loading base state: %w", err)
}
if err := ensureStoreActive(); err != nil {
return fmt.Errorf("initializing store: %w", err)
}
localIssues, err := store.SearchIssues(ctx, "", beads.IssueFilter{})
if err != nil {
return fmt.Errorf("loading local issues: %w", err)
}
remoteIssues, err := loadIssuesFromJSONL(jsonlPath)
if err != nil {
return fmt.Errorf("loading remote issues: %w", err)
}
// Build maps for quick lookup
baseMap := make(map[string]*beads.Issue)
for _, issue := range baseIssues {
baseMap[issue.ID] = issue
}
localMap := make(map[string]*beads.Issue)
for _, issue := range localIssues {
localMap[issue.ID] = issue
}
remoteMap := make(map[string]*beads.Issue)
for _, issue := range remoteIssues {
remoteMap[issue.ID] = issue
}
// Handle manual strategy with interactive resolution
if strategy == config.ConflictStrategyManual {
return resolveSyncConflictsManually(ctx, jsonlPath, beadsDir, conflictState, baseMap, localMap, remoteMap)
}
// Determine winner for each conflict based on strategy
winners := make(map[string]*beads.Issue) // issueID -> winning version
resolved := 0
for _, conflict := range conflictState.Conflicts {
local := localMap[conflict.IssueID]
remote := remoteMap[conflict.IssueID]
var winner string
switch strategy {
case config.ConflictStrategyOurs:
winner = "local"
case config.ConflictStrategyTheirs:
winner = "remote"
case config.ConflictStrategyNewest:
fallthrough
default:
// Compare updated_at timestamps
if local != nil && remote != nil {
if local.UpdatedAt.After(remote.UpdatedAt) {
winner = "local"
} else {
winner = "remote"
}
} else if local != nil {
winner = "local"
} else {
winner = "remote"
}
}
// Store the winning version
if winner == "local" && local != nil {
winners[conflict.IssueID] = local
} else if remote != nil {
winners[conflict.IssueID] = remote
}
fmt.Printf("✓ %s: kept %s", conflict.IssueID, winner)
if strategy == config.ConflictStrategyNewest {
fmt.Print(" (newer)")
}
fmt.Println()
resolved++
}
// Clear conflicts after resolution
if err := ClearSyncConflictState(beadsDir); err != nil {
return fmt.Errorf("clearing conflict state: %w", err)
}
// Run merge for non-conflicting issues, then override conflicts with chosen winners
mergeResult := MergeIssues(baseIssues, localIssues, remoteIssues)
// Override conflicting issues with the strategy-chosen winner
for i, issue := range mergeResult.Merged {
if winner, ok := winners[issue.ID]; ok {
mergeResult.Merged[i] = winner
}
}
// Write merged state
if err := writeMergedStateToJSONL(jsonlPath, mergeResult.Merged); err != nil {
return fmt.Errorf("writing merged state: %w", err)
}
// Import to database
if err := importFromJSONLInline(ctx, jsonlPath, false, false, false); err != nil {
return fmt.Errorf("importing merged state: %w", err)
}
// Export to ensure consistency
if err := exportToJSONL(ctx, jsonlPath); err != nil {
return fmt.Errorf("exporting: %w", err)
}
// Update base state
finalIssues, err := loadIssuesFromJSONL(jsonlPath)
if err != nil {
return fmt.Errorf("reloading final state: %w", err)
}
if err := saveBaseState(beadsDir, finalIssues); err != nil {
return fmt.Errorf("saving base state: %w", err)
}
fmt.Printf("✓ Merge complete (%d conflicts resolved)\n", resolved)
return nil
}
// resolveSyncConflictsManually handles manual conflict resolution with interactive prompts.
func resolveSyncConflictsManually(ctx context.Context, jsonlPath, beadsDir string, conflictState *SyncConflictState,
baseMap, localMap, remoteMap map[string]*beads.Issue) error {
// Build interactive conflicts list
var interactiveConflicts []InteractiveConflict
for _, c := range conflictState.Conflicts {
interactiveConflicts = append(interactiveConflicts, InteractiveConflict{
IssueID: c.IssueID,
Local: localMap[c.IssueID],
Remote: remoteMap[c.IssueID],
Base: baseMap[c.IssueID],
})
}
// Run interactive resolution
resolvedIssues, skipped, err := resolveConflictsInteractively(interactiveConflicts)
if err != nil {
return fmt.Errorf("interactive resolution: %w", err)
}
if skipped > 0 {
fmt.Printf("\n⚠ %d conflict(s) skipped - will remain unresolved\n", skipped)
}
if len(resolvedIssues) == 0 && skipped == len(conflictState.Conflicts) {
fmt.Println("No conflicts were resolved")
return nil
}
// Build the merged issue list:
// 1. Start with issues that weren't in conflict
// 2. Add the resolved issues
conflictIDSet := make(map[string]bool)
for _, c := range conflictState.Conflicts {
conflictIDSet[c.IssueID] = true
}
// Build resolved issue map for quick lookup
resolvedMap := make(map[string]*beads.Issue)
for _, issue := range resolvedIssues {
if issue != nil {
resolvedMap[issue.ID] = issue
}
}
// Collect all unique IDs from base, local, remote
allIDSet := make(map[string]bool)
for id := range baseMap {
allIDSet[id] = true
}
for id := range localMap {
allIDSet[id] = true
}
for id := range remoteMap {
allIDSet[id] = true
}
// Build final merged list
var mergedIssues []*beads.Issue
for id := range allIDSet {
if conflictIDSet[id] {
// This was a conflict
if resolved, ok := resolvedMap[id]; ok {
// User resolved this conflict - use their choice
mergedIssues = append(mergedIssues, resolved)
} else {
// Skipped - keep local version in output, conflict remains for later
if local := localMap[id]; local != nil {
mergedIssues = append(mergedIssues, local)
}
}
} else {
// Not a conflict - use standard 3-way merge logic
local := localMap[id]
remote := remoteMap[id]
base := baseMap[id]
merged, _, _ := MergeIssue(base, local, remote)
if merged != nil {
mergedIssues = append(mergedIssues, merged)
}
}
}
// Clear resolved conflicts (keep skipped ones)
if skipped == 0 {
if err := ClearSyncConflictState(beadsDir); err != nil {
return fmt.Errorf("clearing conflict state: %w", err)
}
} else {
// Update conflict state to only keep skipped conflicts
var remaining []SyncConflictRecord
for _, c := range conflictState.Conflicts {
if _, resolved := resolvedMap[c.IssueID]; !resolved {
remaining = append(remaining, c)
}
}
conflictState.Conflicts = remaining
if err := SaveSyncConflictState(beadsDir, conflictState); err != nil {
return fmt.Errorf("saving updated conflict state: %w", err)
}
}
// Write merged state
if err := writeMergedStateToJSONL(jsonlPath, mergedIssues); err != nil {
return fmt.Errorf("writing merged state: %w", err)
}
// Import to database
if err := importFromJSONLInline(ctx, jsonlPath, false, false, false); err != nil {
return fmt.Errorf("importing merged state: %w", err)
}
// Export to ensure consistency
if err := exportToJSONL(ctx, jsonlPath); err != nil {
return fmt.Errorf("exporting: %w", err)
}
// Update base state
finalIssues, err := loadIssuesFromJSONL(jsonlPath)
if err != nil {
return fmt.Errorf("reloading final state: %w", err)
}
if err := saveBaseState(beadsDir, finalIssues); err != nil {
return fmt.Errorf("saving base state: %w", err)
}
resolvedCount := len(resolvedIssues)
fmt.Printf("\n✓ Manual resolution complete (%d resolved, %d skipped)\n", resolvedCount, skipped)
return nil
}

View file

@ -1,680 +0,0 @@
//go:build cgo
package main
import (
"context"
"os"
"os/exec"
"path/filepath"
"testing"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/git"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/types"
)
// TestMultiRepoPathResolutionCWDInvariant verifies that path resolution for
// repos.additional produces the same absolute paths regardless of CWD.
//
// The bug (oss-lbp): Running from .beads/ caused paths like "oss/" to become
// ".beads/oss/" instead of "{repo}/oss/". This test ensures the fix works
// by verifying resolution from multiple CWDs produces identical results.
//
// Covers: T040-T042
func TestMultiRepoPathResolutionCWDInvariant(t *testing.T) {
ctx := context.Background()
// Store original working directory
originalWd, err := os.Getwd()
if err != nil {
t.Fatalf("failed to get original working directory: %v", err)
}
defer func() { _ = os.Chdir(originalWd) }()
// Create temp repo structure
// Resolve symlinks to avoid macOS /var -> /private/var issues
tmpDir, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatalf("eval symlinks failed: %v", err)
}
// Setup git repo
if err := setupGitRepoInDir(t, tmpDir); err != nil {
t.Fatalf("failed to setup git repo: %v", err)
}
// Create .beads directory structure
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("failed to create .beads dir: %v", err)
}
// Create subdirectory for testing CWD from subdir
subDir := filepath.Join(tmpDir, "src", "pkg")
if err := os.MkdirAll(subDir, 0755); err != nil {
t.Fatalf("failed to create subdir: %v", err)
}
// Create oss/ directory (the multi-repo target)
ossDir := filepath.Join(tmpDir, "oss")
ossBeadsDir := filepath.Join(ossDir, ".beads")
if err := os.MkdirAll(ossBeadsDir, 0755); err != nil {
t.Fatalf("failed to create oss/.beads dir: %v", err)
}
// Create config.yaml with relative path
configContent := `repos:
primary: "."
additional:
- oss/
`
configPath := filepath.Join(beadsDir, "config.yaml")
if err := os.WriteFile(configPath, []byte(configContent), 0600); err != nil {
t.Fatalf("failed to write config file: %v", err)
}
// Create database
dbPath := filepath.Join(beadsDir, "beads.db")
store, err := dolt.New(ctx, &dolt.Config{Path: dbPath})
if err != nil {
t.Fatalf("failed to create store: %v", err)
}
defer store.Close()
// Set issue prefix
if err := store.SetConfig(ctx, "issue_prefix", "test"); err != nil {
t.Fatalf("failed to set issue_prefix: %v", err)
}
// Create a test issue
issue := &types.Issue{
ID: "test-1",
Title: "Test Issue",
Status: types.StatusOpen,
IssueType: types.TypeTask,
Priority: 2,
}
if err := store.CreateIssue(ctx, issue, "test"); err != nil {
t.Fatalf("failed to create issue: %v", err)
}
store.Close()
// T040: Test from repo root
t.Run("T040_from_repo_root", func(t *testing.T) {
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("chdir to repo root failed: %v", err)
}
git.ResetCaches()
// Initialize config
initConfigForTest(t)
multiRepo := config.GetMultiRepoConfig()
if multiRepo == nil {
t.Fatal("GetMultiRepoConfig() returned nil")
}
// The key assertion: "oss/" should resolve to {repo}/oss/
if len(multiRepo.Additional) != 1 {
t.Fatalf("expected 1 additional repo, got %d", len(multiRepo.Additional))
}
// Verify config file used is in the right place
configUsed := config.ConfigFileUsed()
expectedConfig := filepath.Join(beadsDir, "config.yaml")
if configUsed != expectedConfig {
t.Errorf("ConfigFileUsed() = %q, want %q", configUsed, expectedConfig)
}
t.Logf("From repo root: additional[0] = %q", multiRepo.Additional[0])
t.Logf("ConfigFileUsed() = %q", configUsed)
})
// T041: Test from .beads/ directory (the bug trigger location)
t.Run("T041_from_beads_directory", func(t *testing.T) {
if err := os.Chdir(beadsDir); err != nil {
t.Fatalf("chdir to .beads failed: %v", err)
}
git.ResetCaches()
// Re-initialize config from new CWD
initConfigForTest(t)
multiRepo := config.GetMultiRepoConfig()
if multiRepo == nil {
t.Fatal("GetMultiRepoConfig() returned nil")
}
if len(multiRepo.Additional) != 1 {
t.Fatalf("expected 1 additional repo, got %d", len(multiRepo.Additional))
}
// Verify config is still found correctly
configUsed := config.ConfigFileUsed()
expectedConfig := filepath.Join(beadsDir, "config.yaml")
if configUsed != expectedConfig {
t.Errorf("ConfigFileUsed() = %q, want %q", configUsed, expectedConfig)
}
t.Logf("From .beads/: additional[0] = %q", multiRepo.Additional[0])
t.Logf("ConfigFileUsed() = %q", configUsed)
})
// T042: Test from subdirectory
t.Run("T042_from_subdirectory", func(t *testing.T) {
if err := os.Chdir(subDir); err != nil {
t.Fatalf("chdir to subdir failed: %v", err)
}
git.ResetCaches()
// Re-initialize config from new CWD
initConfigForTest(t)
multiRepo := config.GetMultiRepoConfig()
if multiRepo == nil {
t.Fatal("GetMultiRepoConfig() returned nil")
}
if len(multiRepo.Additional) != 1 {
t.Fatalf("expected 1 additional repo, got %d", len(multiRepo.Additional))
}
// Verify config is still found correctly
configUsed := config.ConfigFileUsed()
expectedConfig := filepath.Join(beadsDir, "config.yaml")
if configUsed != expectedConfig {
t.Errorf("ConfigFileUsed() = %q, want %q", configUsed, expectedConfig)
}
t.Logf("From subdir: additional[0] = %q", multiRepo.Additional[0])
t.Logf("ConfigFileUsed() = %q", configUsed)
})
}
// TestExportToMultiRepoCWDInvariant tests that ExportToMultiRepo produces
// consistent export paths regardless of CWD.
//
// This is an integration test that exercises the actual export code path
// which was affected by the bug.
func TestExportToMultiRepoCWDInvariant(t *testing.T) {
ctx := context.Background()
// Store original working directory
originalWd, err := os.Getwd()
if err != nil {
t.Fatalf("failed to get original working directory: %v", err)
}
defer func() { _ = os.Chdir(originalWd) }()
// Create temp repo structure
tmpDir, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatalf("eval symlinks failed: %v", err)
}
// Setup git repo
if err := setupGitRepoInDir(t, tmpDir); err != nil {
t.Fatalf("failed to setup git repo: %v", err)
}
// Create .beads directory
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("failed to create .beads dir: %v", err)
}
// Create oss/.beads directory
ossBeadsDir := filepath.Join(tmpDir, "oss", ".beads")
if err := os.MkdirAll(ossBeadsDir, 0755); err != nil {
t.Fatalf("failed to create oss/.beads dir: %v", err)
}
// Create config.yaml with relative path
configContent := `repos:
primary: "."
additional:
- oss/
`
configPath := filepath.Join(beadsDir, "config.yaml")
if err := os.WriteFile(configPath, []byte(configContent), 0600); err != nil {
t.Fatalf("failed to write config file: %v", err)
}
// Create database and issue once before CWD tests
dbPath := filepath.Join(beadsDir, "beads.db")
store, err := dolt.New(ctx, &dolt.Config{Path: dbPath})
if err != nil {
t.Fatalf("failed to create store: %v", err)
}
// Set issue prefix
if err := store.SetConfig(ctx, "issue_prefix", "oss"); err != nil {
store.Close()
t.Fatalf("failed to set issue_prefix: %v", err)
}
// Create a test issue for oss/ repo
issue := &types.Issue{
ID: "oss-1",
Title: "OSS Issue",
Status: types.StatusOpen,
IssueType: types.TypeTask,
Priority: 2,
SourceRepo: "oss/", // This routes to additional repo
}
if err := store.CreateIssue(ctx, issue, "oss"); err != nil {
store.Close()
t.Fatalf("failed to create issue: %v", err)
}
store.Close()
// Helper function to run export and check results
runExportTest := func(t *testing.T, testCwd string) string {
t.Helper()
// Change to test CWD
if err := os.Chdir(testCwd); err != nil {
t.Fatalf("chdir to %s failed: %v", testCwd, err)
}
git.ResetCaches()
// Initialize config
initConfigForTest(t)
// Open existing store
store, err := dolt.New(ctx, &dolt.Config{Path: dbPath})
if err != nil {
t.Fatalf("failed to open store: %v", err)
}
defer store.Close()
// Run multi-repo export
results, err := store.ExportToMultiRepo(ctx)
if err != nil {
t.Fatalf("ExportToMultiRepo failed: %v", err)
}
// Check that oss/ was exported
if results == nil {
t.Skip("ExportToMultiRepo is a no-op on Dolt backend (JSONL multi-repo not supported)")
}
// The export should create issues.jsonl in oss/.beads/
expectedPath := filepath.Join(ossBeadsDir, "issues.jsonl")
if _, err := os.Stat(expectedPath); os.IsNotExist(err) {
t.Errorf("expected %s to exist after export from %s", expectedPath, testCwd)
}
return expectedPath
}
// Test from repo root
t.Run("export_from_repo_root", func(t *testing.T) {
path := runExportTest(t, tmpDir)
t.Logf("Export from repo root created: %s", path)
})
// Test from .beads/ directory
t.Run("export_from_beads_dir", func(t *testing.T) {
path := runExportTest(t, beadsDir)
t.Logf("Export from .beads/ created: %s", path)
// Key assertion: should NOT create .beads/oss/.beads/issues.jsonl
badPath := filepath.Join(beadsDir, "oss", ".beads", "issues.jsonl")
if _, err := os.Stat(badPath); err == nil {
t.Errorf("BUG: export created %s (CWD-relative path)", badPath)
}
})
// Test from subdirectory
subDir := filepath.Join(tmpDir, "src")
if err := os.MkdirAll(subDir, 0755); err != nil {
t.Fatalf("failed to create subdir: %v", err)
}
t.Run("export_from_subdirectory", func(t *testing.T) {
path := runExportTest(t, subDir)
t.Logf("Export from subdir created: %s", path)
})
}
// TestSyncModePathResolution tests path resolution across different sync modes.
//
// Covers: T050-T052
func TestSyncModePathResolution(t *testing.T) {
ctx := context.Background()
// Store original working directory
originalWd, err := os.Getwd()
if err != nil {
t.Fatalf("failed to get original working directory: %v", err)
}
defer func() { _ = os.Chdir(originalWd) }()
// T050: Normal sync mode path resolution
t.Run("T050_normal_sync_mode", func(t *testing.T) {
// Restore CWD at end of subtest to prevent interference with subsequent tests.
// t.TempDir() cleanup happens after subtest returns, so CWD must be restored first.
subtestWd, err := os.Getwd()
if err != nil {
t.Fatalf("failed to get subtest working directory: %v", err)
}
defer func() { _ = os.Chdir(subtestWd) }()
tmpDir, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatalf("eval symlinks failed: %v", err)
}
// Setup git repo
if err := setupGitRepoInDir(t, tmpDir); err != nil {
t.Fatalf("failed to setup git repo: %v", err)
}
// Create .beads directory
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("failed to create .beads dir: %v", err)
}
// Create oss/.beads directory
ossBeadsDir := filepath.Join(tmpDir, "oss", ".beads")
if err := os.MkdirAll(ossBeadsDir, 0755); err != nil {
t.Fatalf("failed to create oss/.beads dir: %v", err)
}
// Create config.yaml with relative path
configContent := `repos:
primary: "."
additional:
- oss/
`
configPath := filepath.Join(beadsDir, "config.yaml")
if err := os.WriteFile(configPath, []byte(configContent), 0600); err != nil {
t.Fatalf("failed to write config file: %v", err)
}
// Create database
dbPath := filepath.Join(beadsDir, "beads.db")
store, err := dolt.New(ctx, &dolt.Config{Path: dbPath})
if err != nil {
t.Fatalf("failed to create store: %v", err)
}
// Set issue prefix
if err := store.SetConfig(ctx, "issue_prefix", "test"); err != nil {
store.Close()
t.Fatalf("failed to set issue_prefix: %v", err)
}
// Create issue for oss/
issue := &types.Issue{
ID: "test-100",
Title: "Normal mode issue",
Status: types.StatusOpen,
IssueType: types.TypeTask,
Priority: 2,
SourceRepo: "oss/",
}
if err := store.CreateIssue(ctx, issue, "test"); err != nil {
store.Close()
t.Fatalf("failed to create issue: %v", err)
}
// Change to repo root and initialize config
if err := os.Chdir(tmpDir); err != nil {
store.Close()
t.Fatalf("chdir failed: %v", err)
}
git.ResetCaches()
initConfigForTest(t)
// Export
results, err := store.ExportToMultiRepo(ctx)
store.Close()
if err != nil {
t.Fatalf("ExportToMultiRepo failed: %v", err)
}
if results == nil || len(results) == 0 {
t.Skip("ExportToMultiRepo is a no-op on Dolt backend (JSONL multi-repo not supported)")
}
// Verify export created file in correct location
expectedPath := filepath.Join(ossBeadsDir, "issues.jsonl")
if _, err := os.Stat(expectedPath); os.IsNotExist(err) {
t.Errorf("expected %s to exist", expectedPath)
}
t.Logf("Normal sync mode export results: %v", results)
})
// T051: Sync-branch mode with daemon context
t.Run("T051_sync_branch_mode", func(t *testing.T) {
// Restore CWD at end of subtest to prevent interference with subsequent tests.
subtestWd, err := os.Getwd()
if err != nil {
t.Fatalf("failed to get subtest working directory: %v", err)
}
defer func() { _ = os.Chdir(subtestWd) }()
tmpDir, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatalf("eval symlinks failed: %v", err)
}
// Setup git repo
if err := setupGitRepoInDir(t, tmpDir); err != nil {
t.Fatalf("failed to setup git repo: %v", err)
}
// Create .beads directory
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("failed to create .beads dir: %v", err)
}
// Create oss/.beads directory
ossBeadsDir := filepath.Join(tmpDir, "oss", ".beads")
if err := os.MkdirAll(ossBeadsDir, 0755); err != nil {
t.Fatalf("failed to create oss/.beads dir: %v", err)
}
// Create config.yaml with sync-branch AND multi-repo
configContent := `sync:
branch: beads-sync
repos:
primary: "."
additional:
- oss/
`
configPath := filepath.Join(beadsDir, "config.yaml")
if err := os.WriteFile(configPath, []byte(configContent), 0600); err != nil {
t.Fatalf("failed to write config file: %v", err)
}
// Create the sync branch
if err := exec.Command("git", "-C", tmpDir, "branch", "beads-sync").Run(); err != nil {
t.Fatalf("failed to create sync branch: %v", err)
}
// Create database
dbPath := filepath.Join(beadsDir, "beads.db")
store, err := dolt.New(ctx, &dolt.Config{Path: dbPath})
if err != nil {
t.Fatalf("failed to create store: %v", err)
}
// Set issue prefix
if err := store.SetConfig(ctx, "issue_prefix", "test"); err != nil {
store.Close()
t.Fatalf("failed to set issue_prefix: %v", err)
}
// Create issue for oss/
issue := &types.Issue{
ID: "test-200",
Title: "Sync-branch mode issue",
Status: types.StatusOpen,
IssueType: types.TypeTask,
Priority: 2,
SourceRepo: "oss/",
}
if err := store.CreateIssue(ctx, issue, "test"); err != nil {
store.Close()
t.Fatalf("failed to create issue: %v", err)
}
// Simulate daemon context: CWD is .beads/
if err := os.Chdir(beadsDir); err != nil {
store.Close()
t.Fatalf("chdir to .beads/ failed: %v", err)
}
git.ResetCaches()
initConfigForTest(t)
// Export from daemon-like context
results, err := store.ExportToMultiRepo(ctx)
store.Close()
if err != nil {
t.Fatalf("ExportToMultiRepo failed: %v", err)
}
if results == nil || len(results) == 0 {
t.Skip("ExportToMultiRepo is a no-op on Dolt backend (JSONL multi-repo not supported)")
}
// Key assertion: should still export to correct location
expectedPath := filepath.Join(ossBeadsDir, "issues.jsonl")
if _, err := os.Stat(expectedPath); os.IsNotExist(err) {
t.Errorf("expected %s to exist (sync-branch mode from .beads/)", expectedPath)
}
// Verify no spurious directory created
badPath := filepath.Join(beadsDir, "oss", ".beads", "issues.jsonl")
if _, err := os.Stat(badPath); err == nil {
t.Errorf("BUG: created %s (CWD-relative in sync-branch mode)", badPath)
}
t.Logf("Sync-branch mode export results: %v", results)
})
// T052: External BEADS_DIR mode
t.Run("T052_external_beads_dir_mode", func(t *testing.T) {
// Restore CWD at end of subtest to prevent interference with subsequent tests.
subtestWd, err := os.Getwd()
if err != nil {
t.Fatalf("failed to get subtest working directory: %v", err)
}
defer func() { _ = os.Chdir(subtestWd) }()
// Create main project repo
projectDir, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatalf("eval symlinks failed: %v", err)
}
if err := setupGitRepoInDir(t, projectDir); err != nil {
t.Fatalf("failed to setup project repo: %v", err)
}
// Create external beads repo
externalDir, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatalf("eval symlinks failed: %v", err)
}
if err := setupGitRepoInDir(t, externalDir); err != nil {
t.Fatalf("failed to setup external repo: %v", err)
}
// Create .beads in external repo
externalBeadsDir := filepath.Join(externalDir, ".beads")
if err := os.MkdirAll(externalBeadsDir, 0755); err != nil {
t.Fatalf("failed to create external .beads: %v", err)
}
// Create oss/.beads in external repo (sibling to external .beads)
ossBeadsDir := filepath.Join(externalDir, "oss", ".beads")
if err := os.MkdirAll(ossBeadsDir, 0755); err != nil {
t.Fatalf("failed to create oss/.beads: %v", err)
}
// Create config.yaml in external repo with relative path
configContent := `repos:
primary: "."
additional:
- oss/
`
configPath := filepath.Join(externalBeadsDir, "config.yaml")
if err := os.WriteFile(configPath, []byte(configContent), 0600); err != nil {
t.Fatalf("failed to write config file: %v", err)
}
// Create database in external repo
dbPath := filepath.Join(externalBeadsDir, "beads.db")
store, err := dolt.New(ctx, &dolt.Config{Path: dbPath})
if err != nil {
t.Fatalf("failed to create store: %v", err)
}
// Set issue prefix
if err := store.SetConfig(ctx, "issue_prefix", "ext"); err != nil {
store.Close()
t.Fatalf("failed to set issue_prefix: %v", err)
}
// Create issue for oss/ (ext prefix matches issue ID)
issue := &types.Issue{
ID: "ext-300",
Title: "External mode issue",
Status: types.StatusOpen,
IssueType: types.TypeTask,
Priority: 2,
SourceRepo: "oss/",
}
if err := store.CreateIssue(ctx, issue, "ext"); err != nil {
store.Close()
t.Fatalf("failed to create issue: %v", err)
}
// Simulate external mode: CWD is project repo, BEADS_DIR points elsewhere
if err := os.Chdir(projectDir); err != nil {
store.Close()
t.Fatalf("chdir to project failed: %v", err)
}
git.ResetCaches()
// Initialize config from external location
// In external mode, config is loaded from BEADS_DIR, not CWD
// We simulate this by changing to external dir for config init
if err := os.Chdir(externalDir); err != nil {
store.Close()
t.Fatalf("chdir to external failed: %v", err)
}
git.ResetCaches()
initConfigForTest(t)
// Export
results, err := store.ExportToMultiRepo(ctx)
store.Close()
if err != nil {
t.Fatalf("ExportToMultiRepo failed: %v", err)
}
if results == nil || len(results) == 0 {
t.Skip("ExportToMultiRepo is a no-op on Dolt backend (JSONL multi-repo not supported)")
}
// Verify export in correct location
expectedPath := filepath.Join(ossBeadsDir, "issues.jsonl")
if _, err := os.Stat(expectedPath); os.IsNotExist(err) {
t.Errorf("expected %s to exist (external mode)", expectedPath)
}
t.Logf("External BEADS_DIR mode export results: %v", results)
})
}

View file

@ -1,95 +0,0 @@
package main
import (
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/steveyegge/beads/internal/types"
)
func TestReadJSONLToMap(t *testing.T) {
tmpDir := t.TempDir()
jsonlPath := filepath.Join(tmpDir, "test.jsonl")
// Create test JSONL with 3 issues
issues := []types.Issue{
{ID: "test-001", Title: "First", Status: types.StatusOpen},
{ID: "test-002", Title: "Second", Status: types.StatusInProgress},
{ID: "test-003", Title: "Third", Status: types.StatusClosed},
}
var content string
for _, issue := range issues {
data, _ := json.Marshal(issue)
content += string(data) + "\n"
}
if err := os.WriteFile(jsonlPath, []byte(content), 0644); err != nil {
t.Fatalf("failed to write test file: %v", err)
}
// Test readJSONLToMap
issueMap, ids, err := readJSONLToMap(jsonlPath)
if err != nil {
t.Fatalf("readJSONLToMap failed: %v", err)
}
// Verify count
if len(issueMap) != 3 {
t.Errorf("expected 3 issues in map, got %d", len(issueMap))
}
if len(ids) != 3 {
t.Errorf("expected 3 IDs, got %d", len(ids))
}
// Verify order preserved
expectedOrder := []string{"test-001", "test-002", "test-003"}
for i, id := range ids {
if id != expectedOrder[i] {
t.Errorf("ID order mismatch at %d: expected %s, got %s", i, expectedOrder[i], id)
}
}
// Verify content can be unmarshaled
for id, rawJSON := range issueMap {
var issue types.Issue
if err := json.Unmarshal(rawJSON, &issue); err != nil {
t.Errorf("failed to unmarshal issue %s: %v", id, err)
}
if issue.ID != id {
t.Errorf("ID mismatch: expected %s, got %s", id, issue.ID)
}
}
}
func TestReadJSONLToMapWithMalformedLines(t *testing.T) {
tmpDir := t.TempDir()
jsonlPath := filepath.Join(tmpDir, "test.jsonl")
content := `{"id": "test-001", "title": "Good"}
{invalid json}
{"id": "test-002", "title": "Also Good"}
{"id": "", "title": "No ID"}
{"id": "test-003", "title": "Third Good"}
`
if err := os.WriteFile(jsonlPath, []byte(content), 0644); err != nil {
t.Fatalf("failed to write test file: %v", err)
}
issueMap, ids, err := readJSONLToMap(jsonlPath)
if err != nil {
t.Fatalf("readJSONLToMap failed: %v", err)
}
// Should have 3 valid issues (skipped invalid JSON, empty line, and empty ID)
if len(issueMap) != 3 {
t.Errorf("expected 3 issues, got %d", len(issueMap))
}
if len(ids) != 3 {
t.Errorf("expected 3 IDs, got %d", len(ids))
}
}

View file

@ -1,365 +0,0 @@
package main
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/git"
)
// TestExternalBeadsDirE2E tests the full external BEADS_DIR flow.
// This is an end-to-end regression test for PR#918.
//
// When BEADS_DIR points to a separate git repository (external mode),
// sync operations should work correctly:
// 1. Changes are committed to the external beads repo (not the project repo)
// 2. Pulls from the external repo bring in remote changes
// 3. The merge algorithm works correctly across repo boundaries
func TestExternalBeadsDirE2E(t *testing.T) {
ctx := context.Background()
// Store original working directory
originalWd, err := os.Getwd()
if err != nil {
t.Fatalf("failed to get original working directory: %v", err)
}
// Setup: Create the main project repo
projectDir := t.TempDir()
if err := setupGitRepoInDir(t, projectDir); err != nil {
t.Fatalf("failed to setup project repo: %v", err)
}
// Setup: Create a separate external beads repo
// Resolve symlinks to avoid macOS /var -> /private/var issues
externalDir, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatalf("eval symlinks failed: %v", err)
}
if err := setupGitRepoInDir(t, externalDir); err != nil {
t.Fatalf("failed to setup external repo: %v", err)
}
// Create .beads directory in external repo
externalBeadsDir := filepath.Join(externalDir, ".beads")
if err := os.MkdirAll(externalBeadsDir, 0755); err != nil {
t.Fatalf("failed to create external .beads dir: %v", err)
}
// Create issues.jsonl in external beads repo with initial issue
jsonlPath := filepath.Join(externalBeadsDir, "issues.jsonl")
issue1 := `{"id":"ext-1","title":"External Issue 1","status":"open","issue_type":"task","priority":2,"created_at":"2025-01-01T00:00:00Z","updated_at":"2025-01-01T00:00:00Z"}`
if err := os.WriteFile(jsonlPath, []byte(issue1+"\n"), 0644); err != nil {
t.Fatalf("write external JSONL failed: %v", err)
}
// Commit initial beads files in external repo
runGitInDir(t, externalDir, "add", ".beads")
runGitInDir(t, externalDir, "commit", "-m", "initial beads setup")
t.Log("✓ External beads repo initialized with issue ext-1")
// Change to project directory (simulating user's project)
if err := os.Chdir(projectDir); err != nil {
t.Fatalf("chdir to project failed: %v", err)
}
defer func() { _ = os.Chdir(originalWd) }()
// Reset git caches after directory change
git.ResetCaches()
// Test 1: isExternalBeadsDir should detect external repo
if !isExternalBeadsDir(ctx, externalBeadsDir) {
t.Error("isExternalBeadsDir should return true for external beads dir")
}
t.Log("✓ External beads dir correctly detected")
// Test 2: getRepoRootFromPath should correctly identify external repo root
repoRoot, err := getRepoRootFromPath(ctx, externalBeadsDir)
if err != nil {
t.Fatalf("getRepoRootFromPath failed: %v", err)
}
// Normalize paths for comparison
resolvedExternal, _ := filepath.EvalSymlinks(externalDir)
if repoRoot != resolvedExternal {
t.Errorf("getRepoRootFromPath = %q, want %q", repoRoot, resolvedExternal)
}
t.Logf("✓ getRepoRootFromPath correctly identifies external repo: %s", repoRoot)
// Test 3: pullFromExternalBeadsRepo should handle no-remote gracefully
err = pullFromExternalBeadsRepo(ctx, externalBeadsDir)
if err != nil {
t.Errorf("pullFromExternalBeadsRepo should handle no-remote: %v", err)
}
t.Log("✓ Pull from external beads repo handled no-remote correctly")
// Test 4: Create new issue and commit to external repo
issue2 := `{"id":"ext-2","title":"External Issue 2","status":"open","issue_type":"task","priority":2,"created_at":"2025-01-02T00:00:00Z","updated_at":"2025-01-02T00:00:00Z"}`
combinedContent := issue1 + "\n" + issue2 + "\n"
if err := os.WriteFile(jsonlPath, []byte(combinedContent), 0644); err != nil {
t.Fatalf("write updated JSONL failed: %v", err)
}
// Use commitToExternalBeadsRepo (don't push since no real remote)
committed, err := commitToExternalBeadsRepo(ctx, externalBeadsDir, "add ext-2", false)
if err != nil {
t.Fatalf("commitToExternalBeadsRepo failed: %v", err)
}
if !committed {
t.Error("expected commit to succeed for new issue")
}
t.Log("✓ Successfully committed issue ext-2 to external beads repo")
// Test 5: Verify commit was made in external repo (not project repo)
// Check external repo has the commit
logOutput := getGitOutputInDir(t, externalDir, "log", "--oneline", "-1")
if !strings.Contains(logOutput, "add ext-2") {
t.Errorf("external repo should have commit, got: %s", logOutput)
}
t.Log("✓ Commit correctly made in external repo")
// Test 6: Verify project repo is unchanged
projectLogOutput := getGitOutputInDir(t, projectDir, "log", "--oneline", "-1")
if strings.Contains(projectLogOutput, "add ext-2") {
t.Error("project repo should not have beads commit")
}
t.Log("✓ Project repo correctly unchanged")
// Test 7: Verify JSONL content is correct
content, err := os.ReadFile(jsonlPath)
if err != nil {
t.Fatalf("failed to read JSONL: %v", err)
}
contentStr := string(content)
if !strings.Contains(contentStr, "ext-1") || !strings.Contains(contentStr, "ext-2") {
t.Errorf("JSONL should contain both issues, got: %s", contentStr)
}
t.Log("✓ JSONL contains both issues")
t.Log("✓ External BEADS_DIR E2E test completed")
}
// TestExternalBeadsDirDetection tests various edge cases for external beads dir detection.
func TestExternalBeadsDirDetection(t *testing.T) {
ctx := context.Background()
// Store original working directory
originalWd, err := os.Getwd()
if err != nil {
t.Fatalf("failed to get original working directory: %v", err)
}
t.Run("same repo returns false", func(t *testing.T) {
// Setup a single repo
repoDir := t.TempDir()
if err := setupGitRepoInDir(t, repoDir); err != nil {
t.Fatalf("setup failed: %v", err)
}
beadsDir := filepath.Join(repoDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("mkdir failed: %v", err)
}
// Change to repo dir
if err := os.Chdir(repoDir); err != nil {
t.Fatalf("chdir failed: %v", err)
}
defer func() { _ = os.Chdir(originalWd) }()
git.ResetCaches()
// Same repo should return false
if isExternalBeadsDir(ctx, beadsDir) {
t.Error("isExternalBeadsDir should return false for same repo")
}
})
t.Run("different repo returns true", func(t *testing.T) {
// Setup two separate repos
projectDir := t.TempDir()
if err := setupGitRepoInDir(t, projectDir); err != nil {
t.Fatalf("setup project failed: %v", err)
}
externalDir, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatalf("eval symlinks failed: %v", err)
}
if err := setupGitRepoInDir(t, externalDir); err != nil {
t.Fatalf("setup external failed: %v", err)
}
beadsDir := filepath.Join(externalDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("mkdir failed: %v", err)
}
// Change to project dir
if err := os.Chdir(projectDir); err != nil {
t.Fatalf("chdir failed: %v", err)
}
defer func() { _ = os.Chdir(originalWd) }()
git.ResetCaches()
// Different repo should return true
if !isExternalBeadsDir(ctx, beadsDir) {
t.Error("isExternalBeadsDir should return true for different repo")
}
})
t.Run("non-git directory returns false", func(t *testing.T) {
// Setup a repo for cwd
repoDir := t.TempDir()
if err := setupGitRepoInDir(t, repoDir); err != nil {
t.Fatalf("setup failed: %v", err)
}
// Non-git beads dir
nonGitDir := t.TempDir()
beadsDir := filepath.Join(nonGitDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("mkdir failed: %v", err)
}
// Change to repo dir
if err := os.Chdir(repoDir); err != nil {
t.Fatalf("chdir failed: %v", err)
}
defer func() { _ = os.Chdir(originalWd) }()
git.ResetCaches()
// Non-git dir should return false (can't determine, assume local)
if isExternalBeadsDir(ctx, beadsDir) {
t.Error("isExternalBeadsDir should return false for non-git directory")
}
})
}
// TestCommitToExternalBeadsRepo tests the external repo commit function.
func TestCommitToExternalBeadsRepo(t *testing.T) {
ctx := context.Background()
t.Run("commits changes to external repo", func(t *testing.T) {
// Setup external repo
externalDir, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatalf("eval symlinks failed: %v", err)
}
if err := setupGitRepoInDir(t, externalDir); err != nil {
t.Fatalf("setup failed: %v", err)
}
beadsDir := filepath.Join(externalDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("mkdir failed: %v", err)
}
// Write initial JSONL
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
if err := os.WriteFile(jsonlPath, []byte(`{"id":"test-1"}`+"\n"), 0644); err != nil {
t.Fatalf("write failed: %v", err)
}
// Commit
committed, err := commitToExternalBeadsRepo(ctx, beadsDir, "test commit", false)
if err != nil {
t.Fatalf("commit failed: %v", err)
}
if !committed {
t.Error("expected commit to succeed")
}
// Verify commit exists
logOutput := getGitOutputInDir(t, externalDir, "log", "--oneline", "-1")
if !strings.Contains(logOutput, "test commit") {
t.Errorf("commit not found in log: %s", logOutput)
}
})
t.Run("returns false when no changes", func(t *testing.T) {
// Setup external repo
externalDir, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatalf("eval symlinks failed: %v", err)
}
if err := setupGitRepoInDir(t, externalDir); err != nil {
t.Fatalf("setup failed: %v", err)
}
beadsDir := filepath.Join(externalDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("mkdir failed: %v", err)
}
// Write and commit JSONL
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
if err := os.WriteFile(jsonlPath, []byte(`{"id":"test-1"}`+"\n"), 0644); err != nil {
t.Fatalf("write failed: %v", err)
}
runGitInDir(t, externalDir, "add", ".beads")
runGitInDir(t, externalDir, "commit", "-m", "initial")
// Try to commit again with no changes
committed, err := commitToExternalBeadsRepo(ctx, beadsDir, "no changes", false)
if err != nil {
t.Fatalf("commit failed: %v", err)
}
if committed {
t.Error("expected no commit when no changes")
}
})
}
// Helper: Setup git repo in a specific directory (doesn't change cwd)
func setupGitRepoInDir(t *testing.T, dir string) error {
t.Helper()
// Initialize git repo
if err := exec.Command("git", "-C", dir, "init", "--initial-branch=main").Run(); err != nil {
return err
}
// Configure git
_ = exec.Command("git", "-C", dir, "config", "user.email", "test@test.com").Run()
_ = exec.Command("git", "-C", dir, "config", "user.name", "Test User").Run()
// Create initial commit
readmePath := filepath.Join(dir, "README.md")
if err := os.WriteFile(readmePath, []byte("# Test Repo\n"), 0644); err != nil {
return err
}
if err := exec.Command("git", "-C", dir, "add", ".").Run(); err != nil {
return err
}
if err := exec.Command("git", "-C", dir, "commit", "-m", "initial commit").Run(); err != nil {
return err
}
return nil
}
// Helper: Run git command in a specific directory
func runGitInDir(t *testing.T, dir string, args ...string) {
t.Helper()
cmdArgs := append([]string{"-C", dir}, args...)
cmd := exec.Command("git", cmdArgs...)
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git %v failed: %v\n%s", args, err, output)
}
}
// Helper: Get git output from a specific directory
func getGitOutputInDir(t *testing.T, dir string, args ...string) string {
t.Helper()
cmdArgs := append([]string{"-C", dir}, args...)
cmd := exec.Command("git", cmdArgs...)
output, err := cmd.Output()
if err != nil {
t.Fatalf("git %v failed: %v", args, err)
}
return string(output)
}

View file

@ -1,157 +0,0 @@
package main
import (
"testing"
)
// TestIsPushPermissionDenied tests the isPushPermissionDenied function
// with various error messages from different Git hosting providers.
func TestIsPushPermissionDenied(t *testing.T) {
tests := map[string]struct {
output string
expected bool
}{
// GitHub errors
"github_403": {
output: "remote: Permission to owner/repo.git denied to user.\nfatal: unable to access 'https://github.com/owner/repo.git/': The requested URL returned error: 403",
expected: true,
},
"github_permission_denied": {
output: "ERROR: Permission to owner/repo.git denied to user.",
expected: true,
},
"github_ssh_permission": {
output: "Permission denied (publickey).\nfatal: Could not read from remote repository.",
expected: true,
},
// GitLab errors
"gitlab_not_allowed": {
output: "remote: GitLab: You are not allowed to push code to this project.\nTo gitlab.com:owner/repo.git\n! [remote rejected] main -> main (pre-receive hook declined)",
expected: true,
},
"gitlab_permission": {
output: "remote: You are not allowed to push code to protected branches on this project.",
expected: true,
},
// Bitbucket errors
"bitbucket_403": {
output: "remote: HTTP Basic: Access denied\nfatal: Authentication failed for 'https://bitbucket.org/owner/repo.git/'",
expected: true,
},
// Generic permission errors
"generic_permission_denied": {
output: "fatal: remote error: permission denied",
expected: true,
},
"generic_could_not_read": {
output: "fatal: Could not read from remote repository.\n\nPlease make sure you have the correct access rights\nand the repository exists.",
expected: true,
},
"generic_authentication_failed": {
output: "fatal: Authentication failed for 'https://example.com/repo.git/'",
expected: true,
},
"generic_unable_to_access": {
output: "fatal: unable to access 'https://example.com/repo.git/': URL using bad/illegal format or missing URL",
expected: true,
},
// Non-permission errors (should NOT trigger)
"fetch_first": {
output: "To github.com:owner/repo.git\n! [rejected] main -> main (fetch first)\nerror: failed to push some refs",
expected: false,
},
"non_fast_forward": {
output: "To github.com:owner/repo.git\n! [rejected] main -> main (non-fast-forward)\nerror: failed to push some refs",
expected: false,
},
"network_error": {
output: "fatal: unable to connect to github.com:\nCould not connect to server",
expected: false,
},
"no_upstream": {
output: "fatal: The current branch main has no upstream branch.\nTo push the current branch and set the remote as upstream, use\n\n git push --set-upstream origin main",
expected: false,
},
"branch_protected": {
output: "remote: error: GH006: Protected branch update failed for refs/heads/main.",
expected: false,
},
"empty_output": {
output: "",
expected: false,
},
"success_output": {
output: "To github.com:owner/repo.git\n abc123..def456 main -> main",
expected: false,
},
// Edge cases
"case_insensitive_403": {
output: "The Requested URL Returned Error: 403",
expected: true,
},
"case_insensitive_permission": {
output: "PERMISSION DENIED",
expected: true,
},
"partial_match_403_in_sha": {
// This is a tricky case - "403" in the middle of a hash
// We accept this false positive since it's rare and better to over-detect
output: "commit 403abc123 pushed successfully",
expected: true,
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
got := isPushPermissionDenied(tt.output)
if got != tt.expected {
t.Errorf("isPushPermissionDenied(%q) = %v, want %v", tt.output, got, tt.expected)
}
})
}
}
// TestIsPushPermissionDenied_ProviderSpecific tests specific provider error formats
// to ensure we handle the most common cases from major Git hosting platforms.
func TestIsPushPermissionDenied_ProviderSpecific(t *testing.T) {
// These are real error messages captured from various providers
providerErrors := []struct {
name string
provider string
output string
}{
{
name: "GitHub HTTPS with PAT denied",
provider: "GitHub",
output: "remote: Permission to steveyegge/beads.git denied to contributor.\nfatal: unable to access 'https://github.com/steveyegge/beads.git/': The requested URL returned error: 403",
},
{
name: "GitHub SSH key not authorized",
provider: "GitHub",
output: "ERROR: Permission to owner/repo.git denied to user.\nfatal: Could not read from remote repository.\n\nPlease make sure you have the correct access rights\nand the repository exists.",
},
{
name: "GitLab protected branch",
provider: "GitLab",
output: "remote: GitLab: You are not allowed to push code to this project.\nTo gitlab.com:owner/repo.git\n ! [remote rejected] main -> main (pre-receive hook declined)\nerror: failed to push some refs to 'gitlab.com:owner/repo.git'",
},
{
name: "Bitbucket access denied",
provider: "Bitbucket",
output: "remote: You are not allowed to push to this repository.\nfatal: Could not read from remote repository.",
},
}
for _, tc := range providerErrors {
t.Run(tc.name, func(t *testing.T) {
if !isPushPermissionDenied(tc.output) {
t.Errorf("%s error not detected as permission denied:\n%s", tc.provider, tc.output)
}
})
}
}

View file

@ -1,88 +0,0 @@
//go:build cgo
package main
import (
"context"
"path/filepath"
"testing"
"github.com/steveyegge/beads/internal/config"
)
// resetConfigForRemoteTest clears viper config state without loading
// the real config.yaml. This prevents sync.mode from config.yaml
// (e.g., dolt-native in production workspace) from overriding test values.
func resetConfigForRemoteTest(t *testing.T) {
t.Helper()
config.ResetForTesting()
t.Cleanup(config.ResetForTesting)
}
// NOTE: TestDoExportSync_*, TestDoPullFirstSync_*, and TestRemoteStorageInterfaceCheck
// were removed because they depended on the memory backend's mockRemoteStore pattern
// for Push/Pull error injection. With the dolt-native migration (Phase 7), the global
// store is *dolt.DoltStore which doesn't support mock injection. Sync mode functionality
// is tested through integration tests with real dolt remotes.
// TestShouldUseDoltRemote_ModeSelection verifies the mode -> Dolt remote mapping
// using a real dolt store.
func TestShouldUseDoltRemote_ModeSelection(t *testing.T) {
ctx := context.Background()
resetConfigForRemoteTest(t)
tests := []struct {
mode string
wantUse bool
}{
{SyncModeGitPortable, false},
{SyncModeRealtime, false},
{SyncModeDoltNative, true},
{SyncModeBeltAndSuspenders, true},
}
for _, tt := range tests {
t.Run(tt.mode, func(t *testing.T) {
testStore := newTestStoreWithPrefix(t, filepath.Join(t.TempDir(), "test.db"), "test")
if err := testStore.SetConfig(ctx, SyncModeConfigKey, tt.mode); err != nil {
t.Fatalf("set mode: %v", err)
}
got := ShouldUseDoltRemote(ctx, testStore)
if got != tt.wantUse {
t.Errorf("ShouldUseDoltRemote() = %v, want %v", got, tt.wantUse)
}
})
}
}
// TestShouldExportJSONL_DoltNative_False verifies that JSONL export is disabled
// in dolt-native mode using a real dolt store.
func TestShouldExportJSONL_DoltNative_False(t *testing.T) {
ctx := context.Background()
resetConfigForRemoteTest(t)
tests := []struct {
mode string
wantExport bool
}{
{SyncModeGitPortable, true},
{SyncModeRealtime, true},
{SyncModeDoltNative, false},
{SyncModeBeltAndSuspenders, true},
}
for _, tt := range tests {
t.Run(tt.mode, func(t *testing.T) {
testStore := newTestStoreWithPrefix(t, filepath.Join(t.TempDir(), "test.db"), "test")
if err := testStore.SetConfig(ctx, SyncModeConfigKey, tt.mode); err != nil {
t.Fatalf("set mode: %v", err)
}
got := ShouldExportJSONL(ctx, testStore)
if got != tt.wantExport {
t.Errorf("ShouldExportJSONL() = %v, want %v", got, tt.wantExport)
}
})
}
}

View file

@ -1,750 +0,0 @@
package main
import (
"context"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/git"
)
// setupGitRepoWithBeads creates a temporary git repository with a .beads directory.
// Returns the repo path and cleanup function.
func setupGitRepoWithBeads(t *testing.T) (repoPath string, cleanup func()) {
t.Helper()
tmpDir := newGitRepo(t)
originalWd, err := os.Getwd()
if err != nil {
t.Fatalf("failed to get working directory: %v", err)
}
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("failed to change to temp directory: %v", err)
}
git.ResetCaches()
beads.ResetCaches()
// Create .beads directory with issues.jsonl
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
_ = os.Chdir(originalWd)
t.Fatalf("failed to create .beads directory: %v", err)
}
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
if err := os.WriteFile(jsonlPath, []byte(`{"id":"test-1"}`+"\n"), 0644); err != nil {
_ = os.Chdir(originalWd)
t.Fatalf("failed to write issues.jsonl: %v", err)
}
// Create initial commit
_ = exec.Command("git", "add", ".beads").Run()
if err := exec.Command("git", "commit", "-m", "initial").Run(); err != nil {
_ = os.Chdir(originalWd)
t.Fatalf("failed to create initial commit: %v", err)
}
cleanup = func() {
_ = os.Chdir(originalWd)
git.ResetCaches()
beads.ResetCaches()
}
return tmpDir, cleanup
}
// setupRedirectedBeadsRepo creates two git repos: source with redirect, target with actual .beads.
// Returns source path, target path, and cleanup function.
func setupRedirectedBeadsRepo(t *testing.T) (sourcePath, targetPath string, cleanup func()) {
t.Helper()
baseDir := t.TempDir()
originalWd, err := os.Getwd()
if err != nil {
t.Fatalf("failed to get working directory: %v", err)
}
// Create target repo with actual .beads
targetPath = filepath.Join(baseDir, "target")
if err := os.MkdirAll(targetPath, 0755); err != nil {
t.Fatalf("failed to create target directory: %v", err)
}
targetBeadsDir := filepath.Join(targetPath, ".beads")
if err := os.MkdirAll(targetBeadsDir, 0755); err != nil {
t.Fatalf("failed to create target .beads directory: %v", err)
}
// Copy cached git template into target (bd-ktng optimization)
initGitTemplate()
if gitTemplateErr != nil {
t.Fatalf("git template init failed: %v", gitTemplateErr)
}
if err := copyGitDir(gitTemplateDir, targetPath); err != nil {
t.Fatalf("failed to copy git template to target: %v", err)
}
// Write issues.jsonl in target
jsonlPath := filepath.Join(targetBeadsDir, "issues.jsonl")
if err := os.WriteFile(jsonlPath, []byte(`{"id":"test-1"}`+"\n"), 0644); err != nil {
t.Fatalf("failed to write issues.jsonl: %v", err)
}
// Commit in target
cmd := exec.Command("git", "add", ".beads")
cmd.Dir = targetPath
_ = cmd.Run()
cmd = exec.Command("git", "commit", "-m", "initial")
cmd.Dir = targetPath
if err := cmd.Run(); err != nil {
t.Fatalf("failed to create initial commit in target: %v", err)
}
// Create source repo with redirect
sourcePath = filepath.Join(baseDir, "source")
if err := os.MkdirAll(sourcePath, 0755); err != nil {
t.Fatalf("failed to create source directory: %v", err)
}
sourceBeadsDir := filepath.Join(sourcePath, ".beads")
if err := os.MkdirAll(sourceBeadsDir, 0755); err != nil {
t.Fatalf("failed to create source .beads directory: %v", err)
}
// Write redirect file pointing to target
redirectPath := filepath.Join(sourceBeadsDir, "redirect")
// Use relative path: ../target/.beads
if err := os.WriteFile(redirectPath, []byte("../target/.beads\n"), 0644); err != nil {
t.Fatalf("failed to write redirect file: %v", err)
}
// Copy cached git template into source (bd-ktng optimization)
if err := copyGitDir(gitTemplateDir, sourcePath); err != nil {
t.Fatalf("failed to copy git template to source: %v", err)
}
// Commit redirect in source
cmd = exec.Command("git", "add", ".beads")
cmd.Dir = sourcePath
_ = cmd.Run()
cmd = exec.Command("git", "commit", "-m", "initial with redirect")
cmd.Dir = sourcePath
if err := cmd.Run(); err != nil {
t.Fatalf("failed to create initial commit in source: %v", err)
}
// Change to source directory
if err := os.Chdir(sourcePath); err != nil {
t.Fatalf("failed to change to source directory: %v", err)
}
git.ResetCaches()
beads.ResetCaches()
cleanup = func() {
_ = os.Chdir(originalWd)
git.ResetCaches()
beads.ResetCaches()
}
return sourcePath, targetPath, cleanup
}
func TestGitHasBeadsChanges_NoChanges(t *testing.T) {
ctx := context.Background()
_, cleanup := setupGitRepoWithBeads(t)
defer cleanup()
hasChanges, err := gitHasBeadsChanges(ctx)
if err != nil {
t.Fatalf("gitHasBeadsChanges() error = %v", err)
}
if hasChanges {
t.Error("expected no changes for clean repo")
}
}
func TestGitHasBeadsChanges_WithChanges(t *testing.T) {
ctx := context.Background()
repoPath, cleanup := setupGitRepoWithBeads(t)
defer cleanup()
// Modify the issues.jsonl file
jsonlPath := filepath.Join(repoPath, ".beads", "issues.jsonl")
if err := os.WriteFile(jsonlPath, []byte(`{"id":"test-2"}`+"\n"), 0644); err != nil {
t.Fatalf("failed to modify issues.jsonl: %v", err)
}
hasChanges, err := gitHasBeadsChanges(ctx)
if err != nil {
t.Fatalf("gitHasBeadsChanges() error = %v", err)
}
if !hasChanges {
t.Error("expected changes for modified file")
}
}
func TestGitHasBeadsChanges_WithRedirect_NoChanges(t *testing.T) {
ctx := context.Background()
sourcePath, _, cleanup := setupRedirectedBeadsRepo(t)
defer cleanup()
// Set BEADS_DIR to point to source's .beads (which has the redirect)
oldBeadsDir := os.Getenv("BEADS_DIR")
os.Setenv("BEADS_DIR", filepath.Join(sourcePath, ".beads"))
defer os.Setenv("BEADS_DIR", oldBeadsDir)
hasChanges, err := gitHasBeadsChanges(ctx)
if err != nil {
t.Fatalf("gitHasBeadsChanges() error = %v", err)
}
if hasChanges {
t.Error("expected no changes for clean redirected repo")
}
}
func TestGitHasBeadsChanges_WithRedirect_WithChanges(t *testing.T) {
ctx := context.Background()
sourcePath, targetPath, cleanup := setupRedirectedBeadsRepo(t)
defer cleanup()
// Set BEADS_DIR to point to source's .beads (which has the redirect)
oldBeadsDir := os.Getenv("BEADS_DIR")
os.Setenv("BEADS_DIR", filepath.Join(sourcePath, ".beads"))
defer os.Setenv("BEADS_DIR", oldBeadsDir)
// Modify the issues.jsonl file in target (where actual beads is)
jsonlPath := filepath.Join(targetPath, ".beads", "issues.jsonl")
if err := os.WriteFile(jsonlPath, []byte(`{"id":"test-2"}`+"\n"), 0644); err != nil {
t.Fatalf("failed to modify issues.jsonl: %v", err)
}
hasChanges, err := gitHasBeadsChanges(ctx)
if err != nil {
t.Fatalf("gitHasBeadsChanges() error = %v", err)
}
if !hasChanges {
t.Error("expected changes for modified file in redirected repo")
}
}
func TestGitHasUncommittedBeadsChanges_NoChanges(t *testing.T) {
ctx := context.Background()
_, cleanup := setupGitRepoWithBeads(t)
defer cleanup()
hasChanges, err := gitHasUncommittedBeadsChanges(ctx)
if err != nil {
t.Fatalf("gitHasUncommittedBeadsChanges() error = %v", err)
}
if hasChanges {
t.Error("expected no changes for clean repo")
}
}
func TestGitHasUncommittedBeadsChanges_WithChanges(t *testing.T) {
ctx := context.Background()
repoPath, cleanup := setupGitRepoWithBeads(t)
defer cleanup()
// Modify the issues.jsonl file
jsonlPath := filepath.Join(repoPath, ".beads", "issues.jsonl")
if err := os.WriteFile(jsonlPath, []byte(`{"id":"test-2"}`+"\n"), 0644); err != nil {
t.Fatalf("failed to modify issues.jsonl: %v", err)
}
hasChanges, err := gitHasUncommittedBeadsChanges(ctx)
if err != nil {
t.Fatalf("gitHasUncommittedBeadsChanges() error = %v", err)
}
if !hasChanges {
t.Error("expected changes for modified file")
}
}
func TestGitHasUncommittedBeadsChanges_WithRedirect_NoChanges(t *testing.T) {
ctx := context.Background()
sourcePath, _, cleanup := setupRedirectedBeadsRepo(t)
defer cleanup()
// Set BEADS_DIR to point to source's .beads (which has the redirect)
oldBeadsDir := os.Getenv("BEADS_DIR")
os.Setenv("BEADS_DIR", filepath.Join(sourcePath, ".beads"))
defer os.Setenv("BEADS_DIR", oldBeadsDir)
hasChanges, err := gitHasUncommittedBeadsChanges(ctx)
if err != nil {
t.Fatalf("gitHasUncommittedBeadsChanges() error = %v", err)
}
if hasChanges {
t.Error("expected no changes for clean redirected repo")
}
}
func TestGitHasUncommittedBeadsChanges_WithRedirect_WithChanges(t *testing.T) {
ctx := context.Background()
sourcePath, targetPath, cleanup := setupRedirectedBeadsRepo(t)
defer cleanup()
// Set BEADS_DIR to point to source's .beads (which has the redirect)
oldBeadsDir := os.Getenv("BEADS_DIR")
os.Setenv("BEADS_DIR", filepath.Join(sourcePath, ".beads"))
defer os.Setenv("BEADS_DIR", oldBeadsDir)
// Modify the issues.jsonl file in target (where actual beads is)
jsonlPath := filepath.Join(targetPath, ".beads", "issues.jsonl")
if err := os.WriteFile(jsonlPath, []byte(`{"id":"test-2"}`+"\n"), 0644); err != nil {
t.Fatalf("failed to modify issues.jsonl: %v", err)
}
hasChanges, err := gitHasUncommittedBeadsChanges(ctx)
if err != nil {
t.Fatalf("gitHasUncommittedBeadsChanges() error = %v", err)
}
if !hasChanges {
t.Error("expected changes for modified file in redirected repo")
}
}
func TestParseGitStatusForBeadsChanges(t *testing.T) {
tests := []struct {
name string
status string
expected bool
}{
// No changes
{
name: "empty status",
status: "",
expected: false,
},
{
name: "whitespace only",
status: " \n",
expected: false,
},
// Modified (should return true)
{
name: "staged modified",
status: "M .beads/issues.jsonl",
expected: true,
},
{
name: "unstaged modified",
status: " M .beads/issues.jsonl",
expected: true,
},
{
name: "staged and unstaged modified",
status: "MM .beads/issues.jsonl",
expected: true,
},
// Added (should return true)
{
name: "staged added",
status: "A .beads/issues.jsonl",
expected: true,
},
{
name: "added then modified",
status: "AM .beads/issues.jsonl",
expected: true,
},
// Untracked (should return false)
{
name: "untracked file",
status: "?? .beads/issues.jsonl",
expected: false,
},
// Deleted (should return false)
{
name: "staged deleted",
status: "D .beads/issues.jsonl",
expected: false,
},
{
name: "unstaged deleted",
status: " D .beads/issues.jsonl",
expected: false,
},
// Edge cases
{
name: "renamed file",
status: "R old.jsonl -> .beads/issues.jsonl",
expected: false,
},
{
name: "copied file",
status: "C source.jsonl -> .beads/issues.jsonl",
expected: false,
},
{
name: "status too short",
status: "M",
expected: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := parseGitStatusForBeadsChanges(tt.status)
if result != tt.expected {
t.Errorf("parseGitStatusForBeadsChanges(%q) = %v, want %v",
tt.status, result, tt.expected)
}
})
}
}
// TestGitBranchHasUpstream tests the gitBranchHasUpstream function
// which checks if a specific branch (not current HEAD) has upstream configured.
// This is critical for jj/jujutsu compatibility where HEAD is always detached
// but the sync-branch may have proper upstream tracking.
func TestGitBranchHasUpstream(t *testing.T) {
// Create temp directory for test repos
tmpDir, err := os.MkdirTemp("", "beads-upstream-test-*")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
// Create a bare "remote" repo
remoteDir := filepath.Join(tmpDir, "remote.git")
if err := exec.Command("git", "init", "--bare", remoteDir).Run(); err != nil {
t.Fatalf("Failed to create bare repo: %v", err)
}
// Create local repo using cached git template (bd-ktng optimization)
localDir := filepath.Join(tmpDir, "local")
if err := os.MkdirAll(localDir, 0755); err != nil {
t.Fatalf("Failed to create local dir: %v", err)
}
initGitTemplate()
if gitTemplateErr != nil {
t.Fatalf("git template init failed: %v", gitTemplateErr)
}
if err := copyGitDir(gitTemplateDir, localDir); err != nil {
t.Fatalf("failed to copy git template: %v", err)
}
cmds := [][]string{
{"git", "remote", "add", "origin", remoteDir},
}
for _, args := range cmds {
cmd := exec.Command(args[0], args[1:]...)
cmd.Dir = localDir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("Failed to run %v: %v\n%s", args, err, out)
}
}
// Create .beads directory (required for RepoContext)
beadsDir := filepath.Join(localDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("Failed to create .beads dir: %v", err)
}
if err := os.WriteFile(filepath.Join(beadsDir, "issues.jsonl"), []byte{}, 0644); err != nil {
t.Fatalf("Failed to write issues.jsonl: %v", err)
}
// Create initial commit on main
testFile := filepath.Join(localDir, "test.txt")
if err := os.WriteFile(testFile, []byte("test"), 0644); err != nil {
t.Fatalf("Failed to create test file: %v", err)
}
cmds = [][]string{
{"git", "add", "."},
{"git", "commit", "-m", "initial"},
{"git", "push", "-u", "origin", "main"},
}
for _, args := range cmds {
cmd := exec.Command(args[0], args[1:]...)
cmd.Dir = localDir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("Failed to run %v: %v\n%s", args, err, out)
}
}
// Create beads-sync branch with upstream
cmds = [][]string{
{"git", "checkout", "-b", "beads-sync"},
{"git", "push", "-u", "origin", "beads-sync"},
}
for _, args := range cmds {
cmd := exec.Command(args[0], args[1:]...)
cmd.Dir = localDir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("Failed to run %v: %v\n%s", args, err, out)
}
}
// Save current dir and change to local repo
origDir, _ := os.Getwd()
if err := os.Chdir(localDir); err != nil {
t.Fatalf("Failed to chdir: %v", err)
}
// Reset caches after changing directory so RepoContext uses this repo
git.ResetCaches()
beads.ResetCaches()
defer func() {
os.Chdir(origDir)
git.ResetCaches()
beads.ResetCaches()
}()
// Test 1: beads-sync branch should have upstream
t.Run("branch with upstream returns true", func(t *testing.T) {
if !gitBranchHasUpstream("beads-sync") {
t.Error("gitBranchHasUpstream('beads-sync') = false, want true")
}
})
// Test 2: non-existent branch should return false
t.Run("non-existent branch returns false", func(t *testing.T) {
if gitBranchHasUpstream("no-such-branch") {
t.Error("gitBranchHasUpstream('no-such-branch') = true, want false")
}
})
// Test 3: Simulate jj detached HEAD - beads-sync should still work
t.Run("works with detached HEAD (jj scenario)", func(t *testing.T) {
// Detach HEAD (simulating jj's behavior)
cmd := exec.Command("git", "checkout", "--detach", "HEAD")
cmd.Dir = localDir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("Failed to detach HEAD: %v\n%s", err, out)
}
// gitHasUpstream() should fail (detached HEAD)
if gitHasUpstream() {
t.Error("gitHasUpstream() = true with detached HEAD, want false")
}
// But gitBranchHasUpstream("beads-sync") should still work
if !gitBranchHasUpstream("beads-sync") {
t.Error("gitBranchHasUpstream('beads-sync') = false with detached HEAD, want true")
}
})
// Test 4: branch without upstream should return false
t.Run("branch without upstream returns false", func(t *testing.T) {
// Create a local-only branch (no upstream)
cmd := exec.Command("git", "checkout", "-b", "local-only")
cmd.Dir = localDir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("Failed to create local branch: %v\n%s", err, out)
}
if gitBranchHasUpstream("local-only") {
t.Error("gitBranchHasUpstream('local-only') = true, want false (no upstream)")
}
})
}
// TestGetCurrentBranchOrHEAD tests getCurrentBranchOrHEAD which returns "HEAD"
// when in detached HEAD state (e.g., jj/jujutsu) instead of failing.
// TestConfigPreservedDuringSync is a regression test for GH#1100.
// It verifies that config.yaml in .beads/ is not overwritten during sync operations.
// The bug was caused by restoreBeadsDirFromBranch() which ran:
//
// git checkout HEAD -- .beads/
//
// This restored the ENTIRE .beads/ directory, including user's uncommitted config.yaml.
// The function was removed in PR #918 (pull-first refactor).
// This test ensures similar restoration logic is never reintroduced.
func TestConfigPreservedDuringSync(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
t.Run("uncommitted config.yaml not overwritten by git operations", func(t *testing.T) {
// Setup: Create git repo with .beads directory
repoPath, cleanup := setupGitRepoWithBeads(t)
defer cleanup()
beadsDir := filepath.Join(repoPath, ".beads")
// Create config.yaml and commit it
configPath := filepath.Join(beadsDir, "config.yaml")
originalContent := "sync:\n branch: beads-sync\n"
if err := os.WriteFile(configPath, []byte(originalContent), 0644); err != nil {
t.Fatalf("failed to write config.yaml: %v", err)
}
// Commit the config
_ = exec.Command("git", "add", ".beads/config.yaml").Run()
if err := exec.Command("git", "commit", "-m", "add config").Run(); err != nil {
t.Fatalf("failed to commit config: %v", err)
}
// Now modify config.yaml with UNCOMMITTED changes (the bug scenario)
modifiedContent := originalContent + "# User's uncommitted customization\ntest-marker: preserved\n"
if err := os.WriteFile(configPath, []byte(modifiedContent), 0644); err != nil {
t.Fatalf("failed to modify config.yaml: %v", err)
}
// Verify the modification exists before any operations
beforeSync, err := os.ReadFile(configPath)
if err != nil {
t.Fatalf("failed to read config.yaml: %v", err)
}
if !strings.Contains(string(beforeSync), "test-marker: preserved") {
t.Fatal("expected test-marker in config before operations")
}
// Simulate what the old buggy code did: git checkout HEAD -- .beads/
// This should NOT happen during normal sync, but we test that IF it did,
// it would restore committed state (losing uncommitted changes).
// The fact that no code calls this anymore is the fix.
// Verify config.yaml still has uncommitted changes
// (This passes because nothing calls restoreBeadsDirFromBranch anymore)
afterContent, err := os.ReadFile(configPath)
if err != nil {
t.Fatalf("failed to read config.yaml after operations: %v", err)
}
if !strings.Contains(string(afterContent), "test-marker: preserved") {
t.Errorf("REGRESSION: uncommitted config.yaml changes were lost!\n"+
"Before: %s\nAfter: %s", beforeSync, afterContent)
}
// Also verify that git status shows the file as modified (uncommitted)
cmd := exec.Command("git", "status", "--porcelain", ".beads/config.yaml")
output, err := cmd.Output()
if err != nil {
t.Fatalf("git status failed: %v", err)
}
// Should show " M" (modified, unstaged)
if !strings.Contains(string(output), "M") {
t.Errorf("expected config.yaml to show as modified in git status, got: %q", output)
}
})
t.Run("restoreBeadsDirFromBranch function does not exist", func(t *testing.T) {
// This test documents that the function was intentionally removed.
// If someone adds it back, they should also update this test with justification.
// Read the sync_git.go source file
syncGitPath := filepath.Join(getProjectRoot(t), "cmd", "bd", "sync_git.go")
content, err := os.ReadFile(syncGitPath)
if err != nil {
t.Fatalf("failed to read sync_git.go: %v", err)
}
// The function should NOT exist
if strings.Contains(string(content), "func restoreBeadsDirFromBranch") {
t.Error("REGRESSION: restoreBeadsDirFromBranch function was reintroduced!\n" +
"This function caused GH#1100 by restoring entire .beads/ directory.\n" +
"If you need this functionality, use selective restoration that excludes config.yaml.")
}
})
}
// getProjectRoot returns the project root directory for test file access.
// Uses runtime.Caller to find the source file location, which is immune to
// os.Chdir side effects from other subtests.
func getProjectRoot(t *testing.T) string {
t.Helper()
_, thisFile, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("failed to get current file path via runtime.Caller")
}
// thisFile is cmd/bd/sync_git_test.go; walk up to find go.mod
dir := filepath.Dir(thisFile)
for {
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
return dir
}
parent := filepath.Dir(dir)
if parent == dir {
t.Fatal("could not find project root (go.mod)")
}
dir = parent
}
}
func TestGetCurrentBranchOrHEAD(t *testing.T) {
ctx := context.Background()
// Create temp directory for test repo
tmpDir, err := os.MkdirTemp("", "beads-branch-test-*")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
// Initialize git repo
cmds := [][]string{
{"git", "init", "-b", "main"},
{"git", "config", "user.email", "test@test.com"},
{"git", "config", "user.name", "Test"},
}
for _, args := range cmds {
cmd := exec.Command(args[0], args[1:]...)
cmd.Dir = tmpDir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("Failed to run %v: %v\n%s", args, err, out)
}
}
// Create initial commit
testFile := filepath.Join(tmpDir, "test.txt")
if err := os.WriteFile(testFile, []byte("test"), 0644); err != nil {
t.Fatalf("Failed to create test file: %v", err)
}
cmds = [][]string{
{"git", "add", "test.txt"},
{"git", "commit", "-m", "initial"},
}
for _, args := range cmds {
cmd := exec.Command(args[0], args[1:]...)
cmd.Dir = tmpDir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("Failed to run %v: %v\n%s", args, err, out)
}
}
// Save current dir and change to test repo
origDir, _ := os.Getwd()
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to chdir: %v", err)
}
defer os.Chdir(origDir)
// Test 1: Normal branch returns branch name
t.Run("returns branch name when on branch", func(t *testing.T) {
branch := getCurrentBranchOrHEAD(ctx)
if branch != "main" {
t.Errorf("getCurrentBranchOrHEAD() = %q, want %q", branch, "main")
}
})
// Test 2: Detached HEAD returns "HEAD"
t.Run("returns HEAD when detached", func(t *testing.T) {
// Detach HEAD
cmd := exec.Command("git", "checkout", "--detach", "HEAD")
cmd.Dir = tmpDir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("Failed to detach HEAD: %v\n%s", err, out)
}
branch := getCurrentBranchOrHEAD(ctx)
if branch != "HEAD" {
t.Errorf("getCurrentBranchOrHEAD() = %q, want %q", branch, "HEAD")
}
})
}

View file

@ -54,15 +54,6 @@ func sanitizeMetadataKey(key string) string {
return strings.ReplaceAll(key, ":", "_")
}
// getDebounceDuration returns the configured flush debounce duration.
func getDebounceDuration() time.Duration {
duration := config.GetDuration("flush-debounce")
if duration == 0 {
return 5 * time.Second
}
return duration
}
// exportToJSONLWithStore exports issues to JSONL using the provided store.
// If multi-repo mode is configured, routes issues to their respective JSONL files.
// Otherwise, exports to a single JSONL file.
@ -218,6 +209,67 @@ func importToJSONLWithStore(ctx context.Context, store *dolt.DoltStore, jsonlPat
return err
}
// exportToJSONL exports the current database state to the JSONL file.
// Delegates to exportToJSONLWithStore using the global store.
func exportToJSONL(ctx context.Context, jsonlPath string) error {
if err := ensureStoreActive(); err != nil {
return fmt.Errorf("activating store: %w", err)
}
if err := exportToJSONLWithStore(ctx, store, jsonlPath); err != nil {
return err
}
repoKey := getRepoKeyForPath(jsonlPath)
updateExportMetadata(ctx, store, jsonlPath, slog.Default(), repoKey)
return nil
}
// importFromJSONL imports issues from a JSONL file into the database.
func importFromJSONL(ctx context.Context, jsonlPath string) error {
if err := ensureStoreActive(); err != nil {
return fmt.Errorf("activating store: %w", err)
}
return importToJSONLWithStore(ctx, store, jsonlPath)
}
// loadIssuesFromJSONL reads a JSONL file and returns the parsed issues.
func loadIssuesFromJSONL(jsonlPath string) ([]*types.Issue, error) {
file, err := os.Open(jsonlPath) // #nosec G304 - controlled path
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, fmt.Errorf("opening JSONL: %w", err)
}
defer file.Close()
var issues []*types.Issue
scanner := bufio.NewScanner(file)
const maxScannerBuffer = 1024 * 1024 // 1MB
scanner.Buffer(make([]byte, 0, maxScannerBuffer), maxScannerBuffer)
lineNum := 0
for scanner.Scan() {
lineNum++
line := scanner.Text()
if line == "" {
continue
}
var issue types.Issue
if err := json.Unmarshal([]byte(line), &issue); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to parse JSONL line %d: %v\n", lineNum, err)
continue
}
issues = append(issues, &issue)
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("reading JSONL: %w", err)
}
return issues, nil
}
// updateExportMetadata updates jsonl_content_hash and related metadata after a successful export.
func updateExportMetadata(ctx context.Context, store *dolt.DoltStore, jsonlPath string, log *slog.Logger, keySuffix string) {
if keySuffix != "" {

View file

@ -1,101 +0,0 @@
//go:build cgo
package main
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/config"
)
func TestBuildGitCommitArgs_ConfigOptions(t *testing.T) {
initConfigForTest(t)
config.Set("git.author", "Test User <test@example.com>")
config.Set("git.no-gpg-sign", true)
args := buildGitCommitArgs("/repo", "hello", "--", ".beads")
joined := strings.Join(args, " ")
if !strings.Contains(joined, "--author") {
t.Fatalf("expected --author in args: %v", args)
}
if !strings.Contains(joined, "--no-gpg-sign") {
t.Fatalf("expected --no-gpg-sign in args: %v", args)
}
if !strings.Contains(joined, "-m hello") {
t.Fatalf("expected message in args: %v", args)
}
// buildGitCommitArgs includes -C for raw exec.Command
if !strings.HasPrefix(joined, "-C /repo commit") {
t.Fatalf("expected -C /repo prefix in args: %v", args)
}
}
func TestBuildCommitArgs_ForRepoContext(t *testing.T) {
// buildCommitArgs is for use with RepoContext.GitCmd() which sets cmd.Dir,
// so it should NOT include the -C flag.
initConfigForTest(t)
config.Set("git.author", "Test User <test@example.com>")
config.Set("git.no-gpg-sign", true)
args := buildCommitArgs("hello", "--", ".beads")
joined := strings.Join(args, " ")
// Should start with "commit", not "-C"
if !strings.HasPrefix(joined, "commit") {
t.Fatalf("expected to start with 'commit', got: %v", args)
}
if strings.Contains(joined, "-C") {
t.Fatalf("buildCommitArgs should NOT contain -C (RepoContext sets cmd.Dir): %v", args)
}
if !strings.Contains(joined, "--author") {
t.Fatalf("expected --author in args: %v", args)
}
if !strings.Contains(joined, "--no-gpg-sign") {
t.Fatalf("expected --no-gpg-sign in args: %v", args)
}
if !strings.Contains(joined, "-m hello") {
t.Fatalf("expected message in args: %v", args)
}
}
func TestGitCommitBeadsDir_PathspecDoesNotCommitOtherStagedFiles(t *testing.T) {
_, cleanup := setupGitRepo(t)
defer cleanup()
initConfigForTest(t)
if err := os.MkdirAll(".beads", 0o755); err != nil {
t.Fatalf("MkdirAll: %v", err)
}
// Stage an unrelated file before running gitCommitBeadsDir.
if err := os.WriteFile("other.txt", []byte("x\n"), 0o600); err != nil {
t.Fatalf("WriteFile other: %v", err)
}
_ = exec.Command("git", "add", "other.txt").Run()
// Create a beads sync file to commit.
issuesPath := filepath.Join(".beads", "issues.jsonl")
if err := os.WriteFile(issuesPath, []byte("{\"id\":\"test-1\"}\n"), 0o600); err != nil {
t.Fatalf("WriteFile issues: %v", err)
}
ctx := context.Background()
if err := gitCommitBeadsDir(ctx, "beads commit"); err != nil {
t.Fatalf("gitCommitBeadsDir: %v", err)
}
// other.txt should still be staged after the beads-only commit.
out, err := exec.Command("git", "diff", "--cached", "--name-only").CombinedOutput()
if err != nil {
t.Fatalf("git diff --cached: %v\n%s", err, out)
}
if strings.TrimSpace(string(out)) != "other.txt" {
t.Fatalf("expected other.txt still staged, got: %q", out)
}
}

View file

@ -1,119 +0,0 @@
//go:build cgo && integration
package main
import (
"context"
"os"
"os/exec"
"path/filepath"
"testing"
)
// TestLocalOnlyMode tests that daemon works with local git repos (no remote)
func TestLocalOnlyMode(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
// Create temp directory for local-only repo
tempDir := t.TempDir()
// Initialize local git repo without remote
runGitCmd(t, tempDir, "init")
runGitCmd(t, tempDir, "config", "user.email", "test@example.com")
runGitCmd(t, tempDir, "config", "user.name", "Test User")
// Change to temp directory so git commands run in the test repo
t.Chdir(tempDir)
// Verify no remote exists
cmd := exec.Command("git", "remote")
output, err := cmd.Output()
if err != nil {
t.Fatalf("Failed to check git remotes: %v", err)
}
if len(output) > 0 {
t.Fatalf("Expected no remotes, got: %s", output)
}
ctx := context.Background()
// Test hasGitRemote returns false
if hasGitRemote(ctx) {
t.Error("Expected hasGitRemote to return false for local-only repo")
}
// Test gitPull returns nil (no error)
if err := gitPull(ctx, ""); err != nil {
t.Errorf("gitPull should gracefully skip when no remote, got error: %v", err)
}
// Test gitPush returns nil (no error)
if err := gitPush(ctx, ""); err != nil {
t.Errorf("gitPush should gracefully skip when no remote, got error: %v", err)
}
// Create a dummy JSONL file to commit
beadsDir := filepath.Join(tempDir, ".beads")
if err := os.MkdirAll(beadsDir, 0750); err != nil {
t.Fatalf("Failed to create .beads dir: %v", err)
}
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
if err := os.WriteFile(jsonlPath, []byte(`{"id":"test-1","title":"Test"}`+"\n"), 0644); err != nil {
t.Fatalf("Failed to write JSONL: %v", err)
}
// Test gitCommit works (local commits should work fine)
runGitCmd(t, tempDir, "add", ".beads")
if err := gitCommit(ctx, jsonlPath, "Test commit"); err != nil {
t.Errorf("gitCommit should work in local-only mode, got error: %v", err)
}
// Verify commit was created
cmd = exec.Command("git", "log", "--oneline")
output, err = cmd.Output()
if err != nil {
t.Fatalf("Failed to check git log: %v", err)
}
if len(output) == 0 {
t.Error("Expected at least one commit in git log")
}
}
// TestWithRemote verifies hasGitRemote detects remotes correctly
func TestWithRemote(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
// Create temp directories
tempDir := t.TempDir()
remoteDir := filepath.Join(tempDir, "remote")
cloneDir := filepath.Join(tempDir, "clone")
// Create bare remote
if err := os.MkdirAll(remoteDir, 0750); err != nil {
t.Fatalf("Failed to create remote dir: %v", err)
}
runGitCmd(t, remoteDir, "init", "--bare")
// Clone it
runGitCmd(t, tempDir, "clone", remoteDir, cloneDir)
// Change to clone directory
t.Chdir(cloneDir)
ctx := context.Background()
// Test hasGitRemote returns true
if !hasGitRemote(ctx) {
t.Error("Expected hasGitRemote to return true when origin exists")
}
// Verify git pull doesn't error (even with empty remote)
// Note: pull might fail with "couldn't find remote ref", but that's different
// from the fatal "'origin' does not appear to be a git repository" error
_ = gitPull(ctx, "") // Just verify it doesn't panic
}

View file

@ -1,398 +0,0 @@
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"unicode/utf8"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/ui"
)
// InteractiveConflict represents a conflict to be resolved interactively
type InteractiveConflict struct {
IssueID string
Local *beads.Issue
Remote *beads.Issue
Base *beads.Issue // May be nil for first sync
}
// InteractiveResolution represents the user's choice for a conflict
type InteractiveResolution struct {
Choice string // "local", "remote", "merged", "skip", "quit", "accept-all"
Issue *beads.Issue // The resolved issue (nil if skipped/quit)
}
// resolveConflictsInteractively handles manual conflict resolution with user prompts.
// Returns resolved issues and the count of skipped conflicts.
func resolveConflictsInteractively(conflicts []InteractiveConflict) ([]*beads.Issue, int, error) {
// Check if we're in a terminal
if !ui.IsTerminal() {
return nil, 0, fmt.Errorf("manual conflict resolution requires an interactive terminal")
}
reader := bufio.NewReader(os.Stdin)
var resolved []*beads.Issue
skipped := 0
fmt.Printf("\n%s Manual Conflict Resolution\n", ui.RenderAccent("🔧"))
fmt.Printf("Found %d conflict(s) requiring manual resolution.\n\n", len(conflicts))
for i, conflict := range conflicts {
fmt.Printf("%s Conflict %d/%d: %s\n", ui.RenderAccent("━━━"), i+1, len(conflicts), conflict.IssueID)
fmt.Println()
// Display the diff
displayConflictDiff(conflict)
// Prompt for choice
resolution, err := promptConflictResolution(reader, conflict)
if err != nil {
return nil, 0, fmt.Errorf("reading user input: %w", err)
}
switch resolution.Choice {
case "quit":
// Quit - skip all remaining conflicts
remaining := len(conflicts) - i
skipped += remaining
fmt.Printf(" %s Quit - skipping %d remaining conflict(s)\n\n", ui.RenderMuted("⏹"), remaining)
return resolved, skipped, nil
case "accept-all":
// Auto-merge all remaining conflicts
fmt.Printf(" %s Auto-merging %d remaining conflict(s)...\n", ui.RenderAccent("⚡"), len(conflicts)-i)
for j := i; j < len(conflicts); j++ {
c := conflicts[j]
if c.Local != nil && c.Remote != nil {
merged, _ := mergeFieldLevel(c.Base, c.Local, c.Remote)
resolved = append(resolved, merged)
} else if c.Local != nil {
resolved = append(resolved, c.Local)
} else if c.Remote != nil {
resolved = append(resolved, c.Remote)
}
}
fmt.Printf(" %s Done\n\n", ui.RenderPass("✓"))
return resolved, skipped, nil
case "skip":
skipped++
fmt.Printf(" %s Skipped (will keep local, conflict remains)\n\n", ui.RenderMuted("⏭"))
case "local":
resolved = append(resolved, conflict.Local)
fmt.Printf(" %s Kept local version\n\n", ui.RenderPass("✓"))
case "remote":
resolved = append(resolved, conflict.Remote)
fmt.Printf(" %s Kept remote version\n\n", ui.RenderPass("✓"))
case "merged":
resolved = append(resolved, resolution.Issue)
fmt.Printf(" %s Used field-level merge\n\n", ui.RenderPass("✓"))
}
}
return resolved, skipped, nil
}
// displayConflictDiff shows the differences between local and remote versions
func displayConflictDiff(conflict InteractiveConflict) {
local := conflict.Local
remote := conflict.Remote
if local == nil && remote == nil {
fmt.Println(" Both versions are nil (should not happen)")
return
}
if local == nil {
fmt.Printf(" %s Local: (deleted)\n", ui.RenderMuted("LOCAL"))
fmt.Printf(" %s Remote: exists\n", ui.RenderAccent("REMOTE"))
displayIssueSummary(remote, " ")
return
}
if remote == nil {
fmt.Printf(" %s Local: exists\n", ui.RenderAccent("LOCAL"))
displayIssueSummary(local, " ")
fmt.Printf(" %s Remote: (deleted)\n", ui.RenderMuted("REMOTE"))
return
}
// Both exist - show field-by-field diff
fmt.Printf(" %s\n", ui.RenderMuted("─── Field Differences ───"))
fmt.Println()
// Title
if local.Title != remote.Title {
fmt.Printf(" %s\n", ui.RenderAccent("title:"))
fmt.Printf(" %s %s\n", ui.RenderMuted("local:"), local.Title)
fmt.Printf(" %s %s\n", ui.RenderAccent("remote:"), remote.Title)
}
// Status
if local.Status != remote.Status {
fmt.Printf(" %s\n", ui.RenderAccent("status:"))
fmt.Printf(" %s %s\n", ui.RenderMuted("local:"), local.Status)
fmt.Printf(" %s %s\n", ui.RenderAccent("remote:"), remote.Status)
}
// Priority
if local.Priority != remote.Priority {
fmt.Printf(" %s\n", ui.RenderAccent("priority:"))
fmt.Printf(" %s P%d\n", ui.RenderMuted("local:"), local.Priority)
fmt.Printf(" %s P%d\n", ui.RenderAccent("remote:"), remote.Priority)
}
// Assignee
if local.Assignee != remote.Assignee {
fmt.Printf(" %s\n", ui.RenderAccent("assignee:"))
fmt.Printf(" %s %s\n", ui.RenderMuted("local:"), valueOrNone(local.Assignee))
fmt.Printf(" %s %s\n", ui.RenderAccent("remote:"), valueOrNone(remote.Assignee))
}
// Description (show truncated if different)
if local.Description != remote.Description {
fmt.Printf(" %s\n", ui.RenderAccent("description:"))
fmt.Printf(" %s %s\n", ui.RenderMuted("local:"), truncateText(local.Description))
fmt.Printf(" %s %s\n", ui.RenderAccent("remote:"), truncateText(remote.Description))
}
// Notes (show truncated if different)
if local.Notes != remote.Notes {
fmt.Printf(" %s\n", ui.RenderAccent("notes:"))
fmt.Printf(" %s %s\n", ui.RenderMuted("local:"), truncateText(local.Notes))
fmt.Printf(" %s %s\n", ui.RenderAccent("remote:"), truncateText(remote.Notes))
}
// Labels
localLabels := strings.Join(local.Labels, ", ")
remoteLabels := strings.Join(remote.Labels, ", ")
if localLabels != remoteLabels {
fmt.Printf(" %s\n", ui.RenderAccent("labels:"))
fmt.Printf(" %s [%s]\n", ui.RenderMuted("local:"), valueOrNone(localLabels))
fmt.Printf(" %s [%s]\n", ui.RenderAccent("remote:"), valueOrNone(remoteLabels))
}
// Updated timestamps
fmt.Printf(" %s\n", ui.RenderAccent("updated_at:"))
fmt.Printf(" %s %s\n", ui.RenderMuted("local:"), local.UpdatedAt.Format("2006-01-02 15:04:05"))
fmt.Printf(" %s %s\n", ui.RenderAccent("remote:"), remote.UpdatedAt.Format("2006-01-02 15:04:05"))
// Indicate which is newer
if local.UpdatedAt.After(remote.UpdatedAt) {
fmt.Printf(" %s\n", ui.RenderPass("(local is newer)"))
} else if remote.UpdatedAt.After(local.UpdatedAt) {
fmt.Printf(" %s\n", ui.RenderPass("(remote is newer)"))
} else {
fmt.Printf(" %s\n", ui.RenderMuted("(same timestamp)"))
}
fmt.Println()
}
// displayIssueSummary shows a brief summary of an issue
func displayIssueSummary(issue *beads.Issue, indent string) {
if issue == nil {
return
}
fmt.Printf("%stitle: %s\n", indent, issue.Title)
fmt.Printf("%sstatus: %s, priority: P%d\n", indent, issue.Status, issue.Priority)
if issue.Assignee != "" {
fmt.Printf("%sassignee: %s\n", indent, issue.Assignee)
}
}
// promptConflictResolution asks the user how to resolve a conflict
func promptConflictResolution(reader *bufio.Reader, conflict InteractiveConflict) (InteractiveResolution, error) {
local := conflict.Local
remote := conflict.Remote
// Build options based on what's available
var options []string
optionMap := make(map[string]string)
if local != nil {
options = append(options, "l")
optionMap["l"] = "local"
optionMap["local"] = "local"
}
if remote != nil {
options = append(options, "r")
optionMap["r"] = "remote"
optionMap["remote"] = "remote"
}
if local != nil && remote != nil {
options = append(options, "m")
optionMap["m"] = "merged"
optionMap["merge"] = "merged"
optionMap["merged"] = "merged"
}
options = append(options, "s", "a", "q", "d", "?")
optionMap["s"] = "skip"
optionMap["skip"] = "skip"
optionMap["a"] = "accept-all"
optionMap["all"] = "accept-all"
optionMap["q"] = "quit"
optionMap["quit"] = "quit"
optionMap["d"] = "diff"
optionMap["diff"] = "diff"
optionMap["?"] = "help"
optionMap["help"] = "help"
for {
fmt.Printf(" Choice [%s]: ", strings.Join(options, "/"))
input, err := reader.ReadString('\n')
if err != nil {
if err == io.EOF {
// Treat EOF as quit
return InteractiveResolution{Choice: "quit", Issue: nil}, nil
}
return InteractiveResolution{}, err
}
choice := strings.TrimSpace(strings.ToLower(input))
if choice == "" {
// Default to merged if both exist, otherwise keep the one that exists
if local != nil && remote != nil {
choice = "m"
} else if local != nil {
choice = "l"
} else {
choice = "r"
}
}
action, ok := optionMap[choice]
if !ok {
fmt.Printf(" %s Unknown option '%s'. Type '?' for help.\n", ui.RenderFail("✗"), choice)
continue
}
switch action {
case "help":
printResolutionHelp(local != nil, remote != nil)
continue
case "diff":
// Show detailed diff (JSON dump)
showDetailedDiff(conflict)
continue
case "local":
return InteractiveResolution{Choice: "local", Issue: local}, nil
case "remote":
return InteractiveResolution{Choice: "remote", Issue: remote}, nil
case "merged":
// Do field-level merge (same as automatic LWW merge)
merged, _ := mergeFieldLevel(conflict.Base, local, remote)
return InteractiveResolution{Choice: "merged", Issue: merged}, nil
case "skip":
return InteractiveResolution{Choice: "skip", Issue: nil}, nil
case "accept-all":
return InteractiveResolution{Choice: "accept-all", Issue: nil}, nil
case "quit":
return InteractiveResolution{Choice: "quit", Issue: nil}, nil
}
}
}
// printResolutionHelp shows help for resolution options
func printResolutionHelp(hasLocal, hasRemote bool) {
fmt.Println()
fmt.Println(" Resolution options:")
if hasLocal {
fmt.Println(" l, local - Keep the local version")
}
if hasRemote {
fmt.Println(" r, remote - Keep the remote version")
}
if hasLocal && hasRemote {
fmt.Println(" m, merge - Auto-merge (LWW for scalars, union for collections)")
}
fmt.Println(" s, skip - Skip this conflict (keep local, conflict remains)")
fmt.Println(" a, all - Accept auto-merge for all remaining conflicts")
fmt.Println(" q, quit - Quit and skip all remaining conflicts")
fmt.Println(" d, diff - Show detailed JSON diff")
fmt.Println(" ?, help - Show this help")
fmt.Println()
}
// showDetailedDiff displays the full JSON of both versions
func showDetailedDiff(conflict InteractiveConflict) {
fmt.Println()
fmt.Printf(" %s\n", ui.RenderMuted("─── Detailed Diff (JSON) ───"))
fmt.Println()
if conflict.Local != nil {
fmt.Printf(" %s\n", ui.RenderAccent("LOCAL:"))
localJSON, err := json.MarshalIndent(conflict.Local, " ", " ")
if err != nil {
fmt.Printf(" (error marshaling: %v)\n", err)
} else {
fmt.Println(string(localJSON))
}
fmt.Println()
} else {
fmt.Printf(" %s (deleted)\n", ui.RenderMuted("LOCAL:"))
}
if conflict.Remote != nil {
fmt.Printf(" %s\n", ui.RenderAccent("REMOTE:"))
remoteJSON, err := json.MarshalIndent(conflict.Remote, " ", " ")
if err != nil {
fmt.Printf(" (error marshaling: %v)\n", err)
} else {
fmt.Println(string(remoteJSON))
}
fmt.Println()
} else {
fmt.Printf(" %s (deleted)\n", ui.RenderMuted("REMOTE:"))
}
}
// Helper functions
func valueOrNone(s string) string {
if s == "" {
return "(none)"
}
return s
}
const truncateTextMaxLen = 60
// truncateText truncates a string to a fixed max length (runes, not bytes) for proper UTF-8 handling.
// Replaces newlines with spaces for single-line display.
func truncateText(s string) string {
if s == "" {
return "(empty)"
}
// Replace newlines with spaces for display
s = strings.ReplaceAll(s, "\n", " ")
s = strings.ReplaceAll(s, "\r", "")
// Count runes, not bytes, for proper UTF-8 handling
runeCount := utf8.RuneCountInString(s)
if runeCount <= truncateTextMaxLen {
return s
}
// Truncate by runes
runes := []rune(s)
if truncateTextMaxLen <= 3 {
return "..."
}
return string(runes[:truncateTextMaxLen-3]) + "..."
}

View file

@ -1,338 +0,0 @@
package main
import (
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/beads"
)
func TestTruncateText(t *testing.T) {
tests := []struct {
name string
input string
want string
}{
{
name: "empty string",
input: "",
want: "(empty)",
},
{
name: "short string",
input: "hello",
want: "hello",
},
{
name: "newlines replaced",
input: "line1\nline2\r\nline3",
want: "line1 line2 line3",
},
{
name: "truncated at fixed max",
input: strings.Repeat("a", truncateTextMaxLen+10),
want: strings.Repeat("a", truncateTextMaxLen-3) + "...",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := truncateText(tt.input)
if got != tt.want {
t.Errorf("truncateText(%q) = %q, want %q", tt.input, got, tt.want)
}
})
}
}
func TestValueOrNone(t *testing.T) {
tests := []struct {
input string
want string
}{
{"", "(none)"},
{"value", "value"},
{" ", " "},
}
for _, tt := range tests {
got := valueOrNone(tt.input)
if got != tt.want {
t.Errorf("valueOrNone(%q) = %q, want %q", tt.input, got, tt.want)
}
}
}
func TestInteractiveConflictDisplay(t *testing.T) {
now := time.Now()
earlier := now.Add(-1 * time.Hour)
// Test that displayConflictDiff doesn't panic for various inputs
tests := []struct {
name string
conflict InteractiveConflict
}{
{
name: "both exist with differences",
conflict: InteractiveConflict{
IssueID: "test-1",
Local: &beads.Issue{
ID: "test-1",
Title: "Local title",
Status: beads.StatusOpen,
Priority: 1,
UpdatedAt: now,
},
Remote: &beads.Issue{
ID: "test-1",
Title: "Remote title",
Status: beads.StatusInProgress,
Priority: 2,
UpdatedAt: earlier,
},
},
},
{
name: "local deleted",
conflict: InteractiveConflict{
IssueID: "test-2",
Local: nil,
Remote: &beads.Issue{
ID: "test-2",
Title: "Remote only",
Status: beads.StatusOpen,
UpdatedAt: now,
},
},
},
{
name: "remote deleted",
conflict: InteractiveConflict{
IssueID: "test-3",
Local: &beads.Issue{
ID: "test-3",
Title: "Local only",
Status: beads.StatusOpen,
UpdatedAt: now,
},
Remote: nil,
},
},
{
name: "same timestamps",
conflict: InteractiveConflict{
IssueID: "test-4",
Local: &beads.Issue{
ID: "test-4",
Title: "Same time local",
UpdatedAt: now,
},
Remote: &beads.Issue{
ID: "test-4",
Title: "Same time remote",
UpdatedAt: now,
},
},
},
{
name: "with labels",
conflict: InteractiveConflict{
IssueID: "test-5",
Local: &beads.Issue{
ID: "test-5",
Title: "Local",
Labels: []string{"bug", "urgent"},
UpdatedAt: now,
},
Remote: &beads.Issue{
ID: "test-5",
Title: "Remote",
Labels: []string{"feature", "low-priority"},
UpdatedAt: earlier,
},
},
},
{
name: "both nil (edge case)",
conflict: InteractiveConflict{
IssueID: "test-6",
Local: nil,
Remote: nil,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Just make sure it doesn't panic
displayConflictDiff(tt.conflict)
})
}
}
func TestShowDetailedDiff(t *testing.T) {
now := time.Now()
tests := []struct {
name string
conflict InteractiveConflict
}{
{
name: "both exist",
conflict: InteractiveConflict{
IssueID: "test-1",
Local: &beads.Issue{
ID: "test-1",
Title: "Local",
UpdatedAt: now,
},
Remote: &beads.Issue{
ID: "test-1",
Title: "Remote",
UpdatedAt: now,
},
},
},
{
name: "local nil",
conflict: InteractiveConflict{
IssueID: "test-2",
Local: nil,
Remote: &beads.Issue{
ID: "test-2",
Title: "Remote",
UpdatedAt: now,
},
},
},
{
name: "remote nil",
conflict: InteractiveConflict{
IssueID: "test-3",
Local: &beads.Issue{
ID: "test-3",
Title: "Local",
UpdatedAt: now,
},
Remote: nil,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Just make sure it doesn't panic
showDetailedDiff(tt.conflict)
})
}
}
func TestPrintResolutionHelp(t *testing.T) {
// Test all combinations of hasLocal/hasRemote
tests := []struct {
hasLocal bool
hasRemote bool
}{
{true, true},
{true, false},
{false, true},
{false, false},
}
for _, tt := range tests {
// Just make sure it doesn't panic
printResolutionHelp(tt.hasLocal, tt.hasRemote)
}
}
func TestDisplayIssueSummary(t *testing.T) {
issue := &beads.Issue{
ID: "test-1",
Title: "Test issue",
Status: beads.StatusOpen,
Priority: 2,
Assignee: "alice",
}
// Just make sure it doesn't panic
displayIssueSummary(issue, " ")
displayIssueSummary(nil, " ")
}
func TestInteractiveResolutionMerge(t *testing.T) {
// Test that mergeFieldLevel is called correctly in resolution
now := time.Now()
earlier := now.Add(-1 * time.Hour)
local := &beads.Issue{
ID: "test-1",
Title: "Local title",
Status: beads.StatusOpen,
Priority: 1,
Labels: []string{"bug"},
UpdatedAt: now,
}
remote := &beads.Issue{
ID: "test-1",
Title: "Remote title",
Status: beads.StatusInProgress,
Priority: 2,
Labels: []string{"feature"},
UpdatedAt: earlier,
}
// mergeFieldLevel should pick local values (newer) for scalars
// and union for labels
merged, _ := mergeFieldLevel(nil, local, remote)
if merged.Title != "Local title" {
t.Errorf("Expected title 'Local title', got %q", merged.Title)
}
if merged.Status != beads.StatusOpen {
t.Errorf("Expected status 'open', got %q", merged.Status)
}
if merged.Priority != 1 {
t.Errorf("Expected priority 1, got %d", merged.Priority)
}
// Labels should be merged (union)
if len(merged.Labels) != 2 {
t.Errorf("Expected 2 labels, got %d", len(merged.Labels))
}
labelsStr := strings.Join(merged.Labels, ",")
if !strings.Contains(labelsStr, "bug") || !strings.Contains(labelsStr, "feature") {
t.Errorf("Expected labels to contain 'bug' and 'feature', got %v", merged.Labels)
}
}
func TestInteractiveResolutionChoices(t *testing.T) {
// Test InteractiveResolution struct values
tests := []struct {
name string
choice string
issue *beads.Issue
}{
{"local", "local", &beads.Issue{ID: "test"}},
{"remote", "remote", &beads.Issue{ID: "test"}},
{"merged", "merged", &beads.Issue{ID: "test"}},
{"skip", "skip", nil},
{"quit", "quit", nil},
{"accept-all", "accept-all", nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
res := InteractiveResolution{Choice: tt.choice, Issue: tt.issue}
if res.Choice != tt.choice {
t.Errorf("Expected choice %q, got %q", tt.choice, res.Choice)
}
if tt.issue == nil && res.Issue != nil {
t.Errorf("Expected nil issue, got %v", res.Issue)
}
if tt.issue != nil && res.Issue == nil {
t.Errorf("Expected non-nil issue, got nil")
}
})
}
}

View file

@ -1,772 +0,0 @@
package main
import (
"bufio"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"time"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/config"
)
// MergeResult contains the outcome of a 3-way merge
type MergeResult struct {
Merged []*beads.Issue // Final merged state
Conflicts int // Number of true conflicts resolved
Strategy map[string]string // Per-issue: "local", "remote", "merged", "same"
ManualConflicts []ManualConflict // Fields requiring manual resolution
}
// ManualConflict represents a field conflict that requires manual user resolution.
// When a field's strategy is "manual", the conflict is flagged here instead of
// being auto-resolved.
type ManualConflict struct {
IssueID string // Issue ID with conflict
Field string // Field name (e.g., "estimated_minutes")
LocalValue interface{} // Local (ours) value
RemoteValue interface{} // Remote (theirs) value
LocalTime time.Time // When local value was set
RemoteTime time.Time // When remote value was set
}
// MergeStrategy constants for describing how each issue was merged
const (
StrategyLocal = "local" // Only local changed
StrategyRemote = "remote" // Only remote changed
StrategyMerged = "merged" // True conflict, LWW applied
StrategySame = "same" // Both made identical change (or no change)
)
// mergeFieldLevel performs field-by-field merge for true conflicts.
// Returns a new issue with:
// - Scalar fields: from the newer issue (LWW by updated_at, remote wins on tie)
// - Labels: union of both
// - Dependencies: union of both (by DependsOnID+Type)
// - Comments: append from both (deduplicated by ID or content)
// - compaction_level: max strategy (highest value wins)
// - estimated_minutes: manual strategy if configured (flags for user resolution)
//
// Also returns any manual conflicts that require user resolution.
func mergeFieldLevel(_base, local, remote *beads.Issue) (*beads.Issue, []ManualConflict) {
var manualConflicts []ManualConflict
// Determine which is newer for LWW scalars
localNewer := local.UpdatedAt.After(remote.UpdatedAt)
// Clock skew detection: warn if timestamps differ by more than 24 hours
timeDiff := local.UpdatedAt.Sub(remote.UpdatedAt)
if timeDiff < 0 {
timeDiff = -timeDiff
}
if timeDiff > 24*time.Hour {
fmt.Fprintf(os.Stderr, "Warning: Issue %s has %v timestamp difference (possible clock skew)\n",
local.ID, timeDiff.Round(time.Hour))
}
// Start with a copy of the newer issue for scalar fields
var merged beads.Issue
if localNewer {
merged = *local
} else {
merged = *remote
}
// Get per-field strategies from config
fieldStrategies := config.GetFieldStrategies()
// Handle compaction_level with configurable strategy (default: max)
compactionStrategy := fieldStrategies["compaction_level"]
if compactionStrategy == "" {
compactionStrategy = config.FieldStrategyMax // Default for compaction_level
}
switch compactionStrategy {
case config.FieldStrategyMax:
merged.CompactionLevel = maxInt(local.CompactionLevel, remote.CompactionLevel)
case config.FieldStrategyNewest:
// Already handled by default LWW merge above
case config.FieldStrategyManual:
if local.CompactionLevel != remote.CompactionLevel {
manualConflicts = append(manualConflicts, ManualConflict{
IssueID: local.ID,
Field: "compaction_level",
LocalValue: local.CompactionLevel,
RemoteValue: remote.CompactionLevel,
LocalTime: local.UpdatedAt,
RemoteTime: remote.UpdatedAt,
})
// Keep local value as tentative (can be overridden by resolve command)
merged.CompactionLevel = local.CompactionLevel
}
}
// Handle estimated_minutes with configurable strategy (default: manual per spec)
estimatedStrategy := fieldStrategies["estimated_minutes"]
if estimatedStrategy == "" {
estimatedStrategy = config.FieldStrategyManual // Default for estimated_minutes (human judgment needed)
}
switch estimatedStrategy {
case config.FieldStrategyMax:
merged.EstimatedMinutes = maxIntPtr(local.EstimatedMinutes, remote.EstimatedMinutes)
case config.FieldStrategyNewest:
// Already handled by default LWW merge above
case config.FieldStrategyManual:
if !intPtrEqual(local.EstimatedMinutes, remote.EstimatedMinutes) {
manualConflicts = append(manualConflicts, ManualConflict{
IssueID: local.ID,
Field: "estimated_minutes",
LocalValue: derefIntPtr(local.EstimatedMinutes),
RemoteValue: derefIntPtr(remote.EstimatedMinutes),
LocalTime: local.UpdatedAt,
RemoteTime: remote.UpdatedAt,
})
// Keep local value as tentative
merged.EstimatedMinutes = local.EstimatedMinutes
}
}
// Union merge: Labels (always union unless configured otherwise)
labelsStrategy := fieldStrategies["labels"]
if labelsStrategy == "" || labelsStrategy == config.FieldStrategyUnion {
merged.Labels = mergeLabels(local.Labels, remote.Labels)
} else if labelsStrategy == config.FieldStrategyNewest {
// Use LWW for labels (already set from initial merge)
}
// Union merge: Dependencies (by DependsOnID+Type key)
merged.Dependencies = mergeDependencies(local.Dependencies, remote.Dependencies)
// Append merge: Comments (deduplicated)
merged.Comments = mergeComments(local.Comments, remote.Comments)
return &merged, manualConflicts
}
// maxInt returns the larger of two integers
func maxInt(a, b int) int {
if a > b {
return a
}
return b
}
// maxIntPtr returns a pointer to the larger of two *int values
// Treats nil as 0 for comparison purposes
func maxIntPtr(a, b *int) *int {
aVal := 0
bVal := 0
if a != nil {
aVal = *a
}
if b != nil {
bVal = *b
}
if aVal >= bVal {
return a
}
return b
}
// derefIntPtr safely dereferences an int pointer, returning nil representation for display
func derefIntPtr(p *int) interface{} {
if p == nil {
return nil
}
return *p
}
// displayManualConflicts prints manual conflicts that need user resolution.
// These are fields where the configured strategy is "manual" and values differ.
func displayManualConflicts(conflicts []ManualConflict) {
fmt.Fprintf(os.Stderr, "\n⚠ %d field conflict(s) require manual resolution:\n", len(conflicts))
for _, c := range conflicts {
fmt.Fprintf(os.Stderr, "\n %s.%s:\n", c.IssueID, c.Field)
fmt.Fprintf(os.Stderr, " Local: %v (set %s)\n", formatConflictValue(c.LocalValue), c.LocalTime.Format("2006-01-02"))
fmt.Fprintf(os.Stderr, " Remote: %v (set %s)\n", formatConflictValue(c.RemoteValue), c.RemoteTime.Format("2006-01-02"))
}
fmt.Fprintf(os.Stderr, "\n To resolve, use one of:\n")
fmt.Fprintf(os.Stderr, " bd sync --ours # Keep all local values\n")
fmt.Fprintf(os.Stderr, " bd sync --theirs # Keep all remote values\n")
fmt.Fprintf(os.Stderr, " bd resolve <issue-id> <field> <value> # Set specific value\n\n")
}
// formatConflictValue formats a conflict value for display
func formatConflictValue(v interface{}) string {
if v == nil {
return "(not set)"
}
return fmt.Sprintf("%v", v)
}
// mergeLabels performs set union on labels
func mergeLabels(local, remote []string) []string {
seen := make(map[string]bool)
var result []string
// Add all local labels
for _, label := range local {
if !seen[label] {
seen[label] = true
result = append(result, label)
}
}
// Add remote labels not in local
for _, label := range remote {
if !seen[label] {
seen[label] = true
result = append(result, label)
}
}
// Sort for deterministic output
sort.Strings(result)
return result
}
// dependencyKey creates a unique key for deduplication
// Uses DependsOnID + Type as the identity (same target+type = same dependency)
func dependencyKey(d *beads.Dependency) string {
if d == nil {
return ""
}
return d.DependsOnID + ":" + string(d.Type)
}
// mergeDependencies performs set union on dependencies
func mergeDependencies(local, remote []*beads.Dependency) []*beads.Dependency {
seen := make(map[string]*beads.Dependency)
// Add all local dependencies
for _, dep := range local {
if dep == nil {
continue
}
key := dependencyKey(dep)
seen[key] = dep
}
// Add remote dependencies not in local (or with newer timestamp)
for _, dep := range remote {
if dep == nil {
continue
}
key := dependencyKey(dep)
if existing, ok := seen[key]; ok {
// Keep the one with newer CreatedAt
if dep.CreatedAt.After(existing.CreatedAt) {
seen[key] = dep
}
} else {
seen[key] = dep
}
}
// Collect and sort by key for deterministic output
keys := make([]string, 0, len(seen))
for k := range seen {
keys = append(keys, k)
}
sort.Strings(keys)
result := make([]*beads.Dependency, 0, len(keys))
for _, k := range keys {
result = append(result, seen[k])
}
return result
}
// commentKey creates a unique key for deduplication
// Uses ID if present, otherwise content hash
func commentKey(c *beads.Comment) string {
if c == nil {
return ""
}
if c.ID != 0 {
return fmt.Sprintf("id:%d", c.ID)
}
// Fallback to content-based key for comments without ID
return fmt.Sprintf("content:%s:%s", c.Author, c.Text)
}
// mergeComments performs append-merge on comments with deduplication
func mergeComments(local, remote []*beads.Comment) []*beads.Comment {
seen := make(map[string]*beads.Comment)
// Add all local comments
for _, c := range local {
if c == nil {
continue
}
key := commentKey(c)
seen[key] = c
}
// Add remote comments not in local
for _, c := range remote {
if c == nil {
continue
}
key := commentKey(c)
if _, ok := seen[key]; !ok {
seen[key] = c
}
}
// Collect all comments
result := make([]*beads.Comment, 0, len(seen))
for _, c := range seen {
result = append(result, c)
}
// Sort by CreatedAt for chronological order
sort.Slice(result, func(i, j int) bool {
return result[i].CreatedAt.Before(result[j].CreatedAt)
})
return result
}
// MergeIssues performs 3-way merge: base x local x remote -> merged
//
// Algorithm:
// 1. Build lookup maps for base, local, and remote by issue ID
// 2. Collect all unique issue IDs across all three sets
// 3. For each ID, apply MergeIssue to determine final state
// 4. Return merged result with per-issue strategy annotations
func MergeIssues(base, local, remote []*beads.Issue) *MergeResult {
// Build lookup maps by issue ID
baseMap := buildIssueMap(base)
localMap := buildIssueMap(local)
remoteMap := buildIssueMap(remote)
// Collect all unique issue IDs
allIDs := collectUniqueIDs(baseMap, localMap, remoteMap)
result := &MergeResult{
Merged: make([]*beads.Issue, 0, len(allIDs)),
Strategy: make(map[string]string),
ManualConflicts: make([]ManualConflict, 0),
}
for _, id := range allIDs {
baseIssue := baseMap[id]
localIssue := localMap[id]
remoteIssue := remoteMap[id]
merged, strategy, manualConflicts := MergeIssue(baseIssue, localIssue, remoteIssue)
// Always record strategy (even for deletions, for logging/debugging)
result.Strategy[id] = strategy
// Collect manual conflicts for fields that need user resolution
if len(manualConflicts) > 0 {
result.ManualConflicts = append(result.ManualConflicts, manualConflicts...)
}
if merged != nil {
result.Merged = append(result.Merged, merged)
if strategy == StrategyMerged {
result.Conflicts++
}
}
// If merged is nil, the issue was deleted (present in base but not in local/remote)
}
return result
}
// MergeIssue merges a single issue using 3-way algorithm
//
// Cases:
// - base=nil: First sync (no common ancestor)
// - local=nil, remote=nil: impossible (would not be in allIDs)
// - local=nil: return remote (new from remote)
// - remote=nil: return local (new from local)
// - both exist: LWW by updated_at (both added independently)
//
// - base!=nil: Standard 3-way merge
// - base=local=remote: no changes (same)
// - base=local, remote differs: only remote changed (remote)
// - base=remote, local differs: only local changed (local)
// - local=remote (but differs from base): both made identical change (same)
// - all three differ: true conflict, LWW by updated_at (merged)
//
// - Deletion handling:
// - local=nil (deleted locally): if remote unchanged from base, delete; else keep remote
// - remote=nil (deleted remotely): if local unchanged from base, delete; else keep local
func MergeIssue(base, local, remote *beads.Issue) (*beads.Issue, string, []ManualConflict) {
// Case: no base state (first sync)
if base == nil {
if local == nil && remote == nil {
// Should not happen (would not be in allIDs)
return nil, StrategySame, nil
}
if local == nil {
return remote, StrategyRemote, nil
}
if remote == nil {
return local, StrategyLocal, nil
}
// Both exist with no base: treat as conflict, use field-level merge
// This allows labels/comments to be union-merged even in first sync
merged, manualConflicts := mergeFieldLevel(nil, local, remote)
return merged, StrategyMerged, manualConflicts
}
// Case: local deleted
if local == nil {
// If remote unchanged from base, honor the local deletion
if issueEqual(base, remote) {
return nil, StrategyLocal, nil
}
// Remote changed after local deleted: keep remote (remote wins conflict)
return remote, StrategyMerged, nil
}
// Case: remote deleted
if remote == nil {
// If local unchanged from base, honor the remote deletion
if issueEqual(base, local) {
return nil, StrategyRemote, nil
}
// Local changed after remote deleted: keep local (local wins conflict)
return local, StrategyMerged, nil
}
// Standard 3-way cases (all three exist)
if issueEqual(base, local) && issueEqual(base, remote) {
// No changes anywhere
return local, StrategySame, nil
}
if issueEqual(base, local) {
// Only remote changed
return remote, StrategyRemote, nil
}
if issueEqual(base, remote) {
// Only local changed
return local, StrategyLocal, nil
}
if issueEqual(local, remote) {
// Both made identical change
return local, StrategySame, nil
}
// True conflict: use field-level merge
// - Scalar fields use LWW (remote wins on tie)
// - Labels use union (no data loss)
// - Dependencies use union (no data loss)
// - Comments use append (deduplicated)
// - compaction_level uses max (or configured strategy)
// - estimated_minutes uses configured strategy (may flag for manual resolution)
merged, manualConflicts := mergeFieldLevel(base, local, remote)
return merged, StrategyMerged, manualConflicts
}
// issueEqual compares two issues for equality (content-level, not pointer)
// Compares all merge-relevant fields: content, status, workflow, assignment
func issueEqual(a, b *beads.Issue) bool {
if a == nil || b == nil {
return a == nil && b == nil
}
// Core identification
if a.ID != b.ID {
return false
}
// Issue content
if a.Title != b.Title ||
a.Description != b.Description ||
a.Design != b.Design ||
a.AcceptanceCriteria != b.AcceptanceCriteria ||
a.Notes != b.Notes {
return false
}
// Status & workflow
if a.Status != b.Status ||
a.Priority != b.Priority ||
a.IssueType != b.IssueType {
return false
}
// Assignment
if a.Assignee != b.Assignee {
return false
}
if !intPtrEqual(a.EstimatedMinutes, b.EstimatedMinutes) {
return false
}
// Timestamps (updated_at is crucial for LWW)
if !a.UpdatedAt.Equal(b.UpdatedAt) {
return false
}
// Closed state
if !timePtrEqual(a.ClosedAt, b.ClosedAt) ||
a.CloseReason != b.CloseReason {
return false
}
// Time-based scheduling
if !timePtrEqual(a.DueAt, b.DueAt) ||
!timePtrEqual(a.DeferUntil, b.DeferUntil) {
return false
}
// External reference
if !stringPtrEqual(a.ExternalRef, b.ExternalRef) {
return false
}
// Labels (order-independent comparison)
if !stringSliceEqual(a.Labels, b.Labels) {
return false
}
// Dependencies (order-independent comparison)
if !dependenciesEqual(a.Dependencies, b.Dependencies) {
return false
}
// Comments (order-independent comparison)
if !commentsEqual(a.Comments, b.Comments) {
return false
}
return true
}
// buildIssueMap creates a lookup map from issue ID to issue pointer
func buildIssueMap(issues []*beads.Issue) map[string]*beads.Issue {
m := make(map[string]*beads.Issue, len(issues))
for _, issue := range issues {
if issue != nil {
m[issue.ID] = issue
}
}
return m
}
// collectUniqueIDs gathers all unique issue IDs from the three maps
// Returns sorted for deterministic output
func collectUniqueIDs(base, local, remote map[string]*beads.Issue) []string {
seen := make(map[string]bool)
for id := range base {
seen[id] = true
}
for id := range local {
seen[id] = true
}
for id := range remote {
seen[id] = true
}
ids := make([]string, 0, len(seen))
for id := range seen {
ids = append(ids, id)
}
sort.Strings(ids)
return ids
}
// Helper functions for pointer comparison
func intPtrEqual(a, b *int) bool {
if a == nil && b == nil {
return true
}
if a == nil || b == nil {
return false
}
return *a == *b
}
func stringPtrEqual(a, b *string) bool {
if a == nil && b == nil {
return true
}
if a == nil || b == nil {
return false
}
return *a == *b
}
func timePtrEqual(a, b *time.Time) bool {
if a == nil && b == nil {
return true
}
if a == nil || b == nil {
return false
}
return a.Equal(*b)
}
func stringSliceEqual(a, b []string) bool {
if len(a) != len(b) {
return false
}
// Sort copies for order-independent comparison
aCopy := make([]string, len(a))
bCopy := make([]string, len(b))
copy(aCopy, a)
copy(bCopy, b)
sort.Strings(aCopy)
sort.Strings(bCopy)
for i := range aCopy {
if aCopy[i] != bCopy[i] {
return false
}
}
return true
}
// dependenciesEqual compares two dependency slices for equality (order-independent).
// Compares by (depends_on_id, type) pairs which form the logical identity of a dependency.
func dependenciesEqual(a, b []*beads.Dependency) bool {
if len(a) != len(b) {
return false
}
if len(a) == 0 {
return true
}
// Build key sets for order-independent comparison
aKeys := make([]string, len(a))
for i, d := range a {
aKeys[i] = fmt.Sprintf("%s:%s", d.DependsOnID, d.Type)
}
bKeys := make([]string, len(b))
for i, d := range b {
bKeys[i] = fmt.Sprintf("%s:%s", d.DependsOnID, d.Type)
}
sort.Strings(aKeys)
sort.Strings(bKeys)
for i := range aKeys {
if aKeys[i] != bKeys[i] {
return false
}
}
return true
}
// commentsEqual compares two comment slices for equality (order-independent).
// Compares by (author, text, created_at) which identifies a comment's content.
func commentsEqual(a, b []*beads.Comment) bool {
if len(a) != len(b) {
return false
}
if len(a) == 0 {
return true
}
// Build key sets for order-independent comparison
aKeys := make([]string, len(a))
for i, c := range a {
aKeys[i] = fmt.Sprintf("%s:%s:%d", c.Author, c.Text, c.CreatedAt.UnixNano())
}
bKeys := make([]string, len(b))
for i, c := range b {
bKeys[i] = fmt.Sprintf("%s:%s:%d", c.Author, c.Text, c.CreatedAt.UnixNano())
}
sort.Strings(aKeys)
sort.Strings(bKeys)
for i := range aKeys {
if aKeys[i] != bKeys[i] {
return false
}
}
return true
}
// Base state storage functions for sync_base.jsonl
const syncBaseFileName = "sync_base.jsonl"
// loadBaseState loads the last-synced state from .beads/sync_base.jsonl
// Returns empty slice if file doesn't exist (first sync scenario)
func loadBaseState(beadsDir string) ([]*beads.Issue, error) {
baseStatePath := filepath.Join(beadsDir, syncBaseFileName)
// Check if file exists
if _, err := os.Stat(baseStatePath); os.IsNotExist(err) {
// First sync: no base state
return nil, nil
}
// Read and parse JSONL file
file, err := os.Open(baseStatePath)
if err != nil {
return nil, err
}
defer file.Close()
var issues []*beads.Issue
scanner := bufio.NewScanner(file)
// Increase buffer for large issues
buf := make([]byte, 0, 64*1024)
scanner.Buffer(buf, 1024*1024)
lineNum := 0
for scanner.Scan() {
lineNum++
line := scanner.Text()
if line == "" {
continue
}
var issue beads.Issue
if err := json.Unmarshal([]byte(line), &issue); err != nil {
fmt.Fprintf(os.Stderr, "Warning: Skipping malformed line %d in sync_base.jsonl: %v\n", lineNum, err)
continue
}
issues = append(issues, &issue)
}
if err := scanner.Err(); err != nil {
return nil, err
}
return issues, nil
}
// saveBaseState writes the merged state to .beads/sync_base.jsonl
// This becomes the base for the next 3-way merge
func saveBaseState(beadsDir string, issues []*beads.Issue) error {
baseStatePath := filepath.Join(beadsDir, syncBaseFileName)
// Write to temp file first for atomicity
tempPath := baseStatePath + ".tmp"
file, err := os.Create(tempPath)
if err != nil {
return err
}
encoder := json.NewEncoder(file)
encoder.SetEscapeHTML(false)
for _, issue := range issues {
if err := encoder.Encode(issue); err != nil {
_ = file.Close() // Best-effort cleanup
_ = os.Remove(tempPath)
return err
}
}
if err := file.Close(); err != nil {
_ = os.Remove(tempPath) // Best-effort cleanup
return err
}
// Atomic rename
return os.Rename(tempPath, baseStatePath)
}

File diff suppressed because it is too large Load diff

View file

@ -1,149 +0,0 @@
package main
import (
"context"
"fmt"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/storage/dolt"
)
// Sync mode constants - re-exported from internal/config for backward compatibility.
// These are used with *dolt.DoltStore (database) while config.SyncMode* are used
// with viper (config.yaml).
const (
// SyncModeGitPortable exports to JSONL on push, imports on pull.
// This is the default mode - works with standard git workflows.
SyncModeGitPortable = string(config.SyncModeGitPortable)
// SyncModeRealtime exports to JSONL on every database mutation.
// Provides immediate persistence but more git noise.
SyncModeRealtime = string(config.SyncModeRealtime)
// SyncModeDoltNative uses Dolt remotes for sync, no JSONL writes.
// Requires Dolt backend and configured Dolt remote.
SyncModeDoltNative = string(config.SyncModeDoltNative)
// SyncModeBeltAndSuspenders uses both Dolt remotes AND JSONL.
// Maximum redundancy - Dolt for versioning, JSONL for git portability.
SyncModeBeltAndSuspenders = string(config.SyncModeBeltAndSuspenders)
// SyncModeConfigKey is the database config key for sync mode.
SyncModeConfigKey = "sync.mode"
// SyncExportOnConfigKey controls when JSONL export happens.
SyncExportOnConfigKey = "sync.export_on"
// SyncImportOnConfigKey controls when JSONL import happens.
SyncImportOnConfigKey = "sync.import_on"
)
// Trigger constants for export_on and import_on settings.
const (
// TriggerPush triggers on git push (export) or git pull (import).
TriggerPush = "push"
TriggerPull = "pull"
// TriggerChange triggers on every database mutation (realtime mode).
TriggerChange = "change"
)
// GetSyncMode returns the configured sync mode, checking config.yaml first (where bd config set writes),
// then falling back to database. This fixes GH#1277 where yaml and database were inconsistent.
func GetSyncMode(ctx context.Context, s *dolt.DoltStore) string {
// First check config.yaml (where bd config set writes for sync.* keys)
yamlMode := config.GetSyncMode()
if yamlMode != "" && yamlMode != config.SyncModeGitPortable {
// Non-default value in yaml takes precedence
return string(yamlMode)
}
// Fall back to database (legacy path)
mode, err := s.GetConfig(ctx, SyncModeConfigKey)
if err != nil || mode == "" {
return SyncModeGitPortable
}
// Validate mode using the shared validation
if !config.IsValidSyncMode(mode) {
return SyncModeGitPortable
}
return mode
}
// SetSyncMode sets the sync mode configuration in the database.
func SetSyncMode(ctx context.Context, s *dolt.DoltStore, mode string) error {
// Validate mode using the shared validation
if !config.IsValidSyncMode(mode) {
return fmt.Errorf("invalid sync mode: %s (valid: %s)",
mode, fmt.Sprintf("%v", config.ValidSyncModes()))
}
return s.SetConfig(ctx, SyncModeConfigKey, mode)
}
// GetExportTrigger returns when JSONL export should happen.
func GetExportTrigger(ctx context.Context, s *dolt.DoltStore) string {
trigger, err := s.GetConfig(ctx, SyncExportOnConfigKey)
if err != nil || trigger == "" {
// Default based on sync mode
mode := GetSyncMode(ctx, s)
if mode == SyncModeRealtime {
return TriggerChange
}
return TriggerPush
}
return trigger
}
// GetImportTrigger returns when JSONL import should happen.
func GetImportTrigger(ctx context.Context, s *dolt.DoltStore) string {
trigger, err := s.GetConfig(ctx, SyncImportOnConfigKey)
if err != nil || trigger == "" {
return TriggerPull
}
return trigger
}
// ShouldExportJSONL returns true if the current sync mode uses JSONL export.
// In dolt-native mode, JSONL is not used — all sync is via Dolt remotes.
// Belt-and-suspenders mode uses both Dolt AND JSONL for maximum redundancy.
//
// Uses GetSyncMode which checks config.yaml first, then falls back to the database.
// This ensures that sync.mode set in config.yaml (e.g. during Dolt migration) is
// respected even if not yet propagated to the database via 'bd sync mode set'.
func ShouldExportJSONL(ctx context.Context, s *dolt.DoltStore) bool {
mode := GetSyncMode(ctx, s)
return mode != SyncModeDoltNative
}
// ShouldImportJSONL returns true if the current sync mode uses JSONL import.
// In dolt-native mode, there is no JSONL to import — all sync is via Dolt remotes.
// Uses GetSyncMode which checks config.yaml first, then falls back to the database.
func ShouldImportJSONL(ctx context.Context, s *dolt.DoltStore) bool {
mode := GetSyncMode(ctx, s)
return mode != SyncModeDoltNative
}
// ShouldUseDoltRemote returns true if the current sync mode uses Dolt remotes.
func ShouldUseDoltRemote(ctx context.Context, s *dolt.DoltStore) bool {
mode := GetSyncMode(ctx, s)
return mode == SyncModeDoltNative || mode == SyncModeBeltAndSuspenders
}
// SyncModeDescription returns a human-readable description of the sync mode.
func SyncModeDescription(mode string) string {
switch mode {
case SyncModeGitPortable:
return "JSONL exported on push, imported on pull"
case SyncModeRealtime:
return "JSONL exported on every change"
case SyncModeDoltNative:
return "Dolt remotes for sync, no JSONL writes"
case SyncModeBeltAndSuspenders:
return "Both Dolt remotes and JSONL"
default:
return "unknown mode"
}
}

View file

@ -1,191 +0,0 @@
package main
import (
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/config"
)
// Sync mode info for display
var syncModeInfo = []struct {
Mode string
Description string
}{
{SyncModeGitPortable, "JSONL exported on push, imported on pull (default)"},
{SyncModeRealtime, "JSONL exported on every change (more git noise)"},
{SyncModeDoltNative, "Dolt remotes for sync, JSONL export-only backup (requires Dolt backend)"},
{SyncModeBeltAndSuspenders, "Both Dolt remotes and JSONL (maximum redundancy)"},
}
var syncModeCmd = &cobra.Command{
Use: "mode",
Short: "Manage sync mode configuration",
Long: `Manage sync mode configuration.
Sync mode controls how beads synchronizes data with git:
git-portable (default)
JSONL exported on push, imported on pull.
Works with standard git workflows.
realtime
JSONL exported on every database change.
Provides immediate persistence but more git noise.
dolt-native
Dolt remotes for sync, JSONL export-only (backup).
Requires Dolt backend and configured Dolt remote.
belt-and-suspenders
Uses both Dolt remotes AND JSONL.
Maximum redundancy - Dolt for versioning, JSONL for git portability.
Commands:
bd sync mode list List available sync modes
bd sync mode current Show current sync mode
bd sync mode set Set sync mode`,
}
var syncModeListCmd = &cobra.Command{
Use: "list",
Short: "List available sync modes",
Long: `List all available sync modes and their descriptions.
Sync modes control how beads synchronizes with git and Dolt remotes.`,
Run: func(cmd *cobra.Command, args []string) {
if jsonOutput {
modes := make([]map[string]string, len(syncModeInfo))
for i, m := range syncModeInfo {
modes[i] = map[string]string{
"mode": m.Mode,
"description": m.Description,
}
}
outputJSON(map[string]interface{}{
"modes": modes,
})
return
}
fmt.Println("Available sync modes:")
for _, m := range syncModeInfo {
fmt.Printf(" %-22s %s\n", m.Mode, m.Description)
}
fmt.Println("\nSet sync mode: bd sync mode set <mode>")
},
}
var syncModeCurrentCmd = &cobra.Command{
Use: "current",
Short: "Show current sync mode",
Long: `Show the currently configured sync mode.`,
Run: func(cmd *cobra.Command, args []string) {
// Try to get from database if available
var currentMode string
if store != nil {
currentMode = GetSyncMode(rootCtx, store)
} else {
// Fall back to config.yaml
currentMode = string(config.GetSyncMode())
}
if jsonOutput {
result := map[string]interface{}{
"mode": currentMode,
}
// Add description
for _, m := range syncModeInfo {
if m.Mode == currentMode {
result["description"] = m.Description
break
}
}
outputJSON(result)
return
}
fmt.Printf("Current sync mode: %s\n", currentMode)
// Show description
for _, m := range syncModeInfo {
if m.Mode == currentMode {
fmt.Printf(" %s\n", m.Description)
break
}
}
},
}
var syncModeSetCmd = &cobra.Command{
Use: "set <mode>",
Short: "Set sync mode",
Long: `Set the sync mode.
Valid modes:
git-portable JSONL exported on push, imported on pull (default)
realtime JSONL exported on every change
dolt-native Dolt remotes for sync, JSONL export-only backup (requires Dolt backend)
belt-and-suspenders Both Dolt remotes and JSONL
Example:
bd sync mode set realtime
bd sync mode set dolt-native`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
CheckReadonly("sync mode set")
mode := strings.TrimSpace(args[0])
// Validate mode
if !config.IsValidSyncMode(mode) {
fmt.Fprintf(os.Stderr, "Error: invalid sync mode: %s\n", mode)
fmt.Fprintf(os.Stderr, "Valid modes: %s\n", strings.Join(config.ValidSyncModes(), ", "))
os.Exit(1)
}
// Require direct mode for database writes
if err := ensureDirectMode("sync mode set requires direct database access"); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
// Set the mode
if err := SetSyncMode(rootCtx, store, mode); err != nil {
fmt.Fprintf(os.Stderr, "Error setting sync mode: %v\n", err)
os.Exit(1)
}
if jsonOutput {
result := map[string]interface{}{
"mode": mode,
}
// Add description
for _, m := range syncModeInfo {
if m.Mode == mode {
result["description"] = m.Description
break
}
}
outputJSON(result)
return
}
fmt.Printf("Sync mode set to: %s\n", mode)
// Show description
for _, m := range syncModeInfo {
if m.Mode == mode {
fmt.Printf(" %s\n", m.Description)
break
}
}
},
}
func init() {
syncModeCmd.AddCommand(syncModeListCmd)
syncModeCmd.AddCommand(syncModeCurrentCmd)
syncModeCmd.AddCommand(syncModeSetCmd)
syncCmd.AddCommand(syncModeCmd)
}

View file

@ -1,391 +0,0 @@
//go:build cgo
package main
import (
"bytes"
"context"
"encoding/json"
"io"
"os"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/storage/dolt"
)
// TestSyncModeListText tests `bd sync mode list` text output.
func TestSyncModeListText(t *testing.T) {
// Save original state
origJsonOutput := jsonOutput
defer func() { jsonOutput = origJsonOutput }()
jsonOutput = false
// Capture stdout
output := captureSyncModeListOutput(t)
// Verify output contains all sync modes
for _, mode := range config.ValidSyncModes() {
if !strings.Contains(output, mode) {
t.Errorf("output should contain mode '%s', got: %s", mode, output)
}
}
// Verify header
if !strings.Contains(output, "Available sync modes") {
t.Error("output should contain 'Available sync modes' header")
}
// Verify usage hint
if !strings.Contains(output, "bd sync mode set") {
t.Error("output should contain usage hint")
}
}
// TestSyncModeListJSON tests `bd sync mode list --json` output.
func TestSyncModeListJSON(t *testing.T) {
// Save original state
origJsonOutput := jsonOutput
defer func() { jsonOutput = origJsonOutput }()
jsonOutput = true
// Capture stdout
output := captureSyncModeListOutput(t)
// Parse JSON
var result struct {
Modes []struct {
Mode string `json:"mode"`
Description string `json:"description"`
} `json:"modes"`
}
if err := json.Unmarshal([]byte(output), &result); err != nil {
t.Fatalf("failed to parse JSON output: %v\nOutput: %s", err, output)
}
// Verify we have 4 modes
if len(result.Modes) != 4 {
t.Errorf("expected 4 modes, got %d", len(result.Modes))
}
// Verify mode names match valid sync modes
modes := make(map[string]bool)
for _, m := range result.Modes {
modes[m.Mode] = true
if m.Description == "" {
t.Errorf("mode %s has empty description", m.Mode)
}
}
for _, expected := range config.ValidSyncModes() {
if !modes[expected] {
t.Errorf("missing mode: %s", expected)
}
}
}
// TestSyncModeCurrentWithStore tests `bd sync mode current` with a database.
func TestSyncModeCurrentWithStore(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("failed to create .beads dir: %v", err)
}
dbPath := filepath.Join(beadsDir, "beads.db")
testStore, err := dolt.New(ctx, &dolt.Config{Path: dbPath})
if err != nil {
t.Fatalf("failed to create store: %v", err)
}
defer testStore.Close()
// Set a specific sync mode
if err := SetSyncMode(ctx, testStore, SyncModeRealtime); err != nil {
t.Fatalf("failed to set sync mode: %v", err)
}
// Save and restore global store and rootCtx
origStore := store
origStoreActive := storeActive
origRootCtx := rootCtx
defer func() {
storeMutex.Lock()
store = origStore
storeActive = origStoreActive
storeMutex.Unlock()
rootCtx = origRootCtx
}()
storeMutex.Lock()
store = testStore
storeActive = true
storeMutex.Unlock()
rootCtx = ctx
// Test text output
t.Run("text", func(t *testing.T) {
origJsonOutput := jsonOutput
defer func() { jsonOutput = origJsonOutput }()
jsonOutput = false
output := captureSyncModeCurrentOutput(t)
if !strings.Contains(output, "realtime") {
t.Errorf("output should contain 'realtime', got: %s", output)
}
if !strings.Contains(output, "Current sync mode") {
t.Errorf("output should contain 'Current sync mode', got: %s", output)
}
})
// Test JSON output
t.Run("json", func(t *testing.T) {
origJsonOutput := jsonOutput
defer func() { jsonOutput = origJsonOutput }()
jsonOutput = true
output := captureSyncModeCurrentOutput(t)
var result map[string]interface{}
if err := json.Unmarshal([]byte(output), &result); err != nil {
t.Fatalf("failed to parse JSON: %v\nOutput: %s", err, output)
}
if result["mode"] != "realtime" {
t.Errorf("expected mode 'realtime', got %v", result["mode"])
}
if result["description"] == nil {
t.Error("expected description in output")
}
})
}
// TestSyncModeCurrentWithoutStore tests `bd sync mode current` without a database.
func TestSyncModeCurrentWithoutStore(t *testing.T) {
// Save and restore global store
origStore := store
origStoreActive := storeActive
defer func() {
storeMutex.Lock()
store = origStore
storeActive = origStoreActive
storeMutex.Unlock()
}()
storeMutex.Lock()
store = nil
storeActive = false
storeMutex.Unlock()
// Suppress config warnings for cleaner test output
origWarnings := config.ConfigWarnings
config.ConfigWarnings = false
defer func() { config.ConfigWarnings = origWarnings }()
// Test text output - should fall back to config.yaml (default: git-portable)
t.Run("text", func(t *testing.T) {
origJsonOutput := jsonOutput
defer func() { jsonOutput = origJsonOutput }()
jsonOutput = false
output := captureSyncModeCurrentOutput(t)
// Should show default mode when no store
if !strings.Contains(output, "git-portable") {
t.Errorf("output should contain 'git-portable' (default), got: %s", output)
}
})
// Test JSON output
t.Run("json", func(t *testing.T) {
origJsonOutput := jsonOutput
defer func() { jsonOutput = origJsonOutput }()
jsonOutput = true
output := captureSyncModeCurrentOutput(t)
var result map[string]interface{}
if err := json.Unmarshal([]byte(output), &result); err != nil {
t.Fatalf("failed to parse JSON: %v\nOutput: %s", err, output)
}
if result["mode"] != "git-portable" {
t.Errorf("expected mode 'git-portable', got %v", result["mode"])
}
})
}
// TestSyncModeInfoStructure verifies the syncModeInfo slice is well-formed.
func TestSyncModeInfoStructure(t *testing.T) {
if len(syncModeInfo) != 4 {
t.Errorf("expected 4 sync modes, got %d", len(syncModeInfo))
}
for i, m := range syncModeInfo {
if m.Mode == "" {
t.Errorf("syncModeInfo[%d] has empty Mode", i)
}
if m.Description == "" {
t.Errorf("syncModeInfo[%d] has empty Description", i)
}
}
// Verify all valid sync modes are present
modes := make(map[string]bool)
for _, m := range syncModeInfo {
modes[m.Mode] = true
}
for _, expected := range config.ValidSyncModes() {
if !modes[expected] {
t.Errorf("syncModeInfo missing mode: %s", expected)
}
}
}
// TestSyncModeSetValidModes tests `bd sync mode set` with valid modes.
func TestSyncModeSetValidModes(t *testing.T) {
for _, mode := range config.ValidSyncModes() {
t.Run(mode, func(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("failed to create .beads dir: %v", err)
}
dbPath := filepath.Join(beadsDir, "beads.db")
testStore, err := dolt.New(ctx, &dolt.Config{Path: dbPath})
if err != nil {
t.Fatalf("failed to create store: %v", err)
}
defer testStore.Close()
// Set the mode
if err := SetSyncMode(ctx, testStore, mode); err != nil {
t.Fatalf("failed to set sync mode %s: %v", mode, err)
}
// Verify it was set correctly
got := GetSyncMode(ctx, testStore)
if got != mode {
t.Errorf("GetSyncMode() = %q, want %q", got, mode)
}
})
}
}
// TestSyncModeSetInvalidMode tests `bd sync mode set` with an invalid mode.
func TestSyncModeSetInvalidMode(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("failed to create .beads dir: %v", err)
}
dbPath := filepath.Join(beadsDir, "beads.db")
testStore, err := dolt.New(ctx, &dolt.Config{Path: dbPath})
if err != nil {
t.Fatalf("failed to create store: %v", err)
}
defer testStore.Close()
// Try to set invalid mode
err = SetSyncMode(ctx, testStore, "invalid-mode")
if err == nil {
t.Error("expected error for invalid mode, got nil")
}
// Verify error message mentions valid modes
if err != nil && !strings.Contains(err.Error(), "invalid") {
t.Errorf("error should mention 'invalid', got: %v", err)
}
}
// TestSyncModeSetReadonly tests that `bd sync mode set` fails in readonly mode.
func TestSyncModeSetReadonly(t *testing.T) {
// Save and restore readonly mode
origReadonly := readonlyMode
defer func() { readonlyMode = origReadonly }()
readonlyMode = true
// The actual command would call CheckReadonly and exit
// We just verify the readonly flag is checked
if !readonlyMode {
t.Error("readonly mode should be enabled")
}
// In real usage, syncModeSetCmd.Run calls CheckReadonly("sync mode set")
// which would call FatalError. We can't easily test os.Exit, but we
// verify the readonly guard exists by checking the code path.
}
// TestSyncModeValidation tests the IsValidSyncMode helper.
func TestSyncModeValidation(t *testing.T) {
tests := []struct {
mode string
valid bool
}{
{"git-portable", true},
{"realtime", true},
{"dolt-native", true},
{"belt-and-suspenders", true},
{"GIT-PORTABLE", true}, // Case insensitive
{"Git-Portable", true}, // Case insensitive
{" realtime ", true}, // Whitespace trimmed
{"invalid", false},
{"", false},
{"git portable", false}, // Space not hyphen
}
for _, tt := range tests {
t.Run(tt.mode, func(t *testing.T) {
got := config.IsValidSyncMode(tt.mode)
if got != tt.valid {
t.Errorf("IsValidSyncMode(%q) = %v, want %v", tt.mode, got, tt.valid)
}
})
}
}
// captureSyncModeListOutput runs the sync mode list command and captures stdout.
func captureSyncModeListOutput(t *testing.T) string {
t.Helper()
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
syncModeListCmd.Run(syncModeListCmd, []string{})
w.Close()
var buf bytes.Buffer
io.Copy(&buf, r)
os.Stdout = oldStdout
return buf.String()
}
// captureSyncModeCurrentOutput runs the sync mode current command and captures stdout.
func captureSyncModeCurrentOutput(t *testing.T) string {
t.Helper()
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
syncModeCurrentCmd.Run(syncModeCurrentCmd, []string{})
w.Close()
var buf bytes.Buffer
io.Copy(&buf, r)
os.Stdout = oldStdout
return buf.String()
}

View file

@ -1,271 +0,0 @@
//go:build cgo
package main
import (
"context"
"os"
"path/filepath"
"testing"
"github.com/steveyegge/beads/internal/storage/dolt"
)
// TestSyncModeConfig verifies sync mode configuration storage and retrieval.
func TestSyncModeConfig(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
// Create .beads directory
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("mkdir failed: %v", err)
}
// Create store
dbPath := filepath.Join(beadsDir, "beads.db")
testStore, err := dolt.New(ctx, &dolt.Config{Path: dbPath})
if err != nil {
t.Fatalf("failed to create store: %v", err)
}
defer testStore.Close()
// Test 1: Default mode is git-portable
mode := GetSyncMode(ctx, testStore)
if mode != SyncModeGitPortable {
t.Errorf("default sync mode = %q, want %q", mode, SyncModeGitPortable)
}
t.Logf("✓ Default sync mode is git-portable")
// Test 2: Set and get realtime mode
if err := SetSyncMode(ctx, testStore, SyncModeRealtime); err != nil {
t.Fatalf("failed to set sync mode: %v", err)
}
mode = GetSyncMode(ctx, testStore)
if mode != SyncModeRealtime {
t.Errorf("sync mode = %q, want %q", mode, SyncModeRealtime)
}
t.Logf("✓ Can set and get realtime mode")
// Test 3: Set and get dolt-native mode
if err := SetSyncMode(ctx, testStore, SyncModeDoltNative); err != nil {
t.Fatalf("failed to set sync mode: %v", err)
}
mode = GetSyncMode(ctx, testStore)
if mode != SyncModeDoltNative {
t.Errorf("sync mode = %q, want %q", mode, SyncModeDoltNative)
}
t.Logf("✓ Can set and get dolt-native mode")
// Test 4: Set and get belt-and-suspenders mode
if err := SetSyncMode(ctx, testStore, SyncModeBeltAndSuspenders); err != nil {
t.Fatalf("failed to set sync mode: %v", err)
}
mode = GetSyncMode(ctx, testStore)
if mode != SyncModeBeltAndSuspenders {
t.Errorf("sync mode = %q, want %q", mode, SyncModeBeltAndSuspenders)
}
t.Logf("✓ Can set and get belt-and-suspenders mode")
// Test 5: Invalid mode returns error
err = SetSyncMode(ctx, testStore, "invalid-mode")
if err == nil {
t.Error("expected error for invalid sync mode")
}
t.Logf("✓ Invalid mode correctly rejected")
// Test 6: Invalid mode in DB defaults to git-portable
if err := testStore.SetConfig(ctx, SyncModeConfigKey, "invalid"); err != nil {
t.Fatalf("failed to set invalid config: %v", err)
}
mode = GetSyncMode(ctx, testStore)
if mode != SyncModeGitPortable {
t.Errorf("invalid mode should default to %q, got %q", SyncModeGitPortable, mode)
}
t.Logf("✓ Invalid mode in DB defaults to git-portable")
}
// TestShouldExportJSONL verifies JSONL export behavior per mode.
func TestShouldExportJSONL(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("mkdir failed: %v", err)
}
dbPath := filepath.Join(beadsDir, "beads.db")
testStore, err := dolt.New(ctx, &dolt.Config{Path: dbPath})
if err != nil {
t.Fatalf("failed to create store: %v", err)
}
defer testStore.Close()
tests := []struct {
mode string
wantExport bool
}{
{SyncModeGitPortable, true},
{SyncModeRealtime, true},
{SyncModeDoltNative, false}, // dolt-native uses Dolt remotes, not JSONL
{SyncModeBeltAndSuspenders, true},
}
for _, tt := range tests {
t.Run(tt.mode, func(t *testing.T) {
if err := SetSyncMode(ctx, testStore, tt.mode); err != nil {
t.Fatalf("failed to set mode: %v", err)
}
got := ShouldExportJSONL(ctx, testStore)
if got != tt.wantExport {
t.Errorf("ShouldExportJSONL() = %v, want %v", got, tt.wantExport)
}
})
}
}
// TestShouldExportJSONL_UsesGetSyncMode verifies ShouldExportJSONL uses GetSyncMode
// (which checks config.yaml first, then DB). This ensures that sync.mode set in
// config.yaml is respected even when not propagated to the database — fixing the
// bug where dolt-native workspaces paid 10-25s JSONL export overhead (bd-6fiwk).
func TestShouldExportJSONL_UsesGetSyncMode(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("mkdir failed: %v", err)
}
dbPath := filepath.Join(beadsDir, "beads.db")
testStore, err := dolt.New(ctx, &dolt.Config{Path: dbPath})
if err != nil {
t.Fatalf("failed to create store: %v", err)
}
defer testStore.Close()
// Set dolt-native in database — ShouldExportJSONL must return false
if err := testStore.SetConfig(ctx, SyncModeConfigKey, SyncModeDoltNative); err != nil {
t.Fatalf("failed to set config: %v", err)
}
if ShouldExportJSONL(ctx, testStore) {
t.Error("ShouldExportJSONL() = true, want false for dolt-native in DB")
}
// Default (no config set) should return true
if err := testStore.SetConfig(ctx, SyncModeConfigKey, ""); err != nil {
t.Fatalf("failed to clear config: %v", err)
}
if !ShouldExportJSONL(ctx, testStore) {
t.Error("ShouldExportJSONL() = false, want true for default (no config)")
}
}
// TestShouldImportJSONL verifies JSONL import behavior per mode.
func TestShouldImportJSONL(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("mkdir failed: %v", err)
}
dbPath := filepath.Join(beadsDir, "beads.db")
testStore, err := dolt.New(ctx, &dolt.Config{Path: dbPath})
if err != nil {
t.Fatalf("failed to create store: %v", err)
}
defer testStore.Close()
tests := []struct {
mode string
wantImport bool
}{
{SyncModeGitPortable, true},
{SyncModeRealtime, true},
{SyncModeDoltNative, false},
{SyncModeBeltAndSuspenders, true},
}
for _, tt := range tests {
t.Run(tt.mode, func(t *testing.T) {
if err := SetSyncMode(ctx, testStore, tt.mode); err != nil {
t.Fatalf("failed to set mode: %v", err)
}
got := ShouldImportJSONL(ctx, testStore)
if got != tt.wantImport {
t.Errorf("ShouldImportJSONL() = %v, want %v", got, tt.wantImport)
}
})
}
}
// TestShouldUseDoltRemote verifies Dolt remote usage per mode.
func TestShouldUseDoltRemote(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("mkdir failed: %v", err)
}
dbPath := filepath.Join(beadsDir, "beads.db")
testStore, err := dolt.New(ctx, &dolt.Config{Path: dbPath})
if err != nil {
t.Fatalf("failed to create store: %v", err)
}
defer testStore.Close()
tests := []struct {
mode string
wantUse bool
}{
{SyncModeGitPortable, false},
{SyncModeRealtime, false},
{SyncModeDoltNative, true},
{SyncModeBeltAndSuspenders, true},
}
for _, tt := range tests {
t.Run(tt.mode, func(t *testing.T) {
if err := SetSyncMode(ctx, testStore, tt.mode); err != nil {
t.Fatalf("failed to set mode: %v", err)
}
got := ShouldUseDoltRemote(ctx, testStore)
if got != tt.wantUse {
t.Errorf("ShouldUseDoltRemote() = %v, want %v", got, tt.wantUse)
}
})
}
}
// TestSyncModeDescription verifies mode descriptions are meaningful.
func TestSyncModeDescription(t *testing.T) {
tests := []struct {
mode string
wantContain string
}{
{SyncModeGitPortable, "JSONL"},
{SyncModeRealtime, "every change"},
{SyncModeDoltNative, "export-only"},
{SyncModeBeltAndSuspenders, "Both"},
{"invalid", "unknown"},
}
for _, tt := range tests {
t.Run(tt.mode, func(t *testing.T) {
desc := SyncModeDescription(tt.mode)
if desc == "" {
t.Error("description should not be empty")
}
// Just verify descriptions are non-empty and distinct
t.Logf("%s: %s", tt.mode, desc)
})
}
}

View file

@ -1,856 +0,0 @@
//go:build cgo
package main
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/git"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/syncbranch"
"github.com/steveyegge/beads/internal/types"
)
// TestSyncBranchModeWithPullFirst verifies that sync-branch mode config storage
// and retrieval works correctly. The pull-first sync gates on this config.
// This addresses Steve's review concern about --sync-branch regression.
func TestSyncBranchModeWithPullFirst(t *testing.T) {
ctx := context.Background()
tmpDir, cleanup := setupGitRepo(t)
defer cleanup()
// Setup: Create beads directory with database
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("mkdir failed: %v", err)
}
// Create store and configure sync.branch
testDBPath := filepath.Join(beadsDir, "beads.db")
testStore, err := dolt.New(ctx, &dolt.Config{Path: testDBPath})
if err != nil {
t.Fatalf("failed to create store: %v", err)
}
defer testStore.Close()
// Set issue prefix (required)
if err := testStore.SetConfig(ctx, "issue_prefix", "test"); err != nil {
t.Fatalf("failed to set issue_prefix: %v", err)
}
// Configure sync.branch
if err := testStore.SetConfig(ctx, "sync.branch", "beads-metadata"); err != nil {
t.Fatalf("failed to set sync.branch: %v", err)
}
// Create the sync branch in git
if err := exec.Command("git", "branch", "beads-metadata").Run(); err != nil {
t.Fatalf("failed to create sync branch: %v", err)
}
// Create issues.jsonl with a test issue
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
issueContent := `{"id":"test-1","title":"Test Issue","status":"open","issue_type":"task","priority":2,"created_at":"2025-01-01T00:00:00Z","updated_at":"2025-01-01T00:00:00Z"}`
if err := os.WriteFile(jsonlPath, []byte(issueContent+"\n"), 0644); err != nil {
t.Fatalf("write JSONL failed: %v", err)
}
// Test 1: Verify sync.branch config is stored and retrievable
// This is what the pull-first sync checks at lines 181-189 in sync.go
syncBranch, err := testStore.GetConfig(ctx, "sync.branch")
if err != nil {
t.Fatalf("failed to get sync.branch config: %v", err)
}
if syncBranch != "beads-metadata" {
t.Errorf("sync.branch = %q, want %q", syncBranch, "beads-metadata")
}
t.Logf("✓ Sync-branch config correctly stored: %s", syncBranch)
// Test 2: Verify the git branch exists
checkCmd := exec.Command("git", "show-ref", "--verify", "--quiet", "refs/heads/beads-metadata")
if err := checkCmd.Run(); err != nil {
t.Error("expected beads-metadata branch to exist")
}
t.Log("✓ Git sync branch exists")
// Test 3: Verify the DB config key can be read directly by syncbranch package
// Note: syncbranch.Get() also checks config.yaml and env var, which may override
// the DB config in the beads repo test environment. We verify DB storage works.
dbValue, err := testStore.GetConfig(ctx, syncbranch.ConfigKey)
if err != nil {
t.Fatalf("failed to read %s from store: %v", syncbranch.ConfigKey, err)
}
if dbValue != "beads-metadata" {
t.Errorf("store.GetConfig(%s) = %q, want %q", syncbranch.ConfigKey, dbValue, "beads-metadata")
}
t.Logf("✓ sync.branch config key correctly stored: %s", dbValue)
// Key assertion: The sync-branch detection mechanism works
// When sync.branch is configured, doPullFirstSync gates on it (sync.go:181-189)
// and the daemon handles sync-branch commits (daemon_sync_branch.go)
}
// TestExternalBeadsDirWithPullFirst verifies that external BEADS_DIR mode
// is correctly detected and the commit/pull functions work.
// This addresses Steve's review concern about external beads dir regression.
func TestExternalBeadsDirWithPullFirst(t *testing.T) {
ctx := context.Background()
// Setup: Create main project repo
mainDir, cleanupMain := setupGitRepo(t)
defer cleanupMain()
// Setup: Create separate external beads repo
// Resolve symlinks to avoid macOS /var -> /private/var issues
externalDir, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatalf("eval symlinks failed: %v", err)
}
// Initialize external repo
if err := exec.Command("git", "-C", externalDir, "init", "--initial-branch=main").Run(); err != nil {
t.Fatalf("git init (external) failed: %v", err)
}
_ = exec.Command("git", "-C", externalDir, "config", "user.email", "test@test.com").Run()
_ = exec.Command("git", "-C", externalDir, "config", "user.name", "Test User").Run()
// Create initial commit in external repo
if err := os.WriteFile(filepath.Join(externalDir, "README.md"), []byte("External beads repo"), 0644); err != nil {
t.Fatalf("write README failed: %v", err)
}
_ = exec.Command("git", "-C", externalDir, "add", ".").Run()
if err := exec.Command("git", "-C", externalDir, "commit", "-m", "initial").Run(); err != nil {
t.Fatalf("external initial commit failed: %v", err)
}
// Create .beads directory in external repo
externalBeadsDir := filepath.Join(externalDir, ".beads")
if err := os.MkdirAll(externalBeadsDir, 0755); err != nil {
t.Fatalf("mkdir external beads failed: %v", err)
}
// Create issues.jsonl in external beads
jsonlPath := filepath.Join(externalBeadsDir, "issues.jsonl")
issueContent := `{"id":"ext-1","title":"External Issue","status":"open","issue_type":"task","priority":2,"created_at":"2025-01-01T00:00:00Z","updated_at":"2025-01-01T00:00:00Z"}`
if err := os.WriteFile(jsonlPath, []byte(issueContent+"\n"), 0644); err != nil {
t.Fatalf("write external JSONL failed: %v", err)
}
// Commit initial beads files
_ = exec.Command("git", "-C", externalDir, "add", ".beads").Run()
_ = exec.Command("git", "-C", externalDir, "commit", "-m", "add beads").Run()
// Change back to main repo (simulating user's project)
if err := os.Chdir(mainDir); err != nil {
t.Fatalf("chdir to main failed: %v", err)
}
// Test 1: isExternalBeadsDir should detect external repo
if !isExternalBeadsDir(ctx, externalBeadsDir) {
t.Error("isExternalBeadsDir should return true for external beads dir")
}
t.Log("✓ External beads dir correctly detected")
// Test 2: Verify the external beads functions exist and are callable
// The actual commit test requires more complex setup due to path resolution
// The key verification is that detection works (Test 1)
// and the functions are present (verified by compilation)
// Test 3: pullFromExternalBeadsRepo should not error (no remote)
// This tests the function handles no-remote gracefully
err = pullFromExternalBeadsRepo(ctx, externalBeadsDir)
if err != nil {
t.Errorf("pullFromExternalBeadsRepo should handle no-remote: %v", err)
}
t.Log("✓ Pull from external beads repo handled no-remote correctly")
// Test 4: Verify getRepoRootFromPath works for external dir
repoRoot, err := getRepoRootFromPath(ctx, externalBeadsDir)
if err != nil {
t.Fatalf("getRepoRootFromPath failed: %v", err)
}
// Should return the external repo root
resolvedExternal, _ := filepath.EvalSymlinks(externalDir)
if repoRoot != resolvedExternal {
t.Errorf("getRepoRootFromPath = %q, want %q", repoRoot, resolvedExternal)
}
t.Logf("✓ getRepoRootFromPath correctly identifies external repo: %s", repoRoot)
}
// TestMergeIssuesWithBaseState verifies the 3-way merge algorithm
// that underpins pull-first sync works correctly with base state.
// This is the core algorithm that prevents data loss (#911).
func TestMergeIssuesWithBaseState(t *testing.T) {
t.Parallel()
baseTime := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
localTime := time.Date(2025, 1, 2, 0, 0, 0, 0, time.UTC)
remoteTime := time.Date(2025, 1, 3, 0, 0, 0, 0, time.UTC)
tests := []struct {
name string
base []*beads.Issue
local []*beads.Issue
remote []*beads.Issue
wantCount int
wantConflicts int
wantStrategy map[string]string
wantTitles map[string]string // id -> expected title
}{
{
name: "only remote changed",
base: []*beads.Issue{
{ID: "bd-1", Title: "Original", UpdatedAt: baseTime},
},
local: []*beads.Issue{
{ID: "bd-1", Title: "Original", UpdatedAt: baseTime},
},
remote: []*beads.Issue{
{ID: "bd-1", Title: "Remote Edit", UpdatedAt: remoteTime},
},
wantCount: 1,
wantConflicts: 0,
wantStrategy: map[string]string{"bd-1": StrategyRemote},
wantTitles: map[string]string{"bd-1": "Remote Edit"},
},
{
name: "only local changed",
base: []*beads.Issue{
{ID: "bd-1", Title: "Original", UpdatedAt: baseTime},
},
local: []*beads.Issue{
{ID: "bd-1", Title: "Local Edit", UpdatedAt: localTime},
},
remote: []*beads.Issue{
{ID: "bd-1", Title: "Original", UpdatedAt: baseTime},
},
wantCount: 1,
wantConflicts: 0,
wantStrategy: map[string]string{"bd-1": StrategyLocal},
wantTitles: map[string]string{"bd-1": "Local Edit"},
},
{
name: "true conflict - remote wins LWW",
base: []*beads.Issue{
{ID: "bd-1", Title: "Original", UpdatedAt: baseTime},
},
local: []*beads.Issue{
{ID: "bd-1", Title: "Local Edit", UpdatedAt: localTime},
},
remote: []*beads.Issue{
{ID: "bd-1", Title: "Remote Edit", UpdatedAt: remoteTime},
},
wantCount: 1,
wantConflicts: 1,
wantStrategy: map[string]string{"bd-1": StrategyMerged},
wantTitles: map[string]string{"bd-1": "Remote Edit"}, // Remote wins (later timestamp)
},
{
name: "new issue from remote",
base: []*beads.Issue{},
local: []*beads.Issue{},
remote: []*beads.Issue{
{ID: "bd-1", Title: "New Remote Issue", UpdatedAt: remoteTime},
},
wantCount: 1,
wantConflicts: 0,
wantStrategy: map[string]string{"bd-1": StrategyRemote},
wantTitles: map[string]string{"bd-1": "New Remote Issue"},
},
{
name: "new issue from local",
base: []*beads.Issue{},
local: []*beads.Issue{
{ID: "bd-1", Title: "New Local Issue", UpdatedAt: localTime},
},
remote: []*beads.Issue{},
wantCount: 1,
wantConflicts: 0,
wantStrategy: map[string]string{"bd-1": StrategyLocal},
wantTitles: map[string]string{"bd-1": "New Local Issue"},
},
{
name: "both made identical change",
base: []*beads.Issue{
{ID: "bd-1", Title: "Original", UpdatedAt: baseTime},
},
local: []*beads.Issue{
{ID: "bd-1", Title: "Same Edit", UpdatedAt: localTime},
},
remote: []*beads.Issue{
{ID: "bd-1", Title: "Same Edit", UpdatedAt: localTime},
},
wantCount: 1,
wantConflicts: 0,
wantStrategy: map[string]string{"bd-1": StrategySame},
wantTitles: map[string]string{"bd-1": "Same Edit"},
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
result := MergeIssues(tt.base, tt.local, tt.remote)
if len(result.Merged) != tt.wantCount {
t.Errorf("got %d merged issues, want %d", len(result.Merged), tt.wantCount)
}
if result.Conflicts != tt.wantConflicts {
t.Errorf("got %d conflicts, want %d", result.Conflicts, tt.wantConflicts)
}
for id, wantStrategy := range tt.wantStrategy {
if result.Strategy[id] != wantStrategy {
t.Errorf("strategy[%s] = %q, want %q", id, result.Strategy[id], wantStrategy)
}
}
for _, issue := range result.Merged {
if wantTitle, ok := tt.wantTitles[issue.ID]; ok {
if issue.Title != wantTitle {
t.Errorf("title[%s] = %q, want %q", issue.ID, issue.Title, wantTitle)
}
}
}
})
}
}
// TestUpgradeFromOldSync verifies that existing projects safely upgrade to pull-first.
// When sync_base.jsonl doesn't exist (first sync after upgrade), the merge should:
// 1. Keep issues that only exist locally
// 2. Keep issues that only exist remotely
// 3. Merge issues that exist in both (using LWW for scalars, union for sets)
// This is critical for production safety.
func TestUpgradeFromOldSync(t *testing.T) {
t.Parallel()
localTime := time.Date(2025, 1, 2, 0, 0, 0, 0, time.UTC)
remoteTime := time.Date(2025, 1, 3, 0, 0, 0, 0, time.UTC)
// Simulate upgrade scenario: base=nil (no sync_base.jsonl)
// Local has 2 issues, remote has 2 issues (1 overlap)
local := []*beads.Issue{
{ID: "bd-1", Title: "Shared Issue Local", Labels: []string{"local-label"}, UpdatedAt: localTime},
{ID: "bd-2", Title: "Local Only Issue", UpdatedAt: localTime},
}
remote := []*beads.Issue{
{ID: "bd-1", Title: "Shared Issue Remote", Labels: []string{"remote-label"}, UpdatedAt: remoteTime},
{ID: "bd-3", Title: "Remote Only Issue", UpdatedAt: remoteTime},
}
// Key: base is nil (simulating upgrade from old sync)
result := MergeIssues(nil, local, remote)
// Should have 3 issues total
if len(result.Merged) != 3 {
t.Fatalf("expected 3 merged issues, got %d", len(result.Merged))
}
// Build map for easier assertions
byID := make(map[string]*beads.Issue)
for _, issue := range result.Merged {
byID[issue.ID] = issue
}
// bd-1: Shared issue should be merged (remote wins LWW, labels union)
if issue, ok := byID["bd-1"]; ok {
// Remote wins LWW (later timestamp)
if issue.Title != "Shared Issue Remote" {
t.Errorf("bd-1 title = %q, want 'Shared Issue Remote' (LWW)", issue.Title)
}
// Labels should be union
if len(issue.Labels) != 2 {
t.Errorf("bd-1 labels = %v, want union of local and remote labels", issue.Labels)
}
if result.Strategy["bd-1"] != StrategyMerged {
t.Errorf("bd-1 strategy = %q, want %q", result.Strategy["bd-1"], StrategyMerged)
}
} else {
t.Error("bd-1 should exist in merged result")
}
// bd-2: Local only should be kept
if issue, ok := byID["bd-2"]; ok {
if issue.Title != "Local Only Issue" {
t.Errorf("bd-2 title = %q, want 'Local Only Issue'", issue.Title)
}
if result.Strategy["bd-2"] != StrategyLocal {
t.Errorf("bd-2 strategy = %q, want %q", result.Strategy["bd-2"], StrategyLocal)
}
} else {
t.Error("bd-2 should exist in merged result (local only)")
}
// bd-3: Remote only should be kept
if issue, ok := byID["bd-3"]; ok {
if issue.Title != "Remote Only Issue" {
t.Errorf("bd-3 title = %q, want 'Remote Only Issue'", issue.Title)
}
if result.Strategy["bd-3"] != StrategyRemote {
t.Errorf("bd-3 strategy = %q, want %q", result.Strategy["bd-3"], StrategyRemote)
}
} else {
t.Error("bd-3 should exist in merged result (remote only)")
}
t.Log("✓ Upgrade from old sync safely merges all issues")
}
// TestLabelUnionMerge verifies that labels use union merge (no data loss).
// This is the field-level resolution Steve asked about.
func TestLabelUnionMerge(t *testing.T) {
t.Parallel()
baseTime := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
localTime := time.Date(2025, 1, 2, 0, 0, 0, 0, time.UTC)
remoteTime := time.Date(2025, 1, 3, 0, 0, 0, 0, time.UTC)
base := []*beads.Issue{
{ID: "bd-1", Title: "Issue", Labels: []string{"bug"}, UpdatedAt: baseTime},
}
local := []*beads.Issue{
{ID: "bd-1", Title: "Issue", Labels: []string{"bug", "local-label"}, UpdatedAt: localTime},
}
remote := []*beads.Issue{
{ID: "bd-1", Title: "Issue", Labels: []string{"bug", "remote-label"}, UpdatedAt: remoteTime},
}
result := MergeIssues(base, local, remote)
if len(result.Merged) != 1 {
t.Fatalf("expected 1 merged issue, got %d", len(result.Merged))
}
// Labels should be union of both: bug, local-label, remote-label
labels := result.Merged[0].Labels
expectedLabels := map[string]bool{"bug": true, "local-label": true, "remote-label": true}
if len(labels) != 3 {
t.Errorf("expected 3 labels, got %d: %v", len(labels), labels)
}
for _, label := range labels {
if !expectedLabels[label] {
t.Errorf("unexpected label: %s", label)
}
}
t.Logf("✓ Labels correctly union-merged: %v", labels)
}
// setupBareRemoteWithClones creates a bare repo (simulating GitHub) and two clones
// for multi-machine E2E testing. Each clone has its own .beads directory for isolation.
//
// Returns:
// - remoteDir: path to bare repo (the "remote")
// - machineA: path to first clone
// - machineB: path to second clone
// - cleanup: function to call in defer
func setupBareRemoteWithClones(t *testing.T) (remoteDir, machineA, machineB string, cleanup func()) {
t.Helper()
// Create bare repo (acts as "GitHub")
remoteDir = t.TempDir()
// Resolve symlinks to avoid macOS /var -> /private/var issues
remoteDir, _ = filepath.EvalSymlinks(remoteDir)
cmd := exec.Command("git", "init", "--bare", "-b", "main")
cmd.Dir = remoteDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to init bare repo: %v", err)
}
// Clone for Machine A
machineA = t.TempDir()
machineA, _ = filepath.EvalSymlinks(machineA)
if err := exec.Command("git", "clone", remoteDir, machineA).Run(); err != nil {
t.Fatalf("failed to clone for machineA: %v", err)
}
// Configure git user in Machine A
_ = exec.Command("git", "-C", machineA, "config", "user.email", "machineA@test.com").Run()
_ = exec.Command("git", "-C", machineA, "config", "user.name", "Machine A").Run()
// Clone for Machine B
machineB = t.TempDir()
machineB, _ = filepath.EvalSymlinks(machineB)
if err := exec.Command("git", "clone", remoteDir, machineB).Run(); err != nil {
t.Fatalf("failed to clone for machineB: %v", err)
}
// Configure git user in Machine B
_ = exec.Command("git", "-C", machineB, "config", "user.email", "machineB@test.com").Run()
_ = exec.Command("git", "-C", machineB, "config", "user.name", "Machine B").Run()
// Initial commit from Machine A (bare repos need at least one commit)
readmePath := filepath.Join(machineA, "README.md")
if err := os.WriteFile(readmePath, []byte("# Test Repo\n"), 0644); err != nil {
t.Fatalf("failed to write README: %v", err)
}
_ = exec.Command("git", "-C", machineA, "add", ".").Run()
if err := exec.Command("git", "-C", machineA, "commit", "-m", "initial").Run(); err != nil {
t.Fatalf("failed to create initial commit: %v", err)
}
if err := exec.Command("git", "-C", machineA, "push", "-u", "origin", "main").Run(); err != nil {
t.Fatalf("failed to push initial commit: %v", err)
}
// Machine B fetches and checks out main
_ = exec.Command("git", "-C", machineB, "fetch", "origin").Run()
_ = exec.Command("git", "-C", machineB, "checkout", "main").Run()
cleanup = func() {
git.ResetCaches() // Prevent cache pollution between tests
}
return remoteDir, machineA, machineB, cleanup
}
// withBeadsDir runs a function with BEADS_DIR set to the specified directory's .beads subdirectory.
// This provides database isolation for multi-machine tests.
func withBeadsDir(t *testing.T, dir string, fn func()) {
t.Helper()
origBeadsDir := os.Getenv("BEADS_DIR")
beadsDir := filepath.Join(dir, ".beads")
// Create .beads directory if it doesn't exist
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("failed to create .beads dir: %v", err)
}
os.Setenv("BEADS_DIR", beadsDir)
defer func() {
if origBeadsDir != "" {
os.Setenv("BEADS_DIR", origBeadsDir)
} else {
os.Unsetenv("BEADS_DIR")
}
}()
fn()
}
// TestSyncBranchE2E tests the full sync-branch flow with concurrent changes from
// two machines using a real bare repo. This is an end-to-end regression test for PR#918.
//
// Flow:
// 1. Machine A creates bd-1, commits to sync branch, pushes to bare remote
// 2. Machine B creates bd-2, commits to sync branch, pushes to bare remote
// 3. Machine A pulls from sync branch - should merge both issues
// 4. Verify both issues present after merge
func TestSyncBranchE2E(t *testing.T) {
ctx := context.Background()
// Setup: Create bare remote with two clones
_, machineA, machineB, cleanup := setupBareRemoteWithClones(t)
defer cleanup()
syncBranch := "beads-sync"
// Machine A: Create .beads directory and bd-1
beadsDirA := filepath.Join(machineA, ".beads")
if err := os.MkdirAll(beadsDirA, 0755); err != nil {
t.Fatalf("failed to create .beads dir for A: %v", err)
}
jsonlPathA := filepath.Join(beadsDirA, "issues.jsonl")
issue1 := `{"id":"bd-1","title":"Issue from Machine A","status":"open","issue_type":"task","priority":2,"created_at":"2025-01-01T00:00:00Z","updated_at":"2025-01-01T00:00:00Z"}`
if err := os.WriteFile(jsonlPathA, []byte(issue1+"\n"), 0644); err != nil {
t.Fatalf("write JSONL failed for A: %v", err)
}
// Machine A: Commit to sync branch using the worktree-based API (push=true)
withBeadsDir(t, machineA, func() {
commitResult, err := syncbranch.CommitToSyncBranch(ctx, machineA, syncBranch, jsonlPathA, true)
if err != nil {
t.Fatalf("CommitToSyncBranch failed for A: %v", err)
}
if !commitResult.Committed {
t.Fatal("expected commit to succeed for Machine A's issue")
}
t.Log("Machine A committed and pushed bd-1 to sync branch")
})
// Machine B: Create .beads directory and bd-2
beadsDirB := filepath.Join(machineB, ".beads")
if err := os.MkdirAll(beadsDirB, 0755); err != nil {
t.Fatalf("failed to create .beads dir for B: %v", err)
}
jsonlPathB := filepath.Join(beadsDirB, "issues.jsonl")
issue2 := `{"id":"bd-2","title":"Issue from Machine B","status":"open","issue_type":"task","priority":2,"created_at":"2025-01-02T00:00:00Z","updated_at":"2025-01-02T00:00:00Z"}`
if err := os.WriteFile(jsonlPathB, []byte(issue2+"\n"), 0644); err != nil {
t.Fatalf("write JSONL failed for B: %v", err)
}
// Machine B: Pull first to get A's changes, then commit and push
withBeadsDir(t, machineB, func() {
// Pull from remote first (gets Machine A's bd-1)
pullResult, err := syncbranch.PullFromSyncBranch(ctx, machineB, syncBranch, jsonlPathB, false)
if err != nil {
t.Logf("Initial pull for B returned error (may be expected): %v", err)
}
if pullResult != nil && pullResult.Pulled {
t.Log("Machine B pulled existing sync branch content")
}
// Re-read and append bd-2 to maintain bd-1 from pull
existingContent, _ := os.ReadFile(jsonlPathB)
if !strings.Contains(string(existingContent), "bd-2") {
// Append bd-2 if not already present
if len(existingContent) > 0 && !strings.HasSuffix(string(existingContent), "\n") {
existingContent = append(existingContent, '\n')
}
newContent := string(existingContent) + issue2 + "\n"
if err := os.WriteFile(jsonlPathB, []byte(newContent), 0644); err != nil {
t.Fatalf("failed to append bd-2: %v", err)
}
}
// Commit and push bd-2
commitResult, err := syncbranch.CommitToSyncBranch(ctx, machineB, syncBranch, jsonlPathB, true)
if err != nil {
t.Fatalf("CommitToSyncBranch failed for B: %v", err)
}
if !commitResult.Committed {
t.Log("Machine B had no new changes to commit (bd-2 may already be in sync)")
} else {
t.Log("Machine B committed and pushed bd-2 to sync branch")
}
})
// Machine A: Pull from sync branch - should merge both issues
withBeadsDir(t, machineA, func() {
pullResult, err := syncbranch.PullFromSyncBranch(ctx, machineA, syncBranch, jsonlPathA, false)
if err != nil {
t.Logf("PullFromSyncBranch for A returned error (may be expected): %v", err)
}
if pullResult != nil {
t.Logf("Pull result for A: Pulled=%v, Merged=%v, FastForwarded=%v",
pullResult.Pulled, pullResult.Merged, pullResult.FastForwarded)
}
})
// Verify: Both issues should be present in Machine A's JSONL after merge
content, err := os.ReadFile(jsonlPathA)
if err != nil {
t.Fatalf("failed to read merged JSONL: %v", err)
}
contentStr := string(content)
hasIssue1 := strings.Contains(contentStr, "bd-1") || strings.Contains(contentStr, "Machine A")
hasIssue2 := strings.Contains(contentStr, "bd-2") || strings.Contains(contentStr, "Machine B")
if hasIssue1 {
t.Log("Issue bd-1 from Machine A preserved")
} else {
t.Error("FAIL: bd-1 from Machine A missing after merge")
}
if hasIssue2 {
t.Log("Issue bd-2 from Machine B merged")
} else {
t.Error("FAIL: bd-2 from Machine B missing after merge")
}
if hasIssue1 && hasIssue2 {
t.Log("Sync-branch E2E test PASSED: both issues present after merge")
}
}
// TestExportOnlySync tests the --no-pull mode (export-only sync).
// This mode skips pulling from remote and only exports local changes.
//
// Use case: "I just want to push my local changes, don't merge anything"
//
// Flow:
// 1. Create local issue in database
// 2. Run export-only sync (doExportOnlySync)
// 3. Verify issue is exported to JSONL
// 4. Verify changes are committed
func TestExportOnlySync(t *testing.T) {
ctx := context.Background()
tmpDir, cleanup := setupGitRepo(t)
defer cleanup()
beadsDir := filepath.Join(tmpDir, ".beads")
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
// Remove pre-existing issues.jsonl from setupGitRepo (we want a clean slate)
_ = os.Remove(jsonlPath)
// Setup: Create .beads directory
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("failed to create .beads dir: %v", err)
}
// Create a database with a test issue
dbPath := filepath.Join(beadsDir, "beads.db")
testStore, err := dolt.New(ctx, &dolt.Config{Path: dbPath})
if err != nil {
t.Fatalf("failed to create store: %v", err)
}
// Set issue prefix (required for export)
if err := testStore.SetConfig(ctx, "issue_prefix", "export-test"); err != nil {
t.Fatalf("failed to set issue_prefix: %v", err)
}
// Create a test issue in the database
testIssue := &types.Issue{
ID: "export-test-1",
Title: "Export Only Test Issue",
Status: "open",
IssueType: "task",
Priority: 2,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
if err := testStore.CreateIssue(ctx, testIssue, "test"); err != nil {
t.Fatalf("failed to create test issue: %v", err)
}
testStore.Close()
t.Log("✓ Created test issue in database")
// Initialize the global store for doExportOnlySync
// This simulates what `bd sync --no-pull` does
store, err = dolt.New(ctx, &dolt.Config{Path: dbPath})
if err != nil {
t.Fatalf("failed to open store: %v", err)
}
defer func() {
store.Close()
store = nil
}()
// Run export-only sync (--no-pull mode)
// noPush=true to avoid needing a real remote in tests
if err := doExportOnlySync(ctx, jsonlPath, true, "bd sync: export test"); err != nil {
t.Fatalf("doExportOnlySync failed: %v", err)
}
t.Log("✓ Export-only sync completed")
// Verify: JSONL file should exist with our issue
content, err := os.ReadFile(jsonlPath)
if err != nil {
t.Fatalf("failed to read JSONL: %v", err)
}
contentStr := string(content)
if !strings.Contains(contentStr, "export-test-1") {
t.Errorf("JSONL should contain issue ID 'export-test-1', got: %s", contentStr)
}
if !strings.Contains(contentStr, "Export Only Test Issue") {
t.Errorf("JSONL should contain issue title, got: %s", contentStr)
}
t.Log("✓ Issue correctly exported to JSONL")
// Verify: Changes should be committed
output, err := exec.Command("git", "log", "-1", "--pretty=format:%s").Output()
if err != nil {
t.Fatalf("git log failed: %v", err)
}
commitMsg := string(output)
if !strings.Contains(commitMsg, "bd sync") {
t.Errorf("expected commit message to contain 'bd sync', got: %s", commitMsg)
}
t.Log("✓ Changes committed with correct message")
// Verify: issues.jsonl should be tracked and committed (no modifications)
// Note: Database files (.db, .db-wal, .db-shm) and .sync.lock remain untracked
// as expected - only JSONL is committed to git
status, err := exec.Command("git", "status", "--porcelain", jsonlPath).Output()
if err != nil {
t.Fatalf("git status failed: %v", err)
}
if len(status) > 0 {
t.Errorf("expected issues.jsonl to be committed, got: %s", status)
}
t.Log("✓ issues.jsonl is committed after export-only sync")
}
// TestSync_FailsWhenOnSyncBranch verifies that bd sync fails gracefully
// when the current branch matches the configured sync branch.
// This is the runtime guard for GH#1166 - prevents bd sync from attempting
// to create a worktree for a branch that's already checked out.
//
// The issue: If sync.branch = "main" and user is on "main", bd sync would
// try to create a worktree for "main" which fails because it's already checked out.
// Worse, some code paths could commit all staged files instead of just .beads/.
func TestSync_FailsWhenOnSyncBranch(t *testing.T) {
ctx := context.Background()
tmpDir, cleanup := setupGitRepo(t)
defer cleanup()
// Get current branch name (should be "main" from setupGitRepo)
currentBranch, err := syncbranch.GetCurrentBranch(ctx)
if err != nil {
t.Fatalf("failed to get current branch: %v", err)
}
t.Logf("Current branch: %s", currentBranch)
// Test 1: IsSyncBranchSameAsCurrent returns true when branch matches
if !syncbranch.IsSyncBranchSameAsCurrent(ctx, currentBranch) {
t.Error("IsSyncBranchSameAsCurrent should return true when sync branch matches current branch")
}
t.Log("✓ IsSyncBranchSameAsCurrent correctly detects same-branch condition")
// Test 2: IsSyncBranchSameAsCurrent returns false for different branch
if syncbranch.IsSyncBranchSameAsCurrent(ctx, "beads-sync") {
t.Error("IsSyncBranchSameAsCurrent should return false for different branch name")
}
t.Log("✓ IsSyncBranchSameAsCurrent correctly allows different branch names")
// Test 3: Setup sync.branch config to match current branch (the problematic state)
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("failed to create .beads dir: %v", err)
}
dbPath := filepath.Join(beadsDir, "beads.db")
testStore, err := dolt.New(ctx, &dolt.Config{Path: dbPath})
if err != nil {
t.Fatalf("failed to create store: %v", err)
}
defer testStore.Close()
// Configure sync.branch to match current branch (this is the bug condition)
if err := testStore.SetConfig(ctx, "sync.branch", currentBranch); err != nil {
t.Fatalf("failed to set sync.branch: %v", err)
}
t.Logf("✓ Configured sync.branch = %s (matches current branch)", currentBranch)
// Verify the config is stored correctly
syncBranchValue, err := testStore.GetConfig(ctx, "sync.branch")
if err != nil {
t.Fatalf("failed to get sync.branch config: %v", err)
}
if syncBranchValue != currentBranch {
t.Errorf("sync.branch config = %q, want %q", syncBranchValue, currentBranch)
}
// Test 4: The runtime guard logic (same as in sync.go)
// This simulates what happens in the sync command
syncBranchName := syncBranchValue
hasSyncBranchConfig := syncBranchName != ""
if hasSyncBranchConfig {
if syncbranch.IsSyncBranchSameAsCurrent(ctx, syncBranchName) {
// This is the expected behavior - we caught the misconfiguration
t.Log("✓ Runtime guard correctly detected sync-branch = current-branch condition")
} else {
t.Error("FAIL: Runtime guard did not detect sync-branch = current-branch condition")
}
} else {
t.Error("FAIL: sync.branch config should be set")
}
t.Log("✓ TestSync_FailsWhenOnSyncBranch PASSED")
}

View file

@ -1,178 +0,0 @@
package main
import (
"encoding/json"
"os"
"path/filepath"
"sync"
"time"
)
// SyncState tracks sync health for backoff and user hints.
// Stored in .beads/sync-state.json (gitignored, local-only).
type SyncState struct {
LastFailure time.Time `json:"last_failure,omitempty"`
FailureCount int `json:"failure_count"`
BackoffUntil time.Time `json:"backoff_until,omitempty"`
NeedsManualSync bool `json:"needs_manual_sync"`
FailureReason string `json:"failure_reason,omitempty"`
}
const (
syncStateFile = "sync-state.json"
// Backoff schedule: 30s, 1m, 2m, 5m, 10m, 30m (cap)
maxBackoffDuration = 30 * time.Minute
// Clear stale state after 24 hours
staleStateThreshold = 24 * time.Hour
)
var (
// backoffSchedule defines the exponential backoff durations
backoffSchedule = []time.Duration{
30 * time.Second,
1 * time.Minute,
2 * time.Minute,
5 * time.Minute,
10 * time.Minute,
30 * time.Minute,
}
// syncStateMu protects concurrent access to sync state file
syncStateMu sync.Mutex
)
// LoadSyncState loads the sync state from .beads/sync-state.json.
// Returns empty state if file doesn't exist or is stale.
func LoadSyncState(beadsDir string) SyncState {
syncStateMu.Lock()
defer syncStateMu.Unlock()
return loadSyncStateUnlocked(beadsDir)
}
// loadSyncStateUnlocked loads sync state without acquiring lock.
// Caller must hold syncStateMu.
func loadSyncStateUnlocked(beadsDir string) SyncState {
statePath := filepath.Join(beadsDir, syncStateFile)
data, err := os.ReadFile(statePath) // #nosec G304 - path constructed from beadsDir
if err != nil {
return SyncState{}
}
var state SyncState
if err := json.Unmarshal(data, &state); err != nil {
return SyncState{}
}
// Clear stale state (older than 24h with no recent failures)
if !state.LastFailure.IsZero() && time.Since(state.LastFailure) > staleStateThreshold {
_ = os.Remove(statePath)
return SyncState{}
}
return state
}
// SaveSyncState saves the sync state to .beads/sync-state.json.
func SaveSyncState(beadsDir string, state SyncState) error {
syncStateMu.Lock()
defer syncStateMu.Unlock()
return saveSyncStateUnlocked(beadsDir, state)
}
// saveSyncStateUnlocked saves sync state without acquiring lock.
// Caller must hold syncStateMu.
func saveSyncStateUnlocked(beadsDir string, state SyncState) error {
statePath := filepath.Join(beadsDir, syncStateFile)
// If state is empty/reset, remove the file
if state.FailureCount == 0 && !state.NeedsManualSync {
_ = os.Remove(statePath)
return nil
}
data, err := json.MarshalIndent(state, "", " ")
if err != nil {
return err
}
return os.WriteFile(statePath, data, 0600)
}
// ClearSyncState removes the sync state file.
func ClearSyncState(beadsDir string) error {
syncStateMu.Lock()
defer syncStateMu.Unlock()
statePath := filepath.Join(beadsDir, syncStateFile)
err := os.Remove(statePath)
if os.IsNotExist(err) {
return nil
}
return err
}
// RecordSyncFailure updates the sync state after a failure.
// Returns the duration until next retry.
func RecordSyncFailure(beadsDir string, reason string) time.Duration {
syncStateMu.Lock()
defer syncStateMu.Unlock()
state := loadSyncStateUnlocked(beadsDir)
state.LastFailure = time.Now()
state.FailureCount++
state.FailureReason = reason
// Calculate backoff duration
backoffIndex := state.FailureCount - 1
if backoffIndex >= len(backoffSchedule) {
backoffIndex = len(backoffSchedule) - 1
}
backoff := backoffSchedule[backoffIndex]
state.BackoffUntil = time.Now().Add(backoff)
// Mark as needing manual sync after 3 failures (likely a conflict)
if state.FailureCount >= 3 {
state.NeedsManualSync = true
}
_ = saveSyncStateUnlocked(beadsDir, state) // Best effort: state persistence is advisory for backoff logic
return backoff
}
// RecordSyncSuccess clears the sync state after a successful sync.
func RecordSyncSuccess(beadsDir string) {
_ = ClearSyncState(beadsDir) // Best effort: stale state is harmless
}
// ShouldSkipSync returns true if we're still in the backoff period.
func ShouldSkipSync(beadsDir string) bool {
state := LoadSyncState(beadsDir)
if state.BackoffUntil.IsZero() {
return false
}
return time.Now().Before(state.BackoffUntil)
}
// ResetBackoffOnDaemonStart resets backoff counters when daemon starts,
// but preserves NeedsManualSync flag so hints still show.
func ResetBackoffOnDaemonStart(beadsDir string) {
syncStateMu.Lock()
defer syncStateMu.Unlock()
state := loadSyncStateUnlocked(beadsDir)
if state.FailureCount == 0 && !state.NeedsManualSync {
return
}
needsManual := state.NeedsManualSync
reason := state.FailureReason
state = SyncState{
NeedsManualSync: needsManual,
FailureReason: reason,
}
_ = saveSyncStateUnlocked(beadsDir, state)
}

View file

@ -1,143 +0,0 @@
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/syncbranch"
)
// showSyncStateStatus shows the current sync state per the spec.
// Output format:
//
// Sync mode: git-portable
// Last export: 2026-01-16 10:30:00 (commit abc123)
// Pending changes: 3 issues modified since last export
// Import branch: none
// Conflicts: none
func showSyncStateStatus(ctx context.Context, jsonlPath string) error {
if err := ensureStoreActive(); err != nil {
return fmt.Errorf("failed to initialize store: %w", err)
}
beadsDir := filepath.Dir(jsonlPath)
// Sync mode (from config)
syncCfg := config.GetSyncConfig()
fmt.Printf("Sync mode: %s (%s)\n", syncCfg.Mode, SyncModeDescription(string(syncCfg.Mode)))
fmt.Printf(" Export on: %s, Import on: %s\n", syncCfg.ExportOn, syncCfg.ImportOn)
// Conflict strategy
conflictCfg := config.GetConflictConfig()
fmt.Printf("Conflict strategy: %s\n", conflictCfg.Strategy)
// Federation config (if set)
fedCfg := config.GetFederationConfig()
if fedCfg.Remote != "" {
fmt.Printf("Federation remote: %s\n", fedCfg.Remote)
if fedCfg.Sovereignty != "" {
fmt.Printf(" Sovereignty: %s\n", fedCfg.Sovereignty)
}
}
// Last export time
lastExport, err := store.GetMetadata(ctx, "last_import_time")
if err != nil || lastExport == "" {
fmt.Println("Last export: never")
} else {
// Try to parse and format nicely
t, err := time.Parse(time.RFC3339Nano, lastExport)
if err != nil {
fmt.Printf("Last export: %s\n", lastExport)
} else {
// Try to get the last commit hash for the JSONL file
commitHash := getLastJSONLCommitHash(ctx, jsonlPath)
if commitHash != "" {
fmt.Printf("Last export: %s (commit %s)\n", t.Format("2006-01-02 15:04:05"), commitHash[:7])
} else {
fmt.Printf("Last export: %s\n", t.Format("2006-01-02 15:04:05"))
}
}
}
// Dirty tracking removed (woho.4) — pending changes not tracked
fmt.Println("Pending changes: not tracked (dirty tracking removed)")
// Import branch (sync branch status)
syncBranch, _ := syncbranch.Get(ctx, store)
if syncBranch == "" {
fmt.Println("Import branch: none")
} else {
fmt.Printf("Import branch: %s\n", syncBranch)
}
// Conflicts - check for sync conflict state file
syncConflictPath := filepath.Join(beadsDir, "sync_conflicts.json")
if _, err := os.Stat(syncConflictPath); err == nil {
conflictState, err := LoadSyncConflictState(beadsDir)
if err != nil {
fmt.Println("Conflicts: unknown (error reading sync state)")
} else if len(conflictState.Conflicts) > 0 {
fmt.Printf("Conflicts: %d unresolved\n", len(conflictState.Conflicts))
for _, c := range conflictState.Conflicts {
fmt.Printf(" - %s: %s\n", c.IssueID, c.Reason)
}
} else {
fmt.Println("Conflicts: none")
}
} else {
fmt.Println("Conflicts: none")
}
return nil
}
// getLastJSONLCommitHash returns the short commit hash of the last commit
// that touched the JSONL file, or empty string if unknown.
func getLastJSONLCommitHash(ctx context.Context, jsonlPath string) string {
rc, err := beads.GetRepoContext()
if err != nil {
return ""
}
cmd := rc.GitCmd(ctx, "log", "-1", "--format=%h", "--", jsonlPath)
output, err := cmd.Output()
if err != nil {
return ""
}
return strings.TrimSpace(string(output))
}
// staleSyncLockAge is the maximum age of a sync lock file before it's considered stale.
// Sync operations should complete well within this window, even for large repos.
const staleSyncLockAge = 1 * time.Hour
// cleanStaleSyncLock checks if the sync lock file is stale and removes it.
// Returns true if a stale lock was cleaned up.
// On Unix, flock is automatically released when a process exits, so this is a safety
// net for edge cases (NFS mounts, hung processes, container restarts).
func cleanStaleSyncLock(lockPath string) bool {
info, err := os.Stat(lockPath)
if err != nil {
return false
}
age := time.Since(info.ModTime())
if age <= staleSyncLockAge {
return false
}
fmt.Fprintf(os.Stderr, "Warning: removing stale sync lock (age: %s)\n", age.Round(time.Second))
if err := os.Remove(lockPath); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to remove stale sync lock: %v\n", err)
return false
}
return true
}

View file

@ -1,928 +0,0 @@
//go:build cgo
package main
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/gofrs/flock"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/syncbranch"
"github.com/steveyegge/beads/internal/types"
)
func TestIsGitRepo_InGitRepo(t *testing.T) {
// This test assumes we're running in the beads git repo
if !isGitRepo() {
t.Skip("not in a git repository")
}
}
func TestIsGitRepo_NotInGitRepo(t *testing.T) {
tmpDir := t.TempDir()
t.Chdir(tmpDir)
if isGitRepo() {
t.Error("expected false when not in git repo")
}
}
func TestGitHasUpstream_NoUpstream(t *testing.T) {
_, cleanup := setupGitRepo(t)
defer cleanup()
// Should not have upstream
if gitHasUpstream() {
t.Error("expected false when no upstream configured")
}
}
func TestGitHasChanges_NoFile(t *testing.T) {
ctx := context.Background()
_, cleanup := setupGitRepo(t)
defer cleanup()
// Check - should have no changes (test.txt was committed by setupGitRepo)
hasChanges, err := gitHasChanges(ctx, "test.txt")
if err != nil {
t.Fatalf("gitHasChanges() error = %v", err)
}
if hasChanges {
t.Error("expected no changes for committed file")
}
}
func TestGitHasChanges_ModifiedFile(t *testing.T) {
ctx := context.Background()
tmpDir, cleanup := setupGitRepo(t)
defer cleanup()
// Modify the file
testFile := filepath.Join(tmpDir, "test.txt")
os.WriteFile(testFile, []byte("modified"), 0644)
// Check - should have changes
hasChanges, err := gitHasChanges(ctx, "test.txt")
if err != nil {
t.Fatalf("gitHasChanges() error = %v", err)
}
if !hasChanges {
t.Error("expected changes for modified file")
}
}
func TestGitHasUnmergedPaths_CleanRepo(t *testing.T) {
_, cleanup := setupGitRepo(t)
defer cleanup()
// Should not have unmerged paths
hasUnmerged, err := gitHasUnmergedPaths()
if err != nil {
t.Fatalf("gitHasUnmergedPaths() error = %v", err)
}
if hasUnmerged {
t.Error("expected no unmerged paths in clean repo")
}
}
func TestGitCommit_Success(t *testing.T) {
ctx := context.Background()
_, cleanup := setupGitRepo(t)
defer cleanup()
// Create a new file
testFile := "new.txt"
os.WriteFile(testFile, []byte("content"), 0644)
// Commit the file
err := gitCommit(ctx, testFile, "test commit")
if err != nil {
t.Fatalf("gitCommit() error = %v", err)
}
// Verify file is committed
hasChanges, err := gitHasChanges(ctx, testFile)
if err != nil {
t.Fatalf("gitHasChanges() error = %v", err)
}
if hasChanges {
t.Error("expected no changes after commit")
}
}
func TestGitCommit_AutoMessage(t *testing.T) {
ctx := context.Background()
_, cleanup := setupGitRepo(t)
defer cleanup()
// Create a new file
testFile := "new.txt"
os.WriteFile(testFile, []byte("content"), 0644)
// Commit with auto-generated message (empty string)
err := gitCommit(ctx, testFile, "")
if err != nil {
t.Fatalf("gitCommit() error = %v", err)
}
// Verify it committed (message generation worked)
cmd := exec.Command("git", "log", "-1", "--pretty=%B")
output, _ := cmd.Output()
if len(output) == 0 {
t.Error("expected commit message to be generated")
}
}
func TestCountIssuesInJSONL_NonExistent(t *testing.T) {
t.Parallel()
count, err := countIssuesInJSONL("/nonexistent/path.jsonl")
if err == nil {
t.Error("expected error for nonexistent file")
}
if count != 0 {
t.Errorf("count = %d, want 0 on error", count)
}
}
func TestCountIssuesInJSONL_EmptyFile(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
jsonlPath := filepath.Join(tmpDir, "empty.jsonl")
os.WriteFile(jsonlPath, []byte(""), 0644)
count, err := countIssuesInJSONL(jsonlPath)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if count != 0 {
t.Errorf("count = %d, want 0", count)
}
}
func TestCountIssuesInJSONL_MultipleIssues(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
jsonlPath := filepath.Join(tmpDir, "issues.jsonl")
content := `{"id":"bd-1"}
{"id":"bd-2"}
{"id":"bd-3"}
`
os.WriteFile(jsonlPath, []byte(content), 0644)
count, err := countIssuesInJSONL(jsonlPath)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if count != 3 {
t.Errorf("count = %d, want 3", count)
}
}
func TestCountIssuesInJSONL_WithMalformedLines(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
jsonlPath := filepath.Join(tmpDir, "mixed.jsonl")
content := `{"id":"bd-1"}
not valid json
{"id":"bd-2"}
{"id":"bd-3"}
`
os.WriteFile(jsonlPath, []byte(content), 0644)
count, err := countIssuesInJSONL(jsonlPath)
// countIssuesInJSONL returns error on malformed JSON
if err == nil {
t.Error("expected error for malformed JSON")
}
// Should have counted the first valid issue before hitting error
if count != 1 {
t.Errorf("count = %d, want 1 (before malformed line)", count)
}
}
func TestGetCurrentBranch(t *testing.T) {
ctx := context.Background()
_, cleanup := setupGitRepo(t)
defer cleanup()
// Get current branch
branch, err := getCurrentBranch(ctx)
if err != nil {
t.Fatalf("getCurrentBranch() error = %v", err)
}
// Default branch is usually main or master
if branch != "main" && branch != "master" {
t.Logf("got branch %s (expected main or master, but this can vary)", branch)
}
}
func TestMergeSyncBranch_NoSyncBranchConfigured(t *testing.T) {
ctx := context.Background()
_, cleanup := setupGitRepo(t)
defer cleanup()
// Try to merge without sync.branch configured (or database)
err := mergeSyncBranch(ctx, false)
if err == nil {
t.Error("expected error when sync.branch not configured")
}
// Error could be about missing database or missing sync.branch config
if err != nil && !strings.Contains(err.Error(), "sync.branch") && !strings.Contains(err.Error(), "database") {
t.Errorf("expected error about sync.branch or database, got: %v", err)
}
}
func TestMergeSyncBranch_OnSyncBranch(t *testing.T) {
ctx := context.Background()
tmpDir, cleanup := setupGitRepo(t)
defer cleanup()
// Create sync branch
exec.Command("git", "checkout", "-b", "beads-metadata").Run()
// Initialize bd database and set sync.branch
beadsDir := filepath.Join(tmpDir, ".beads")
os.MkdirAll(beadsDir, 0755)
// This test will fail with store access issues, so we just verify the branch check
// The actual merge functionality is tested in integration tests
currentBranch, _ := getCurrentBranch(ctx)
if currentBranch != "beads-metadata" {
t.Skipf("test setup failed, current branch is %s", currentBranch)
}
}
func TestMergeSyncBranch_DirtyWorkingTree(t *testing.T) {
_, cleanup := setupGitRepo(t)
defer cleanup()
// Create uncommitted changes
os.WriteFile("test.txt", []byte("modified"), 0644)
// This test verifies the dirty working tree check would work
// (We can't test the full merge without database setup)
statusCmd := exec.Command("git", "status", "--porcelain")
output, _ := statusCmd.Output()
if len(output) == 0 {
t.Error("expected dirty working tree for test setup")
}
}
func TestGetSyncBranch_EnvOverridesDB(t *testing.T) {
ctx := context.Background()
// Save and restore global store state
oldStore := store
storeMutex.Lock()
oldStoreActive := storeActive
storeMutex.Unlock()
oldDBPath := dbPath
// Use a temp dir for Dolt store (Dolt doesn't support :memory:)
testStore, err := dolt.New(context.Background(), &dolt.Config{Path: filepath.Join(t.TempDir(), "test.db")})
if err != nil {
t.Fatalf("failed to create test store: %v", err)
}
defer testStore.Close()
// Seed DB config and globals
if err := testStore.SetConfig(ctx, "sync.branch", "db-branch"); err != nil {
t.Fatalf("failed to set sync.branch in db: %v", err)
}
storeMutex.Lock()
store = testStore
storeActive = true
storeMutex.Unlock()
dbPath = "" // avoid FindDatabasePath in ensureStoreActive
// Set environment override
if err := os.Setenv(syncbranch.EnvVar, "env-branch"); err != nil {
t.Fatalf("failed to set %s: %v", syncbranch.EnvVar, err)
}
defer os.Unsetenv(syncbranch.EnvVar)
// Ensure we restore globals after the test
defer func() {
storeMutex.Lock()
store = oldStore
storeActive = oldStoreActive
storeMutex.Unlock()
dbPath = oldDBPath
}()
branch, err := getSyncBranch(ctx)
if err != nil {
t.Fatalf("getSyncBranch() error = %v", err)
}
if branch != "env-branch" {
t.Errorf("getSyncBranch() = %q, want %q (env override)", branch, "env-branch")
}
}
func TestIsInRebase_NotInRebase(t *testing.T) {
_, cleanup := setupGitRepo(t)
defer cleanup()
// Should not be in rebase
if isInRebase() {
t.Error("expected false when not in rebase")
}
}
func TestIsInRebase_InRebase(t *testing.T) {
tmpDir, cleanup := setupGitRepo(t)
defer cleanup()
// Simulate rebase by creating rebase-merge directory
os.MkdirAll(filepath.Join(tmpDir, ".git", "rebase-merge"), 0755)
// Should detect rebase
if !isInRebase() {
t.Error("expected true when .git/rebase-merge exists")
}
}
func TestIsInRebase_InRebaseApply(t *testing.T) {
tmpDir, cleanup := setupMinimalGitRepo(t)
defer cleanup()
// Simulate non-interactive rebase by creating rebase-apply directory
os.MkdirAll(filepath.Join(tmpDir, ".git", "rebase-apply"), 0755)
// Should detect rebase
if !isInRebase() {
t.Error("expected true when .git/rebase-apply exists")
}
}
func TestHasJSONLConflict_NoConflict(t *testing.T) {
_, cleanup := setupGitRepo(t)
defer cleanup()
// Should not have JSONL conflict
if hasJSONLConflict() {
t.Error("expected false when no conflicts")
}
}
func TestHasJSONLConflict_OnlyJSONLConflict(t *testing.T) {
tmpDir, cleanup := setupGitRepoWithBranch(t, "main")
defer cleanup()
// Create initial commit with beads.jsonl
beadsDir := filepath.Join(tmpDir, ".beads")
os.MkdirAll(beadsDir, 0755)
os.WriteFile(filepath.Join(beadsDir, "beads.jsonl"), []byte(`{"id":"bd-1","title":"original"}`), 0644)
exec.Command("git", "add", ".").Run()
exec.Command("git", "commit", "-m", "add beads.jsonl").Run()
// Create a second commit on main (modify same issue)
os.WriteFile(filepath.Join(beadsDir, "beads.jsonl"), []byte(`{"id":"bd-1","title":"main-version"}`), 0644)
exec.Command("git", "add", ".").Run()
exec.Command("git", "commit", "-m", "main change").Run()
// Create a branch from the first commit
exec.Command("git", "checkout", "-b", "feature", "HEAD~1").Run()
os.WriteFile(filepath.Join(beadsDir, "beads.jsonl"), []byte(`{"id":"bd-1","title":"feature-version"}`), 0644)
exec.Command("git", "add", ".").Run()
exec.Command("git", "commit", "-m", "feature change").Run()
// Attempt rebase onto main (will conflict)
exec.Command("git", "rebase", "main").Run()
// Should detect JSONL conflict during rebase
if !hasJSONLConflict() {
t.Error("expected true when only beads.jsonl has conflict during rebase")
}
}
func TestHasJSONLConflict_MultipleConflicts(t *testing.T) {
tmpDir, cleanup := setupGitRepoWithBranch(t, "main")
defer cleanup()
// Create initial commit with beads.jsonl and another file
beadsDir := filepath.Join(tmpDir, ".beads")
os.MkdirAll(beadsDir, 0755)
os.WriteFile(filepath.Join(beadsDir, "beads.jsonl"), []byte(`{"id":"bd-1","title":"original"}`), 0644)
os.WriteFile("other.txt", []byte("line1\nline2\nline3"), 0644)
exec.Command("git", "add", ".").Run()
exec.Command("git", "commit", "-m", "add initial files").Run()
// Create a second commit on main (modify both files)
os.WriteFile(filepath.Join(beadsDir, "beads.jsonl"), []byte(`{"id":"bd-1","title":"main-version"}`), 0644)
os.WriteFile("other.txt", []byte("line1\nmain-version\nline3"), 0644)
exec.Command("git", "add", ".").Run()
exec.Command("git", "commit", "-m", "main change").Run()
// Create a branch from the first commit
exec.Command("git", "checkout", "-b", "feature", "HEAD~1").Run()
os.WriteFile(filepath.Join(beadsDir, "beads.jsonl"), []byte(`{"id":"bd-1","title":"feature-version"}`), 0644)
os.WriteFile("other.txt", []byte("line1\nfeature-version\nline3"), 0644)
exec.Command("git", "add", ".").Run()
exec.Command("git", "commit", "-m", "feature change").Run()
// Attempt rebase (will conflict on both files)
exec.Command("git", "rebase", "main").Run()
// Should NOT auto-resolve when multiple files conflict
if hasJSONLConflict() {
t.Error("expected false when multiple files have conflicts (should not auto-resolve)")
}
}
// Note: TestZFCSkipsExportAfterImport was removed as ZFC checks are no longer part of the
// legacy sync flow. Use --pull-first for structural staleness handling via 3-way merge.
// TestHashBasedStalenessDetection_bd_f2f tests the bd-f2f fix:
// When JSONL content differs from stored hash (e.g., remote changed status),
// hasJSONLChanged should detect the mismatch even if counts are equal.
func TestHashBasedStalenessDetection_bd_f2f(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
// Create test database
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("failed to create beads dir: %v", err)
}
testDBPath := filepath.Join(beadsDir, "beads.db")
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
// Create store
testStore, err := dolt.New(ctx, &dolt.Config{Path: testDBPath})
if err != nil {
t.Fatalf("failed to create store: %v", err)
}
defer testStore.Close()
// Initialize issue prefix (required for creating issues)
if err := testStore.SetConfig(ctx, "issue_prefix", "test"); err != nil {
t.Fatalf("failed to set issue prefix: %v", err)
}
// Create an issue in DB (simulating stale DB with old content)
issue := &types.Issue{
ID: "test-abc",
Title: "Test Issue",
Status: types.StatusOpen,
Priority: 1, // DB has priority 1
IssueType: types.TypeTask,
}
if err := testStore.CreateIssue(ctx, issue, "test"); err != nil {
t.Fatalf("failed to create issue: %v", err)
}
// Create JSONL with same issue but different priority (correct remote state)
// This simulates what happens after git pull brings in updated JSONL
// (e.g., remote changed priority from 1 to 0)
jsonlContent := `{"id":"test-abc","title":"Test Issue","status":"open","priority":0,"type":"task"}
`
if err := os.WriteFile(jsonlPath, []byte(jsonlContent), 0600); err != nil {
t.Fatalf("failed to write JSONL: %v", err)
}
// Store an OLD hash (different from current JSONL)
// This simulates the case where JSONL was updated externally (by git pull)
// but DB still has old hash from before the pull
oldHash := "0000000000000000000000000000000000000000000000000000000000000000"
if err := testStore.SetMetadata(ctx, "jsonl_content_hash", oldHash); err != nil {
t.Fatalf("failed to set old hash: %v", err)
}
// Verify counts are equal (1 issue in both)
dbCount, err := countDBIssuesFast(ctx, testStore)
if err != nil {
t.Fatalf("failed to count DB issues: %v", err)
}
jsonlCount, err := countIssuesInJSONL(jsonlPath)
if err != nil {
t.Fatalf("failed to count JSONL issues: %v", err)
}
if dbCount != jsonlCount {
t.Fatalf("setup error: expected equal counts, got DB=%d, JSONL=%d", dbCount, jsonlCount)
}
// The key test: hasJSONLChanged should detect the hash mismatch
// even though counts are equal
repoKey := getRepoKeyForPath(jsonlPath)
changed := hasJSONLChanged(ctx, testStore, jsonlPath, repoKey)
if !changed {
t.Error("bd-f2f: hasJSONLChanged should return true when JSONL hash differs from stored hash")
t.Log("This is the bug scenario: counts match (1 == 1) but content differs (priority=1 vs priority=0)")
t.Log("Without the bd-f2f fix, the stale DB would export old content and corrupt the remote")
} else {
t.Log("✓ bd-f2f fix verified: hash mismatch detected even with equal counts")
}
// Verify that after updating hash, hasJSONLChanged returns false
currentHash, err := computeJSONLHash(jsonlPath)
if err != nil {
t.Fatalf("failed to compute current hash: %v", err)
}
if err := testStore.SetMetadata(ctx, "jsonl_content_hash", currentHash); err != nil {
t.Fatalf("failed to set current hash: %v", err)
}
changedAfterUpdate := hasJSONLChanged(ctx, testStore, jsonlPath, repoKey)
if changedAfterUpdate {
t.Error("hasJSONLChanged should return false after hash is updated to match JSONL")
}
}
// TestResolveNoGitHistoryForFromMain tests that --from-main forces noGitHistory=true
// to prevent creating incorrect deletion records for locally-created beads.
// See: https://github.com/steveyegge/beads/issues/417
func TestResolveNoGitHistoryForFromMain(t *testing.T) {
t.Parallel()
tests := []struct {
name string
fromMain bool
noGitHistory bool
want bool
}{
{
name: "fromMain=true forces noGitHistory=true regardless of flag",
fromMain: true,
noGitHistory: false,
want: true,
},
{
name: "fromMain=true with noGitHistory=true stays true",
fromMain: true,
noGitHistory: true,
want: true,
},
{
name: "fromMain=false preserves noGitHistory=false",
fromMain: false,
noGitHistory: false,
want: false,
},
{
name: "fromMain=false preserves noGitHistory=true",
fromMain: false,
noGitHistory: true,
want: true,
},
}
for _, tt := range tests {
tt := tt // capture range variable
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got := resolveNoGitHistoryForFromMain(tt.fromMain, tt.noGitHistory)
if got != tt.want {
t.Errorf("resolveNoGitHistoryForFromMain(%v, %v) = %v, want %v",
tt.fromMain, tt.noGitHistory, got, tt.want)
}
})
}
}
// TestGetGitCommonDir tests that getGitCommonDir correctly returns the shared
// git directory for both regular repos and worktrees.
func TestGetGitCommonDir(t *testing.T) {
ctx := context.Background()
// Test 1: Regular repo
t.Run("regular repo", func(t *testing.T) {
repoDir, cleanup := setupGitRepo(t)
defer cleanup()
commonDir, err := getGitCommonDir(ctx, repoDir)
if err != nil {
t.Fatalf("getGitCommonDir failed: %v", err)
}
// For a regular repo, git-common-dir should point to .git
expectedGitDir := filepath.Join(repoDir, ".git")
// Resolve symlinks for comparison (macOS /var -> /private/var)
if resolved, err := filepath.EvalSymlinks(expectedGitDir); err == nil {
expectedGitDir = resolved
}
if commonDir != expectedGitDir {
t.Errorf("getGitCommonDir = %q, want %q", commonDir, expectedGitDir)
}
})
// Test 2: Worktree (non-bare) shares common dir with main repo
t.Run("worktree shares common dir with main repo", func(t *testing.T) {
repoDir, cleanup := setupGitRepo(t)
defer cleanup()
// Create a branch for the worktree
if err := exec.Command("git", "-C", repoDir, "branch", "test-branch").Run(); err != nil {
t.Fatalf("git branch failed: %v", err)
}
// Create worktree
worktreeDir := filepath.Join(t.TempDir(), "worktree")
if output, err := exec.Command("git", "-C", repoDir, "worktree", "add", worktreeDir, "test-branch").CombinedOutput(); err != nil {
t.Fatalf("git worktree add failed: %v\n%s", err, output)
}
// Get common dir for both
mainCommonDir, err := getGitCommonDir(ctx, repoDir)
if err != nil {
t.Fatalf("getGitCommonDir(main) failed: %v", err)
}
worktreeCommonDir, err := getGitCommonDir(ctx, worktreeDir)
if err != nil {
t.Fatalf("getGitCommonDir(worktree) failed: %v", err)
}
// Both should return the same common dir
if mainCommonDir != worktreeCommonDir {
t.Errorf("common dirs differ: main=%q, worktree=%q", mainCommonDir, worktreeCommonDir)
}
})
}
// TestIsExternalBeadsDir tests that isExternalBeadsDir correctly identifies
// when beads directory is in the same vs different git repo.
// GH#810: This was broken for bare repo worktrees.
func TestIsExternalBeadsDir(t *testing.T) {
ctx := context.Background()
// Test 1: Same directory - not external
t.Run("same directory is not external", func(t *testing.T) {
repoDir, cleanup := setupGitRepo(t)
defer cleanup()
beadsDir := filepath.Join(repoDir, ".beads")
if err := os.MkdirAll(beadsDir, 0750); err != nil {
t.Fatalf("mkdir failed: %v", err)
}
// Change to the repo directory (isExternalBeadsDir uses cwd)
origDir, _ := os.Getwd()
if err := os.Chdir(repoDir); err != nil {
t.Fatalf("chdir failed: %v", err)
}
defer func() { _ = os.Chdir(origDir) }()
if isExternalBeadsDir(ctx, beadsDir) {
t.Error("expected local beads dir to not be external")
}
})
// Test 2: Different repo - is external
t.Run("different repo is external", func(t *testing.T) {
repo1Dir, cleanup1 := setupGitRepo(t)
defer cleanup1()
repo2Dir, cleanup2 := setupGitRepo(t)
defer cleanup2()
beadsDir := filepath.Join(repo2Dir, ".beads")
if err := os.MkdirAll(beadsDir, 0750); err != nil {
t.Fatalf("mkdir failed: %v", err)
}
// Change to repo1
origDir, _ := os.Getwd()
if err := os.Chdir(repo1Dir); err != nil {
t.Fatalf("chdir failed: %v", err)
}
defer func() { _ = os.Chdir(origDir) }()
if !isExternalBeadsDir(ctx, beadsDir) {
t.Error("expected beads dir in different repo to be external")
}
})
// Test 3: Worktree with beads - not external (GH#810 fix)
t.Run("worktree beads dir is not external", func(t *testing.T) {
repoDir, cleanup := setupGitRepo(t)
defer cleanup()
// Create a branch for the worktree
if err := exec.Command("git", "-C", repoDir, "branch", "test-branch").Run(); err != nil {
t.Fatalf("git branch failed: %v", err)
}
// Create worktree
worktreeDir := filepath.Join(t.TempDir(), "worktree")
if output, err := exec.Command("git", "-C", repoDir, "worktree", "add", worktreeDir, "test-branch").CombinedOutput(); err != nil {
t.Fatalf("git worktree add failed: %v\n%s", err, output)
}
// Create beads dir in worktree
beadsDir := filepath.Join(worktreeDir, ".beads")
if err := os.MkdirAll(beadsDir, 0750); err != nil {
t.Fatalf("mkdir failed: %v", err)
}
// Change to worktree
origDir, _ := os.Getwd()
if err := os.Chdir(worktreeDir); err != nil {
t.Fatalf("chdir failed: %v", err)
}
defer func() { _ = os.Chdir(origDir) }()
// Beads dir in same worktree should NOT be external
if isExternalBeadsDir(ctx, beadsDir) {
t.Error("expected beads dir in same worktree to not be external")
}
})
}
// TestConcurrentEdit tests the pull-first sync flow with concurrent edits.
// This validates the 3-way merge logic for the pull-first sync refactor (#911).
//
// Scenario:
// - Base state exists (issue bd-1 at version 2025-01-01)
// - Local modifies issue (version 2025-01-02)
// - Remote also modifies issue (version 2025-01-03)
// - 3-way merge detects conflict and resolves using LWW (remote wins)
func TestConcurrentEdit(t *testing.T) {
ctx := context.Background()
tmpDir := newGitRepo(t)
t.Chdir(tmpDir)
// Setup: Create beads directory with JSONL (base state)
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("mkdir failed: %v", err)
}
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
// Base state: single issue at 2025-01-01
baseTime := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
baseIssue := `{"id":"bd-1","title":"Original Title","status":"open","issue_type":"task","priority":2,"created_at":"2025-01-01T00:00:00Z","updated_at":"2025-01-01T00:00:00Z"}`
if err := os.WriteFile(jsonlPath, []byte(baseIssue+"\n"), 0644); err != nil {
t.Fatalf("write JSONL failed: %v", err)
}
// Initial commit
_ = exec.Command("git", "add", ".").Run()
if err := exec.Command("git", "commit", "-m", "initial").Run(); err != nil {
t.Fatalf("initial commit failed: %v", err)
}
// Create database and import base state
testDBPath := filepath.Join(beadsDir, "beads.db")
testStore, err := dolt.New(ctx, &dolt.Config{Path: testDBPath})
if err != nil {
t.Fatalf("failed to create test store: %v", err)
}
defer testStore.Close()
// Set issue_prefix
if err := testStore.SetConfig(ctx, "issue_prefix", "bd"); err != nil {
t.Fatalf("failed to set issue_prefix: %v", err)
}
// Load base state for 3-way merge
baseIssues, err := loadIssuesFromJSONL(jsonlPath)
if err != nil {
t.Fatalf("loadIssuesFromJSONL (base) failed: %v", err)
}
// Create local issue (modified at 2025-01-02)
localTime := time.Date(2025, 1, 2, 0, 0, 0, 0, time.UTC)
localIssueObj := &types.Issue{
ID: "bd-1",
Title: "Local Edit",
Status: types.StatusOpen,
IssueType: types.TypeTask,
Priority: 2,
CreatedAt: baseTime,
UpdatedAt: localTime,
}
localIssues := []*types.Issue{localIssueObj}
// Simulate "remote" edit: change title in JSONL (modified at 2025-01-03 - later)
remoteIssue := `{"id":"bd-1","title":"Remote Edit","status":"open","issue_type":"task","priority":2,"created_at":"2025-01-01T00:00:00Z","updated_at":"2025-01-03T00:00:00Z"}`
if err := os.WriteFile(jsonlPath, []byte(remoteIssue+"\n"), 0644); err != nil {
t.Fatalf("write remote JSONL failed: %v", err)
}
remoteIssues, err := loadIssuesFromJSONL(jsonlPath)
if err != nil {
t.Fatalf("loadIssuesFromJSONL (remote) failed: %v", err)
}
if len(remoteIssues) != 1 {
t.Fatalf("expected 1 remote issue, got %d", len(remoteIssues))
}
// 3-way merge with base state
mergeResult := MergeIssues(baseIssues, localIssues, remoteIssues)
// Verify merge result
if len(mergeResult.Merged) != 1 {
t.Fatalf("expected 1 merged issue, got %d", len(mergeResult.Merged))
}
// LWW: Remote wins because it has later updated_at (2025-01-03 > 2025-01-02)
if mergeResult.Merged[0].Title != "Remote Edit" {
t.Errorf("expected merged title 'Remote Edit' (remote wins LWW), got '%s'", mergeResult.Merged[0].Title)
}
// Verify strategy: should be "merged" (conflict resolved by LWW)
if mergeResult.Strategy["bd-1"] != StrategyMerged {
t.Errorf("expected strategy '%s' for bd-1, got '%s'", StrategyMerged, mergeResult.Strategy["bd-1"])
}
// Verify 1 conflict was detected and resolved
if mergeResult.Conflicts != 1 {
t.Errorf("expected 1 conflict (both sides modified), got %d", mergeResult.Conflicts)
}
t.Log("TestConcurrentEdit: 3-way merge with LWW resolution validated")
}
// TestConcurrentSyncBlocked tests that concurrent syncs are blocked by file lock.
// This validates the P0 fix for preventing data corruption when running bd sync
// from multiple terminals simultaneously.
func TestConcurrentSyncBlocked(t *testing.T) {
ctx := context.Background()
tmpDir := newGitRepo(t)
t.Chdir(tmpDir)
// Setup: Create beads directory with JSONL
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("mkdir failed: %v", err)
}
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
// Create initial JSONL
if err := os.WriteFile(jsonlPath, []byte(`{"id":"bd-1","title":"Test"}`+"\n"), 0644); err != nil {
t.Fatalf("write JSONL failed: %v", err)
}
// Initial commit
_ = exec.Command("git", "add", ".").Run()
if err := exec.Command("git", "commit", "-m", "initial").Run(); err != nil {
t.Fatalf("initial commit failed: %v", err)
}
// Create database
testDBPath := filepath.Join(beadsDir, "beads.db")
testStore, err := dolt.New(ctx, &dolt.Config{Path: testDBPath})
if err != nil {
t.Fatalf("failed to create test store: %v", err)
}
defer testStore.Close()
// Set issue_prefix
if err := testStore.SetConfig(ctx, "issue_prefix", "bd"); err != nil {
t.Fatalf("failed to set issue_prefix: %v", err)
}
// Simulate another sync holding the lock
lockPath := filepath.Join(beadsDir, ".sync.lock")
lock := flock.New(lockPath)
locked, err := lock.TryLock()
if err != nil {
t.Fatalf("failed to acquire lock: %v", err)
}
if !locked {
t.Fatal("expected to acquire lock")
}
// Now try to acquire the same lock (simulating concurrent sync)
lock2 := flock.New(lockPath)
locked2, err := lock2.TryLock()
if err != nil {
t.Fatalf("TryLock error: %v", err)
}
// Second lock attempt should fail (not block)
if locked2 {
lock2.Unlock()
t.Error("expected second lock attempt to fail (concurrent sync should be blocked)")
} else {
t.Log("Concurrent sync correctly blocked by file lock")
}
// Release first lock
if err := lock.Unlock(); err != nil {
t.Fatalf("failed to unlock: %v", err)
}
// Now lock should be acquirable again
lock3 := flock.New(lockPath)
locked3, err := lock3.TryLock()
if err != nil {
t.Fatalf("TryLock error after unlock: %v", err)
}
if !locked3 {
t.Error("expected lock to be acquirable after first sync completes")
} else {
lock3.Unlock()
t.Log("Lock correctly acquirable after first sync completes")
}
}

View file

@ -1,265 +0,0 @@
//go:build cgo
package main
import (
"context"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/types"
)
// setupSyncValidationTest creates a test store and properly initializes globals.
// Returns the store and a cleanup function that should be deferred.
func setupSyncValidationTest(t *testing.T) (*testing.T, func()) {
t.Helper()
tmpDir := t.TempDir()
testDBPath := filepath.Join(tmpDir, ".beads", "issues.db")
testStore := newTestStore(t, testDBPath)
// Save original state
origStore := store
origStoreActive := storeActive
origDBPath := dbPath
// Set up test state
store = testStore
storeMutex.Lock()
storeActive = true
storeMutex.Unlock()
dbPath = testDBPath
cleanup := func() {
storeMutex.Lock()
store = origStore
storeActive = origStoreActive
storeMutex.Unlock()
dbPath = origDBPath
}
return t, cleanup
}
// TestValidateOpenIssuesForSync_ModeNone verifies validation is skipped when
// validation.on-sync is set to "none" (default).
func TestValidateOpenIssuesForSync_ModeNone(t *testing.T) {
_, cleanup := setupSyncValidationTest(t)
defer cleanup()
// Create a bug without required sections (should fail validation)
ctx := context.Background()
issue := &types.Issue{
ID: "test-001",
Title: "Bug without sections",
IssueType: types.TypeBug,
Description: "No steps to reproduce or acceptance criteria",
Status: types.StatusOpen,
}
if err := store.CreateIssue(ctx, issue, "test-user"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
// Set validation mode to "none"
initConfigForTest(t)
config.Set("validation.on-sync", "none")
// Should return nil (skip validation)
err := validateOpenIssuesForSync(ctx)
if err != nil {
t.Errorf("validateOpenIssuesForSync with mode=none returned error: %v", err)
}
}
// TestValidateOpenIssuesForSync_ModeEmpty verifies validation is skipped when
// validation.on-sync is empty (backwards compatibility).
func TestValidateOpenIssuesForSync_ModeEmpty(t *testing.T) {
_, cleanup := setupSyncValidationTest(t)
defer cleanup()
// Create a bug without required sections
ctx := context.Background()
issue := &types.Issue{
ID: "test-001",
Title: "Bug without sections",
IssueType: types.TypeBug,
Description: "No sections",
Status: types.StatusOpen,
}
if err := store.CreateIssue(ctx, issue, "test-user"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
// Set validation mode to empty string
initConfigForTest(t)
config.Set("validation.on-sync", "")
// Should return nil (skip validation)
err := validateOpenIssuesForSync(ctx)
if err != nil {
t.Errorf("validateOpenIssuesForSync with mode=empty returned error: %v", err)
}
}
// TestValidateOpenIssuesForSync_ModeWarn verifies sync proceeds when
// validation.on-sync is "warn" even with invalid issues.
func TestValidateOpenIssuesForSync_ModeWarn(t *testing.T) {
_, cleanup := setupSyncValidationTest(t)
defer cleanup()
// Create a bug without required sections
ctx := context.Background()
issue := &types.Issue{
ID: "test-001",
Title: "Bug without sections",
IssueType: types.TypeBug,
Description: "No steps to reproduce or acceptance criteria",
Status: types.StatusOpen,
}
if err := store.CreateIssue(ctx, issue, "test-user"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
// Set validation mode to "warn"
initConfigForTest(t)
config.Set("validation.on-sync", "warn")
// Should return nil (warnings printed but sync proceeds)
// The function prints to stderr but returns nil to allow sync to continue
err := validateOpenIssuesForSync(ctx)
if err != nil {
t.Errorf("validateOpenIssuesForSync with mode=warn should return nil, got: %v", err)
}
}
// TestValidateOpenIssuesForSync_ModeError verifies sync is blocked when
// validation.on-sync is "error" and issues fail validation.
func TestValidateOpenIssuesForSync_ModeError(t *testing.T) {
_, cleanup := setupSyncValidationTest(t)
defer cleanup()
// Create a bug without required sections
ctx := context.Background()
issue := &types.Issue{
ID: "test-001",
Title: "Bug without sections",
IssueType: types.TypeBug,
Description: "No sections at all",
Status: types.StatusOpen,
}
if err := store.CreateIssue(ctx, issue, "test-user"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
// Set validation mode to "error"
initConfigForTest(t)
config.Set("validation.on-sync", "error")
// Should return error (function also prints to stderr which we allow)
err := validateOpenIssuesForSync(ctx)
if err == nil {
t.Error("validateOpenIssuesForSync with mode=error should return error for invalid issues")
}
if !strings.Contains(err.Error(), "template validation failed") {
t.Errorf("expected 'template validation failed' in error, got: %v", err)
}
}
// TestValidateOpenIssuesForSync_NoWarnings verifies no errors when all issues pass validation.
func TestValidateOpenIssuesForSync_NoWarnings(t *testing.T) {
_, cleanup := setupSyncValidationTest(t)
defer cleanup()
// Create a bug WITH all required sections
ctx := context.Background()
issue := &types.Issue{
ID: "test-001",
Title: "Bug with sections",
IssueType: types.TypeBug,
Description: `## Steps to Reproduce
1. Do this
2. Do that
## Acceptance Criteria
- It works`,
Status: types.StatusOpen,
}
if err := store.CreateIssue(ctx, issue, "test-user"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
// Set validation mode to "error" (strictest mode)
initConfigForTest(t)
config.Set("validation.on-sync", "error")
// Should return nil (no validation errors)
err := validateOpenIssuesForSync(ctx)
if err != nil {
t.Errorf("validateOpenIssuesForSync should not return error for valid issues: %v", err)
}
}
// TestValidateOpenIssuesForSync_SkipsClosedIssues verifies closed issues are not validated.
func TestValidateOpenIssuesForSync_SkipsClosedIssues(t *testing.T) {
_, cleanup := setupSyncValidationTest(t)
defer cleanup()
ctx := context.Background()
// Create a closed bug without required sections (should be skipped)
closedIssue := &types.Issue{
ID: "test-001",
Title: "Closed bug without sections",
IssueType: types.TypeBug,
Description: "No sections",
Status: types.StatusClosed,
}
if err := store.CreateIssue(ctx, closedIssue, "test-user"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
// Set validation mode to "error"
initConfigForTest(t)
config.Set("validation.on-sync", "error")
// Should return nil (closed issues are not validated)
err := validateOpenIssuesForSync(ctx)
if err != nil {
t.Errorf("validateOpenIssuesForSync should skip closed issues: %v", err)
}
}
// TestValidateOpenIssuesForSync_ChoreHasNoRequirements verifies chore type
// has no required sections and passes validation.
func TestValidateOpenIssuesForSync_ChoreHasNoRequirements(t *testing.T) {
_, cleanup := setupSyncValidationTest(t)
defer cleanup()
// Create a chore without any sections (should pass - no requirements)
ctx := context.Background()
issue := &types.Issue{
ID: "test-001",
Title: "Chore issue",
IssueType: types.TypeChore,
Description: "Just a description, no sections needed",
Status: types.StatusOpen,
}
if err := store.CreateIssue(ctx, issue, "test-user"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
// Set validation mode to "error"
initConfigForTest(t)
config.Set("validation.on-sync", "error")
// Should return nil (chore has no requirements)
err := validateOpenIssuesForSync(ctx)
if err != nil {
t.Errorf("validateOpenIssuesForSync should not error for chore issues: %v", err)
}
}

View file

@ -14,7 +14,6 @@ import (
"sync"
"time"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/storage/dolt"
)
@ -393,16 +392,9 @@ func initDefaultTips() {
}
// syncConflictCondition checks if there's a sync conflict that needs manual resolution.
// This is the condition function for the sync_conflict tip.
// Sync conflict tracking was removed — always returns false.
func syncConflictCondition() bool {
// Find beads directory to check sync state
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
return false
}
state := LoadSyncState(beadsDir)
return state.NeedsManualSync
return false
}
// init initializes the tip system with default tips