beads/cmd/bd/init_test.go
Eddie the Engineer c79bb32bca fix(backends): maintainer fixup — CI repair + adoption review fixes
Maintainer fixup for the choose-your-own-storage-backend PR, amended across the
pre-review CI-repair and the review-loop apply-fixes iterations so contributor
commits stay intact under one maintainer commit.

CI repair (pre-review):
- default.nix: bump vendorHash for the added Postgres/MySQL driver deps.
- conformance.yml: provision the Postgres service DB with a C-locale cluster so
  text ORDER BY sorts by code point, matching Dolt's utf8mb4_0900_bin oracle.

Review fixes — blockers:
- uow/doltserver_tx: on a non-serialization DOLT_COMMIT failure, ROLLBACK on the
  pinned session before releasing it, and poison (pool-discard via driver.ErrBadConn)
  the connection when the rollback also fails, so a later borrower can't inherit an
  open transaction and implicitly commit orphaned writes. Satisfies the existing
  doltserver_tx_test rollback/poison cases.
- sqlitedialect: translate GREATEST/LEAST to SQLite scalar max/min so the
  ReconcileChildCounters upsert (GREATEST(last_child, ?)) no longer aborts creation
  or import of hierarchical dotted issue IDs (e.g. x-1.2) on the SQLite backend.

Review fixes — majors:
- conformance: add a portable dotted hierarchical child-ID scenario (x-1, x-1.1,
  x-1.2, x-1.2.1) exercising the ReconcileChildCounters GREATEST path on every
  backend — the coverage hole that let the SQLite blocker ship green. Verified
  against the embedded-Dolt oracle and the real SQLite driver.
- postgres: warn at provision/open when the database collation is not code-point
  ordered (C/POSIX/C.*), since text ORDER BY otherwise diverges from Dolt silently.
- sqlite: pin the pool to one connection and add busy_timeout + WAL to the DSN so
  overlapping operations wait instead of surfacing a raw "database is locked"
  (matches the Dolt backend's single-connection posture). Adds a concurrency guard.
- cmd/bd: gate explicit `bd dolt commit` / `bd vc commit` with a typed
  storage.ErrUnsupported on non-Dolt backends instead of the no-op Commit printing
  "Committed."; internal opportunistic auto-commit is untouched.

Review fixes — attempt 2 (stale init backend-flag test contract):
- cmd/bd/init_test, init_embedded_test: the init backend-flag tests still asserted
  the pre-#3151 one-backend contract (--backend=sqlite must fail "SQLite backend
  has been removed"; --backend=postgres is an "unknown backend"), so
  `go test ./cmd/bd -run '^TestInitBackendFlag$'` failed in a clean environment now
  that sqlite/postgres/mysql are supported pluggable backends. Rewrite
  TestInitBackendFlag and the cgo TestEmbeddedInit sibling (rejected_backends →
  sql_backend_flags) for the new contract: --backend=sqlite initializes and
  persists backend=sqlite; --backend=postgres is recognized and fails only on
  missing connection config (not "unknown backend"); a genuinely unknown backend
  is still rejected. Pin BEADS_DIR and scrub BEADS_*/BD_* so the subtests are
  hermetic against an ambient .beads or Dolt server.

Cleanups (non-gating):
- cmd/bd/init: extract checkExistingSQLBackend so the added SQL-backend branches
  don't inflate checkExistingBeadsDataAt's complexity, and load config once.
- configfile: correct the stale "Deprecated: always dolt" Backend field comment.

Review fixes -- attempt 3 (SQLite datetime parity blocker + conformance/rewrite
hardening of the storage-parity gate):
- sqlite/dsn: add _time_format=datetime. Without it modernc binds time.Time via
  t.String() ("2026-07-09 12:34:56.123 +0000 UTC"), a shape SQLite's date functions
  cannot parse, so the counts mega-query's DATE_FORMAT(created_at,...) (strftime on
  SQLite) returns NULL and deps_json exposes a zero created_at while Dolt emits the
  real timestamp. datetime stores whole-second "2026-07-09 12:34:56", matching
  Dolt/MySQL datetime(0). Verified end-to-end against the real modernc driver.
- conformance: add ReadyWorkDepCreatedAtParity -- imports a dependency with a known
  created_at (the bd import / CreateIssuesWithFullOptions bound-time.Time path) and
  asserts the counts-rendered deps_json created_at equals it, closing the blind spot
  that let the SQLite blocker ship green (the counts tests only checked DependencyCount).
  Proven to fail on the pre-fix DSN and pass on both the fixed SQLite backend and the
  embedded-Dolt oracle.
- conformance: add ClaimReadyIssueConcurrentExclusivity -- races 24 workers over 8
  ready issues and asserts each is claimed exactly once, exercising the SQL backends'
  multi-writer claim property that was previously only asserted, never raced. Gated to
  the multi-connection dialects (postgres/mysql) via DialectName; SQLite (single-conn
  pool) and embedded-Dolt skip.
- conformance.sh: run the embedded-Dolt reference conformance with
  BEADS_TEST_EMBEDDED_DOLT=1 and fail loudly if it skips. It self-skips without the env
  var, so the parity gate was reporting success while never running the reference oracle.
- mysqldialect: drive the is_blocked-recompute error-1093 rewrite test from the real
  issueops templates (new issueops.SelfReferentialRecomputeTemplates) instead of a
  hand-copied fixture, so template drift fails a non-gated test rather than only the
  env-gated MySQL conformance suite. All four mark/unmark x issue/wisp templates
  verified rewritten into the materialized derived-table form.

Note: the review re-flagged TestInitBackendFlag as failing, but it passes in a clean run
(plain and gms_pure_go, matching the scorecard's own rerun); the only cmd/bd failure in
this sandbox is an unrelated pre-existing embedded-Dolt/CGO test not in this PR's diff.

Review fixes -- attempt 4 (conformance-gate self-brick + all-wisps inline-dependency
drop blockers; Postgres error-log password-leak major):
- conformance.sh: anchor the embedded-Dolt reference skip/pass guards to top-level
  result lines (^--- SKIP/PASS: TestConformance). The attempt-3 loud-fail guard used
  an unanchored grep, so the indented, legitimate subtest skip of
  ClaimReadyIssueConcurrentExclusivity (embedded-Dolt is single-writer) matched it and
  false-failed the entire storage-parity gate on every run even when the top-level
  suite passed. Whole-suite-skip protection is preserved.
- sqlkit/portable + embeddeddolt/create_issue: the all-wisps arm looped the
  single-issue issueops.CreateIssueInTx, which runs no batch dependency-persist pass,
  so an all-wisps batch carrying inline dependencies (e.g. importing no-history beads
  with inter-bead edges -- export DOES include no-history beads, GH#2619) silently
  dropped every edge (not even reported via OnSkippedDependency) and, one transaction
  per issue, forfeited batch atomicity. Both now mark ephemeral, then run the whole
  batch in ONE transaction through issueops.CreateIssuesInTx, matching the server-mode
  DoltStore all-wisps arm. The embedded-Dolt reference oracle had the same latent drop,
  so the oracle and the new SQL backends were corrected together to keep conformance
  parity (the finding compared sqlkit against the server-mode DoltStore, which already
  persisted these edges).
- conformance: add CreateAllWispsInlineDependencies -- an all-wisp batch with one valid
  inter-wisp edge and one unresolvable edge; asserts the valid edge persists and the
  unresolvable one is reported via OnSkippedDependency. Fails on the pre-fix per-issue
  loop, passes on the batch path; verified on SQLite and the embedded-Dolt oracle, with
  a full embedded-Dolt conformance re-run clean.
- pgdialect: scrub query-param/sslpassword secrets from pgx ParseConfig errors in Open
  and OpenRaw (new ScrubDSNError). pgx's ParseConfigError redacts only URL userinfo, so
  a postgres://u@h/db?password=SECRET DSN (the shape bd init connects with) leaked the
  cleartext secret through the wrapped parse/TLS-config error into logs. Connect-time
  errors were verified not to carry the password. Adds redact_error_test coverage for
  the query-param, sslpassword, userinfo, and libpq-keyword shapes plus the real
  Open/OpenRaw parse-failure path.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 17:44:37 +00:00

2575 lines
79 KiB
Go

//go:build cgo
package main
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/git"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/testutil"
)
// skipIfNoDolt skips the test when no Dolt server is available.
// Checks both binary availability and test server status.
func skipIfNoDolt(t *testing.T) {
t.Helper()
testutil.RequireDoltBinary(t)
if testDoltServerPort == 0 {
t.Skip("skipping: Dolt test server not running")
}
}
func TestInitCommand(t *testing.T) {
skipIfNoDolt(t)
tests := []struct {
name string
prefix string
quiet bool
wantOutputText string
wantNoOutput bool
}{
{
name: "init with default prefix",
prefix: "",
quiet: false,
wantOutputText: "bd initialized successfully",
},
{
name: "init with custom prefix",
prefix: "myproject",
quiet: false,
wantOutputText: "myproject-<hash>",
},
{
name: "init with quiet flag",
prefix: "test",
quiet: true,
wantNoOutput: true,
},
{
name: "init with prefix ending in hyphen",
prefix: "test-",
quiet: false,
wantOutputText: "test-<hash>",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Reset global state
origDBPath := dbPath
origStore := store
defer func() {
if store != nil && store != origStore {
store.Close()
}
store = origStore
dbPath = origDBPath
}()
dbPath = ""
store = nil
// Reset Cobra command state
rootCmd.SetArgs([]string{})
initCmd.Flags().Set("prefix", "")
initCmd.Flags().Set("quiet", "false")
tmpDir := t.TempDir()
t.Chdir(tmpDir)
// Capture output
var buf bytes.Buffer
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
defer func() {
os.Stdout = oldStdout
}()
// Build command arguments
args := []string{"init"}
if tt.prefix != "" {
args = append(args, "--prefix", tt.prefix)
}
if tt.quiet {
args = append(args, "--quiet")
}
rootCmd.SetArgs(args)
// Run command
var err error
err = rootCmd.Execute()
// Restore stdout and read output
w.Close()
buf.ReadFrom(r)
os.Stdout = oldStdout
output := buf.String()
if err != nil {
t.Fatalf("init command failed: %v", err)
}
// Check output
if tt.wantNoOutput {
if output != "" {
t.Errorf("Expected no output with --quiet, got: %s", output)
}
} else if tt.wantOutputText != "" {
if !strings.Contains(output, tt.wantOutputText) {
t.Errorf("Expected output to contain %q, got: %s", tt.wantOutputText, output)
}
}
// Verify .beads directory was created
beadsDir := filepath.Join(tmpDir, ".beads")
if _, err := os.Stat(beadsDir); os.IsNotExist(err) {
t.Error(".beads directory was not created")
}
// Verify .gitignore was created with proper content
gitignorePath := filepath.Join(beadsDir, ".gitignore")
gitignoreContent, err := os.ReadFile(gitignorePath)
if err != nil {
t.Errorf(".gitignore file was not created: %v", err)
} else {
// Check for essential patterns
gitignoreStr := string(gitignoreContent)
expectedPatterns := []string{
"*.db",
"*.db?*",
"*.db-journal",
"*.db-wal",
"*.db-shm",
"bd.sock",
"dolt/",
}
for _, pattern := range expectedPatterns {
if !strings.Contains(gitignoreStr, pattern) {
t.Errorf(".gitignore missing expected pattern: %s", pattern)
}
}
}
// Verify Dolt database directory was created
doltPath := filepath.Join(beadsDir, "dolt")
if info, err := os.Stat(doltPath); os.IsNotExist(err) {
t.Errorf("Dolt database directory was not created at %s", doltPath)
} else if !info.IsDir() {
t.Errorf("Expected %s to be a directory", doltPath)
}
// Database content verification (prefix, metadata) is skipped here because
// embedded Dolt's Close() can timeout, leaving file locks held and preventing
// re-opening the DB in the same process. The init command's own internal logic
// verifies these writes succeed; prefix/metadata correctness is also covered
// by dedicated Dolt storage tests.
})
}
}
// Note: Error case testing is omitted because the init command calls os.Exit()
// on errors, which makes it difficult to test in a unit test context.
func TestInitAlreadyInitialized(t *testing.T) {
skipIfNoDolt(t)
// Reset global state
origDBPath := dbPath
defer func() { dbPath = origDBPath }()
dbPath = ""
tmpDir := t.TempDir()
t.Chdir(tmpDir)
// Initialize once
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--quiet"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("First init failed: %v", err)
}
// Initialize again with same prefix and --force flag (bd-emg: safety guard)
// Without --force, init should refuse when database already exists
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--quiet", "--force"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("Second init with --force failed: %v", err)
}
// Verify database still works
dbPath := filepath.Join(tmpDir, ".beads", "dolt")
store, err := openExistingTestDB(t, dbPath)
if err != nil {
t.Fatalf("Failed to open database: %v", err)
}
defer store.Close()
ctx := context.Background()
prefix, err := store.GetConfig(ctx, "issue_prefix")
if err != nil {
t.Fatalf("Failed to get prefix after re-init: %v", err)
}
if prefix != "test" {
t.Errorf("Expected prefix 'test', got %q", prefix)
}
}
// GH#3490: `bd init --init-if-missing` makes init idempotent for scaffold
// scripts. When the workspace is already initialized, init must skip and
// return without error (exit 0), emitting a benign "Skipping init" message,
// instead of aborting via os.Exit(1). The default (no-flag) abort path calls
// os.Exit(1) and therefore cannot be exercised in-process (see the note above
// TestInitAlreadyInitialized); this test covers the new success path.
func TestInitIfMissing(t *testing.T) {
skipIfNoDolt(t)
// Reset global state
origDBPath := dbPath
// Cobra flag values persist across Execute() calls on the shared command
// tree (a sibling test may have left --force set, and our own first init
// sets --quiet). Normalize the flags this test depends on before each run,
// and restore defaults afterward so we neither inherit nor leak state.
resetInitFlags := func() {
_ = initCmd.Flags().Set("force", "false")
_ = initCmd.Flags().Set("reinit-local", "false")
_ = initCmd.Flags().Set("init-if-missing", "false")
_ = initCmd.Flags().Set("quiet", "false")
_ = initCmd.Flags().Set("prefix", "")
}
defer func() {
dbPath = origDBPath
resetInitFlags()
}()
dbPath = ""
resetInitFlags()
tmpDir := t.TempDir()
t.Chdir(tmpDir)
// First init creates the workspace.
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--quiet"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("First init failed: %v", err)
}
// Re-running with --init-if-missing must be a benign no-op that exits 0:
// Execute() returns nil rather than the process aborting via os.Exit(1).
// Clear --quiet (set by the first run) so the skip message is emitted, and
// ensure no stale --force bypasses the already-initialized guard.
resetInitFlags()
oldStderr := os.Stderr
r, w, _ := os.Pipe()
os.Stderr = w
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--init-if-missing"})
execErr := rootCmd.Execute()
w.Close()
os.Stderr = oldStderr
var buf bytes.Buffer
buf.ReadFrom(r)
stderr := buf.String()
if execErr != nil {
t.Fatalf("init --init-if-missing on an initialized workspace should succeed, got: %v", execErr)
}
if !strings.Contains(stderr, "Skipping init: workspace already initialized") {
t.Errorf("expected a 'Skipping init: workspace already initialized' message on stderr, got:\n%s", stderr)
}
// The skip is a no-op: the existing workspace must remain in place (init
// returned before touching any data). We assert on the .beads directory
// rather than a specific backend layout so the test holds for both the
// embedded and server test modes.
beadsDir := filepath.Join(tmpDir, ".beads")
if info, err := os.Stat(beadsDir); err != nil || !info.IsDir() {
t.Fatalf("expected existing .beads workspace to remain at %s, stat err: %v", beadsDir, err)
}
}
// TestInitIfMissingPrefixMismatch covers the guard that keeps --init-if-missing
// from masking a genuine prefix mismatch (review follow-up on #4332/#3490): a
// re-init that explicitly requests a different prefix than the existing
// workspace must abort, while a matching prefix (after normalization) or an
// undeterminable existing name must fall through to the benign skip.
func TestInitIfMissingPrefixMismatch(t *testing.T) {
tests := []struct {
name string
existing string
requested string
want bool
}{
{name: "exact match", existing: "foo", requested: "foo", want: false},
{name: "case-insensitive match", existing: "Foo", requested: "foo", want: false},
{name: "hyphen normalizes to underscore", existing: "my_proj", requested: "my-proj", want: false},
{name: "trailing hyphen trimmed", existing: "foo", requested: "foo-", want: false},
{name: "leading-digit gets bd_ prefix", existing: "bd_001", requested: "001", want: false},
{name: "genuine mismatch aborts", existing: "foo", requested: "bar", want: true},
{name: "unknown existing falls through", existing: "", requested: "bar", want: false},
{name: "empty requested falls through", existing: "foo", requested: "", want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := initIfMissingPrefixMismatch(tt.existing, tt.requested); got != tt.want {
t.Errorf("initIfMissingPrefixMismatch(%q, %q) = %v, want %v",
tt.existing, tt.requested, got, tt.want)
}
})
}
}
// TestInitIfMissingMatchingPrefixSkips verifies the mismatch guard does not
// regress the happy path: re-running with the SAME explicit --prefix as the
// existing workspace still skips cleanly (exit 0) rather than aborting.
func TestInitIfMissingMatchingPrefixSkips(t *testing.T) {
skipIfNoDolt(t)
origDBPath := dbPath
resetInitFlags := func() {
_ = initCmd.Flags().Set("force", "false")
_ = initCmd.Flags().Set("reinit-local", "false")
_ = initCmd.Flags().Set("init-if-missing", "false")
_ = initCmd.Flags().Set("quiet", "false")
_ = initCmd.Flags().Set("prefix", "")
}
defer func() {
dbPath = origDBPath
resetInitFlags()
}()
dbPath = ""
resetInitFlags()
tmpDir := t.TempDir()
t.Chdir(tmpDir)
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--quiet"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("First init failed: %v", err)
}
resetInitFlags()
oldStderr := os.Stderr
r, w, _ := os.Pipe()
os.Stderr = w
// Same prefix as the existing workspace: must skip, not abort.
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--init-if-missing"})
execErr := rootCmd.Execute()
w.Close()
os.Stderr = oldStderr
var buf bytes.Buffer
buf.ReadFrom(r)
stderr := buf.String()
if execErr != nil {
t.Fatalf("init --init-if-missing with matching prefix should succeed, got: %v", execErr)
}
if !strings.Contains(stderr, "Skipping init: workspace already initialized") {
t.Errorf("expected benign skip message, got:\n%s", stderr)
}
}
func TestInitIfMissingDatabaseMismatch(t *testing.T) {
tests := []struct {
name string
existing string
requested string
want bool
}{
{name: "exact match", existing: "foo", requested: "foo", want: false},
{name: "case-insensitive match", existing: "Foo", requested: "foo", want: false},
{name: "genuine mismatch aborts", existing: "foo", requested: "bar", want: true},
{name: "unknown existing falls through", existing: "", requested: "bar", want: false},
{name: "empty requested falls through", existing: "foo", requested: "", want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := initIfMissingDatabaseMismatch(tt.existing, tt.requested); got != tt.want {
t.Errorf("initIfMissingDatabaseMismatch(%q, %q) = %v, want %v",
tt.existing, tt.requested, got, tt.want)
}
})
}
}
// TestCheckExistingBeadsDataOperationalErrorNotMasked verifies the core of the
// --init-if-missing idempotency fix: only the benign "already initialized"
// outcome matches errWorkspaceAlreadyInitialized (and may be skipped), while an
// operational failure must NOT match it — otherwise --init-if-missing would mask
// a real error (e.g. an unreadable .beads/embeddeddolt) as a successful skip.
func TestCheckExistingBeadsDataOperationalErrorNotMasked(t *testing.T) {
saveEmbeddedConfig := func(t *testing.T, beadsDir string) {
t.Helper()
cfg := &configfile.Config{
Database: "dolt",
Backend: configfile.BackendDolt,
DoltMode: configfile.DoltModeEmbedded,
}
if err := cfg.Save(beadsDir); err != nil {
t.Fatalf("save config: %v", err)
}
}
t.Run("existing database matches sentinel", func(t *testing.T) {
beadsDir := t.TempDir()
saveEmbeddedConfig(t, beadsDir)
// A real embedded database lives at embeddeddolt/<db>/.dolt.
if err := os.MkdirAll(filepath.Join(beadsDir, "embeddeddolt", "mydb", ".dolt"), 0o750); err != nil {
t.Fatal(err)
}
err := checkExistingBeadsDataAt(beadsDir, "mydb")
if err == nil {
t.Fatal("expected already-initialized error, got nil")
}
if !errors.Is(err, errWorkspaceAlreadyInitialized) {
t.Errorf("existing-database error must match errWorkspaceAlreadyInitialized, got: %v", err)
}
})
t.Run("operational error not masked", func(t *testing.T) {
beadsDir := t.TempDir()
saveEmbeddedConfig(t, beadsDir)
// Make embeddeddolt a regular file so os.ReadDir fails with a
// non-IsNotExist (operational) error rather than "already initialized".
if err := os.WriteFile(filepath.Join(beadsDir, "embeddeddolt"), []byte("not a dir"), 0o600); err != nil {
t.Fatal(err)
}
err := checkExistingBeadsDataAt(beadsDir, "mydb")
if err == nil {
t.Fatal("expected operational error, got nil")
}
if errors.Is(err, errWorkspaceAlreadyInitialized) {
t.Errorf("operational error must NOT match errWorkspaceAlreadyInitialized (would be masked by --init-if-missing): %v", err)
}
})
}
func TestInitWithCustomDBPath(t *testing.T) {
t.Skip("BEADS_DB env var does not control Dolt store location; Dolt always uses .beads/dolt/")
// Save original state
origDBPath := dbPath
defer func() { dbPath = origDBPath }()
tmpDir := t.TempDir()
customDBDir := filepath.Join(tmpDir, "custom", "location")
// Change to a different directory to ensure --db flag is actually used
workDir := filepath.Join(tmpDir, "workdir")
if err := os.MkdirAll(workDir, 0750); err != nil {
t.Fatalf("Failed to create work directory: %v", err)
}
t.Chdir(workDir)
customDBPath := filepath.Join(customDBDir, "test.db")
// Test with BEADS_DB environment variable (replacing --db flag test)
t.Run("init with BEADS_DB pointing to custom path", func(t *testing.T) {
dbPath = "" // Reset global
os.Setenv("BEADS_DB", customDBPath)
defer os.Unsetenv("BEADS_DB")
rootCmd.SetArgs([]string{"init", "--prefix", "custom", "--quiet"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("Init with BEADS_DB failed: %v", err)
}
// Verify database was created at custom location
if _, err := os.Stat(customDBPath); os.IsNotExist(err) {
t.Errorf("Database was not created at custom path %s", customDBPath)
}
// Verify database works
store, err := openExistingTestDB(t, customDBPath)
if err != nil {
t.Fatalf("Failed to open database: %v", err)
}
defer store.Close()
ctx := context.Background()
prefix, err := store.GetConfig(ctx, "issue_prefix")
if err != nil {
t.Fatalf("Failed to get prefix: %v", err)
}
if prefix != "custom" {
t.Errorf("Expected prefix 'custom', got %q", prefix)
}
// Verify .beads/ directory was NOT created in work directory
if _, err := os.Stat(filepath.Join(workDir, ".beads")); err == nil {
t.Error(".beads/ directory should not be created when using BEADS_DB env var")
}
})
// Test with BEADS_DB env var
t.Run("init with BEADS_DB env var", func(t *testing.T) {
dbPath = "" // Reset global
envDBPath := filepath.Join(tmpDir, "env", "location", "env.db")
os.Setenv("BEADS_DB", envDBPath)
defer os.Unsetenv("BEADS_DB")
rootCmd.SetArgs([]string{"init", "--prefix", "envtest", "--quiet"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("Init with BEADS_DB failed: %v", err)
}
// Verify database was created at env location
if _, err := os.Stat(envDBPath); os.IsNotExist(err) {
t.Errorf("Database was not created at BEADS_DB path %s", envDBPath)
}
// Verify database works
store, err := openExistingTestDB(t, envDBPath)
if err != nil {
t.Fatalf("Failed to open database: %v", err)
}
defer store.Close()
ctx := context.Background()
prefix, err := store.GetConfig(ctx, "issue_prefix")
if err != nil {
t.Fatalf("Failed to get prefix: %v", err)
}
if prefix != "envtest" {
t.Errorf("Expected prefix 'envtest', got %q", prefix)
}
})
// Test that BEADS_DB path containing ".beads" doesn't create CWD/.beads
t.Run("init with BEADS_DB path containing .beads", func(t *testing.T) {
dbPath = "" // Reset global
// Path contains ".beads" but is outside work directory
customPath := filepath.Join(tmpDir, "storage", ".beads-backup", "test.db")
os.Setenv("BEADS_DB", customPath)
defer os.Unsetenv("BEADS_DB")
rootCmd.SetArgs([]string{"init", "--prefix", "beadstest", "--quiet"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("Init with custom .beads path failed: %v", err)
}
// Verify database was created at custom location
if _, err := os.Stat(customPath); os.IsNotExist(err) {
t.Errorf("Database was not created at custom path %s", customPath)
}
// Verify .beads/ directory was NOT created in work directory
if _, err := os.Stat(filepath.Join(workDir, ".beads")); err == nil {
t.Error(".beads/ directory should not be created in CWD when BEADS_DB path contains .beads")
}
})
// Test with multiple BEADS_DB variations
t.Run("BEADS_DB with subdirectories", func(t *testing.T) {
dbPath = "" // Reset global
envPath := filepath.Join(tmpDir, "env", "subdirs", "test.db")
os.Setenv("BEADS_DB", envPath)
defer os.Unsetenv("BEADS_DB")
rootCmd.SetArgs([]string{"init", "--prefix", "envtest2", "--quiet"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("Init with BEADS_DB subdirs failed: %v", err)
}
// Verify database was created at env location
if _, err := os.Stat(envPath); os.IsNotExist(err) {
t.Errorf("Database was not created at BEADS_DB path %s", envPath)
}
// Verify .beads/ directory was NOT created in work directory
if _, err := os.Stat(filepath.Join(workDir, ".beads")); err == nil {
t.Error(".beads/ directory should not be created in CWD when BEADS_DB is set")
}
})
}
// TestSetupClaudeSettings_InvalidJSON verifies that invalid JSON in existing
// settings.local.json returns an error instead of silently overwriting.
// This is a regression test for bd-5bj where user settings were lost.
func TestSetupClaudeSettings_InvalidJSON(t *testing.T) {
tmpDir := t.TempDir()
t.Chdir(tmpDir)
// Create .claude directory
claudeDir := filepath.Join(tmpDir, ".claude")
if err := os.MkdirAll(claudeDir, 0755); err != nil {
t.Fatalf("Failed to create .claude directory: %v", err)
}
// Create settings.local.json with invalid JSON (array syntax in object context)
// This is the exact pattern that caused the bug in the user's file
invalidJSON := `{
"permissions": {
"allow": [
"Bash(python3:*)"
],
"deny": [
"_comment": "Add commands to block here"
]
}
}`
settingsPath := filepath.Join(claudeDir, "settings.local.json")
if err := os.WriteFile(settingsPath, []byte(invalidJSON), 0644); err != nil {
t.Fatalf("Failed to write invalid settings: %v", err)
}
// Call setupClaudeSettings - should return an error
var err error
err = setupClaudeSettings(false)
if err == nil {
t.Fatal("Expected error for invalid JSON, got nil")
}
// Verify the error message mentions invalid JSON
if !strings.Contains(err.Error(), "invalid JSON") {
t.Errorf("Expected error to mention 'invalid JSON', got: %v", err)
}
// Verify the original file was NOT modified
content, err := os.ReadFile(settingsPath)
if err != nil {
t.Fatalf("Failed to read settings file: %v", err)
}
if !strings.Contains(string(content), "permissions") {
t.Error("Original file content should be preserved")
}
if strings.Contains(string(content), "bd prime") {
t.Error("File should NOT contain bd prime prompt after error")
}
}
// TestSetupClaudeSettings_ValidJSON verifies that valid JSON is properly updated
func TestSetupClaudeSettings_ValidJSON(t *testing.T) {
tmpDir := t.TempDir()
t.Chdir(tmpDir)
// Create .claude directory
claudeDir := filepath.Join(tmpDir, ".claude")
if err := os.MkdirAll(claudeDir, 0755); err != nil {
t.Fatalf("Failed to create .claude directory: %v", err)
}
// Create settings.local.json with valid JSON
validJSON := `{
"permissions": {
"allow": [
"Bash(python3:*)"
]
},
"hooks": {
"PreToolUse": []
}
}`
settingsPath := filepath.Join(claudeDir, "settings.local.json")
if err := os.WriteFile(settingsPath, []byte(validJSON), 0644); err != nil {
t.Fatalf("Failed to write valid settings: %v", err)
}
// Call setupClaudeSettings - should succeed
var err error
err = setupClaudeSettings(false)
if err != nil {
t.Fatalf("Expected no error for valid JSON, got: %v", err)
}
// Verify the file was updated with prompt AND preserved existing settings
content, err := os.ReadFile(settingsPath)
if err != nil {
t.Fatalf("Failed to read settings file: %v", err)
}
contentStr := string(content)
// Should contain the new prompt
if !strings.Contains(contentStr, "bd prime") {
t.Error("File should contain bd prime prompt")
}
// Should preserve existing permissions
if !strings.Contains(contentStr, "permissions") {
t.Error("File should preserve permissions section")
}
// Should preserve existing hooks
if !strings.Contains(contentStr, "hooks") {
t.Error("File should preserve hooks section")
}
if !strings.Contains(contentStr, "PreToolUse") {
t.Error("File should preserve PreToolUse hook")
}
}
// TestSetupClaudeSettings_NoExistingFile verifies behavior when no file exists
func TestSetupClaudeSettings_NoExistingFile(t *testing.T) {
tmpDir := t.TempDir()
t.Chdir(tmpDir)
// Don't create .claude directory - setupClaudeSettings should create it
// Call setupClaudeSettings - should succeed
var err error
err = setupClaudeSettings(false)
if err != nil {
t.Fatalf("Expected no error when no file exists, got: %v", err)
}
// Verify the file was created with prompt
settingsPath := filepath.Join(tmpDir, ".claude", "settings.local.json")
content, err := os.ReadFile(settingsPath)
if err != nil {
t.Fatalf("Failed to read settings file: %v", err)
}
if !strings.Contains(string(content), "bd prime") {
t.Error("File should contain bd prime prompt")
}
}
// setupIsolatedGitConfig creates an empty git config in tmpDir and sets GIT_CONFIG_GLOBAL
// to prevent tests from using the real user's global git config.
func setupIsolatedGitConfig(t *testing.T, tmpDir string) {
t.Helper()
gitConfigPath := filepath.Join(tmpDir, ".gitconfig")
if err := os.WriteFile(gitConfigPath, []byte(""), 0644); err != nil {
t.Fatal(err)
}
t.Setenv("GIT_CONFIG_GLOBAL", gitConfigPath)
}
// TestSetupGlobalGitIgnore_ReadOnly verifies graceful handling when the
// gitignore file cannot be written (prints manual instructions instead of failing).
func TestSetupGlobalGitIgnore_ReadOnly(t *testing.T) {
t.Run("read-only file", func(t *testing.T) {
if runtime.GOOS == "darwin" {
t.Skip("macOS allows file owner to write to read-only (0444) files")
}
tmpDir := t.TempDir()
setupIsolatedGitConfig(t, tmpDir)
configDir := filepath.Join(tmpDir, ".config", "git")
if err := os.MkdirAll(configDir, 0755); err != nil {
t.Fatal(err)
}
ignorePath := filepath.Join(configDir, "ignore")
if err := os.WriteFile(ignorePath, []byte("# existing\n"), 0644); err != nil {
t.Fatal(err)
}
if err := os.Chmod(ignorePath, 0444); err != nil {
t.Fatal(err)
}
defer os.Chmod(ignorePath, 0644)
output := captureStdout(t, func() error {
return setupGlobalGitIgnore(tmpDir, "/test/project", false)
})
if !strings.Contains(output, "Unable to write") {
t.Error("expected instructions for manual addition")
}
if !strings.Contains(output, "/test/project/.beads/") {
t.Error("expected .beads pattern in output")
}
})
t.Run("symlink to read-only file", func(t *testing.T) {
if runtime.GOOS == "darwin" {
t.Skip("macOS allows file owner to write to read-only (0444) files")
}
tmpDir := t.TempDir()
setupIsolatedGitConfig(t, tmpDir)
// Target file in a separate location
targetDir := filepath.Join(tmpDir, "target")
if err := os.MkdirAll(targetDir, 0755); err != nil {
t.Fatal(err)
}
targetFile := filepath.Join(targetDir, "ignore")
if err := os.WriteFile(targetFile, []byte("# existing\n"), 0644); err != nil {
t.Fatal(err)
}
if err := os.Chmod(targetFile, 0444); err != nil {
t.Fatal(err)
}
defer os.Chmod(targetFile, 0644)
// Symlink from expected location
configDir := filepath.Join(tmpDir, ".config", "git")
if err := os.MkdirAll(configDir, 0755); err != nil {
t.Fatal(err)
}
if err := os.Symlink(targetFile, filepath.Join(configDir, "ignore")); err != nil {
t.Fatal(err)
}
output := captureStdout(t, func() error {
return setupGlobalGitIgnore(tmpDir, "/test/project", false)
})
if !strings.Contains(output, "Unable to write") {
t.Error("expected instructions for manual addition")
}
if !strings.Contains(output, "/test/project/.beads/") {
t.Error("expected .beads pattern in output")
}
})
}
// TestInitPromptRoleConfig tests the beads.role git config read/write functions
func TestInitPromptRoleConfig(t *testing.T) {
t.Run("getBeadsRole returns empty when not configured", func(t *testing.T) {
tmpDir := newGitRepo(t)
t.Chdir(tmpDir)
role, hasRole := getBeadsRole()
if hasRole {
t.Errorf("Expected hasRole=false when not configured, got true with role=%q", role)
}
if role != "" {
t.Errorf("Expected empty role when not configured, got %q", role)
}
})
t.Run("setBeadsRole and getBeadsRole roundtrip", func(t *testing.T) {
tmpDir := newGitRepo(t)
t.Chdir(tmpDir)
// Set role to contributor
if err := setBeadsRole("contributor"); err != nil {
t.Fatalf("Failed to set beads.role: %v", err)
}
role, hasRole := getBeadsRole()
if !hasRole {
t.Error("Expected hasRole=true after setting role")
}
if role != "contributor" {
t.Errorf("Expected role 'contributor', got %q", role)
}
// Change to maintainer
if err := setBeadsRole("maintainer"); err != nil {
t.Fatalf("Failed to set beads.role: %v", err)
}
role, hasRole = getBeadsRole()
if !hasRole {
t.Error("Expected hasRole=true after setting role")
}
if role != "maintainer" {
t.Errorf("Expected role 'maintainer', got %q", role)
}
})
}
// TestInitPromptSkippedWithFlags verifies that --contributor and --team flags skip the prompt
func TestInitPromptSkippedWithFlags(t *testing.T) {
skipIfNoDolt(t)
t.Run("contributor flag skips prompt and runs wizard", func(t *testing.T) {
// Reset global state
origDBPath := dbPath
defer func() { dbPath = origDBPath }()
dbPath = ""
// Reset caches so RepoContext picks up new directory
beads.ResetCaches()
git.ResetCaches()
defer func() {
beads.ResetCaches()
git.ResetCaches()
}()
// Reset Cobra flags
initCmd.Flags().Set("contributor", "false")
tmpDir := newGitRepo(t)
t.Chdir(tmpDir)
// Verify no role is set initially
role, hasRole := getBeadsRole()
if hasRole {
t.Fatalf("Expected no role initially, got %q", role)
}
// Run bd init with --contributor flag (quiet to suppress wizard output)
// The wizard will fail because there's no planning repo, but that's OK
// We just want to verify the flag bypasses the prompt
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--contributor", "--quiet"})
_ = rootCmd.Execute() // Ignore error - wizard may fail
// The --contributor flag should NOT set beads.role (that's done by prompt, not flag)
// The flag just triggers the wizard directly
})
t.Run("team flag skips prompt", func(t *testing.T) {
// Reset global state
origDBPath := dbPath
defer func() { dbPath = origDBPath }()
dbPath = ""
// Reset caches so RepoContext picks up new directory
beads.ResetCaches()
git.ResetCaches()
defer func() {
beads.ResetCaches()
git.ResetCaches()
}()
// Reset Cobra flags
initCmd.Flags().Set("team", "false")
tmpDir := newGitRepo(t)
t.Chdir(tmpDir)
// Verify no role is set initially
role, hasRole := getBeadsRole()
if hasRole {
t.Fatalf("Expected no role initially, got %q", role)
}
// Run bd init with --team flag
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--team", "--quiet"})
_ = rootCmd.Execute() // Ignore error - wizard may fail
// The --team flag should not set beads.role
// (team wizard is separate from contributor/maintainer roles)
})
}
// TestInitPromptTTYDetection verifies shouldPromptForRole behavior
func TestInitPromptTTYDetection(t *testing.T) {
// Note: In test environment, stdin is typically NOT a TTY (it's a pipe)
// This test verifies the function works, not that we're in a TTY
t.Run("shouldPromptForRole returns false in test environment", func(t *testing.T) {
// In test environment, stdin is typically piped, not a TTY
result := shouldPromptForRole()
// We can't guarantee what the result will be in all test environments,
// but we can verify the function doesn't panic and returns a bool
if result {
t.Log("Test environment has TTY stdin (unusual but acceptable)")
} else {
t.Log("Test environment does not have TTY stdin (expected)")
}
})
}
// TestInitPromptNonGitRepo verifies prompt is skipped in non-git directories
func TestInitPromptNonGitRepo(t *testing.T) {
skipIfNoDolt(t)
// Reset global state
origDBPath := dbPath
defer func() { dbPath = origDBPath }()
dbPath = ""
// Reset caches so RepoContext picks up new directory
beads.ResetCaches()
git.ResetCaches()
defer func() {
beads.ResetCaches()
git.ResetCaches()
}()
// Reset Cobra flags that may be set from previous tests
initCmd.Flags().Set("contributor", "false")
initCmd.Flags().Set("team", "false")
tmpDir := t.TempDir()
t.Chdir(tmpDir)
// DON'T initialize git repo
// Run bd init - should succeed without prompting (no git repo)
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--quiet"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("Init should succeed in non-git directory: %v", err)
}
// Verify .beads was created
beadsDir := filepath.Join(tmpDir, ".beads")
if _, err := os.Stat(beadsDir); os.IsNotExist(err) {
t.Error(".beads directory should be created even without git")
}
}
// TestInitPromptExistingRole verifies behavior when beads.role is already set
func TestInitPromptExistingRole(t *testing.T) {
skipIfNoDolt(t)
t.Run("existing role is preserved on reinit with --force", func(t *testing.T) {
// Reset global state
origDBPath := dbPath
defer func() { dbPath = origDBPath }()
dbPath = ""
// Reset caches so RepoContext picks up new directory
beads.ResetCaches()
git.ResetCaches()
defer func() {
beads.ResetCaches()
git.ResetCaches()
}()
// Reset Cobra flags that may be set from previous tests
initCmd.Flags().Set("contributor", "false")
initCmd.Flags().Set("team", "false")
initCmd.Flags().Set("force", "false")
tmpDir := newGitRepo(t)
t.Chdir(tmpDir)
// Set role before init
if err := setBeadsRole("contributor"); err != nil {
t.Fatalf("Failed to set beads.role: %v", err)
}
// Run bd init (non-interactive, so prompt is skipped)
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--quiet"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("Init failed: %v", err)
}
// Verify role is still set
role, hasRole := getBeadsRole()
if !hasRole {
t.Error("Expected beads.role to still be set after init")
}
if role != "contributor" {
t.Errorf("Expected role 'contributor' to be preserved, got %q", role)
}
// Reset Cobra flags for reinit
initCmd.Flags().Set("force", "false")
// Reinit with --force (non-interactive)
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--quiet", "--force"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("Reinit failed: %v", err)
}
// Verify role is still set (not cleared by reinit)
role, hasRole = getBeadsRole()
if !hasRole {
t.Error("Expected beads.role to still be set after reinit")
}
if role != "contributor" {
t.Errorf("Expected role 'contributor' to be preserved after reinit, got %q", role)
}
})
}
func TestInitContributorSetsBeadsRoleContributor(t *testing.T) {
skipIfNoDolt(t)
origDBPath := dbPath
defer func() { dbPath = origDBPath }()
dbPath = ""
beads.ResetCaches()
git.ResetCaches()
defer func() {
beads.ResetCaches()
git.ResetCaches()
}()
initCmd.Flags().Set("contributor", "false")
initCmd.Flags().Set("team", "false")
initCmd.Flags().Set("force", "false")
tmpDir := newGitRepo(t)
t.Chdir(tmpDir)
// Keep test isolated from the real home/planning repo.
testHome := t.TempDir()
t.Setenv("HOME", testHome)
// Configure remotes so contributor wizard doesn't ask the "continue anyway" prompt.
cmd := exec.Command("git", "remote", "add", "origin", "git@github.com:osamu2001/zmx.git")
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to add origin remote: %v", err)
}
cmd = exec.Command("git", "remote", "add", "upstream", "git@github.com:neurosnap/zmx.git")
cmd.Dir = tmpDir
if err := cmd.Run(); err != nil {
t.Fatalf("failed to add upstream remote: %v", err)
}
// Wizard answers:
// 1) "Do you want to use a separate planning repo anyway? [Y/n]" -> Enter (default yes)
// 2) "Planning repo path [press Enter for default]" -> Enter (default ~/.beads-planning)
r, w, err := os.Pipe()
if err != nil {
t.Fatalf("failed to create stdin pipe: %v", err)
}
oldStdin := os.Stdin
os.Stdin = r
t.Cleanup(func() { os.Stdin = oldStdin })
t.Cleanup(func() { _ = r.Close() })
_, _ = w.WriteString("\n\n")
_ = w.Close()
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--contributor", "--quiet"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("init --contributor failed: %v", err)
}
role, hasRole := getBeadsRole()
if !hasRole {
t.Fatal("expected beads.role to be configured")
}
if role != "contributor" {
t.Fatalf("beads.role = %q, want %q", role, "contributor")
}
}
// TestInitNonInteractiveAlwaysSetsRole verifies that bd init --non-interactive
// always leaves beads.role set, even when no --role flag is provided (GH#2950).
// This is the safety net for the init flow.
func TestInitNonInteractiveAlwaysSetsRole(t *testing.T) {
skipIfNoDolt(t)
origDBPath := dbPath
defer func() { dbPath = origDBPath }()
dbPath = ""
beads.ResetCaches()
git.ResetCaches()
defer func() {
beads.ResetCaches()
git.ResetCaches()
}()
initCmd.Flags().Set("contributor", "false")
initCmd.Flags().Set("team", "false")
initCmd.Flags().Set("force", "false")
initCmd.Flags().Set("role", "")
tmpDir := newGitRepo(t)
t.Chdir(tmpDir)
// Ensure no role is set before init
exec.Command("git", "config", "--unset", "beads.role").Run() //nolint:errcheck
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--quiet", "--non-interactive"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("init --non-interactive failed: %v", err)
}
role, hasRole := getBeadsRole()
if !hasRole {
t.Fatal("expected beads.role to be configured after non-interactive init (GH#2950)")
}
if role != "maintainer" {
t.Fatalf("beads.role = %q, want %q (default for non-interactive)", role, "maintainer")
}
}
// TestInitWithRedirect verifies that bd init creates the database in the redirect target,
// not in the local .beads directory. (GH#bd-0qel)
// TestInitRedirect groups redirect-related init tests.
func TestInitRedirect(t *testing.T) {
skipIfNoDolt(t)
resetRedirectState := func(t *testing.T) {
t.Helper()
origDBPath := dbPath
origBeadsDir := os.Getenv("BEADS_DIR")
t.Cleanup(func() {
dbPath = origDBPath
if origBeadsDir != "" {
os.Setenv("BEADS_DIR", origBeadsDir)
} else {
os.Unsetenv("BEADS_DIR")
}
})
dbPath = ""
os.Unsetenv("BEADS_DIR")
initCmd.Flags().Set("prefix", "")
initCmd.Flags().Set("quiet", "false")
initCmd.Flags().Set("force", "false")
}
t.Run("RedirectCreatesDBInTarget", func(t *testing.T) {
resetRedirectState(t)
tmpDir := t.TempDir()
projectDir := filepath.Join(tmpDir, "project")
if err := os.MkdirAll(projectDir, 0755); err != nil {
t.Fatal(err)
}
localBeadsDir := filepath.Join(projectDir, ".beads")
if err := os.MkdirAll(localBeadsDir, 0755); err != nil {
t.Fatal(err)
}
targetBeadsDir := filepath.Join(tmpDir, "canonical", ".beads")
if err := os.MkdirAll(targetBeadsDir, 0755); err != nil {
t.Fatal(err)
}
redirectPath := filepath.Join(localBeadsDir, beads.RedirectFileName)
if err := os.WriteFile(redirectPath, []byte("../canonical/.beads\n"), 0644); err != nil {
t.Fatal(err)
}
t.Chdir(projectDir)
rootCmd.SetArgs([]string{"init", "--prefix", "redirect-test", "--quiet"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("Init with redirect failed: %v", err)
}
targetDBPath := filepath.Join(targetBeadsDir, "dolt")
if _, err := os.Stat(targetDBPath); os.IsNotExist(err) {
t.Errorf("Dolt database was NOT created in redirect target: %s", targetDBPath)
}
localDBPath := filepath.Join(localBeadsDir, "dolt")
if _, err := os.Stat(localDBPath); err == nil {
t.Errorf("Database was incorrectly created in local .beads: %s (should be in redirect target)", localDBPath)
}
store, err := openExistingTestDB(t, targetDBPath)
if err != nil {
t.Fatalf("Failed to open database in redirect target: %v", err)
}
defer store.Close()
ctx := context.Background()
prefix, err := store.GetConfig(ctx, "issue_prefix")
if err != nil {
t.Fatalf("Failed to get issue prefix from database: %v", err)
}
if prefix != "redirect-test" {
t.Errorf("Expected prefix 'redirect-test', got %q", prefix)
}
})
// Verifies that bd init errors when the redirect target already has a database,
// preventing accidental overwrites. (GH#bd-0qel)
t.Run("ErrorWhenTargetHasExistingDB", func(t *testing.T) {
resetRedirectState(t)
tmpDir := t.TempDir()
canonicalDir := filepath.Join(tmpDir, "canonical")
canonicalBeadsDir := filepath.Join(canonicalDir, ".beads")
if err := os.MkdirAll(canonicalBeadsDir, 0755); err != nil {
t.Fatal(err)
}
canonicalDBPath := filepath.Join(canonicalBeadsDir, "beads.db")
// Create the db file so checkExistingBeadsData detects it
if err := os.WriteFile(canonicalDBPath, []byte{}, 0644); err != nil {
t.Fatalf("Failed to create canonical db file: %v", err)
}
projectDir := filepath.Join(tmpDir, "project")
projectBeadsDir := filepath.Join(projectDir, ".beads")
if err := os.MkdirAll(projectBeadsDir, 0755); err != nil {
t.Fatal(err)
}
redirectPath := filepath.Join(projectBeadsDir, beads.RedirectFileName)
if err := os.WriteFile(redirectPath, []byte("../canonical/.beads\n"), 0644); err != nil {
t.Fatal(err)
}
// Use os.Chdir since checkExistingBeadsData reads CWD directly
origWd, _ := os.Getwd()
if err := os.Chdir(projectDir); err != nil {
t.Fatal(err)
}
defer os.Chdir(origWd)
err := checkExistingBeadsData("new-prefix")
if err == nil {
t.Fatal("Expected checkExistingBeadsData to return error when redirect target already has database")
}
errorMsg := err.Error()
if !strings.Contains(errorMsg, "redirect target already has database") {
t.Errorf("Expected error about redirect target having database, got: %s", errorMsg)
}
// Verify the canonical DB file still exists (wasn't deleted/overwritten)
if _, statErr := os.Stat(canonicalDBPath); os.IsNotExist(statErr) {
t.Error("Canonical database file should still exist after error")
}
})
}
// =============================================================================
// BEADS_DIR Tests
// =============================================================================
// These tests verify that bd init respects the BEADS_DIR environment variable
// for both safety checks and database creation.
// TestInitBEADS_DIR groups BEADS_DIR-related init tests.
// Tests requirements FR-001, FR-002, FR-004, NFR-001.
func TestInitBEADS_DIR(t *testing.T) {
skipIfNoDolt(t)
// resetBeadsDirState resets global state and env vars for each subtest.
resetBeadsDirState := func(t *testing.T) {
t.Helper()
origDBPath := dbPath
t.Cleanup(func() {
dbPath = origDBPath
beads.ResetCaches()
git.ResetCaches()
})
dbPath = ""
beads.ResetCaches()
git.ResetCaches()
initCmd.Flags().Set("prefix", "")
initCmd.Flags().Set("quiet", "false")
initCmd.Flags().Set("backend", "")
}
// checkExistingBeadsData tests (FR-001, FR-004)
t.Run("CheckExisting_NoExistingDB", func(t *testing.T) {
resetBeadsDirState(t)
tmpDir := t.TempDir()
beadsDirPath := filepath.Join(tmpDir, "external", ".beads")
os.MkdirAll(beadsDirPath, 0755)
os.Setenv("BEADS_DIR", beadsDirPath)
t.Cleanup(func() { os.Unsetenv("BEADS_DIR") })
beads.ResetCaches()
err := checkExistingBeadsData("test")
if err != nil {
t.Errorf("Expected no error when BEADS_DIR has no database, got: %v", err)
}
})
t.Run("CheckExisting_CWDIgnoredWhenSet", func(t *testing.T) {
resetBeadsDirState(t)
tmpDir := t.TempDir()
// Create CWD with existing database (should be ignored)
cwdBeadsDir := filepath.Join(tmpDir, "cwd", ".beads")
os.MkdirAll(cwdBeadsDir, 0755)
cwdDBPath := filepath.Join(cwdBeadsDir, beads.CanonicalDatabaseName)
// Create the db file so checkExistingBeadsData detects it
if err := os.WriteFile(cwdDBPath, []byte{}, 0644); err != nil {
t.Fatal(err)
}
// Create BEADS_DIR location (no database)
beadsDirPath := filepath.Join(tmpDir, "external", ".beads")
os.MkdirAll(beadsDirPath, 0755)
os.Setenv("BEADS_DIR", beadsDirPath)
t.Cleanup(func() { os.Unsetenv("BEADS_DIR") })
beads.ResetCaches()
origWd, _ := os.Getwd()
os.Chdir(filepath.Join(tmpDir, "cwd"))
defer os.Chdir(origWd)
err := checkExistingBeadsData("test")
if err != nil {
t.Errorf("Expected no error when BEADS_DIR has no database (CWD should be ignored), got: %v", err)
}
})
t.Run("CheckExisting_ErrorWhenDBExists", func(t *testing.T) {
resetBeadsDirState(t)
tmpDir := t.TempDir()
beadsDirPath := filepath.Join(tmpDir, "external", ".beads")
os.MkdirAll(beadsDirPath, 0755)
testDBPath := filepath.Join(beadsDirPath, beads.CanonicalDatabaseName)
// Create the db file so checkExistingBeadsData detects it
if err := os.WriteFile(testDBPath, []byte{}, 0644); err != nil {
t.Fatal(err)
}
os.Setenv("BEADS_DIR", beadsDirPath)
t.Cleanup(func() { os.Unsetenv("BEADS_DIR") })
beads.ResetCaches()
err := checkExistingBeadsData("test")
if err == nil {
t.Error("Expected error when BEADS_DIR already has database")
}
if !strings.Contains(err.Error(), beadsDirPath) {
t.Errorf("Expected error to mention BEADS_DIR path %s, got: %v", beadsDirPath, err)
}
})
// FR-002: init creates database at BEADS_DIR
t.Run("InitCreatesDBAtBeadsDir", func(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Skipping BEADS_DIR test on Windows")
}
resetBeadsDirState(t)
tmpDir := t.TempDir()
beadsDirPath := filepath.Join(tmpDir, "external", ".beads")
os.MkdirAll(filepath.Dir(beadsDirPath), 0755)
os.Setenv("BEADS_DIR", beadsDirPath)
t.Cleanup(func() { os.Unsetenv("BEADS_DIR") })
beads.ResetCaches()
git.ResetCaches()
cwdPath := filepath.Join(tmpDir, "workdir")
os.MkdirAll(cwdPath, 0755)
t.Chdir(cwdPath)
rootCmd.SetArgs([]string{"init", "--prefix", "beadsdir-test", "--quiet"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("Init with BEADS_DIR failed: %v", err)
}
expectedDBPath := filepath.Join(beadsDirPath, "dolt")
if info, err := os.Stat(expectedDBPath); os.IsNotExist(err) {
t.Errorf("Dolt database was not created at BEADS_DIR path: %s", expectedDBPath)
} else if !info.IsDir() {
t.Errorf("Expected %s to be a directory", expectedDBPath)
}
cwdDBPath := filepath.Join(cwdPath, ".beads", "dolt")
if _, err := os.Stat(cwdDBPath); err == nil {
t.Errorf("Database should NOT have been created at CWD: %s", cwdDBPath)
}
store, err := openExistingTestDB(t, expectedDBPath)
if err != nil {
t.Fatalf("Failed to open database at BEADS_DIR: %v", err)
}
defer store.Close()
ctx := context.Background()
prefix, err := store.GetConfig(ctx, "issue_prefix")
if err != nil {
t.Fatalf("Failed to get prefix from database: %v", err)
}
if prefix != "beadsdir-test" {
t.Errorf("Expected prefix 'beadsdir-test', got %q", prefix)
}
})
// NFR-001: existing behavior unchanged when BEADS_DIR not set
t.Run("WithoutBeadsDirNoBehaviorChange", func(t *testing.T) {
resetBeadsDirState(t)
os.Unsetenv("BEADS_DIR")
beads.ResetCaches()
git.ResetCaches()
tmpDir := t.TempDir()
t.Chdir(tmpDir)
rootCmd.SetArgs([]string{"init", "--prefix", "no-beadsdir", "--quiet"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("Init without BEADS_DIR failed: %v", err)
}
expectedDBPath := filepath.Join(tmpDir, ".beads", "dolt")
if info, err := os.Stat(expectedDBPath); os.IsNotExist(err) {
t.Errorf("Dolt database was not created at default CWD/.beads path: %s", expectedDBPath)
} else if !info.IsDir() {
t.Errorf("Expected %s to be a directory", expectedDBPath)
}
store, err := openExistingTestDB(t, expectedDBPath)
if err != nil {
t.Fatalf("Failed to open database: %v", err)
}
defer store.Close()
ctx := context.Background()
prefix, err := store.GetConfig(ctx, "issue_prefix")
if err != nil {
t.Fatalf("Failed to get prefix from database: %v", err)
}
if prefix != "no-beadsdir" {
t.Errorf("Expected prefix 'no-beadsdir', got %q", prefix)
}
})
// Worktree bypass: BEADS_DIR skips the worktree guard and git init
t.Run("WorktreeBypassWhenBeadsDirSet", func(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Skipping worktree test on Windows")
}
resetBeadsDirState(t)
tmpDir := t.TempDir()
// Create a main git repo with an initial commit (required for worktrees)
mainRepo := filepath.Join(tmpDir, "main-repo")
if err := os.MkdirAll(mainRepo, 0755); err != nil {
t.Fatalf("Failed to create main repo dir: %v", err)
}
runGit := func(dir string, args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = dir
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git %v in %s failed: %v\n%s", args, dir, err, out)
}
}
runGit(mainRepo, "init")
runGit(mainRepo, "config", "user.email", "test@test.com")
runGit(mainRepo, "config", "user.name", "Test")
runGit(mainRepo, "commit", "--allow-empty", "-m", "initial")
// Create a worktree
worktreeDir := filepath.Join(tmpDir, "my-worktree")
runGit(mainRepo, "worktree", "add", worktreeDir, "-b", "test-wt")
// Set BEADS_DIR to a standalone location outside the repo
beadsDirPath := filepath.Join(tmpDir, "standalone", ".beads")
if err := os.MkdirAll(filepath.Dir(beadsDirPath), 0755); err != nil {
t.Fatalf("Failed to create standalone dir: %v", err)
}
os.Setenv("BEADS_DIR", beadsDirPath)
t.Cleanup(func() { os.Unsetenv("BEADS_DIR") })
beads.ResetCaches()
git.ResetCaches()
// cd into the worktree — without BEADS_DIR this would fail
t.Chdir(worktreeDir)
rootCmd.SetArgs([]string{"init", "--prefix", "wt-bypass", "--skip-hooks", "--quiet"})
err := rootCmd.Execute()
if err != nil {
t.Fatalf("Init with BEADS_DIR from worktree should succeed, got: %v", err)
}
// Verify database was created at BEADS_DIR, not in the worktree
expectedDBPath := filepath.Join(beadsDirPath, "dolt")
if _, statErr := os.Stat(expectedDBPath); os.IsNotExist(statErr) {
t.Errorf("Dolt database was not created at BEADS_DIR path: %s", expectedDBPath)
}
worktreeDBPath := filepath.Join(worktreeDir, ".beads", "dolt")
if _, statErr := os.Stat(worktreeDBPath); statErr == nil {
t.Errorf("Database should NOT have been created in worktree: %s", worktreeDBPath)
}
})
// Precedence: BEADS_DB > BEADS_DIR
t.Run("BEADS_DB_OverridesBeadsDir", func(t *testing.T) {
t.Skip("BEADS_DB env var does not control Dolt store location; Dolt always uses .beads/dolt/")
resetBeadsDirState(t)
beadsDirTarget := t.TempDir()
beadsDBTarget := t.TempDir()
beadsDirBeads := filepath.Join(beadsDirTarget, ".beads")
if err := os.MkdirAll(beadsDirBeads, 0750); err != nil {
t.Fatal(err)
}
beadsDBPath := filepath.Join(beadsDBTarget, "override.db")
t.Setenv("BEADS_DIR", beadsDirBeads)
t.Setenv("BEADS_DB", beadsDBPath)
tmpDir := t.TempDir()
t.Chdir(tmpDir)
rootCmd.SetArgs([]string{"init", "--prefix", "precedence", "--quiet"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("Init with BEADS_DB + BEADS_DIR failed: %v", err)
}
if _, err := os.Stat(beadsDBPath); os.IsNotExist(err) {
t.Errorf("Database was NOT created at BEADS_DB path: %s", beadsDBPath)
}
beadsDirDBPath := filepath.Join(beadsDirBeads, beads.CanonicalDatabaseName)
if _, err := os.Stat(beadsDirDBPath); err == nil {
t.Errorf("Database was incorrectly created at BEADS_DIR path: %s (BEADS_DB should override)", beadsDirDBPath)
}
store, err := openExistingTestDB(t, beadsDBPath)
if err != nil {
t.Fatalf("Failed to open database: %v", err)
}
defer store.Close()
ctx := context.Background()
prefix, err := store.GetConfig(ctx, "issue_prefix")
if err != nil {
t.Fatalf("Failed to get prefix from database: %v", err)
}
if prefix != "precedence" {
t.Errorf("Expected prefix 'precedence', got %q", prefix)
}
})
}
// TestInit_WithBEADS_DIR_DoltBackend verifies that bd init with Dolt backend
// creates the database at BEADS_DIR when the environment variable is set.
// This tests requirements FR-002 for Dolt backend.
func TestInit_WithBEADS_DIR_DoltBackend(t *testing.T) {
// Skip on Windows
if runtime.GOOS == "windows" {
t.Skip("Skipping BEADS_DIR Dolt test on Windows")
}
testutil.RequireDoltBinary(t)
// Reset global state
origDBPath := dbPath
defer func() { dbPath = origDBPath }()
dbPath = ""
// Save and restore BEADS_DIR
origBeadsDir := os.Getenv("BEADS_DIR")
defer func() {
if origBeadsDir != "" {
os.Setenv("BEADS_DIR", origBeadsDir)
} else {
os.Unsetenv("BEADS_DIR")
}
beads.ResetCaches()
git.ResetCaches()
}()
// Reset Cobra flags
initCmd.Flags().Set("prefix", "")
initCmd.Flags().Set("quiet", "false")
initCmd.Flags().Set("backend", "")
tmpDir := t.TempDir()
// Create external BEADS_DIR location
beadsDirPath := filepath.Join(tmpDir, "external", ".beads")
os.MkdirAll(filepath.Dir(beadsDirPath), 0755)
os.Setenv("BEADS_DIR", beadsDirPath)
beads.ResetCaches()
git.ResetCaches()
// Change to a different working directory
cwdPath := filepath.Join(tmpDir, "workdir")
os.MkdirAll(cwdPath, 0755)
t.Chdir(cwdPath)
// Run bd init with Dolt backend
rootCmd.SetArgs([]string{"init", "--prefix", "dolt-test", "--quiet"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("Init with BEADS_DIR and Dolt backend failed: %v", err)
}
// In embedded mode (default), the engine creates .beads/embeddeddolt/ —
// .beads/dolt/ should NOT be created (GH#2903).
unexpectedDoltPath := filepath.Join(beadsDirPath, "dolt")
if _, err := os.Stat(unexpectedDoltPath); err == nil {
t.Errorf("Empty .beads/dolt/ should not be created in embedded mode: %s", unexpectedDoltPath)
}
// Verify database was NOT created at CWD
cwdDoltPath := filepath.Join(cwdPath, ".beads", "dolt")
if _, err := os.Stat(cwdDoltPath); err == nil {
t.Errorf("Dolt database should NOT have been created at CWD: %s", cwdDoltPath)
}
}
// Note: TestInit_WithoutBEADS_DIR_NoBehaviorChange and TestInit_BEADS_DB_OverridesBEADS_DIR
// are now subtests of TestInitBEADS_DIR above.
// TestInitDoltMetadata verifies that bd init --backend dolt writes and persists
// all 3 tracking metadata fields (bd_version, repo_id, clone_id) via verifyMetadata.
// Covers FR-001, FR-002, FR-003, FR-004.
func TestInitDoltMetadata(t *testing.T) {
skipIfNoDolt(t)
if runtime.GOOS == "windows" {
t.Skip("Skipping Dolt metadata test on Windows")
}
saveAndRestoreGlobals(t)
dbPath = ""
// Reset caches to avoid stale state
beads.ResetCaches()
git.ResetCaches()
t.Cleanup(func() {
beads.ResetCaches()
git.ResetCaches()
})
// Reset Cobra flags
initCmd.Flags().Set("prefix", "")
initCmd.Flags().Set("quiet", "false")
initCmd.Flags().Set("backend", "")
tmpDir := newGitRepo(t)
t.Chdir(tmpDir)
// Add remote.origin.url so ComputeRepoID succeeds
_ = runCommandInDir(tmpDir, "git", "config", "remote.origin.url", "https://github.com/test/repo.git")
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--quiet"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("init --backend dolt failed: %v", err)
}
// Open the dolt store to verify metadata was written
ctx := context.Background()
doltPath := filepath.Join(tmpDir, ".beads", "dolt")
doltStore, err := openDoltStoreForTest(t, ctx, doltPath, "test")
if err != nil {
t.Fatalf("failed to open dolt store for verification: %v", err)
}
defer doltStore.Close()
// FR-001: bd_version must be written
bdVersion, err := doltStore.GetLocalMetadata(ctx, "bd_version")
if err != nil {
t.Fatalf("GetLocalMetadata(bd_version) failed: %v", err)
}
if bdVersion == "" {
t.Error("bd_version local metadata was not written")
}
// FR-002: repo_id must be written (git repo with remote configured)
repoID, err := doltStore.GetMetadata(ctx, "repo_id")
if err != nil {
t.Fatalf("GetMetadata(repo_id) failed: %v", err)
}
if repoID == "" {
t.Error("repo_id metadata was not written")
}
// FR-003: clone_id must be written
cloneID, err := doltStore.GetMetadata(ctx, "clone_id")
if err != nil {
t.Fatalf("GetMetadata(clone_id) failed: %v", err)
}
if cloneID == "" {
t.Error("clone_id metadata was not written")
}
}
// openDoltStoreForTest opens an existing Dolt store for read-only verification in tests.
func openDoltStoreForTest(t *testing.T, ctx context.Context, doltPath, dbName string) (*dolt.DoltStore, error) {
t.Helper()
return dolt.New(ctx, &dolt.Config{
Path: doltPath,
Database: dbName,
ReadOnly: true,
})
}
// TestVerifyMetadataSuccess verifies that verifyMetadata writes and reads back metadata.
// Note: Failure path tests (write errors, read-back mismatches) were removed because
// verifyMetadata now takes *dolt.DoltStore (concrete type), making interface-based
// mocking impossible. The failure paths are simple error-to-stderr logic.
func TestVerifyMetadataSuccess(t *testing.T) {
skipIfNoDolt(t)
ctx := context.Background()
tmpDir := t.TempDir()
testDB := filepath.Join(tmpDir, "test.db")
store := newTestStore(t, testDB)
defer store.Close()
ok := verifyMetadata(ctx, store, "test_key", "test_value")
if !ok {
t.Error("verifyMetadata should return true on success")
}
// Verify the value was actually written
val, err := store.GetMetadata(ctx, "test_key")
if err != nil {
t.Fatalf("GetMetadata failed: %v", err)
}
if val != "test_value" {
t.Errorf("expected 'test_value', got %q", val)
}
}
// TestInitDoltMetadataNoGit verifies that bd init outside a git repo gracefully
// skips repo_id while still writing bd_version and clone_id.
// Verifies warning output; actual metadata persistence checked by e2e tests.
// Covers FR-015 (skip repo_id outside git).
func TestInitDoltMetadataNoGit(t *testing.T) {
skipIfNoDolt(t)
if runtime.GOOS == "windows" {
t.Skip("Skipping Dolt metadata test on Windows")
}
saveAndRestoreGlobals(t)
dbPath = ""
beads.ResetCaches()
git.ResetCaches()
t.Cleanup(func() {
beads.ResetCaches()
git.ResetCaches()
})
// Reset Cobra flags
initCmd.Flags().Set("prefix", "")
initCmd.Flags().Set("quiet", "false")
initCmd.Flags().Set("backend", "")
// Create temp dir WITHOUT git init — bd init will create one,
// but there will be no remote configured so upstream warning is expected.
tmpDir := t.TempDir()
t.Chdir(tmpDir)
// Run init in a non-git directory (bd init will create git repo internally)
rootCmd.SetArgs([]string{"init", "--prefix", "nogit"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("init --prefix nogit failed: %v", err)
}
// Note: no upstream/repository ID warning expected here because bd init
// creates a brand-new git repo with no remotes, and the upstream warning
// is intentionally skipped for repos with no remotes (not noise-worthy).
// Verify .beads/dolt directory was created (init succeeded)
doltPath := filepath.Join(tmpDir, ".beads", "dolt")
if info, err := os.Stat(doltPath); os.IsNotExist(err) {
t.Errorf("Dolt database directory was not created: %s", doltPath)
} else if !info.IsDir() {
t.Errorf("Expected Dolt path to be a directory: %s", doltPath)
}
// Verify no SQLite database was created (backend-specific)
sqlitePath := filepath.Join(tmpDir, ".beads", "beads.db")
if _, err := os.Stat(sqlitePath); err == nil {
t.Errorf("unexpected sqlite database created in dolt mode")
}
}
func TestInitServerModeWritesDoltCompatibilityMarker(t *testing.T) {
skipIfNoDolt(t)
saveAndRestoreGlobals(t)
ensureCleanGlobalState(t)
dbPath = ""
store = nil
tmpDir := t.TempDir()
t.Chdir(tmpDir)
beadsDir := filepath.Join(tmpDir, ".beads")
doltDir := filepath.Join(beadsDir, "dolt")
if err := os.MkdirAll(beadsDir, 0o700); err != nil {
t.Fatalf("creating beads dir: %v", err)
}
if err := os.MkdirAll(filepath.Join(doltDir, ".dolt"), 0o750); err != nil {
t.Fatalf("creating simulated server data dir: %v", err)
}
database := uniqueTestDBName(t)
t.Cleanup(func() {
dropTestDatabase(database, testDoltServerPort)
})
rootCmd.SetArgs([]string{
"init",
"--server",
"--external",
"--server-host", "127.0.0.1",
"--server-port", fmt.Sprintf("%d", testDoltServerPort),
"--database", database,
"--prefix", "marker",
"--quiet",
"--skip-hooks",
"--skip-agents",
})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("server init failed: %v", err)
}
markerPath := filepath.Join(doltDir, ".bd-dolt-ok")
if _, err := os.Stat(markerPath); err != nil {
t.Fatalf("expected server init to write %s: %v", markerPath, err)
}
}
func TestInitServerModeWarnsOnMarkerFailureInQuietMode(t *testing.T) {
skipIfNoDolt(t)
saveAndRestoreGlobals(t)
ensureCleanGlobalState(t)
dbPath = ""
store = nil
tmpDir := t.TempDir()
t.Chdir(tmpDir)
beadsDir := filepath.Join(tmpDir, ".beads")
doltDir := filepath.Join(beadsDir, "dolt")
if err := os.MkdirAll(doltDir, 0o700); err != nil {
t.Fatalf("creating dolt dir: %v", err)
}
if err := os.WriteFile(filepath.Join(doltDir, ".dolt"), []byte("not a dir"), 0o600); err != nil {
t.Fatalf("creating invalid dot-dolt marker: %v", err)
}
database := uniqueTestDBName(t)
t.Cleanup(func() {
dropTestDatabase(database, testDoltServerPort)
})
oldStderr := os.Stderr
r, w, err := os.Pipe()
if err != nil {
t.Fatalf("pipe stderr: %v", err)
}
os.Stderr = w
defer func() {
os.Stderr = oldStderr
}()
rootCmd.SetArgs([]string{
"init",
"--server",
"--external",
"--server-host", "127.0.0.1",
"--server-port", fmt.Sprintf("%d", testDoltServerPort),
"--database", database,
"--prefix", "marker",
"--quiet",
"--skip-hooks",
"--skip-agents",
})
if err := rootCmd.Execute(); err != nil {
w.Close()
t.Fatalf("server init failed: %v", err)
}
if err := w.Close(); err != nil {
t.Fatalf("close stderr writer: %v", err)
}
var stderr bytes.Buffer
if _, err := stderr.ReadFrom(r); err != nil {
t.Fatalf("read stderr: %v", err)
}
if !strings.Contains(stderr.String(), "Warning: failed to write Dolt compatibility marker") {
t.Fatalf("expected marker warning in stderr, got:\n%s", stderr.String())
}
if !strings.Contains(stderr.String(), doltDir) {
t.Fatalf("expected marker warning to include dolt dir %s, got:\n%s", doltDir, stderr.String())
}
}
func setupBareParentInitWorktree(t *testing.T) (string, string) {
t.Helper()
tmpDir := t.TempDir()
bareDir := filepath.Join(tmpDir, "repo.git")
mainWorktreeDir := filepath.Join(tmpDir, "main")
featureWorktreeDir := filepath.Join(tmpDir, "feature")
runGit := func(dir string, args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = dir
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git %v in %s failed: %v\n%s", args, dir, err, out)
}
}
runGit(tmpDir, "init", "--bare", bareDir)
runGit(tmpDir, "--git-dir", bareDir, "symbolic-ref", "HEAD", "refs/heads/main")
runGit(tmpDir, "--git-dir", bareDir, "config", "user.email", "test@example.com")
runGit(tmpDir, "--git-dir", bareDir, "config", "user.name", "Test User")
emptyTreeCmd := exec.Command("git", "--git-dir", bareDir, "hash-object", "-t", "tree", "/dev/null")
emptyTreeCmd.Dir = tmpDir
emptyTreeOut, err := emptyTreeCmd.CombinedOutput()
if err != nil {
t.Fatalf("git hash-object failed: %v\n%s", err, emptyTreeOut)
}
emptyTree := strings.TrimSpace(string(emptyTreeOut))
commitCmd := exec.Command("git", "--git-dir", bareDir, "commit-tree", "-m", "Initial commit", emptyTree)
commitCmd.Dir = tmpDir
commitOut, err := commitCmd.CombinedOutput()
if err != nil {
t.Fatalf("git commit-tree failed: %v\n%s", err, commitOut)
}
initCommit := strings.TrimSpace(string(commitOut))
runGit(tmpDir, "--git-dir", bareDir, "update-ref", "HEAD", initCommit)
runGit(tmpDir, "--git-dir", bareDir, "worktree", "add", mainWorktreeDir, "main")
runGit(mainWorktreeDir, "branch", "feature")
runGit(tmpDir, "--git-dir", bareDir, "worktree", "add", featureWorktreeDir, "feature")
return bareDir, featureWorktreeDir
}
// TestInitDatabaseFlag tests the --database flag for bd init.
// Uses subprocess execution because:
// - init manipulates extensive Cobra global state that's difficult to reset
// - init validation paths call os.Exit(1), which kills in-process tests
//
// Each subtest runs bd init in a temp directory and verifies metadata.json.
func TestInitDatabaseFlag(t *testing.T) {
skipIfNoDolt(t)
bd := buildBDForInitTests(t)
t.Run("metadata_written", func(t *testing.T) {
tmpDir := t.TempDir()
// Run init with --database to specify a pre-existing database name
cmd := exec.Command(bd, "init", "--database", "myapp_production", "--quiet")
cmd.Dir = tmpDir
cmd.Env = os.Environ()
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("bd init --database failed: %v\n%s", err, out)
}
// Verify metadata.json contains the correct database name
beadsDir := filepath.Join(tmpDir, ".beads")
cfg, err := configfile.Load(beadsDir)
if err != nil {
t.Fatalf("Failed to load metadata.json: %v", err)
}
if cfg == nil {
t.Fatal("metadata.json not found")
}
if cfg.DoltDatabase != "myapp_production" {
t.Errorf("Expected DoltDatabase %q, got %q", "myapp_production", cfg.DoltDatabase)
}
if cfg.DoltMode != configfile.DoltModeServer {
t.Errorf("Expected DoltMode %q, got %q", configfile.DoltModeServer, cfg.DoltMode)
}
})
t.Run("BareParentWorktreeAutoInit", func(t *testing.T) {
skipIfNoDolt(t)
if runtime.GOOS == "windows" {
t.Skip("Skipping worktree test on Windows")
}
origDBPath := dbPath
t.Cleanup(func() {
dbPath = origDBPath
beads.ResetCaches()
git.ResetCaches()
})
dbPath = ""
beads.ResetCaches()
git.ResetCaches()
bd := buildBDForInitTests(t)
bareDir, worktreeDir := setupBareParentInitWorktree(t)
bareBeadsDir := filepath.Join(bareDir, ".beads")
cmd := exec.Command(bd, "init", "--prefix", "bare-fallback", "--skip-hooks", "--quiet")
cmd.Dir = worktreeDir
cmd.Env = append(os.Environ(), "BEADS_DOLT_SHARED_SERVER=1")
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("bd init from bare-parent worktree failed: %v\n%s", err, out)
}
if _, err := os.Stat(filepath.Join(bareBeadsDir, "metadata.json")); err != nil {
t.Fatalf("expected bare parent metadata.json to exist: %v", err)
}
if _, err := os.Stat(filepath.Join(worktreeDir, ".beads")); !os.IsNotExist(err) {
t.Fatalf("worktree should not get a local .beads directory, stat err=%v", err)
}
retry := exec.Command(bd, "init", "--prefix", "bare-fallback", "--skip-hooks", "--quiet")
retry.Dir = worktreeDir
retry.Env = append(os.Environ(), "BEADS_DOLT_SHARED_SERVER=1")
retryOut, retryErr := retry.CombinedOutput()
if retryErr == nil {
t.Fatal("expected second bd init to fail against existing bare-parent .beads")
}
if !strings.Contains(string(retryOut), "already initialized") && !strings.Contains(string(retryOut), "already exists") {
t.Fatalf("expected existing-data guard on second init, got:\n%s", retryOut)
}
})
t.Run("with_prefix", func(t *testing.T) {
tmpDir := t.TempDir()
// Run init with both --database and --prefix
// --database should override prefix for DB name, but prefix still sets issue_prefix
cmd := exec.Command(bd, "init", "--database", "shared_db", "--prefix", "team-alpha", "--quiet")
cmd.Dir = tmpDir
cmd.Env = os.Environ()
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("bd init --database --prefix failed: %v\n%s", err, out)
}
// Verify metadata.json
beadsDir := filepath.Join(tmpDir, ".beads")
cfg, err := configfile.Load(beadsDir)
if err != nil {
t.Fatalf("Failed to load metadata.json: %v", err)
}
if cfg == nil {
t.Fatal("metadata.json not found")
}
// --database overrides the SQL database name
if cfg.DoltDatabase != "shared_db" {
t.Errorf("Expected DoltDatabase %q (from --database), got %q", "shared_db", cfg.DoltDatabase)
}
// Verify the database was opened and issue_prefix was set
// by reopening the store and checking config
dbPath := filepath.Join(beadsDir, "dolt")
s, err := openExistingTestDB(t, dbPath)
if err != nil {
t.Fatalf("Failed to reopen database: %v", err)
}
defer s.Close()
ctx := context.Background()
issuePrefix, err := s.GetConfig(ctx, "issue_prefix")
if err != nil {
t.Fatalf("Failed to get issue_prefix: %v", err)
}
if issuePrefix != "team-alpha" {
t.Errorf("Expected issue_prefix %q (from --prefix), got %q", "team-alpha", issuePrefix)
}
})
t.Run("server_config_in_metadata", func(t *testing.T) {
tmpDir := t.TempDir()
// Run init with --database
cmd := exec.Command(bd, "init", "--database", "test_server_cfg", "--quiet")
cmd.Dir = tmpDir
cmd.Env = os.Environ()
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("bd init --database failed: %v\n%s", err, out)
}
// Verify metadata.json has both dolt_database and dolt_mode: server
beadsDir := filepath.Join(tmpDir, ".beads")
cfg, err := configfile.Load(beadsDir)
if err != nil {
t.Fatalf("Failed to load metadata.json: %v", err)
}
if cfg == nil {
t.Fatal("metadata.json not found")
}
if cfg.DoltDatabase != "test_server_cfg" {
t.Errorf("Expected DoltDatabase %q, got %q", "test_server_cfg", cfg.DoltDatabase)
}
if cfg.DoltMode != configfile.DoltModeServer {
t.Errorf("Expected DoltMode %q, got %q", configfile.DoltModeServer, cfg.DoltMode)
}
if cfg.Backend != configfile.BackendDolt {
t.Errorf("Expected Backend %q, got %q", configfile.BackendDolt, cfg.Backend)
}
})
t.Run("shared_server_flag_selects_server_mode", func(t *testing.T) {
tmpDir := t.TempDir()
cmd := exec.Command(bd, "init", "--shared-server", "--prefix", "shared-mode-test", "--skip-hooks")
cmd.Dir = tmpDir
cmd.Env = os.Environ()
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("bd init --shared-server failed: %v\n%s", err, out)
}
beadsDir := filepath.Join(tmpDir, ".beads")
cfg, err := configfile.Load(beadsDir)
if err != nil {
t.Fatalf("Failed to load metadata.json: %v", err)
}
if cfg == nil {
t.Fatal("metadata.json not found")
}
if cfg.DoltMode != configfile.DoltModeServer {
t.Errorf("Expected DoltMode %q, got %q", configfile.DoltModeServer, cfg.DoltMode)
}
configYAML, err := os.ReadFile(filepath.Join(beadsDir, "config.yaml"))
if err != nil {
t.Fatalf("Failed to read config.yaml: %v", err)
}
if !strings.Contains(string(configYAML), "dolt.shared-server: true") {
t.Fatalf("expected config.yaml to enable shared server, got:\n%s", configYAML)
}
outStr := string(out)
if !strings.Contains(outStr, "Shared server mode enabled") {
t.Fatalf("expected init output to mention shared server mode, got:\n%s", outStr)
}
if !strings.Contains(outStr, "Mode: server") {
t.Fatalf("expected init output to report server mode, got:\n%s", outStr)
}
if strings.Contains(outStr, "Mode: embedded") {
t.Fatalf("init output should not report embedded mode when --shared-server is set:\n%s", outStr)
}
})
t.Run("validation_invalid_name", func(t *testing.T) {
tmpDir := t.TempDir()
// Run init with an invalid database name (contains semicolon = SQL injection)
cmd := exec.Command(bd, "init", "--database", "bad;name", "--quiet")
cmd.Dir = tmpDir
cmd.Env = os.Environ()
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatal("Expected error for invalid database name, but command succeeded")
}
outStr := string(out)
if !strings.Contains(outStr, "invalid database name") {
t.Errorf("Expected error to mention 'invalid database name', got: %s", outStr)
}
// Verify no .beads directory was created (early validation prevents side effects)
beadsDir := filepath.Join(tmpDir, ".beads")
if _, err := os.Stat(beadsDir); err == nil {
t.Error(".beads directory should not be created when validation fails")
}
})
t.Run("validation_name_with_spaces", func(t *testing.T) {
tmpDir := t.TempDir()
// Database name with spaces should fail validation
cmd := exec.Command(bd, "init", "--database", "my database", "--quiet")
cmd.Dir = tmpDir
cmd.Env = os.Environ()
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatal("Expected error for database name with spaces, but command succeeded")
}
outStr := string(out)
if !strings.Contains(outStr, "invalid database name") {
t.Errorf("Expected error to mention 'invalid database name', got: %s", outStr)
}
})
t.Run("validation_name_with_backtick", func(t *testing.T) {
tmpDir := t.TempDir()
// Database name with backtick injection should fail validation
cmd := exec.Command(bd, "init", "--database", "db`; DROP DATABASE x; --", "--quiet")
cmd.Dir = tmpDir
cmd.Env = os.Environ()
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatal("Expected error for database name with backtick injection, but command succeeded")
}
outStr := string(out)
if !strings.Contains(outStr, "invalid database name") {
t.Errorf("Expected error to mention 'invalid database name', got: %s", outStr)
}
})
}
func TestBareParentWorktreeCoreCommandsWithoutRedirect(t *testing.T) {
skipIfNoDolt(t)
if runtime.GOOS == "windows" {
t.Skip("Skipping worktree test on Windows")
}
bd := buildBDForInitTests(t)
bareDir, worktreeDir := setupBareParentInitWorktree(t)
bareBeadsDir := filepath.Join(bareDir, ".beads")
sharedEnv := append(os.Environ(), "BEADS_DOLT_SHARED_SERVER=1")
initCmd := exec.Command(bd, "init", "--prefix", "bare-core", "--skip-hooks", "--quiet")
initCmd.Dir = worktreeDir
initCmd.Env = sharedEnv
if out, err := initCmd.CombinedOutput(); err != nil {
t.Fatalf("bd init from bare-parent worktree failed: %v\n%s", err, out)
}
if _, err := os.Stat(filepath.Join(bareBeadsDir, "metadata.json")); err != nil {
t.Fatalf("expected bare parent metadata.json to exist: %v", err)
}
createCmd := exec.Command(bd, "create", "bare fallback issue", "--description", "regression", "--json")
createCmd.Dir = worktreeDir
createCmd.Env = sharedEnv
createOut, err := createCmd.CombinedOutput()
if err != nil {
t.Fatalf("bd create from bare-parent worktree failed: %v\n%s", err, createOut)
}
if !strings.Contains(string(createOut), "bare fallback issue") {
t.Fatalf("bd create output did not include created title:\n%s", createOut)
}
listCmd := exec.Command(bd, "list", "--json")
listCmd.Dir = worktreeDir
listCmd.Env = sharedEnv
listOut, err := listCmd.CombinedOutput()
if err != nil {
t.Fatalf("bd list from bare-parent worktree failed: %v\n%s", err, listOut)
}
if !strings.Contains(string(listOut), "bare fallback issue") {
t.Fatalf("bd list output did not include created issue:\n%s", listOut)
}
}
// initBackendTestEnv returns the process environment with all beads-specific
// variables (BEADS_*, BD_*) removed and BEADS_DIR pinned to beadsDir. Pinning
// BEADS_DIR isolates each subtest's workspace and stops bd from walking up into
// an ambient .beads left by another test or tool; HOME is preserved so bd init's
// git bootstrap still works.
func initBackendTestEnv(beadsDir string) []string {
var env []string
for _, e := range os.Environ() {
if strings.HasPrefix(e, "BEADS_") || strings.HasPrefix(e, "BD_") {
continue
}
env = append(env, e)
}
return append(env, "BEADS_DIR="+beadsDir)
}
func TestInitBackendFlag(t *testing.T) {
bd := buildBDForInitTests(t)
// SQLite is a supported pluggable backend now (it was removed under the
// one-backend assumption in #3151 and re-added as a leaf backend): init
// succeeds and metadata.json records backend=sqlite.
t.Run("sqlite_initializes_and_persists_backend", func(t *testing.T) {
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
cmd := exec.Command(bd, "init", "--backend", "sqlite", "--quiet")
cmd.Dir = tmpDir
cmd.Env = initBackendTestEnv(beadsDir)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("bd init --backend=sqlite should succeed: %v\n%s", err, out)
}
cfg, err := configfile.Load(beadsDir)
if err != nil {
t.Fatalf("Failed to load metadata.json: %v", err)
}
if cfg == nil {
t.Fatal("metadata.json not found after --backend=sqlite init")
}
if cfg.Backend != configfile.BackendSQLite {
t.Errorf("Expected backend %q, got %q", configfile.BackendSQLite, cfg.Backend)
}
})
// Postgres is a recognized backend now: it must not be rejected as unknown,
// and it fails only because the required connection config is absent.
t.Run("postgres_is_recognized_and_requires_config", func(t *testing.T) {
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
cmd := exec.Command(bd, "init", "--backend", "postgres", "--quiet")
cmd.Dir = tmpDir
cmd.Env = initBackendTestEnv(beadsDir)
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatal("Expected non-zero exit for --backend=postgres without connection config")
}
outStr := string(out)
if strings.Contains(outStr, "unknown backend") {
t.Errorf("postgres must be a recognized backend, not reported unknown: %s", outStr)
}
if !strings.Contains(outStr, "--pg-url") {
t.Errorf("Expected missing --pg-url guidance for postgres, got: %s", outStr)
}
})
// A genuinely unsupported backend value is still rejected up front.
t.Run("unknown_backend_errors", func(t *testing.T) {
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
cmd := exec.Command(bd, "init", "--backend", "mongodb", "--quiet")
cmd.Dir = tmpDir
cmd.Env = initBackendTestEnv(beadsDir)
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatal("Expected non-zero exit for a genuinely unknown backend")
}
outStr := string(out)
if !strings.Contains(outStr, "unknown backend") {
t.Errorf("Expected 'unknown backend' error, got: %s", outStr)
}
})
t.Run("dolt_backend_succeeds", func(t *testing.T) {
skipIfNoDolt(t)
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
cmd := exec.Command(bd, "init", "--backend", "dolt", "--quiet")
cmd.Dir = tmpDir
cmd.Env = initBackendTestEnv(beadsDir)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("bd init --backend=dolt should succeed: %v\n%s", err, out)
}
})
t.Run("default_backend_is_dolt", func(t *testing.T) {
skipIfNoDolt(t)
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
cmd := exec.Command(bd, "init", "--quiet")
cmd.Dir = tmpDir
cmd.Env = initBackendTestEnv(beadsDir)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("bd init should default to dolt: %v\n%s", err, out)
}
// Verify metadata.json has backend: dolt
cfg, err := configfile.Load(beadsDir)
if err != nil {
t.Fatalf("Failed to load metadata.json: %v", err)
}
if cfg == nil {
t.Fatal("metadata.json not found")
}
if cfg.Backend != configfile.BackendDolt {
t.Errorf("Expected backend %q, got %q", configfile.BackendDolt, cfg.Backend)
}
})
}
// TestInitDatabaseAdoptsExistingProjectID verifies that bd init --database adopts
// the _project_id from an existing server database instead of generating a new one.
// This prevents PROJECT IDENTITY MISMATCH errors when multiple users connect to
// a shared remote Dolt server. (GH#2922)
func TestInitDatabaseAdoptsExistingProjectID(t *testing.T) {
skipIfNoDolt(t)
// Reset global state
origDBPath := dbPath
origStore := store
defer func() {
if store != nil && store != origStore {
store.Close()
}
store = origStore
dbPath = origDBPath
}()
dbPath = ""
store = nil
ctx := context.Background()
// Create a database with a known _project_id (simulates first user's init)
database := uniqueTestDBName(t)
firstBeadsDir := filepath.Join(t.TempDir(), ".beads")
if err := os.MkdirAll(firstBeadsDir, 0o755); err != nil {
t.Fatalf("mkdir: %v", err)
}
doltNewMutex.Lock()
firstStore, err := dolt.New(ctx, &dolt.Config{
Path: filepath.Join(firstBeadsDir, "dolt"),
BeadsDir: firstBeadsDir,
ServerHost: "127.0.0.1",
ServerPort: testDoltServerPort,
Database: database,
CreateIfMissing: true,
})
doltNewMutex.Unlock()
if err != nil {
t.Fatalf("create first store: %v", err)
}
knownProjectID := "test-known-project-id-gh2922"
if err := firstStore.SetMetadata(ctx, "_project_id", knownProjectID); err != nil {
t.Fatalf("set _project_id: %v", err)
}
if err := firstStore.SetConfig(ctx, "issue_prefix", "test"); err != nil {
t.Fatalf("set issue_prefix: %v", err)
}
firstStore.Close()
t.Cleanup(func() {
dropTestDatabase(database, testDoltServerPort)
})
// Simulate second user — init with --database pointing at the existing DB
secondDir := t.TempDir()
t.Chdir(secondDir)
// Set up minimal git repo (init expects it for repo_id)
if err := exec.Command("git", "-C", secondDir, "init").Run(); err != nil {
t.Fatalf("git init: %v", err)
}
_ = exec.Command("git", "-C", secondDir, "config", "user.email", "test@test.com").Run()
_ = exec.Command("git", "-C", secondDir, "config", "user.name", "Test").Run()
rootCmd.SetArgs([]string{
"init",
"--server",
"--server-host", "127.0.0.1",
"--server-port", fmt.Sprintf("%d", testDoltServerPort),
"--database", database,
"--prefix", "second",
"--quiet",
"--skip-hooks",
"--skip-agents",
})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("second init failed: %v", err)
}
// Verify the second user's metadata.json adopted the existing project_id
secondBeadsDir := filepath.Join(secondDir, ".beads")
cfg, err := configfile.Load(secondBeadsDir)
if err != nil {
t.Fatalf("load metadata.json: %v", err)
}
if cfg.ProjectID != knownProjectID {
t.Errorf("ProjectID = %q, want %q (should adopt existing project_id from server)", cfg.ProjectID, knownProjectID)
}
}