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>
This commit is contained in:
parent
1ed5b33303
commit
93cfee9054
7 changed files with 696 additions and 22 deletions
17
CHANGELOG.md
17
CHANGELOG.md
|
|
@ -9,6 +9,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
|
||||
### Fixed
|
||||
|
||||
- **`bd -C dir prime` now describes the target workspace instead of the launch
|
||||
directory** ([#5509](https://github.com/gastownhall/beads/issues/5509)). `-C`
|
||||
resolves `BEADS_DIR` but never changes directory, so prime's cwd-relative
|
||||
surfaces still described wherever the command was launched: the clone-local
|
||||
`.beads/PRIME.md` tier, the AGENTS.md/CLAUDE.md divergence reminder, the git
|
||||
upstream/remote probes behind the template's git-authority wording, and the
|
||||
redirect notice. All four now resolve against the `-C` target, matching
|
||||
`cd dir && bd prime`; without `-C` the behavior is byte-for-byte unchanged.
|
||||
|
||||
Note for `-C` users: the git-remote probe prime shares with auto-backup
|
||||
(`isBackupAutoEnabled`) follows the same change, so under
|
||||
`bd -C dir <any command>` auto-backup enablement and the `bd backup status`
|
||||
note are now decided by the `-C` target's git remote rather than the launch
|
||||
directory's. That makes the probe agree with the store actually being backed
|
||||
up, but it can flip auto-backup on or off for `-C` invocations whose launch
|
||||
directory and target differ in remote configuration.
|
||||
|
||||
- **`bd close` now exits non-zero when any issue in a batch fails to close**
|
||||
([#6648](https://github.com/gastownhall/beads/issues/6648)). A batch with one
|
||||
refused id used to exit 0 as long as another id closed, so scripts could not
|
||||
|
|
|
|||
|
|
@ -66,6 +66,135 @@ func TestResolveChangeDirBeadsDirRejectsDirectoryWithoutProject(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
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
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import (
|
|||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
|
@ -187,7 +188,7 @@ Memory injection caps:
|
|||
// working under a custom template — matching the default-template behavior
|
||||
// (GH#3941).
|
||||
if !primeExportMode {
|
||||
if content, ok := readCustomPrimeContent(beadsDir); ok {
|
||||
if content, ok := readCustomPrimeContent(primeWorkspaceDir(), beadsDir); ok {
|
||||
if !primeNoMemories {
|
||||
if mem := formatMemoriesForPrime(false); mem != "" {
|
||||
content += mem
|
||||
|
|
@ -209,7 +210,7 @@ Memory injection caps:
|
|||
// Append the AGENTS.md/CLAUDE.md divergence reminder only when both
|
||||
// files are independent regulars carrying the bd marker; otherwise this
|
||||
// adds nothing (zero output, negligible cost).
|
||||
buf.WriteString(primeDivergenceReminder(""))
|
||||
buf.WriteString(primeDivergenceReminder(primeWorkspaceDir()))
|
||||
emit(buf.String())
|
||||
return nil
|
||||
},
|
||||
|
|
@ -229,14 +230,16 @@ func init() {
|
|||
}
|
||||
|
||||
// readCustomPrimeContent returns the contents of a custom PRIME.md override and
|
||||
// true when one is found. It checks, in priority order: the local .beads/PRIME.md
|
||||
// (clone-specific customization), the redirected workspace PRIME.md (shared
|
||||
// customization), then the global ~/.config/beads/PRIME.md. It returns ("", false)
|
||||
// when no override exists, so callers fall through to the generated default.
|
||||
func readCustomPrimeContent(beadsDir string) (string, bool) {
|
||||
localPrimePath := filepath.Join(".beads", "PRIME.md")
|
||||
// Try local first (user's clone-specific customization).
|
||||
// #nosec G304 -- path is relative to cwd
|
||||
// true when one is found. It checks, in priority order: the workspace-local
|
||||
// .beads/PRIME.md under workspaceDir (clone-specific customization; "" means
|
||||
// the cwd), the redirected workspace PRIME.md under beadsDir (shared
|
||||
// customization), then the global ~/.config/beads/PRIME.md. It returns
|
||||
// ("", false) when no override exists, so callers fall through to the
|
||||
// generated default.
|
||||
func readCustomPrimeContent(workspaceDir, beadsDir string) (string, bool) {
|
||||
// Try local first (user's clone-specific customization; 4021f4944 / GH#876).
|
||||
localPrimePath := filepath.Join(workspaceDir, ".beads", "PRIME.md")
|
||||
// #nosec G304 -- path is relative to the workspace root (-C target or cwd)
|
||||
if content, err := os.ReadFile(localPrimePath); err == nil {
|
||||
return string(content), true
|
||||
}
|
||||
|
|
@ -256,6 +259,46 @@ func readCustomPrimeContent(beadsDir string) (string, bool) {
|
|||
return "", false
|
||||
}
|
||||
|
||||
// primeWorkspaceDir returns the directory prime resolves workspace-relative
|
||||
// state against — the .beads/PRIME.md local tier, the AGENTS.md/CLAUDE.md
|
||||
// divergence reminder, the git probes behind the default template's
|
||||
// git-authority wording, and the template's redirect notice: the absolute -C
|
||||
// target when set, else "" (the process cwd). -C only redirects BEADS_DIR, it does not chdir, so this is what makes
|
||||
// `bd -C dir prime` match `cd dir && bd prime` (#5509). It is deliberately not
|
||||
// the parent of the resolved beads dir, which may have followed .beads/redirect
|
||||
// or walked up from a subdirectory (see the CASE A/B tests in
|
||||
// prime_divergence_test.go).
|
||||
func primeWorkspaceDir() string {
|
||||
if strings.TrimSpace(changeDir) == "" {
|
||||
return ""
|
||||
}
|
||||
abs, err := filepath.Abs(changeDir)
|
||||
if err != nil {
|
||||
return filepath.Clean(changeDir)
|
||||
}
|
||||
return abs
|
||||
}
|
||||
|
||||
// primeGitCmd returns the git command prime's repository probes run. Under -C
|
||||
// it runs in the -C target, so the upstream/remote checks describe the primed
|
||||
// workspace rather than the process cwd (#5509); otherwise it runs in the
|
||||
// cwd repository via GitCmdCWD, exactly as before.
|
||||
//
|
||||
// NOTE: the probes built here are not prime-only — see primeHasGitRemote for
|
||||
// the auto-backup consumer that inherits this directory choice.
|
||||
func primeGitCmd(ctx context.Context, args ...string) (*exec.Cmd, error) {
|
||||
if ws := primeWorkspaceDir(); ws != "" {
|
||||
cmd := exec.CommandContext(ctx, "git", args...)
|
||||
cmd.Dir = ws
|
||||
return cmd, nil
|
||||
}
|
||||
rc, err := internalbeads.GetRepoContext()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rc.GitCmdCWD(ctx, args...), nil
|
||||
}
|
||||
|
||||
// outputHookJSON wraps content in the SessionStart hook JSON envelope shared
|
||||
// by Claude Code, Gemini CLI, and Codex. All three require stdout to be valid
|
||||
// JSON — no plain text may be emitted alongside it. See:
|
||||
|
|
@ -321,11 +364,10 @@ func isMCPActive() bool {
|
|||
var isEphemeralBranch = func() bool {
|
||||
// git rev-parse --abbrev-ref --symbolic-full-name @{u}
|
||||
// Returns error code 128 if no upstream configured
|
||||
rc, err := internalbeads.GetRepoContext()
|
||||
cmd, err := primeGitCmd(context.Background(), "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}")
|
||||
if err != nil {
|
||||
return true // Default to ephemeral if we can't determine context
|
||||
}
|
||||
cmd := rc.GitCmdCWD(context.Background(), "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}")
|
||||
return cmd.Run() != nil
|
||||
}
|
||||
|
||||
|
|
@ -343,12 +385,19 @@ var primeAgentProfile = func() config.AgentProfile {
|
|||
}
|
||||
|
||||
// primeHasGitRemote detects if any git remote is configured (stubbable for tests)
|
||||
//
|
||||
// NOTE: despite the prime prefix, this has a consumer outside prime —
|
||||
// isBackupAutoEnabled (backup_auto.go) gates auto-backup and the
|
||||
// `bd backup status` note on it. Since it probes through primeGitCmd,
|
||||
// `bd -C dir <any command>` now keys that decision off the -C target's git
|
||||
// remote rather than the cwd's (#5509). That is the consistent answer, because
|
||||
// the store being backed up is the -C-resolved one, but it is a behavior
|
||||
// change beyond prime: check backup_auto before changing what this probes.
|
||||
var primeHasGitRemote = func() bool {
|
||||
rc, err := internalbeads.GetRepoContext()
|
||||
cmd, err := primeGitCmd(context.Background(), "remote")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
cmd := rc.GitCmdCWD(context.Background(), "remote")
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
return false
|
||||
|
|
@ -379,9 +428,18 @@ func primeDoltSyncBullets(doltSync bool, pushFirst bool) string {
|
|||
"- `bd dolt push` - Push beads to Dolt remote\n"
|
||||
}
|
||||
|
||||
// primeRedirectInfo reports the redirect state of the primed workspace: the
|
||||
// -C target when one is given (#5509), else the process cwd exactly as before.
|
||||
func primeRedirectInfo() beads.RedirectInfo {
|
||||
if ws := primeWorkspaceDir(); ws != "" {
|
||||
return internalbeads.GetRedirectInfoFrom(ws)
|
||||
}
|
||||
return beads.GetRedirectInfo()
|
||||
}
|
||||
|
||||
// getRedirectNotice returns a notice string if beads is redirected
|
||||
func getRedirectNotice(verbose bool) string {
|
||||
redirectInfo := beads.GetRedirectInfo()
|
||||
redirectInfo := primeRedirectInfo()
|
||||
if !redirectInfo.IsRedirected {
|
||||
return ""
|
||||
}
|
||||
|
|
|
|||
|
|
@ -99,3 +99,102 @@ func TestPrimeDivergenceReminder_EmptyDirArgUsesCwd(t *testing.T) {
|
|||
t.Fatalf("expected empty for cwd without files, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The remaining tests cover the workspace the reminder is resolved against
|
||||
// under -C (#5509): primeWorkspaceDir is the -C directory itself, not the
|
||||
// parent of the beads dir that -C resolved to.
|
||||
|
||||
func TestPrimeDivergenceWorkspaceDir_ChangeDirUsesTarget(t *testing.T) {
|
||||
t.Cleanup(func() {
|
||||
changeDir = ""
|
||||
})
|
||||
// Only the cwd carries divergent agent files; the -C target has none.
|
||||
cwd := primeTestWorkspace(t, map[string]string{
|
||||
".beads/metadata.json": primeTestMetadata,
|
||||
"AGENTS.md": "# Agents\n" + markerBlock,
|
||||
"CLAUDE.md": "# Claude\n" + markerBlock,
|
||||
})
|
||||
target := primeTestWorkspace(t, map[string]string{".beads/metadata.json": primeTestMetadata})
|
||||
t.Chdir(cwd)
|
||||
|
||||
changeDir = target
|
||||
if got := primeDivergenceReminder(primeWorkspaceDir()); got != "" {
|
||||
t.Fatalf("with -C, reminder against target must be empty, got %q", got)
|
||||
}
|
||||
changeDir = ""
|
||||
if got := primeDivergenceReminder(primeWorkspaceDir()); got == "" {
|
||||
t.Fatal("control: without -C the cwd fixture must emit a divergence note")
|
||||
}
|
||||
}
|
||||
|
||||
// CASE A: the -C target is a redirect clone. The reminder must be resolved
|
||||
// against the clone (where the agent files live), not against the parent of
|
||||
// the external store that -C resolved BEADS_DIR to.
|
||||
func TestPrimeDivergenceWorkspaceDir_RedirectUsesChangeDir(t *testing.T) {
|
||||
t.Cleanup(func() {
|
||||
changeDir = ""
|
||||
})
|
||||
external := primeTestWorkspace(t, map[string]string{".beads/metadata.json": primeTestMetadata})
|
||||
externalBeads := filepath.Join(external, ".beads")
|
||||
target := primeTestWorkspace(t, map[string]string{
|
||||
".beads/redirect": externalBeads + "\n",
|
||||
"AGENTS.md": "# Agents\n" + markerBlock,
|
||||
"CLAUDE.md": "# Claude\n" + markerBlock,
|
||||
})
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
changeDir = target
|
||||
ws := primeWorkspaceDir()
|
||||
if ws != target {
|
||||
t.Fatalf("CASE A: primeWorkspaceDir = %q, want -C target %q (not parent of redirected beads %q)", ws, target, filepath.Dir(resolvedBeads))
|
||||
}
|
||||
if got := primeDivergenceReminder(ws); got == "" {
|
||||
t.Fatal("CASE A: reminder against -C target must emit divergence note")
|
||||
}
|
||||
if got := primeDivergenceReminder(filepath.Dir(resolvedBeads)); got != "" {
|
||||
t.Fatalf("control: parent-of-resolved-beads must not emit note, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// CASE B: the -C target is a subdirectory of the workspace. -C resolves
|
||||
// BEADS_DIR by walking up to the root's .beads, but the reminder still reads
|
||||
// the -C directory itself, as `cd sub && bd prime` would.
|
||||
func TestPrimeDivergenceWorkspaceDir_SubdirUsesChangeDir(t *testing.T) {
|
||||
t.Cleanup(func() {
|
||||
changeDir = ""
|
||||
})
|
||||
wsRoot := primeTestWorkspace(t, map[string]string{
|
||||
".beads/metadata.json": primeTestMetadata,
|
||||
"AGENTS.md": "# Agents\n" + markerBlock,
|
||||
"CLAUDE.md": "# Claude\n" + markerBlock,
|
||||
"sub/.keep": "",
|
||||
})
|
||||
sub := filepath.Join(wsRoot, "sub")
|
||||
|
||||
resolvedBeads, err := resolveChangeDirBeadsDir(sub)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveChangeDirBeadsDir: %v", err)
|
||||
}
|
||||
if filepath.Clean(resolvedBeads) != filepath.Join(wsRoot, ".beads") {
|
||||
t.Fatalf("resolved beads = %q, want root %q", resolvedBeads, filepath.Join(wsRoot, ".beads"))
|
||||
}
|
||||
|
||||
changeDir = sub
|
||||
ws := primeWorkspaceDir()
|
||||
if ws != sub {
|
||||
t.Fatalf("CASE B: primeWorkspaceDir = %q, want -C subdir %q (not parent-of-beads %q)", ws, sub, filepath.Dir(resolvedBeads))
|
||||
}
|
||||
if got := primeDivergenceReminder(ws); got != "" {
|
||||
t.Fatalf("CASE B: reminder against -C subdir must be empty, got %q", got)
|
||||
}
|
||||
if got := primeDivergenceReminder(filepath.Dir(resolvedBeads)); got == "" {
|
||||
t.Fatal("control: parent-of-beads-dir must emit note (proves CASE B distinguishes the wrong derivation)")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import (
|
|||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
|
@ -154,3 +155,212 @@ func TestEmbeddedPrimeConcurrent(t *testing.T) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
// primeChangeDirRepo lays out a minimal beads project (metadata.json is what
|
||||
// makes .beads a project for -C resolution) inside a fresh git repository on
|
||||
// branch main, plus the given workspace files. The #5509 tests below build two
|
||||
// of these and compare `bd -C repo-b prime` run from repo-a against the
|
||||
// `cd repo-b && bd prime` reference byte for byte.
|
||||
func primeChangeDirRepo(t *testing.T, files map[string]string) string {
|
||||
t.Helper()
|
||||
dir := primeTestWorkspace(t, files)
|
||||
if err := os.WriteFile(filepath.Join(dir, ".beads", "metadata.json"), []byte(primeTestMetadata), 0o644); err != nil {
|
||||
t.Fatalf("write metadata.json: %v", err)
|
||||
}
|
||||
primeChangeDirGit(t, dir, "init", "-q")
|
||||
primeChangeDirGit(t, dir, "symbolic-ref", "HEAD", "refs/heads/main")
|
||||
return dir
|
||||
}
|
||||
|
||||
// primeChangeDirRedirectClone lays out a git repository on branch main whose
|
||||
// .beads holds only a redirect to storeBeadsDir: a clone sharing an external
|
||||
// store, the shape the template's redirect notice describes.
|
||||
func primeChangeDirRedirectClone(t *testing.T, storeBeadsDir string) string {
|
||||
t.Helper()
|
||||
dir := primeTestWorkspace(t, map[string]string{".beads/redirect": storeBeadsDir + "\n"})
|
||||
primeChangeDirGit(t, dir, "init", "-q")
|
||||
primeChangeDirGit(t, dir, "symbolic-ref", "HEAD", "refs/heads/main")
|
||||
return dir
|
||||
}
|
||||
|
||||
func primeChangeDirGit(t *testing.T, dir string, args ...string) {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = append(os.Environ(),
|
||||
"GIT_AUTHOR_NAME=bd-test", "GIT_AUTHOR_EMAIL=bd-test@example.com",
|
||||
"GIT_COMMITTER_NAME=bd-test", "GIT_COMMITTER_EMAIL=bd-test@example.com",
|
||||
)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("git %s in %s: %v\n%s", strings.Join(args, " "), dir, err, out)
|
||||
}
|
||||
}
|
||||
|
||||
// primeChangeDirRun runs bd in dir with env and returns stdout.
|
||||
func primeChangeDirRun(t *testing.T, bd, dir string, env []string, args ...string) string {
|
||||
t.Helper()
|
||||
cmd := exec.Command(bd, args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = env
|
||||
stdout, stderr, err := runCommandBuffers(t, cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("bd %s in %s failed: %v\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), dir, err, stdout.String(), stderr.String())
|
||||
}
|
||||
return stdout.String()
|
||||
}
|
||||
|
||||
// primeFirstDiff describes the first line at which got and want differ.
|
||||
func primeFirstDiff(got, want string) string {
|
||||
gotLines, wantLines := strings.Split(got, "\n"), strings.Split(want, "\n")
|
||||
for i := 0; i < len(gotLines) || i < len(wantLines); i++ {
|
||||
var g, w string
|
||||
if i < len(gotLines) {
|
||||
g = gotLines[i]
|
||||
}
|
||||
if i < len(wantLines) {
|
||||
w = wantLines[i]
|
||||
}
|
||||
if g != w {
|
||||
return fmt.Sprintf("line %d: got %q, want %q", i+1, g, w)
|
||||
}
|
||||
}
|
||||
return "no differing line"
|
||||
}
|
||||
|
||||
// The three TestEmbeddedPrimeChangeDir* tests below need no embedded Dolt and
|
||||
// carry no BEADS_TEST_EMBEDDED_DOLT gate of their own — they are plain `bd`
|
||||
// subprocess parity tests. The TestEmbedded prefix is deliberate and
|
||||
// load-bearing in both directions: the fast `./...` lanes run
|
||||
// -skip '^TestEmbedded' (pr.yml, main.yml), and .github/scripts/embedded-test-shard.sh
|
||||
// discovers shard members by grepping ^func TestEmbedded in *_embedded_test.go.
|
||||
// So they run in the full embedded tier, which ci-embedded-tier.sh enables
|
||||
// unconditionally for merge_group and pushes to main — i.e. in the merge queue
|
||||
// before this can land, not on every PR push. Renaming them out of the prefix
|
||||
// moves ~30s of subprocess work into every short lane; renaming the file out of
|
||||
// *_embedded_test.go drops them from the shard runner entirely.
|
||||
//
|
||||
// TestEmbeddedPrimeChangeDirPrimesTarget is the issue's repro end to end
|
||||
// (#5509): from repo-a, `bd -C repo-b prime` must emit repo-b's PRIME.md,
|
||||
// identically to `cd repo-b && bd prime`, while plain `bd prime` and an
|
||||
// env-only BEADS_DIR redirect keep priming the cwd.
|
||||
func TestEmbeddedPrimeChangeDirPrimesTarget(t *testing.T) {
|
||||
bd := buildBDForInitTests(t)
|
||||
const primeA = "# PRIME repo-a\n"
|
||||
const primeB = "# PRIME repo-b\n"
|
||||
repoA := primeChangeDirRepo(t, map[string]string{".beads/PRIME.md": primeA})
|
||||
repoB := primeChangeDirRepo(t, map[string]string{".beads/PRIME.md": primeB})
|
||||
env := bdEnv(repoA)
|
||||
|
||||
if got := primeChangeDirRun(t, bd, repoB, env, "prime", "--no-memories"); got != primeB {
|
||||
t.Fatalf("reference cd repo-b && bd prime = %q, want %q", got, primeB)
|
||||
}
|
||||
if got := primeChangeDirRun(t, bd, repoA, env, "-C", repoB, "prime", "--no-memories"); got != primeB {
|
||||
t.Fatalf("bd -C repo-b prime from repo-a = %q, want repo-b %q", got, primeB)
|
||||
}
|
||||
relB, err := filepath.Rel(repoA, repoB)
|
||||
if err != nil {
|
||||
t.Fatalf("relative path to repo-b: %v", err)
|
||||
}
|
||||
if got := primeChangeDirRun(t, bd, repoA, env, "-C", relB, "prime", "--no-memories"); got != primeB {
|
||||
t.Fatalf("bd -C %s prime from repo-a = %q, want repo-b %q", relB, got, primeB)
|
||||
}
|
||||
if got := primeChangeDirRun(t, bd, repoA, env, "prime", "--no-memories"); got != primeA {
|
||||
t.Fatalf("bd prime in repo-a = %q, want %q", got, primeA)
|
||||
}
|
||||
envRedirect := append(bdEnv(repoA), "BEADS_DIR="+filepath.Join(repoB, ".beads"))
|
||||
if got := primeChangeDirRun(t, bd, repoA, envRedirect, "prime", "--no-memories"); got != primeA {
|
||||
t.Fatalf("env-only BEADS_DIR redirect must stay local-first: got %q, want %q", got, primeA)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEmbeddedPrimeChangeDirDefaultTemplateMatchesTarget covers the generated
|
||||
// (no PRIME.md) path of #5509. The default template's git-authority wording
|
||||
// comes from git probes and the AGENTS.md/CLAUDE.md divergence reminder from
|
||||
// the workspace files; both must describe the -C target, not the cwd. repo-a
|
||||
// has a remote with an upstream-tracking branch and no agent files; repo-b has
|
||||
// no remote and both agent files carrying the bd marker.
|
||||
func TestEmbeddedPrimeChangeDirDefaultTemplateMatchesTarget(t *testing.T) {
|
||||
bd := buildBDForInitTests(t)
|
||||
repoA := primeChangeDirRepo(t, nil)
|
||||
primeChangeDirGit(t, repoA, "commit", "-q", "--allow-empty", "-m", "init")
|
||||
primeChangeDirGit(t, repoA, "remote", "add", "origin", filepath.Join(t.TempDir(), "origin.git"))
|
||||
primeChangeDirGit(t, repoA, "update-ref", "refs/remotes/origin/main", "HEAD")
|
||||
primeChangeDirGit(t, repoA, "config", "branch.main.remote", "origin")
|
||||
primeChangeDirGit(t, repoA, "config", "branch.main.merge", "refs/heads/main")
|
||||
repoB := primeChangeDirRepo(t, map[string]string{
|
||||
"AGENTS.md": "# Agents\n" + markerBlock,
|
||||
"CLAUDE.md": "# Claude\n" + markerBlock,
|
||||
})
|
||||
env := bdEnv(repoA)
|
||||
|
||||
want := primeChangeDirRun(t, bd, repoB, env, "prime", "--no-memories")
|
||||
cwdOut := primeChangeDirRun(t, bd, repoA, env, "prime", "--no-memories")
|
||||
if want == cwdOut {
|
||||
t.Fatal("fixture: repo-a and repo-b must prime differently")
|
||||
}
|
||||
got := primeChangeDirRun(t, bd, repoA, env, "-C", repoB, "prime", "--no-memories")
|
||||
if got != want {
|
||||
t.Fatalf("bd -C repo-b prime from repo-a differs from cd repo-b && bd prime: %s", primeFirstDiff(got, want))
|
||||
}
|
||||
if got == cwdOut {
|
||||
t.Fatal("bd -C repo-b prime from repo-a still primes repo-a")
|
||||
}
|
||||
// Name the two repo-b facts that must have followed -C.
|
||||
for _, needle := range []string{
|
||||
"No git remote configured",
|
||||
"AGENTS.md and CLAUDE.md are independent files",
|
||||
} {
|
||||
if !strings.Contains(want, needle) {
|
||||
t.Errorf("fixture: cd repo-b && bd prime lacks %q", needle)
|
||||
}
|
||||
if !strings.Contains(got, needle) {
|
||||
t.Errorf("bd -C repo-b prime from repo-a lacks %q", needle)
|
||||
}
|
||||
if strings.Contains(cwdOut, needle) {
|
||||
t.Errorf("fixture: bd prime in repo-a must not contain %q", needle)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestEmbeddedPrimeChangeDirRedirectNoticeFollowsTarget covers the default
|
||||
// template's redirect notice under -C (#5509): it must describe the -C
|
||||
// target's redirect state in both directions. From a plain repo,
|
||||
// `bd -C clone prime` must carry the clone's "Redirected" notice naming the
|
||||
// clone's store; from a redirect clone, `bd -C plain prime` must carry no
|
||||
// notice and never name the cwd's store. Each direction is compared byte for
|
||||
// byte with `cd <target> && bd prime`.
|
||||
func TestEmbeddedPrimeChangeDirRedirectNoticeFollowsTarget(t *testing.T) {
|
||||
bd := buildBDForInitTests(t)
|
||||
plain := primeChangeDirRepo(t, nil)
|
||||
store := primeTestWorkspace(t, map[string]string{".beads/metadata.json": primeTestMetadata})
|
||||
storeBeads := filepath.Join(store, ".beads")
|
||||
clone := primeChangeDirRedirectClone(t, storeBeads)
|
||||
env := bdEnv(plain)
|
||||
|
||||
refPlain := primeChangeDirRun(t, bd, plain, env, "prime", "--no-memories")
|
||||
refClone := primeChangeDirRun(t, bd, clone, env, "prime", "--no-memories")
|
||||
if !strings.Contains(refClone, "Redirected") || !strings.Contains(refClone, storeBeads) {
|
||||
t.Fatalf("fixture: cd clone && bd prime must carry a Redirected notice naming %s:\n%s", storeBeads, refClone)
|
||||
}
|
||||
if strings.Contains(refPlain, "Redirected") || strings.Contains(refPlain, storeBeads) {
|
||||
t.Fatalf("fixture: cd plain && bd prime must carry no redirect notice:\n%s", refPlain)
|
||||
}
|
||||
|
||||
// cwd = plain repo, -C = redirect clone: the clone's notice must appear.
|
||||
got := primeChangeDirRun(t, bd, plain, env, "-C", clone, "prime", "--no-memories")
|
||||
if !strings.Contains(got, "Redirected") || !strings.Contains(got, storeBeads) {
|
||||
t.Errorf("bd -C clone prime from plain lacks the clone's Redirected notice naming %s", storeBeads)
|
||||
}
|
||||
if got != refClone {
|
||||
t.Errorf("bd -C clone prime from plain differs from cd clone && bd prime: %s", primeFirstDiff(got, refClone))
|
||||
}
|
||||
|
||||
// cwd = redirect clone, -C = plain repo: no notice, and never the cwd's store.
|
||||
got = primeChangeDirRun(t, bd, clone, env, "-C", plain, "prime", "--no-memories")
|
||||
if strings.Contains(got, "Redirected") || strings.Contains(got, storeBeads) {
|
||||
t.Errorf("bd -C plain prime from clone carries the cwd's redirect notice:\n%s", got)
|
||||
}
|
||||
if got != refPlain {
|
||||
t.Errorf("bd -C plain prime from clone differs from cd plain && bd prime: %s", primeFirstDiff(got, refPlain))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -348,16 +348,41 @@ type RedirectInfo struct {
|
|||
// BEADS_DIR is set. This handles the case where BEADS_DIR is pre-set to the redirect target
|
||||
// (e.g., by shell environment or tooling), but we still need to detect that a redirect exists.
|
||||
func GetRedirectInfo() RedirectInfo {
|
||||
return redirectInfoFor(findLocalBdsDirInRepo(), findLocalBeadsDir)
|
||||
}
|
||||
|
||||
// GetRedirectInfoFrom is GetRedirectInfo for the workspace at dir rather than
|
||||
// the process cwd: the .beads directory at dir's git repository root is
|
||||
// checked for a redirect first, then the nearest .beads walking up from dir.
|
||||
// BEADS_DIR is not consulted, since a caller asking about dir has already
|
||||
// resolved it (under `bd -C dir` it names the redirect target itself, which
|
||||
// would mask the clone's redirect). Used by `bd -C dir prime` so the redirect
|
||||
// notice describes the primed workspace (gastownhall/beads#5509).
|
||||
//
|
||||
// NOTE: the non-git fallback here is the walk-up probe alone, so relative to
|
||||
// GetRedirectInfo this drops three cwd-specific tiers: BEADS_DIR (deliberate,
|
||||
// see above), the worktree-local redirect / separate-DB probe, and
|
||||
// GetWorktreeFallbackBeadsDir. Inside a git worktree those tiers can answer
|
||||
// differently, so a caller that has not already resolved dir the way
|
||||
// `bd -C dir` does wants GetRedirectInfo, not this.
|
||||
func GetRedirectInfoFrom(dir string) RedirectInfo {
|
||||
return redirectInfoFor(findLocalBdsDirInRepoFrom(dir), func() string { return findBeadsDirUpward(dir) })
|
||||
}
|
||||
|
||||
// redirectInfoFor reports the redirect state given the repo-local .beads
|
||||
// directory ("" outside a git repository) and a fallback locator for the
|
||||
// non-git case.
|
||||
func redirectInfoFor(repoLocalBeadsDir string, fallback func() string) RedirectInfo {
|
||||
// First, always check the git repo's local .beads directory for redirects
|
||||
// This handles the case where BEADS_DIR is pre-set to the redirect target
|
||||
if localBeadsDir := findLocalBdsDirInRepo(); localBeadsDir != "" {
|
||||
if info := checkRedirectInDir(localBeadsDir); info.IsRedirected {
|
||||
if repoLocalBeadsDir != "" {
|
||||
if info := checkRedirectInDir(repoLocalBeadsDir); info.IsRedirected {
|
||||
return info
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to original logic for non-git-repo cases
|
||||
if localBeadsDir := findLocalBeadsDir(); localBeadsDir != "" {
|
||||
if localBeadsDir := fallback(); localBeadsDir != "" {
|
||||
return checkRedirectInDir(localBeadsDir)
|
||||
}
|
||||
|
||||
|
|
@ -392,13 +417,36 @@ func checkRedirectInDir(beadsDir string) RedirectInfo {
|
|||
// This ignores BEADS_DIR to find the "true local" .beads for redirect detection.
|
||||
// bd-wayc3: Added to detect redirects even when BEADS_DIR is pre-set.
|
||||
func findLocalBdsDirInRepo() string {
|
||||
// Get git repo root
|
||||
repoRoot := git.GetRepoRoot()
|
||||
return repoLocalBeadsDir(git.GetRepoRoot())
|
||||
}
|
||||
|
||||
// findLocalBdsDirInRepoFrom is findLocalBdsDirInRepo for the git repository
|
||||
// containing dir rather than the process cwd.
|
||||
func findLocalBdsDirInRepoFrom(dir string) string {
|
||||
repoRoot, err := gitOutput(dir, "rev-parse", "--show-toplevel")
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return repoLocalBeadsDir(repoRoot)
|
||||
}
|
||||
|
||||
// repoLocalBeadsDir returns <repoRoot>/.beads when repoRoot is known and the
|
||||
// directory exists, else "".
|
||||
//
|
||||
// repoRoot is canonicalized here so both locators share one form: the cwd
|
||||
// variant receives it pre-canonicalized from git.GetRepoRoot(), while the From
|
||||
// variant hands over raw `git rev-parse --show-toplevel` output, which on
|
||||
// Windows is `C:/...` or msys `/c/...`. Left un-normalized, the os.Stat below
|
||||
// misses and the repo-local tier falls through to the walk-up locator — the
|
||||
// fallback bd-wayc3 exists to beat. Canonicalizing after the "" guard is
|
||||
// deliberate: utils.CanonicalizePath("") resolves to the process cwd, which
|
||||
// would leak the cwd's .beads into an answer about another directory.
|
||||
func repoLocalBeadsDir(repoRoot string) string {
|
||||
if repoRoot == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
beadsDir := filepath.Join(repoRoot, ".beads")
|
||||
beadsDir := filepath.Join(utils.CanonicalizePath(git.NormalizePath(repoRoot)), ".beads")
|
||||
if info, err := os.Stat(beadsDir); err == nil && info.IsDir() {
|
||||
return beadsDir
|
||||
}
|
||||
|
|
@ -444,8 +492,13 @@ func findLocalBeadsDir() string {
|
|||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return findBeadsDirUpward(cwd)
|
||||
}
|
||||
|
||||
walk := NewAncestorDirWalk(cwd, cwd)
|
||||
// findBeadsDirUpward returns the nearest .beads directory at or above start,
|
||||
// without following redirects, or "" when there is none.
|
||||
func findBeadsDirUpward(start string) string {
|
||||
walk := NewAncestorDirWalk(start, start)
|
||||
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() {
|
||||
|
|
|
|||
|
|
@ -421,6 +421,114 @@ func TestCheckRedirectInDir(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
// TestGetRedirectInfoFrom covers the -C form of redirect detection
|
||||
// (gastownhall/beads#5509): it reports the named workspace's redirect state,
|
||||
// while GetRedirectInfo keeps reporting the cwd's, with BEADS_DIR already
|
||||
// resolved to the store the way `bd -C` sets it.
|
||||
func TestGetRedirectInfoFrom(t *testing.T) {
|
||||
t.Cleanup(git.ResetCaches)
|
||||
tmpDir := t.TempDir()
|
||||
tmpDir, _ = filepath.EvalSymlinks(tmpDir)
|
||||
|
||||
storeDir := filepath.Join(tmpDir, "store", ".beads")
|
||||
clone := filepath.Join(tmpDir, "clone")
|
||||
plain := filepath.Join(tmpDir, "plain")
|
||||
loose := filepath.Join(tmpDir, "loose")
|
||||
for _, dir := range []string{storeDir, filepath.Join(clone, ".beads"), filepath.Join(plain, ".beads"), filepath.Join(loose, ".beads"), filepath.Join(loose, "sub")} {
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// Target must contain a recognizable database for FollowRedirect to
|
||||
// honor the redirect (gastownhall/beads#4692 guard).
|
||||
if err := os.WriteFile(filepath.Join(storeDir, "beads.db"), []byte{}, 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, dir := range []string{clone, loose} {
|
||||
if err := os.WriteFile(filepath.Join(dir, ".beads", "redirect"), []byte(storeDir+"\n"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, dir := range []string{clone, plain} {
|
||||
cmd := exec.Command("git", "init", "-q")
|
||||
cmd.Dir = dir
|
||||
if err := cmd.Run(); err != nil {
|
||||
t.Skipf("git not available: %v", err)
|
||||
}
|
||||
}
|
||||
t.Setenv("BEADS_DIR", storeDir)
|
||||
t.Setenv("BEADS_DB", "")
|
||||
|
||||
// cwd = redirect clone, workspace asked about = plain repo.
|
||||
t.Chdir(clone)
|
||||
git.ResetCaches()
|
||||
if !GetRedirectInfo().IsRedirected {
|
||||
t.Fatal("control: GetRedirectInfo in the clone must report its redirect")
|
||||
}
|
||||
if info := GetRedirectInfoFrom(plain); info.IsRedirected {
|
||||
t.Errorf("GetRedirectInfoFrom(plain) = %+v, want no redirect", info)
|
||||
}
|
||||
|
||||
// cwd = plain repo, workspace asked about = redirect clone.
|
||||
t.Chdir(plain)
|
||||
git.ResetCaches()
|
||||
if GetRedirectInfo().IsRedirected {
|
||||
t.Fatal("control: GetRedirectInfo in the plain repo must report no redirect")
|
||||
}
|
||||
if info := GetRedirectInfoFrom(clone); !info.IsRedirected || info.TargetDir != storeDir {
|
||||
t.Errorf("GetRedirectInfoFrom(clone) = %+v, want redirect to %q", info, storeDir)
|
||||
}
|
||||
|
||||
// No git repository: the nearest .beads above the directory is used.
|
||||
if info := GetRedirectInfoFrom(filepath.Join(loose, "sub")); !info.IsRedirected || info.TargetDir != storeDir {
|
||||
t.Errorf("GetRedirectInfoFrom(loose/sub) = %+v, want redirect to %q", info, storeDir)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRepoLocalBeadsDirCanonicalizesRepoRoot pins both halves of the shared
|
||||
// repo-local tier's contract (gastownhall/beads#5509): the repo root is
|
||||
// canonicalized before it is joined, so the From locator's raw
|
||||
// `git rev-parse --show-toplevel` output lands on the same .beads as the cwd
|
||||
// locator's already-canonical git.GetRepoRoot(); and "" stays "", because
|
||||
// canonicalizing it would resolve to the process cwd and answer about the
|
||||
// wrong workspace.
|
||||
func TestRepoLocalBeadsDirCanonicalizesRepoRoot(t *testing.T) {
|
||||
t.Cleanup(git.ResetCaches)
|
||||
tmpDir := t.TempDir()
|
||||
tmpDir, err := filepath.EvalSymlinks(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
realRoot := filepath.Join(tmpDir, "real")
|
||||
if err := os.MkdirAll(filepath.Join(realRoot, ".beads"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
linkRoot := filepath.Join(tmpDir, "link")
|
||||
if err := os.Symlink(realRoot, linkRoot); err != nil {
|
||||
t.Skipf("symlinks unavailable: %v", err)
|
||||
}
|
||||
|
||||
want := filepath.Join(realRoot, ".beads")
|
||||
if got := repoLocalBeadsDir(realRoot); got != want {
|
||||
t.Errorf("control: repoLocalBeadsDir(%q) = %q, want %q", realRoot, got, want)
|
||||
}
|
||||
// A non-canonical root must resolve to the canonical .beads. Without the
|
||||
// canonicalization this returns <link>/.beads, which string-compares
|
||||
// unequal against every other locator's answer for the same directory.
|
||||
if got := repoLocalBeadsDir(linkRoot); got != want {
|
||||
t.Errorf("repoLocalBeadsDir(symlinked root) = %q, want %q", got, want)
|
||||
}
|
||||
|
||||
// "" means "not in a git repository". Canonicalizing before this guard
|
||||
// would turn it into the cwd and report the cwd's .beads as the named
|
||||
// workspace's — the cwd leak the -C fix exists to remove.
|
||||
t.Chdir(realRoot)
|
||||
if got := repoLocalBeadsDir(""); got != "" {
|
||||
t.Errorf("repoLocalBeadsDir(\"\") = %q, want \"\" (cwd must not leak in)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFollowRedirect_ChainPrevention tests that redirect chains are not followed
|
||||
func TestFollowRedirect_ChainPrevention(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue