beads/cmd/bd/directory_flag_test.go
Vishnu J 93cfee9054
fix: honor changed directory when running prime (#6550)
* fix(prime): honor -C for the local PRIME.md tier, git probes, divergence reminder, and redirect notice (#5509)

`bd -C <dir> prime` silently primed the process cwd. -C is implemented as
setenv BEADS_DIR (no chdir), so the store and memories already followed the
target, but four workspace-relative reads in prime did not: the
first-priority .beads/PRIME.md lookup, the AGENTS.md/CLAUDE.md divergence
reminder, the git probes (upstream, remotes) behind the default template's
git-authority wording, and the template's redirect notice all resolved
against the cwd. On the no-PRIME.md path the output for `bd -C repo-b prime`
was byte-identical to priming the cwd repo.

Add primeWorkspaceDir(), which returns the absolute -C target when set and ""
(cwd) otherwise, and resolve all four against it: readCustomPrimeContent
takes the workspace dir as a parameter, the reminder takes the same
workspace, a new primeGitCmd helper runs isEphemeralBranch and
primeHasGitRemote in the -C target (falling back to GitCmdCWD without -C,
as before), and primeRedirectInfo asks internal/beads about the -C target
through a new GetRedirectInfoFrom(dir). GetRedirectInfo() delegates to the
same core for the cwd, so redirect detection without -C is unchanged. The
clone-local PRIME.md tier is rebased onto the -C target rather than dropped,
so a redirect clone with its own .beads/PRIME.md yields the clone-local file
under -C exactly as `cd <dir> && bd prime` does. The workspace is
deliberately the -C directory itself, not the parent of the resolved beads
dir, which may have followed .beads/redirect or walked up from a
subdirectory.

Env-only BEADS_DIR redirects are unchanged: without -C the cwd-local
PRIME.md still wins (clone-specific customization, GH#876), guarded by
TestReadCustomPrimeContent_EnvRedirectStillLocalFirst.

Tests: unit coverage for primeWorkspaceDir (absolute, relative, unset),
the -C target and redirect-clone PRIME.md tiers, the env-only redirect, the
divergence-reminder workspace (redirect and subdirectory cases), and
GetRedirectInfoFrom against GetRedirectInfo in both directions plus the
non-git walk-up, plus three end-to-end runs (cgo build tag, shared
once-per-process bd binary): the issue's two-repo PRIME.md repro, a
no-PRIME.md pair where `bd -C repo-b prime` from repo-a must equal
`cd repo-b && bd prime` byte for byte while differing from the cwd's own
prime (repo-a has a remote and upstream, repo-b has neither and carries
divergent AGENTS.md/CLAUDE.md), and a plain-repo/redirect-clone pair where
the redirect notice must follow -C in both directions.

Fixes #5509

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(prime): canonicalize the -C repo root and document the shared probes

Maintainer review fixes for #6550 (adopt-pr review iteration 1). Nothing here
was a merge gate: the scorecard approved at 962/1000 with no required changes.
No behavior change on Linux/macOS.

- internal/beads: canonicalize the repo root inside repoLocalBeadsDir, the
  helper both locators share. findLocalBdsDirInRepoFrom handed it raw
  `git rev-parse --show-toplevel` output while the cwd twin passes
  git.GetRepoRoot()'s already-normalized value, so on Windows (`C:/...`, msys
  `/c/...`) the repo-local tier missed and resolution fell through to the
  walk-up locator - the fallback bd-wayc3 exists to beat. Canonicalizing stays
  below the "" guard on purpose: utils.CanonicalizePath("") resolves to the
  process cwd. TestRepoLocalBeadsDirCanonicalizesRepoRoot pins both halves and
  reds on either mutation (drop the canonicalization; move it above the guard).
- internal/beads: document that GetRedirectInfoFrom's fallback drops the
  worktree-local redirect probe and GetWorktreeFallbackBeadsDir, not only
  BEADS_DIR.
- cmd/bd/prime.go: NOTE that primeHasGitRemote and primeGitCmd have a consumer
  outside prime (isBackupAutoEnabled), which inherits the -C directory choice.
- CHANGELOG: add the Unreleased/Fixed entry for #5509 and disclose that
  `bd -C dir <any command>` now decides auto-backup enablement from the -C
  target's git remote rather than the launch directory's.
- cmd/bd/prime_embedded_test.go: record why the three -C repros carry the
  TestEmbedded prefix (fast lanes -skip it, embedded-test-shard.sh discovers
  shard members by it) and that they need no embedded Dolt.

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

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Julian Knutsen <julian@knutsen.dev>
2026-09-27 00:59:29 -07:00

225 lines
7.3 KiB
Go

package main
import (
"os"
"path/filepath"
"testing"
"github.com/spf13/cobra"
)
func TestResolveChangeDirBeadsDirDoesNotChangeCWD(t *testing.T) {
origWD, err := os.Getwd()
if err != nil {
t.Fatalf("Getwd: %v", err)
}
t.Cleanup(func() {
_ = os.Chdir(origWD)
})
startDir := t.TempDir()
t.Chdir(startDir)
projectDir := t.TempDir()
if resolved, err := filepath.EvalSymlinks(projectDir); err == nil {
projectDir = resolved
}
beadsDir := filepath.Join(projectDir, ".beads")
if err := os.MkdirAll(beadsDir, 0o755); err != nil {
t.Fatalf("MkdirAll: %v", err)
}
if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(`{"backend":"dolt"}`), 0o644); err != nil {
t.Fatalf("WriteFile: %v", err)
}
got, err := resolveChangeDirBeadsDir(projectDir)
if err != nil {
t.Fatalf("resolveChangeDirBeadsDir: %v", err)
}
if got != beadsDir {
t.Fatalf("resolveChangeDirBeadsDir() = %q, want %q", got, beadsDir)
}
afterWD, err := os.Getwd()
if err != nil {
t.Fatalf("Getwd after resolve: %v", err)
}
if afterWD != startDir {
t.Fatalf("working directory changed to %q, want %q", afterWD, startDir)
}
}
func TestResolveChangeDirBeadsDirRejectsFile(t *testing.T) {
filePath := filepath.Join(t.TempDir(), "not-a-directory")
if err := os.WriteFile(filePath, []byte("x"), 0o644); err != nil {
t.Fatalf("WriteFile: %v", err)
}
if _, err := resolveChangeDirBeadsDir(filePath); err == nil {
t.Fatal("expected non-directory -C target to fail")
}
}
func TestResolveChangeDirBeadsDirRejectsDirectoryWithoutProject(t *testing.T) {
if _, err := resolveChangeDirBeadsDir(t.TempDir()); err == nil {
t.Fatal("expected -C target without a beads project to fail")
}
}
const primeTestMetadata = `{"backend":"dolt"}`
// primeTestWorkspace creates a workspace root (symlinks resolved, so paths
// compare equal to what -C resolution yields) holding an empty .beads/ plus
// the given files, keyed by path relative to the root.
func primeTestWorkspace(t *testing.T, files map[string]string) string {
t.Helper()
dir := t.TempDir()
if resolved, err := filepath.EvalSymlinks(dir); err == nil {
dir = resolved
}
if err := os.MkdirAll(filepath.Join(dir, ".beads"), 0o755); err != nil {
t.Fatalf("mkdir .beads: %v", err)
}
for rel, content := range files {
path := filepath.Join(dir, rel)
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatalf("mkdir %s: %v", filepath.Dir(path), err)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatalf("write %s: %v", path, err)
}
}
return dir
}
func TestPrimeWorkspaceDir(t *testing.T) {
t.Cleanup(func() {
changeDir = ""
})
parent := primeTestWorkspace(t, map[string]string{"target/.beads/metadata.json": primeTestMetadata})
target := filepath.Join(parent, "target")
t.Chdir(parent)
for _, tc := range []struct{ changeDir, want string }{
{"", ""}, // no -C: workspace-relative reads stay on the cwd
{" ", ""}, // blank -C is treated as unset, as applyChangeDirSelection does
{target, target}, // absolute -C
{"target", target}, // relative -C, like `bd -C target prime`
} {
changeDir = tc.changeDir
if got := primeWorkspaceDir(); got != tc.want {
t.Errorf("changeDir=%q: primeWorkspaceDir() = %q, want %q", tc.changeDir, got, tc.want)
}
}
}
func TestReadCustomPrimeContent_ChangeDirPrefersTarget(t *testing.T) {
const cwdPrime = "# CWD local PRIME\ncwd-local-custom\n"
const targetPrime = "# Target workspace PRIME\ntarget-workspace-custom\n"
cwd := primeTestWorkspace(t, map[string]string{".beads/PRIME.md": cwdPrime})
target := primeTestWorkspace(t, map[string]string{".beads/PRIME.md": targetPrime})
t.Chdir(cwd)
// bd -C target prime: the workspace is the -C target, so its clone-local
// PRIME.md wins over the cwd's.
got, ok := readCustomPrimeContent(target, filepath.Join(target, ".beads"))
if !ok {
t.Fatal("expected a custom PRIME.md, got none")
}
if got != targetPrime {
t.Fatalf("with -C target, readCustomPrimeContent = %q, want target %q", got, targetPrime)
}
}
// Without -C the workspace is the cwd even when BEADS_DIR points elsewhere: the
// cwd's clone-local PRIME.md keeps winning (GH#876), and the redirected
// workspace's file is only the second tier.
func TestReadCustomPrimeContent_EnvRedirectStillLocalFirst(t *testing.T) {
const cwdPrime = "# CWD local PRIME\nenv-redirect-local-wins\n"
const redirectedPrime = "# Redirected workspace PRIME\nenv-redirect-shared\n"
cwd := primeTestWorkspace(t, map[string]string{".beads/PRIME.md": cwdPrime})
redirected := primeTestWorkspace(t, map[string]string{".beads/PRIME.md": redirectedPrime})
t.Chdir(cwd)
got, ok := readCustomPrimeContent("", filepath.Join(redirected, ".beads"))
if !ok {
t.Fatal("expected a custom PRIME.md, got none")
}
if got != cwdPrime {
t.Fatalf("env-only redirect must keep local-first: got %q, want local %q", got, cwdPrime)
}
}
// -C target is a redirect clone (.beads/redirect -> external store) that also
// carries its own clone-local .beads/PRIME.md. `cd target && bd prime` reads the
// clone-local file ahead of the shared one; `bd -C target prime` must match it,
// not fall through to the external store's PRIME.md and not read the cwd's.
func TestReadCustomPrimeContent_ChangeDirRedirectClonePrefersCloneLocal(t *testing.T) {
const cwdPrime = "# CWD-LOCAL\n"
const clonePrime = "# TARGET-CLONE-LOCAL\n"
const sharedPrime = "# EXTERNAL-SHARED\n"
cwd := primeTestWorkspace(t, map[string]string{".beads/PRIME.md": cwdPrime})
external := primeTestWorkspace(t, map[string]string{
".beads/metadata.json": primeTestMetadata,
".beads/PRIME.md": sharedPrime,
})
externalBeads := filepath.Join(external, ".beads")
target := primeTestWorkspace(t, map[string]string{
".beads/redirect": externalBeads + "\n",
".beads/PRIME.md": clonePrime,
})
resolvedBeads, err := resolveChangeDirBeadsDir(target)
if err != nil {
t.Fatalf("resolveChangeDirBeadsDir: %v", err)
}
if filepath.Clean(resolvedBeads) != filepath.Clean(externalBeads) {
t.Fatalf("resolved beads = %q, want external %q", resolvedBeads, externalBeads)
}
// Reference: cd target && bd prime.
t.Chdir(target)
want, ok := readCustomPrimeContent("", resolvedBeads)
if !ok || want != clonePrime {
t.Fatalf("reference (cd target): got %q, %v; want clone-local %q", want, ok, clonePrime)
}
// Under test: bd -C target prime from an unrelated cwd with its own PRIME.md.
t.Chdir(cwd)
got, ok := readCustomPrimeContent(target, resolvedBeads)
if !ok {
t.Fatal("expected a custom PRIME.md, got none")
}
if got != want {
t.Fatalf("bd -C target must match cd target: got %q, want %q", got, want)
}
}
func TestIsPreviewCommand(t *testing.T) {
tests := []struct {
name string
flag string
set string
want bool
}{
{name: "dry run", flag: "dry-run", set: "true", want: true},
{name: "inspect", flag: "inspect", set: "true", want: true},
{name: "false preview flag", flag: "dry-run", set: "false", want: false},
{name: "no preview flag", want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := &cobra.Command{Use: "test"}
if tt.flag != "" {
cmd.Flags().Bool(tt.flag, false, "")
if err := cmd.Flags().Set(tt.flag, tt.set); err != nil {
t.Fatalf("set %s: %v", tt.flag, err)
}
}
if got := isPreviewCommand(cmd); got != tt.want {
t.Fatalf("isPreviewCommand() = %v, want %v", got, tt.want)
}
})
}
}