diff --git a/cmd/bd/bootstrap.go b/cmd/bd/bootstrap.go index e2d5b642d..8dca57edd 100644 --- a/cmd/bd/bootstrap.go +++ b/cmd/bd/bootstrap.go @@ -3,11 +3,14 @@ package main import ( "bufio" "context" + "database/sql" "fmt" "os" "path/filepath" "strings" + "time" + _ "github.com/go-sql-driver/mysql" "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/beads" "github.com/steveyegge/beads/internal/config" @@ -19,6 +22,74 @@ import ( "golang.org/x/term" ) +type bootstrapServerProbeConfig struct { + host string + port int + user string + pass string + database string + tls bool +} + +type bootstrapServerDBCheck struct { + Exists bool + Reachable bool + Err error +} + +var checkBootstrapServerDB = func(probeCfg bootstrapServerProbeConfig) bootstrapServerDBCheck { + host := probeCfg.host + port := probeCfg.port + user := probeCfg.user + password := probeCfg.pass + dbName := probeCfg.database + var userPart string + if password != "" { + userPart = fmt.Sprintf("%s:%s", user, password) + } else { + userPart = user + } + params := "timeout=5s" + if probeCfg.tls { + params += "&tls=true" + } + dsn := fmt.Sprintf("%s@tcp(%s:%d)/?%s", userPart, host, port, params) + + db, err := sql.Open("mysql", dsn) + if err != nil { + return bootstrapServerDBCheck{Reachable: false, Err: err} + } + defer db.Close() + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + if err := db.PingContext(ctx); err != nil { + return bootstrapServerDBCheck{Reachable: false, Err: err} + } + + rows, err := db.QueryContext(ctx, "SHOW DATABASES") + if err != nil { + return bootstrapServerDBCheck{Reachable: true, Err: err} + } + defer rows.Close() + + for rows.Next() { + var name string + if err := rows.Scan(&name); err != nil { + return bootstrapServerDBCheck{Reachable: true, Err: err} + } + if name == dbName { + return bootstrapServerDBCheck{Exists: true, Reachable: true} + } + } + if err := rows.Err(); err != nil { + return bootstrapServerDBCheck{Reachable: true, Err: err} + } + + return bootstrapServerDBCheck{Exists: false, Reachable: true} +} + var bootstrapCmd = &cobra.Command{ Use: "bootstrap", GroupID: "setup", @@ -143,20 +214,48 @@ func detectBootstrapAction(beadsDir string, cfg *configfile.Config) BootstrapPla Database: cfg.GetDoltDatabase(), } - // Check for existing database (path differs between server and embedded mode) + // Check for existing database (path differs between server and embedded mode). + // Use cfg.GetDoltMode() rather than the global isEmbeddedMode() so that + // the detection logic respects the config object passed in by the caller + // (important for tests and for cases where the global serverMode flag + // has not been set yet). var dbPath string - if isEmbeddedMode() { - dbPath = filepath.Join(beadsDir, "embeddeddolt") - } else { + if cfg.GetDoltMode() == configfile.DoltModeServer { dbPath = doltserver.ResolveDoltDir(beadsDir) + } else { + dbPath = filepath.Join(beadsDir, "embeddeddolt") } if info, err := os.Stat(dbPath); err == nil && info.IsDir() { entries, _ := os.ReadDir(dbPath) if len(entries) > 0 { - plan.HasExisting = true - plan.Action = "none" - plan.Reason = "Database already exists at " + dbPath - return plan + if cfg.GetDoltMode() == configfile.DoltModeServer { + resolved := doltserver.DefaultConfig(beadsDir) + probeCfg := bootstrapServerProbeConfig{ + host: cfg.GetDoltServerHost(), + port: resolved.Port, + user: cfg.GetDoltServerUser(), + pass: cfg.GetDoltServerPassword(), + database: cfg.GetDoltDatabase(), + tls: cfg.GetDoltServerTLS(), + } + result := checkBootstrapServerDB(probeCfg) + if result.Err != nil { + plan.Action = "none" + plan.Reason = fmt.Sprintf("Could not verify existing server database %s: %v", cfg.GetDoltDatabase(), result.Err) + return plan + } + if result.Exists { + plan.HasExisting = true + plan.Action = "none" + plan.Reason = fmt.Sprintf("Database %s already exists on server at %s:%d", probeCfg.database, probeCfg.host, probeCfg.port) + return plan + } + } else { + plan.HasExisting = true + plan.Action = "none" + plan.Reason = "Database already exists at " + dbPath + return plan + } } } diff --git a/cmd/bd/bootstrap_test.go b/cmd/bd/bootstrap_test.go index 2a2bcc294..b53ebfbcd 100644 --- a/cmd/bd/bootstrap_test.go +++ b/cmd/bd/bootstrap_test.go @@ -3,22 +3,30 @@ package main import ( + "fmt" "os" "os/exec" "path/filepath" + "strings" "testing" "github.com/steveyegge/beads/internal/configfile" ) -func TestDetectBootstrapAction_NoneWhenDatabaseExists_Embedded(t *testing.T) { +func TestDetectBootstrapAction_NoneWhenDatabaseExists(t *testing.T) { + t.Setenv("BEADS_DOLT_DATA_DIR", "") + t.Setenv("BEADS_DOLT_SERVER_DATABASE", "") + t.Setenv("BEADS_DOLT_SERVER_HOST", "") + t.Setenv("BEADS_DOLT_SERVER_PORT", "") tmpDir := t.TempDir() beadsDir := filepath.Join(tmpDir, ".beads") if err := os.MkdirAll(beadsDir, 0o750); err != nil { t.Fatal(err) } - // Create embeddeddolt directory with content so it's detected as existing + // Create embeddeddolt directory with content so it's detected as existing. + // Default config uses embedded mode, so the detection logic looks for + // beadsDir/embeddeddolt (not beadsDir/dolt). embeddedDir := filepath.Join(beadsDir, "embeddeddolt") if err := os.MkdirAll(filepath.Join(embeddedDir, "beads"), 0o750); err != nil { t.Fatal(err) @@ -34,46 +42,6 @@ func TestDetectBootstrapAction_NoneWhenDatabaseExists_Embedded(t *testing.T) { t.Fatal(err) } - // Embedded mode is the default — no need to set serverMode - cfg := configfile.DefaultConfig() - plan := detectBootstrapAction(beadsDir, cfg) - - if plan.Action != "none" { - t.Errorf("action = %q, want %q", plan.Action, "none") - } - if !plan.HasExisting { - t.Error("HasExisting = false, want true") - } -} - -func TestDetectBootstrapAction_NoneWhenDatabaseExists_Server(t *testing.T) { - // Switch to server mode for this test - oldServerMode := serverMode - serverMode = true - defer func() { serverMode = oldServerMode }() - - tmpDir := t.TempDir() - beadsDir := filepath.Join(tmpDir, ".beads") - if err := os.MkdirAll(beadsDir, 0o750); err != nil { - t.Fatal(err) - } - - // Create dolt directory with content so it's detected as existing - doltDir := filepath.Join(beadsDir, "dolt") - if err := os.MkdirAll(filepath.Join(doltDir, "beads"), 0o750); err != nil { - t.Fatal(err) - } - - // Run from tmpDir so auto-detect doesn't find parent git repo - oldWd, err := os.Getwd() - if err != nil { - t.Fatal(err) - } - defer func() { _ = os.Chdir(oldWd) }() - if err := os.Chdir(tmpDir); err != nil { - t.Fatal(err) - } - cfg := configfile.DefaultConfig() plan := detectBootstrapAction(beadsDir, cfg) @@ -86,6 +54,10 @@ func TestDetectBootstrapAction_NoneWhenDatabaseExists_Server(t *testing.T) { } func TestDetectBootstrapAction_RestoreWhenBackupExists(t *testing.T) { + t.Setenv("BEADS_DOLT_DATA_DIR", "") + t.Setenv("BEADS_DOLT_SERVER_DATABASE", "") + t.Setenv("BEADS_DOLT_SERVER_HOST", "") + t.Setenv("BEADS_DOLT_SERVER_PORT", "") tmpDir := t.TempDir() beadsDir := filepath.Join(tmpDir, ".beads") backupDir := filepath.Join(beadsDir, "backup") @@ -118,6 +90,10 @@ func TestDetectBootstrapAction_RestoreWhenBackupExists(t *testing.T) { } func TestDetectBootstrapAction_InitWhenNothingExists(t *testing.T) { + t.Setenv("BEADS_DOLT_DATA_DIR", "") + t.Setenv("BEADS_DOLT_SERVER_DATABASE", "") + t.Setenv("BEADS_DOLT_SERVER_HOST", "") + t.Setenv("BEADS_DOLT_SERVER_PORT", "") tmpDir := t.TempDir() beadsDir := filepath.Join(tmpDir, ".beads") if err := os.MkdirAll(beadsDir, 0o750); err != nil { @@ -142,7 +118,129 @@ func TestDetectBootstrapAction_InitWhenNothingExists(t *testing.T) { } } +func TestDetectBootstrapAction_ServerModeMissingConfiguredDBDoesNotReturnNone(t *testing.T) { + t.Setenv("BEADS_DOLT_DATA_DIR", "") + t.Setenv("BEADS_DOLT_SERVER_DATABASE", "") + t.Setenv("BEADS_DOLT_SERVER_HOST", "") + t.Setenv("BEADS_DOLT_SERVER_PORT", "") + tmpDir := t.TempDir() + beadsDir := filepath.Join(tmpDir, ".beads") + if err := os.MkdirAll(beadsDir, 0o750); err != nil { + t.Fatal(err) + } + sharedDir := filepath.Join(tmpDir, "shared-dolt") + if err := os.MkdirAll(filepath.Join(sharedDir, "hq"), 0o750); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(sharedDir, "dolt-server.port"), []byte("3311"), 0o644); err != nil { + t.Fatal(err) + } + + oldWd, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + defer func() { _ = os.Chdir(oldWd) }() + if err := os.Chdir(tmpDir); err != nil { + t.Fatal(err) + } + + cfg := configfile.DefaultConfig() + cfg.DoltMode = configfile.DoltModeServer + cfg.DoltDatabase = "project_missing" + cfg.DoltDataDir = sharedDir + t.Setenv("BEADS_DOLT_SHARED_SERVER", "1") + t.Setenv("BEADS_DOLT_DATA_DIR", sharedDir) + + origCheck := checkBootstrapServerDB + checkBootstrapServerDB = func(probeCfg bootstrapServerProbeConfig) bootstrapServerDBCheck { + if probeCfg.database != "project_missing" { + t.Fatalf("unexpected dbName: %s", probeCfg.database) + } + if probeCfg.port != 3311 { + t.Fatalf("expected resolved server port 3311, got %d", probeCfg.port) + } + return bootstrapServerDBCheck{Exists: false, Reachable: true} + } + defer func() { checkBootstrapServerDB = origCheck }() + + plan := detectBootstrapAction(beadsDir, cfg) + if plan.Action == "none" { + t.Fatalf("expected bootstrap to continue recovery when configured server DB is missing, got plan %#v", plan) + } + if plan.Action != "init" { + t.Fatalf("expected init fallback when no remote/backup/jsonl exists, got %q", plan.Action) + } +} + +func TestDetectBootstrapAction_ServerModeProbeErrorStopsWithReason(t *testing.T) { + t.Setenv("BEADS_DOLT_DATA_DIR", "") + t.Setenv("BEADS_DOLT_SERVER_DATABASE", "") + t.Setenv("BEADS_DOLT_SERVER_HOST", "") + t.Setenv("BEADS_DOLT_SERVER_PORT", "") + tmpDir := t.TempDir() + beadsDir := filepath.Join(tmpDir, ".beads") + if err := os.MkdirAll(beadsDir, 0o750); err != nil { + t.Fatal(err) + } + sharedDir := filepath.Join(tmpDir, "shared-dolt") + if err := os.MkdirAll(filepath.Join(sharedDir, "hq"), 0o750); err != nil { + t.Fatal(err) + } + + oldWd, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + defer func() { _ = os.Chdir(oldWd) }() + if err := os.Chdir(tmpDir); err != nil { + t.Fatal(err) + } + + cfg := configfile.DefaultConfig() + cfg.DoltMode = configfile.DoltModeServer + cfg.DoltDatabase = "project_missing" + cfg.DoltDataDir = sharedDir + t.Setenv("BEADS_DOLT_DATA_DIR", sharedDir) + + origCheck := checkBootstrapServerDB + checkBootstrapServerDB = func(probeCfg bootstrapServerProbeConfig) bootstrapServerDBCheck { + return bootstrapServerDBCheck{Reachable: true, Err: fmt.Errorf("permission denied")} + } + defer func() { checkBootstrapServerDB = origCheck }() + + plan := detectBootstrapAction(beadsDir, cfg) + if plan.Action != "none" { + t.Fatalf("expected bootstrap to stop when server probe errors, got %#v", plan) + } + if !strings.Contains(plan.Reason, "permission denied") { + t.Fatalf("expected probe error in plan reason, got %#v", plan) + } +} + +func TestCheckBootstrapServerDB_HonorsTLSFlagInDSN(t *testing.T) { + probeCfg := bootstrapServerProbeConfig{ + host: "127.0.0.1", + port: 1, + user: "root", + database: "beads", + tls: true, + } + + result := checkBootstrapServerDB(probeCfg) + if result.Reachable { + t.Fatal("expected unreachable test connection") + } + if result.Err == nil { + t.Fatal("expected connection error for unreachable test host") + } +} + func TestDetectBootstrapAction_SyncWhenOriginHasDoltRef(t *testing.T) { + t.Setenv("BEADS_DOLT_DATA_DIR", "") + t.Setenv("BEADS_DOLT_SERVER_DATABASE", "") + t.Setenv("BEADS_DOLT_SERVER_HOST", "") + t.Setenv("BEADS_DOLT_SERVER_PORT", "") // Create a bare repo with a refs/dolt/data ref bareDir := filepath.Join(t.TempDir(), "bare.git") runGitForBootstrapTest(t, "", "init", "--bare", bareDir) @@ -189,6 +287,10 @@ func TestDetectBootstrapAction_SyncWhenOriginHasDoltRef(t *testing.T) { } func TestDetectBootstrapAction_InitWhenOriginHasNoDoltRef(t *testing.T) { + t.Setenv("BEADS_DOLT_DATA_DIR", "") + t.Setenv("BEADS_DOLT_SERVER_DATABASE", "") + t.Setenv("BEADS_DOLT_SERVER_HOST", "") + t.Setenv("BEADS_DOLT_SERVER_PORT", "") // Create a bare repo without refs/dolt/data bareDir := filepath.Join(t.TempDir(), "bare.git") runGitForBootstrapTest(t, "", "init", "--bare", bareDir) diff --git a/cmd/bd/doctor/agent.go b/cmd/bd/doctor/agent.go index 9372a72d9..1cbead640 100644 --- a/cmd/bd/doctor/agent.go +++ b/cmd/bd/doctor/agent.go @@ -306,13 +306,13 @@ func enrichGitUpstream(dc DoctorCheck) agentEnrichment { } func enrichFreshClone(dc DoctorCheck) agentEnrichment { - commands := []string{"bd init"} - explanation := fmt.Sprintf("Fresh clone detected: %s. The .beads/ directory exists (committed to git) but the local database hasn't been initialized. Run bd init to bootstrap from the tracked config.", dc.Message) + commands := []string{"bd bootstrap"} + explanation := fmt.Sprintf("Fresh clone detected: %s. The .beads/ directory exists (committed to git) but the local database has not been recovered yet. Run bd bootstrap as the safe existing-project recovery entry point.", dc.Message) // When the message mentions sync.git-remote, include it in the suggested commands. if strings.Contains(dc.Message, "sync.git-remote") { - explanation = fmt.Sprintf("Fresh clone detected: %s. The .beads/ directory exists (committed to git) but the database is not found on the configured server. Consider setting sync.git-remote in .beads/config.yaml to bootstrap from a Dolt remote, then run bd init.", dc.Message) - commands = []string{"Set sync.git-remote in .beads/config.yaml", "bd init"} + explanation = fmt.Sprintf("Fresh clone detected: %s. The .beads/ directory exists (committed to git) but the database is not found on the configured server. Run bd bootstrap as the safe entry point; if bootstrap cannot find the expected remote automatically, then set sync.git-remote in .beads/config.yaml and rerun bd bootstrap.", dc.Message) + commands = []string{"bd bootstrap", "Set sync.git-remote in .beads/config.yaml if bootstrap cannot find the expected remote"} } return agentEnrichment{ diff --git a/cmd/bd/doctor/agent_test.go b/cmd/bd/doctor/agent_test.go new file mode 100644 index 000000000..ca4223be5 --- /dev/null +++ b/cmd/bd/doctor/agent_test.go @@ -0,0 +1,39 @@ +package doctor + +import ( + "strings" + "testing" +) + +func TestEnrichFreshClone_UsesBootstrapFirstGuidance(t *testing.T) { + dc := DoctorCheck{Name: "Fresh Clone", Message: "database not found on configured server"} + enrichment := enrichFreshClone(dc) + + if enrichment.severity != "blocking" { + t.Fatalf("expected blocking severity, got %q", enrichment.severity) + } + if !strings.Contains(enrichment.explanation, "bd bootstrap") { + t.Fatalf("expected bootstrap guidance, got: %s", enrichment.explanation) + } + if len(enrichment.commands) != 1 || enrichment.commands[0] != "bd bootstrap" { + t.Fatalf("expected bootstrap-first commands, got %#v", enrichment.commands) + } + if strings.Contains(enrichment.explanation, "run bd init") { + t.Fatalf("did not expect init-first guidance, got: %s", enrichment.explanation) + } +} + +func TestEnrichFreshClone_WithSyncRemoteMentionsBootstrapAndFallback(t *testing.T) { + dc := DoctorCheck{Name: "Fresh Clone", Message: "sync.git-remote is configured but database not found"} + enrichment := enrichFreshClone(dc) + + if !strings.Contains(enrichment.explanation, "bd bootstrap") { + t.Fatalf("expected bootstrap guidance, got: %s", enrichment.explanation) + } + if len(enrichment.commands) != 2 || enrichment.commands[0] != "bd bootstrap" { + t.Fatalf("expected bootstrap-first command list, got %#v", enrichment.commands) + } + if !strings.Contains(enrichment.commands[1], "sync.git-remote") { + t.Fatalf("expected sync.git-remote fallback command, got %#v", enrichment.commands) + } +} diff --git a/cmd/bd/doctor/database.go b/cmd/bd/doctor/database.go index 451b6f35d..403b020b3 100644 --- a/cmd/bd/doctor/database.go +++ b/cmd/bd/doctor/database.go @@ -69,7 +69,7 @@ func CheckDatabaseVersion(path string, cliVersion string) DoctorCheck { Status: StatusError, Message: "No dolt database found", Detail: "Storage: Dolt", - Fix: "Run 'bd init' to create database (will clone from remote if configured)", + Fix: "Run 'bd bootstrap' as the safe existing-project recovery entry point. Use '--dry-run' to inspect the plan first, and use 'bd init' only for brand-new projects.", } } @@ -111,7 +111,7 @@ func CheckDatabaseVersionWithStore(ss *SharedStore, cliVersion string) DoctorChe Status: StatusError, Message: "No dolt database found", Detail: "Storage: Dolt", - Fix: "Run 'bd init' to create database (will clone from remote if configured)", + Fix: "Run 'bd bootstrap' as the safe existing-project recovery entry point. Use '--dry-run' to inspect the plan first, and use 'bd init' only for brand-new projects.", } } return DoctorCheck{ diff --git a/cmd/bd/doctor/fresh_clone_server.go b/cmd/bd/doctor/fresh_clone_server.go index 0f6d4acfc..df3e3aad4 100644 --- a/cmd/bd/doctor/fresh_clone_server.go +++ b/cmd/bd/doctor/fresh_clone_server.go @@ -88,12 +88,12 @@ func freshCloneServerResult(dbExists bool, dbName, host string, port int, syncGi var msg strings.Builder fmt.Fprintf(&msg, "Fresh clone detected: database %q not found on server at %s:%d.", dbName, host, port) - fix := "bd init" + fix := "bd bootstrap" if syncGitRemote == "" { - msg.WriteString(" Set sync.git-remote in .beads/config.yaml to bootstrap from a remote.") - fix = "bd init (after setting sync.git-remote in .beads/config.yaml)" + msg.WriteString(" Run bd bootstrap first as the safe recovery entry point. It may recover existing state or initialize if no prior state can be found. If bootstrap cannot find the expected remote automatically, then set sync.git-remote in .beads/config.yaml and rerun bd bootstrap.") + fix = "bd bootstrap" } else { - fmt.Fprintf(&msg, " sync.git-remote is configured (%s) — run bd init to bootstrap.", syncGitRemote) + fmt.Fprintf(&msg, " sync.git-remote is configured (%s) — run bd bootstrap to recover from the remote, or use --dry-run to inspect the plan first.", syncGitRemote) } return DoctorCheck{ diff --git a/cmd/bd/doctor/fresh_clone_server_test.go b/cmd/bd/doctor/fresh_clone_server_test.go index 8227c558f..01e92b42b 100644 --- a/cmd/bd/doctor/fresh_clone_server_test.go +++ b/cmd/bd/doctor/fresh_clone_server_test.go @@ -46,7 +46,7 @@ func TestFreshCloneServerResult(t *testing.T) { wantNotContain: []string{ "sync.git-remote is configured", }, - wantFix: "bd init (after setting sync.git-remote in .beads/config.yaml)", + wantFix: "bd bootstrap", }, "DB missing, sync.git-remote IS configured returns Warning with remote hint": { dbExists: false, @@ -60,12 +60,12 @@ func TestFreshCloneServerResult(t *testing.T) { "not found on server", "sync.git-remote is configured", "https://doltremoteapi.dolthub.com/myorg/beads", - "bd init to bootstrap", + "bd bootstrap", }, wantNotContain: []string{ "Set sync.git-remote in .beads/config.yaml", }, - wantFix: "bd init", + wantFix: "bd bootstrap", }, } diff --git a/cmd/bd/doctor/legacy.go b/cmd/bd/doctor/legacy.go index 0d1983b9b..cf7ecdc1a 100644 --- a/cmd/bd/doctor/legacy.go +++ b/cmd/bd/doctor/legacy.go @@ -338,7 +338,7 @@ func CheckFreshClone(repoPath string) DoctorCheck { } // Check if JSONL has any issues (empty JSONL = not really a fresh clone) - issueCount, prefix := countJSONLIssuesAndPrefix(jsonlPath) + issueCount, _ := countJSONLIssuesAndPrefix(jsonlPath) if issueCount == 0 { return DoctorCheck{ Name: "Fresh Clone", @@ -348,10 +348,7 @@ func CheckFreshClone(repoPath string) DoctorCheck { } // This is a fresh clone! JSONL has issues but no database. - fixCmd := "bd init" - if prefix != "" { - fixCmd = fmt.Sprintf("bd init --prefix %s", prefix) - } + fixCmd := "bd bootstrap" return DoctorCheck{ Name: "Fresh Clone", @@ -359,8 +356,10 @@ func CheckFreshClone(repoPath string) DoctorCheck { Message: fmt.Sprintf("Fresh clone detected (%d issues in %s, no database)", issueCount, jsonlName), Detail: "This appears to be a freshly cloned repository.\n" + " The JSONL file contains issues but no local database exists.\n" + - " Run 'bd init' to create the database and import existing issues.", - Fix: fmt.Sprintf("Run '%s' to initialize the database and import issues", fixCmd), + " Run 'bd bootstrap' as the safe entry point for recovering existing state.\n" + + " Use '--dry-run' first if you need to inspect whether bootstrap will recover or initialize.\n" + + " Use 'bd init' only when creating a brand-new project with no existing .beads data.", + Fix: fmt.Sprintf("Run '%s' to recover the existing database and import tracked issues", fixCmd), } } diff --git a/cmd/bd/doctor/legacy_test.go b/cmd/bd/doctor/legacy_test.go index 4ff0cb5f1..37e376fb9 100644 --- a/cmd/bd/doctor/legacy_test.go +++ b/cmd/bd/doctor/legacy_test.go @@ -451,11 +451,11 @@ func TestCheckFreshClone(t *testing.T) { if check.Fix == "" { t.Error("Expected fix message for warning, got empty string") } - if tt.expectPrefix != "" && !strings.Contains(check.Fix, tt.expectPrefix) { - t.Errorf("Expected fix to contain prefix %q, got: %s", tt.expectPrefix, check.Fix) + if tt.expectPrefix != "" && strings.Contains(check.Fix, "bd init") { + t.Errorf("did not expect legacy fresh-clone recovery to keep init-based guidance, got: %s", check.Fix) } - if !strings.Contains(check.Fix, "bd init") { - t.Error("Expected fix to mention 'bd init'") + if !strings.Contains(check.Fix, "bd bootstrap") { + t.Error("Expected fix to mention 'bd bootstrap'") } } }) diff --git a/cmd/bd/doctor/server.go b/cmd/bd/doctor/server.go index 51c835246..5e455676c 100644 --- a/cmd/bd/doctor/server.go +++ b/cmd/bd/doctor/server.go @@ -433,7 +433,7 @@ func checkDatabaseExists(db *sql.DB, database string) DoctorCheck { Name: "Database Exists", Status: StatusError, Message: fmt.Sprintf("Database '%s' not found", database), - Fix: fmt.Sprintf("Run 'bd init' to create the '%s' database", database), + Fix: fmt.Sprintf("Run 'bd bootstrap' to recover the existing '%s' database safely. Use 'bd init' only for brand-new projects.", database), Category: CategoryFederation, } } diff --git a/cmd/bd/dolt_autostart_lifecycle_integration_test.go b/cmd/bd/dolt_autostart_lifecycle_integration_test.go index b411bf545..a401df30f 100644 --- a/cmd/bd/dolt_autostart_lifecycle_integration_test.go +++ b/cmd/bd/dolt_autostart_lifecycle_integration_test.go @@ -18,7 +18,7 @@ func TestE2E_AutoStartedRepoLocalServerPersistsAcrossCommands(t *testing.T) { if testing.Short() { t.Skip("skipping slow integration test in short mode") } - if isEmbeddedDolt { + if isEmbeddedMode() { t.Skip("skipping: bd dolt status not supported in embedded mode") } if runtime.GOOS == windowsOS { diff --git a/cmd/bd/init_guard.go b/cmd/bd/init_guard.go index 3c7fdccdb..bbb83ac9f 100644 --- a/cmd/bd/init_guard.go +++ b/cmd/bd/init_guard.go @@ -92,16 +92,18 @@ func initGuardServerMessage(dbName, host string, port int, prefix, syncGitRemote b.WriteString(" bd doctor # check project health\n") b.WriteString(" bd dolt status # inspect Dolt server state\n") + b.WriteString("\nIf this is an existing project, fresh clone, or shared-server recovery, run:\n") + b.WriteString(" bd bootstrap\n") + b.WriteString("This is the safe entry point for existing-project recovery and may recover or initialize depending on detected state.\n") + if syncGitRemote != "" { fmt.Fprintf(&b, "\nTip: sync.git-remote is configured (%s).\n", syncGitRemote) - b.WriteString("If this is a fresh clone, run:\n") - fmt.Fprintf(&b, " bd init --prefix %s\n", prefix) - b.WriteString("to bootstrap from the remote (existing data is preserved).\n") + b.WriteString("Run bd bootstrap to recover from the configured remote, or use --dry-run to inspect the plan first.\n") } else { b.WriteString("\nIf this is a brand-new project, create the database with:\n") fmt.Fprintf(&b, " bd init --prefix %s\n", prefix) - b.WriteString("\nTo bootstrap from an existing Dolt remote, set sync.git-remote\n") - b.WriteString("in .beads/config.yaml first, then run bd init.\n") + b.WriteString("\nIf bd bootstrap cannot find the expected remote automatically, set sync.git-remote\n") + b.WriteString("in .beads/config.yaml and re-run bd bootstrap.\n") } b.WriteString("\n⚠ Caution: bd init --force destroys ALL existing issues. Do not\n") diff --git a/cmd/bd/init_guard_test.go b/cmd/bd/init_guard_test.go index 9f948f0c0..9fdaf3bd0 100644 --- a/cmd/bd/init_guard_test.go +++ b/cmd/bd/init_guard_test.go @@ -28,10 +28,9 @@ func TestInitGuardServerMessage(t *testing.T) { `"acf_beads"`, "127.0.0.1:3309", "not found on server", - "server is running but this database hasn't been created yet", "bd doctor", "bd dolt status", - "bd init --prefix acf", + "bd bootstrap", "set sync.git-remote", ".beads/config.yaml", "Aborting", @@ -53,13 +52,11 @@ func TestInitGuardServerMessage(t *testing.T) { `"beads_kc"`, "192.168.1.50:3307", "not found on server", - "server is running but this database hasn't been created yet", "bd doctor", "bd dolt status", - "bd init --prefix kc", + "bd bootstrap", "sync.git-remote is configured", "https://doltremoteapi.dolthub.com/myorg/beads", - "existing data is preserved", "--force destroys ALL existing issues", }, wantNotContain: []string{ @@ -124,6 +121,9 @@ func TestInitGuardDBCheck_ExistsPath(t *testing.T) { if !strings.Contains(err.Error(), "not found on server") { t.Errorf("expected 'not found on server' in message, got:\n%s", err.Error()) } + if !strings.Contains(err.Error(), "bd bootstrap") { + t.Errorf("expected bootstrap-first recovery guidance, got:\n%s", err.Error()) + } }) } diff --git a/cmd/bd/main_errors.go b/cmd/bd/main_errors.go index ea613a0b0..7cff60cc6 100644 --- a/cmd/bd/main_errors.go +++ b/cmd/bd/main_errors.go @@ -30,14 +30,11 @@ func handleFreshCloneError(err error) bool { } fmt.Fprintf(os.Stderr, "Error: Database not initialized\n\n") - fmt.Fprintf(os.Stderr, "This appears to be a fresh clone or the database needs initialization.\n") - if !isEmbeddedMode() { - fmt.Fprintf(os.Stderr, "\nTo diagnose, run:\n") - fmt.Fprintf(os.Stderr, " bd doctor\n\n") - } else { - fmt.Fprintln(os.Stderr) - } - fmt.Fprintf(os.Stderr, "To initialize a new database: bd init --prefix \n") + fmt.Fprintf(os.Stderr, "This appears to be a fresh clone or an existing project whose database needs recovery.\n") + fmt.Fprintf(os.Stderr, "\nTo diagnose, run:\n") + fmt.Fprintf(os.Stderr, " bd doctor\n\n") + fmt.Fprintf(os.Stderr, "If this is an existing project or fresh clone, run: bd bootstrap\n") + fmt.Fprintf(os.Stderr, "To create a brand-new database from scratch: bd init --prefix \n") return true } diff --git a/cmd/bd/main_errors_test.go b/cmd/bd/main_errors_test.go new file mode 100644 index 000000000..096629884 --- /dev/null +++ b/cmd/bd/main_errors_test.go @@ -0,0 +1,45 @@ +package main + +import ( + "bytes" + "errors" + "io" + "os" + "strings" + "testing" +) + +func TestHandleFreshCloneError_UsesBootstrapFirstGuidance(t *testing.T) { + err := errors.New("post-migration validation failed: required config key missing: issue_prefix") + + origStderr := os.Stderr + r, w, pipeErr := os.Pipe() + if pipeErr != nil { + t.Fatal(pipeErr) + } + os.Stderr = w + + handled := handleFreshCloneError(err) + _ = w.Close() + os.Stderr = origStderr + + var buf bytes.Buffer + if _, copyErr := io.Copy(&buf, r); copyErr != nil { + t.Fatal(copyErr) + } + _ = r.Close() + + if !handled { + t.Fatal("expected fresh clone error to be handled") + } + msg := buf.String() + if !strings.Contains(msg, "bd bootstrap") { + t.Fatalf("expected bootstrap guidance, got:\n%s", msg) + } + if strings.Contains(msg, "To initialize a new database: bd init") { + t.Fatalf("did not expect init-first guidance for fresh clone recovery, got:\n%s", msg) + } + if !strings.Contains(msg, "brand-new database from scratch") { + t.Fatalf("expected brand-new project fallback note, got:\n%s", msg) + } +} diff --git a/internal/storage/dolt/errors.go b/internal/storage/dolt/errors.go index 852abf847..0d5e399bc 100644 --- a/internal/storage/dolt/errors.go +++ b/internal/storage/dolt/errors.go @@ -108,9 +108,9 @@ func databaseNotFoundError(cfg *Config) error { if HasBackupFiles(cfg.BeadsDir) { b.WriteString("Backup files found in .beads/backup/ — this may be a branch-switch\n") b.WriteString("or fresh-clone scenario where the Dolt database doesn't exist yet.\n\n") - b.WriteString("To restore your issues:\n") - b.WriteString(" bd init --prefix # Initialize the database\n") - b.WriteString(" bd backup restore # Restore issues from backup\n\n") + b.WriteString("Use the safe entry point for existing-project recovery:\n") + b.WriteString(" bd bootstrap # Auto-detect remote/backup/JSONL recovery or initialization\n") + b.WriteString(" bd backup restore # If backup recovery still needs manual restore\n\n") b.WriteString("If this is NOT a branch switch, see common causes below.\n\n") } @@ -124,9 +124,12 @@ func databaseNotFoundError(cfg *Config) error { b.WriteString(" bd dolt status # Show which data directory the server is using") if cfg.SyncGitRemote != "" { - fmt.Fprintf(&b, "\n\nTip: sync.git-remote is configured (%s).\nRun bd init to bootstrap from the remote.", cfg.SyncGitRemote) + fmt.Fprintf(&b, "\n\nTip: sync.git-remote is configured (%s).\nRun bd bootstrap to recover from the remote or confirm what bootstrap will do with --dry-run.", cfg.SyncGitRemote) } else { - b.WriteString("\n\nTip: To bootstrap from an existing Dolt remote, set sync.git-remote\nin .beads/config.yaml and re-run bd init.") + b.WriteString("\n\nTip: If this is an existing project, fresh clone, or shared-server recovery, run bd bootstrap first.\n") + b.WriteString("If bootstrap cannot find the expected remote automatically, set sync.git-remote\nin .beads/config.yaml and re-run bd bootstrap.\n") + b.WriteString("Use bd bootstrap --dry-run if you need to confirm the plan before it initializes anything.\n") + b.WriteString("Use bd init only when creating a brand-new project with no existing .beads data.") } return errors.New(b.String()) diff --git a/internal/storage/dolt/errors_test.go b/internal/storage/dolt/errors_test.go index f8d9eae50..03e0160dd 100644 --- a/internal/storage/dolt/errors_test.go +++ b/internal/storage/dolt/errors_test.go @@ -122,13 +122,16 @@ func TestDatabaseNotFoundHint(t *testing.T) { t.Errorf("expected server address in error, got:\n%s", msg) } - // Must contain existing suggestions - if !strings.Contains(msg, "bd init") { - t.Errorf("expected bd init suggestion, got:\n%s", msg) + // Must contain recovery suggestions + if !strings.Contains(msg, "bd bootstrap") { + t.Errorf("expected bd bootstrap suggestion, got:\n%s", msg) } if !strings.Contains(msg, "bd doctor") { t.Errorf("expected bd doctor suggestion, got:\n%s", msg) } + if strings.Contains(msg, "re-run bd init") { + t.Errorf("did not expect init-first recovery guidance, got:\n%s", msg) + } }) t.Run("hint mentions configured sync.git-remote when set", func(t *testing.T) { @@ -145,8 +148,8 @@ func TestDatabaseNotFoundHint(t *testing.T) { if !strings.Contains(msg, "https://doltremoteapi.dolthub.com/myorg/beads") { t.Errorf("expected remote URL in hint, got:\n%s", msg) } - if !strings.Contains(msg, "bd init") { - t.Errorf("expected bd init suggestion, got:\n%s", msg) + if !strings.Contains(msg, "bd bootstrap") { + t.Errorf("expected bd bootstrap suggestion, got:\n%s", msg) } }) @@ -172,6 +175,9 @@ func TestDatabaseNotFoundHint(t *testing.T) { if !strings.Contains(msg, "bd backup restore") { t.Errorf("expected bd backup restore suggestion, got:\n%s", msg) } + if !strings.Contains(msg, "bd bootstrap") { + t.Errorf("expected bd bootstrap suggestion, got:\n%s", msg) + } // Should still mention branch switching as a common cause if !strings.Contains(msg, "branch") { t.Errorf("expected branch-switch mention, got:\n%s", msg) diff --git a/internal/storage/embeddeddolt/new_methods_test.go b/internal/storage/embeddeddolt/new_methods_test.go index 880533a09..c491660a7 100644 --- a/internal/storage/embeddeddolt/new_methods_test.go +++ b/internal/storage/embeddeddolt/new_methods_test.go @@ -1,4 +1,4 @@ -//go:build embeddeddolt +//go:build cgo package embeddeddolt_test diff --git a/internal/storage/embeddeddolt/slots.go b/internal/storage/embeddeddolt/slots.go index 0a1985de5..5bd794248 100644 --- a/internal/storage/embeddeddolt/slots.go +++ b/internal/storage/embeddeddolt/slots.go @@ -1,4 +1,4 @@ -//go:build embeddeddolt +//go:build cgo package embeddeddolt