beads/cmd/bd/backup_test.go
Okano, Osamu ef6c6e3e48
Follow up remaining runtime .beads fallbacks after GH#3124 (#3183)
* fix(workspace): align resolved workspace messaging and config lookup

intent(workspace): pure worktrees and external BEADS_DIR setups should work without implying a local .beads directory is required
decision(config): derive config repo roots from FindBeadsDir-backed workspace resolution instead of a local-only .beads walk
constraint(workspace-detection): keep FindBeadsDir ordering and storage behavior unchanged while making bd where the primary diagnostic hint
learned(testing): shared-server env and global .beads ignore rules can distort CGO suites, so regression coverage now normalizes those test paths

* fix(bootstrap): align no-workspace JSON wording

intent(bootstrap): machine-readable no-workspace output should match the resolved-workspace guidance used elsewhere on this branch
decision(bootstrap-json): reuse the shared workspace error helpers through a dedicated payload builder so tests can lock the JSON contract
constraint(review-loop): keep the bootstrap CLI flow unchanged outside the no-workspace JSON branch while adding a focused regression test

* fix(where): allow no-workspace diagnostics without db (beads-9f74-5l1)

intent(where): no-workspace guidance should point to a command that actually runs when workspace resolution fails
decision(startup): treat top-level where as a no-db command so it reaches its own handler before database preflight
constraint(where-tests): subprocess mode can change the exact hint text, so the regression test locks the JSON contract and stable guidance fragments instead

* fix(bootstrap): restore bd where guidance for no-workspace output (beads-9f74-3c3)

intent(bootstrap): no-workspace bootstrap guidance should match the resolved-workspace diagnostics introduced on this branch
decision(no-workspace-hints): reuse the shared hint that mentions bd where instead of the bootstrap-specific fallback text
constraint(bootstrap-tests): cover both the payload helper and subprocess CLI path so wording regressions are caught before release

* fix(workspace): remove no-workspace .beads fallbacks (beads-9f74-gr1)

intent(workspace-resolution): finish the GH#3124 follow-up for runtime paths that still fabricated local .beads state
rejected(no-workspace-fallback): inventing ./ .beads paths outside an active workspace hid shared-worktree resolution and created stray files
decision(setup-recipes): keep built-in bd setup recipes usable without a workspace but require an active workspace for custom recipe state
constraint(worktree-support): completion and backup helpers still need to resolve shared main-repo workspaces from a git worktree

* fix(config): skip no-workspace store init for store-free commands

intent(config): review-fix-loop found no-workspace config commands should reach their own graceful paths instead of failing in PersistentPreRun
decision(config-preflight): detect store-free config subcommands before DB synthesis so config.yaml, git-backed, and diagnostic flows can run without an opened store
constraint(json-contract): keep bd config validate --json machine-readable on stdout once pre-run stops short-circuiting into low-level DB errors
learned(config-preflight): the parent config command not being in noDbCommands leaked store init into show, validate, drift, apply, and yaml-only config helpers

* fix(ci): restore init prefix normalization and formatting

intent(ci): clear the current PR failures instead of leaving the branch blocked behind known red checks

decision(init-prefix): normalize dotted prefixes before persisting issue_prefix so config, metadata.json, and Dolt database naming stay aligned for Julia-style repos
constraint(fmt-check): CI runs gofmt over the whole repo, so the existing spacing drift in internal/jira/tracker_test.go had to be cleaned up on this branch to get a green run
learned(ci): the latest main CI was already red on the same formatting file and the same embedded shard, so rebasing surfaced pre-existing blockers rather than introducing a new shard-only regression
2026-04-10 21:23:14 -07:00

193 lines
5 KiB
Go

//go:build cgo
package main
import (
"encoding/json"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/git"
)
func TestBackupStateRoundTrip(t *testing.T) {
t.Parallel()
dir := t.TempDir()
// Load from empty dir returns zero state
state, err := loadBackupState(dir)
if err != nil {
t.Fatalf("loadBackupState: %v", err)
}
if state.LastDoltCommit != "" {
t.Errorf("expected empty commit, got %q", state.LastDoltCommit)
}
// Save and reload
state.LastDoltCommit = "abc123"
state.Timestamp = time.Date(2026, 2, 26, 12, 0, 0, 0, time.UTC)
if err := saveBackupState(dir, state); err != nil {
t.Fatalf("saveBackupState: %v", err)
}
loaded, err := loadBackupState(dir)
if err != nil {
t.Fatalf("loadBackupState after save: %v", err)
}
if loaded.LastDoltCommit != "abc123" {
t.Errorf("commit = %q, want abc123", loaded.LastDoltCommit)
}
}
func TestBackupAtomicWrite(t *testing.T) {
t.Parallel()
dir := t.TempDir()
path := filepath.Join(dir, "test.jsonl")
data := []byte(`{"id":"test-1","title":"hello"}` + "\n")
if err := atomicWriteFile(path, data); err != nil {
t.Fatalf("atomicWriteFile: %v", err)
}
got, err := os.ReadFile(path)
if err != nil {
t.Fatalf("ReadFile: %v", err)
}
if string(got) != string(data) {
t.Errorf("got %q, want %q", got, data)
}
}
func TestBackupDir_NoWorkspaceReturnsActiveWorkspaceError(t *testing.T) {
tmpDir := t.TempDir()
t.Chdir(tmpDir)
t.Setenv("BEADS_DIR", "")
t.Setenv("BEADS_DB", "")
t.Setenv("BD_BACKUP_GIT_REPO", filepath.Join(tmpDir, "not-a-repo"))
beads.ResetCaches()
git.ResetCaches()
t.Cleanup(func() {
beads.ResetCaches()
git.ResetCaches()
})
dir, err := backupDir()
if err == nil {
t.Fatalf("backupDir() = %q, want error", dir)
}
if !strings.Contains(err.Error(), activeWorkspaceNotFoundError()) {
t.Fatalf("backupDir() error = %q, want active workspace wording", err)
}
if !strings.Contains(err.Error(), diagHint()) {
t.Fatalf("backupDir() error = %q, want diag hint", err)
}
if _, statErr := os.Stat(filepath.Join(tmpDir, ".beads")); !os.IsNotExist(statErr) {
t.Fatalf("backupDir() should not create local .beads, stat err = %v", statErr)
}
}
func TestBackupDir_UsesWorktreeFallback(t *testing.T) {
tmpDir := t.TempDir()
mainRepoDir := filepath.Join(tmpDir, "main-repo")
if err := os.MkdirAll(mainRepoDir, 0o755); err != nil {
t.Fatalf("mkdir main repo: %v", err)
}
run := func(dir string, args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = dir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git %v failed: %v\n%s", args, err, out)
}
}
run(mainRepoDir, "init")
run(mainRepoDir, "config", "user.email", "test@example.com")
run(mainRepoDir, "config", "user.name", "Test User")
if err := os.WriteFile(filepath.Join(mainRepoDir, "README.md"), []byte("# Test\n"), 0o644); err != nil {
t.Fatalf("write README: %v", err)
}
run(mainRepoDir, "add", "README.md")
run(mainRepoDir, "commit", "-m", "Initial commit")
worktreeDir := filepath.Join(tmpDir, "worktree")
cmd := exec.Command("git", "worktree", "add", worktreeDir, "HEAD")
cmd.Dir = mainRepoDir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git worktree add failed: %v\n%s", err, out)
}
t.Cleanup(func() {
cleanupCmd := exec.Command("git", "worktree", "remove", "--force", worktreeDir)
cleanupCmd.Dir = mainRepoDir
_ = cleanupCmd.Run()
})
mainBeadsDir := filepath.Join(mainRepoDir, ".beads")
if err := os.MkdirAll(filepath.Join(mainBeadsDir, "dolt"), 0o755); err != nil {
t.Fatalf("mkdir main beads dir: %v", err)
}
_ = os.RemoveAll(filepath.Join(worktreeDir, ".beads"))
t.Chdir(worktreeDir)
t.Setenv("BEADS_DIR", "")
t.Setenv("BEADS_DB", "")
t.Setenv("BD_BACKUP_GIT_REPO", filepath.Join(tmpDir, "not-a-repo"))
beads.ResetCaches()
git.ResetCaches()
t.Cleanup(func() {
beads.ResetCaches()
git.ResetCaches()
})
dir, err := backupDir()
if err != nil {
t.Fatalf("backupDir() error = %v", err)
}
gotResolved, err := filepath.EvalSymlinks(dir)
if err != nil {
t.Fatalf("EvalSymlinks(%q): %v", dir, err)
}
wantResolved, err := filepath.EvalSymlinks(filepath.Join(mainBeadsDir, "backup"))
if err != nil {
t.Fatalf("EvalSymlinks(%q): %v", filepath.Join(mainBeadsDir, "backup"), err)
}
if gotResolved != wantResolved {
t.Fatalf("backupDir() = %q (resolved %q), want resolved %q", dir, gotResolved, wantResolved)
}
}
// splitJSONL splits JSONL data into individual JSON lines, skipping empty lines.
func splitJSONL(data []byte) []json.RawMessage {
var result []json.RawMessage
for _, line := range splitLines(data) {
if len(line) > 0 {
result = append(result, json.RawMessage(line))
}
}
return result
}
// splitLines splits data into lines without importing strings.
func splitLines(data []byte) [][]byte {
var lines [][]byte
start := 0
for i, b := range data {
if b == '\n' {
lines = append(lines, data[start:i])
start = i + 1
}
}
if start < len(data) {
lines = append(lines, data[start:])
}
return lines
}