beads/cmd/bd/config_apply_test.go
Steve Yegge 46aa59cc65
test(cmd/bd): stop tests from mutating the host checkout's .git; guard it in TestMain (wy-qlvlmf) (#7650)
* wy-qlvlmf: test(cmd/bd): stop tests from mutating the host checkout's .git; guard it in TestMain

On 2026-10-16 a 'go test ./cmd/bd' run from a linked worktree rewrote the
host rig's shared .git/config (core.bare=true, extensions.worktreeConfig,
remote.origin.url replaced by metadata_test's fixture URL, user identity,
core.hooksPath) and its hooks dir, leaving every worktree of that clone
answering 'fatal: this operation must be run in a work tree' (r880).

Root causes, all one class — fixture git commands routed at the repository
the test process itself lives in instead of a fixture the test owns:
- TestRunApplyAllOK ran runApply(false) (a LIVE apply: hook reinstall,
  hooksPath mkdir) with no fixture, against the package cwd's repo.
- runGitForBootstrapTest treated dir=="" as 'inherit package cwd'.
- doctor/fix setupGitRepoInDir swallowed git config failures non-fatally
  and ran with whatever git routing env (GIT_DIR, GIT_WORK_TREE) leaked in.

Fixes:
- TestRunApplyAllOK / TestRunApplyDryRun now chdir into an isolated
  git+.beads fixture (isolatedApplyFixture + runInDir).
- runGitForBootstrapTest: empty dir gets a neutral t.TempDir() cwd, never
  the package cwd; env scrubbed of git routing vars.
- initGitRepoAt / doctor setupGitRepoInDir / doctor-fix setupGitRepoInDir:
  refuse an empty dir, fail on ANY git error, scrub routing env.
- testMainInner scrubs git routing env process-wide at startup.
- TestMain's repo guard now also snapshots the checkout's own git state
  (common .git/config, config.worktree, common hooks dir) and reddens the
  run on any diff, naming the mutated file.

Guard vacuity check: a probe test writing one key into the checkout's
.git/config passes individually and reddens the suite via the guard.

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

* build(bazel): auto-sync BUILD files

Applied from the bazel-sync-patch artifact of https://github.com/gastownhall/beads/actions/runs/39013861275
(`make bazel-sync`: gazelle, tools/bazel/go_srcs.py, bazel mod tidy).
Only BUILD.bazel, MODULE.bazel and MODULE.bazel.lock are ever pushed; see
scripts/bazel-autofix-push.sh.

* test(cmd/bd): scrub doctor suites, keep git fences, key-level config guard (wy-qlvlmf)

Maintainer fixup on top of #7650 by cat, for the first review's three
majors, minor and nit, and three of the second review's minors.

- Doctor suites: the leaked-GIT_DIR vector was still open in
  cmd/bd/doctor and cmd/bd/doctor/fix. Their four TestMains now unset
  the repository-location env first (testutil.UnsetGitRepoLocationEnv),
  and the three initGitTemplate copies plus
  testutil.ForceRepoLocalHooksPath run git with a filtered env. With
  GIT_DIR/GIT_WORK_TREE leaked at a decoy repo, the PR head wrote
  core.hooksPath into the decoy and failed 120 doctor tests; with this
  commit all three packages pass and the decoy stays byte-identical.

- Narrower scrub: the process-wide scrub also removed
  GIT_CEILING_DIRECTORIES and the GIT_CONFIG_* fences that
  tools/bazel/test_env.sh and scripts/ci/lib/test-env.sh set on purpose.
  testutil.WithoutGitRepoLocationEnv removes only GIT_DIR, GIT_WORK_TREE,
  GIT_COMMON_DIR, GIT_INDEX_FILE, GIT_OBJECT_DIRECTORY,
  GIT_ALTERNATE_OBJECT_DIRECTORIES, GIT_NAMESPACE and the legacy
  GIT_CONFIG (which sends `git config` reads and writes to the file it
  names, even under -C). Keys match exactly, so GIT_CEILING_DIRECTORIES,
  GIT_CONFIG_GLOBAL and GIT_CONFIG_NOSYSTEM stay. Every helper that
  built its own scrubbed env now uses it.

- Guard false reds: the TestMain guard compared the shared common config
  byte for byte, so a sibling worktree's routine branch write failed a
  passing run. It now diffs `git config --list -z` key by key.
  branch.<name>.* keys, and a remote other than origin added or removed
  whole, print a NOTE and leave the exit code alone. Any other key
  (including origin appearing or disappearing, and a changed key of a
  remote that exists before and after), any config.worktree change, any
  hook file change or an unparseable config still fails the run.

- config.worktree: the guard also snapshots a main checkout's own
  config.worktree, which sits in the common dir. With
  extensions.worktreeConfig set its keys override the shared config, and
  before this an escaped `git config --worktree` write there went
  unreported.

- Report: changed keys are named with values redacted, deleted and new
  files are reported as such, pre-run copies of the changed files are
  saved (0700 dir, 0600 files) and their path printed, and a failure to
  locate the checkout's git dirs prints a warning instead of disarming
  the guard silently.

- doctor setupGitRepoInDir stat-checks its dir like the doctor/fix copy.

New tests: internal/testutil/git_env_test.go, and
cmd/bd/test_repo_git_guard_test.go (real-git fixtures for locating the
git dirs, classifying writes, config parsing and the report).

Validation: ./scripts/test.sh ./cmd/bd in a scratch clone with GIT_DIR
leaked at a decoy (ok; decoy and the clone's .git unchanged; guard
quiet); bazel test --config=ci for testutil, doctor, doctor/fix,
fmt_test and the new bd_test guard tests; make ci-pr-lint;
tools/bazel/go_srcs.py --check.

Second review: leaving GIT_CONFIG out of the scrub fails
TestWithoutGitRepoLocationEnvKeepsWrapperGitControls and
TestForceRepoLocalHooksPathIgnoresLeakedGitDir; the old main-checkout
config.worktree path fails TestLocateRepoGitDirs/main_checkout and the
new config.worktree case; treating origin like any other remote fails
the new origin added and removed cases. In a scratch main-checkout clone
with extensions.worktreeConfig set, a test that wrote
`git config --worktree user.email` into the checkout now fails the
suite (exit 1, an ERROR naming .git/config.worktree). bazel test
--config=ci passes for testutil, fmt_test and the bd_test guard tests.

Not in this commit: the same scrub in beads_test_env_enter
(scripts/ci/lib/test-env.sh) and tools/bazel/test_env.sh, which would
cover the packages outside cmd/bd that still write to the clone under a
hook-leaked GIT_DIR. That predates this PR and is left to a follow-up.

Co-authored-by: cat <cino@ghosttrack.com>
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: cat <cino@ghosttrack.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
2026-10-17 12:36:48 +00:00

436 lines
14 KiB
Go

package main
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/storage"
)
func TestApplyHooksNoDrift(t *testing.T) {
result := applyHooks(false, false)
if result.Status != applyStatusOK {
t.Errorf("expected status %q, got %q", applyStatusOK, result.Status)
}
if result.Action != "none" {
t.Errorf("expected action %q, got %q", "none", result.Action)
}
}
func TestApplyHooksDryRun(t *testing.T) {
result := applyHooks(true, true)
if result.Status != applyStatusDryRun {
t.Errorf("expected status %q, got %q", applyStatusDryRun, result.Status)
}
if result.Action != "reinstall" {
t.Errorf("expected action %q, got %q", "reinstall", result.Action)
}
}
func TestApplyRemoteNoDrift(t *testing.T) {
result := applyRemote(false, false)
if result.Status != applyStatusOK {
t.Errorf("expected status %q, got %q", applyStatusOK, result.Status)
}
if result.Action != "none" {
t.Errorf("expected action %q, got %q", "none", result.Action)
}
}
func TestApplyRemoteDryRun(t *testing.T) {
// When drifted but no beads dir, should skip
result := applyRemote(true, true)
if result.Status != applyStatusSkipped && result.Status != applyStatusDryRun {
t.Errorf("expected status %q or %q, got %q", applyStatusSkipped, applyStatusDryRun, result.Status)
}
}
func TestRemoteApplyStoreConfigUsesReadOnlyForDryRun(t *testing.T) {
dryRunConfig := remoteApplyStoreConfig(true)
if !dryRunConfig.ReadOnly {
t.Fatal("dry-run remote apply must open the Dolt store read-only")
}
if !dryRunConfig.DisableAutoStart {
t.Fatal("remote apply diagnostics must not auto-start Dolt")
}
applyConfig := remoteApplyStoreConfig(false)
if applyConfig.ReadOnly {
t.Fatal("non-dry-run remote apply must remain writable")
}
if !applyConfig.DisableAutoStart {
t.Fatal("remote apply writes must not auto-start Dolt")
}
}
func TestRemoteURLMatchesConfigNormalizesEquivalentGitURLs(t *testing.T) {
tests := []struct {
name string
current string
configured string
want bool
}{
{
name: "https normalized to git https",
current: "git+https://github.com/gastownhall/beads.git",
configured: "https://github.com/gastownhall/beads.git",
want: true,
},
{
name: "ssh normalized to git ssh",
current: "git+ssh://github.com/gastownhall/beads.git",
configured: "ssh://github.com/gastownhall/beads.git",
want: true,
},
{
name: "different repos still differ",
current: "git+https://github.com/gastownhall/beads.git",
configured: "https://github.com/gastownhall/other.git",
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := remoteURLMatchesConfig(tt.current, tt.configured); got != tt.want {
t.Fatalf("remoteURLMatchesConfig(%q, %q) = %v, want %v", tt.current, tt.configured, got, tt.want)
}
})
}
}
func TestApplyServerNoDrift(t *testing.T) {
result := applyServer(false, false)
if result.Status != applyStatusOK {
t.Errorf("expected status %q, got %q", applyStatusOK, result.Status)
}
if result.Action != "none" {
t.Errorf("expected action %q, got %q", "none", result.Action)
}
}
func TestApplyServerDriftedButNotConfigured(t *testing.T) {
// Server running but config doesn't say shared-server=true
// Should skip (not stop the server)
t.Setenv("BEADS_TEST_IGNORE_REPO_CONFIG", "1")
result := applyServer(true, false)
// Without a .beads dir or with shared-server not set, should skip
if result.Status != applyStatusSkipped {
t.Errorf("expected status %q, got %q", applyStatusSkipped, result.Status)
}
}
func TestApplyServerDryRun(t *testing.T) {
t.Setenv("BEADS_TEST_IGNORE_REPO_CONFIG", "1")
result := applyServer(true, true)
// Without beads dir, should skip even in dry-run
if result.Status != applyStatusSkipped {
t.Errorf("expected status %q, got %q", applyStatusSkipped, result.Status)
}
}
func TestApplyServerSkipsWhenAutoStartDisabled(t *testing.T) {
tests := []struct {
name string
autoStartEnv string
autoStartYML string
}{
{
name: "environment disables auto-start",
autoStartEnv: "0",
autoStartYML: "true",
},
{
name: "workspace config disables auto-start",
autoStartEnv: "",
autoStartYML: "false",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
root := t.TempDir()
beadsDir := filepath.Join(root, ".beads")
if err := os.MkdirAll(beadsDir, 0o755); err != nil {
t.Fatalf("create .beads: %v", err)
}
configYAML := "dolt:\n shared-server: true\n auto-start: " + tt.autoStartYML + "\n"
if err := os.WriteFile(filepath.Join(beadsDir, "config.yaml"), []byte(configYAML), 0o600); err != nil {
t.Fatalf("write config.yaml: %v", err)
}
sharedDir := filepath.Join(root, "shared-server")
t.Setenv("BEADS_DIR", beadsDir)
t.Setenv("BEADS_SHARED_SERVER_DIR", sharedDir)
t.Setenv("BEADS_DOLT_AUTO_START", tt.autoStartEnv)
initConfigForTest(t)
for _, dryRun := range []bool{false, true} {
name := "apply"
if dryRun {
name = "dry-run"
}
t.Run(name, func(t *testing.T) {
result := applyServer(true, dryRun)
if result.Status != applyStatusSkipped {
t.Fatalf("status = %q, want %q: %+v", result.Status, applyStatusSkipped, result)
}
if result.Action != "start" {
t.Fatalf("action = %q, want %q", result.Action, "start")
}
if !strings.Contains(result.Message, "auto-start is disabled") || !strings.Contains(result.Message, "externally managed") {
t.Fatalf("message does not explain skip policy: %q", result.Message)
}
if _, err := os.Stat(sharedDir); !os.IsNotExist(err) {
t.Fatalf("applyServer created shared server state despite disabled auto-start: %v", err)
}
})
}
})
}
}
// isolatedApplyFixture builds a throwaway git repo with a .beads dir for the
// runApply tests. runApply(false) is a live apply: it inspects AND MUTATES the
// repository that owns the process cwd (hook reinstalls, hooksPath mkdirs).
// Run bare from the package dir, that repository is this checkout — the r880
// host .git clobber (wy-qlvlmf) — so these tests must always chdir into a
// fixture they own first.
func isolatedApplyFixture(t *testing.T) string {
t.Helper()
dir := t.TempDir()
initGitRepoAt(t, dir)
if err := os.MkdirAll(filepath.Join(dir, ".beads"), 0o755); err != nil {
t.Fatalf("create fixture .beads: %v", err)
}
return dir
}
func TestRunApplyAllOK(t *testing.T) {
t.Setenv("BEADS_TEST_IGNORE_REPO_CONFIG", "1")
runInDir(t, isolatedApplyFixture(t), func() {
// In a test environment with no drift, all results should be ok or skipped
results := runApply(false)
if len(results) != 3 {
t.Errorf("expected 3 results, got %d", len(results))
}
for _, r := range results {
if r.Status == applyStatusError {
t.Errorf("unexpected error for check %q: %s", r.Check, r.Error)
}
}
})
}
func TestRunApplyDryRun(t *testing.T) {
t.Setenv("BEADS_TEST_IGNORE_REPO_CONFIG", "1")
runInDir(t, isolatedApplyFixture(t), func() {
results := runApply(true)
if len(results) != 3 {
t.Errorf("expected 3 results, got %d", len(results))
}
// In dry-run, no actions should be "applied"
for _, r := range results {
if r.Status == applyStatusApplied {
t.Errorf("dry-run should not apply actions, but check %q was applied", r.Check)
}
}
})
}
func TestDriftDomainsGroupsDottedChecks(t *testing.T) {
items := []DriftItem{
{Check: "hooks.missing", Status: driftStatusDrift},
{Check: "remote", Status: driftStatusDrift},
{Check: "server", Status: driftStatusOK},
}
got := driftDomains(items)
if !got["hooks"] {
t.Fatal("expected hooks.missing drift to mark hooks domain drifted")
}
if !got["remote"] {
t.Fatal("expected remote drift to mark remote domain drifted")
}
if got["server"] {
t.Fatal("did not expect ok server check to mark server domain drifted")
}
}
func TestShouldRecheckRemoteAfterServerStart(t *testing.T) {
appliedServer := ApplyResult{Check: "server", Status: applyStatusApplied}
if !shouldRecheckRemoteAfterServerStart(true, appliedServer) {
t.Fatal("expected remote recheck after skipped remote drift and applied server start")
}
dryRunServer := ApplyResult{Check: "server", Status: applyStatusDryRun}
if shouldRecheckRemoteAfterServerStart(true, dryRunServer) {
t.Fatal("did not expect remote recheck when server was not actually started")
}
if shouldRecheckRemoteAfterServerStart(false, appliedServer) {
t.Fatal("did not expect remote recheck when initial remote drift was not skipped")
}
}
func TestRemoteApplyResultPreservesSkippedRemoteWithoutRecheck(t *testing.T) {
skippedRemote := DriftItem{
Check: "remote",
Status: driftStatusSkipped,
Message: "Cannot open Dolt store: server unavailable",
}
serverOK := ApplyResult{Check: "server", Status: applyStatusOK}
result := remoteApplyResult([]DriftItem{skippedRemote}, serverOK, false, func() []DriftItem {
t.Fatal("remote should not be rechecked unless the server was started")
return nil
})
if result.Check != "remote" {
t.Fatalf("expected remote result, got %q", result.Check)
}
if result.Status != applyStatusSkipped {
t.Fatalf("expected skipped remote result, got %q", result.Status)
}
if result.Message != skippedRemote.Message {
t.Fatalf("message = %q, want %q", result.Message, skippedRemote.Message)
}
}
func TestRemoteApplyResultPreservesSkippedRemoteAfterRecheck(t *testing.T) {
initialSkipped := DriftItem{
Check: "remote",
Status: driftStatusSkipped,
Message: "Cannot open Dolt store: server unavailable",
}
recheckedSkipped := DriftItem{
Check: "remote",
Status: driftStatusSkipped,
Message: "Cannot list remotes: access denied",
}
serverApplied := ApplyResult{Check: "server", Status: applyStatusApplied}
rechecked := false
result := remoteApplyResult([]DriftItem{initialSkipped}, serverApplied, false, func() []DriftItem {
rechecked = true
return []DriftItem{recheckedSkipped}
})
if !rechecked {
t.Fatal("expected remote recheck after server start")
}
if result.Status != applyStatusSkipped {
t.Fatalf("expected skipped remote result, got %q", result.Status)
}
if result.Message != recheckedSkipped.Message {
t.Fatalf("message = %q, want %q", result.Message, recheckedSkipped.Message)
}
}
func TestRemoteApplyResultUsesSuccessfulRemoteRecheck(t *testing.T) {
initialSkipped := DriftItem{
Check: "remote",
Status: driftStatusSkipped,
Message: "Cannot open Dolt store: server unavailable",
}
serverApplied := ApplyResult{Check: "server", Status: applyStatusApplied}
rechecked := false
result := remoteApplyResult([]DriftItem{initialSkipped}, serverApplied, false, func() []DriftItem {
rechecked = true
return []DriftItem{{
Check: "remote",
Status: driftStatusOK,
Message: "Dolt origin remote matches federation.remote",
}}
})
if !rechecked {
t.Fatal("expected remote recheck after server start")
}
if result.Status != applyStatusOK {
t.Fatalf("expected ok remote result after successful recheck, got %q", result.Status)
}
}
func TestPrintApplyResults(t *testing.T) {
// Smoke test — just ensure no panic
results := []ApplyResult{
{Check: "hooks", Action: "none", Status: applyStatusOK, Message: "up to date"},
{Check: "remote", Action: "add_remote", Status: applyStatusApplied, Message: "added"},
{Check: "server", Action: "start", Status: applyStatusError, Message: "failed", Error: "no dolt"},
{Check: "hooks", Action: "reinstall", Status: applyStatusDryRun, Message: "would reinstall"},
{Check: "remote", Action: "none", Status: applyStatusSkipped, Message: "skipped"},
}
// Redirect stdout to avoid test noise
old := os.Stdout
os.Stdout, _ = os.Open(os.DevNull)
defer func() { os.Stdout = old }()
printApplyResults(results)
printApplyResults(nil)
}
// fakeOriginRemoteEvidence simulates the two evidence sources
// currentOriginRemoteURL consults: the SQL-visible dolt_remotes listing and
// the on-disk .dolt/repo_state.json enumeration.
type fakeOriginRemoteEvidence struct {
listed []storage.RemoteInfo
listErr error
persisted []storage.RemoteInfo
}
func (f *fakeOriginRemoteEvidence) ListRemotes(ctx context.Context) ([]storage.RemoteInfo, error) {
return f.listed, f.listErr
}
func (f *fakeOriginRemoteEvidence) PersistedRemoteInfos() []storage.RemoteInfo {
return f.persisted
}
// TestCurrentOriginRemoteURL pins the wy-6k7f7 evidence rule for
// `bd config apply`: an empty dolt_remotes listing alone is not proof there
// is no origin — a cold-started sql-server hides a persisted remote
// (GH#2118), and blind-adding over it was the defect. The SQL listing wins
// when populated; the persisted enumeration is the fallback; a failed
// listing is an error, never evidence.
func TestCurrentOriginRemoteURL(t *testing.T) {
ctx := context.Background()
t.Run("listing_wins_when_populated", func(t *testing.T) {
url, err := currentOriginRemoteURL(ctx, &fakeOriginRemoteEvidence{
listed: []storage.RemoteInfo{{Name: "origin", URL: "https://sql.example/repo"}},
persisted: []storage.RemoteInfo{{Name: "origin", URL: "https://disk.example/repo"}},
})
if err != nil || url != "https://sql.example/repo" {
t.Fatalf("got (%q, %v), want the SQL-visible URL", url, err)
}
})
t.Run("cold_start_recovers_persisted_origin", func(t *testing.T) {
url, err := currentOriginRemoteURL(ctx, &fakeOriginRemoteEvidence{
persisted: []storage.RemoteInfo{{Name: "origin", URL: "https://disk.example/repo"}},
})
if err != nil || url != "https://disk.example/repo" {
t.Fatalf("got (%q, %v), want the persisted on-disk URL", url, err)
}
})
t.Run("no_evidence_means_no_origin", func(t *testing.T) {
url, err := currentOriginRemoteURL(ctx, &fakeOriginRemoteEvidence{
persisted: []storage.RemoteInfo{{Name: "peer-mini", URL: "https://disk.example/other"}},
})
if err != nil || url != "" {
t.Fatalf("got (%q, %v), want empty with no error", url, err)
}
})
t.Run("list_failure_is_an_error_not_evidence", func(t *testing.T) {
_, err := currentOriginRemoteURL(ctx, &fakeOriginRemoteEvidence{
listErr: errors.New("connection refused"),
persisted: []storage.RemoteInfo{{Name: "origin", URL: "https://disk.example/repo"}},
})
if err == nil {
t.Fatal("a failed listing must surface as an error, not fall through to disk")
}
})
}