fix(init): ignore beads store at OS temp root (#6641)

* fix(init): ignore beads store at OS temp root

* fix(discovery): centralize temp-root walk ceiling

* fix(discovery): guard the empty boundary sentinel in the migrated walks

Maintainer review fixup for #6641.

FindAllDatabases canonicalized findGitRoot()'s "not in a git repo"
sentinel. CanonicalizePath("") resolves to the current working
directory, so the `dir == gitRoot` break fired on the walk's first
iteration and discovery stopped at the CWD instead of walking upward -
an exported-API regression for every non-git caller. Guard the
canonicalization the way findDatabaseInTree already does.

findParentConfig hit the same mechanism one file away: an unset HOME
makes os.UserHomeDir fail, and canonicalizing the resulting "" turned
"don't search above $HOME" into "stop at the CWD".

Also record the two AncestorDirWalk semantics the migration changed but
did not document: the temp-root ceiling ends the walk rather than
skipping the temp root (so ancestors above it are unreachable from
below, which matters when TMPDIR points inside a project), and the walk
yields the filesystem root, which most of the replaced hand-rolled loops
did not. Both are now pinned by tests so they cannot flip silently.

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

---------

Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Rongjun GENG 2026-09-26 18:58:00 -07:00 • committed by GitHub
commit 183565d50b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 515 additions and 76 deletions

View file

@ -29,6 +29,7 @@ import (
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
"github.com/steveyegge/beads/internal/storage/schema"
"github.com/steveyegge/beads/internal/storage/versioncontrolops"
"github.com/steveyegge/beads/internal/utils"
"golang.org/x/term"
)
@ -1308,10 +1309,18 @@ func isNonInteractiveBootstrap(flagValue bool) bool {
func findParentConfig(beadsDir string) (*configfile.Config, error) {
// Start from the parent of beadsDir's enclosing directory.
// beadsDir is typically "<project>/.beads", so we start from <project>'s parent.
start := filepath.Dir(filepath.Dir(beadsDir))
homeDir, _ := os.UserHomeDir()
for dir := start; dir != "/" && dir != "."; {
start := utils.CanonicalizePath(filepath.Dir(filepath.Dir(beadsDir)))
// Canonicalize the $HOME boundary only when there is one. An unset HOME
// makes os.UserHomeDir fail, and CanonicalizePath("") resolves to the
// current working directory, which would silently turn "don't search above
// $HOME" into "stop at the CWD". Keep "" meaning "no boundary".
homeDir := ""
if home, err := os.UserHomeDir(); err == nil && home != "" {
homeDir = utils.CanonicalizePath(home)
}
origin := utils.CanonicalizePath(filepath.Dir(beadsDir))
walk := beads.NewAncestorDirWalk(start, origin)
for dir, ok := walk.Next(); ok; dir, ok = walk.Next() {
candidate := filepath.Join(dir, ".beads")
cfg, err := configfile.LoadForDiscovery(candidate)
if err != nil {
@ -1329,11 +1338,6 @@ func findParentConfig(beadsDir string) (*configfile.Config, error) {
break
}
parent := filepath.Dir(dir)
if parent == dir {
break
}
dir = parent
}
return nil, nil
}

View file

@ -1044,6 +1044,72 @@ func TestFindParentConfigDoesNotSkipCorruptNearestAncestor(t *testing.T) {
}
}
func TestFindParentConfigDoesNotAdoptOSTempRoot(t *testing.T) {
sandbox := t.TempDir()
tempRoot := filepath.Join(sandbox, "tmp")
rootBeadsDir := filepath.Join(tempRoot, ".beads")
if err := os.MkdirAll(rootBeadsDir, 0o750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(rootBeadsDir, "metadata.json"), []byte(`{"dolt_database":"temp_root"}`), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("TMPDIR", tempRoot)
requested := filepath.Join(tempRoot, "isolated", "project", ".beads")
cfg, err := findParentConfig(requested)
if err != nil {
t.Fatal(err)
}
if cfg != nil {
t.Fatalf("findParentConfig() adopted OS temp-root database %q", cfg.GetDoltDatabase())
}
}
// TestFindParentConfigWithoutHomeKeepsSearchingAboveCwd pins the $HOME
// boundary's empty sentinel. os.UserHomeDir fails when HOME is unset, and
// canonicalizing the resulting "" resolves it to the current working
// directory, which silently turns "don't search above $HOME" into "stop at the
// CWD". The walk here starts exactly at the CWD, so the ancestor workspace
// config one level up is only reachable when "" still means "no boundary".
func TestFindParentConfigWithoutHomeKeepsSearchingAboveCwd(t *testing.T) {
sandbox := t.TempDir()
workspace := filepath.Join(sandbox, "workspace")
workspaceBeadsDir := filepath.Join(workspace, ".beads")
if err := os.MkdirAll(workspaceBeadsDir, 0o750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(workspaceBeadsDir, "metadata.json"), []byte(`{"dolt_database":"parent_workspace"}`), 0o600); err != nil {
t.Fatal(err)
}
// findParentConfig starts at the parent of the requested .beads directory's
// project, which is <workspace>/rig here.
rig := filepath.Join(workspace, "rig")
requested := filepath.Join(rig, "project", ".beads")
if err := os.MkdirAll(requested, 0o750); err != nil {
t.Fatal(err)
}
t.Chdir(rig)
// Keep the temp-root ceiling clear of this walk; it is not what this pins.
t.Setenv("TMPDIR", filepath.Join(sandbox, "tmp"))
// os.UserHomeDir reads HOME everywhere except Windows, where it reads
// USERPROFILE; clear both so it fails the way an unset HOME does.
t.Setenv("HOME", "")
t.Setenv("USERPROFILE", "")
cfg, err := findParentConfig(requested)
if err != nil {
t.Fatal(err)
}
if cfg == nil {
t.Fatal("findParentConfig() = nil, want the workspace config above the CWD")
}
if got := cfg.GetDoltDatabase(); got != "parent_workspace" {
t.Errorf("GetDoltDatabase() = %q, want %q", got, "parent_workspace")
}
}
// TestDetectBootstrapAction_SharedServerEnvUsesSharedPath verifies that when
// BEADS_DOLT_SHARED_SERVER=1 is set but cfg.DoltMode is the default (embedded),
// detectBootstrapAction looks in the shared-server directory — not embeddeddolt/.

View file

@ -19,6 +19,7 @@ import (
"github.com/steveyegge/beads/internal/git"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/testutil"
"github.com/steveyegge/beads/internal/utils"
)
// skipIfNoDolt skips the test when no Dolt server is available.
@ -181,6 +182,42 @@ func TestInitCommand(t *testing.T) {
}
}
func TestInitTargetsRequestedProjectBelowOSTempRoot(t *testing.T) {
sandbox := t.TempDir()
tempRoot := filepath.Join(sandbox, "tmp")
tempBeadsDir := filepath.Join(tempRoot, ".beads")
if err := os.MkdirAll(tempBeadsDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(tempBeadsDir, "metadata.json"), []byte("{}\n"), 0o644); err != nil {
t.Fatal(err)
}
project := filepath.Join(tempRoot, "isolated", "project")
if err := os.MkdirAll(project, 0o755); err != nil {
t.Fatal(err)
}
t.Chdir(project)
t.Setenv("TMPDIR", tempRoot)
t.Setenv("BEADS_DIR", "")
t.Setenv("BEADS_DB", "")
t.Setenv("BD_DB", "")
originalDBPath := dbPath
dbPath = ""
t.Cleanup(func() { dbPath = originalDBPath })
selected := selectedNoDBBeadsDir(initCmd)
if selected != "" {
t.Fatalf("selectedNoDBBeadsDir(init) = %q, want no inherited temp-root store", selected)
}
prepareSelectedNoDBContext(selected)
want := filepath.Join(project, ".beads")
if got := resolveInitBeadsDir(); !utils.PathsEqual(got, want) {
t.Fatalf("resolveInitBeadsDir() = %q, want requested project %q", got, want)
}
}
// Note: Error case testing is omitted because the init command calls os.Exit()
// on errors, which makes it difficult to test in a unit test context.

View file

@ -170,8 +170,9 @@ func findOriginalBeadsDir() string {
}
}
// Walk up directory tree looking for .beads with redirect
for dir := cwd; dir != "/" && dir != "."; {
// Walk up directory tree looking for .beads with redirect.
walk := beads.NewAncestorDirWalk(cwd, cwd)
for dir, ok := walk.Next(); ok; dir, ok = walk.Next() {
beadsDir := filepath.Join(dir, ".beads")
if info, err := os.Stat(beadsDir); err == nil && info.IsDir() {
redirectFile := filepath.Join(beadsDir, beads.RedirectFileName)
@ -182,15 +183,6 @@ func findOriginalBeadsDir() string {
return ""
}
// Move up one directory
parent := filepath.Dir(dir)
if parent == dir {
// Reached filesystem root (works on both Unix and Windows)
// On Unix: filepath.Dir("/") returns "/"
// On Windows: filepath.Dir("C:\\") returns "C:\\"
break
}
dir = parent
}
return ""

View file

@ -484,3 +484,45 @@ func TestFindOriginalBeadsDir_BeadsDirEnvWithRedirectReturnsEnv(t *testing.T) {
t.Errorf("findOriginalBeadsDir = %q, want a path ending in alt/.beads", got)
}
}
func TestFindOriginalBeadsDirRespectsOSTempRootCeiling(t *testing.T) {
t.Run("child does not inherit redirect", func(t *testing.T) {
tempRoot := filepath.Join(t.TempDir(), "tmp")
rootBeads := filepath.Join(tempRoot, ".beads")
if err := os.MkdirAll(rootBeads, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(rootBeads, beads.RedirectFileName), []byte(filepath.Join(t.TempDir(), ".beads")), 0o644); err != nil {
t.Fatal(err)
}
child := filepath.Join(tempRoot, "fixture")
if err := os.MkdirAll(child, 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("TMPDIR", tempRoot)
t.Setenv("BEADS_DIR", "")
t.Chdir(child)
if got := findOriginalBeadsDir(); got != "" {
t.Fatalf("findOriginalBeadsDir() = %q, want no temp-root ancestor", got)
}
})
t.Run("temp root start remains usable", func(t *testing.T) {
tempRoot := filepath.Join(t.TempDir(), "tmp")
rootBeads := filepath.Join(tempRoot, ".beads")
if err := os.MkdirAll(rootBeads, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(rootBeads, beads.RedirectFileName), []byte(filepath.Join(t.TempDir(), ".beads")), 0o644); err != nil {
t.Fatal(err)
}
t.Setenv("TMPDIR", tempRoot)
t.Setenv("BEADS_DIR", "")
t.Chdir(tempRoot)
if got := findOriginalBeadsDir(); !utils.PathsEqual(got, rootBeads) {
t.Fatalf("findOriginalBeadsDir() = %q, want %q", got, rootBeads)
}
})
}

View file

@ -445,21 +445,13 @@ func findLocalBeadsDir() string {
return ""
}
for dir := cwd; dir != "/" && dir != "."; {
walk := NewAncestorDirWalk(cwd, cwd)
for dir, ok := walk.Next(); ok; dir, ok = walk.Next() {
beadsDir := filepath.Join(dir, ".beads")
if info, err := os.Stat(beadsDir); err == nil && info.IsDir() {
return beadsDir
}
// Move up one directory
parent := filepath.Dir(dir)
if parent == dir {
// Reached filesystem root (works on both Unix and Windows)
// On Unix: filepath.Dir("/") returns "/"
// On Windows: filepath.Dir("C:\\") returns "C:\\"
break
}
dir = parent
}
return ""
@ -630,7 +622,8 @@ func FindBeadsDirFrom(startDir string) string {
}
}
for dir := startDir; dir != "/" && dir != "."; {
walk := NewAncestorDirWalk(startDir, startDir)
for dir, ok := walk.Next(); ok; dir, ok = walk.Next() {
beadsDir := filepath.Join(dir, ".beads")
if info, err := os.Stat(beadsDir); err == nil && info.IsDir() {
resolved := FollowRedirect(beadsDir)
@ -649,11 +642,6 @@ func FindBeadsDirFrom(startDir string) string {
}
}
parent := filepath.Dir(dir)
if parent == dir {
break
}
dir = parent
}
if fallbackBeadsDir != "" {
@ -709,6 +697,95 @@ func hasBeadsProjectFiles(beadsDir string) bool {
return false
}
// AncestorDirWalk yields canonical directories from startDir upward, up to and
// including the filesystem root.
//
// The OS temp root is an ancestor ceiling that *ends* the walk rather than
// skipping one directory: a walk that starts below the temp root stops there
// without yielding it, so the temp root's own ancestors are unreachable from
// below. That matters when TMPDIR points inside a project (TMPDIR=$REPO/tmp),
// where the project's own .beads sits above the ceiling and is not discovered
// from a path under $REPO/tmp. Terminating is the deliberate choice: resuming
// above the temp root would let a walk started below it adopt ambient state
// from the temp root's ancestors, which is the capture this ceiling exists to
// prevent. A caller whose actual discovery origin is the temp root may inspect
// that starting directory exactly once, which keeps a deliberately initialized
// /tmp workspace usable without letting ambient /tmp/.beads state capture
// projects below it. Both paths are canonicalized once so macOS
// /var -> /private/var aliases cannot bypass the ceiling.
//
// The filesystem root is yielded. The hand-rolled loops this type replaces were
// inconsistent about it — most stopped before "/" while findDatabaseInTree and
// FindAllDatabases inspected it — and the resolvers are easier to reason about
// when they agree on which ancestors exist. The ceiling is not extended to "/"
// because it guards against ambient state in a world-writable shared root,
// which the filesystem root is not.
type AncestorDirWalk struct {
next string
origin string
tempRoot string
done bool
}
// NewAncestorDirWalk constructs an upward directory walk. originDir is the
// caller's actual discovery start even when startDir begins a later segment of
// a bounded walk.
func NewAncestorDirWalk(startDir, originDir string) *AncestorDirWalk {
return &AncestorDirWalk{
next: canonicalizeAncestorWalkPath(startDir),
origin: canonicalizeAncestorWalkPath(originDir),
tempRoot: canonicalizeAncestorWalkPath(os.TempDir()),
}
}
// canonicalizeAncestorWalkPath resolves the longest existing ancestor and
// reattaches any missing tail. Discovery often starts from a not-yet-created
// project path; a bare EvalSymlinks would leave /var unresolved while the
// existing temp root resolves to /private/var, defeating the ceiling.
func canonicalizeAncestorWalkPath(path string) string {
abs, err := filepath.Abs(path)
if err != nil {
return filepath.Clean(path)
}
cur := filepath.Clean(abs)
remainder := ""
for {
if resolved, err := filepath.EvalSymlinks(cur); err == nil {
resolved = utils.CanonicalizePath(resolved)
if remainder == "" {
return resolved
}
return filepath.Join(resolved, remainder)
}
parent := filepath.Dir(cur)
if parent == cur {
return filepath.Clean(abs)
}
remainder = filepath.Join(filepath.Base(cur), remainder)
cur = parent
}
}
// Next returns the next directory permitted by the temp-root ceiling.
func (w *AncestorDirWalk) Next() (string, bool) {
if w == nil || w.done || w.next == "" || w.next == "." {
return "", false
}
dir := w.next
if w.tempRoot != "" && dir == w.tempRoot && dir != w.origin {
w.done = true
return "", false
}
parent := filepath.Dir(dir)
if parent == dir || (w.tempRoot != "" && dir == w.tempRoot) {
w.done = true
} else {
w.next = parent
}
return dir, true
}
// hasBeadsDatabase is the strict counterpart to hasBeadsProjectFiles: it
// returns true only when beadsDir contains an actual database — a dolt/
// directory, an embeddeddolt/ directory, or a non-backup *.db file. Mere
@ -819,7 +896,8 @@ func FindBeadsDir() string {
if walkBoundary != "" {
walkBoundaryCanonical = utils.CanonicalizePath(walkBoundary)
}
for dir := cwdCanonical; dir != "/" && dir != "."; {
walk := NewAncestorDirWalk(cwdCanonical, cwdCanonical)
for dir, ok := walk.Next(); ok; dir, ok = walk.Next() {
// Stop at the walk boundary (exclusive — don't check this directory).
// For worktrees: stops before worktree root so step 3 handles it.
// For non-worktrees: stops before git root (which is checked below in the
@ -827,7 +905,6 @@ func FindBeadsDir() string {
if walkBoundaryCanonical != "" && dir == walkBoundaryCanonical {
break
}
beadsDir := filepath.Join(dir, ".beads")
if info, err := os.Stat(beadsDir); err == nil && info.IsDir() {
beadsDir = FollowRedirect(beadsDir)
@ -836,11 +913,6 @@ func FindBeadsDir() string {
}
}
parent := filepath.Dir(dir)
if parent == dir {
break
}
dir = parent
}
// 3. Worktree-specific fallback: redirect, own .beads, shared .beads.
@ -968,7 +1040,8 @@ func FindBeadsDir() string {
extendedRootCanonical = utils.CanonicalizePath(extendedRoot)
}
for dir := walkBoundaryCanonical; dir != "/" && dir != "."; {
extendedWalk := NewAncestorDirWalk(walkBoundaryCanonical, cwdCanonical)
for dir, ok := extendedWalk.Next(); ok; dir, ok = extendedWalk.Next() {
beadsDir := filepath.Join(dir, ".beads")
if info, err := os.Stat(beadsDir); err == nil && info.IsDir() {
beadsDir = FollowRedirect(beadsDir)
@ -982,11 +1055,6 @@ func FindBeadsDir() string {
break
}
parent := filepath.Dir(dir)
if parent == dir {
break
}
dir = parent
}
}
@ -1245,7 +1313,8 @@ func findDatabaseInTree() string {
}
// Walk up directory tree (regular repository or worktree fallback)
for {
walk := NewAncestorDirWalk(dir, dir)
for dir, ok := walk.Next(); ok; dir, ok = walk.Next() {
beadsDir := filepath.Join(dir, ".beads")
if info, err := os.Stat(beadsDir); err == nil && info.IsDir() {
// Follow redirect if present
@ -1257,19 +1326,10 @@ func findDatabaseInTree() string {
}
}
// Move up one directory
parent := filepath.Dir(dir)
if parent == dir {
// Reached filesystem root
break
}
// Stop at git root to avoid finding unrelated databases
if gitRootCanonical != "" && dir == gitRootCanonical {
break
}
dir = parent
}
return ""
@ -1291,11 +1351,20 @@ func FindAllDatabases() []DatabaseInfo {
return databases
}
// Find git root to limit the search
// Find git root to limit the search. Canonicalize the boundary so the
// `dir == gitRoot` comparison below is robust against symlink or case-form
// mismatches, but only when there is a boundary: outside a git repository
// findGitRoot returns "" and CanonicalizePath("") resolves to the current
// working directory, which would fire the break on the walk's first
// iteration and stop discovery at the CWD. Mirrors findDatabaseInTree.
gitRoot := findGitRoot()
if gitRoot != "" {
gitRoot = utils.CanonicalizePath(gitRoot)
}
// Walk up directory tree
for {
walk := NewAncestorDirWalk(dir, dir)
for dir, ok := walk.Next(); ok; dir, ok = walk.Next() {
beadsDir := filepath.Join(dir, ".beads")
if info, err := os.Stat(beadsDir); err == nil && info.IsDir() {
// Follow redirect if present
@ -1323,12 +1392,6 @@ func FindAllDatabases() []DatabaseInfo {
// Skip if we've already seen this database (via symlink or other path)
if seen[canonicalPath] {
// Move up one directory
parent := filepath.Dir(dir)
if parent == dir {
break
}
dir = parent
continue
}
seen[canonicalPath] = true
@ -1344,19 +1407,10 @@ func FindAllDatabases() []DatabaseInfo {
}
}
// Move up one directory
parent := filepath.Dir(dir)
if parent == dir {
// Reached filesystem root
break
}
// Stop at git root to avoid finding unrelated databases
if gitRoot != "" && dir == gitRoot {
break
}
dir = parent
}
return databases

View file

@ -6,6 +6,8 @@ import (
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"strings"
"testing"
@ -386,6 +388,248 @@ func TestFindBeadsDirSkipsDaemonRegistry(t *testing.T) {
}
}
func TestFindBeadsDirFromSkipsOSTempRoot(t *testing.T) {
sandbox := t.TempDir()
tempRoot := filepath.Join(sandbox, "private", "tmp")
if err := os.MkdirAll(filepath.Join(tempRoot, ".beads"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(tempRoot, ".beads", "metadata.json"), []byte("{}\n"), 0o644); err != nil {
t.Fatal(err)
}
child := filepath.Join(tempRoot, "isolated", "project")
if err := os.MkdirAll(child, 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("TMPDIR", tempRoot)
if got := FindBeadsDirFrom(child); got != "" {
t.Fatalf("FindBeadsDirFrom() = %q, want no discovery from OS temp root", got)
}
}
func TestFindBeadsDirFromSkipsAliasedOSTempRoot(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("symlinked temp-root alias is a Unix path regression")
}
sandbox := t.TempDir()
realTempRoot := filepath.Join(sandbox, "private", "var", "tmp")
aliasParent := filepath.Join(sandbox, "var")
if err := os.MkdirAll(realTempRoot, 0o755); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join(sandbox, "private", "var"), aliasParent); err != nil {
t.Fatal(err)
}
aliasTempRoot := filepath.Join(aliasParent, "tmp")
if err := os.MkdirAll(filepath.Join(realTempRoot, ".beads"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(realTempRoot, ".beads", "metadata.json"), []byte("{}\n"), 0o644); err != nil {
t.Fatal(err)
}
child := filepath.Join(realTempRoot, "isolated", "project")
if err := os.MkdirAll(child, 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("TMPDIR", aliasTempRoot)
if got := FindBeadsDirFrom(child); got != "" {
t.Fatalf("FindBeadsDirFrom() = %q, want aliased OS temp root ignored", got)
}
}
func TestFindBeadsDirFromPreservesNestedProjectUnderOSTempRoot(t *testing.T) {
sandbox := t.TempDir()
tempRoot := filepath.Join(sandbox, "tmp")
project := filepath.Join(tempRoot, "project")
want := filepath.Join(project, ".beads")
if err := os.MkdirAll(want, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(want, "metadata.json"), []byte("{}\n"), 0o644); err != nil {
t.Fatal(err)
}
child := filepath.Join(project, "nested", "directory")
if err := os.MkdirAll(child, 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("TMPDIR", tempRoot)
if got := FindBeadsDirFrom(child); !utils.PathsEqual(got, want) {
t.Fatalf("FindBeadsDirFrom() = %q, want nested project %q", got, want)
}
}
func TestDiscoveryResolversDoNotAdoptOSTempRootAncestor(t *testing.T) {
tempRoot := filepath.Join(t.TempDir(), "tmp")
rootBeadsDir := filepath.Join(tempRoot, ".beads")
if err := os.MkdirAll(filepath.Join(rootBeadsDir, "dolt"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(rootBeadsDir, "metadata.json"), []byte("{}\n"), 0o644); err != nil {
t.Fatal(err)
}
child := filepath.Join(tempRoot, "fixture", "nested")
if err := os.MkdirAll(child, 0o755); err != nil {
t.Fatal(err)
}
t.Chdir(child)
t.Setenv("TMPDIR", tempRoot)
t.Setenv("BEADS_DIR", "")
t.Setenv("BEADS_DB", "")
t.Setenv("BD_DB", "")
if got := FindDatabasePath(); got != "" {
t.Errorf("FindDatabasePath() = %q, want no temp-root ancestor", got)
}
if got := FindBeadsDir(); got != "" {
t.Errorf("FindBeadsDir() = %q, want no temp-root ancestor", got)
}
if got := findLocalBeadsDir(); got != "" {
t.Errorf("findLocalBeadsDir() = %q, want no temp-root ancestor", got)
}
if got := FindAllDatabases(); len(got) != 0 {
t.Errorf("FindAllDatabases() = %+v, want no temp-root ancestor", got)
}
}
func TestDiscoveryResolversHonorStoreAtOSTempRootStart(t *testing.T) {
tempRoot := filepath.Join(t.TempDir(), "tmp")
rootBeadsDir := filepath.Join(tempRoot, ".beads")
if err := os.MkdirAll(filepath.Join(rootBeadsDir, "dolt"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(rootBeadsDir, "metadata.json"), []byte("{}\n"), 0o644); err != nil {
t.Fatal(err)
}
t.Chdir(tempRoot)
t.Setenv("TMPDIR", tempRoot)
t.Setenv("BEADS_DIR", "")
t.Setenv("BEADS_DB", "")
t.Setenv("BD_DB", "")
if got := FindDatabasePath(); got == "" {
t.Error("FindDatabasePath() = empty, want temp-root start store")
}
if got := FindBeadsDir(); !utils.PathsEqual(got, rootBeadsDir) {
t.Errorf("FindBeadsDir() = %q, want %q", got, rootBeadsDir)
}
if got := findLocalBeadsDir(); !utils.PathsEqual(got, rootBeadsDir) {
t.Errorf("findLocalBeadsDir() = %q, want %q", got, rootBeadsDir)
}
if got := FindAllDatabases(); len(got) != 1 {
t.Errorf("FindAllDatabases() = %+v, want temp-root start store", got)
}
}
// TestFindAllDatabasesFindsAncestorStoreOutsideGitRepo pins the empty-gitRoot
// arm. findGitRoot returns "" outside a git repository, and canonicalizing that
// sentinel resolves it to the current working directory, which makes the
// git-root break fire on the walk's first iteration and stops discovery at the
// CWD instead of walking upward.
func TestFindAllDatabasesFindsAncestorStoreOutsideGitRepo(t *testing.T) {
sandbox := t.TempDir()
workspace := filepath.Join(sandbox, "workspace")
wantBeadsDir := filepath.Join(workspace, ".beads")
if err := os.MkdirAll(filepath.Join(wantBeadsDir, "dolt"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(wantBeadsDir, "metadata.json"), []byte("{}\n"), 0o644); err != nil {
t.Fatal(err)
}
child := filepath.Join(workspace, "project", "nested")
if err := os.MkdirAll(child, 0o755); err != nil {
t.Fatal(err)
}
t.Chdir(child)
// The git context is cached per process from wherever it was first
// resolved, so it has to be re-resolved from the sandbox for this test to
// exercise the non-git arm at all.
git.ResetCaches()
t.Cleanup(git.ResetCaches)
if root := findGitRoot(); root != "" {
t.Skipf("sandbox %q resolves inside git repo %q; cannot exercise the non-git arm", child, root)
}
// Keep the temp-root ceiling clear of this walk; it is not what this pins.
t.Setenv("TMPDIR", filepath.Join(sandbox, "tmp"))
got := FindAllDatabases()
if len(got) != 1 {
t.Fatalf("FindAllDatabases() = %+v, want the ancestor store %q", got, wantBeadsDir)
}
if !utils.PathsEqual(got[0].BeadsDir, wantBeadsDir) {
t.Errorf("FindAllDatabases()[0].BeadsDir = %q, want %q", got[0].BeadsDir, wantBeadsDir)
}
}
// TestAncestorDirWalkEndsAtOSTempRoot pins that the ceiling terminates the walk
// rather than skipping the temp root and resuming above it.
func TestAncestorDirWalkEndsAtOSTempRoot(t *testing.T) {
sandbox := t.TempDir()
tempRoot := filepath.Join(sandbox, "tmp")
project := filepath.Join(tempRoot, "project")
start := filepath.Join(project, "nested")
if err := os.MkdirAll(start, 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("TMPDIR", tempRoot)
var got []string
walk := NewAncestorDirWalk(start, start)
for dir, ok := walk.Next(); ok; dir, ok = walk.Next() {
got = append(got, dir)
}
want := []string{
canonicalizeAncestorWalkPath(start),
canonicalizeAncestorWalkPath(project),
}
if !slices.Equal(got, want) {
t.Fatalf("walk yielded %q, want %q — the temp-root ceiling must end the walk, not skip the temp root and continue above it", got, want)
}
}
// TestAncestorDirWalkYieldsFilesystemRoot pins the documented choice that the
// walk includes the filesystem root. Most of the hand-rolled loops this type
// replaced stopped before "/"; the unified walk does not, so the behavior is
// deliberate and must not flip silently.
func TestAncestorDirWalkYieldsFilesystemRoot(t *testing.T) {
sandbox := t.TempDir()
start := filepath.Join(sandbox, "project", "nested")
if err := os.MkdirAll(start, 0o755); err != nil {
t.Fatal(err)
}
// Point the ceiling somewhere off this walk so it can reach the root.
t.Setenv("TMPDIR", filepath.Join(sandbox, "tmp"))
fsRoot := canonicalizeAncestorWalkPath(start)
for {
parent := filepath.Dir(fsRoot)
if parent == fsRoot {
break
}
fsRoot = parent
}
last := ""
// The walk must terminate at the root; bound the loop so a regression
// reports a failure instead of hanging until the package timeout.
const maxDepth = 256
steps := 0
walk := NewAncestorDirWalk(start, start)
for dir, ok := walk.Next(); ok; dir, ok = walk.Next() {
last = dir
if steps++; steps > maxDepth {
t.Fatalf("walk did not terminate after %d directories, last %q", maxDepth, last)
}
}
if last != fsRoot {
t.Errorf("last yielded directory = %q, want the filesystem root %q", last, fsRoot)
}
}
// TestFindBeadsDirValidatesBeadsDirEnv verifies that BEADS_DIR env var
// is validated for project files (bd-420)
func TestFindBeadsDirValidatesBeadsDirEnv(t *testing.T) {