fix(cli): preserve redirect-source dolt_database for no-DB commands, guarded on explicit targets (#5774)

* fix(doctor): preserve redirect-source dolt_database for no-DB commands (be-xil)

selectedNoDBBeadsDir() (used by doctor/bootstrap/context/dolt no-DB
commands) resolves an ambient beads dir via beads.FindBeadsDir(), which
always follows a .beads/redirect internally before returning. By the
time prepareSelectedNoDBContext's own internal
preserveRedirectSourceDatabase call sees a beadsDir, it is already the
post-redirect target (which has no redirect file of its own), so the
source repo's configured dolt_database is silently never captured into
BEADS_DOLT_SERVER_DATABASE. doctor's Dolt health checks still open the
store via BEADS_DOLT_SERVER_DATABASE when set, so this left doctor
falling through to the shared target's own default database and
reporting a false "wrong database" diagnosis with a destructive --fix.

Call preserveRedirectSourceDatabase with the source dir explicitly
before selectedNoDBBeadsDir() resolves and loses that information,
mirroring the pattern already used by the store-requiring
PersistentPreRunE path just below it.

go build/vet ./cmd/bd/... clean; new regression test and sibling
PersistentPreRun tests pass.

* test(doctor): red — explicit --db target must override ambient redirect

Adds TestDoctorPersistentPreRunExplicitDBTargetOverridesAmbientRedirect,
covering both reviewers' round-1 change request: an explicit --db target
must not be shadowed by an ambient repo's unrelated redirect-source
database. Currently RED — preserveRedirectSourceDatabase() is called
unconditionally, so BEADS_DOLT_SERVER_DATABASE leaks the ambient repo's
redirect-source db past the explicit target.

refs be-fyt

* fix(doctor): green — guard redirect-source preservation on explicit --db

Round 1 of be-fyt review: preserveRedirectSourceDatabase() was called
unconditionally inside the skipsStoreInit branch, mirroring the guard
already present on the store-requiring sibling branch below it. Since
beads.GetRedirectInfo() always resolves from the ambient CWD repo's
local .beads regardless of --db/BEADS_DIR (bd-wayc3), an explicit
--db/BEADS_DB/BD_DB target's own database was silently shadowed by the
ambient repo's unrelated redirect-source database — reopening be-xil's
failure mode via a narrower trigger.

Fix: only preserve the redirect-source database when dbPath is unset,
matching the existing guard at the sibling call site.

TestDoctorPersistentPreRunExplicitDBTargetOverridesAmbientRedirect now
passes; full ./cmd/bd/... suite shows the identical 9 pre-existing
be-j8e-class failures as the pre-fix baseline, no new failures.

refs be-fyt

* docs(release-gates): add be-27c gate record

Explicit --db target must override ambient redirect-source database
(be-xil follow-on). PASS 7/7, independently re-verified.

* test(doctor): red — BEADS_DB/BD_DB leak past the redirect-source guard

The skipsStoreInit guard added in 848ed9f9 is spelled `dbPath == ""`, and
the PR body describes it as covering "an explicit --db, BEADS_DB, or BD_DB
target". It does not: main.go:1002-1004 only falls back to the configured
db when BEADS_DB, BD_DB and BEADS_DIR are all unset, so with either env var
set and no --db flag, dbPath stays "" and the guard reads "no explicit
target given" for a caller that gave a perfectly explicit one.

selectedNoDBBeadsDir (main.go:519, :523) does honor BEADS_DB and BD_DB, so
the two disagree: BEADS_DIR is correctly rebound to the explicit target
while the ambient repo's redirect-source database is preserved into
BEADS_DOLT_SERVER_DATABASE anyway. That is be-xil's "wrong database"
failure mode, still live for two of the three targets the guard names.

Both subtests fail at this commit:

  BEADS_DOLT_SERVER_DATABASE = "ambient_source_db", want ""
    (leaked past an explicit BEADS_DB target)
  BEADS_DOLT_SERVER_DATABASE = "ambient_source_db", want ""
    (leaked past an explicit BD_DB target)

Reported in review of PR #5774 by bee-ghosttrack, item 2.

* fix(doctor): green — guard on the explicit target, not on dbPath

Replace the `dbPath == ""` guard with explicitDBTargetGiven(), which asks
the question selectedNoDBBeadsDir asks — dbPath, BEADS_DB, or BD_DB — so
the two cannot drift apart again. Both subtests from the previous commit
now pass; the four pre-existing PersistentPreRun tests are unchanged.

Deliberately NOT keyed on PersistentFlags().Changed("db"), which the review
suggested as the condition. A --db value naming a *database* rather than a
path is moved to dbNameFromDBFlag and clears dbPath (main.go ~990), and it
is consumed only on the store-requiring path (~1553, proxied-server mode).
On the no-DB path selectedNoDBBeadsDir therefore finds no explicit
directory target and falls through to beads.FindBeadsDir(), which follows
the ambient repo's redirect — so the ambient workspace IS what gets
selected and its source database must still be preserved. Measured on the
previous commit with `bd doctor --db somebaredbname` in a redirected repo:

  dbPath=""
  BEADS_DIR=".../ambient-shared/.beads"      ← ambient redirect target
  BEADS_DOLT_SERVER_DATABASE="ambient_source_db"   ← correctly preserved

Keying on Changed("db") suppresses that and reopens be-xil for
`bd doctor --db <name>`. TestDoctorPersistentPreRunBareDBNameStillPreserves-
AmbientSourceDatabase pins it: with Changed("db") in the predicate it fails
with `BEADS_DOLT_SERVER_DATABASE = "", want "ambient_source_db"`.

(A free function referencing rootCmd also cannot compile here — it forms an
initialization cycle through rootCmd's own PersistentPreRunE — so that
variant would need cmd threaded through, as selectedNoDBBeadsDir does.)

Addresses review of PR #5774 by bee-ghosttrack, item 2.

* docs(changelog): record the redirect-source database fixes

Both entries under Unreleased/Fixed: the be-xil preservation for no-DB
commands, and the be-fyt explicit-target guard on top of it. Called out in
review of PR #5774 by bee-ghosttrack as a non-blocking gap — this is a
behavior change to bd doctor/bootstrap on every redirected workspace and
was not recorded anywhere users read.

* test(doctor): compare BEADS_DIR canonically so macOS passes

CI caught this on macos-latest (the only failing check on this PR):

  doctor_context_test.go:376:
    BEADS_DIR = "/private/var/folders/.../ambient-shared/.beads",
         want  "/var/folders/.../ambient-shared/.beads"

Same directory. On macOS /var is a symlink to /private/var, so t.TempDir()
hands back the /var form while the value under test is resolved through
beads.FindBeadsDir() -> utils.CanonicalizePath, which runs EvalSymlinks.
A raw string compare therefore fails on macOS and nowhere else.

Both of the assertions added in this PR now canonicalize each side before
comparing. Only my two are touched: the pre-existing sibling assertions
reach BEADS_DIR via resolveCommandBeadsDir(dbPath), which does not
EvalSymlinks, so they are unaffected and left alone rather than churned.

Canonicalizing is a no-op where the path is already resolved, so this is
symmetric and cannot mask a genuine mismatch — the assertion still fails if
a different directory is selected. Verified utils.CanonicalizePath does
resolve symlinks with a throwaway probe (symlink in, real path out).

* docs(cli): correct the "cannot drift apart" claim, name the BEADS_DIR gap

Review item 5 (round 2, PR #5774) is right and the claim in the code was
wrong. explicitDBTargetGiven covers three routes; selectedNoDBBeadsDir
honors a fourth — BEADS_DIR != "" -> beads.FindBeadsDir() (~line 551) —
so the two predicates still disagree there, and the comment asserting they
"cannot drift apart again" pointed a future reader at exactly the wrong
conclusion.

Reproduced before writing this, rather than taking the review's probe on
faith. At this head, BEADS_TEST_SKIP=dolt, ambient repo git init-ed with
an active redirect and BEADS_DIR naming an unrelated target:

  PROBE[git_repo]:  BEADS_DIR=".../target/.beads"
                    BEADS_DOLT_SERVER_DATABASE="ambient_source_db"  <- leaked
                    dbPath=""
  --- FAIL: .../git_repo
  --- PASS: .../plain_dir

The plain_dir control passes, which pins the defect to the bd-wayc3 branch:
GetRedirectInfo only reaches the ambient repo through findLocalBdsDirInRepo
(internal/beads/beads.go:394), which keys off git.GetRepoRoot() alone. Every
test in doctor_context_test.go builds a plain t.TempDir(), so the branch
production always takes has no coverage — that is the second half of it.

Comments only; no behavior change, and the gap is documented rather than
closed here deliberately. Emptiness is the wrong test for it: BEADS_DIR
pre-set to the redirect target is bd-wayc3's own case, where preservation is
wanted, so the fix has to compare BEADS_DIR against the redirect target.
That comparison, the git-repo fixture and the third test case are specified
in be-bf75p with the probe source attached.

gofmt/vet/build clean; go test ./cmd/bd/ -run
'TestDoctorPersistentPreRun|TestBootstrapPersistentPreRun' green.

* chore: remove leaked internal release-gate doc from PR branch

  release-gates/be-27c-redirect-source-guard-gate.md

Tracked our internal gc-management/beads-rig release-gate checklist and
should never have been committed to this upstream branch -- it's process
residue from our deploy tooling, not part of the change itself.

Per maintainer bee-ghosttrack's request during review of PR #6571. The
root cause (our deploy tooling auto-committing this file) is already fixed
as of gm-qatxl1; this branch predates that fix, so this commit is cleanup
only -- no other content on this branch is touched.

Ref: be-lk7o3

---------

Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jim Wordelman 2026-09-30 15:29:36 -07:00 • committed by GitHub
commit ed15632a16
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 347 additions and 0 deletions

View file

@ -9,6 +9,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- **No-DB commands in a redirected workspace no longer lose the source
repo's `dolt_database`** (be-xil, be-fyt). `bd doctor`, `bootstrap`,
`context`, `dolt`, `init` and `version` skip store init, and the beads dir
they select is resolved through `beads.FindBeadsDir()`, which follows a
`.beads/redirect` internally. The source repo's configured database name was
therefore gone before anything could capture it, so `bd doctor` fell through
to the shared target directory's own default database and reported
`Dolt Schema: wrong database` — offering a `--fix` that would have repointed
the rig at an unrelated rig's store. The redirect source is now captured
before that resolution, matching the store-requiring path.
- **An explicit `--db`, `BEADS_DB` or `BD_DB` target is no longer shadowed by
the ambient repo's redirect-source database** (be-fyt). `beads.GetRedirectInfo()`
deliberately resolves from the CWD repo's local `.beads` regardless of
`--db`/`BEADS_DIR` (bd-wayc3), so when the ambient repo itself had an active
redirect, the preservation above re-opened the same "wrong database" failure
through a narrower door. Preservation is now skipped whenever the caller
named an explicit target, asking the same question `selectedNoDBBeadsDir`
asks so the two cannot drift apart. Note that a `--db` value naming a
*database* rather than a path is not an explicit *directory* target: it is
consumed only on the store-requiring path, the ambient workspace is still
what gets selected, and its source database is still preserved.
- **An ambient `BEADS_DOLT_SERVER_PORT` now marks a workspace externally
managed — suppressing auto-start — and no longer stops bd reaping its own
orphaned server**

View file

@ -128,6 +128,262 @@ func TestDoctorPersistentPreRunUsesExplicitDBTarget(t *testing.T) {
}
}
// TestDoctorPersistentPreRunPreservesSourceDatabaseAcrossRedirect covers
// be-xil: bd doctor reported "Dolt Schema: wrong database" and offered a
// destructive --fix that would have repointed the rig at a different rig's
// store entirely.
//
// Root cause: selectedNoDBBeadsDir (used by doctor/bootstrap/context/dolt)
// resolves an ambient BEADS_DIR pointing at a redirect stub via
// beads.FindBeadsDir(), which always follows the redirect internally before
// returning. By the time prepareSelectedNoDBContext's own internal
// preserveRedirectSourceDatabase call sees a beadsDir, it's already the
// redirect TARGET (no redirect file of its own), so
// beads.ResolveRedirect never detects a redirect was followed and the
// source repo's configured dolt_database is silently never captured into
// BEADS_DOLT_SERVER_DATABASE. doctor's Dolt health checks resolve their own
// beadsDir independently (beads.ResolveBeadsDirForRepo, which also always
// follows the redirect) but still open the store via
// configfile.Config.GetDoltDatabase(), which checks BEADS_DOLT_SERVER_DATABASE
// before the loaded config's raw field — so this env var is the only thing
// standing between doctor and the shared target's own default database.
//
// The fix calls preserveRedirectSourceDatabase(beads.GetRedirectInfo().LocalDir)
// explicitly with the SOURCE dir before selectedNoDBBeadsDir resolves and
// loses that information; the function's own idempotency guard (early return
// once the env var is set) makes prepareSelectedNoDBContext's later internal
// call a harmless no-op.
func TestDoctorPersistentPreRunPreservesSourceDatabaseAcrossRedirect(t *testing.T) {
sourceRepo := filepath.Join(t.TempDir(), "source")
sourceBeadsDir := filepath.Join(sourceRepo, ".beads")
writeTestConfigYAML(t, sourceBeadsDir, "")
writeMetadataConfig(t, sourceBeadsDir, configfile.DoltModeServer, "source_db")
targetBeadsDir := filepath.Join(t.TempDir(), "shared", ".beads")
writeTestConfigYAML(t, targetBeadsDir, "")
writeMetadataConfig(t, targetBeadsDir, configfile.DoltModeServer, "target_default_db")
if err := os.WriteFile(filepath.Join(sourceBeadsDir, "redirect"), []byte(targetBeadsDir), 0o600); err != nil {
t.Fatalf("write redirect: %v", err)
}
t.Chdir(sourceRepo)
t.Setenv("BEADS_DIR", sourceBeadsDir)
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
t.Setenv("BEADS_DOLT_SERVER_DATABASE", "")
t.Setenv("BEADS_DOLT_SERVER_PORT", "")
config.ResetForTesting()
t.Cleanup(config.ResetForTesting)
savePersistentPreRunState(t)
if err := rootCmd.PersistentPreRunE(doctorCmd, nil); err != nil {
t.Fatalf("PersistentPreRunE: %v", err)
}
if got := os.Getenv("BEADS_DOLT_SERVER_DATABASE"); got != "source_db" {
t.Fatalf("BEADS_DOLT_SERVER_DATABASE = %q, want %q (source database lost across redirect — be-xil regression)", got, "source_db")
}
}
// TestDoctorPersistentPreRunExplicitDBTargetOverridesAmbientRedirect covers
// be-fyt round 1: the be-xil fix above called preserveRedirectSourceDatabase
// unconditionally in the skipsStoreInit branch (main.go ~1168), unlike its
// dbPath-guarded sibling at ~1223. beads.GetRedirectInfo() always resolves
// from the ambient CWD repo's local .beads regardless of --db/BEADS_DIR
// (bd-wayc3), so when the ambient repo itself has an active redirect AND the
// caller passes an explicit --db target, the ambient repo's redirect-source
// database silently shadowed the explicit target's own configured database —
// reopening be-xil's exact "wrong database" failure mode via a narrower
// trigger. Neither TestDoctorPersistentPreRunUsesExplicitDBTarget (no
// ambient redirect) nor TestDoctorPersistentPreRunPreservesSourceDatabaseAcrossRedirect
// (no explicit --db target) exercises the combination; this test does.
func TestDoctorPersistentPreRunExplicitDBTargetOverridesAmbientRedirect(t *testing.T) {
ambientSourceDir := filepath.Join(t.TempDir(), "ambient-source")
ambientSourceBeadsDir := filepath.Join(ambientSourceDir, ".beads")
writeTestConfigYAML(t, ambientSourceBeadsDir, "")
writeMetadataConfig(t, ambientSourceBeadsDir, configfile.DoltModeServer, "ambient_source_db")
ambientSharedBeadsDir := filepath.Join(t.TempDir(), "ambient-shared", ".beads")
writeTestConfigYAML(t, ambientSharedBeadsDir, "")
writeMetadataConfig(t, ambientSharedBeadsDir, configfile.DoltModeServer, "ambient_shared_default_db")
if err := os.WriteFile(filepath.Join(ambientSourceBeadsDir, "redirect"), []byte(ambientSharedBeadsDir), 0o600); err != nil {
t.Fatalf("write redirect: %v", err)
}
targetRepo := filepath.Join(t.TempDir(), "target")
targetBeadsDir := filepath.Join(targetRepo, ".beads")
writeTestConfigYAML(t, targetBeadsDir, "")
writeMetadataConfig(t, targetBeadsDir, configfile.DoltModeServer, "explicit_target_db")
// Run from within the ambient repo, whose own .beads has an active
// redirect, while an explicit --db points at a wholly unrelated target.
t.Chdir(ambientSourceDir)
t.Setenv("BEADS_DIR", ambientSourceBeadsDir)
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
t.Setenv("BEADS_DOLT_SERVER_DATABASE", "")
t.Setenv("BEADS_DOLT_SERVER_PORT", "")
config.ResetForTesting()
t.Cleanup(config.ResetForTesting)
savePersistentPreRunState(t)
targetDBPath := filepath.Join(targetBeadsDir, "dolt")
dbPath = targetDBPath
if flag := rootCmd.PersistentFlags().Lookup("db"); flag != nil {
flag.Changed = true
}
if err := rootCmd.PersistentPreRunE(doctorCmd, nil); err != nil {
t.Fatalf("PersistentPreRunE: %v", err)
}
if got := os.Getenv("BEADS_DOLT_SERVER_DATABASE"); got != "" {
t.Fatalf("BEADS_DOLT_SERVER_DATABASE = %q, want \"\" (ambient repo's redirect-source database leaked past an explicit --db target)", got)
}
if got := os.Getenv("BEADS_DIR"); got != targetBeadsDir {
t.Fatalf("BEADS_DIR = %q, want %q (explicit --db target)", got, targetBeadsDir)
}
}
// TestDoctorPersistentPreRunExplicitEnvDBTargetOverridesAmbientRedirect covers
// the env-var half of the same guard. The --db sibling above delivers the
// explicit target through the flag, which populates dbPath; BEADS_DB and BD_DB
// do not. main.go:1002-1004 only falls back to the configured db when
// BEADS_DB, BD_DB and BEADS_DIR are all unset, so with BEADS_DB set and no
// --db flag, dbPath stays "" — a guard spelled `dbPath == ""` therefore reads
// "no explicit target" for a caller that gave a perfectly explicit one.
// selectedNoDBBeadsDir (main.go:519, :523) does honor BEADS_DB/BD_DB as
// explicit targets, so the two disagree: BEADS_DIR is correctly rebound to the
// explicit target while the ambient repo's redirect-source database is
// preserved into BEADS_DOLT_SERVER_DATABASE anyway — be-xil's "wrong database"
// failure mode, still live for two of the three targets the guard names.
func TestDoctorPersistentPreRunExplicitEnvDBTargetOverridesAmbientRedirect(t *testing.T) {
for _, tc := range []struct {
name string
envVar string
}{
{name: "BEADS_DB", envVar: "BEADS_DB"},
{name: "BD_DB", envVar: "BD_DB"},
} {
t.Run(tc.name, func(t *testing.T) {
ambientSourceDir := filepath.Join(t.TempDir(), "ambient-source")
ambientSourceBeadsDir := filepath.Join(ambientSourceDir, ".beads")
writeTestConfigYAML(t, ambientSourceBeadsDir, "")
writeMetadataConfig(t, ambientSourceBeadsDir, configfile.DoltModeServer, "ambient_source_db")
ambientSharedBeadsDir := filepath.Join(t.TempDir(), "ambient-shared", ".beads")
writeTestConfigYAML(t, ambientSharedBeadsDir, "")
writeMetadataConfig(t, ambientSharedBeadsDir, configfile.DoltModeServer, "ambient_shared_default_db")
if err := os.WriteFile(filepath.Join(ambientSourceBeadsDir, "redirect"), []byte(ambientSharedBeadsDir), 0o600); err != nil {
t.Fatalf("write redirect: %v", err)
}
targetRepo := filepath.Join(t.TempDir(), "target")
targetBeadsDir := filepath.Join(targetRepo, ".beads")
writeTestConfigYAML(t, targetBeadsDir, "")
writeMetadataConfig(t, targetBeadsDir, configfile.DoltModeServer, "explicit_target_db")
// Run from within the ambient repo, whose own .beads has an active
// redirect. BEADS_DIR stays unset so the explicit target arrives
// solely through the env var under test.
t.Chdir(ambientSourceDir)
t.Setenv("BEADS_DIR", "")
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
t.Setenv("BEADS_DOLT_SERVER_DATABASE", "")
t.Setenv("BEADS_DOLT_SERVER_PORT", "")
config.ResetForTesting()
t.Cleanup(config.ResetForTesting)
savePersistentPreRunState(t)
// Explicit target via env var, with the --db flag deliberately
// untouched: dbPath stays "" all the way into the guard.
t.Setenv("BEADS_DB", "")
t.Setenv("BD_DB", "")
t.Setenv(tc.envVar, filepath.Join(targetBeadsDir, "dolt"))
if err := rootCmd.PersistentPreRunE(doctorCmd, nil); err != nil {
t.Fatalf("PersistentPreRunE: %v", err)
}
if got := os.Getenv("BEADS_DOLT_SERVER_DATABASE"); got != "" {
t.Fatalf("BEADS_DOLT_SERVER_DATABASE = %q, want \"\" (ambient repo's redirect-source database leaked past an explicit %s target)", got, tc.envVar)
}
if got, want := utils.CanonicalizePath(os.Getenv("BEADS_DIR")), utils.CanonicalizePath(targetBeadsDir); got != want {
t.Fatalf("BEADS_DIR = %q, want %q (explicit %s target)", got, want, tc.envVar)
}
})
}
}
// TestDoctorPersistentPreRunBareDBNameStillPreservesAmbientSourceDatabase pins
// why explicitDBTargetGiven does not key on PersistentFlags().Changed("db").
//
// A --db value that names a database rather than a path is moved to
// dbNameFromDBFlag and clears dbPath (main.go ~990), leaving Changed("db")
// true with dbPath == "". That value is consumed only on the store-requiring
// path (~1553, proxied-server mode), so on the no-DB path selectedNoDBBeadsDir
// finds no explicit directory target and falls through to beads.FindBeadsDir(),
// which follows the ambient repo's redirect. The selected workspace IS the
// ambient one, so the ambient source's dolt_database must still be preserved —
// exactly be-xil's fix. A guard that treated Changed("db") as "explicit target
// given" would suppress preservation here and reopen be-xil for
// `bd doctor --db <name>` in a redirected repo.
func TestDoctorPersistentPreRunBareDBNameStillPreservesAmbientSourceDatabase(t *testing.T) {
ambientSourceDir := filepath.Join(t.TempDir(), "ambient-source")
ambientSourceBeadsDir := filepath.Join(ambientSourceDir, ".beads")
writeTestConfigYAML(t, ambientSourceBeadsDir, "")
writeMetadataConfig(t, ambientSourceBeadsDir, configfile.DoltModeServer, "ambient_source_db")
ambientSharedBeadsDir := filepath.Join(t.TempDir(), "ambient-shared", ".beads")
writeTestConfigYAML(t, ambientSharedBeadsDir, "")
writeMetadataConfig(t, ambientSharedBeadsDir, configfile.DoltModeServer, "ambient_shared_default_db")
if err := os.WriteFile(filepath.Join(ambientSourceBeadsDir, "redirect"), []byte(ambientSharedBeadsDir), 0o600); err != nil {
t.Fatalf("write redirect: %v", err)
}
t.Chdir(ambientSourceDir)
t.Setenv("BEADS_DIR", "")
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
t.Setenv("BEADS_DOLT_SERVER_DATABASE", "")
t.Setenv("BEADS_DOLT_SERVER_PORT", "")
config.ResetForTesting()
t.Cleanup(config.ResetForTesting)
savePersistentPreRunState(t)
t.Setenv("BEADS_DB", "")
t.Setenv("BD_DB", "")
// A valid identifier that does not exist as a path: main.go ~990 routes it
// to dbNameFromDBFlag and clears dbPath.
dbPath = "somebaredbname"
if flag := rootCmd.PersistentFlags().Lookup("db"); flag != nil {
flag.Changed = true
}
if err := rootCmd.PersistentPreRunE(doctorCmd, nil); err != nil {
t.Fatalf("PersistentPreRunE: %v", err)
}
if dbPath != "" {
t.Fatalf("dbPath = %q, want \"\" — precondition: a bare --db name must be moved off dbPath, otherwise this test no longer covers the Changed(\"db\")/dbPath==\"\" combination", dbPath)
}
// Compare canonicalized: this path is resolved through beads.FindBeadsDir(),
// which runs utils.CanonicalizePath (EvalSymlinks). On macOS t.TempDir()
// hands back /var/folders/... while the resolved form is /private/var/... —
// the same directory, so a raw string compare fails there and nowhere else.
if got, want := utils.CanonicalizePath(os.Getenv("BEADS_DIR")), utils.CanonicalizePath(ambientSharedBeadsDir); got != want {
t.Fatalf("BEADS_DIR = %q, want %q — precondition: a bare --db name selects no explicit directory, so the ambient redirect target must be chosen", got, want)
}
if got := os.Getenv("BEADS_DOLT_SERVER_DATABASE"); got != "ambient_source_db" {
t.Fatalf("BEADS_DOLT_SERVER_DATABASE = %q, want %q (be-xil regression: the ambient workspace was selected, so its redirect-source database must still be preserved — do not add Changed(\"db\") to explicitDBTargetGiven)", got, "ambient_source_db")
}
}
func TestBootstrapPersistentPreRunUsesExplicitDBTarget(t *testing.T) {
callerRepo := filepath.Join(t.TempDir(), "caller")
callerBeadsDir := filepath.Join(callerRepo, ".beads")

View file

@ -625,6 +625,36 @@ func preserveRedirectSourceDatabase(beadsDir string) {
}
}
// explicitDBTargetGiven reports whether the caller named an explicit database
// target that overrides the ambient workspace. These are the three routes the
// PR body for be-fyt names and that selectedNoDBBeadsDir below honors ahead of
// the ambient repo: a --db value that resolves to a path (which lands in
// dbPath), BEADS_DB, and BD_DB.
//
// Deliberately NOT keyed on PersistentFlags().Changed("db"). A --db value that
// names a *database* rather than a path is moved to dbNameFromDBFlag and
// clears dbPath (~line 990), and that value is consumed only on the
// store-requiring path (~line 1553). On the no-DB path selectedNoDBBeadsDir
// therefore falls through to the ambient workspace anyway, so the ambient
// redirect source's database must still be preserved for it. Keying on
// Changed("db") would suppress that and reopen be-xil for
// `bd doctor --db <name>` in a redirected repo; see
// TestDoctorPersistentPreRunBareDBNameStillPreservesAmbientSourceDatabase.
//
// KNOWN GAP (be-bf75p): selectedNoDBBeadsDir honors a fourth route this
// predicate does not — BEADS_DIR != "" -> beads.FindBeadsDir() (~line 551) —
// so a BEADS_DIR naming a foreign target still inherits the ambient repo's
// redirect-source database. Reproduces only inside a git repo, because
// GetRedirectInfo reaches the ambient repo through findLocalBdsDirInRepo
// (internal/beads/beads.go:394), which keys off git.GetRepoRoot() alone.
// Emptiness is the wrong test for it: BEADS_DIR pre-set *to the redirect
// target* is bd-wayc3's own case, where preservation is wanted, so the fix has
// to compare BEADS_DIR against the redirect target rather than check that it
// is unset. That comparison is be-bf75p's, not this PR's.
func explicitDBTargetGiven() bool {
return dbPath != "" || os.Getenv("BEADS_DB") != "" || os.Getenv("BD_DB") != ""
}
func selectedNoDBBeadsDir(cmd *cobra.Command) string {
if cmd != nil && cmd.Root() != nil && cmd.Root().PersistentFlags().Changed("db") && dbPath != "" {
if selectedBeadsDir := resolveCommandBeadsDir(dbPath); selectedBeadsDir != "" {
@ -1293,7 +1323,46 @@ var rootCmd = &cobra.Command{
// setup before they inspect server mode or per-project Dolt settings.
// Rebind them to the selected workspace so explicit --db / BEADS_DB
// targets behave consistently across doctor/bootstrap/context/dolt.
//
// Capture redirect info BEFORE selectedNoDBBeadsDir() resolves the
// beads dir, mirroring the store-requiring path below (be-xil):
// selectedNoDBBeadsDir() always returns the post-redirect target
// directory (every branch bottoms out in beads.FindBeadsDir() or a
// dbPath already resolved through it, both of which call
// FollowRedirect internally). Calling preserveRedirectSourceDatabase
// with that already-resolved target means beads.ResolveRedirect finds
// no redirect file there and silently never preserves the source's
// configured dolt_database — so doctor (and other no-DB commands)
// would fall through to the shared target directory's own default
// database instead of the source's, producing false "wrong database"
// diagnoses against an unrelated rig's schema.
if skipsStoreInit {
// be-fyt round 1: only preserve when the caller did NOT name an
// explicit target. beads.GetRedirectInfo() always resolves from the
// ambient CWD repo's local .beads regardless of --db/BEADS_DIR
// (bd-wayc3), so calling it unconditionally let an explicit --db/
// BEADS_DB/BD_DB target's own database be silently shadowed by the
// ambient repo's unrelated redirect-source database — reopening
// be-xil's failure mode via a narrower trigger.
//
// Round 2 (review of PR #5774): the guard was spelled `dbPath == ""`,
// but dbPath is populated from BEADS_DB/BD_DB only when those are
// *unset* (~line 1002), so both env routes slipped straight through
// a guard that claimed to cover them while selectedNoDBBeadsDir
// (~lines 519, 523) rebound BEADS_DIR to the explicit target — the
// two disagreed. explicitDBTargetGiven now covers all three of the
// routes that populate dbPath/BEADS_DB/BD_DB.
//
// It does NOT cover selectedNoDBBeadsDir's fourth route, BEADS_DIR
// (~line 551), so the two predicates still disagree there and a
// foreign BEADS_DIR target inherits the ambient repo's
// redirect-source database — inside a git repo only. Measured, not
// assumed; tracked and specified as be-bf75p. See the KNOWN GAP
// paragraph on explicitDBTargetGiven for why emptiness is the wrong
// test and what the fix has to compare instead.
if !explicitDBTargetGiven() {
preserveRedirectSourceDatabase(beads.GetRedirectInfo().LocalDir)
}
beadsDir := selectedNoDBBeadsDir(cmd)
prepareSelectedNoDBContext(beadsDir)
refreshBoundCommandConfig(cmd)