fix(beads): make an explicit BEADS_DIR authoritative during discovery (#6938)

* fix(beads): make an explicit BEADS_DIR authoritative during discovery

FindBeadsDir ignored a BEADS_DIR that did not hold project files yet
(missing, empty, or uninitialized) and walked up from the current
directory instead. PersistentPreRun then rebound BEADS_DIR to whatever
ancestor workspace the walk found, so:

- `bd init` refused with "already initialized" because of the parent
  workspace instead of initializing the named directory;
- data commands (`bd list`, `bd create`, ...) read and wrote the
  parent's store.

FindBeadsDir now returns "" for such a BEADS_DIR, matching
FindDatabasePath, which already refused to fall back. Commands that
create a workspace (import/setup default path, bootstrap's
fresh-clone synthesis) target the named directory via the new
beads.ExplicitBeadsDir helper instead of CWD. Behaviour with BEADS_DIR
unset is unchanged.

Tests: FindBeadsDir unit cases (missing/empty/non-project BEADS_DIR,
initialized BEADS_DIR, unset BEADS_DIR still walks up), and a bd
subprocess regression in embedded and proxied-server modes (init under
an initialized parent, list refuses, create lands in the new store).

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

* docs(changelog): note that BEADS_DIR at a project root now errors

Review follow-up for the explicit-BEADS_DIR fix: call out the behaviour
change for BEADS_DIR pointing at a project root (or a not-yet-created
.beads), which previously worked only because discovery walked up.

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Julian Knutsen 2026-09-29 02:26:09 -07:00 • committed by GitHub
commit 51a7c8e324
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 314 additions and 8 deletions

View file

@ -9,6 +9,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- **An explicit `BEADS_DIR` is authoritative during workspace discovery.**
When `BEADS_DIR` named a directory without project files yet (missing,
empty, or not initialized), discovery ignored it and walked up from the
current directory instead, then rebound `BEADS_DIR` to whatever ancestor
workspace it found. `bd init` refused with "already initialized" because of
the parent workspace, and data commands such as `bd create` and `bd list`
read and wrote the parent's store. Discovery now reports no workspace for
such a `BEADS_DIR`, so `bd init` initializes the named directory and other
commands fail with "no beads database found". `bd import`/`bd setup` and
`bd bootstrap` target the named directory when they create a workspace.
Behaviour with `BEADS_DIR` unset is unchanged. **Behaviour change:** a
`BEADS_DIR` that points at a project root rather than its `.beads`
directory (for example `BEADS_DIR=$repo` instead of `BEADS_DIR=$repo/.beads`),
or at a `.beads` that does not exist yet, used to work by accident because
discovery walked up to the nearest workspace; it now fails with "no beads
database found". Point `BEADS_DIR` at the `.beads` directory itself.
([#6938](https://github.com/gastownhall/beads/pull/6938))
- **A proxied workspace's proxy retires when its Dolt backend exits
cleanly.** The proxy noticed its `dolt sql-server` child exiting only when
the exit status was non-zero. A backend that shut down gracefully (for

View file

@ -791,6 +791,7 @@ go_test(
"init_cancel_e2e_test.go",
"init_commit_test.go",
"init_embedded_test.go",
"init_explicit_beads_dir_embedded_test.go",
"init_gateway_test.go",
"init_git_bootstrap_routing_test.go",
"init_guard_test.go",

View file

@ -190,7 +190,9 @@ Examples:
if isGitRepo() && !isBareGitRepo() {
if originURL, err := gitOriginGetURL(); err == nil && originURL != "" {
if gitOriginHasDoltDataRef() {
if fallbackDir := beads.GetWorktreeFallbackBeadsDir(); fallbackDir != "" {
if explicitDir := beads.ExplicitBeadsDir(); explicitDir != "" {
beadsDir = explicitDir
} else if fallbackDir := beads.GetWorktreeFallbackBeadsDir(); fallbackDir != "" {
beadsDir = fallbackDir
} else {
cwd, err := os.Getwd()

View file

@ -0,0 +1,146 @@
//go:build cgo
package main
import (
"bytes"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/storage/dbproxy/proxy"
)
// explicitBeadsDirMode describes how a storage mode's bd subprocesses are
// initialized and run for the explicit-BEADS_DIR regression tests.
type explicitBeadsDirMode struct {
initArgs []string
env func(home string) []string
proxied bool
}
// runExplicitBeadsDirBD runs bd in dir with the mode's isolated environment.
// beadsDir, when non-empty, is passed as an explicit BEADS_DIR.
func runExplicitBeadsDirBD(t *testing.T, bd string, mode explicitBeadsDirMode, home, dir, beadsDir string, args ...string) (string, string, error) {
t.Helper()
cmd := exec.Command(bd, args...)
cmd.Dir = dir
env := append(mode.env(home), "XDG_CONFIG_HOME="+filepath.Join(home, ".config"))
if beadsDir != "" {
env = append(env, "BEADS_DIR="+beadsDir)
}
cmd.Env = env
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
return stdout.String(), stderr.String(), err
}
// testExplicitBeadsDirIsAuthoritative covers the regression where an explicit
// BEADS_DIR without project files was ignored during discovery: bd walked up
// from CWD, bound the parent workspace, and `bd init` then refused ("already
// initialized") while data commands read and wrote the parent's store.
func testExplicitBeadsDirIsAuthoritative(t *testing.T, bd string, mode explicitBeadsDirMode) {
t.Helper()
home := t.TempDir()
parent := t.TempDir()
initGitRepoAt(t, parent)
parentBeadsDir := filepath.Join(parent, ".beads")
child := filepath.Join(parent, "child")
explicit := filepath.Join(child, ".beads")
if err := os.MkdirAll(child, 0o755); err != nil {
t.Fatal(err)
}
if mode.proxied {
for _, root := range []string{filepath.Join(parentBeadsDir, "dolt"), filepath.Join(explicit, "dolt")} {
root := root
t.Cleanup(func() {
if _, err := os.Stat(root); err != nil {
return
}
if err := proxy.Shutdown(root); err != nil {
t.Logf("proxy.Shutdown(%s): %v", root, err)
}
})
shutdownProxyOnInterrupt(t, root)
}
}
initArgs := append([]string{"init", "--quiet", "--non-interactive", "--skip-agents", "--skip-hooks"}, mode.initArgs...)
if stdout, stderr, err := runExplicitBeadsDirBD(t, bd, mode, home, parent, "", append(initArgs, "--prefix", "par")...); err != nil {
t.Fatalf("parent bd init: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
}
parentID, stderr, err := runExplicitBeadsDirBD(t, bd, mode, home, parent, "", "create", "--silent", "parent issue")
if err != nil {
t.Fatalf("parent bd create: %v\nstderr:\n%s", err, stderr)
}
parentID = strings.TrimSpace(parentID)
// A data command against the uninitialized explicit dir must not fall
// back to the parent workspace.
stdout, stderr, err := runExplicitBeadsDirBD(t, bd, mode, home, child, explicit, "list", "--json")
if err == nil || strings.Contains(stdout, parentID) {
t.Errorf("bd list with BEADS_DIR=%s (no workspace yet) should fail without reading the parent store; err=%v\nstdout:\n%s\nstderr:\n%s", explicit, err, stdout, stderr)
} else if !strings.Contains(stderr, "no beads database found") {
t.Errorf("bd list with an uninitialized BEADS_DIR: want \"no beads database found\", got stderr:\n%s", stderr)
}
// bd init must initialize the explicit dir (existing but empty, as a
// caller that pre-creates it would leave it), not refuse because of the
// parent workspace.
if err := os.MkdirAll(explicit, 0o755); err != nil {
t.Fatal(err)
}
if stdout, stderr, err := runExplicitBeadsDirBD(t, bd, mode, home, child, explicit, append(initArgs, "--prefix", "kid")...); err != nil {
t.Fatalf("bd init with BEADS_DIR=%s: %v\nstdout:\n%s\nstderr:\n%s", explicit, err, stdout, stderr)
}
childCfg, err := configfile.Load(explicit)
if err != nil || childCfg == nil {
t.Fatalf("load %s metadata: cfg=%v err=%v", explicit, childCfg, err)
}
if childCfg.DoltDatabase != "kid" {
t.Fatalf("explicit BEADS_DIR dolt_database = %q, want %q", childCfg.DoltDatabase, "kid")
}
parentCfg, err := configfile.Load(parentBeadsDir)
if err != nil || parentCfg == nil || parentCfg.DoltDatabase != "par" {
t.Fatalf("parent metadata changed: cfg=%+v err=%v", parentCfg, err)
}
// Writes through the explicit dir land in the new workspace only.
childID, stderr, err := runExplicitBeadsDirBD(t, bd, mode, home, child, explicit, "create", "--silent", "child issue")
if err != nil {
t.Fatalf("bd create with BEADS_DIR=%s: %v\nstderr:\n%s", explicit, err, stderr)
}
childID = strings.TrimSpace(childID)
if !strings.HasPrefix(childID, "kid-") {
t.Fatalf("bd create with BEADS_DIR=%s minted %q, want a kid- ID", explicit, childID)
}
parentList, stderr, err := runExplicitBeadsDirBD(t, bd, mode, home, parent, "", "list", "--json")
if err != nil {
t.Fatalf("parent bd list: %v\nstderr:\n%s", err, stderr)
}
if strings.Contains(parentList, childID) || !strings.Contains(parentList, parentID) {
t.Fatalf("parent store should hold only %s, got:\n%s", parentID, parentList)
}
}
func TestEmbeddedInitExplicitBeadsDirIsAuthoritative(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt init tests")
}
t.Parallel()
testExplicitBeadsDirIsAuthoritative(t, buildEmbeddedBD(t), explicitBeadsDirMode{env: bdEnv})
}
func TestProxiedServerInitExplicitBeadsDirIsAuthoritative(t *testing.T) {
requireProxiedServerEnv(t)
testExplicitBeadsDirIsAuthoritative(t, buildEmbeddedBD(t), explicitBeadsDirMode{
initArgs: []string{"--proxied-server"},
env: bdProxiedEnv,
proxied: true,
})
}

View file

@ -1465,6 +1465,11 @@ var rootCmd = &cobra.Command{
// would create a local database instead of using the redirect target.
// (GH#bd-0qel)
targetBeadsDir := beads.FindBeadsDir()
if targetBeadsDir == "" {
// An explicit BEADS_DIR is authoritative even
// before it holds project files.
targetBeadsDir = beads.ExplicitBeadsDir()
}
if targetBeadsDir == "" {
targetBeadsDir = ".beads"
}

View file

@ -32,6 +32,7 @@ go_test(
"beads_test.go",
"context_test.go",
"cwd_priority_test.go",
"explicit_beads_dir_test.go",
"fingerprint_test.go",
"routing_integration_test.go",
"sqlite_database_path_test.go",

View file

@ -892,11 +892,26 @@ func hasBeadsDatabase(beadsDir string) bool {
return false
}
// ExplicitBeadsDir returns the .beads directory named by the BEADS_DIR
// environment variable, canonicalized and with any redirect followed, or ""
// when BEADS_DIR is unset. Unlike FindBeadsDir it does not require the
// directory to exist or to hold project files, so commands that create a
// workspace can target the caller's explicit choice instead of CWD.
func ExplicitBeadsDir() string {
beadsDir := os.Getenv("BEADS_DIR")
if beadsDir == "" {
return ""
}
return FollowRedirect(canonicalizeBeadsDirPath(beadsDir))
}
// FindBeadsDir finds the .beads/ directory in the current directory tree.
// Returns empty string if not found.
//
// Resolution order:
// 1. BEADS_DIR environment variable (highest priority)
// 1. BEADS_DIR environment variable (highest priority). An explicit
// BEADS_DIR is authoritative: when it does not (yet) hold project files,
// FindBeadsDir returns "" instead of discovering some other workspace.
// 2. Walk up from CWD toward repo root boundary, checking each directory
// for .beads/ with valid project files. For worktrees, stops at the
// worktree root; for non-worktrees, stops at the git root.
@ -911,18 +926,20 @@ func hasBeadsDatabase(beadsDir string) bool {
// contents are used as the actual .beads directory path.
func FindBeadsDir() string {
// 1. Check BEADS_DIR environment variable (preferred)
if beadsDir := os.Getenv("BEADS_DIR"); beadsDir != "" {
absBeadsDir := canonicalizeBeadsDirPath(beadsDir)
// Follow redirect if present
absBeadsDir = FollowRedirect(absBeadsDir)
if absBeadsDir := ExplicitBeadsDir(); absBeadsDir != "" {
if info, err := os.Stat(absBeadsDir); err == nil && info.IsDir() {
// Validate directory contains actual project files
if hasBeadsProjectFiles(absBeadsDir) {
return absBeadsDir
}
}
// The caller named this directory explicitly. Walking up from CWD
// here would bind an unrelated ancestor workspace (and PersistentPreRun
// would then rewrite BEADS_DIR to it), so `bd init` and every other
// command would act on the wrong store. Report "not found" instead,
// matching FindDatabasePath.
return ""
}
// 2. Walk up from CWD toward the repo root, checking each directory for .beads/.

View file

@ -0,0 +1,116 @@
package beads
import (
"os"
"os/exec"
"path/filepath"
"testing"
)
// explicitBeadsDirFixture builds a git repo whose root holds an initialized
// workspace (parent/.beads with metadata.json) and a child directory that has
// not been initialized yet. It chdirs into the child, so an unconstrained walk
// up from CWD would bind the parent workspace.
func explicitBeadsDirFixture(t *testing.T) (parentBeadsDir, childDir string) {
t.Helper()
root := t.TempDir()
cmd := exec.Command("git", "init", "--quiet", root)
cmd.Env = append(os.Environ(), "GIT_CONFIG_NOSYSTEM=1", "HOME="+root, "XDG_CONFIG_HOME="+root)
if out, err := cmd.CombinedOutput(); err != nil {
t.Skipf("git not available: %v: %s", err, out)
}
parentBeadsDir = filepath.Join(root, ".beads")
if err := os.MkdirAll(parentBeadsDir, 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(parentBeadsDir, "metadata.json"), []byte(`{"backend":"dolt","dolt_database":"parent"}`), 0o600); err != nil {
t.Fatal(err)
}
childDir = filepath.Join(root, "child")
if err := os.MkdirAll(childDir, 0o700); err != nil {
t.Fatal(err)
}
t.Chdir(childDir)
return parentBeadsDir, childDir
}
// TestFindBeadsDir_ExplicitBEADS_DIRIsAuthoritative verifies that an explicit
// BEADS_DIR which does not (yet) hold project files is never replaced by a
// workspace discovered by walking up from CWD. Before the fix, FindBeadsDir
// silently fell back to the ancestor walk, so every command — including
// `bd init` after PersistentPreRun rebinds BEADS_DIR — targeted the parent
// workspace instead of the directory the caller named.
func TestFindBeadsDir_ExplicitBEADS_DIRIsAuthoritative(t *testing.T) {
cases := []struct {
name string
setup func(t *testing.T, explicit string)
}{
{name: "missing", setup: func(*testing.T, string) {}},
{name: "empty", setup: func(t *testing.T, explicit string) {
if err := os.MkdirAll(explicit, 0o700); err != nil {
t.Fatal(err)
}
}},
{name: "non-project files only", setup: func(t *testing.T, explicit string) {
if err := os.MkdirAll(explicit, 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(explicit, "registry.json"), []byte("[]"), 0o600); err != nil {
t.Fatal(err)
}
}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
parentBeadsDir, childDir := explicitBeadsDirFixture(t)
explicit := filepath.Join(childDir, ".beads")
tc.setup(t, explicit)
t.Setenv("BEADS_DIR", explicit)
if got := FindBeadsDir(); got != "" {
t.Fatalf("FindBeadsDir() = %q with BEADS_DIR=%q; want \"\" (explicit BEADS_DIR must not fall back to the ancestor workspace %q)", got, explicit, parentBeadsDir)
}
if got := FindDatabasePath(); got != "" {
t.Fatalf("FindDatabasePath() = %q with BEADS_DIR=%q; want \"\"", got, explicit)
}
})
}
}
// TestFindBeadsDir_ExplicitBEADS_DIRSelectedOnceInitialized verifies the
// explicit directory is returned as soon as it holds project files, even with
// an initialized ancestor workspace.
func TestFindBeadsDir_ExplicitBEADS_DIRSelectedOnceInitialized(t *testing.T) {
_, childDir := explicitBeadsDirFixture(t)
explicit := filepath.Join(childDir, ".beads")
if err := os.MkdirAll(explicit, 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(explicit, "metadata.json"), []byte(`{"backend":"dolt","dolt_database":"child"}`), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("BEADS_DIR", explicit)
got, _ := filepath.EvalSymlinks(FindBeadsDir())
want, _ := filepath.EvalSymlinks(explicit)
if got != want {
t.Fatalf("FindBeadsDir() = %q; want explicit BEADS_DIR %q", got, want)
}
}
// TestFindBeadsDir_UnsetBEADS_DIRStillWalksUp pins the unchanged behaviour
// when BEADS_DIR is not set: discovery walks up from CWD to the ancestor
// workspace.
func TestFindBeadsDir_UnsetBEADS_DIRStillWalksUp(t *testing.T) {
parentBeadsDir, _ := explicitBeadsDirFixture(t)
t.Setenv("BEADS_DIR", "")
if err := os.Unsetenv("BEADS_DIR"); err != nil {
t.Fatal(err)
}
got, _ := filepath.EvalSymlinks(FindBeadsDir())
want, _ := filepath.EvalSymlinks(parentBeadsDir)
if got != want {
t.Fatalf("FindBeadsDir() = %q; want ancestor workspace %q", got, want)
}
}