Follow up remaining runtime .beads fallbacks after GH#3124 (#3183)

* fix(workspace): align resolved workspace messaging and config lookup

intent(workspace): pure worktrees and external BEADS_DIR setups should work without implying a local .beads directory is required
decision(config): derive config repo roots from FindBeadsDir-backed workspace resolution instead of a local-only .beads walk
constraint(workspace-detection): keep FindBeadsDir ordering and storage behavior unchanged while making bd where the primary diagnostic hint
learned(testing): shared-server env and global .beads ignore rules can distort CGO suites, so regression coverage now normalizes those test paths

* fix(bootstrap): align no-workspace JSON wording

intent(bootstrap): machine-readable no-workspace output should match the resolved-workspace guidance used elsewhere on this branch
decision(bootstrap-json): reuse the shared workspace error helpers through a dedicated payload builder so tests can lock the JSON contract
constraint(review-loop): keep the bootstrap CLI flow unchanged outside the no-workspace JSON branch while adding a focused regression test

* fix(where): allow no-workspace diagnostics without db (beads-9f74-5l1)

intent(where): no-workspace guidance should point to a command that actually runs when workspace resolution fails
decision(startup): treat top-level where as a no-db command so it reaches its own handler before database preflight
constraint(where-tests): subprocess mode can change the exact hint text, so the regression test locks the JSON contract and stable guidance fragments instead

* fix(bootstrap): restore bd where guidance for no-workspace output (beads-9f74-3c3)

intent(bootstrap): no-workspace bootstrap guidance should match the resolved-workspace diagnostics introduced on this branch
decision(no-workspace-hints): reuse the shared hint that mentions bd where instead of the bootstrap-specific fallback text
constraint(bootstrap-tests): cover both the payload helper and subprocess CLI path so wording regressions are caught before release

* fix(workspace): remove no-workspace .beads fallbacks (beads-9f74-gr1)

intent(workspace-resolution): finish the GH#3124 follow-up for runtime paths that still fabricated local .beads state
rejected(no-workspace-fallback): inventing ./ .beads paths outside an active workspace hid shared-worktree resolution and created stray files
decision(setup-recipes): keep built-in bd setup recipes usable without a workspace but require an active workspace for custom recipe state
constraint(worktree-support): completion and backup helpers still need to resolve shared main-repo workspaces from a git worktree

* fix(config): skip no-workspace store init for store-free commands

intent(config): review-fix-loop found no-workspace config commands should reach their own graceful paths instead of failing in PersistentPreRun
decision(config-preflight): detect store-free config subcommands before DB synthesis so config.yaml, git-backed, and diagnostic flows can run without an opened store
constraint(json-contract): keep bd config validate --json machine-readable on stdout once pre-run stops short-circuiting into low-level DB errors
learned(config-preflight): the parent config command not being in noDbCommands leaked store init into show, validate, drift, apply, and yaml-only config helpers

* fix(ci): restore init prefix normalization and formatting

intent(ci): clear the current PR failures instead of leaving the branch blocked behind known red checks

decision(init-prefix): normalize dotted prefixes before persisting issue_prefix so config, metadata.json, and Dolt database naming stay aligned for Julia-style repos
constraint(fmt-check): CI runs gofmt over the whole repo, so the existing spacing drift in internal/jira/tracker_test.go had to be cleaned up on this branch to get a green run
learned(ci): the latest main CI was already red on the same formatting file and the same embedded shard, so rebasing surfaced pre-existing blockers rather than introducing a new shard-only regression
This commit is contained in:
Okano, Osamu 2026-04-11 13:23:14 +09:00 • committed by GitHub
commit ef6c6e3e48
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
39 changed files with 1059 additions and 135 deletions

View file

@ -210,7 +210,7 @@ type doltBackupState struct {
func doltBackupConfigPath() (string, error) {
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
return "", fmt.Errorf("not in a beads repository")
return "", fmt.Errorf("%s", activeWorkspaceNotFoundError())
}
return filepath.Join(beadsDir, "dolt-backup.json"), nil
}
@ -218,7 +218,7 @@ func doltBackupConfigPath() (string, error) {
func doltBackupStatePath() (string, error) {
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
return "", fmt.Errorf("not in a beads repository")
return "", fmt.Errorf("%s", activeWorkspaceNotFoundError())
}
return filepath.Join(beadsDir, "dolt-backup-state.json"), nil
}
@ -346,7 +346,7 @@ func showDoltBackupStatusJSON() map[string]interface{} {
func doltBackupSize() (int64, error) {
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
return 0, fmt.Errorf("not in a beads repository")
return 0, fmt.Errorf("%s", activeWorkspaceNotFoundError())
}
dataDir := doltserver.ResolveDoltDir(beadsDir)
return dirSize(dataDir)

View file

@ -23,7 +23,8 @@ type backupState struct {
// backupDir returns the backup directory path, creating it if needed.
// When backup.git-repo is set to a valid git repo, returns a backup/ subdirectory
// inside that repo. Otherwise falls back to .beads/backup/.
// inside that repo. Otherwise it requires an active beads workspace and uses its
// backup/ subdirectory.
func backupDir() (string, error) {
gitRepo := config.GetString("backup.git-repo")
if gitRepo != "" {
@ -43,7 +44,7 @@ func backupDir() (string, error) {
}
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
beadsDir = ".beads"
return "", fmt.Errorf("%s; %s", activeWorkspaceNotFoundError(), diagHint())
}
dir := filepath.Join(beadsDir, "backup")
if err := os.MkdirAll(dir, 0700); err != nil {

View file

@ -127,7 +127,7 @@ func syncProjectIDFromDB(ctx context.Context, s storage.DoltStorage) error {
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
return fmt.Errorf("cannot find .beads directory")
return fmt.Errorf("%s; %s", activeWorkspaceNotFoundError(), diagHint())
}
cfg, err := configfile.Load(beadsDir)

View file

@ -4,9 +4,13 @@ package main
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/git"
"github.com/steveyegge/beads/internal/testutil"
)
@ -33,3 +37,50 @@ func TestBackupRestoreMissingDir(t *testing.T) {
t.Error("expected error for nonexistent backup dir")
}
}
func TestSyncProjectIDFromDB_NoWorkspaceUsesActiveWorkspaceError(t *testing.T) {
if testDoltServerPort == 0 {
t.Skip("Dolt test server not available")
}
if testutil.DoltContainerCrashed() {
t.Skipf("Dolt test server crashed: %v", testutil.DoltContainerCrashError())
}
ensureTestMode(t)
ctx := context.Background()
repoDir := t.TempDir()
testDBPath := filepath.Join(repoDir, ".beads", "beads.db")
s := newTestStoreWithPrefix(t, testDBPath, "bp")
t.Cleanup(func() { _ = s.Close() })
if err := s.SetMetadata(ctx, "_project_id", "project-123"); err != nil {
t.Fatalf("SetMetadata(_project_id): %v", err)
}
noWorkspaceDir := t.TempDir()
t.Chdir(noWorkspaceDir)
t.Setenv("BEADS_DIR", "")
t.Setenv("BEADS_DB", "")
beads.ResetCaches()
git.ResetCaches()
t.Cleanup(func() {
beads.ResetCaches()
git.ResetCaches()
})
err := syncProjectIDFromDB(ctx, s)
if err == nil {
t.Fatal("expected syncProjectIDFromDB to fail without an active workspace")
}
if !strings.Contains(err.Error(), activeWorkspaceNotFoundError()) {
t.Fatalf("syncProjectIDFromDB error = %q, want active workspace wording", err)
}
if !strings.Contains(err.Error(), diagHint()) {
t.Fatalf("syncProjectIDFromDB error = %q, want diag hint", err)
}
if _, statErr := os.Stat(filepath.Join(noWorkspaceDir, ".beads")); !os.IsNotExist(statErr) {
t.Fatalf("syncProjectIDFromDB should not create local .beads, stat err = %v", statErr)
}
}

View file

@ -5,9 +5,14 @@ package main
import (
"encoding/json"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/git"
)
func TestBackupStateRoundTrip(t *testing.T) {
@ -59,6 +64,107 @@ func TestBackupAtomicWrite(t *testing.T) {
}
}
func TestBackupDir_NoWorkspaceReturnsActiveWorkspaceError(t *testing.T) {
tmpDir := t.TempDir()
t.Chdir(tmpDir)
t.Setenv("BEADS_DIR", "")
t.Setenv("BEADS_DB", "")
t.Setenv("BD_BACKUP_GIT_REPO", filepath.Join(tmpDir, "not-a-repo"))
beads.ResetCaches()
git.ResetCaches()
t.Cleanup(func() {
beads.ResetCaches()
git.ResetCaches()
})
dir, err := backupDir()
if err == nil {
t.Fatalf("backupDir() = %q, want error", dir)
}
if !strings.Contains(err.Error(), activeWorkspaceNotFoundError()) {
t.Fatalf("backupDir() error = %q, want active workspace wording", err)
}
if !strings.Contains(err.Error(), diagHint()) {
t.Fatalf("backupDir() error = %q, want diag hint", err)
}
if _, statErr := os.Stat(filepath.Join(tmpDir, ".beads")); !os.IsNotExist(statErr) {
t.Fatalf("backupDir() should not create local .beads, stat err = %v", statErr)
}
}
func TestBackupDir_UsesWorktreeFallback(t *testing.T) {
tmpDir := t.TempDir()
mainRepoDir := filepath.Join(tmpDir, "main-repo")
if err := os.MkdirAll(mainRepoDir, 0o755); err != nil {
t.Fatalf("mkdir main repo: %v", err)
}
run := func(dir string, args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = dir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git %v failed: %v\n%s", args, err, out)
}
}
run(mainRepoDir, "init")
run(mainRepoDir, "config", "user.email", "test@example.com")
run(mainRepoDir, "config", "user.name", "Test User")
if err := os.WriteFile(filepath.Join(mainRepoDir, "README.md"), []byte("# Test\n"), 0o644); err != nil {
t.Fatalf("write README: %v", err)
}
run(mainRepoDir, "add", "README.md")
run(mainRepoDir, "commit", "-m", "Initial commit")
worktreeDir := filepath.Join(tmpDir, "worktree")
cmd := exec.Command("git", "worktree", "add", worktreeDir, "HEAD")
cmd.Dir = mainRepoDir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git worktree add failed: %v\n%s", err, out)
}
t.Cleanup(func() {
cleanupCmd := exec.Command("git", "worktree", "remove", "--force", worktreeDir)
cleanupCmd.Dir = mainRepoDir
_ = cleanupCmd.Run()
})
mainBeadsDir := filepath.Join(mainRepoDir, ".beads")
if err := os.MkdirAll(filepath.Join(mainBeadsDir, "dolt"), 0o755); err != nil {
t.Fatalf("mkdir main beads dir: %v", err)
}
_ = os.RemoveAll(filepath.Join(worktreeDir, ".beads"))
t.Chdir(worktreeDir)
t.Setenv("BEADS_DIR", "")
t.Setenv("BEADS_DB", "")
t.Setenv("BD_BACKUP_GIT_REPO", filepath.Join(tmpDir, "not-a-repo"))
beads.ResetCaches()
git.ResetCaches()
t.Cleanup(func() {
beads.ResetCaches()
git.ResetCaches()
})
dir, err := backupDir()
if err != nil {
t.Fatalf("backupDir() error = %v", err)
}
gotResolved, err := filepath.EvalSymlinks(dir)
if err != nil {
t.Fatalf("EvalSymlinks(%q): %v", dir, err)
}
wantResolved, err := filepath.EvalSymlinks(filepath.Join(mainBeadsDir, "backup"))
if err != nil {
t.Fatalf("EvalSymlinks(%q): %v", filepath.Join(mainBeadsDir, "backup"), err)
}
if gotResolved != wantResolved {
t.Fatalf("backupDir() = %q (resolved %q), want resolved %q", dir, gotResolved, wantResolved)
}
}
// splitJSONL splits JSONL data into individual JSON lines, skipping empty lines.
func splitJSONL(data []byte) []json.RawMessage {
var result []json.RawMessage

View file

@ -156,14 +156,10 @@ Examples:
if beadsDir == "" {
// No .beads and no remote data — nothing to bootstrap from.
if jsonOutput {
outputJSON(map[string]interface{}{
"action": "none",
"reason": "no .beads directory found",
"suggestion": "Run 'bd init' to create a new project",
})
outputJSON(noWorkspaceBootstrapPayload())
} else {
fmt.Fprintf(os.Stderr, "No .beads directory found.\n")
fmt.Fprintf(os.Stderr, "To create a new project, use: bd init\n")
fmt.Fprintf(os.Stderr, "%s\n", activeWorkspaceNotFoundMessage())
fmt.Fprintf(os.Stderr, "Hint: %s\n", diagHint())
fmt.Fprintf(os.Stderr, "Bootstrap is for existing projects that need database setup.\n")
}
os.Exit(1)
@ -217,6 +213,14 @@ type BootstrapPlan struct {
HasExisting bool `json:"has_existing"`
}
func noWorkspaceBootstrapPayload() map[string]interface{} {
return map[string]interface{}{
"action": "none",
"reason": activeWorkspaceNotFoundError(),
"suggestion": diagHint(),
}
}
func detectBootstrapAction(beadsDir string, cfg *configfile.Config) BootstrapPlan {
plan := BootstrapPlan{
BeadsDir: beadsDir,

View file

@ -3,6 +3,7 @@
package main
import (
"encoding/json"
"fmt"
"os"
"os/exec"
@ -26,6 +27,63 @@ func bdBootstrap(t *testing.T, bd, dir string, args ...string) string {
return string(out)
}
func bdBootstrapAllowError(t *testing.T, bd, dir string, args ...string) (string, error) {
t.Helper()
fullArgs := append([]string{"bootstrap"}, args...)
cmd := exec.Command(bd, fullArgs...)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
out, err := cmd.CombinedOutput()
return string(out), err
}
func TestBootstrapNoWorkspace(t *testing.T) {
t.Parallel()
bd := buildEmbeddedBD(t)
dir := t.TempDir()
t.Run("default_output", func(t *testing.T) {
out, err := bdBootstrapAllowError(t, bd, dir)
if err == nil {
t.Fatal("expected bd bootstrap to exit non-zero without a workspace")
}
if !strings.Contains(out, activeWorkspaceNotFoundMessage()) {
t.Fatalf("expected no-workspace message, got: %s", out)
}
if !strings.Contains(out, "bd where") {
t.Fatalf("expected bootstrap hint to mention bd where, got: %s", out)
}
})
t.Run("json_output", func(t *testing.T) {
out, err := bdBootstrapAllowError(t, bd, dir, "--json")
if err == nil {
t.Fatal("expected bd bootstrap --json to exit non-zero without a workspace")
}
s := strings.TrimSpace(out)
start := strings.Index(s, "{")
if start < 0 {
t.Fatalf("expected JSON object in output, got: %s", out)
}
var payload map[string]string
if err := json.Unmarshal([]byte(s[start:]), &payload); err != nil {
t.Fatalf("parse bootstrap JSON: %v\n%s", err, s)
}
if payload["action"] != "none" {
t.Fatalf("action = %q, want %q", payload["action"], "none")
}
if payload["reason"] != activeWorkspaceNotFoundError() {
t.Fatalf("reason = %q, want %q", payload["reason"], activeWorkspaceNotFoundError())
}
if !strings.Contains(payload["suggestion"], "bd where") {
t.Fatalf("suggestion should mention bd where, got: %q", payload["suggestion"])
}
})
}
func TestEmbeddedBootstrap(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")

View file

@ -118,6 +118,20 @@ func TestDetectBootstrapAction_InitWhenNothingExists(t *testing.T) {
}
}
func TestNoWorkspaceBootstrapPayload(t *testing.T) {
payload := noWorkspaceBootstrapPayload()
if got := payload["action"]; got != "none" {
t.Fatalf("action = %v, want %q", got, "none")
}
if got := payload["reason"]; got != activeWorkspaceNotFoundError() {
t.Fatalf("reason = %v, want %q", got, activeWorkspaceNotFoundError())
}
if got := payload["suggestion"]; got != diagHint() {
t.Fatalf("suggestion = %v, want %q", got, diagHint())
}
}
func TestDetectBootstrapAction_ServerModeMissingConfiguredDBDoesNotReturnNone(t *testing.T) {
t.Setenv("BEADS_DOLT_DATA_DIR", "")
t.Setenv("BEADS_DOLT_SERVER_DATABASE", "")

View file

@ -750,8 +750,7 @@ func runCompactDolt() {
// Find beads directory
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
fmt.Fprintf(os.Stderr, "Error: could not find .beads directory\n")
os.Exit(1)
FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
// Check for dolt directory

View file

@ -3,7 +3,6 @@ package main
import (
"context"
"fmt"
"path/filepath"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/beads"
@ -22,13 +21,9 @@ func issueIDCompletion(cmd *cobra.Command, args []string, toComplete string) ([]
// Get database path - use same logic as in PersistentPreRun
currentDBPath := dbPath
if currentDBPath == "" {
// Try to find database path
foundDB := beads.FindDatabasePath()
if foundDB != "" {
currentDBPath = foundDB
} else {
// Default path
currentDBPath = filepath.Join(".beads", beads.CanonicalDatabaseName)
currentDBPath = beads.FindDatabasePath()
if currentDBPath == "" {
return nil, cobra.ShellCompDirectiveNoFileComp
}
}

View file

@ -5,6 +5,7 @@ package main
import (
"context"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
@ -217,6 +218,90 @@ func TestIssueIDCompletion_NoStore(t *testing.T) {
}
}
func TestIssueIDCompletion_UsesWorktreeFallbackWhenStoreNil(t *testing.T) {
originalStore := store
originalDBPath := dbPath
originalRootCtx := rootCtx
defer func() {
store = originalStore
dbPath = originalDBPath
rootCtx = originalRootCtx
}()
ctx := context.Background()
rootCtx = ctx
tmpDir := t.TempDir()
mainRepoDir := filepath.Join(tmpDir, "main-repo")
if err := os.MkdirAll(mainRepoDir, 0o755); err != nil {
t.Fatalf("mkdir main repo: %v", err)
}
run := func(dir string, args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = dir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git %v failed: %v\n%s", args, err, out)
}
}
run(mainRepoDir, "init")
run(mainRepoDir, "config", "user.email", "test@example.com")
run(mainRepoDir, "config", "user.name", "Test User")
if err := os.WriteFile(filepath.Join(mainRepoDir, "README.md"), []byte("# Test\n"), 0o644); err != nil {
t.Fatalf("write README: %v", err)
}
run(mainRepoDir, "add", "README.md")
run(mainRepoDir, "commit", "-m", "Initial commit")
worktreeDir := filepath.Join(tmpDir, "worktree")
cmd := exec.Command("git", "worktree", "add", worktreeDir, "HEAD")
cmd.Dir = mainRepoDir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git worktree add failed: %v\n%s", err, out)
}
t.Cleanup(func() {
cleanupCmd := exec.Command("git", "worktree", "remove", "--force", worktreeDir)
cleanupCmd.Dir = mainRepoDir
_ = cleanupCmd.Run()
})
testDB := filepath.Join(mainRepoDir, ".beads", "beads.db")
testStore := newTestStoreWithPrefix(t, testDB, "wt")
if err := testStore.CreateIssue(ctx, &types.Issue{
ID: "wt-abc1",
Title: "Worktree completion target",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}, "test"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
store = nil
dbPath = ""
t.Chdir(worktreeDir)
beads.ResetCaches()
git.ResetCaches()
t.Cleanup(func() {
beads.ResetCaches()
git.ResetCaches()
})
completions, directive := issueIDCompletion(&cobra.Command{}, nil, "wt-a")
if directive != cobra.ShellCompDirectiveNoFileComp {
t.Fatalf("directive = %d, want %d", directive, cobra.ShellCompDirectiveNoFileComp)
}
if len(completions) != 1 {
t.Fatalf("len(completions) = %d, want 1 (%v)", len(completions), completions)
}
if len(completions[0]) < len("wt-abc1") || completions[0][:len("wt-abc1")] != "wt-abc1" {
t.Fatalf("completion = %q, want prefix %q", completions[0], "wt-abc1")
}
}
func TestCompleteCommandWorksWithoutDatabase(t *testing.T) {
// This test verifies that shell completions work even without a beads database.
// The __complete command must be in noDbCommands list so that PersistentPreRun

View file

@ -436,21 +436,13 @@ Checks:
- Remote URL format is valid (dolthub://, gs://, s3://, az://, file://)
- routing.mode is valid (auto, maintainer, contributor, explicit)
Examples:
bd config validate
bd config validate --json`,
Examples:
bd config validate
bd config validate --json`,
Run: func(cmd *cobra.Command, args []string) {
cwd, err := os.Getwd()
repoPath, err := resolvedConfigRepoRoot()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
// Find repo root by walking up to find .beads directory
repoPath := findBeadsRepoRoot(cwd)
if repoPath == "" {
fmt.Fprintf(os.Stderr, "Error: not in a beads repository (no .beads directory found)\n")
os.Exit(1)
FatalErrorWithHintRespectJSON(activeWorkspaceNotFoundError(), diagHint())
}
// Run the existing doctor config values check
@ -563,6 +555,17 @@ func findBeadsRepoRoot(startPath string) string {
return ""
}
// resolvedConfigRepoRoot returns the repository root for the active beads
// workspace. It follows FindBeadsDir semantics, including BEADS_DIR and
// worktree/shared fallback resolution.
func resolvedConfigRepoRoot() (string, error) {
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
return "", fmt.Errorf("%s", activeWorkspaceNotFoundError())
}
return filepath.Dir(beadsDir), nil
}
var configSetManyCmd = &cobra.Command{
Use: "set-many <key=value>...",
Short: "Set multiple configuration values in one operation",

View file

@ -155,7 +155,7 @@ func applyRemote(drifted bool, dryRun bool) ApplyResult {
Check: "remote",
Action: "configure",
Status: applyStatusSkipped,
Message: "No .beads directory found",
Message: "No active beads workspace found",
}
}
@ -259,7 +259,7 @@ func applyServer(drifted bool, dryRun bool) ApplyResult {
Check: "server",
Action: "start",
Status: applyStatusSkipped,
Message: "No .beads directory found",
Message: "No active beads workspace found",
}
}

View file

@ -149,7 +149,7 @@ func checkRemoteDrift() []DriftItem {
return []DriftItem{{
Check: "remote",
Status: driftStatusSkipped,
Message: "No .beads directory found",
Message: "No active beads workspace found",
}}
}
@ -234,7 +234,7 @@ func checkServerDrift() []DriftItem {
return []DriftItem{{
Check: "server",
Status: driftStatusSkipped,
Message: "No .beads directory found",
Message: "No active beads workspace found",
}}
}

View file

@ -0,0 +1,165 @@
//go:build cgo
package main
import (
"bytes"
"encoding/json"
"os"
"os/exec"
"strings"
"testing"
)
func runConfigCommandWithStreams(t *testing.T, bd, dir string, args ...string) (stdout string, stderr string, err error) {
t.Helper()
fullArgs := append([]string{"config"}, args...)
cmd := exec.Command(bd, fullArgs...)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
var stdoutBuf bytes.Buffer
var stderrBuf bytes.Buffer
cmd.Stdout = &stdoutBuf
cmd.Stderr = &stderrBuf
err = cmd.Run()
return stdoutBuf.String(), stderrBuf.String(), err
}
func assertNoStoreInitLeak(t *testing.T, stderr string) {
t.Helper()
for _, needle := range []string{
"database name may default incorrectly",
"failed to open database",
"no database selected",
} {
if strings.Contains(stderr, needle) {
t.Fatalf("unexpected low-level store init output %q in stderr:\n%s", needle, stderr)
}
}
}
func TestEmbeddedConfigNoWorkspaceStoreFreeCommands(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir := t.TempDir()
t.Run("get_yaml_only", func(t *testing.T) {
stdout, stderr, err := runConfigCommandWithStreams(t, bd, dir, "get", "no-db")
if err != nil {
t.Fatalf("config get no-db failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
}
assertNoStoreInitLeak(t, stderr)
if strings.TrimSpace(stderr) != "" {
t.Fatalf("expected no stderr for config get no-db, got:\n%s", stderr)
}
got := strings.TrimSpace(stdout)
if got != "false" && !strings.Contains(got, "not set in config.yaml") {
t.Fatalf("expected yaml-only config lookup result, got stdout:\n%s", stdout)
}
})
t.Run("set_yaml_only_reports_config_yaml_error", func(t *testing.T) {
stdout, stderr, err := runConfigCommandWithStreams(t, bd, dir, "set", "no-db", "true")
if err == nil {
t.Fatalf("expected config set no-db to fail without a workspace config, stdout:\n%s\nstderr:\n%s", stdout, stderr)
}
assertNoStoreInitLeak(t, stderr)
if !strings.Contains(stderr, "no .beads/config.yaml found") {
t.Fatalf("expected config.yaml error, got stderr:\n%s", stderr)
}
})
t.Run("show_json", func(t *testing.T) {
stdout, stderr, err := runConfigCommandWithStreams(t, bd, dir, "show", "--json")
if err != nil {
t.Fatalf("config show --json failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
}
assertNoStoreInitLeak(t, stderr)
if strings.TrimSpace(stderr) != "" {
t.Fatalf("expected no stderr for config show --json, got:\n%s", stderr)
}
var payload []map[string]any
if err := json.Unmarshal([]byte(stdout), &payload); err != nil {
t.Fatalf("parse config show --json output: %v\nstdout:\n%s", err, stdout)
}
if len(payload) == 0 {
t.Fatalf("expected config show --json to return entries, got empty payload")
}
})
t.Run("drift_json", func(t *testing.T) {
stdout, stderr, err := runConfigCommandWithStreams(t, bd, dir, "drift", "--json")
if err != nil {
t.Fatalf("config drift --json failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
}
assertNoStoreInitLeak(t, stderr)
if strings.TrimSpace(stderr) != "" {
t.Fatalf("expected no stderr for config drift --json, got:\n%s", stderr)
}
var payload []map[string]any
if err := json.Unmarshal([]byte(stdout), &payload); err != nil {
t.Fatalf("parse config drift --json output: %v\nstdout:\n%s", err, stdout)
}
if len(payload) == 0 {
t.Fatalf("expected config drift --json to return checks, got empty payload")
}
})
t.Run("apply_json", func(t *testing.T) {
stdout, stderr, err := runConfigCommandWithStreams(t, bd, dir, "apply", "--json")
if err != nil {
t.Fatalf("config apply --json failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
}
assertNoStoreInitLeak(t, stderr)
if strings.TrimSpace(stderr) != "" {
t.Fatalf("expected no stderr for config apply --json, got:\n%s", stderr)
}
var payload []map[string]any
if err := json.Unmarshal([]byte(stdout), &payload); err != nil {
t.Fatalf("parse config apply --json output: %v\nstdout:\n%s", err, stdout)
}
if len(payload) == 0 {
t.Fatalf("expected config apply --json to return results, got empty payload")
}
})
}
func TestEmbeddedConfigValidateJSONNoWorkspaceWritesStdout(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir := t.TempDir()
stdout, stderr, err := runConfigCommandWithStreams(t, bd, dir, "validate", "--json")
if err == nil {
t.Fatalf("expected config validate --json to fail without a workspace, stdout:\n%s\nstderr:\n%s", stdout, stderr)
}
assertNoStoreInitLeak(t, stderr)
if strings.TrimSpace(stderr) != "" {
t.Fatalf("expected JSON error on stdout only, got stderr:\n%s", stderr)
}
var payload map[string]string
if err := json.Unmarshal([]byte(stdout), &payload); err != nil {
t.Fatalf("parse config validate --json output: %v\nstdout:\n%s", err, stdout)
}
if payload["error"] != activeWorkspaceNotFoundError() {
t.Fatalf("error = %q, want %q", payload["error"], activeWorkspaceNotFoundError())
}
if !strings.Contains(payload["hint"], "bd where") {
t.Fatalf("expected hint to mention bd where, got %q", payload["hint"])
}
}

View file

@ -10,7 +10,9 @@ import (
"strings"
"testing"
"github.com/steveyegge/beads/internal/beads"
"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"
)
@ -420,40 +422,100 @@ federation:
})
}
// TestFindBeadsRepoRoot tests the repo root finding function
func TestFindBeadsRepoRoot(t *testing.T) {
// Create a temp directory structure
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
subDir := filepath.Join(tmpDir, "sub", "dir")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("Failed to create .beads dir: %v", err)
}
if err := os.MkdirAll(subDir, 0755); err != nil {
t.Fatalf("Failed to create sub dir: %v", err)
func TestResolvedConfigRepoRoot(t *testing.T) {
resetResolutionCaches := func(t *testing.T) {
t.Helper()
beads.ResetCaches()
git.ResetCaches()
t.Cleanup(func() {
beads.ResetCaches()
git.ResetCaches()
})
}
t.Run("from repo root", func(t *testing.T) {
got := findBeadsRepoRoot(tmpDir)
if got != tmpDir {
t.Errorf("findBeadsRepoRoot(%q) = %q, want %q", tmpDir, got, tmpDir)
assertSameResolvedPath := func(t *testing.T, got, want string) {
t.Helper()
gotResolved, err := filepath.EvalSymlinks(got)
if err != nil {
t.Fatalf("EvalSymlinks(%q): %v", got, err)
}
wantResolved, err := filepath.EvalSymlinks(want)
if err != nil {
t.Fatalf("EvalSymlinks(%q): %v", want, err)
}
if gotResolved != wantResolved {
t.Errorf("resolvedConfigRepoRoot() = %q (resolved %q), want %q (resolved %q)", got, gotResolved, want, wantResolved)
}
}
t.Run("uses local workspace from subdirectory", func(t *testing.T) {
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
subDir := filepath.Join(tmpDir, "sub", "dir")
if err := os.MkdirAll(beadsDir, 0o755); err != nil {
t.Fatalf("Failed to create .beads dir: %v", err)
}
if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(`{"backend":"dolt"}`), 0o644); err != nil {
t.Fatalf("Failed to create metadata.json: %v", err)
}
if err := os.MkdirAll(subDir, 0o755); err != nil {
t.Fatalf("Failed to create sub dir: %v", err)
}
t.Chdir(subDir)
resetResolutionCaches(t)
got, err := resolvedConfigRepoRoot()
if err != nil {
t.Fatalf("resolvedConfigRepoRoot returned error: %v", err)
}
assertSameResolvedPath(t, got, tmpDir)
})
t.Run("from subdirectory", func(t *testing.T) {
got := findBeadsRepoRoot(subDir)
if got != tmpDir {
t.Errorf("findBeadsRepoRoot(%q) = %q, want %q", subDir, got, tmpDir)
t.Run("uses BEADS_DIR target", func(t *testing.T) {
cwdDir := t.TempDir()
targetRepo := t.TempDir()
targetBeadsDir := filepath.Join(targetRepo, ".beads")
if err := os.MkdirAll(targetBeadsDir, 0o755); err != nil {
t.Fatalf("Failed to create target .beads dir: %v", err)
}
if err := os.WriteFile(filepath.Join(targetBeadsDir, "metadata.json"), []byte(`{"backend":"dolt"}`), 0o644); err != nil {
t.Fatalf("Failed to create target metadata.json: %v", err)
}
t.Setenv("BEADS_DIR", targetBeadsDir)
t.Chdir(cwdDir)
resetResolutionCaches(t)
got, err := resolvedConfigRepoRoot()
if err != nil {
t.Fatalf("resolvedConfigRepoRoot returned error: %v", err)
}
assertSameResolvedPath(t, got, targetRepo)
})
t.Run("not in repo", func(t *testing.T) {
noRepoDir := t.TempDir()
got := findBeadsRepoRoot(noRepoDir)
if got != "" {
t.Errorf("findBeadsRepoRoot(%q) = %q, want empty string", noRepoDir, got)
t.Run("uses worktree fallback when local .beads is absent", func(t *testing.T) {
bareDir, worktreeDir := setupBareParentInitWorktree(t)
bareBeadsDir := filepath.Join(bareDir, ".beads")
if err := os.MkdirAll(bareBeadsDir, 0o755); err != nil {
t.Fatalf("Failed to create bare .beads dir: %v", err)
}
if err := os.WriteFile(filepath.Join(bareBeadsDir, "metadata.json"), []byte(`{"backend":"dolt"}`), 0o644); err != nil {
t.Fatalf("Failed to create bare metadata.json: %v", err)
}
t.Chdir(worktreeDir)
resetResolutionCaches(t)
got, err := resolvedConfigRepoRoot()
if err != nil {
t.Fatalf("resolvedConfigRepoRoot returned error: %v", err)
}
assertSameResolvedPath(t, got, bareDir)
})
}

View file

@ -57,7 +57,12 @@ func commitFile(t *testing.T, dir, name, content, msg string) {
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
t.Fatalf("write file: %v", err)
}
runGit(t, dir, "add", name)
addArgs := []string{"add"}
if name == ".beads" || strings.HasPrefix(name, ".beads/") {
addArgs = append(addArgs, "-f")
}
addArgs = append(addArgs, name)
runGit(t, dir, addArgs...)
runGit(t, dir, "commit", "-m", msg)
}

View file

@ -60,12 +60,12 @@ func CheckMigrationReadiness(path string) (DoctorCheck, MigrationValidationResul
// Check if .beads exists
if _, err := os.Stat(beadsDir); os.IsNotExist(err) {
result.Ready = false
result.Errors = append(result.Errors, "No .beads directory found")
result.Errors = append(result.Errors, "No active beads workspace found")
return DoctorCheck{
Name: "Migration Readiness",
Status: StatusError,
Message: "No beads installation found",
Fix: "Run 'bd init' first to create a beads installation",
Message: "No active beads workspace found",
Fix: "Run 'bd where' to inspect the resolved workspace, or 'bd init' to create a beads installation",
Category: CategoryMaintenance,
}, result
}
@ -173,11 +173,11 @@ func CheckMigrationCompletion(path string) (DoctorCheck, MigrationValidationResu
if _, err := os.Stat(beadsDir); os.IsNotExist(err) {
result.Ready = false
result.DoltHealthy = false
result.Errors = append(result.Errors, "No .beads directory found")
result.Errors = append(result.Errors, "No active beads workspace found")
return DoctorCheck{
Name: "Migration Completion",
Status: StatusError,
Message: "No beads installation found",
Message: "No active beads workspace found",
Category: CategoryMaintenance,
}, result
}

View file

@ -358,8 +358,7 @@ required. Use this command for explicit control or diagnostics.`,
}
beadsDir := selectedDoltBeadsDir()
if beadsDir == "" {
fmt.Fprintf(os.Stderr, "Error: not in a beads repository (no .beads directory found)\n")
os.Exit(1)
FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
serverDir := doltserver.ResolveServerDir(beadsDir)
@ -396,8 +395,7 @@ on the next bd command unless auto-start is disabled.`,
}
beadsDir := selectedDoltBeadsDir()
if beadsDir == "" {
fmt.Fprintf(os.Stderr, "Error: not in a beads repository (no .beads directory found)\n")
os.Exit(1)
FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
serverDir := doltserver.ResolveServerDir(beadsDir)
force, _ := cmd.Flags().GetBool("force")
@ -423,8 +421,7 @@ Displays whether the server is running, its PID, port, and data directory.`,
}
beadsDir := selectedDoltBeadsDir()
if beadsDir == "" {
fmt.Fprintf(os.Stderr, "Error: not in a beads repository (no .beads directory found)\n")
os.Exit(1)
FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
serverDir := doltserver.ResolveServerDir(beadsDir)
@ -1037,8 +1034,7 @@ func selectedDoltBeadsDir() string {
func showDoltConfig(testConnection bool) {
beadsDir := selectedDoltBeadsDir()
if beadsDir == "" {
fmt.Fprintf(os.Stderr, "Error: not in a beads repository (no .beads directory found)\n")
os.Exit(1)
FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
cfg, err := configfile.Load(beadsDir)
@ -1157,8 +1153,7 @@ func showDoltConfig(testConnection bool) {
func setDoltConfig(key, value string, updateConfig bool) {
beadsDir := selectedDoltBeadsDir()
if beadsDir == "" {
fmt.Fprintf(os.Stderr, "Error: not in a beads repository (no .beads directory found)\n")
os.Exit(1)
FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
cfg, err := configfile.Load(beadsDir)
@ -1320,8 +1315,7 @@ func setDoltConfig(key, value string, updateConfig bool) {
func testDoltConnection() {
beadsDir := selectedDoltBeadsDir()
if beadsDir == "" {
fmt.Fprintf(os.Stderr, "Error: not in a beads repository (no .beads directory found)\n")
os.Exit(1)
FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
cfg, err := configfile.Load(beadsDir)
@ -1489,8 +1483,7 @@ func testHTTPConnectivity(url string) bool {
func openDoltServerConnection() (*sql.DB, func()) {
beadsDir := selectedDoltBeadsDir()
if beadsDir == "" {
fmt.Fprintln(os.Stderr, "Error: not in a beads repository (no .beads directory found)")
os.Exit(1)
FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
cfg, err := configfile.Load(beadsDir)

View file

@ -25,7 +25,7 @@ type pushState struct {
func pushStatePath() (string, error) {
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
return "", fmt.Errorf("not in a beads repository")
return "", fmt.Errorf("%s", activeWorkspaceNotFoundError())
}
return filepath.Join(beadsDir, "push-state.json"), nil
}

View file

@ -6,13 +6,36 @@ import (
"os"
)
// diagHint returns the appropriate diagnostic hint for the current mode.
// In embedded mode, 'bd doctor' is not available so the hint omits it.
func activeWorkspaceNotFoundError() string {
return "no active beads workspace found"
}
func activeWorkspaceNotFoundMessage() string {
return "No active beads workspace found."
}
// diagHint returns the appropriate diagnostic hint when the active beads
// workspace cannot be resolved. In embedded mode, 'bd doctor' is not
// available so the hint omits it.
func diagHint() string {
if isEmbeddedMode() {
return "run 'bd init' to create a new database"
return workspaceDiagHint(true)
}
func whereDiagHint() string {
return workspaceDiagHint(false)
}
func workspaceDiagHint(includeWhere bool) string {
if includeWhere {
if isEmbeddedMode() {
return "run 'bd where' to inspect the resolved workspace, or 'bd init' to create a new database"
}
return "run 'bd where' to inspect the resolved workspace, run 'bd doctor' to diagnose, or 'bd init' to create a new database"
}
return "run 'bd doctor' to diagnose, or 'bd init' to create a new database"
if isEmbeddedMode() {
return "check BEADS_DIR/worktree setup, or run 'bd init' to create a new database"
}
return "check BEADS_DIR/worktree setup, run 'bd doctor' to diagnose, or run 'bd init' to create a new database"
}
// FatalError writes an error message to stderr and exits with code 1.
@ -61,6 +84,18 @@ func FatalErrorRespectJSON(format string, args ...interface{}) {
os.Exit(1)
}
// FatalErrorWithHintRespectJSON writes an error message with a hint and exits.
// If --json is set, emits structured JSON to stdout so callers can parse it.
func FatalErrorWithHintRespectJSON(message, hint string) {
if jsonOutput {
outputJSON(map[string]string{"error": message, "hint": hint})
} else {
fmt.Fprintf(os.Stderr, "Error: %s\n", message)
fmt.Fprintf(os.Stderr, "Hint: %s\n", hint)
}
os.Exit(1)
}
// FatalErrorWithHint writes an error message with a hint to stderr and exits.
// Use this when you can provide an actionable suggestion to fix the error.
//

View file

@ -548,7 +548,7 @@ func installHooksWithOptions(hookNames []string, force bool, shared bool, chain
// Use .beads/hooks/ directory (preferred for Dolt backend)
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
return fmt.Errorf("not in a beads workspace (no .beads directory found)")
return fmt.Errorf("%s", activeWorkspaceNotFoundError())
}
hooksDir = filepath.Join(beadsDir, "hooks")
} else if shared {

View file

@ -53,7 +53,7 @@ func runImport(cmd *cobra.Command, args []string) error {
// Default: .beads/issues.jsonl
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
return fmt.Errorf("no .beads directory found — run 'bd init' first")
return fmt.Errorf("%s — %s", activeWorkspaceNotFoundError(), diagHint())
}
jsonlPath = filepath.Join(beadsDir, "issues.jsonl")
}

View file

@ -244,11 +244,14 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
prefix = filepath.Base(cwd)
}
// Normalize prefix: strip leading dots and trailing hyphens.
// Leading dots produce invalid Dolt database names (e.g. ".claude" -> "bd_.claude").
// The trailing hyphen is added automatically during ID generation.
// Normalize prefix before storing it in config or deriving the Dolt
// database name. Dots are not valid in issue prefixes and must match the
// underscore form used for DoltDatabase/metadata.json.
// Leading dots produce invalid names (e.g. ".claude" -> "claude"), and
// the trailing hyphen is added automatically during ID generation.
prefix = strings.TrimLeft(prefix, ".")
prefix = strings.TrimRight(prefix, "-")
prefix = strings.ReplaceAll(prefix, ".", "_")
// Sanitize prefix for use as a MySQL database name.
// Directory names like "001" (common in temp dirs) are invalid because

View file

@ -606,6 +606,9 @@ func TestEmbeddedInit(t *testing.T) {
if cfg.DoltDatabase != want {
t.Errorf("DoltDatabase: got %q, want %q (dot must be sanitized)", cfg.DoltDatabase, want)
}
if val := readBack(t, beadsDir, want, "issue_prefix", false); val != want {
t.Errorf("issue_prefix: got %q, want %q", val, want)
}
// Verify bd list succeeds — confirms the database name in metadata.json
// matches the actual Dolt database created during init.

View file

@ -251,6 +251,42 @@ func isSelectedNoDBCommand(cmd *cobra.Command) bool {
}
}
// configCommandCanRunWithoutStore returns true for config subcommands whose Run
// path can execute without an opened Dolt store. This lets no-workspace calls
// fail or degrade in the command itself instead of tripping low-level DB init.
func configCommandCanRunWithoutStore(cmd *cobra.Command, args []string) bool {
if cmd == nil || cmd.Parent() == nil || cmd.Parent().Name() != "config" {
return false
}
switch cmd.Name() {
case "show", "validate", "drift", "apply":
return true
case "set", "get", "unset":
if len(args) == 0 {
return true
}
key := args[0]
return config.IsYamlOnlyKey(key) || key == "beads.role"
case "set-many":
if len(args) == 0 {
return true
}
for _, arg := range args {
key, _, ok := strings.Cut(arg, "=")
if !ok || key == "" {
return true
}
if !config.IsYamlOnlyKey(key) && key != "beads.role" {
return false
}
}
return true
default:
return false
}
}
func prepareSelectedNoDBContext(beadsDir string) {
if beadsDir == "" {
return
@ -548,6 +584,7 @@ var rootCmd = &cobra.Command{
"quickstart",
"setup",
"version",
"where",
"zsh",
}
@ -626,19 +663,13 @@ var rootCmd = &cobra.Command{
// No database found — allow some commands to run without a database
// - import: auto-initializes database if missing
// - setup: creates editor integration files (no DB needed)
// - config set/get for yaml-only keys: writes to config.yaml, not db (GH#536)
// - config show/validate/drift/apply: read-only diagnostics, degrade gracefully (bd-934, bd-omc, bd-3rw)
isYamlOnlyConfigOp := false
if cmd.Parent() != nil && cmd.Parent().Name() == "config" {
if (cmd.Name() == "set" || cmd.Name() == "get") && len(args) > 0 && config.IsYamlOnlyKey(args[0]) {
isYamlOnlyConfigOp = true
}
if cmd.Name() == "show" || cmd.Name() == "validate" || cmd.Name() == "drift" || cmd.Name() == "apply" {
isYamlOnlyConfigOp = true
}
// - config subcommands that operate on config.yaml, git config,
// or best-effort diagnostics only (GH#536, bd-934, bd-omc, bd-3rw)
if configCommandCanRunWithoutStore(cmd, args) {
return
}
if cmd.Name() != "import" && cmd.Name() != "setup" && !isYamlOnlyConfigOp {
if cmd.Name() != "import" && cmd.Name() != "setup" {
// No database found - provide context-aware error message
fmt.Fprintf(os.Stderr, "Error: no beads database found\n")
fmt.Fprintf(os.Stderr, "Hint: %s\n", diagHint())

View file

@ -56,11 +56,11 @@ Subcommands:
if jsonOutput {
outputJSON(map[string]interface{}{
"error": "no_beads_directory",
"message": "No .beads directory found. " + diagHint() + ".",
"message": activeWorkspaceNotFoundMessage() + " " + diagHint() + ".",
})
os.Exit(1)
} else {
FatalErrorWithHint("no .beads directory found", diagHint())
FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
}
@ -404,11 +404,11 @@ func handleInspect() {
if jsonOutput {
outputJSON(map[string]interface{}{
"error": "no_beads_directory",
"message": "No .beads directory found. " + diagHint() + ".",
"message": activeWorkspaceNotFoundMessage() + " " + diagHint() + ".",
})
os.Exit(1)
}
FatalErrorWithHint("no .beads directory found", diagHint())
FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
// Check if database is available via the global store
@ -549,11 +549,11 @@ func handleToSeparateBranch(branch string, dryRun bool) {
if jsonOutput {
outputJSON(map[string]interface{}{
"error": "no_beads_directory",
"message": "No .beads directory found. " + diagHint() + ".",
"message": activeWorkspaceNotFoundMessage() + " " + diagHint() + ".",
})
os.Exit(1)
}
FatalErrorWithHint("no .beads directory found", diagHint())
FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
store := getStore()

View file

@ -61,11 +61,11 @@ Config options:
Set via: bd config set no-git-ops true
Useful when you want to control when commits happen manually.
Workflow customization:
- Place a .beads/PRIME.md file to override the default output entirely.
- Use --export to dump the default content for customization.`,
Workflow customization:
- Place a .beads/PRIME.md file in the local clone or resolved workspace to override the default output entirely.
- Use --export to dump the default content for customization.`,
Run: func(cmd *cobra.Command, args []string) {
// Find .beads/ directory
// Resolve the active beads workspace.
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
// Not in a beads project - silent exit with success
@ -89,7 +89,8 @@ Workflow customization:
// Check for custom PRIME.md override (unless --export flag)
// This allows users to fully customize workflow instructions
// Check local .beads/ first (even if redirected), then redirected location
// Check local .beads/ first (clone-specific override), then the
// resolved workspace location.
if !primeExportMode {
localPrimePath := filepath.Join(".beads", "PRIME.md")
redirectedPrimePath := filepath.Join(beadsDir, "PRIME.md")
@ -410,7 +411,7 @@ git push # Push to remote
context := `# Beads Workflow Context
> **Context Recovery**: Run ` + "`bd prime`" + ` after compaction, clear, or new session
> Hooks auto-call this in Claude Code when .beads/ detected
> Hooks auto-call this in Claude Code when a beads workspace is resolved
` + redirectNotice + `# 🚨 SESSION CLOSE PROTOCOL 🚨

View file

@ -174,6 +174,24 @@ func TestPrimeClaimGuidanceUsesAtomicClaim(t *testing.T) {
}
}
func TestPrimeContextUsesWorkspaceLanguage(t *testing.T) {
defer stubIsEphemeralBranch(false)()
defer stubPrimeHasGitRemote(true)()
var buf bytes.Buffer
if err := outputPrimeContext(&buf, false, false); err != nil {
t.Fatalf("outputPrimeContext failed: %v", err)
}
output := buf.String()
if !strings.Contains(output, "resolved") || !strings.Contains(output, "workspace") {
t.Fatalf("prime output should describe resolved workspace semantics: %s", output)
}
if strings.Contains(output, "when .beads/ detected") {
t.Fatal("prime output should not imply local .beads detection is required")
}
}
// stubIsEphemeralBranch temporarily replaces isEphemeralBranch
// with a stub returning returnValue.
//

View file

@ -68,7 +68,7 @@ shared across all clones of this repository.`,
beadsDir := filepath.Join(expandedPath, ".beads")
if _, err := os.Stat(beadsDir); os.IsNotExist(err) {
return fmt.Errorf("no .beads directory found at %s - is this a beads repository?", expandedPath)
return fmt.Errorf("no beads workspace found at %s", expandedPath)
}
}

View file

@ -93,12 +93,48 @@ func runSetup(cmd *cobra.Command, args []string) {
runRecipe(recipeName)
}
func listRecipes() {
func setupWorkspaceError() error {
return fmt.Errorf("%s; %s", activeWorkspaceNotFoundError(), diagHint())
}
func builtinSetupRecipes() map[string]recipes.Recipe {
allRecipes := make(map[string]recipes.Recipe, len(recipes.BuiltinRecipes))
for name, recipe := range recipes.BuiltinRecipes {
allRecipes[name] = recipe
}
return allRecipes
}
func loadSetupRecipes() (map[string]recipes.Recipe, bool, error) {
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
beadsDir = ".beads"
return builtinSetupRecipes(), false, nil
}
allRecipes, err := recipes.GetAllRecipes(beadsDir)
if err != nil {
return nil, false, err
}
return allRecipes, true, nil
}
func lookupSetupRecipe(name string) (*recipes.Recipe, error) {
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
normalized := strings.ToLower(strings.Trim(name, "-"))
recipe, ok := recipes.BuiltinRecipes[normalized]
if !ok {
return nil, fmt.Errorf("unknown recipe: %s (workspace-local custom recipes require an active beads workspace)", normalized)
}
resolved := recipe
return &resolved, nil
}
return recipes.GetRecipe(name, beadsDir)
}
func listRecipes() {
allRecipes, usingWorkspaceRecipes, err := loadSetupRecipes()
if err != nil {
FatalError("loading recipes: %v", err)
}
@ -121,6 +157,11 @@ func listRecipes() {
fmt.Printf(" %-12s %-25s (%s)\n", name, r.Description, source)
}
fmt.Println()
if !usingWorkspaceRecipes {
fmt.Printf("Note: %s Showing built-in recipes only.\n", activeWorkspaceNotFoundMessage())
fmt.Printf("Hint: %s\n", diagHint())
fmt.Println()
}
fmt.Println("Use 'bd setup <recipe>' to install.")
fmt.Println("Use 'bd setup --add <name> <path>' to add a custom recipe.")
}
@ -143,7 +184,7 @@ func writeToPath(path string) error {
func addRecipe(name, path string) error {
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
beadsDir = ".beads"
return setupWorkspaceError()
}
if err := recipes.SaveUserRecipe(beadsDir, name, path); err != nil {
@ -190,11 +231,7 @@ func runRecipe(name string) {
}
// For all other recipes (built-in or user), use generic file-based install
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
beadsDir = ".beads"
}
recipe, err := recipes.GetRecipe(name, beadsDir)
recipe, err := lookupSetupRecipe(name)
if err != nil {
FatalErrorWithHint(fmt.Sprintf("%v", err), "Use 'bd setup --list' to see available recipes.")
}

187
cmd/bd/setup_test.go Normal file
View file

@ -0,0 +1,187 @@
//go:build cgo
package main
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/git"
"github.com/steveyegge/beads/internal/recipes"
)
func resetSetupResolutionCaches(t *testing.T) {
t.Helper()
beads.ResetCaches()
git.ResetCaches()
t.Cleanup(func() {
beads.ResetCaches()
git.ResetCaches()
})
}
func resetSetupGlobals(t *testing.T) {
t.Helper()
originalProject := setupProject
originalGlobal := setupGlobal
originalCheck := setupCheck
originalRemove := setupRemove
originalStealth := setupStealth
originalPrint := setupPrint
originalOutput := setupOutput
originalList := setupList
originalAdd := setupAdd
setupProject = false
setupGlobal = false
setupCheck = false
setupRemove = false
setupStealth = false
setupPrint = false
setupOutput = ""
setupList = false
setupAdd = ""
t.Cleanup(func() {
setupProject = originalProject
setupGlobal = originalGlobal
setupCheck = originalCheck
setupRemove = originalRemove
setupStealth = originalStealth
setupPrint = originalPrint
setupOutput = originalOutput
setupList = originalList
setupAdd = originalAdd
})
}
func TestLoadSetupRecipes_NoWorkspaceUsesBuiltinsOnly(t *testing.T) {
tmpDir := t.TempDir()
orphanBeadsDir := filepath.Join(tmpDir, ".beads")
if err := recipes.SaveUserRecipe(orphanBeadsDir, "myeditor", ".myeditor/rules.md"); err != nil {
t.Fatalf("SaveUserRecipe: %v", err)
}
t.Chdir(tmpDir)
t.Setenv("BEADS_DIR", "")
resetSetupResolutionCaches(t)
allRecipes, usingWorkspaceRecipes, err := loadSetupRecipes()
if err != nil {
t.Fatalf("loadSetupRecipes: %v", err)
}
if usingWorkspaceRecipes {
t.Fatal("expected built-in-only recipe set without an active workspace")
}
if _, ok := allRecipes["cursor"]; !ok {
t.Fatal("expected built-in cursor recipe to be available")
}
if _, ok := allRecipes["myeditor"]; ok {
t.Fatal("unexpected orphan custom recipe outside active workspace")
}
}
func TestListRecipes_NoWorkspaceShowsBuiltinOnlyNote(t *testing.T) {
tmpDir := t.TempDir()
orphanBeadsDir := filepath.Join(tmpDir, ".beads")
if err := recipes.SaveUserRecipe(orphanBeadsDir, "myeditor", ".myeditor/rules.md"); err != nil {
t.Fatalf("SaveUserRecipe: %v", err)
}
t.Chdir(tmpDir)
t.Setenv("BEADS_DIR", "")
resetSetupResolutionCaches(t)
out := captureStdout(t, func() error {
listRecipes()
return nil
})
if !strings.Contains(out, "cursor") {
t.Fatalf("expected built-in recipes in output, got:\n%s", out)
}
if strings.Contains(out, "myeditor") {
t.Fatalf("unexpected orphan custom recipe in output:\n%s", out)
}
if !strings.Contains(out, "Note: No active beads workspace found. Showing built-in recipes only.") {
t.Fatalf("expected built-in-only note in output, got:\n%s", out)
}
if !strings.Contains(out, "Hint: "+diagHint()) {
t.Fatalf("expected diagnostic hint in output, got:\n%s", out)
}
}
func TestAddRecipe_NoWorkspaceReturnsActiveWorkspaceError(t *testing.T) {
tmpDir := t.TempDir()
t.Chdir(tmpDir)
t.Setenv("BEADS_DIR", "")
resetSetupResolutionCaches(t)
err := addRecipe("myeditor", ".myeditor/rules.md")
if err == nil {
t.Fatal("expected addRecipe to fail without active workspace")
}
if !strings.Contains(err.Error(), activeWorkspaceNotFoundError()) {
t.Fatalf("expected active-workspace error, got: %v", err)
}
if !strings.Contains(err.Error(), diagHint()) {
t.Fatalf("expected diagnostic hint, got: %v", err)
}
if _, statErr := os.Stat(filepath.Join(tmpDir, ".beads", "recipes.toml")); !os.IsNotExist(statErr) {
t.Fatalf("expected no local recipes.toml, got err=%v", statErr)
}
}
func TestLookupSetupRecipe_NoWorkspaceIgnoresOrphanCustomRecipes(t *testing.T) {
tmpDir := t.TempDir()
orphanBeadsDir := filepath.Join(tmpDir, ".beads")
if err := recipes.SaveUserRecipe(orphanBeadsDir, "myeditor", ".myeditor/rules.md"); err != nil {
t.Fatalf("SaveUserRecipe: %v", err)
}
t.Chdir(tmpDir)
t.Setenv("BEADS_DIR", "")
resetSetupResolutionCaches(t)
_, err := lookupSetupRecipe("myeditor")
if err == nil {
t.Fatal("expected custom recipe lookup to fail without active workspace")
}
if !strings.Contains(err.Error(), "workspace-local custom recipes require an active beads workspace") {
t.Fatalf("expected explicit no-workspace message, got: %v", err)
}
}
func TestRunRecipe_BuiltinFileRecipeWorksWithoutWorkspace(t *testing.T) {
tmpDir := t.TempDir()
t.Chdir(tmpDir)
t.Setenv("BEADS_DIR", "")
resetSetupResolutionCaches(t)
resetSetupGlobals(t)
out := captureStdout(t, func() error {
runRecipe("windsurf")
return nil
})
if !strings.Contains(out, "Installing Windsurf integration") {
t.Fatalf("expected install output, got:\n%s", out)
}
installedPath := filepath.Join(tmpDir, ".windsurf", "rules", "beads.md")
data, err := os.ReadFile(installedPath)
if err != nil {
t.Fatalf("ReadFile(%q): %v", installedPath, err)
}
if string(data) != recipes.Template {
t.Fatalf("installed recipe contents did not match template")
}
if _, err := os.Stat(filepath.Join(tmpDir, ".beads")); !os.IsNotExist(err) {
t.Fatalf("expected no local .beads directory to be created, got err=%v", err)
}
}

View file

@ -157,7 +157,8 @@ Examples:
Run: func(cmd *cobra.Command, args []string) {
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
fmt.Println("Error: No .beads directory found")
fmt.Println("Error: " + activeWorkspaceNotFoundMessage())
fmt.Println("Hint: " + diagHint())
return
}

View file

@ -24,8 +24,8 @@ var whereCmd = &cobra.Command{
Short: "Show active beads location",
Long: `Show the active beads database location, including redirect information.
This command is useful for debugging when using redirects, to understand
which .beads directory is actually being used.
This command is useful for debugging when using redirects, to understand
which beads workspace is actually being used.
Examples:
bd where # Show active beads location
@ -38,10 +38,14 @@ Examples:
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
if jsonOutput {
outputJSON(map[string]string{"error": "no beads directory found"})
outputJSON(map[string]string{
"error": "no_beads_directory",
"message": activeWorkspaceNotFoundMessage(),
"hint": whereDiagHint(),
})
} else {
fmt.Fprintln(os.Stderr, "Error: no beads directory found")
fmt.Fprintln(os.Stderr, "Hint: "+diagHint())
fmt.Fprintln(os.Stderr, "Error: "+activeWorkspaceNotFoundMessage())
fmt.Fprintln(os.Stderr, "Hint: "+whereDiagHint())
}
os.Exit(1)
}

View file

@ -26,6 +26,66 @@ func bdWhere(t *testing.T, bd, dir string, args ...string) string {
return string(out)
}
func bdWhereAllowError(t *testing.T, bd, dir string, args ...string) (string, error) {
t.Helper()
fullArgs := append([]string{"where"}, args...)
cmd := exec.Command(bd, fullArgs...)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
out, err := cmd.CombinedOutput()
return string(out), err
}
func TestWhereNoWorkspace(t *testing.T) {
t.Parallel()
bd := buildEmbeddedBD(t)
dir := t.TempDir()
t.Run("default_output", func(t *testing.T) {
out, err := bdWhereAllowError(t, bd, dir)
if err == nil {
t.Fatal("expected bd where to exit non-zero without a workspace")
}
if !strings.Contains(out, activeWorkspaceNotFoundMessage()) {
t.Fatalf("expected no-workspace message, got: %s", out)
}
if strings.Contains(out, "no beads database found") {
t.Fatalf("where should report workspace resolution failure, not database init failure: %s", out)
}
})
t.Run("json_output", func(t *testing.T) {
out, err := bdWhereAllowError(t, bd, dir, "--json")
if err == nil {
t.Fatal("expected bd where --json to exit non-zero without a workspace")
}
s := strings.TrimSpace(out)
start := strings.Index(s, "{")
if start < 0 {
t.Fatalf("expected JSON object in output, got: %s", out)
}
var payload map[string]string
if err := json.Unmarshal([]byte(s[start:]), &payload); err != nil {
t.Fatalf("parse where JSON: %v\n%s", err, s)
}
if payload["error"] != "no_beads_directory" {
t.Fatalf("error = %q, want %q", payload["error"], "no_beads_directory")
}
if payload["message"] != activeWorkspaceNotFoundMessage() {
t.Fatalf("message = %q, want %q", payload["message"], activeWorkspaceNotFoundMessage())
}
if !strings.Contains(payload["hint"], "BEADS_DIR/worktree setup") {
t.Fatalf("hint should mention workspace diagnostics, got: %q", payload["hint"])
}
if !strings.Contains(payload["hint"], "bd init") {
t.Fatalf("hint should mention bd init, got: %q", payload["hint"])
}
})
}
func TestEmbeddedWhere(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")

View file

@ -157,7 +157,7 @@ func runWorktreeCreate(cmd *cobra.Command, args []string) error {
// Get repository context (validates .beads exists and resolves paths)
rc, err := beads.GetRepoContext()
if err != nil {
return fmt.Errorf("no .beads directory found; %s: %w", diagHint(), err)
return fmt.Errorf("%s; %s: %w", activeWorkspaceNotFoundError(), diagHint(), err)
}
// Worktree operations use CWD repo (where user is working), not BEADS_DIR repo

View file

@ -20,9 +20,10 @@ Git worktrees share the same `.git` directory and `.beads` database:
### Worktree-Aware Features
**Database Discovery:**
- Searches main repository first for `.beads` directory
- Resolves the active workspace using `BEADS_DIR`, worktree fallback, and shared main-repo `.beads`
- Falls back to worktree-local search if needed
- Prevents database duplication across worktrees
- Use `bd where` as the authoritative check; local `./.beads` may be absent in pure worktree or redirected setups
**Git Operations:**
- Worktree-aware repository root detection

View file

@ -177,6 +177,7 @@ Creates or updates `AGENTS.md` with the beads integration section (same markers
### Notes
- Restart Codex if it's already running to pick up the new instructions.
- In worktree/shared/`BEADS_DIR` setups, use `bd where` to confirm the resolved workspace; the integration does not require a local `./.beads`.
## Mux
@ -268,6 +269,7 @@ The hooks call `bd prime` which:
1. Outputs workflow context for Claude to read
2. Syncs any pending changes
3. Ensures Claude always knows how to use beads
4. Follows resolved workspace semantics, so `bd where` is the right diagnostic check when local `./.beads` is absent
This is more context-efficient than MCP tools (~1-2k tokens vs 10-50k for MCP schemas).

View file

@ -1047,7 +1047,7 @@ func TestGitCmd_WorktreeContext(t *testing.T) {
t.Fatalf("failed to get relative path: %v", err)
}
addCmd := rc.GitCmd(ctx, "add", relPath)
addCmd := rc.GitCmd(ctx, "add", "-f", relPath)
addOutput, err := addCmd.CombinedOutput()
if err != nil {
t.Fatalf("GitCmd git add failed: %v\nOutput: %s", err, addOutput)