From 4fcbd588255f24919008b3c3cdc1b4999d33fb4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?coffeegoddd=E2=98=95=EF=B8=8F=E2=9C=A8?= Date: Tue, 19 May 2026 14:17:14 -0700 Subject: [PATCH 1/5] /{cmd,internal}: wip, implementing init with proxied-server --- cmd/bd/fs_adapters.go | 30 ++ cmd/bd/init.go | 24 + cmd/bd/init_proxied_server.go | 476 ++++++++++++++++++ cmd/bd/init_templates.go | 22 +- cmd/bd/main.go | 132 ++--- cmd/bd/uow_factory.go | 57 +++ internal/storage/domain/beads.go | 207 ++++++++ internal/storage/domain/bootstrap.go | 102 +++- internal/storage/domain/config.go | 52 +- internal/storage/domain/db/config.go | 73 +++ internal/storage/domain/db/config_test.go | 105 ++++ internal/storage/domain/db/remote.go | 57 +++ internal/storage/domain/db/suite_test.go | 106 ++++ internal/storage/domain/fs/beads.go | 288 +++++++++++ internal/storage/domain/fs/beads_test.go | 379 ++++++++++++++ internal/storage/domain/fs/suite_test.go | 37 ++ internal/storage/domain/remote.go | 73 ++- internal/storage/fs/provider.go | 31 ++ internal/storage/uow/doltserver_provider.go | 21 +- .../storage/uow/doltserver_provider_test.go | 74 ++- internal/storage/uow/doltserver_tx.go | 118 +---- internal/storage/uow/tx.go | 7 +- internal/storage/uow/uow.go | 45 +- 23 files changed, 2313 insertions(+), 203 deletions(-) create mode 100644 cmd/bd/fs_adapters.go create mode 100644 cmd/bd/init_proxied_server.go create mode 100644 cmd/bd/uow_factory.go create mode 100644 internal/storage/domain/beads.go create mode 100644 internal/storage/domain/db/config.go create mode 100644 internal/storage/domain/db/config_test.go create mode 100644 internal/storage/domain/db/remote.go create mode 100644 internal/storage/domain/db/suite_test.go create mode 100644 internal/storage/domain/fs/beads.go create mode 100644 internal/storage/domain/fs/beads_test.go create mode 100644 internal/storage/domain/fs/suite_test.go create mode 100644 internal/storage/fs/provider.go diff --git a/cmd/bd/fs_adapters.go b/cmd/bd/fs_adapters.go new file mode 100644 index 000000000..241fd7a74 --- /dev/null +++ b/cmd/bd/fs_adapters.go @@ -0,0 +1,30 @@ +package main + +import ( + "github.com/steveyegge/beads/cmd/bd/setup" + "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/templates/agents" +) + +func newFileSystemAdapters() domain.BeadsDirFSAdapters { + return domain.BeadsDirFSAdapters{ + ResolveBeadsDir: func() domain.BeadsDirResolution { + beadsDir, hasExplicit := resolveBeadsDirForInit() + return domain.BeadsDirResolution{BeadsDir: beadsDir, HasExplicit: hasExplicit} + }, + ApplyNoCOW: applyNoCOW, + WriteLocalVersion: writeLocalVersion, + SetupForkExclude: setupForkExclude, + SetupStealthMode: setupStealthMode, + InstallGitHooks: func(p domain.HooksInstallParams) error { + return installHooksWithOptions(p.HookNames, p.Force, p.Shared, p.Chain, p.BeadsHooks) + }, + InstallJJHooks: installJJHooks, + AddAgentsInstructions: func(p domain.AgentsFileParams) { + addAgentsInstructions(p.File, p.Verbose, p.TemplatePath, agents.Profile(p.Profile), agents.RenderOpts{HasRemote: p.HasRemote}) + }, + InstallClaudeProject: setup.InstallClaudeProject, + SetYAMLConfig: config.SetYamlConfig, + } +} diff --git a/cmd/bd/init.go b/cmd/bd/init.go index 6e6eb2977..e29928a0e 100644 --- a/cmd/bd/init.go +++ b/cmd/bd/init.go @@ -219,6 +219,30 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): cmdCtx.ProxiedServerMode = initProxiedServer } + if initProxiedServer { + runInitProxiedServer(cmd, rootCtx, initProxiedServerInput{ + prefix: prefix, + database: database, + roleFlag: roleFlag, + initRemote: initRemote, + initRemoteChanged: initRemoteChanged, + destroyToken: destroyToken, + serverConfigPath: serverConfigPath, + serverLogPath: serverLogPath, + serverRootPath: serverRootPath, + quiet: quiet, + stealth: stealth, + skipHooks: skipHooks, + skipAgents: skipAgents, + reinitLocal: reinitLocal, + contributor: contributor, + team: team, + fromJSONL: fromJSONL, + nonInteractive: nonInteractive, + }) + return + } + // Propagate --shared-server flag to env so that IsSharedServerMode(), // ResolveDoltDir(), and DefaultConfig() all see shared mode immediately // (before config.yaml exists). Safe: init runs once and exits. diff --git a/cmd/bd/init_proxied_server.go b/cmd/bd/init_proxied_server.go new file mode 100644 index 000000000..340f3bd2b --- /dev/null +++ b/cmd/bd/init_proxied_server.go @@ -0,0 +1,476 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "time" + + "github.com/spf13/cobra" + + "github.com/steveyegge/beads/internal/beads" + "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/configfile" + "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/storage/fs" + "github.com/steveyegge/beads/internal/ui" + "github.com/steveyegge/beads/internal/utils" +) + +type initProxiedServerInput struct { + prefix string + database string + roleFlag string + initRemote string + initRemoteChanged bool + destroyToken string + serverConfigPath string + serverLogPath string + serverRootPath string + quiet bool + stealth bool + skipHooks bool + skipAgents bool + reinitLocal bool + contributor bool + team bool + fromJSONL bool + nonInteractive bool +} + +func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxiedServerInput) { + if in.fromJSONL { + FatalError("--from-jsonl is not supported with --proxied-server") + } + if in.contributor { + FatalError("--contributor is not supported with --proxied-server") + } + if in.team { + FatalError("--team is not supported with --proxied-server") + } + + if err := config.Initialize(); err != nil { + fmt.Fprintf(os.Stderr, "Warning: failed to initialize config: %v\n", err) + } + + if err := checkExistingBeadsData(in.prefix); err != nil { + FatalError("%v", err) + } + + fsProvider := fs.NewFileSystemProvider(newFileSystemAdapters()) + fsUseCase := fsProvider.BeadsDirFSUseCase() + + if in.stealth { + if err := fsUseCase.SetupStealthMode(ctx, !in.quiet); err != nil { + FatalError("setting up stealth mode: %v", err) + } + in.skipHooks = true + } + + prefix := resolveInitPrefix(in.prefix) + + cwd, err := os.Getwd() + if err != nil { + FatalError("failed to get current directory: %v", err) + } + + beadsDirResolution := fsUseCase.ResolveBeadsDir(ctx) + beadsDir, hasExplicitBeadsDir := beadsDirResolution.BeadsDir, beadsDirResolution.HasExplicit + if strings.Contains(filepath.Clean(cwd), string(filepath.Separator)+".beads"+string(filepath.Separator)) || + strings.HasSuffix(filepath.Clean(cwd), string(filepath.Separator)+".beads") { + fmt.Fprintf(os.Stderr, "Error: cannot initialize bd inside a .beads directory\n") + fmt.Fprintf(os.Stderr, "Current directory: %s\n", cwd) + os.Exit(1) + } + + beadsDirAbs, err := filepath.Abs(beadsDir) + if err != nil { + beadsDirAbs = filepath.Clean(beadsDir) + } + + cwdAbs, _ := filepath.Abs(cwd) + beadsDirIsLocal := strings.HasPrefix(beadsDirAbs, filepath.Clean(cwdAbs)+string(filepath.Separator)) || + filepath.Clean(beadsDirAbs) == filepath.Clean(cwdAbs) + useLocalBeads := !hasExplicitBeadsDir || beadsDirIsLocal + + if !isGitRepo() && !hasExplicitBeadsDir { + gitInitCmd := exec.Command("git", "init") + if output, err := gitInitCmd.CombinedOutput(); err != nil { + FatalError("failed to initialize git repository: %v\n%s", err, output) + } + git.ResetCaches() + if !in.quiet { + fmt.Printf(" %s Initialized git repository\n", ui.RenderPass("✓")) + } + } + + dbName := resolveProxiedDatabaseName(beadsDir, prefix, in.database) + projectID := resolveProjectID(beadsDir) + + metadataBody, err := composeProxiedServerMetadataJSON(proxiedMetadataInputs{ + dbName: dbName, + projectID: projectID, + serverConfigPath: in.serverConfigPath, + serverLogPath: in.serverLogPath, + serverRootPath: in.serverRootPath, + }) + if err != nil { + FatalError("composing metadata.json: %v", err) + } + configYAMLBody := renderInitConfigYAML("", false) + + fsParams := domain.InitializeBeadsDirParams{ + BeadsDir: beadsDir, + MetadataJSONBody: metadataBody, + ConfigYAMLBody: configYAMLBody, + SetNoCOW: true, + } + if useLocalBeads && beadsDirIsLocal { + fsParams.RepoRoot = cwd + } + if useLocalBeads { + fsParams.LocalVersion = Version + } + + fsResult, err := fsUseCase.InitializeBeadsDir(ctx, fsParams) + if err != nil { + FatalError("initializing .beads directory: %v", err) + } + if fsResult.NoCOWErr != nil && !in.quiet { + fmt.Fprintf(os.Stderr, "Warning: failed to set FS_NOCOW_FL on %s: %v\n", beadsDir, fsResult.NoCOWErr) + } + if fsResult.LocalVersionErr != nil && !in.quiet { + fmt.Fprintf(os.Stderr, "Warning: failed to initialize version tracking: %v\n", fsResult.LocalVersionErr) + } + + uowProvider, err := newProxiedServerUOWProvider(ctx, beadsDir) + if err != nil { + FatalError("failed to open uow provider: %v", err) + } + + uw, err := uowProvider.NewUOW(ctx) + if err != nil { + FatalError("failed to open unit of work: %v", err) + } + defer uw.Close(ctx) + + bootstrapParams := domain.BootstrapProjectParams{ + Prefix: prefix, + ProjectID: projectID, + BdVersion: Version, + LastImportTime: time.Now(), + } + + if repoID, err := beads.ComputeRepoID(); err == nil { + bootstrapParams.RepoID = repoID + } else if !in.quiet { + fmt.Fprintf(os.Stderr, "Warning: could not compute repository ID: %v\n", err) + } + if cloneID, err := beads.GetCloneID(); err == nil { + bootstrapParams.CloneID = cloneID + } else if !in.quiet { + fmt.Fprintf(os.Stderr, "Warning: could not compute clone ID: %v\n", err) + } + if remoteURL := resolveProxiedInitRemoteURL(in); remoteURL != "" { + bootstrapParams.RemoteName = "origin" + bootstrapParams.RemoteURL = remoteURL + } + + if _, err := uw.BootstrapUseCase().BootstrapProject(ctx, bootstrapParams); err != nil { + FatalError("bootstrap project: %v", err) + } + + if err := uw.Commit(ctx, "bd init"); err != nil { + FatalError("commit init: %v", err) + } + + runInitProxiedServerTail(cmd, ctx, in, runInitTailContext{ + beadsDir: beadsDir, + prefix: prefix, + dbName: dbName, + useLocalBeads: useLocalBeads, + remoteURL: bootstrapParams.RemoteURL, + fsUseCase: fsUseCase, + }) +} + +func resolveInitPrefix(flagPrefix string) string { + prefix := flagPrefix + if prefix == "" { + prefix = config.GetString("issue-prefix") + } + if prefix == "" { + cwd, err := os.Getwd() + if err != nil { + FatalError("failed to get current directory: %v", err) + } + prefix = filepath.Base(cwd) + } + prefix = strings.TrimLeft(prefix, ".") + prefix = strings.TrimRight(prefix, "-") + prefix = strings.ReplaceAll(prefix, ".", "_") + if len(prefix) > 0 && !((prefix[0] >= 'a' && prefix[0] <= 'z') || (prefix[0] >= 'A' && prefix[0] <= 'Z') || prefix[0] == '_') { + prefix = "bd_" + prefix + } + return prefix +} + +func resolveBeadsDirForInit() (beadsDir string, hasExplicit bool) { + if envBeadsDir := os.Getenv("BEADS_DIR"); envBeadsDir != "" { + return utils.CanonicalizePath(envBeadsDir), true + } + beadsDir = beads.GetWorktreeFallbackBeadsDir() + if beadsDir == "" { + beadsDir = beads.FollowRedirect(filepath.Join(".", ".beads")) + } + return beadsDir, false +} + +func resolveProxiedDatabaseName(beadsDir, prefix, dbFlag string) string { + if dbFlag != "" { + return dbFlag + } + if cfg, _ := configfile.Load(beadsDir); cfg != nil && cfg.DoltDatabase != "" { + return cfg.DoltDatabase + } + if prefix != "" { + return strings.ReplaceAll(prefix, "-", "_") + } + return configfile.DefaultDoltDatabase +} + +func resolveProjectID(beadsDir string) string { + if cfg, _ := configfile.Load(beadsDir); cfg != nil && cfg.ProjectID != "" { + return cfg.ProjectID + } + return configfile.GenerateProjectID() +} + +func resolveProxiedInitRemoteURL(in initProxiedServerInput) string { + url, source := resolveInitConfiguredSyncRemote(in.initRemote, in.initRemoteChanged, resolveSyncRemote) + if url != "" { + return url + } + if source != initSyncRemoteNone { + return "" + } + if !in.stealth && isGitRepo() && !isBareGitRepo() { + if originURL, err := gitOriginGetURL(); err == nil && originURL != "" { + return normalizeRemoteURL(originURL) + } + } + return "" +} + +type proxiedMetadataInputs struct { + dbName string + projectID string + serverConfigPath string + serverLogPath string + serverRootPath string +} + +func composeProxiedServerMetadataJSON(in proxiedMetadataInputs) ([]byte, error) { + cfg := configfile.DefaultConfig() + cfg.Backend = configfile.BackendDolt + cfg.Database = "dolt" + cfg.DoltDatabase = in.dbName + cfg.DoltMode = configfile.DoltModeProxiedServer + cfg.ProjectID = in.projectID + + cfg.DoltProxiedServerConfig = in.serverConfigPath + cfg.DoltProxiedServerLog = in.serverLogPath + cfg.DoltProxiedServerRootPath = in.serverRootPath + + if filepath.IsAbs(cfg.DoltDataDir) { + cfg.DoltDataDir = "" + } + if filepath.IsAbs(cfg.DoltProxiedServerConfig) { + cfg.DoltProxiedServerConfig = "" + } + if filepath.IsAbs(cfg.DoltProxiedServerLog) { + cfg.DoltProxiedServerLog = "" + } + if filepath.IsAbs(cfg.DoltProxiedServerRootPath) { + cfg.DoltProxiedServerRootPath = "" + } + + return json.MarshalIndent(cfg, "", " ") +} + +type runInitTailContext struct { + beadsDir string + prefix string + dbName string + useLocalBeads bool + remoteURL string + fsUseCase domain.BeadsDirFSUseCase +} + +func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initProxiedServerInput, t runInitTailContext) { + if isGitRepo() { + role := in.roleFlag + if role == "" { + role = "maintainer" + } + if _, hasRole := getBeadsRole(); !hasRole { + if err := setBeadsRole(role); err != nil && !in.quiet { + fmt.Fprintf(os.Stderr, "Warning: failed to set beads.role: %v\n", err) + } + } else if in.roleFlag != "" { + if err := setBeadsRole(role); err != nil && !in.quiet { + fmt.Fprintf(os.Stderr, "Warning: failed to set beads.role: %v\n", err) + } + } + } + + setupExclude, _ := cmd.Flags().GetBool("setup-exclude") + if setupExclude { + if err := t.fsUseCase.SetupForkExclude(ctx, !in.quiet); err != nil { + fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err) + } + } else if !in.stealth && isGitRepo() { + if isFork, upstreamURL := detectForkSetup(); isFork { + if in.nonInteractive { + if err := t.fsUseCase.SetupForkExclude(ctx, !in.quiet); err != nil { + fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err) + } + } else { + shouldExclude, err := promptForkExclude(upstreamURL, in.quiet) + if err != nil && isCanceled(err) { + fmt.Fprintln(os.Stderr, "Setup canceled.") + exitCanceled() + } + if shouldExclude { + if err := t.fsUseCase.SetupForkExclude(ctx, !in.quiet); err != nil { + fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err) + } + } + } + } + } + + if !in.skipHooks && (!hooksInstalled() || hooksNeedUpdate()) { + if hooksInstalled() && !in.quiet { + fmt.Printf(" Updating hooks to version %s...\n", Version) + } + isJJ := git.IsJujutsuRepo() + isColocated := git.IsColocatedJJGit() + switch { + case isJJ && !isColocated: + if !in.quiet { + printJJAliasInstructions() + } + case isColocated: + if err := t.fsUseCase.InstallJJHooks(ctx); err != nil && !in.quiet { + fmt.Fprintf(os.Stderr, "\n%s Failed to install jj hooks: %v\n", ui.RenderWarn("⚠"), err) + } else if !in.quiet { + fmt.Printf(" Hooks installed (jujutsu mode - no staging)\n") + } + default: + if isGitRepo() { + hooksParams := domain.HooksInstallParams{ + HookNames: managedHookNames, + BeadsHooks: true, + } + if err := t.fsUseCase.InstallGitHooks(ctx, hooksParams); err != nil && !in.quiet { + fmt.Fprintf(os.Stderr, "\n%s Failed to install git hooks to .beads/hooks/: %v\n", ui.RenderWarn("⚠"), err) + } else if !in.quiet { + fmt.Printf(" Hooks installed to: .beads/hooks/\n") + } + } + } + } + + if !in.stealth && !in.skipAgents { + agentsTemplate, _ := cmd.Flags().GetString("agents-template") + agentsProfileStr, _ := cmd.Flags().GetString("agents-profile") + agentsFile, _ := cmd.Flags().GetString("agents-file") + if agentsFile != "" { + if err := config.ValidateAgentsFile(agentsFile); err != nil { + fmt.Fprintf(os.Stderr, "Error: invalid --agents-file: %v\n", err) + return + } + if err := t.fsUseCase.SetYAMLConfig(ctx, "agents.file", agentsFile); err != nil { + fmt.Fprintf(os.Stderr, "Warning: failed to persist agents.file to config: %v\n", err) + } + } + resolvedAgentsFile := agentsFile + if resolvedAgentsFile == "" { + resolvedAgentsFile = config.SafeAgentsFile() + } + if isBareGitRepo() { + if !in.quiet { + fmt.Printf(" Skipping %s generation in bare repository\n", resolvedAgentsFile) + } + } else { + _ = t.fsUseCase.AddAgentsInstructions(ctx, domain.AgentsFileParams{ + File: resolvedAgentsFile, + Verbose: !in.quiet, + TemplatePath: agentsTemplate, + Profile: agentsProfileStr, + HasRemote: t.remoteURL != "", + }) + } + } + + if !in.stealth && !in.skipAgents && !isBareGitRepo() { + if err := t.fsUseCase.InstallClaudeProject(ctx, in.stealth); err != nil && !in.quiet { + fmt.Fprintf(os.Stderr, "Warning: failed to setup Claude hooks: %v\n", err) + } + } + + if !in.stealth && isGitRepo() && t.useLocalBeads { + gitAddCmd := exec.Command("git", "add", ".beads/") + if _, addErr := gitAddCmd.CombinedOutput(); addErr == nil { + agentsFileToStage := config.SafeAgentsFile() + if _, statErr := os.Stat(agentsFileToStage); statErr == nil { + _ = exec.Command("git", "add", agentsFileToStage).Run() + } + if _, statErr := os.Stat(filepath.Join(".claude", "settings.json")); statErr == nil { + _ = exec.Command("git", "add", filepath.Join(".claude", "settings.json")).Run() + } + if _, statErr := os.Stat("CLAUDE.md"); statErr == nil { + _ = exec.Command("git", "add", "CLAUDE.md").Run() + } + if _, statErr := os.Stat(".gitignore"); statErr == nil { + _ = exec.Command("git", "add", ".gitignore").Run() + } + commitCmd := exec.Command("git", "commit", "--no-verify", "-m", "bd init: initialize beads issue tracking") + if commitOut, commitErr := commitCmd.CombinedOutput(); commitErr != nil { + if !in.quiet && !strings.Contains(string(commitOut), "nothing to commit") { + fmt.Fprintf(os.Stderr, "Warning: failed to commit beads files: %v\n", commitErr) + } + } else if !in.quiet { + fmt.Printf(" %s Committed beads files to git\n", ui.RenderPass("✓")) + } + } + } + + if isGitRepo() && !in.quiet { + if gitHasAnyRemotes() && !gitHasUpstream() { + fmt.Fprintf(os.Stderr, "\n%s Git upstream not configured\n", ui.RenderWarn("⚠")) + fmt.Fprintf(os.Stderr, " For sync workflows, set your upstream with:\n") + fmt.Fprintf(os.Stderr, " %s\n\n", ui.RenderAccent("git remote add upstream ")) + } + if !in.stealth && !in.initRemoteChanged && t.remoteURL == "" { + printInitNoDoltRemoteWarning() + } + } + + if in.quiet { + return + } + fmt.Printf("\n%s bd initialized successfully!\n\n", ui.RenderPass("✓")) + fmt.Printf(" Backend: %s\n", ui.RenderAccent(configfile.BackendDolt)) + fmt.Printf(" Mode: %s\n", ui.RenderAccent("proxied-server")) + fmt.Printf(" Database: %s\n", ui.RenderAccent(t.dbName)) + fmt.Printf(" Issue prefix: %s\n", ui.RenderAccent(t.prefix)) + fmt.Printf(" Issues will be named: %s\n\n", ui.RenderAccent(t.prefix+"- (e.g., "+t.prefix+"-a3f2dd)")) + fmt.Printf("Run %s to get started.\n\n", ui.RenderAccent("bd quickstart")) +} diff --git a/cmd/bd/init_templates.go b/cmd/bd/init_templates.go index 6f988374c..6a2395944 100644 --- a/cmd/bd/init_templates.go +++ b/cmd/bd/init_templates.go @@ -16,18 +16,29 @@ func createConfigYaml(beadsDir string, noDbMode bool, prefix string) error { return nil } + body := renderInitConfigYAML(prefix, noDbMode) + if err := os.WriteFile(configYamlPath, body, 0600); err != nil { + return fmt.Errorf("failed to write config.yaml: %w", err) + } + + return nil +} + +// renderInitConfigYAML returns the canonical config.yaml body produced by +// bd init. When noDbMode is true, the prefix is baked into the file (since +// there's no database to store it). +func renderInitConfigYAML(prefix string, noDbMode bool) []byte { noDbLine := "# no-db: false" if noDbMode { noDbLine = "no-db: true # JSONL-only mode, no database" } - // In no-db mode, we need to persist the prefix in config.yaml prefixLine := "# issue-prefix: \"\"" if noDbMode && prefix != "" { prefixLine = fmt.Sprintf("issue-prefix: %q", prefix) } - configYamlTemplate := fmt.Sprintf(`# Beads Configuration File + body := fmt.Sprintf(`# Beads Configuration File # This file configures default behavior for all bd commands in this repository # All settings can also be set via environment variables (BD_* prefix) # or overridden with command-line flags @@ -83,12 +94,7 @@ func createConfigYaml(beadsDir string, noDbMode bool, prefix string) error { # - linear.api_key → use LINEAR_API_KEY env var instead # - github.token → use GITHUB_TOKEN env var instead `, prefixLine, noDbLine) - - if err := os.WriteFile(configYamlPath, []byte(configYamlTemplate), 0600); err != nil { - return fmt.Errorf("failed to write config.yaml: %w", err) - } - - return nil + return []byte(body) } // createReadme creates the README.md file in the .beads directory diff --git a/cmd/bd/main.go b/cmd/bd/main.go index 2124d4b1d..0a086fa06 100644 --- a/cmd/bd/main.go +++ b/cmd/bd/main.go @@ -28,6 +28,7 @@ import ( "github.com/steveyegge/beads/internal/molecules" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/dolt" + "github.com/steveyegge/beads/internal/storage/uow" "github.com/steveyegge/beads/internal/telemetry" "github.com/steveyegge/beads/internal/utils" "go.opentelemetry.io/otel/attribute" @@ -35,11 +36,12 @@ import ( ) var ( - changeDir string - dbPath string - actor string - store storage.DoltStorage - jsonOutput bool + changeDir string + dbPath string + actor string + store storage.DoltStorage + uowProvider uow.UnitOfWorkProvider + jsonOutput bool // Signal-aware context for graceful cancellation rootCtx context.Context @@ -67,9 +69,9 @@ var changeDirEnvSnapshot map[string]envSnapshotValue var ( sandboxMode bool - globalFlag bool // Use the global shared-server database (beads_global) - serverMode bool // True when using external dolt sql-server (dolt_mode=server) - proxiedServerMode bool // True when using per-workspace proxied dolt sql-server (dolt_mode=proxied-server) + globalFlag bool // Use the global shared-server database (beads_global) + serverMode bool // True when using external dolt sql-server (dolt_mode=server) + proxiedServerMode bool readonlyMode bool // Read-only mode: block write operations (for worker sandboxes) storeIsReadOnly bool // Track if store was opened read-only (for staleness checks) lockTimeout = 30 * time.Second // Dolt open timeout (fixed default) @@ -988,6 +990,17 @@ var rootCmd = &cobra.Command{ // other helper paths stay in lockstep with the main command path. dolt.ApplyCLIAutoStart(beadsDir, doltCfg) + if proxiedServerMode { + p, err := newProxiedServerUOWProvider(rootCtx, beadsDir) + if err != nil { + FatalError("failed to open uow provider: %v", err) + } + uowProvider = p + + syncCommandContext() + return + } + // Default auto-commit based on mode when the user hasn't set a value: // - Server mode: OFF — the server handles commits via its own transaction // lifecycle; firing DOLT_COMMIT after every write under concurrent load @@ -1087,65 +1100,72 @@ var rootCmd = &cobra.Command{ PersistentPostRun: func(cmd *cobra.Command, args []string) { defer restoreChangeDirSelection() - // Dolt auto-commit: after a successful write command (and after final flush), - // create a Dolt commit so changes don't remain only in the working set. - if commandDidWrite.Load() && !commandDidExplicitDoltCommit { - if err := maybeAutoCommit(rootCtx, doltAutoCommitParams{Command: cmd.Name()}); err != nil { - FatalError("dolt auto-commit failed: %v", err) + if proxiedServerMode { + if uowProvider != nil { + _ = uowProvider.Close(rootCtx) + uowProvider = nil + } + } else { + // Dolt auto-commit: after a successful write command (and after final flush), + // create a Dolt commit so changes don't remain only in the working set. + if commandDidWrite.Load() && !commandDidExplicitDoltCommit { + if err := maybeAutoCommit(rootCtx, doltAutoCommitParams{Command: cmd.Name()}); err != nil { + FatalError("dolt auto-commit failed: %v", err) + } } - } - // Tip metadata auto-commit: if a tip was shown, create a separate Dolt commit for the - // tip_*_last_shown metadata updates. This may happen even for otherwise read-only commands. - if commandDidWriteTipMetadata && len(commandTipIDsShown) > 0 { - // Only applies when dolt auto-commit is enabled and backend is versioned (Dolt). - if mode, err := getDoltAutoCommitMode(); err != nil { - FatalError("dolt tip auto-commit failed: %v", err) - } else if mode == doltAutoCommitOn { - // Apply tip metadata writes now (deferred in recordTipShown for Dolt). - for tipID := range commandTipIDsShown { - key := fmt.Sprintf("tip_%s_last_shown", tipID) - value := time.Now().Format(time.RFC3339) - if err := store.SetLocalMetadata(rootCtx, key, value); err != nil { + // Tip metadata auto-commit: if a tip was shown, create a separate Dolt commit for the + // tip_*_last_shown metadata updates. This may happen even for otherwise read-only commands. + if commandDidWriteTipMetadata && len(commandTipIDsShown) > 0 { + // Only applies when dolt auto-commit is enabled and backend is versioned (Dolt). + if mode, err := getDoltAutoCommitMode(); err != nil { + FatalError("dolt tip auto-commit failed: %v", err) + } else if mode == doltAutoCommitOn { + // Apply tip metadata writes now (deferred in recordTipShown for Dolt). + for tipID := range commandTipIDsShown { + key := fmt.Sprintf("tip_%s_last_shown", tipID) + value := time.Now().Format(time.RFC3339) + if err := store.SetLocalMetadata(rootCtx, key, value); err != nil { + FatalError("dolt tip auto-commit failed: %v", err) + } + } + + ids := make([]string, 0, len(commandTipIDsShown)) + for tipID := range commandTipIDsShown { + ids = append(ids, tipID) + } + msg := formatDoltAutoCommitMessage("tip", getActor(), ids) + if err := maybeAutoCommit(rootCtx, doltAutoCommitParams{Command: "tip", MessageOverride: msg}); err != nil { FatalError("dolt tip auto-commit failed: %v", err) } } - - ids := make([]string, 0, len(commandTipIDsShown)) - for tipID := range commandTipIDsShown { - ids = append(ids, tipID) - } - msg := formatDoltAutoCommitMessage("tip", getActor(), ids) - if err := maybeAutoCommit(rootCtx, doltAutoCommitParams{Command: "tip", MessageOverride: msg}); err != nil { - FatalError("dolt tip auto-commit failed: %v", err) - } } - } - // Auto-backup: export JSONL to .beads/backup/ if enabled and due - maybeAutoBackup(rootCtx) + // Auto-backup: export JSONL to .beads/backup/ if enabled and due + maybeAutoBackup(rootCtx) - // Auto-export: write git-tracked JSONL for portability if enabled and due. - // Read-only commands must not perform post-run maintenance writes or emit - // sync guidance after machine-readable output. - if shouldRunPostCommandAutoExport(cmd) { - maybeAutoExport(rootCtx) - } + // Auto-export: write git-tracked JSONL for portability if enabled and due. + // Read-only commands must not perform post-run maintenance writes or emit + // sync guidance after machine-readable output. + if shouldRunPostCommandAutoExport(cmd) { + maybeAutoExport(rootCtx) + } - // Auto-push: push to Dolt remote if enabled and due. - // Skip for read-only commands to avoid unnecessary network operations - // and metadata writes on commands like bd list/show/ready (GH#2191). - if !isReadOnlyCommand(cmd.Name()) { - maybeAutoPush(rootCtx) - } + // Auto-push: push to Dolt remote if enabled and due. + // Skip for read-only commands to avoid unnecessary network operations + // and metadata writes on commands like bd list/show/ready (GH#2191). + if !isReadOnlyCommand(cmd.Name()) { + maybeAutoPush(rootCtx) + } - // Signal that store is closing (prevents background flush from accessing closed store) - storeMutex.Lock() - storeActive = false - storeMutex.Unlock() + // Signal that store is closing (prevents background flush from accessing closed store) + storeMutex.Lock() + storeActive = false + storeMutex.Unlock() - if store != nil { - _ = store.Close() // Best effort cleanup + if store != nil { + _ = store.Close() // Best effort cleanup + } } // End the command span and flush OTel data before process exit. diff --git a/cmd/bd/uow_factory.go b/cmd/bd/uow_factory.go new file mode 100644 index 000000000..58bc57d46 --- /dev/null +++ b/cmd/bd/uow_factory.go @@ -0,0 +1,57 @@ +package main + +import ( + "context" + "fmt" + "os/exec" + + "github.com/steveyegge/beads/internal/configfile" + "github.com/steveyegge/beads/internal/storage/dbproxy/proxy" + "github.com/steveyegge/beads/internal/storage/uow" +) + +func newProxiedServerUOWProvider(ctx context.Context, beadsDir string) (uow.UnitOfWorkProvider, error) { + if beadsDir == "" { + return nil, fmt.Errorf("newProxiedServerUOWProvider: beadsDir must be set") + } + + doltBin, err := exec.LookPath("dolt") + if err != nil { + return nil, fmt.Errorf("newProxiedServerUOWProvider: dolt is not installed (not found in PATH); install from https://docs.dolthub.com/introduction/installation: %w", err) + } + + persisted, _ := configfile.Load(beadsDir) + database := configfile.DefaultDoltDatabase + if persisted != nil { + database = persisted.GetDoltDatabase() + } + + rootPath := resolveProxiedServerRootPath(beadsDir, persisted) + if err := validateProxiedServerRootPath(rootPath); err != nil { + return nil, err + } + + configPath, err := ensureProxiedServerConfig(beadsDir, persisted) + if err != nil { + return nil, err + } + + logPath, isCustomLog := resolveProxiedServerLogPath(beadsDir, persisted) + if isCustomLog { + if err := validateProxiedServerLogPath(logPath); err != nil { + return nil, err + } + } + + return uow.NewDoltServerUOWProvider( + ctx, + rootPath, + database, + logPath, + configPath, + proxy.BackendLocalServer, + "root", + "", // proxy is loopback-only, no auth + doltBin, + ) +} diff --git a/internal/storage/domain/beads.go b/internal/storage/domain/beads.go new file mode 100644 index 000000000..29a043cde --- /dev/null +++ b/internal/storage/domain/beads.go @@ -0,0 +1,207 @@ +package domain + +import ( + "context" + "fmt" + "path/filepath" +) + +type BeadsDirFSRepository interface { + CreateBeadsDir(ctx context.Context, beadsDir string) error + BeadsDirExists(ctx context.Context, beadsDir string) (bool, error) + WriteBeadsGitignore(ctx context.Context, beadsDir string) error + BeadsGitignoreExists(ctx context.Context, beadsDir string) (bool, error) + WriteProjectGitignore(ctx context.Context, repoRoot string) error + ProjectGitignoreExists(ctx context.Context, repoRoot string) (bool, error) + WriteInteractionsLog(ctx context.Context, beadsDir string) error + WriteReadme(ctx context.Context, beadsDir string) error + WriteMetadataJSON(ctx context.Context, beadsDir string, content []byte) error + ReadMetadataJSON(ctx context.Context, beadsDir string) ([]byte, error) + WriteConfigYAML(ctx context.Context, beadsDir string, content []byte) error + ReadConfigYAML(ctx context.Context, beadsDir string) ([]byte, error) +} + +type BeadsDirFSUseCase interface { + ResolveBeadsDir(ctx context.Context) BeadsDirResolution + InitializeBeadsDir(ctx context.Context, params InitializeBeadsDirParams) (InitializeBeadsDirResult, error) + SetupForkExclude(ctx context.Context, verbose bool) error + SetupStealthMode(ctx context.Context, verbose bool) error + InstallGitHooks(ctx context.Context, params HooksInstallParams) error + InstallJJHooks(ctx context.Context) error + AddAgentsInstructions(ctx context.Context, params AgentsFileParams) error + InstallClaudeProject(ctx context.Context, stealth bool) error + SetYAMLConfig(ctx context.Context, key, value string) error +} + +type BeadsDirResolution struct { + BeadsDir string + HasExplicit bool +} + +type InitializeBeadsDirParams struct { + BeadsDir string + RepoRoot string + MetadataJSONBody []byte + ConfigYAMLBody []byte + + // SetNoCOW, when true, applies FS_NOCOW_FL to BeadsDir after creation. + // Best-effort: failures surface in InitializeBeadsDirResult.NoCOWErr, + // not the returned error. + SetNoCOW bool + + // LocalVersion, when non-empty, writes BeadsDir/.local_version with + // the given value. Best-effort: failures surface in + // InitializeBeadsDirResult.LocalVersionErr, not the returned error. + LocalVersion string +} + +type InitializeBeadsDirResult struct { + NoCOWErr error + LocalVersionErr error +} + +type HooksInstallParams struct { + HookNames []string + Force bool + Shared bool + Chain bool + BeadsHooks bool +} + +type AgentsFileParams struct { + File string + Verbose bool + TemplatePath string + Profile string + HasRemote bool +} + +// BeadsDirFSAdapters wires the use case's non-trivial side effects to the +// CLI-side helper implementations. Each adapter is optional at the type +// level; methods that depend on a nil adapter return a configuration error. +type BeadsDirFSAdapters struct { + ResolveBeadsDir func() BeadsDirResolution + ApplyNoCOW func(path string) error + WriteLocalVersion func(path, version string) error + SetupForkExclude func(verbose bool) error + SetupStealthMode func(verbose bool) error + InstallGitHooks func(params HooksInstallParams) error + InstallJJHooks func() error + AddAgentsInstructions func(params AgentsFileParams) + InstallClaudeProject func(stealth bool) error + SetYAMLConfig func(key, value string) error +} + +func NewBeadsDirFSUseCase(fsRepo BeadsDirFSRepository, adapters BeadsDirFSAdapters) BeadsDirFSUseCase { + return &beadsDirFSUseCaseImpl{fsRepo: fsRepo, adapters: adapters} +} + +type beadsDirFSUseCaseImpl struct { + fsRepo BeadsDirFSRepository + adapters BeadsDirFSAdapters +} + +var _ BeadsDirFSUseCase = (*beadsDirFSUseCaseImpl)(nil) + +func (u *beadsDirFSUseCaseImpl) ResolveBeadsDir(ctx context.Context) BeadsDirResolution { + if u.adapters.ResolveBeadsDir == nil { + return BeadsDirResolution{} + } + return u.adapters.ResolveBeadsDir() +} + +func (u *beadsDirFSUseCaseImpl) InitializeBeadsDir(ctx context.Context, params InitializeBeadsDirParams) (InitializeBeadsDirResult, error) { + if params.BeadsDir == "" { + return InitializeBeadsDirResult{}, fmt.Errorf("InitializeBeadsDir: BeadsDir must not be empty") + } + + if err := u.fsRepo.CreateBeadsDir(ctx, params.BeadsDir); err != nil { + return InitializeBeadsDirResult{}, err + } + if err := u.fsRepo.WriteBeadsGitignore(ctx, params.BeadsDir); err != nil { + return InitializeBeadsDirResult{}, err + } + if len(params.MetadataJSONBody) > 0 { + if err := u.fsRepo.WriteMetadataJSON(ctx, params.BeadsDir, params.MetadataJSONBody); err != nil { + return InitializeBeadsDirResult{}, err + } + } + if len(params.ConfigYAMLBody) > 0 { + if err := u.fsRepo.WriteConfigYAML(ctx, params.BeadsDir, params.ConfigYAMLBody); err != nil { + return InitializeBeadsDirResult{}, err + } + } + if err := u.fsRepo.WriteInteractionsLog(ctx, params.BeadsDir); err != nil { + return InitializeBeadsDirResult{}, err + } + if err := u.fsRepo.WriteReadme(ctx, params.BeadsDir); err != nil { + return InitializeBeadsDirResult{}, err + } + if params.RepoRoot != "" { + if err := u.fsRepo.WriteProjectGitignore(ctx, params.RepoRoot); err != nil { + return InitializeBeadsDirResult{}, err + } + } + + var result InitializeBeadsDirResult + if params.SetNoCOW && u.adapters.ApplyNoCOW != nil { + result.NoCOWErr = u.adapters.ApplyNoCOW(params.BeadsDir) + } + if params.LocalVersion != "" && u.adapters.WriteLocalVersion != nil { + result.LocalVersionErr = u.adapters.WriteLocalVersion( + filepath.Join(params.BeadsDir, ".local_version"), + params.LocalVersion, + ) + } + return result, nil +} + +func (u *beadsDirFSUseCaseImpl) SetupForkExclude(ctx context.Context, verbose bool) error { + if u.adapters.SetupForkExclude == nil { + return fmt.Errorf("SetupForkExclude: adapter not configured") + } + return u.adapters.SetupForkExclude(verbose) +} + +func (u *beadsDirFSUseCaseImpl) SetupStealthMode(ctx context.Context, verbose bool) error { + if u.adapters.SetupStealthMode == nil { + return fmt.Errorf("SetupStealthMode: adapter not configured") + } + return u.adapters.SetupStealthMode(verbose) +} + +func (u *beadsDirFSUseCaseImpl) InstallGitHooks(ctx context.Context, params HooksInstallParams) error { + if u.adapters.InstallGitHooks == nil { + return fmt.Errorf("InstallGitHooks: adapter not configured") + } + return u.adapters.InstallGitHooks(params) +} + +func (u *beadsDirFSUseCaseImpl) InstallJJHooks(ctx context.Context) error { + if u.adapters.InstallJJHooks == nil { + return fmt.Errorf("InstallJJHooks: adapter not configured") + } + return u.adapters.InstallJJHooks() +} + +func (u *beadsDirFSUseCaseImpl) AddAgentsInstructions(ctx context.Context, params AgentsFileParams) error { + if u.adapters.AddAgentsInstructions == nil { + return fmt.Errorf("AddAgentsInstructions: adapter not configured") + } + u.adapters.AddAgentsInstructions(params) + return nil +} + +func (u *beadsDirFSUseCaseImpl) InstallClaudeProject(ctx context.Context, stealth bool) error { + if u.adapters.InstallClaudeProject == nil { + return fmt.Errorf("InstallClaudeProject: adapter not configured") + } + return u.adapters.InstallClaudeProject(stealth) +} + +func (u *beadsDirFSUseCaseImpl) SetYAMLConfig(ctx context.Context, key, value string) error { + if u.adapters.SetYAMLConfig == nil { + return fmt.Errorf("SetYAMLConfig: adapter not configured") + } + return u.adapters.SetYAMLConfig(key, value) +} diff --git a/internal/storage/domain/bootstrap.go b/internal/storage/domain/bootstrap.go index f9433306d..5e979fcef 100644 --- a/internal/storage/domain/bootstrap.go +++ b/internal/storage/domain/bootstrap.go @@ -1,11 +1,107 @@ package domain -import "context" +import ( + "context" + "fmt" + "time" +) type BootstrapUseCase interface { BootstrapProject(ctx context.Context, params BootstrapProjectParams) (BootstrapProjectResult, error) } -type BootstrapProjectParams struct{} +type BootstrapProjectParams struct { + Prefix string + ProjectID string + BdVersion string + LastImportTime time.Time -type BootstrapProjectResult struct{} + RepoID string + CloneID string + + RemoteName string + RemoteURL string +} + +type BootstrapProjectResult struct { + RemoteConfigured bool +} + +func NewBootstrapUseCase(cfgRepo ConfigSQLRepository, remoteUseCase DoltRemoteUseCase) BootstrapUseCase { + return &bootstrapUseCaseImpl{ + cfgRepo: cfgRepo, + remoteUseCase: remoteUseCase, + } +} + +type bootstrapUseCaseImpl struct { + cfgRepo ConfigSQLRepository + remoteUseCase DoltRemoteUseCase +} + +var _ BootstrapUseCase = (*bootstrapUseCaseImpl)(nil) + +func (u *bootstrapUseCaseImpl) BootstrapProject(ctx context.Context, params BootstrapProjectParams) (BootstrapProjectResult, error) { + if params.Prefix == "" { + return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: Prefix must not be empty") + } + if params.ProjectID == "" { + return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: ProjectID must not be empty") + } + if params.BdVersion == "" { + return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: BdVersion must not be empty") + } + if params.LastImportTime.IsZero() { + return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: LastImportTime must not be zero") + } + + if err := u.cfgRepo.SetConfig(ctx, "issue_prefix", params.Prefix); err != nil { + return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: set issue_prefix: %w", err) + } + if err := u.cfgRepo.SetMetadata(ctx, "_project_id", params.ProjectID); err != nil { + return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: set _project_id: %w", err) + } + if params.RepoID != "" { + if err := u.cfgRepo.SetMetadata(ctx, "repo_id", params.RepoID); err != nil { + return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: set repo_id: %w", err) + } + } + if params.CloneID != "" { + if err := u.cfgRepo.SetMetadata(ctx, "clone_id", params.CloneID); err != nil { + return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: set clone_id: %w", err) + } + } + if err := u.cfgRepo.SetMetadata(ctx, "last_import_time", params.LastImportTime.UTC().Format(time.RFC3339)); err != nil { + return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: set last_import_time: %w", err) + } + if err := u.cfgRepo.SetLocalMetadata(ctx, "bd_version", params.BdVersion); err != nil { + return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: set bd_version: %w", err) + } + + var result BootstrapProjectResult + if params.RemoteURL != "" { + name := params.RemoteName + if name == "" { + name = "origin" + } + remotes, err := u.remoteUseCase.ListRemotes(ctx) + if err != nil { + return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: list remotes: %w", err) + } + exists := false + for _, r := range remotes { + if r.Name == name { + exists = true + break + } + } + if !exists { + if err := u.remoteUseCase.CreateRemote(ctx, name, params.RemoteURL); err != nil { + return BootstrapProjectResult{}, fmt.Errorf("BootstrapProject: create remote %s: %w", name, err) + } + result.RemoteConfigured = true + } + } + + return result, nil +} diff --git a/internal/storage/domain/config.go b/internal/storage/domain/config.go index 4894077e3..f9624928f 100644 --- a/internal/storage/domain/config.go +++ b/internal/storage/domain/config.go @@ -1,6 +1,9 @@ package domain -import "context" +import ( + "context" + "fmt" +) type ConfigSQLRepository interface { GetMetadata(ctx context.Context, key string) (string, error) @@ -12,8 +15,6 @@ type ConfigSQLRepository interface { } type ConfigUseCase interface { - ConfigureContributorMode(ctx context.Context, params ContributorModeParams) error - ConfigureTeamMode(ctx context.Context, params TeamModeParams) error VerifyInit(ctx context.Context) (VerifyResult, error) } @@ -23,12 +24,47 @@ type BatchCreateOptions struct{} type Statistics struct{} -type ContributorModeParams struct{} - -type TeamModeParams struct{} - type GlobalDatabaseParams struct{} type ImportResult struct{} -type VerifyResult struct{} +type VerifyResult struct { + ProjectID string + IssuePrefix string + Missing []string +} + +func NewConfigUseCase(cfgRepo ConfigSQLRepository) ConfigUseCase { + return &configUseCaseImpl{cfgRepo: cfgRepo} +} + +type configUseCaseImpl struct { + cfgRepo ConfigSQLRepository +} + +var _ ConfigUseCase = (*configUseCaseImpl)(nil) + +func (u *configUseCaseImpl) VerifyInit(ctx context.Context) (VerifyResult, error) { + projectID, err := u.cfgRepo.GetMetadata(ctx, "_project_id") + if err != nil { + return VerifyResult{}, fmt.Errorf("VerifyInit: read _project_id: %w", err) + } + issuePrefix, err := u.cfgRepo.GetConfig(ctx, "issue_prefix") + if err != nil { + return VerifyResult{}, fmt.Errorf("VerifyInit: read issue_prefix: %w", err) + } + + var missing []string + if projectID == "" { + missing = append(missing, "metadata._project_id") + } + if issuePrefix == "" { + missing = append(missing, "config.issue_prefix") + } + + return VerifyResult{ + ProjectID: projectID, + IssuePrefix: issuePrefix, + Missing: missing, + }, nil +} diff --git a/internal/storage/domain/db/config.go b/internal/storage/domain/db/config.go new file mode 100644 index 000000000..9afddd360 --- /dev/null +++ b/internal/storage/domain/db/config.go @@ -0,0 +1,73 @@ +package db + +import ( + "context" + "database/sql" + "errors" + "fmt" + "strings" + + "github.com/steveyegge/beads/internal/storage/domain" +) + +func NewConfigSQLRepository(runner Runner) domain.ConfigSQLRepository { + return &configSQLRepositoryImpl{runner: runner} +} + +type configSQLRepositoryImpl struct { + runner Runner +} + +var _ domain.ConfigSQLRepository = (*configSQLRepositoryImpl)(nil) + +func (r *configSQLRepositoryImpl) GetMetadata(ctx context.Context, key string) (string, error) { + var value string + err := r.runner.QueryRowContext(ctx, "SELECT value FROM metadata WHERE `key` = ?", key).Scan(&value) + if errors.Is(err, sql.ErrNoRows) { + return "", nil + } + if err != nil { + return "", fmt.Errorf("db: GetMetadata %s: %w", key, err) + } + return value, nil +} + +func (r *configSQLRepositoryImpl) SetMetadata(ctx context.Context, key, value string) error { + if _, err := r.runner.ExecContext(ctx, "REPLACE INTO metadata (`key`, value) VALUES (?, ?)", key, value); err != nil { + return fmt.Errorf("db: SetMetadata %s: %w", key, err) + } + return nil +} + +func (r *configSQLRepositoryImpl) SetLocalMetadata(ctx context.Context, key, value string) error { + if _, err := r.runner.ExecContext(ctx, "REPLACE INTO local_metadata (`key`, value) VALUES (?, ?)", key, value); err != nil { + return fmt.Errorf("db: SetLocalMetadata %s: %w", key, err) + } + return nil +} + +func (r *configSQLRepositoryImpl) GetConfig(ctx context.Context, key string) (string, error) { + var value string + err := r.runner.QueryRowContext(ctx, "SELECT value FROM config WHERE `key` = ?", key).Scan(&value) + if errors.Is(err, sql.ErrNoRows) { + return "", nil + } + if err != nil { + return "", fmt.Errorf("db: GetConfig %s: %w", key, err) + } + return value, nil +} + +func (r *configSQLRepositoryImpl) SetConfig(ctx context.Context, key, value string) error { + if key == "issue_prefix" { + value = strings.TrimSuffix(value, "-") + } + if _, err := r.runner.ExecContext(ctx, "REPLACE INTO config (`key`, value) VALUES (?, ?)", key, value); err != nil { + return fmt.Errorf("db: SetConfig %s: %w", key, err) + } + return nil +} + +func (r *configSQLRepositoryImpl) GetStatistics(ctx context.Context) (domain.Statistics, error) { + return domain.Statistics{}, nil +} diff --git a/internal/storage/domain/db/config_test.go b/internal/storage/domain/db/config_test.go new file mode 100644 index 000000000..33465357b --- /dev/null +++ b/internal/storage/domain/db/config_test.go @@ -0,0 +1,105 @@ +package db + +import ( + "github.com/steveyegge/beads/internal/storage/domain" +) + +func (s *testSuite) TestConfigSQLRepository() { + s.Run("GetMetadata", func() { + s.Run("MissingKeyReturnsEmpty", s.configGetMetadataMissingKey) + s.Run("RoundTrip", s.configGetMetadataRoundTrip) + }) + s.Run("SetMetadata", func() { + s.Run("Overwrite", s.configSetMetadataOverwrite) + }) + s.Run("SetLocalMetadata", func() { + s.Run("WritesToLocalMetadataTable", s.configSetLocalMetadataWrites) + }) + s.Run("GetConfig", func() { + s.Run("MissingKeyReturnsEmpty", s.configGetConfigMissingKey) + s.Run("RoundTrip", s.configGetConfigRoundTrip) + }) + s.Run("SetConfig", func() { + s.Run("Overwrite", s.configSetConfigOverwrite) + s.Run("IssuePrefixTrimsTrailingHyphen", s.configSetConfigIssuePrefixTrim) + s.Run("IssuePrefixWithoutHyphenUnchanged", s.configSetConfigIssuePrefixUnchanged) + }) +} + +func (s *testSuite) configRepo() domain.ConfigSQLRepository { + return NewConfigSQLRepository(s.Runner()) +} + +func (s *testSuite) configGetMetadataMissingKey() { + v, err := s.configRepo().GetMetadata(s.Ctx(), "no_such_key") + s.Require().NoError(err) + s.Equal("", v) +} + +func (s *testSuite) configGetMetadataRoundTrip() { + r := s.configRepo() + s.Require().NoError(r.SetMetadata(s.Ctx(), "_project_id", "abc-123")) + v, err := r.GetMetadata(s.Ctx(), "_project_id") + s.Require().NoError(err) + s.Equal("abc-123", v) +} + +func (s *testSuite) configSetMetadataOverwrite() { + r := s.configRepo() + s.Require().NoError(r.SetMetadata(s.Ctx(), "k", "v1")) + s.Require().NoError(r.SetMetadata(s.Ctx(), "k", "v2")) + v, err := r.GetMetadata(s.Ctx(), "k") + s.Require().NoError(err) + s.Equal("v2", v) +} + +func (s *testSuite) configSetLocalMetadataWrites() { + r := s.configRepo() + s.Require().NoError(r.SetLocalMetadata(s.Ctx(), "bd_version", "1.2.3")) + + var v string + err := s.Runner(). + QueryRowContext(s.Ctx(), "SELECT value FROM local_metadata WHERE `key` = ?", "bd_version"). + Scan(&v) + s.Require().NoError(err) + s.Equal("1.2.3", v) +} + +func (s *testSuite) configGetConfigMissingKey() { + v, err := s.configRepo().GetConfig(s.Ctx(), "no_such_key") + s.Require().NoError(err) + s.Equal("", v) +} + +func (s *testSuite) configGetConfigRoundTrip() { + r := s.configRepo() + s.Require().NoError(r.SetConfig(s.Ctx(), "team.sync_branch", "main")) + v, err := r.GetConfig(s.Ctx(), "team.sync_branch") + s.Require().NoError(err) + s.Equal("main", v) +} + +func (s *testSuite) configSetConfigOverwrite() { + r := s.configRepo() + s.Require().NoError(r.SetConfig(s.Ctx(), "k", "v1")) + s.Require().NoError(r.SetConfig(s.Ctx(), "k", "v2")) + v, err := r.GetConfig(s.Ctx(), "k") + s.Require().NoError(err) + s.Equal("v2", v) +} + +func (s *testSuite) configSetConfigIssuePrefixTrim() { + r := s.configRepo() + s.Require().NoError(r.SetConfig(s.Ctx(), "issue_prefix", "bd-")) + v, err := r.GetConfig(s.Ctx(), "issue_prefix") + s.Require().NoError(err) + s.Equal("bd", v) +} + +func (s *testSuite) configSetConfigIssuePrefixUnchanged() { + r := s.configRepo() + s.Require().NoError(r.SetConfig(s.Ctx(), "issue_prefix", "bd")) + v, err := r.GetConfig(s.Ctx(), "issue_prefix") + s.Require().NoError(err) + s.Equal("bd", v) +} diff --git a/internal/storage/domain/db/remote.go b/internal/storage/domain/db/remote.go new file mode 100644 index 000000000..0606f4ca1 --- /dev/null +++ b/internal/storage/domain/db/remote.go @@ -0,0 +1,57 @@ +package db + +import ( + "context" + "fmt" + + "github.com/steveyegge/beads/internal/storage/domain" +) + +func NewRemoteSQLRepository(runner Runner) domain.RemoteSQLRepository { + return &remoteSQLRepositoryImpl{ + runner: runner, + vc: NewDoltVersionControlSQLRepository(runner), + } +} + +type remoteSQLRepositoryImpl struct { + runner Runner + vc DoltVersionControlSQLRepository +} + +var _ domain.RemoteSQLRepository = (*remoteSQLRepositoryImpl)(nil) + +func (r *remoteSQLRepositoryImpl) AddRemote(ctx context.Context, name, url string) error { + if err := r.vc.Remote(ctx, "add", name, url); err != nil { + return fmt.Errorf("db: AddRemote %s: %w", name, err) + } + return nil +} + +func (r *remoteSQLRepositoryImpl) RemoveRemote(ctx context.Context, name string) error { + if err := r.vc.Remote(ctx, "remove", name); err != nil { + return fmt.Errorf("db: RemoveRemote %s: %w", name, err) + } + return nil +} + +func (r *remoteSQLRepositoryImpl) ListRemotes(ctx context.Context) ([]domain.Remote, error) { + rows, err := r.runner.QueryContext(ctx, "SELECT name, url FROM dolt_remotes") + if err != nil { + return nil, fmt.Errorf("db: ListRemotes: query: %w", err) + } + defer rows.Close() + + var remotes []domain.Remote + for rows.Next() { + var rem domain.Remote + if err := rows.Scan(&rem.Name, &rem.URL); err != nil { + return nil, fmt.Errorf("db: ListRemotes: scan: %w", err) + } + remotes = append(remotes, rem) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("db: ListRemotes: rows: %w", err) + } + return remotes, nil +} diff --git a/internal/storage/domain/db/suite_test.go b/internal/storage/domain/db/suite_test.go new file mode 100644 index 000000000..5a381a10a --- /dev/null +++ b/internal/storage/domain/db/suite_test.go @@ -0,0 +1,106 @@ +package db + +import ( + "context" + "database/sql" + "math/rand" + "testing" + + _ "github.com/go-sql-driver/mysql" + "github.com/stretchr/testify/suite" + + "github.com/steveyegge/beads/internal/storage/doltutil" + "github.com/steveyegge/beads/internal/storage/schema" + "github.com/steveyegge/beads/internal/testutil" +) + +type testSuite struct { + suite.Suite + db *sql.DB + dbName string + baselineCommit string +} + +func (s *testSuite) SetupSuite() { + testutil.RequireDoltContainer(s.T()) + + port := testutil.DoltContainerPortInt() + s.Require().NotZero(port, "test container port must be set") + + ctx := context.Background() + + rootDSN := doltutil.ServerDSN{Host: "127.0.0.1", Port: port, User: "root"}.String() + root, err := sql.Open("mysql", rootDSN) + s.Require().NoError(err) + defer root.Close() + + s.dbName = "beads_domain_db_test_" + randomSuffix(8) + _, err = root.ExecContext(ctx, "CREATE DATABASE `"+s.dbName+"`") + s.Require().NoError(err) + + dsn := doltutil.ServerDSN{Host: "127.0.0.1", Port: port, User: "root", Database: s.dbName}.String() + db, err := sql.Open("mysql", dsn) + s.Require().NoError(err) + s.Require().NoError(db.PingContext(ctx)) + s.db = db + + _, err = schema.MigrateUp(ctx, db) + s.Require().NoError(err, "applying beads schema") + + _, err = db.ExecContext(ctx, "CALL DOLT_ADD('-A')") + s.Require().NoError(err, "dolt add baseline") + _, err = db.ExecContext(ctx, "CALL DOLT_COMMIT('-m', ?, '--allow-empty')", "beads domain/db test baseline") + s.Require().NoError(err, "dolt commit baseline") + s.Require().NoError( + db.QueryRowContext(ctx, "SELECT HASHOF('HEAD')").Scan(&s.baselineCommit), + "capture baseline commit hash", + ) +} + +func (s *testSuite) TearDownSuite() { + if s.db != nil { + _ = s.db.Close() + s.db = nil + } + if s.dbName == "" { + return + } + port := testutil.DoltContainerPortInt() + if port == 0 { + return + } + rootDSN := doltutil.ServerDSN{Host: "127.0.0.1", Port: port, User: "root"}.String() + root, err := sql.Open("mysql", rootDSN) + if err != nil { + return + } + defer root.Close() + _, _ = root.ExecContext(context.Background(), "DROP DATABASE IF EXISTS `"+s.dbName+"`") +} + +func (s *testSuite) SetupTest() { + _, err := s.db.ExecContext(context.Background(), "CALL DOLT_RESET('--hard', ?)", s.baselineCommit) + s.Require().NoError(err, "reset to baseline %s", s.baselineCommit) +} + +func (s *testSuite) Runner() Runner { + return s.db +} + +func (s *testSuite) Ctx() context.Context { + return context.Background() +} + +var suffixLetters = []rune("abcdefghijklmnopqrstuvwxyz") + +func randomSuffix(n int) string { + b := make([]rune, n) + for i := range b { + b[i] = suffixLetters[rand.Intn(len(suffixLetters))] + } + return string(b) +} + +func TestDomainDB(t *testing.T) { + suite.Run(t, &testSuite{}) +} diff --git a/internal/storage/domain/fs/beads.go b/internal/storage/domain/fs/beads.go new file mode 100644 index 000000000..98409c7a1 --- /dev/null +++ b/internal/storage/domain/fs/beads.go @@ -0,0 +1,288 @@ +package fs + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/storage/domain" +) + +const beadsGitignoreTemplate = `# Dolt database (managed by Dolt, not git) +dolt/ +embeddeddolt/ +proxieddb/ + +# Runtime files +bd.sock +bd.sock.startlock +sync-state.json +last-touched +.exclusive-lock + +# Daemon runtime (lock, log, pid) +daemon.* + +# Push state (runtime, per-machine) +push-state.json + +# Lock files (various runtime locks) +*.lock + +# Credential key (encryption key for federation peer auth — never commit) +.beads-credential-key + +# Local version tracking (prevents upgrade notification spam after git ops) +.local_version + +# Worktree redirect file (contains relative path to main repo's .beads/) +# Must not be committed as paths would be wrong in other clones +redirect + +# Sync state (local-only, per-machine) +# These files are machine-specific and should not be shared across clones +.sync.lock +export-state/ +export-state.json + +# Ephemeral store (SQLite - wisps/molecules, intentionally not versioned) +ephemeral.sqlite3 +ephemeral.sqlite3-journal +ephemeral.sqlite3-wal +ephemeral.sqlite3-shm + +# Dolt server management (auto-started by bd) +dolt-server.pid +dolt-server.log +dolt-server.lock +dolt-server.port +dolt-server.activity + +# Corrupt backup directories (created by bd doctor --fix recovery) +*.corrupt.backup/ + +# Backup data (auto-exported JSONL, local-only) +backup/ + +# Per-project environment file (Dolt connection config, GH#2520) +.env + +# Legacy files (from pre-Dolt versions) +*.db +*.db?* +*.db-journal +*.db-wal +*.db-shm +db.sqlite +bd.db +# NOTE: Do NOT add negation patterns here. +# They would override fork protection in .git/info/exclude. +# Config files (metadata.json, config.yaml) are tracked by git by default +# since no pattern above ignores them. +` + +var projectGitignorePatterns = []string{ + ".dolt/", + "*.db", + ".beads-credential-key", + ".beads/proxieddb/", +} + +const projectGitignoreHeader = "# Beads / Dolt files (added by bd init)" + +const beadsReadmeTemplate = `# Beads + +This directory is managed by [beads](https://github.com/steveyegge/beads). +Run ` + "`bd help`" + ` for available commands. +` + +func NewBeadsDirFSRepository() domain.BeadsDirFSRepository { + return &beadsDirFSRepositoryImpl{} +} + +type beadsDirFSRepositoryImpl struct{} + +var _ domain.BeadsDirFSRepository = (*beadsDirFSRepositoryImpl)(nil) + +func (r *beadsDirFSRepositoryImpl) CreateBeadsDir(ctx context.Context, beadsDir string) error { + if beadsDir == "" { + return fmt.Errorf("fs: CreateBeadsDir: beadsDir must not be empty") + } + if err := os.MkdirAll(beadsDir, config.BeadsDirPerm); err != nil { + return fmt.Errorf("fs: CreateBeadsDir: mkdir %s: %w", beadsDir, err) + } + if _, err := config.FixBeadsDirPermissions(beadsDir); err != nil { + return fmt.Errorf("fs: CreateBeadsDir: fix perms %s: %w", beadsDir, err) + } + return nil +} + +func (r *beadsDirFSRepositoryImpl) BeadsDirExists(ctx context.Context, beadsDir string) (bool, error) { + info, err := os.Stat(beadsDir) + if errors.Is(err, os.ErrNotExist) { + return false, nil + } + if err != nil { + return false, fmt.Errorf("fs: BeadsDirExists: stat %s: %w", beadsDir, err) + } + return info.IsDir(), nil +} + +func (r *beadsDirFSRepositoryImpl) WriteBeadsGitignore(ctx context.Context, beadsDir string) error { + path := filepath.Join(beadsDir, ".gitignore") + // #nosec G304 -- path joined under caller-supplied beadsDir + if existing, err := os.ReadFile(path); err == nil && bytes.Equal(existing, []byte(beadsGitignoreTemplate)) { + return nil + } + if err := os.WriteFile(path, []byte(beadsGitignoreTemplate), 0600); err != nil { + return fmt.Errorf("fs: WriteBeadsGitignore: %w", err) + } + return nil +} + +func (r *beadsDirFSRepositoryImpl) BeadsGitignoreExists(ctx context.Context, beadsDir string) (bool, error) { + return fileExists(filepath.Join(beadsDir, ".gitignore"), "fs: BeadsGitignoreExists") +} + +func (r *beadsDirFSRepositoryImpl) WriteProjectGitignore(ctx context.Context, repoRoot string) error { + if repoRoot == "" { + return fmt.Errorf("fs: WriteProjectGitignore: repoRoot must not be empty") + } + path := filepath.Join(repoRoot, ".gitignore") + // #nosec G304 -- path joined under caller-supplied repoRoot + existing, err := os.ReadFile(path) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("fs: WriteProjectGitignore: read: %w", err) + } + + var toAdd []string + for _, pattern := range projectGitignorePatterns { + if !containsLine(existing, pattern) { + toAdd = append(toAdd, pattern) + } + } + if len(toAdd) == 0 { + return nil + } + + var buf bytes.Buffer + buf.Write(existing) + if len(existing) > 0 && !bytes.HasSuffix(existing, []byte("\n")) { + buf.WriteByte('\n') + } + if !containsLine(existing, projectGitignoreHeader) { + if len(existing) > 0 { + buf.WriteByte('\n') + } + buf.WriteString(projectGitignoreHeader + "\n") + } + for _, pattern := range toAdd { + buf.WriteString(pattern + "\n") + } + + // #nosec G306 -- .gitignore must be world-readable so users can read/edit it + if err := os.WriteFile(path, buf.Bytes(), 0644); err != nil { + return fmt.Errorf("fs: WriteProjectGitignore: write: %w", err) + } + return nil +} + +func (r *beadsDirFSRepositoryImpl) ProjectGitignoreExists(ctx context.Context, repoRoot string) (bool, error) { + return fileExists(filepath.Join(repoRoot, ".gitignore"), "fs: ProjectGitignoreExists") +} + +func (r *beadsDirFSRepositoryImpl) WriteInteractionsLog(ctx context.Context, beadsDir string) error { + path := filepath.Join(beadsDir, "interactions.jsonl") + switch _, err := os.Stat(path); { + case err == nil: + return nil + case !errors.Is(err, os.ErrNotExist): + return fmt.Errorf("fs: WriteInteractionsLog: stat: %w", err) + } + // #nosec G306 -- interactions log is consumed by user tooling + if err := os.WriteFile(path, []byte{}, 0644); err != nil { + return fmt.Errorf("fs: WriteInteractionsLog: write: %w", err) + } + return nil +} + +func (r *beadsDirFSRepositoryImpl) WriteReadme(ctx context.Context, beadsDir string) error { + path := filepath.Join(beadsDir, "README.md") + if _, err := os.Stat(path); err == nil { + return nil // preserve any user edits + } + // #nosec G306 -- README should be world-readable + if err := os.WriteFile(path, []byte(beadsReadmeTemplate), 0644); err != nil { + return fmt.Errorf("fs: WriteReadme: %w", err) + } + return nil +} + +func (r *beadsDirFSRepositoryImpl) WriteMetadataJSON(ctx context.Context, beadsDir string, content []byte) error { + path := filepath.Join(beadsDir, "metadata.json") + if err := os.WriteFile(path, content, 0600); err != nil { + return fmt.Errorf("fs: WriteMetadataJSON: %w", err) + } + return nil +} + +func (r *beadsDirFSRepositoryImpl) ReadMetadataJSON(ctx context.Context, beadsDir string) ([]byte, error) { + path := filepath.Join(beadsDir, "metadata.json") + // #nosec G304 -- path joined under caller-supplied beadsDir + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("fs: ReadMetadataJSON: %w", err) + } + return data, nil +} + +func (r *beadsDirFSRepositoryImpl) WriteConfigYAML(ctx context.Context, beadsDir string, content []byte) error { + path := filepath.Join(beadsDir, "config.yaml") + if err := os.WriteFile(path, content, 0600); err != nil { + return fmt.Errorf("fs: WriteConfigYAML: %w", err) + } + return nil +} + +func (r *beadsDirFSRepositoryImpl) ReadConfigYAML(ctx context.Context, beadsDir string) ([]byte, error) { + path := filepath.Join(beadsDir, "config.yaml") + // #nosec G304 -- path joined under caller-supplied beadsDir + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("fs: ReadConfigYAML: %w", err) + } + return data, nil +} + +func fileExists(path, opLabel string) (bool, error) { + info, err := os.Stat(path) + if errors.Is(err, os.ErrNotExist) { + return false, nil + } + if err != nil { + return false, fmt.Errorf("%s: stat %s: %w", opLabel, path, err) + } + return !info.IsDir(), nil +} + +func containsLine(content []byte, line string) bool { + s := bufio.NewScanner(bytes.NewReader(content)) + for s.Scan() { + if strings.TrimSpace(s.Text()) == line { + return true + } + } + return false +} diff --git a/internal/storage/domain/fs/beads_test.go b/internal/storage/domain/fs/beads_test.go new file mode 100644 index 000000000..944af4cb2 --- /dev/null +++ b/internal/storage/domain/fs/beads_test.go @@ -0,0 +1,379 @@ +package fs + +import ( + "bytes" + "os" + "path/filepath" + "runtime" + "strings" + + "github.com/steveyegge/beads/internal/config" +) + +func (s *testSuite) TestBeadsDirFSRepository() { + s.Run("CreateBeadsDir", func() { + s.Run("EmptyPathErrors", s.createBeadsDirEmptyPath) + s.Run("CreatesDirectoryWithPerms", s.createBeadsDirCreates) + s.Run("IdempotentOnExisting", s.createBeadsDirIdempotent) + }) + s.Run("BeadsDirExists", func() { + s.Run("MissingReturnsFalse", s.beadsDirExistsMissing) + s.Run("PresentReturnsTrue", s.beadsDirExistsPresent) + s.Run("FileNotDirReturnsFalse", s.beadsDirExistsIsFile) + }) + s.Run("WriteBeadsGitignore", func() { + s.Run("WritesTemplate", s.writeBeadsGitignoreWrites) + s.Run("IdempotentOnMatchingContent", s.writeBeadsGitignoreIdempotent) + s.Run("OverwritesDifferingContent", s.writeBeadsGitignoreOverwrites) + }) + s.Run("BeadsGitignoreExists", func() { + s.Run("MissingReturnsFalse", s.beadsGitignoreExistsMissing) + s.Run("PresentReturnsTrue", s.beadsGitignoreExistsPresent) + }) + s.Run("WriteProjectGitignore", func() { + s.Run("EmptyRepoRootErrors", s.writeProjectGitignoreEmptyRoot) + s.Run("CreatesWithHeaderAndPatterns", s.writeProjectGitignoreCreates) + s.Run("AppendsToExisting", s.writeProjectGitignoreAppends) + s.Run("SkipsAlreadyPresentPatterns", s.writeProjectGitignoreNoDuplicates) + s.Run("NoChangeWhenAllPresent", s.writeProjectGitignoreNoOpWhenComplete) + s.Run("AddsLeadingNewlineWhenMissing", s.writeProjectGitignoreFixesTrailingNewline) + }) + s.Run("ProjectGitignoreExists", func() { + s.Run("MissingReturnsFalse", s.projectGitignoreExistsMissing) + s.Run("PresentReturnsTrue", s.projectGitignoreExistsPresent) + }) + s.Run("WriteInteractionsLog", func() { + s.Run("CreatesEmptyFile", s.writeInteractionsLogCreates) + s.Run("PreservesExisting", s.writeInteractionsLogPreserves) + }) + s.Run("WriteReadme", func() { + s.Run("CreatesFromTemplate", s.writeReadmeCreates) + s.Run("PreservesExisting", s.writeReadmePreserves) + }) + s.Run("MetadataJSON", func() { + s.Run("ReadMissingReturnsNil", s.readMetadataJSONMissing) + s.Run("WriteThenReadRoundTrip", s.metadataJSONRoundTrip) + s.Run("WriteOverwrites", s.metadataJSONOverwrite) + }) + s.Run("ConfigYAML", func() { + s.Run("ReadMissingReturnsNil", s.readConfigYAMLMissing) + s.Run("WriteThenReadRoundTrip", s.configYAMLRoundTrip) + s.Run("WriteOverwrites", s.configYAMLOverwrite) + }) +} + +func (s *testSuite) createBeadsDirEmptyPath() { + err := s.repo.CreateBeadsDir(s.Ctx(), "") + s.Require().Error(err) +} + +func (s *testSuite) createBeadsDirCreates() { + _, dir := s.beadsDir() + s.Require().NoError(s.repo.CreateBeadsDir(s.Ctx(), dir)) + + info, err := os.Stat(dir) + s.Require().NoError(err) + s.True(info.IsDir()) + + if runtime.GOOS != "windows" { + s.Equal(config.BeadsDirPerm, info.Mode().Perm()) + } +} + +func (s *testSuite) createBeadsDirIdempotent() { + _, dir := s.beadsDir() + s.Require().NoError(s.repo.CreateBeadsDir(s.Ctx(), dir)) + s.Require().NoError(s.repo.CreateBeadsDir(s.Ctx(), dir)) +} + +func (s *testSuite) beadsDirExistsMissing() { + _, dir := s.beadsDir() + exists, err := s.repo.BeadsDirExists(s.Ctx(), dir) + s.Require().NoError(err) + s.False(exists) +} + +func (s *testSuite) beadsDirExistsPresent() { + _, dir := s.beadsDir() + s.Require().NoError(os.MkdirAll(dir, 0700)) + exists, err := s.repo.BeadsDirExists(s.Ctx(), dir) + s.Require().NoError(err) + s.True(exists) +} + +func (s *testSuite) beadsDirExistsIsFile() { + _, path := s.beadsDir() + s.Require().NoError(os.WriteFile(path, []byte("not a dir"), 0600)) + exists, err := s.repo.BeadsDirExists(s.Ctx(), path) + s.Require().NoError(err) + s.False(exists) +} + +func (s *testSuite) writeBeadsGitignoreWrites() { + _, dir := s.beadsDir() + s.Require().NoError(os.MkdirAll(dir, 0700)) + s.Require().NoError(s.repo.WriteBeadsGitignore(s.Ctx(), dir)) + + data, err := os.ReadFile(filepath.Join(dir, ".gitignore")) + s.Require().NoError(err) + s.Equal(beadsGitignoreTemplate, string(data)) +} + +func (s *testSuite) writeBeadsGitignoreIdempotent() { + _, dir := s.beadsDir() + s.Require().NoError(os.MkdirAll(dir, 0700)) + path := filepath.Join(dir, ".gitignore") + s.Require().NoError(os.WriteFile(path, []byte(beadsGitignoreTemplate), 0600)) + + before, err := os.Stat(path) + s.Require().NoError(err) + + s.Require().NoError(s.repo.WriteBeadsGitignore(s.Ctx(), dir)) + + after, err := os.Stat(path) + s.Require().NoError(err) + s.Equal(before.ModTime(), after.ModTime(), "file should not be rewritten when content already matches") +} + +func (s *testSuite) writeBeadsGitignoreOverwrites() { + _, dir := s.beadsDir() + s.Require().NoError(os.MkdirAll(dir, 0700)) + path := filepath.Join(dir, ".gitignore") + s.Require().NoError(os.WriteFile(path, []byte("stale\n"), 0600)) + + s.Require().NoError(s.repo.WriteBeadsGitignore(s.Ctx(), dir)) + + data, err := os.ReadFile(path) + s.Require().NoError(err) + s.Equal(beadsGitignoreTemplate, string(data)) +} + +func (s *testSuite) beadsGitignoreExistsMissing() { + _, dir := s.beadsDir() + s.Require().NoError(os.MkdirAll(dir, 0700)) + exists, err := s.repo.BeadsGitignoreExists(s.Ctx(), dir) + s.Require().NoError(err) + s.False(exists) +} + +func (s *testSuite) beadsGitignoreExistsPresent() { + _, dir := s.beadsDir() + s.Require().NoError(os.MkdirAll(dir, 0700)) + s.Require().NoError(os.WriteFile(filepath.Join(dir, ".gitignore"), []byte("x"), 0600)) + exists, err := s.repo.BeadsGitignoreExists(s.Ctx(), dir) + s.Require().NoError(err) + s.True(exists) +} + +func (s *testSuite) writeProjectGitignoreEmptyRoot() { + err := s.repo.WriteProjectGitignore(s.Ctx(), "") + s.Require().Error(err) +} + +func (s *testSuite) writeProjectGitignoreCreates() { + root := s.tmpRoot() + s.Require().NoError(s.repo.WriteProjectGitignore(s.Ctx(), root)) + + data, err := os.ReadFile(filepath.Join(root, ".gitignore")) + s.Require().NoError(err) + body := string(data) + + s.Contains(body, projectGitignoreHeader) + for _, pattern := range projectGitignorePatterns { + s.Contains(body, pattern) + } +} + +func (s *testSuite) writeProjectGitignoreAppends() { + root := s.tmpRoot() + path := filepath.Join(root, ".gitignore") + preexisting := "node_modules/\n*.log\n" + s.Require().NoError(os.WriteFile(path, []byte(preexisting), 0644)) + + s.Require().NoError(s.repo.WriteProjectGitignore(s.Ctx(), root)) + + data, err := os.ReadFile(path) + s.Require().NoError(err) + body := string(data) + + s.True(strings.HasPrefix(body, preexisting), "preexisting content must be preserved at the top") + s.Contains(body, projectGitignoreHeader) + for _, pattern := range projectGitignorePatterns { + s.Contains(body, pattern) + } +} + +func (s *testSuite) writeProjectGitignoreNoDuplicates() { + root := s.tmpRoot() + path := filepath.Join(root, ".gitignore") + preexisting := ".dolt/\nnode_modules/\n" + s.Require().NoError(os.WriteFile(path, []byte(preexisting), 0644)) + + s.Require().NoError(s.repo.WriteProjectGitignore(s.Ctx(), root)) + + data, err := os.ReadFile(path) + s.Require().NoError(err) + + s.Equal(1, strings.Count(string(data), ".dolt/\n"), "must not duplicate existing patterns") +} + +func (s *testSuite) writeProjectGitignoreNoOpWhenComplete() { + root := s.tmpRoot() + path := filepath.Join(root, ".gitignore") + var buf bytes.Buffer + buf.WriteString("existing\n") + buf.WriteString(projectGitignoreHeader + "\n") + for _, pattern := range projectGitignorePatterns { + buf.WriteString(pattern + "\n") + } + s.Require().NoError(os.WriteFile(path, buf.Bytes(), 0644)) + + before, err := os.Stat(path) + s.Require().NoError(err) + + s.Require().NoError(s.repo.WriteProjectGitignore(s.Ctx(), root)) + + after, err := os.Stat(path) + s.Require().NoError(err) + s.Equal(before.ModTime(), after.ModTime(), "must not rewrite when all patterns already present") +} + +func (s *testSuite) writeProjectGitignoreFixesTrailingNewline() { + root := s.tmpRoot() + path := filepath.Join(root, ".gitignore") + s.Require().NoError(os.WriteFile(path, []byte("no-trailing-newline"), 0644)) + + s.Require().NoError(s.repo.WriteProjectGitignore(s.Ctx(), root)) + + data, err := os.ReadFile(path) + s.Require().NoError(err) + body := string(data) + + s.True(strings.HasPrefix(body, "no-trailing-newline\n"), "trailing newline must be inserted before appended content") + s.Contains(body, projectGitignoreHeader) +} + +func (s *testSuite) projectGitignoreExistsMissing() { + root := s.tmpRoot() + exists, err := s.repo.ProjectGitignoreExists(s.Ctx(), root) + s.Require().NoError(err) + s.False(exists) +} + +func (s *testSuite) projectGitignoreExistsPresent() { + root := s.tmpRoot() + s.Require().NoError(os.WriteFile(filepath.Join(root, ".gitignore"), []byte("x"), 0644)) + exists, err := s.repo.ProjectGitignoreExists(s.Ctx(), root) + s.Require().NoError(err) + s.True(exists) +} + +func (s *testSuite) writeInteractionsLogCreates() { + _, dir := s.beadsDir() + s.Require().NoError(os.MkdirAll(dir, 0700)) + s.Require().NoError(s.repo.WriteInteractionsLog(s.Ctx(), dir)) + + data, err := os.ReadFile(filepath.Join(dir, "interactions.jsonl")) + s.Require().NoError(err) + s.Empty(data) +} + +func (s *testSuite) writeInteractionsLogPreserves() { + _, dir := s.beadsDir() + s.Require().NoError(os.MkdirAll(dir, 0700)) + path := filepath.Join(dir, "interactions.jsonl") + existing := []byte(`{"event":"x"}` + "\n") + s.Require().NoError(os.WriteFile(path, existing, 0644)) + + s.Require().NoError(s.repo.WriteInteractionsLog(s.Ctx(), dir)) + + data, err := os.ReadFile(path) + s.Require().NoError(err) + s.Equal(existing, data) +} + +func (s *testSuite) writeReadmeCreates() { + _, dir := s.beadsDir() + s.Require().NoError(os.MkdirAll(dir, 0700)) + s.Require().NoError(s.repo.WriteReadme(s.Ctx(), dir)) + + data, err := os.ReadFile(filepath.Join(dir, "README.md")) + s.Require().NoError(err) + s.Equal(beadsReadmeTemplate, string(data)) +} + +func (s *testSuite) writeReadmePreserves() { + _, dir := s.beadsDir() + s.Require().NoError(os.MkdirAll(dir, 0700)) + path := filepath.Join(dir, "README.md") + custom := []byte("# My custom readme\n") + s.Require().NoError(os.WriteFile(path, custom, 0644)) + + s.Require().NoError(s.repo.WriteReadme(s.Ctx(), dir)) + + data, err := os.ReadFile(path) + s.Require().NoError(err) + s.Equal(custom, data) +} + +func (s *testSuite) readMetadataJSONMissing() { + _, dir := s.beadsDir() + s.Require().NoError(os.MkdirAll(dir, 0700)) + data, err := s.repo.ReadMetadataJSON(s.Ctx(), dir) + s.Require().NoError(err) + s.Nil(data) +} + +func (s *testSuite) metadataJSONRoundTrip() { + _, dir := s.beadsDir() + s.Require().NoError(os.MkdirAll(dir, 0700)) + body := []byte(`{"_project_id":"abc-123"}`) + + s.Require().NoError(s.repo.WriteMetadataJSON(s.Ctx(), dir, body)) + + got, err := s.repo.ReadMetadataJSON(s.Ctx(), dir) + s.Require().NoError(err) + s.Equal(body, got) +} + +func (s *testSuite) metadataJSONOverwrite() { + _, dir := s.beadsDir() + s.Require().NoError(os.MkdirAll(dir, 0700)) + s.Require().NoError(s.repo.WriteMetadataJSON(s.Ctx(), dir, []byte(`{"v":1}`))) + s.Require().NoError(s.repo.WriteMetadataJSON(s.Ctx(), dir, []byte(`{"v":2}`))) + + got, err := s.repo.ReadMetadataJSON(s.Ctx(), dir) + s.Require().NoError(err) + s.Equal([]byte(`{"v":2}`), got) +} + +func (s *testSuite) readConfigYAMLMissing() { + _, dir := s.beadsDir() + s.Require().NoError(os.MkdirAll(dir, 0700)) + data, err := s.repo.ReadConfigYAML(s.Ctx(), dir) + s.Require().NoError(err) + s.Nil(data) +} + +func (s *testSuite) configYAMLRoundTrip() { + _, dir := s.beadsDir() + s.Require().NoError(os.MkdirAll(dir, 0700)) + body := []byte("issue_prefix: bd\n") + + s.Require().NoError(s.repo.WriteConfigYAML(s.Ctx(), dir, body)) + + got, err := s.repo.ReadConfigYAML(s.Ctx(), dir) + s.Require().NoError(err) + s.Equal(body, got) +} + +func (s *testSuite) configYAMLOverwrite() { + _, dir := s.beadsDir() + s.Require().NoError(os.MkdirAll(dir, 0700)) + s.Require().NoError(s.repo.WriteConfigYAML(s.Ctx(), dir, []byte("v: 1\n"))) + s.Require().NoError(s.repo.WriteConfigYAML(s.Ctx(), dir, []byte("v: 2\n"))) + + got, err := s.repo.ReadConfigYAML(s.Ctx(), dir) + s.Require().NoError(err) + s.Equal([]byte("v: 2\n"), got) +} diff --git a/internal/storage/domain/fs/suite_test.go b/internal/storage/domain/fs/suite_test.go new file mode 100644 index 000000000..430988d88 --- /dev/null +++ b/internal/storage/domain/fs/suite_test.go @@ -0,0 +1,37 @@ +package fs + +import ( + "context" + "path/filepath" + "testing" + + "github.com/stretchr/testify/suite" + + "github.com/steveyegge/beads/internal/storage/domain" +) + +type testSuite struct { + suite.Suite + repo domain.BeadsDirFSRepository +} + +func (s *testSuite) SetupTest() { + s.repo = NewBeadsDirFSRepository() +} + +func (s *testSuite) Ctx() context.Context { + return context.Background() +} + +func (s *testSuite) tmpRoot() string { + return s.T().TempDir() +} + +func (s *testSuite) beadsDir() (string, string) { + root := s.tmpRoot() + return root, filepath.Join(root, ".beads") +} + +func TestDomainFS(t *testing.T) { + suite.Run(t, &testSuite{}) +} diff --git a/internal/storage/domain/remote.go b/internal/storage/domain/remote.go index 8c8277714..ac32126e2 100644 --- a/internal/storage/domain/remote.go +++ b/internal/storage/domain/remote.go @@ -1,6 +1,9 @@ package domain -import "context" +import ( + "context" + "fmt" +) type DoltRemoteUseCase interface { CreateRemote(ctx context.Context, name, url string) error @@ -9,4 +12,70 @@ type DoltRemoteUseCase interface { ListRemotes(ctx context.Context) ([]Remote, error) } -type Remote struct{} +type Remote struct { + Name string + URL string +} + +type RemoteSQLRepository interface { + AddRemote(ctx context.Context, name, url string) error + RemoveRemote(ctx context.Context, name string) error + ListRemotes(ctx context.Context) ([]Remote, error) +} + +func NewDoltRemoteUseCase(remoteRepo RemoteSQLRepository) DoltRemoteUseCase { + return &doltRemoteUseCaseImpl{remoteRepo: remoteRepo} +} + +type doltRemoteUseCaseImpl struct { + remoteRepo RemoteSQLRepository +} + +var _ DoltRemoteUseCase = (*doltRemoteUseCaseImpl)(nil) + +func (u *doltRemoteUseCaseImpl) CreateRemote(ctx context.Context, name, url string) error { + if name == "" { + return fmt.Errorf("CreateRemote: name must not be empty") + } + if url == "" { + return fmt.Errorf("CreateRemote: url must not be empty") + } + if err := u.remoteRepo.AddRemote(ctx, name, url); err != nil { + return fmt.Errorf("CreateRemote %s: %w", name, err) + } + return nil +} + +func (u *doltRemoteUseCaseImpl) UpdateRemote(ctx context.Context, name, url string) error { + if name == "" { + return fmt.Errorf("UpdateRemote: name must not be empty") + } + if url == "" { + return fmt.Errorf("UpdateRemote: url must not be empty") + } + if err := u.remoteRepo.RemoveRemote(ctx, name); err != nil { + return fmt.Errorf("UpdateRemote %s: remove: %w", name, err) + } + if err := u.remoteRepo.AddRemote(ctx, name, url); err != nil { + return fmt.Errorf("UpdateRemote %s: add: %w", name, err) + } + return nil +} + +func (u *doltRemoteUseCaseImpl) DeleteRemote(ctx context.Context, name string) error { + if name == "" { + return fmt.Errorf("DeleteRemote: name must not be empty") + } + if err := u.remoteRepo.RemoveRemote(ctx, name); err != nil { + return fmt.Errorf("DeleteRemote %s: %w", name, err) + } + return nil +} + +func (u *doltRemoteUseCaseImpl) ListRemotes(ctx context.Context) ([]Remote, error) { + remotes, err := u.remoteRepo.ListRemotes(ctx) + if err != nil { + return nil, fmt.Errorf("ListRemotes: %w", err) + } + return remotes, nil +} diff --git a/internal/storage/fs/provider.go b/internal/storage/fs/provider.go new file mode 100644 index 000000000..01cfc556c --- /dev/null +++ b/internal/storage/fs/provider.go @@ -0,0 +1,31 @@ +package fs + +import ( + "github.com/steveyegge/beads/internal/storage/domain" + domainfs "github.com/steveyegge/beads/internal/storage/domain/fs" +) + +type FileSystemProvider interface { + BeadsDirFSUseCase() domain.BeadsDirFSUseCase +} + +func NewFileSystemProvider(adapters domain.BeadsDirFSAdapters) FileSystemProvider { + return &fileSystemProviderImpl{adapters: adapters} +} + +type fileSystemProviderImpl struct { + adapters domain.BeadsDirFSAdapters + beadsDirFSUseCase domain.BeadsDirFSUseCase +} + +var _ FileSystemProvider = (*fileSystemProviderImpl)(nil) + +func (p *fileSystemProviderImpl) BeadsDirFSUseCase() domain.BeadsDirFSUseCase { + if p.beadsDirFSUseCase == nil { + p.beadsDirFSUseCase = domain.NewBeadsDirFSUseCase( + domainfs.NewBeadsDirFSRepository(), + p.adapters, + ) + } + return p.beadsDirFSUseCase +} diff --git a/internal/storage/uow/doltserver_provider.go b/internal/storage/uow/doltserver_provider.go index 73af9a96c..637e37451 100644 --- a/internal/storage/uow/doltserver_provider.go +++ b/internal/storage/uow/doltserver_provider.go @@ -107,15 +107,28 @@ func (p *doltServerProvider) NewUOW(ctx context.Context) (UnitOfWork, error) { return NewUOW(ctx, p) } -func (p *doltServerProvider) NewTx(ctx context.Context) (Tx, error) { +func (p *doltServerProvider) Close(ctx context.Context) error { + if p.db == nil { + return nil + } + db := p.db + p.db = nil + return db.Close() +} + +func (p *doltServerProvider) BeginTx(ctx context.Context) (Tx, error) { conn, err := p.db.Conn(ctx) if err != nil { return nil, fmt.Errorf("uow: pin connection: %w", err) } + + _, err = conn.ExecContext(ctx, "START TRANSACTION;") + if err != nil { + return nil, fmt.Errorf("uow: failed to start transaction: %w", err) + } + return &doltServerTx{ - conn: conn, - vc: db.NewDoltVersionControlSQLRepository(conn), - targetBranch: p.defaultBranch, + conn: conn, }, nil } diff --git a/internal/storage/uow/doltserver_provider_test.go b/internal/storage/uow/doltserver_provider_test.go index 53c7d886b..e4e3afd70 100644 --- a/internal/storage/uow/doltserver_provider_test.go +++ b/internal/storage/uow/doltserver_provider_test.go @@ -20,10 +20,6 @@ import ( "github.com/stretchr/testify/require" ) -// shutdownOnInterrupt installs a SIGINT/SIGTERM handler that runs -// proxy.Shutdown(rootDir) and exits, so the proxy and child dolt sql-server -// don't survive an early test abort (e.g. Ctrl+C). The handler is removed via -// t.Cleanup on normal test completion. func shutdownOnInterrupt(t *testing.T, rootDir string) { t.Helper() ch := make(chan os.Signal, 1) @@ -111,8 +107,74 @@ func TestNewDoltServerUOWProvider_HappyPath(t *testing.T) { require.NoError(t, err) require.NotNil(t, provider) - impl := provider.(*doltServerProvider) - t.Cleanup(func() { _ = impl.db.Close() }) + t.Cleanup(func() { _ = provider.Close(context.Background()) }) +} + +func TestNewDoltServerUOWProvider_ConcurrentInstantiation(t *testing.T) { + testutil.RequireDoltBinary(t) + bin, err := exec.LookPath("dolt") + require.NoError(t, err) + + bdBin := buildBDBinary(t) + prev := proxy.ResolveExecutable + proxy.ResolveExecutable = func() (string, error) { return bdBin, nil } + t.Cleanup(func() { proxy.ResolveExecutable = prev }) + + t.Setenv("HOME", t.TempDir()) + + port, err := proxy.PickFreePort() + require.NoError(t, err) + storeRootDir := t.TempDir() + shutdownOnInterrupt(t, storeRootDir) + t.Cleanup(func() { + if err := proxy.Shutdown(storeRootDir); err != nil { + t.Logf("proxy.Shutdown(%s): %v", storeRootDir, err) + } + }) + cfgPath := writeServerConfig(t, port) + logPath := filepath.Join(t.TempDir(), "server.log") + + const concurrency = 10 + type result struct { + provider UnitOfWorkProvider + err error + } + results := make([]result, concurrency) + + var wg sync.WaitGroup + wg.Add(concurrency) + for i := 0; i < concurrency; i++ { + i := i + go func() { + defer wg.Done() + p, err := NewDoltServerUOWProvider( + context.Background(), + storeRootDir, + "beads", + logPath, + cfgPath, + proxy.BackendLocalServer, + "root", + "", + bin, + ) + results[i] = result{provider: p, err: err} + }() + } + wg.Wait() + + t.Cleanup(func() { + for _, r := range results { + if r.provider != nil { + _ = r.provider.Close(context.Background()) + } + } + }) + + for i, r := range results { + assert.NoErrorf(t, r.err, "provider %d", i) + assert.NotNilf(t, r.provider, "provider %d", i) + } } var ( diff --git a/internal/storage/uow/doltserver_tx.go b/internal/storage/uow/doltserver_tx.go index e56bc2090..078bf19f1 100644 --- a/internal/storage/uow/doltserver_tx.go +++ b/internal/storage/uow/doltserver_tx.go @@ -2,102 +2,31 @@ package uow import ( "context" - "crypto/rand" "database/sql" - "encoding/hex" "errors" - "fmt" - "strings" - db "github.com/steveyegge/beads/internal/storage/domain/db" + "github.com/steveyegge/beads/internal/storage/domain/db" ) type doltServerTx struct { - conn *sql.Conn - vc db.DoltVersionControlSQLRepository - tx *sql.Tx - branch string - targetBranch string - done bool + conn *sql.Conn + done bool } var _ Tx = (*doltServerTx)(nil) -func (t *doltServerTx) Begin(ctx context.Context) (*sql.Tx, error) { - if t.tx != nil { - return nil, errors.New("uow: Begin: already begun") - } - - success := false - defer func() { - if !success { - t.releaseConn() - } - }() - - branch, err := genRandomBranchName() - if err != nil { - return nil, err - } - - if err := t.vc.Branch(ctx, branch, t.targetBranch); err != nil { - return nil, fmt.Errorf("uow: create work branch %q from %q: %w", branch, t.targetBranch, err) - } - - if err := t.vc.Checkout(ctx, branch); err != nil { - _ = t.vc.Branch(ctx, "-d", branch) - return nil, fmt.Errorf("uow: checkout work branch %q: %w", branch, err) - } - - sqlTx, err := t.conn.BeginTx(ctx, nil) - if err != nil { - t.cleanupBranchBestEffort(ctx) - return nil, fmt.Errorf("uow: begin sql tx: %w", err) - } - - t.branch = branch - t.tx = sqlTx - success = true - - return sqlTx, nil +func (t *doltServerTx) Runner() db.Runner { + return t.conn } func (t *doltServerTx) Commit(ctx context.Context, message string) error { if t.done { return errors.New("uow: commit: already done") } - t.done = true - defer func() { - t.cleanupBranchBestEffort(ctx) - t.releaseConn() - }() - - if err := t.tx.Commit(); err != nil { - return fmt.Errorf("uow: commit sql tx: %w", err) - } - - if err := t.vc.Add(ctx, "-A"); err != nil { - return fmt.Errorf("uow: dolt add: %w", err) - } - - if err := t.vc.Commit(ctx, "-m", message); err != nil && !isNothingToCommit(err) { - return fmt.Errorf("uow: dolt commit: %w", err) - } - - if err := t.vc.Checkout(ctx, t.targetBranch); err != nil { - return fmt.Errorf("uow: checkout %s: %w", t.targetBranch, err) - } - - if err := t.vc.Merge(ctx, t.branch); err != nil { - return fmt.Errorf("uow: merge %s into %s: %w", t.branch, t.targetBranch, err) - } - - if err := t.vc.Branch(ctx, "-d", t.branch); err != nil { - return fmt.Errorf("uow: delete work branch %s: %w", t.branch, err) - } - - return nil + defer t.releaseConn() + _, err := t.conn.ExecContext(ctx, "CALL DOLT_COMMIT('-Am', ?);", message) + return err } func (t *doltServerTx) Rollback(ctx context.Context) error { @@ -106,18 +35,8 @@ func (t *doltServerTx) Rollback(ctx context.Context) error { } t.done = true defer t.releaseConn() - - var errs []error - if err := t.tx.Rollback(); err != nil && !errors.Is(err, sql.ErrTxDone) { - errs = append(errs, fmt.Errorf("uow: rollback sql tx: %w", err)) - } - if err := t.vc.Checkout(ctx, t.targetBranch); err != nil { - errs = append(errs, fmt.Errorf("uow: checkout %s on rollback: %w", t.targetBranch, err)) - } - if err := t.vc.Branch(ctx, "-d", t.branch); err != nil { - errs = append(errs, fmt.Errorf("uow: delete work branch %s on rollback: %w", t.branch, err)) - } - return errors.Join(errs...) + _, err := t.conn.ExecContext(ctx, "ROLLBACK;") + return err } func (t *doltServerTx) RollbackUnlessCommitted(ctx context.Context) { @@ -126,26 +45,9 @@ func (t *doltServerTx) RollbackUnlessCommitted(ctx context.Context) { } } -func (t *doltServerTx) cleanupBranchBestEffort(ctx context.Context) { - _ = t.vc.Checkout(ctx, t.targetBranch) - _ = t.vc.Branch(ctx, "-d", t.branch) -} - func (t *doltServerTx) releaseConn() { if t.conn != nil { _ = t.conn.Close() t.conn = nil } } - -func isNothingToCommit(err error) bool { - return err != nil && strings.Contains(err.Error(), "nothing to commit") -} - -func genRandomBranchName() (string, error) { - var buf [8]byte - if _, err := rand.Read(buf[:]); err != nil { - return "", fmt.Errorf("uow: gen random branch name: %w", err) - } - return "bd-" + hex.EncodeToString(buf[:]), nil -} diff --git a/internal/storage/uow/tx.go b/internal/storage/uow/tx.go index 93782dfde..85ac533a7 100644 --- a/internal/storage/uow/tx.go +++ b/internal/storage/uow/tx.go @@ -2,16 +2,17 @@ package uow import ( "context" - "database/sql" + + "github.com/steveyegge/beads/internal/storage/domain/db" ) type Tx interface { - Begin(ctx context.Context) (*sql.Tx, error) + Runner() db.Runner Commit(ctx context.Context, message string) error Rollback(ctx context.Context) error RollbackUnlessCommitted(ctx context.Context) } type TxProvider interface { - NewTx(ctx context.Context) (Tx, error) + BeginTx(ctx context.Context) (Tx, error) } diff --git a/internal/storage/uow/uow.go b/internal/storage/uow/uow.go index 8d77ea08a..cb8000e4c 100644 --- a/internal/storage/uow/uow.go +++ b/internal/storage/uow/uow.go @@ -1,29 +1,40 @@ package uow -import "context" +import ( + "context" + + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/storage/domain/db" +) type UnitOfWork interface { Close(ctx context.Context) Commit(ctx context.Context, message string) error + + ConfigUseCase() domain.ConfigUseCase + DoltRemoteUseCase() domain.DoltRemoteUseCase + BootstrapUseCase() domain.BootstrapUseCase } type UnitOfWorkProvider interface { NewUOW(ctx context.Context) (UnitOfWork, error) + Close(ctx context.Context) error } func NewUOW(ctx context.Context, p TxProvider) (UnitOfWork, error) { - tx, err := p.NewTx(ctx) + tx, err := p.BeginTx(ctx) if err != nil { return nil, err } - if _, err := tx.Begin(ctx); err != nil { - return nil, err - } return &baseUOW{tx: tx}, nil } type baseUOW struct { tx Tx + + configUseCase domain.ConfigUseCase + remoteUseCase domain.DoltRemoteUseCase + bootstrapUseCase domain.BootstrapUseCase } func (u *baseUOW) Commit(ctx context.Context, message string) error { @@ -33,3 +44,27 @@ func (u *baseUOW) Commit(ctx context.Context, message string) error { func (u *baseUOW) Close(ctx context.Context) { u.tx.RollbackUnlessCommitted(ctx) } + +func (u *baseUOW) ConfigUseCase() domain.ConfigUseCase { + if u.configUseCase == nil { + u.configUseCase = domain.NewConfigUseCase(db.NewConfigSQLRepository(u.tx.Runner())) + } + return u.configUseCase +} + +func (u *baseUOW) DoltRemoteUseCase() domain.DoltRemoteUseCase { + if u.remoteUseCase == nil { + u.remoteUseCase = domain.NewDoltRemoteUseCase(db.NewRemoteSQLRepository(u.tx.Runner())) + } + return u.remoteUseCase +} + +func (u *baseUOW) BootstrapUseCase() domain.BootstrapUseCase { + if u.bootstrapUseCase == nil { + u.bootstrapUseCase = domain.NewBootstrapUseCase( + db.NewConfigSQLRepository(u.tx.Runner()), + u.DoltRemoteUseCase(), + ) + } + return u.bootstrapUseCase +} From 98be00c92e4979e43e7156d051d9395a4eb93876 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?coffeegoddd=E2=98=95=EF=B8=8F=E2=9C=A8?= Date: Tue, 19 May 2026 15:37:37 -0700 Subject: [PATCH 2/5] /{cmd,internal}: refactoring --- cmd/bd/doctor/gitignore.go | 6 +- cmd/bd/doctor/gitignore_test.go | 2 +- cmd/bd/fs_adapters.go | 14 +- cmd/bd/init_proxied_server.go | 159 +++++------- cmd/bd/init_templates.go | 23 +- internal/storage/domain/beads.go | 126 ++++++--- internal/storage/domain/fs/beads.go | 244 ++++++++---------- internal/storage/domain/fs/beads_test.go | 298 +++++++++++++--------- internal/storage/domain/fs/suite_test.go | 26 +- internal/storage/domain/git.go | 211 +++++++++++++++ internal/storage/domain/git/git.go | 216 ++++++++++++++++ internal/storage/domain/git/git_test.go | 221 ++++++++++++++++ internal/storage/domain/git/suite_test.go | 58 +++++ internal/storage/fs/provider.go | 12 +- internal/storage/git/provider.go | 28 ++ 15 files changed, 1233 insertions(+), 411 deletions(-) create mode 100644 internal/storage/domain/git.go create mode 100644 internal/storage/domain/git/git.go create mode 100644 internal/storage/domain/git/git_test.go create mode 100644 internal/storage/domain/git/suite_test.go create mode 100644 internal/storage/git/provider.go diff --git a/cmd/bd/doctor/gitignore.go b/cmd/bd/doctor/gitignore.go index 85746cd4b..40b01b9e3 100644 --- a/cmd/bd/doctor/gitignore.go +++ b/cmd/bd/doctor/gitignore.go @@ -94,8 +94,8 @@ var ProjectGitignorePatterns = []string{ ".beads/proxieddb/", } -// projectGitignoreComment is the section header added to the project .gitignore -const projectGitignoreComment = "# Beads / Dolt files (added by bd init)" +// ProjectGitignoreHeader is the section header added to the project .gitignore +const ProjectGitignoreHeader = "# Beads / Dolt files (added by bd init)" // requiredPatterns are patterns that MUST be in .beads/.gitignore var requiredPatterns = []string{ @@ -712,7 +712,7 @@ func EnsureProjectGitignore(repoPath string) error { newContent += "\n" } - newContent += "\n" + projectGitignoreComment + "\n" + newContent += "\n" + ProjectGitignoreHeader + "\n" for _, pattern := range toAdd { newContent += pattern + "\n" } diff --git a/cmd/bd/doctor/gitignore_test.go b/cmd/bd/doctor/gitignore_test.go index b1191e203..acaff5d03 100644 --- a/cmd/bd/doctor/gitignore_test.go +++ b/cmd/bd/doctor/gitignore_test.go @@ -1812,7 +1812,7 @@ func TestEnsureProjectGitignore_CreatesFile(t *testing.T) { if !strings.Contains(contentStr, "*.db") { t.Error("Expected *.db pattern in .gitignore") } - if !strings.Contains(contentStr, projectGitignoreComment) { + if !strings.Contains(contentStr, ProjectGitignoreHeader) { t.Error("Expected section comment in .gitignore") } } diff --git a/cmd/bd/fs_adapters.go b/cmd/bd/fs_adapters.go index 241fd7a74..c55b25ae0 100644 --- a/cmd/bd/fs_adapters.go +++ b/cmd/bd/fs_adapters.go @@ -1,18 +1,24 @@ package main import ( + "github.com/steveyegge/beads/cmd/bd/doctor" "github.com/steveyegge/beads/cmd/bd/setup" "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/storage/domain" "github.com/steveyegge/beads/internal/templates/agents" ) +func newBeadsDirTemplates() domain.BeadsDirTemplates { + return domain.BeadsDirTemplates{ + BeadsGitignore: doctor.GitignoreTemplate, + ProjectGitignoreHeader: doctor.ProjectGitignoreHeader, + ProjectGitignorePatterns: doctor.ProjectGitignorePatterns, + Readme: BeadsReadmeTemplate, + } +} + func newFileSystemAdapters() domain.BeadsDirFSAdapters { return domain.BeadsDirFSAdapters{ - ResolveBeadsDir: func() domain.BeadsDirResolution { - beadsDir, hasExplicit := resolveBeadsDirForInit() - return domain.BeadsDirResolution{BeadsDir: beadsDir, HasExplicit: hasExplicit} - }, ApplyNoCOW: applyNoCOW, WriteLocalVersion: writeLocalVersion, SetupForkExclude: setupForkExclude, diff --git a/cmd/bd/init_proxied_server.go b/cmd/bd/init_proxied_server.go index 340f3bd2b..86eaccdd4 100644 --- a/cmd/bd/init_proxied_server.go +++ b/cmd/bd/init_proxied_server.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" "os" - "os/exec" "path/filepath" "strings" "time" @@ -15,11 +14,10 @@ import ( "github.com/steveyegge/beads/internal/beads" "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/configfile" - "github.com/steveyegge/beads/internal/git" "github.com/steveyegge/beads/internal/storage/domain" "github.com/steveyegge/beads/internal/storage/fs" + "github.com/steveyegge/beads/internal/storage/git" "github.com/steveyegge/beads/internal/ui" - "github.com/steveyegge/beads/internal/utils" ) type initProxiedServerInput struct { @@ -62,8 +60,14 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie FatalError("%v", err) } - fsProvider := fs.NewFileSystemProvider(newFileSystemAdapters()) + cwd, err := os.Getwd() + if err != nil { + FatalError("failed to get current directory: %v", err) + } + + fsProvider := fs.NewFileSystemProvider(cwd, newBeadsDirTemplates(), newFileSystemAdapters()) fsUseCase := fsProvider.BeadsDirFSUseCase() + gitUC := git.NewGitProvider(cwd).GitUseCase() if in.stealth { if err := fsUseCase.SetupStealthMode(ctx, !in.quiet); err != nil { @@ -74,13 +78,16 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie prefix := resolveInitPrefix(in.prefix) - cwd, err := os.Getwd() + proxiedInit, err := fsUseCase.ResolveProxiedInit(ctx, domain.ResolveProxiedInitParams{ + Prefix: prefix, + DBFlag: in.database, + }) if err != nil { - FatalError("failed to get current directory: %v", err) + FatalError("resolving proxied init: %v", err) } + beadsDir, hasExplicitBeadsDir := proxiedInit.BeadsDir, proxiedInit.HasExplicit + dbName, projectID := proxiedInit.DBName, proxiedInit.ProjectID - beadsDirResolution := fsUseCase.ResolveBeadsDir(ctx) - beadsDir, hasExplicitBeadsDir := beadsDirResolution.BeadsDir, beadsDirResolution.HasExplicit if strings.Contains(filepath.Clean(cwd), string(filepath.Separator)+".beads"+string(filepath.Separator)) || strings.HasSuffix(filepath.Clean(cwd), string(filepath.Separator)+".beads") { fmt.Fprintf(os.Stderr, "Error: cannot initialize bd inside a .beads directory\n") @@ -98,20 +105,16 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie filepath.Clean(beadsDirAbs) == filepath.Clean(cwdAbs) useLocalBeads := !hasExplicitBeadsDir || beadsDirIsLocal - if !isGitRepo() && !hasExplicitBeadsDir { - gitInitCmd := exec.Command("git", "init") - if output, err := gitInitCmd.CombinedOutput(); err != nil { - FatalError("failed to initialize git repository: %v\n%s", err, output) + if !hasExplicitBeadsDir { + res, err := gitUC.EnsureGitRepo(ctx) + if err != nil { + FatalError("failed to initialize git repository: %v", err) } - git.ResetCaches() - if !in.quiet { + if res.DidInit && !in.quiet { fmt.Printf(" %s Initialized git repository\n", ui.RenderPass("✓")) } } - dbName := resolveProxiedDatabaseName(beadsDir, prefix, in.database) - projectID := resolveProjectID(beadsDir) - metadataBody, err := composeProxiedServerMetadataJSON(proxiedMetadataInputs{ dbName: dbName, projectID: projectID, @@ -125,13 +128,10 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie configYAMLBody := renderInitConfigYAML("", false) fsParams := domain.InitializeBeadsDirParams{ - BeadsDir: beadsDir, - MetadataJSONBody: metadataBody, - ConfigYAMLBody: configYAMLBody, - SetNoCOW: true, - } - if useLocalBeads && beadsDirIsLocal { - fsParams.RepoRoot = cwd + MetadataJSONBody: metadataBody, + ConfigYAMLBody: configYAMLBody, + SetNoCOW: true, + WriteProjectGitignore: useLocalBeads && beadsDirIsLocal, } if useLocalBeads { fsParams.LocalVersion = Version @@ -176,7 +176,7 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie } else if !in.quiet { fmt.Fprintf(os.Stderr, "Warning: could not compute clone ID: %v\n", err) } - if remoteURL := resolveProxiedInitRemoteURL(in); remoteURL != "" { + if remoteURL := resolveProxiedInitRemoteURL(ctx, gitUC, in); remoteURL != "" { bootstrapParams.RemoteName = "origin" bootstrapParams.RemoteURL = remoteURL } @@ -196,6 +196,7 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie useLocalBeads: useLocalBeads, remoteURL: bootstrapParams.RemoteURL, fsUseCase: fsUseCase, + gitUC: gitUC, }) } @@ -220,38 +221,7 @@ func resolveInitPrefix(flagPrefix string) string { return prefix } -func resolveBeadsDirForInit() (beadsDir string, hasExplicit bool) { - if envBeadsDir := os.Getenv("BEADS_DIR"); envBeadsDir != "" { - return utils.CanonicalizePath(envBeadsDir), true - } - beadsDir = beads.GetWorktreeFallbackBeadsDir() - if beadsDir == "" { - beadsDir = beads.FollowRedirect(filepath.Join(".", ".beads")) - } - return beadsDir, false -} - -func resolveProxiedDatabaseName(beadsDir, prefix, dbFlag string) string { - if dbFlag != "" { - return dbFlag - } - if cfg, _ := configfile.Load(beadsDir); cfg != nil && cfg.DoltDatabase != "" { - return cfg.DoltDatabase - } - if prefix != "" { - return strings.ReplaceAll(prefix, "-", "_") - } - return configfile.DefaultDoltDatabase -} - -func resolveProjectID(beadsDir string) string { - if cfg, _ := configfile.Load(beadsDir); cfg != nil && cfg.ProjectID != "" { - return cfg.ProjectID - } - return configfile.GenerateProjectID() -} - -func resolveProxiedInitRemoteURL(in initProxiedServerInput) string { +func resolveProxiedInitRemoteURL(ctx context.Context, gitUC domain.GitUseCase, in initProxiedServerInput) string { url, source := resolveInitConfiguredSyncRemote(in.initRemote, in.initRemoteChanged, resolveSyncRemote) if url != "" { return url @@ -259,8 +229,8 @@ func resolveProxiedInitRemoteURL(in initProxiedServerInput) string { if source != initSyncRemoteNone { return "" } - if !in.stealth && isGitRepo() && !isBareGitRepo() { - if originURL, err := gitOriginGetURL(); err == nil && originURL != "" { + if !in.stealth { + if originURL, err := gitUC.OriginRemoteURL(ctx); err == nil && originURL != "" { return normalizeRemoteURL(originURL) } } @@ -310,20 +280,18 @@ type runInitTailContext struct { useLocalBeads bool remoteURL string fsUseCase domain.BeadsDirFSUseCase + gitUC domain.GitUseCase } func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initProxiedServerInput, t runInitTailContext) { - if isGitRepo() { + if t.gitUC.IsGitRepo(ctx) { role := in.roleFlag if role == "" { role = "maintainer" } - if _, hasRole := getBeadsRole(); !hasRole { - if err := setBeadsRole(role); err != nil && !in.quiet { - fmt.Fprintf(os.Stderr, "Warning: failed to set beads.role: %v\n", err) - } - } else if in.roleFlag != "" { - if err := setBeadsRole(role); err != nil && !in.quiet { + _, hasRole, _ := t.gitUC.BeadsRole(ctx) + if !hasRole || in.roleFlag != "" { + if err := t.gitUC.SetBeadsRole(ctx, role); err != nil && !in.quiet { fmt.Fprintf(os.Stderr, "Warning: failed to set beads.role: %v\n", err) } } @@ -334,8 +302,8 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr if err := t.fsUseCase.SetupForkExclude(ctx, !in.quiet); err != nil { fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err) } - } else if !in.stealth && isGitRepo() { - if isFork, upstreamURL := detectForkSetup(); isFork { + } else if !in.stealth && t.gitUC.IsGitRepo(ctx) { + if isFork, upstreamURL, _ := t.gitUC.DetectFork(ctx); isFork { if in.nonInteractive { if err := t.fsUseCase.SetupForkExclude(ctx, !in.quiet); err != nil { fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err) @@ -359,8 +327,8 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr if hooksInstalled() && !in.quiet { fmt.Printf(" Updating hooks to version %s...\n", Version) } - isJJ := git.IsJujutsuRepo() - isColocated := git.IsColocatedJJGit() + isJJ := t.gitUC.IsJujutsuRepo(ctx) + isColocated := t.gitUC.IsColocatedJJGit(ctx) switch { case isJJ && !isColocated: if !in.quiet { @@ -373,7 +341,7 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr fmt.Printf(" Hooks installed (jujutsu mode - no staging)\n") } default: - if isGitRepo() { + if t.gitUC.IsGitRepo(ctx) { hooksParams := domain.HooksInstallParams{ HookNames: managedHookNames, BeadsHooks: true, @@ -404,7 +372,7 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr if resolvedAgentsFile == "" { resolvedAgentsFile = config.SafeAgentsFile() } - if isBareGitRepo() { + if t.gitUC.IsBareGitRepo(ctx) { if !in.quiet { fmt.Printf(" Skipping %s generation in bare repository\n", resolvedAgentsFile) } @@ -419,41 +387,34 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr } } - if !in.stealth && !in.skipAgents && !isBareGitRepo() { + if !in.stealth && !in.skipAgents && !t.gitUC.IsBareGitRepo(ctx) { if err := t.fsUseCase.InstallClaudeProject(ctx, in.stealth); err != nil && !in.quiet { fmt.Fprintf(os.Stderr, "Warning: failed to setup Claude hooks: %v\n", err) } } - if !in.stealth && isGitRepo() && t.useLocalBeads { - gitAddCmd := exec.Command("git", "add", ".beads/") - if _, addErr := gitAddCmd.CombinedOutput(); addErr == nil { - agentsFileToStage := config.SafeAgentsFile() - if _, statErr := os.Stat(agentsFileToStage); statErr == nil { - _ = exec.Command("git", "add", agentsFileToStage).Run() - } - if _, statErr := os.Stat(filepath.Join(".claude", "settings.json")); statErr == nil { - _ = exec.Command("git", "add", filepath.Join(".claude", "settings.json")).Run() - } - if _, statErr := os.Stat("CLAUDE.md"); statErr == nil { - _ = exec.Command("git", "add", "CLAUDE.md").Run() - } - if _, statErr := os.Stat(".gitignore"); statErr == nil { - _ = exec.Command("git", "add", ".gitignore").Run() - } - commitCmd := exec.Command("git", "commit", "--no-verify", "-m", "bd init: initialize beads issue tracking") - if commitOut, commitErr := commitCmd.CombinedOutput(); commitErr != nil { - if !in.quiet && !strings.Contains(string(commitOut), "nothing to commit") { - fmt.Fprintf(os.Stderr, "Warning: failed to commit beads files: %v\n", commitErr) - } - } else if !in.quiet { - fmt.Printf(" %s Committed beads files to git\n", ui.RenderPass("✓")) - } + if !in.stealth && t.gitUC.IsGitRepo(ctx) && t.useLocalBeads { + commitResult, err := t.gitUC.CommitInitArtifacts(ctx, domain.CommitInitArtifactsParams{ + BeadsDir: ".beads/", + OptionalPaths: []string{ + config.SafeAgentsFile(), + filepath.Join(".claude", "settings.json"), + "CLAUDE.md", + ".gitignore", + }, + Message: "bd init: initialize beads issue tracking", + NoVerify: true, + }) + switch { + case err != nil && !in.quiet: + fmt.Fprintf(os.Stderr, "Warning: failed to commit beads files: %v\n", err) + case err == nil && commitResult.DidCommit && !in.quiet: + fmt.Printf(" %s Committed beads files to git\n", ui.RenderPass("✓")) } } - if isGitRepo() && !in.quiet { - if gitHasAnyRemotes() && !gitHasUpstream() { + if t.gitUC.IsGitRepo(ctx) && !in.quiet { + if t.gitUC.HasAnyRemotes(ctx) && !t.gitUC.HasUpstream(ctx) { fmt.Fprintf(os.Stderr, "\n%s Git upstream not configured\n", ui.RenderWarn("⚠")) fmt.Fprintf(os.Stderr, " For sync workflows, set your upstream with:\n") fmt.Fprintf(os.Stderr, " %s\n\n", ui.RenderAccent("git remote add upstream ")) diff --git a/cmd/bd/init_templates.go b/cmd/bd/init_templates.go index 6a2395944..4ea3bb874 100644 --- a/cmd/bd/init_templates.go +++ b/cmd/bd/init_templates.go @@ -97,16 +97,8 @@ func renderInitConfigYAML(prefix string, noDbMode bool) []byte { return []byte(body) } -// createReadme creates the README.md file in the .beads directory -func createReadme(beadsDir string) error { - readmePath := filepath.Join(beadsDir, "README.md") - - // Skip if already exists - if _, err := os.Stat(readmePath); err == nil { - return nil - } - - readmeTemplate := `# Beads - AI-Native Issue Tracking +// BeadsReadmeTemplate is the canonical .beads/README.md content written during init. +const BeadsReadmeTemplate = `# Beads - AI-Native Issue Tracking Welcome to Beads! This repository uses **Beads** for issue tracking - a modern, AI-native tool designed to live directly in your codebase alongside your code. @@ -189,9 +181,18 @@ bd create "Try out Beads" *Beads: Issue tracking that moves at the speed of thought* ⚡ ` +// createReadme creates the README.md file in the .beads directory. +func createReadme(beadsDir string) error { + readmePath := filepath.Join(beadsDir, "README.md") + + // Skip if already exists + if _, err := os.Stat(readmePath); err == nil { + return nil + } + // Write README.md (0644 is standard for markdown files) // #nosec G306 - README needs to be readable - if err := os.WriteFile(readmePath, []byte(readmeTemplate), 0644); err != nil { + if err := os.WriteFile(readmePath, []byte(BeadsReadmeTemplate), 0644); err != nil { return fmt.Errorf("failed to write README.md: %w", err) } diff --git a/internal/storage/domain/beads.go b/internal/storage/domain/beads.go index 29a043cde..09364f5db 100644 --- a/internal/storage/domain/beads.go +++ b/internal/storage/domain/beads.go @@ -4,25 +4,33 @@ import ( "context" "fmt" "path/filepath" + "strings" + + "github.com/steveyegge/beads/internal/configfile" ) type BeadsDirFSRepository interface { - CreateBeadsDir(ctx context.Context, beadsDir string) error - BeadsDirExists(ctx context.Context, beadsDir string) (bool, error) - WriteBeadsGitignore(ctx context.Context, beadsDir string) error - BeadsGitignoreExists(ctx context.Context, beadsDir string) (bool, error) - WriteProjectGitignore(ctx context.Context, repoRoot string) error - ProjectGitignoreExists(ctx context.Context, repoRoot string) (bool, error) - WriteInteractionsLog(ctx context.Context, beadsDir string) error - WriteReadme(ctx context.Context, beadsDir string) error - WriteMetadataJSON(ctx context.Context, beadsDir string, content []byte) error - ReadMetadataJSON(ctx context.Context, beadsDir string) ([]byte, error) - WriteConfigYAML(ctx context.Context, beadsDir string, content []byte) error - ReadConfigYAML(ctx context.Context, beadsDir string) ([]byte, error) + ResolveBeadsDirPath(ctx context.Context) BeadsDirResolution + BeadsDirIsLocal(ctx context.Context) bool + + CreateBeadsDir(ctx context.Context) error + BeadsDirExists(ctx context.Context) (bool, error) + WriteBeadsGitignore(ctx context.Context) error + BeadsGitignoreExists(ctx context.Context) (bool, error) + WriteProjectGitignore(ctx context.Context) error + ProjectGitignoreExists(ctx context.Context) (bool, error) + WriteInteractionsLog(ctx context.Context) error + WriteReadme(ctx context.Context) error + WriteMetadataJSON(ctx context.Context, content []byte) error + ReadMetadataJSON(ctx context.Context) ([]byte, error) + WriteConfigYAML(ctx context.Context, content []byte) error + ReadConfigYAML(ctx context.Context) ([]byte, error) + ReadBeadsConfig(ctx context.Context) (*configfile.Config, error) } type BeadsDirFSUseCase interface { ResolveBeadsDir(ctx context.Context) BeadsDirResolution + ResolveProxiedInit(ctx context.Context, params ResolveProxiedInitParams) (ResolveProxiedInitResult, error) InitializeBeadsDir(ctx context.Context, params InitializeBeadsDirParams) (InitializeBeadsDirResult, error) SetupForkExclude(ctx context.Context, verbose bool) error SetupStealthMode(ctx context.Context, verbose bool) error @@ -38,12 +46,36 @@ type BeadsDirResolution struct { HasExplicit bool } +type ResolveProxiedInitParams struct { + Prefix string + DBFlag string +} + +type ResolveProxiedInitResult struct { + BeadsDir string + HasExplicit bool + DBName string + ProjectID string +} + +// BeadsDirTemplates carries the text bodies the repository writes during init. +// Passing them in lets the CLI keep canonical copies (e.g. doctor.GitignoreTemplate) +// rather than maintaining duplicates inside the storage layer. +type BeadsDirTemplates struct { + BeadsGitignore string + ProjectGitignoreHeader string + ProjectGitignorePatterns []string + Readme string +} + type InitializeBeadsDirParams struct { - BeadsDir string - RepoRoot string MetadataJSONBody []byte ConfigYAMLBody []byte + // WriteProjectGitignore, when true, appends Dolt/beads patterns to the + // project-root .gitignore (workDir/.gitignore). + WriteProjectGitignore bool + // SetNoCOW, when true, applies FS_NOCOW_FL to BeadsDir after creation. // Best-effort: failures surface in InitializeBeadsDirResult.NoCOWErr, // not the returned error. @@ -80,7 +112,6 @@ type AgentsFileParams struct { // CLI-side helper implementations. Each adapter is optional at the type // level; methods that depend on a nil adapter return a configuration error. type BeadsDirFSAdapters struct { - ResolveBeadsDir func() BeadsDirResolution ApplyNoCOW func(path string) error WriteLocalVersion func(path, version string) error SetupForkExclude func(verbose bool) error @@ -104,52 +135,83 @@ type beadsDirFSUseCaseImpl struct { var _ BeadsDirFSUseCase = (*beadsDirFSUseCaseImpl)(nil) func (u *beadsDirFSUseCaseImpl) ResolveBeadsDir(ctx context.Context) BeadsDirResolution { - if u.adapters.ResolveBeadsDir == nil { - return BeadsDirResolution{} + return u.fsRepo.ResolveBeadsDirPath(ctx) +} + +func (u *beadsDirFSUseCaseImpl) ResolveProxiedInit(ctx context.Context, params ResolveProxiedInitParams) (ResolveProxiedInitResult, error) { + resolution := u.fsRepo.ResolveBeadsDirPath(ctx) + result := ResolveProxiedInitResult{ + BeadsDir: resolution.BeadsDir, + HasExplicit: resolution.HasExplicit, } - return u.adapters.ResolveBeadsDir() + + cfg, err := u.fsRepo.ReadBeadsConfig(ctx) + if err != nil { + return ResolveProxiedInitResult{}, fmt.Errorf("ResolveProxiedInit: read config: %w", err) + } + + result.DBName = resolveDoltDatabaseName(cfg, params.Prefix, params.DBFlag) + result.ProjectID = resolveProjectID(cfg) + return result, nil +} + +func resolveDoltDatabaseName(cfg *configfile.Config, prefix, dbFlag string) string { + if dbFlag != "" { + return dbFlag + } + if cfg != nil && cfg.DoltDatabase != "" { + return cfg.DoltDatabase + } + if prefix != "" { + return strings.ReplaceAll(prefix, "-", "_") + } + return configfile.DefaultDoltDatabase +} + +func resolveProjectID(cfg *configfile.Config) string { + if cfg != nil && cfg.ProjectID != "" { + return cfg.ProjectID + } + return configfile.GenerateProjectID() } func (u *beadsDirFSUseCaseImpl) InitializeBeadsDir(ctx context.Context, params InitializeBeadsDirParams) (InitializeBeadsDirResult, error) { - if params.BeadsDir == "" { - return InitializeBeadsDirResult{}, fmt.Errorf("InitializeBeadsDir: BeadsDir must not be empty") - } - - if err := u.fsRepo.CreateBeadsDir(ctx, params.BeadsDir); err != nil { + if err := u.fsRepo.CreateBeadsDir(ctx); err != nil { return InitializeBeadsDirResult{}, err } - if err := u.fsRepo.WriteBeadsGitignore(ctx, params.BeadsDir); err != nil { + if err := u.fsRepo.WriteBeadsGitignore(ctx); err != nil { return InitializeBeadsDirResult{}, err } if len(params.MetadataJSONBody) > 0 { - if err := u.fsRepo.WriteMetadataJSON(ctx, params.BeadsDir, params.MetadataJSONBody); err != nil { + if err := u.fsRepo.WriteMetadataJSON(ctx, params.MetadataJSONBody); err != nil { return InitializeBeadsDirResult{}, err } } if len(params.ConfigYAMLBody) > 0 { - if err := u.fsRepo.WriteConfigYAML(ctx, params.BeadsDir, params.ConfigYAMLBody); err != nil { + if err := u.fsRepo.WriteConfigYAML(ctx, params.ConfigYAMLBody); err != nil { return InitializeBeadsDirResult{}, err } } - if err := u.fsRepo.WriteInteractionsLog(ctx, params.BeadsDir); err != nil { + if err := u.fsRepo.WriteInteractionsLog(ctx); err != nil { return InitializeBeadsDirResult{}, err } - if err := u.fsRepo.WriteReadme(ctx, params.BeadsDir); err != nil { + if err := u.fsRepo.WriteReadme(ctx); err != nil { return InitializeBeadsDirResult{}, err } - if params.RepoRoot != "" { - if err := u.fsRepo.WriteProjectGitignore(ctx, params.RepoRoot); err != nil { + if params.WriteProjectGitignore { + if err := u.fsRepo.WriteProjectGitignore(ctx); err != nil { return InitializeBeadsDirResult{}, err } } var result InitializeBeadsDirResult if params.SetNoCOW && u.adapters.ApplyNoCOW != nil { - result.NoCOWErr = u.adapters.ApplyNoCOW(params.BeadsDir) + result.NoCOWErr = u.adapters.ApplyNoCOW(u.fsRepo.ResolveBeadsDirPath(ctx).BeadsDir) } if params.LocalVersion != "" && u.adapters.WriteLocalVersion != nil { + beadsDir := u.fsRepo.ResolveBeadsDirPath(ctx).BeadsDir result.LocalVersionErr = u.adapters.WriteLocalVersion( - filepath.Join(params.BeadsDir, ".local_version"), + filepath.Join(beadsDir, ".local_version"), params.LocalVersion, ) } diff --git a/internal/storage/domain/fs/beads.go b/internal/storage/domain/fs/beads.go index 98409c7a1..4ee254bca 100644 --- a/internal/storage/domain/fs/beads.go +++ b/internal/storage/domain/fs/beads.go @@ -10,159 +10,125 @@ import ( "path/filepath" "strings" + "github.com/steveyegge/beads/internal/beads" "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/configfile" "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/utils" ) -const beadsGitignoreTemplate = `# Dolt database (managed by Dolt, not git) -dolt/ -embeddeddolt/ -proxieddb/ - -# Runtime files -bd.sock -bd.sock.startlock -sync-state.json -last-touched -.exclusive-lock - -# Daemon runtime (lock, log, pid) -daemon.* - -# Push state (runtime, per-machine) -push-state.json - -# Lock files (various runtime locks) -*.lock - -# Credential key (encryption key for federation peer auth — never commit) -.beads-credential-key - -# Local version tracking (prevents upgrade notification spam after git ops) -.local_version - -# Worktree redirect file (contains relative path to main repo's .beads/) -# Must not be committed as paths would be wrong in other clones -redirect - -# Sync state (local-only, per-machine) -# These files are machine-specific and should not be shared across clones -.sync.lock -export-state/ -export-state.json - -# Ephemeral store (SQLite - wisps/molecules, intentionally not versioned) -ephemeral.sqlite3 -ephemeral.sqlite3-journal -ephemeral.sqlite3-wal -ephemeral.sqlite3-shm - -# Dolt server management (auto-started by bd) -dolt-server.pid -dolt-server.log -dolt-server.lock -dolt-server.port -dolt-server.activity - -# Corrupt backup directories (created by bd doctor --fix recovery) -*.corrupt.backup/ - -# Backup data (auto-exported JSONL, local-only) -backup/ - -# Per-project environment file (Dolt connection config, GH#2520) -.env - -# Legacy files (from pre-Dolt versions) -*.db -*.db?* -*.db-journal -*.db-wal -*.db-shm -db.sqlite -bd.db -# NOTE: Do NOT add negation patterns here. -# They would override fork protection in .git/info/exclude. -# Config files (metadata.json, config.yaml) are tracked by git by default -# since no pattern above ignores them. -` - -var projectGitignorePatterns = []string{ - ".dolt/", - "*.db", - ".beads-credential-key", - ".beads/proxieddb/", +// NewBeadsDirFSRepository binds the repository to a project working directory +// and the canonical templates the caller wants written into .beads/. Paths are +// derived from workDir at construction time; the BEADS_DIR env variable, if set, +// still overrides the .beads location (HasExplicit will be true in that case). +func NewBeadsDirFSRepository(workDir string, templates domain.BeadsDirTemplates) domain.BeadsDirFSRepository { + beadsDir, hasExplicit := resolveBeadsDir(workDir) + return &beadsDirFSRepositoryImpl{ + workDir: workDir, + beadsDir: beadsDir, + hasExplicit: hasExplicit, + templates: templates, + } } -const projectGitignoreHeader = "# Beads / Dolt files (added by bd init)" - -const beadsReadmeTemplate = `# Beads - -This directory is managed by [beads](https://github.com/steveyegge/beads). -Run ` + "`bd help`" + ` for available commands. -` - -func NewBeadsDirFSRepository() domain.BeadsDirFSRepository { - return &beadsDirFSRepositoryImpl{} +type beadsDirFSRepositoryImpl struct { + workDir string + beadsDir string + hasExplicit bool + templates domain.BeadsDirTemplates } -type beadsDirFSRepositoryImpl struct{} - var _ domain.BeadsDirFSRepository = (*beadsDirFSRepositoryImpl)(nil) -func (r *beadsDirFSRepositoryImpl) CreateBeadsDir(ctx context.Context, beadsDir string) error { - if beadsDir == "" { - return fmt.Errorf("fs: CreateBeadsDir: beadsDir must not be empty") +func resolveBeadsDir(workDir string) (string, bool) { + if envBeadsDir := os.Getenv("BEADS_DIR"); envBeadsDir != "" { + return utils.CanonicalizePath(envBeadsDir), true } - if err := os.MkdirAll(beadsDir, config.BeadsDirPerm); err != nil { - return fmt.Errorf("fs: CreateBeadsDir: mkdir %s: %w", beadsDir, err) + // GetWorktreeFallbackBeadsDir still uses cwd-derived git context; in + // practice init runs with workDir == cwd, so this is consistent. + if dir := beads.GetWorktreeFallbackBeadsDir(); dir != "" { + return dir, false } - if _, err := config.FixBeadsDirPermissions(beadsDir); err != nil { - return fmt.Errorf("fs: CreateBeadsDir: fix perms %s: %w", beadsDir, err) + return beads.FollowRedirect(filepath.Join(workDir, ".beads")), false +} + +func (r *beadsDirFSRepositoryImpl) ResolveBeadsDirPath(ctx context.Context) domain.BeadsDirResolution { + return domain.BeadsDirResolution{BeadsDir: r.beadsDir, HasExplicit: r.hasExplicit} +} + +func (r *beadsDirFSRepositoryImpl) BeadsDirIsLocal(ctx context.Context) bool { + workDirAbs, err := filepath.Abs(r.workDir) + if err != nil { + return false + } + beadsDirAbs, err := filepath.Abs(r.beadsDir) + if err != nil { + return false + } + return strings.HasPrefix(beadsDirAbs, filepath.Clean(workDirAbs)+string(filepath.Separator)) || + filepath.Clean(beadsDirAbs) == filepath.Clean(workDirAbs) +} + +func (r *beadsDirFSRepositoryImpl) CreateBeadsDir(ctx context.Context) error { + if r.beadsDir == "" { + return fmt.Errorf("fs: CreateBeadsDir: beadsDir not resolved") + } + if err := os.MkdirAll(r.beadsDir, config.BeadsDirPerm); err != nil { + return fmt.Errorf("fs: CreateBeadsDir: mkdir %s: %w", r.beadsDir, err) + } + if _, err := config.FixBeadsDirPermissions(r.beadsDir); err != nil { + return fmt.Errorf("fs: CreateBeadsDir: fix perms %s: %w", r.beadsDir, err) } return nil } -func (r *beadsDirFSRepositoryImpl) BeadsDirExists(ctx context.Context, beadsDir string) (bool, error) { - info, err := os.Stat(beadsDir) +func (r *beadsDirFSRepositoryImpl) BeadsDirExists(ctx context.Context) (bool, error) { + info, err := os.Stat(r.beadsDir) if errors.Is(err, os.ErrNotExist) { return false, nil } if err != nil { - return false, fmt.Errorf("fs: BeadsDirExists: stat %s: %w", beadsDir, err) + return false, fmt.Errorf("fs: BeadsDirExists: stat %s: %w", r.beadsDir, err) } return info.IsDir(), nil } -func (r *beadsDirFSRepositoryImpl) WriteBeadsGitignore(ctx context.Context, beadsDir string) error { - path := filepath.Join(beadsDir, ".gitignore") - // #nosec G304 -- path joined under caller-supplied beadsDir - if existing, err := os.ReadFile(path); err == nil && bytes.Equal(existing, []byte(beadsGitignoreTemplate)) { +func (r *beadsDirFSRepositoryImpl) WriteBeadsGitignore(ctx context.Context) error { + if r.templates.BeadsGitignore == "" { + return fmt.Errorf("fs: WriteBeadsGitignore: template not configured") + } + path := filepath.Join(r.beadsDir, ".gitignore") + body := []byte(r.templates.BeadsGitignore) + // #nosec G304 -- path joined under bound beadsDir + if existing, err := os.ReadFile(path); err == nil && bytes.Equal(existing, body) { return nil } - if err := os.WriteFile(path, []byte(beadsGitignoreTemplate), 0600); err != nil { + if err := os.WriteFile(path, body, 0600); err != nil { return fmt.Errorf("fs: WriteBeadsGitignore: %w", err) } return nil } -func (r *beadsDirFSRepositoryImpl) BeadsGitignoreExists(ctx context.Context, beadsDir string) (bool, error) { - return fileExists(filepath.Join(beadsDir, ".gitignore"), "fs: BeadsGitignoreExists") +func (r *beadsDirFSRepositoryImpl) BeadsGitignoreExists(ctx context.Context) (bool, error) { + return fileExists(filepath.Join(r.beadsDir, ".gitignore"), "fs: BeadsGitignoreExists") } -func (r *beadsDirFSRepositoryImpl) WriteProjectGitignore(ctx context.Context, repoRoot string) error { - if repoRoot == "" { - return fmt.Errorf("fs: WriteProjectGitignore: repoRoot must not be empty") +func (r *beadsDirFSRepositoryImpl) WriteProjectGitignore(ctx context.Context) error { + if r.workDir == "" { + return fmt.Errorf("fs: WriteProjectGitignore: workDir not set") } - path := filepath.Join(repoRoot, ".gitignore") - // #nosec G304 -- path joined under caller-supplied repoRoot + if len(r.templates.ProjectGitignorePatterns) == 0 { + return fmt.Errorf("fs: WriteProjectGitignore: patterns not configured") + } + path := filepath.Join(r.workDir, ".gitignore") + // #nosec G304 -- path joined under bound workDir existing, err := os.ReadFile(path) if err != nil && !errors.Is(err, os.ErrNotExist) { return fmt.Errorf("fs: WriteProjectGitignore: read: %w", err) } var toAdd []string - for _, pattern := range projectGitignorePatterns { + for _, pattern := range r.templates.ProjectGitignorePatterns { if !containsLine(existing, pattern) { toAdd = append(toAdd, pattern) } @@ -176,11 +142,11 @@ func (r *beadsDirFSRepositoryImpl) WriteProjectGitignore(ctx context.Context, re if len(existing) > 0 && !bytes.HasSuffix(existing, []byte("\n")) { buf.WriteByte('\n') } - if !containsLine(existing, projectGitignoreHeader) { + if header := r.templates.ProjectGitignoreHeader; header != "" && !containsLine(existing, header) { if len(existing) > 0 { buf.WriteByte('\n') } - buf.WriteString(projectGitignoreHeader + "\n") + buf.WriteString(header + "\n") } for _, pattern := range toAdd { buf.WriteString(pattern + "\n") @@ -193,12 +159,12 @@ func (r *beadsDirFSRepositoryImpl) WriteProjectGitignore(ctx context.Context, re return nil } -func (r *beadsDirFSRepositoryImpl) ProjectGitignoreExists(ctx context.Context, repoRoot string) (bool, error) { - return fileExists(filepath.Join(repoRoot, ".gitignore"), "fs: ProjectGitignoreExists") +func (r *beadsDirFSRepositoryImpl) ProjectGitignoreExists(ctx context.Context) (bool, error) { + return fileExists(filepath.Join(r.workDir, ".gitignore"), "fs: ProjectGitignoreExists") } -func (r *beadsDirFSRepositoryImpl) WriteInteractionsLog(ctx context.Context, beadsDir string) error { - path := filepath.Join(beadsDir, "interactions.jsonl") +func (r *beadsDirFSRepositoryImpl) WriteInteractionsLog(ctx context.Context) error { + path := filepath.Join(r.beadsDir, "interactions.jsonl") switch _, err := os.Stat(path); { case err == nil: return nil @@ -212,29 +178,32 @@ func (r *beadsDirFSRepositoryImpl) WriteInteractionsLog(ctx context.Context, bea return nil } -func (r *beadsDirFSRepositoryImpl) WriteReadme(ctx context.Context, beadsDir string) error { - path := filepath.Join(beadsDir, "README.md") +func (r *beadsDirFSRepositoryImpl) WriteReadme(ctx context.Context) error { + if r.templates.Readme == "" { + return fmt.Errorf("fs: WriteReadme: template not configured") + } + path := filepath.Join(r.beadsDir, "README.md") if _, err := os.Stat(path); err == nil { return nil // preserve any user edits } // #nosec G306 -- README should be world-readable - if err := os.WriteFile(path, []byte(beadsReadmeTemplate), 0644); err != nil { + if err := os.WriteFile(path, []byte(r.templates.Readme), 0644); err != nil { return fmt.Errorf("fs: WriteReadme: %w", err) } return nil } -func (r *beadsDirFSRepositoryImpl) WriteMetadataJSON(ctx context.Context, beadsDir string, content []byte) error { - path := filepath.Join(beadsDir, "metadata.json") +func (r *beadsDirFSRepositoryImpl) WriteMetadataJSON(ctx context.Context, content []byte) error { + path := filepath.Join(r.beadsDir, "metadata.json") if err := os.WriteFile(path, content, 0600); err != nil { return fmt.Errorf("fs: WriteMetadataJSON: %w", err) } return nil } -func (r *beadsDirFSRepositoryImpl) ReadMetadataJSON(ctx context.Context, beadsDir string) ([]byte, error) { - path := filepath.Join(beadsDir, "metadata.json") - // #nosec G304 -- path joined under caller-supplied beadsDir +func (r *beadsDirFSRepositoryImpl) ReadMetadataJSON(ctx context.Context) ([]byte, error) { + path := filepath.Join(r.beadsDir, "metadata.json") + // #nosec G304 -- path joined under bound beadsDir data, err := os.ReadFile(path) if errors.Is(err, os.ErrNotExist) { return nil, nil @@ -245,17 +214,17 @@ func (r *beadsDirFSRepositoryImpl) ReadMetadataJSON(ctx context.Context, beadsDi return data, nil } -func (r *beadsDirFSRepositoryImpl) WriteConfigYAML(ctx context.Context, beadsDir string, content []byte) error { - path := filepath.Join(beadsDir, "config.yaml") +func (r *beadsDirFSRepositoryImpl) WriteConfigYAML(ctx context.Context, content []byte) error { + path := filepath.Join(r.beadsDir, "config.yaml") if err := os.WriteFile(path, content, 0600); err != nil { return fmt.Errorf("fs: WriteConfigYAML: %w", err) } return nil } -func (r *beadsDirFSRepositoryImpl) ReadConfigYAML(ctx context.Context, beadsDir string) ([]byte, error) { - path := filepath.Join(beadsDir, "config.yaml") - // #nosec G304 -- path joined under caller-supplied beadsDir +func (r *beadsDirFSRepositoryImpl) ReadConfigYAML(ctx context.Context) ([]byte, error) { + path := filepath.Join(r.beadsDir, "config.yaml") + // #nosec G304 -- path joined under bound beadsDir data, err := os.ReadFile(path) if errors.Is(err, os.ErrNotExist) { return nil, nil @@ -266,6 +235,17 @@ func (r *beadsDirFSRepositoryImpl) ReadConfigYAML(ctx context.Context, beadsDir return data, nil } +func (r *beadsDirFSRepositoryImpl) ReadBeadsConfig(ctx context.Context) (*configfile.Config, error) { + if r.beadsDir == "" { + return nil, fmt.Errorf("fs: ReadBeadsConfig: beadsDir not resolved") + } + cfg, err := configfile.Load(r.beadsDir) + if err != nil { + return nil, fmt.Errorf("fs: ReadBeadsConfig: %w", err) + } + return cfg, nil +} + func fileExists(path, opLabel string) (bool, error) { info, err := os.Stat(path) if errors.Is(err, os.ErrNotExist) { diff --git a/internal/storage/domain/fs/beads_test.go b/internal/storage/domain/fs/beads_test.go index 944af4cb2..712d70c87 100644 --- a/internal/storage/domain/fs/beads_test.go +++ b/internal/storage/domain/fs/beads_test.go @@ -8,11 +8,11 @@ import ( "strings" "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/storage/domain" ) func (s *testSuite) TestBeadsDirFSRepository() { s.Run("CreateBeadsDir", func() { - s.Run("EmptyPathErrors", s.createBeadsDirEmptyPath) s.Run("CreatesDirectoryWithPerms", s.createBeadsDirCreates) s.Run("IdempotentOnExisting", s.createBeadsDirIdempotent) }) @@ -31,7 +31,6 @@ func (s *testSuite) TestBeadsDirFSRepository() { s.Run("PresentReturnsTrue", s.beadsGitignoreExistsPresent) }) s.Run("WriteProjectGitignore", func() { - s.Run("EmptyRepoRootErrors", s.writeProjectGitignoreEmptyRoot) s.Run("CreatesWithHeaderAndPatterns", s.writeProjectGitignoreCreates) s.Run("AppendsToExisting", s.writeProjectGitignoreAppends) s.Run("SkipsAlreadyPresentPatterns", s.writeProjectGitignoreNoDuplicates) @@ -60,18 +59,25 @@ func (s *testSuite) TestBeadsDirFSRepository() { s.Run("WriteThenReadRoundTrip", s.configYAMLRoundTrip) s.Run("WriteOverwrites", s.configYAMLOverwrite) }) -} - -func (s *testSuite) createBeadsDirEmptyPath() { - err := s.repo.CreateBeadsDir(s.Ctx(), "") - s.Require().Error(err) + s.Run("ReadBeadsConfig", func() { + s.Run("MissingFileReturnsNil", s.readBeadsConfigMissing) + s.Run("ParsesMetadataJSON", s.readBeadsConfigParses) + }) + s.Run("ResolveBeadsDirPath", func() { + s.Run("HonorsBeadsDirEnv", s.resolveBeadsDirPathHonorsEnv) + s.Run("FallsBackToLocalDotBeads", s.resolveBeadsDirPathLocalFallback) + }) + s.Run("BeadsDirIsLocal", func() { + s.Run("TrueForWorkDirChild", s.beadsDirIsLocalTrue) + s.Run("FalseForExplicitEnv", s.beadsDirIsLocalFalseEnv) + }) } func (s *testSuite) createBeadsDirCreates() { - _, dir := s.beadsDir() - s.Require().NoError(s.repo.CreateBeadsDir(s.Ctx(), dir)) + _, beadsDir, repo := s.newRepo() + s.Require().NoError(repo.CreateBeadsDir(s.Ctx())) - info, err := os.Stat(dir) + info, err := os.Stat(beadsDir) s.Require().NoError(err) s.True(info.IsDir()) @@ -81,54 +87,54 @@ func (s *testSuite) createBeadsDirCreates() { } func (s *testSuite) createBeadsDirIdempotent() { - _, dir := s.beadsDir() - s.Require().NoError(s.repo.CreateBeadsDir(s.Ctx(), dir)) - s.Require().NoError(s.repo.CreateBeadsDir(s.Ctx(), dir)) + _, _, repo := s.newRepo() + s.Require().NoError(repo.CreateBeadsDir(s.Ctx())) + s.Require().NoError(repo.CreateBeadsDir(s.Ctx())) } func (s *testSuite) beadsDirExistsMissing() { - _, dir := s.beadsDir() - exists, err := s.repo.BeadsDirExists(s.Ctx(), dir) + _, _, repo := s.newRepo() + exists, err := repo.BeadsDirExists(s.Ctx()) s.Require().NoError(err) s.False(exists) } func (s *testSuite) beadsDirExistsPresent() { - _, dir := s.beadsDir() - s.Require().NoError(os.MkdirAll(dir, 0700)) - exists, err := s.repo.BeadsDirExists(s.Ctx(), dir) + _, beadsDir, repo := s.newRepo() + s.Require().NoError(os.MkdirAll(beadsDir, 0700)) + exists, err := repo.BeadsDirExists(s.Ctx()) s.Require().NoError(err) s.True(exists) } func (s *testSuite) beadsDirExistsIsFile() { - _, path := s.beadsDir() - s.Require().NoError(os.WriteFile(path, []byte("not a dir"), 0600)) - exists, err := s.repo.BeadsDirExists(s.Ctx(), path) + _, beadsDir, repo := s.newRepo() + s.Require().NoError(os.WriteFile(beadsDir, []byte("not a dir"), 0600)) + exists, err := repo.BeadsDirExists(s.Ctx()) s.Require().NoError(err) s.False(exists) } func (s *testSuite) writeBeadsGitignoreWrites() { - _, dir := s.beadsDir() - s.Require().NoError(os.MkdirAll(dir, 0700)) - s.Require().NoError(s.repo.WriteBeadsGitignore(s.Ctx(), dir)) + _, beadsDir, repo := s.newRepo() + s.Require().NoError(os.MkdirAll(beadsDir, 0700)) + s.Require().NoError(repo.WriteBeadsGitignore(s.Ctx())) - data, err := os.ReadFile(filepath.Join(dir, ".gitignore")) + data, err := os.ReadFile(filepath.Join(beadsDir, ".gitignore")) s.Require().NoError(err) - s.Equal(beadsGitignoreTemplate, string(data)) + s.Equal(testTemplates().BeadsGitignore, string(data)) } func (s *testSuite) writeBeadsGitignoreIdempotent() { - _, dir := s.beadsDir() - s.Require().NoError(os.MkdirAll(dir, 0700)) - path := filepath.Join(dir, ".gitignore") - s.Require().NoError(os.WriteFile(path, []byte(beadsGitignoreTemplate), 0600)) + _, beadsDir, repo := s.newRepo() + s.Require().NoError(os.MkdirAll(beadsDir, 0700)) + path := filepath.Join(beadsDir, ".gitignore") + s.Require().NoError(os.WriteFile(path, []byte(testTemplates().BeadsGitignore), 0600)) before, err := os.Stat(path) s.Require().NoError(err) - s.Require().NoError(s.repo.WriteBeadsGitignore(s.Ctx(), dir)) + s.Require().NoError(repo.WriteBeadsGitignore(s.Ctx())) after, err := os.Stat(path) s.Require().NoError(err) @@ -136,80 +142,77 @@ func (s *testSuite) writeBeadsGitignoreIdempotent() { } func (s *testSuite) writeBeadsGitignoreOverwrites() { - _, dir := s.beadsDir() - s.Require().NoError(os.MkdirAll(dir, 0700)) - path := filepath.Join(dir, ".gitignore") + _, beadsDir, repo := s.newRepo() + s.Require().NoError(os.MkdirAll(beadsDir, 0700)) + path := filepath.Join(beadsDir, ".gitignore") s.Require().NoError(os.WriteFile(path, []byte("stale\n"), 0600)) - s.Require().NoError(s.repo.WriteBeadsGitignore(s.Ctx(), dir)) + s.Require().NoError(repo.WriteBeadsGitignore(s.Ctx())) data, err := os.ReadFile(path) s.Require().NoError(err) - s.Equal(beadsGitignoreTemplate, string(data)) + s.Equal(testTemplates().BeadsGitignore, string(data)) } func (s *testSuite) beadsGitignoreExistsMissing() { - _, dir := s.beadsDir() - s.Require().NoError(os.MkdirAll(dir, 0700)) - exists, err := s.repo.BeadsGitignoreExists(s.Ctx(), dir) + _, beadsDir, repo := s.newRepo() + s.Require().NoError(os.MkdirAll(beadsDir, 0700)) + exists, err := repo.BeadsGitignoreExists(s.Ctx()) s.Require().NoError(err) s.False(exists) } func (s *testSuite) beadsGitignoreExistsPresent() { - _, dir := s.beadsDir() - s.Require().NoError(os.MkdirAll(dir, 0700)) - s.Require().NoError(os.WriteFile(filepath.Join(dir, ".gitignore"), []byte("x"), 0600)) - exists, err := s.repo.BeadsGitignoreExists(s.Ctx(), dir) + _, beadsDir, repo := s.newRepo() + s.Require().NoError(os.MkdirAll(beadsDir, 0700)) + s.Require().NoError(os.WriteFile(filepath.Join(beadsDir, ".gitignore"), []byte("x"), 0600)) + exists, err := repo.BeadsGitignoreExists(s.Ctx()) s.Require().NoError(err) s.True(exists) } -func (s *testSuite) writeProjectGitignoreEmptyRoot() { - err := s.repo.WriteProjectGitignore(s.Ctx(), "") - s.Require().Error(err) -} - func (s *testSuite) writeProjectGitignoreCreates() { - root := s.tmpRoot() - s.Require().NoError(s.repo.WriteProjectGitignore(s.Ctx(), root)) + workDir, _, repo := s.newRepo() + s.Require().NoError(repo.WriteProjectGitignore(s.Ctx())) - data, err := os.ReadFile(filepath.Join(root, ".gitignore")) + data, err := os.ReadFile(filepath.Join(workDir, ".gitignore")) s.Require().NoError(err) body := string(data) - s.Contains(body, projectGitignoreHeader) - for _, pattern := range projectGitignorePatterns { + tpl := testTemplates() + s.Contains(body, tpl.ProjectGitignoreHeader) + for _, pattern := range tpl.ProjectGitignorePatterns { s.Contains(body, pattern) } } func (s *testSuite) writeProjectGitignoreAppends() { - root := s.tmpRoot() - path := filepath.Join(root, ".gitignore") + workDir, _, repo := s.newRepo() + path := filepath.Join(workDir, ".gitignore") preexisting := "node_modules/\n*.log\n" s.Require().NoError(os.WriteFile(path, []byte(preexisting), 0644)) - s.Require().NoError(s.repo.WriteProjectGitignore(s.Ctx(), root)) + s.Require().NoError(repo.WriteProjectGitignore(s.Ctx())) data, err := os.ReadFile(path) s.Require().NoError(err) body := string(data) + tpl := testTemplates() s.True(strings.HasPrefix(body, preexisting), "preexisting content must be preserved at the top") - s.Contains(body, projectGitignoreHeader) - for _, pattern := range projectGitignorePatterns { + s.Contains(body, tpl.ProjectGitignoreHeader) + for _, pattern := range tpl.ProjectGitignorePatterns { s.Contains(body, pattern) } } func (s *testSuite) writeProjectGitignoreNoDuplicates() { - root := s.tmpRoot() - path := filepath.Join(root, ".gitignore") + workDir, _, repo := s.newRepo() + path := filepath.Join(workDir, ".gitignore") preexisting := ".dolt/\nnode_modules/\n" s.Require().NoError(os.WriteFile(path, []byte(preexisting), 0644)) - s.Require().NoError(s.repo.WriteProjectGitignore(s.Ctx(), root)) + s.Require().NoError(repo.WriteProjectGitignore(s.Ctx())) data, err := os.ReadFile(path) s.Require().NoError(err) @@ -218,12 +221,13 @@ func (s *testSuite) writeProjectGitignoreNoDuplicates() { } func (s *testSuite) writeProjectGitignoreNoOpWhenComplete() { - root := s.tmpRoot() - path := filepath.Join(root, ".gitignore") + workDir, _, repo := s.newRepo() + path := filepath.Join(workDir, ".gitignore") + tpl := testTemplates() var buf bytes.Buffer buf.WriteString("existing\n") - buf.WriteString(projectGitignoreHeader + "\n") - for _, pattern := range projectGitignorePatterns { + buf.WriteString(tpl.ProjectGitignoreHeader + "\n") + for _, pattern := range tpl.ProjectGitignorePatterns { buf.WriteString(pattern + "\n") } s.Require().NoError(os.WriteFile(path, buf.Bytes(), 0644)) @@ -231,7 +235,7 @@ func (s *testSuite) writeProjectGitignoreNoOpWhenComplete() { before, err := os.Stat(path) s.Require().NoError(err) - s.Require().NoError(s.repo.WriteProjectGitignore(s.Ctx(), root)) + s.Require().NoError(repo.WriteProjectGitignore(s.Ctx())) after, err := os.Stat(path) s.Require().NoError(err) @@ -239,53 +243,53 @@ func (s *testSuite) writeProjectGitignoreNoOpWhenComplete() { } func (s *testSuite) writeProjectGitignoreFixesTrailingNewline() { - root := s.tmpRoot() - path := filepath.Join(root, ".gitignore") + workDir, _, repo := s.newRepo() + path := filepath.Join(workDir, ".gitignore") s.Require().NoError(os.WriteFile(path, []byte("no-trailing-newline"), 0644)) - s.Require().NoError(s.repo.WriteProjectGitignore(s.Ctx(), root)) + s.Require().NoError(repo.WriteProjectGitignore(s.Ctx())) data, err := os.ReadFile(path) s.Require().NoError(err) body := string(data) s.True(strings.HasPrefix(body, "no-trailing-newline\n"), "trailing newline must be inserted before appended content") - s.Contains(body, projectGitignoreHeader) + s.Contains(body, testTemplates().ProjectGitignoreHeader) } func (s *testSuite) projectGitignoreExistsMissing() { - root := s.tmpRoot() - exists, err := s.repo.ProjectGitignoreExists(s.Ctx(), root) + _, _, repo := s.newRepo() + exists, err := repo.ProjectGitignoreExists(s.Ctx()) s.Require().NoError(err) s.False(exists) } func (s *testSuite) projectGitignoreExistsPresent() { - root := s.tmpRoot() - s.Require().NoError(os.WriteFile(filepath.Join(root, ".gitignore"), []byte("x"), 0644)) - exists, err := s.repo.ProjectGitignoreExists(s.Ctx(), root) + workDir, _, repo := s.newRepo() + s.Require().NoError(os.WriteFile(filepath.Join(workDir, ".gitignore"), []byte("x"), 0644)) + exists, err := repo.ProjectGitignoreExists(s.Ctx()) s.Require().NoError(err) s.True(exists) } func (s *testSuite) writeInteractionsLogCreates() { - _, dir := s.beadsDir() - s.Require().NoError(os.MkdirAll(dir, 0700)) - s.Require().NoError(s.repo.WriteInteractionsLog(s.Ctx(), dir)) + _, beadsDir, repo := s.newRepo() + s.Require().NoError(os.MkdirAll(beadsDir, 0700)) + s.Require().NoError(repo.WriteInteractionsLog(s.Ctx())) - data, err := os.ReadFile(filepath.Join(dir, "interactions.jsonl")) + data, err := os.ReadFile(filepath.Join(beadsDir, "interactions.jsonl")) s.Require().NoError(err) s.Empty(data) } func (s *testSuite) writeInteractionsLogPreserves() { - _, dir := s.beadsDir() - s.Require().NoError(os.MkdirAll(dir, 0700)) - path := filepath.Join(dir, "interactions.jsonl") + _, beadsDir, repo := s.newRepo() + s.Require().NoError(os.MkdirAll(beadsDir, 0700)) + path := filepath.Join(beadsDir, "interactions.jsonl") existing := []byte(`{"event":"x"}` + "\n") s.Require().NoError(os.WriteFile(path, existing, 0644)) - s.Require().NoError(s.repo.WriteInteractionsLog(s.Ctx(), dir)) + s.Require().NoError(repo.WriteInteractionsLog(s.Ctx())) data, err := os.ReadFile(path) s.Require().NoError(err) @@ -293,23 +297,23 @@ func (s *testSuite) writeInteractionsLogPreserves() { } func (s *testSuite) writeReadmeCreates() { - _, dir := s.beadsDir() - s.Require().NoError(os.MkdirAll(dir, 0700)) - s.Require().NoError(s.repo.WriteReadme(s.Ctx(), dir)) + _, beadsDir, repo := s.newRepo() + s.Require().NoError(os.MkdirAll(beadsDir, 0700)) + s.Require().NoError(repo.WriteReadme(s.Ctx())) - data, err := os.ReadFile(filepath.Join(dir, "README.md")) + data, err := os.ReadFile(filepath.Join(beadsDir, "README.md")) s.Require().NoError(err) - s.Equal(beadsReadmeTemplate, string(data)) + s.Equal(testTemplates().Readme, string(data)) } func (s *testSuite) writeReadmePreserves() { - _, dir := s.beadsDir() - s.Require().NoError(os.MkdirAll(dir, 0700)) - path := filepath.Join(dir, "README.md") + _, beadsDir, repo := s.newRepo() + s.Require().NoError(os.MkdirAll(beadsDir, 0700)) + path := filepath.Join(beadsDir, "README.md") custom := []byte("# My custom readme\n") s.Require().NoError(os.WriteFile(path, custom, 0644)) - s.Require().NoError(s.repo.WriteReadme(s.Ctx(), dir)) + s.Require().NoError(repo.WriteReadme(s.Ctx())) data, err := os.ReadFile(path) s.Require().NoError(err) @@ -317,63 +321,125 @@ func (s *testSuite) writeReadmePreserves() { } func (s *testSuite) readMetadataJSONMissing() { - _, dir := s.beadsDir() - s.Require().NoError(os.MkdirAll(dir, 0700)) - data, err := s.repo.ReadMetadataJSON(s.Ctx(), dir) + _, beadsDir, repo := s.newRepo() + s.Require().NoError(os.MkdirAll(beadsDir, 0700)) + data, err := repo.ReadMetadataJSON(s.Ctx()) s.Require().NoError(err) s.Nil(data) } func (s *testSuite) metadataJSONRoundTrip() { - _, dir := s.beadsDir() - s.Require().NoError(os.MkdirAll(dir, 0700)) + _, beadsDir, repo := s.newRepo() + s.Require().NoError(os.MkdirAll(beadsDir, 0700)) body := []byte(`{"_project_id":"abc-123"}`) - s.Require().NoError(s.repo.WriteMetadataJSON(s.Ctx(), dir, body)) + s.Require().NoError(repo.WriteMetadataJSON(s.Ctx(), body)) - got, err := s.repo.ReadMetadataJSON(s.Ctx(), dir) + got, err := repo.ReadMetadataJSON(s.Ctx()) s.Require().NoError(err) s.Equal(body, got) } func (s *testSuite) metadataJSONOverwrite() { - _, dir := s.beadsDir() - s.Require().NoError(os.MkdirAll(dir, 0700)) - s.Require().NoError(s.repo.WriteMetadataJSON(s.Ctx(), dir, []byte(`{"v":1}`))) - s.Require().NoError(s.repo.WriteMetadataJSON(s.Ctx(), dir, []byte(`{"v":2}`))) + _, beadsDir, repo := s.newRepo() + s.Require().NoError(os.MkdirAll(beadsDir, 0700)) + s.Require().NoError(repo.WriteMetadataJSON(s.Ctx(), []byte(`{"v":1}`))) + s.Require().NoError(repo.WriteMetadataJSON(s.Ctx(), []byte(`{"v":2}`))) - got, err := s.repo.ReadMetadataJSON(s.Ctx(), dir) + got, err := repo.ReadMetadataJSON(s.Ctx()) s.Require().NoError(err) s.Equal([]byte(`{"v":2}`), got) } func (s *testSuite) readConfigYAMLMissing() { - _, dir := s.beadsDir() - s.Require().NoError(os.MkdirAll(dir, 0700)) - data, err := s.repo.ReadConfigYAML(s.Ctx(), dir) + _, beadsDir, repo := s.newRepo() + s.Require().NoError(os.MkdirAll(beadsDir, 0700)) + data, err := repo.ReadConfigYAML(s.Ctx()) s.Require().NoError(err) s.Nil(data) } func (s *testSuite) configYAMLRoundTrip() { - _, dir := s.beadsDir() - s.Require().NoError(os.MkdirAll(dir, 0700)) + _, beadsDir, repo := s.newRepo() + s.Require().NoError(os.MkdirAll(beadsDir, 0700)) body := []byte("issue_prefix: bd\n") - s.Require().NoError(s.repo.WriteConfigYAML(s.Ctx(), dir, body)) + s.Require().NoError(repo.WriteConfigYAML(s.Ctx(), body)) - got, err := s.repo.ReadConfigYAML(s.Ctx(), dir) + got, err := repo.ReadConfigYAML(s.Ctx()) s.Require().NoError(err) s.Equal(body, got) } func (s *testSuite) configYAMLOverwrite() { - _, dir := s.beadsDir() - s.Require().NoError(os.MkdirAll(dir, 0700)) - s.Require().NoError(s.repo.WriteConfigYAML(s.Ctx(), dir, []byte("v: 1\n"))) - s.Require().NoError(s.repo.WriteConfigYAML(s.Ctx(), dir, []byte("v: 2\n"))) + _, beadsDir, repo := s.newRepo() + s.Require().NoError(os.MkdirAll(beadsDir, 0700)) + s.Require().NoError(repo.WriteConfigYAML(s.Ctx(), []byte("v: 1\n"))) + s.Require().NoError(repo.WriteConfigYAML(s.Ctx(), []byte("v: 2\n"))) - got, err := s.repo.ReadConfigYAML(s.Ctx(), dir) + got, err := repo.ReadConfigYAML(s.Ctx()) s.Require().NoError(err) s.Equal([]byte("v: 2\n"), got) } + +func (s *testSuite) readBeadsConfigMissing() { + _, beadsDir, repo := s.newRepo() + s.Require().NoError(os.MkdirAll(beadsDir, 0700)) + cfg, err := repo.ReadBeadsConfig(s.Ctx()) + s.Require().NoError(err) + s.Nil(cfg) +} + +func (s *testSuite) readBeadsConfigParses() { + _, beadsDir, repo := s.newRepo() + s.Require().NoError(os.MkdirAll(beadsDir, 0700)) + body := []byte(`{"dolt_database":"my_db","project_id":"pid-123"}`) + s.Require().NoError(repo.WriteMetadataJSON(s.Ctx(), body)) + + cfg, err := repo.ReadBeadsConfig(s.Ctx()) + s.Require().NoError(err) + s.Require().NotNil(cfg) + s.Equal("my_db", cfg.DoltDatabase) + s.Equal("pid-123", cfg.ProjectID) +} + +func (s *testSuite) resolveBeadsDirPathHonorsEnv() { + envDir := s.T().TempDir() + s.T().Setenv("BEADS_DIR", envDir) + + workDir := s.T().TempDir() + repo := NewBeadsDirFSRepository(workDir, testTemplates()) + + res := repo.ResolveBeadsDirPath(s.Ctx()) + s.True(res.HasExplicit) + s.NotEmpty(res.BeadsDir) +} + +func (s *testSuite) resolveBeadsDirPathLocalFallback() { + workDir, beadsDir, repo := s.newRepo() + + res := repo.ResolveBeadsDirPath(s.Ctx()) + s.False(res.HasExplicit) + // When BEADS_DIR is unset and we're outside a git worktree, the fallback is + // workDir/.beads (FollowRedirect leaves the path unchanged when no redirect). + s.Equal(beadsDir, res.BeadsDir) + _ = workDir +} + +func (s *testSuite) beadsDirIsLocalTrue() { + _, _, repo := s.newRepo() + s.True(repo.BeadsDirIsLocal(s.Ctx())) +} + +func (s *testSuite) beadsDirIsLocalFalseEnv() { + envDir := s.T().TempDir() + s.T().Setenv("BEADS_DIR", envDir) + + workDir := s.T().TempDir() + repo := NewBeadsDirFSRepository(workDir, testTemplates()) + + s.False(repo.BeadsDirIsLocal(s.Ctx()), "explicit BEADS_DIR outside workDir is not local") +} + +// statically assert the BeadsDirTemplates type is reachable for downstream callers. +var _ = domain.BeadsDirTemplates{} diff --git a/internal/storage/domain/fs/suite_test.go b/internal/storage/domain/fs/suite_test.go index 430988d88..5e92235eb 100644 --- a/internal/storage/domain/fs/suite_test.go +++ b/internal/storage/domain/fs/suite_test.go @@ -12,24 +12,30 @@ import ( type testSuite struct { suite.Suite - repo domain.BeadsDirFSRepository -} - -func (s *testSuite) SetupTest() { - s.repo = NewBeadsDirFSRepository() } func (s *testSuite) Ctx() context.Context { return context.Background() } -func (s *testSuite) tmpRoot() string { - return s.T().TempDir() +// newRepo returns a fresh (workDir, beadsDir, repo) for an isolated subtest. +// The repo is bound to workDir; beadsDir is workDir/.beads. +func (s *testSuite) newRepo() (workDir, beadsDir string, repo domain.BeadsDirFSRepository) { + s.T().Helper() + s.T().Setenv("BEADS_DIR", "") + workDir = s.T().TempDir() + beadsDir = filepath.Join(workDir, ".beads") + repo = NewBeadsDirFSRepository(workDir, testTemplates()) + return } -func (s *testSuite) beadsDir() (string, string) { - root := s.tmpRoot() - return root, filepath.Join(root, ".beads") +func testTemplates() domain.BeadsDirTemplates { + return domain.BeadsDirTemplates{ + BeadsGitignore: "# test beads gitignore\ndolt/\n", + ProjectGitignoreHeader: "# Beads test header", + ProjectGitignorePatterns: []string{".dolt/", "*.db"}, + Readme: "# test readme\n", + } } func TestDomainFS(t *testing.T) { diff --git a/internal/storage/domain/git.go b/internal/storage/domain/git.go new file mode 100644 index 000000000..2976b2354 --- /dev/null +++ b/internal/storage/domain/git.go @@ -0,0 +1,211 @@ +package domain + +import ( + "context" + "fmt" + "os" + "path/filepath" +) + +type GitRepository interface { + IsGitRepo(ctx context.Context) (bool, error) + IsBareGitRepo(ctx context.Context) (bool, error) + IsJujutsuRepo(ctx context.Context) (bool, error) + IsColocatedJJGit(ctx context.Context) (bool, error) + + Init(ctx context.Context) error + + GetConfig(ctx context.Context, key string) (value string, found bool, err error) + SetConfig(ctx context.Context, key, value string) error + + GetRemoteURL(ctx context.Context, name string) (url string, found bool, err error) + ListRemoteNames(ctx context.Context) ([]string, error) + + CurrentBranch(ctx context.Context) (string, error) + BranchHasUpstream(ctx context.Context, branch string) (bool, error) + + Add(ctx context.Context, paths ...string) error + Commit(ctx context.Context, params GitCommitParams) (GitCommitResult, error) +} + +type GitCommitParams struct { + Message string + NoVerify bool +} + +type GitCommitResult struct { + DidCommit bool + Output []byte +} + +type GitUseCase interface { + IsGitRepo(ctx context.Context) bool + IsBareGitRepo(ctx context.Context) bool + IsJujutsuRepo(ctx context.Context) bool + IsColocatedJJGit(ctx context.Context) bool + + EnsureGitRepo(ctx context.Context) (EnsureGitRepoResult, error) + OriginRemoteURL(ctx context.Context) (string, error) + DetectFork(ctx context.Context) (isFork bool, upstreamURL string, err error) + + BeadsRole(ctx context.Context) (role string, hasRole bool, err error) + SetBeadsRole(ctx context.Context, role string) error + + HasAnyRemotes(ctx context.Context) bool + HasUpstream(ctx context.Context) bool + + CommitInitArtifacts(ctx context.Context, params CommitInitArtifactsParams) (CommitInitArtifactsResult, error) +} + +type EnsureGitRepoResult struct { + DidInit bool + AlreadyExists bool +} + +type CommitInitArtifactsParams struct { + BeadsDir string + OptionalPaths []string + Message string + NoVerify bool +} + +type CommitInitArtifactsResult struct { + StagedPaths []string + DidCommit bool +} + +const beadsRoleConfigKey = "beads.role" + +func NewGitUseCase(workDir string, repo GitRepository) GitUseCase { + return &gitUseCaseImpl{workDir: workDir, repo: repo} +} + +type gitUseCaseImpl struct { + workDir string + repo GitRepository +} + +var _ GitUseCase = (*gitUseCaseImpl)(nil) + +func (u *gitUseCaseImpl) IsGitRepo(ctx context.Context) bool { + ok, _ := u.repo.IsGitRepo(ctx) + return ok +} + +func (u *gitUseCaseImpl) IsBareGitRepo(ctx context.Context) bool { + ok, _ := u.repo.IsBareGitRepo(ctx) + return ok +} + +func (u *gitUseCaseImpl) IsJujutsuRepo(ctx context.Context) bool { + ok, _ := u.repo.IsJujutsuRepo(ctx) + return ok +} + +func (u *gitUseCaseImpl) IsColocatedJJGit(ctx context.Context) bool { + ok, _ := u.repo.IsColocatedJJGit(ctx) + return ok +} + +func (u *gitUseCaseImpl) EnsureGitRepo(ctx context.Context) (EnsureGitRepoResult, error) { + exists, err := u.repo.IsGitRepo(ctx) + if err != nil { + return EnsureGitRepoResult{}, fmt.Errorf("EnsureGitRepo: check: %w", err) + } + if exists { + return EnsureGitRepoResult{AlreadyExists: true}, nil + } + if err := u.repo.Init(ctx); err != nil { + return EnsureGitRepoResult{}, fmt.Errorf("EnsureGitRepo: init: %w", err) + } + return EnsureGitRepoResult{DidInit: true}, nil +} + +func (u *gitUseCaseImpl) OriginRemoteURL(ctx context.Context) (string, error) { + isRepo, err := u.repo.IsGitRepo(ctx) + if err != nil || !isRepo { + return "", err + } + bare, err := u.repo.IsBareGitRepo(ctx) + if err != nil || bare { + return "", err + } + url, _, err := u.repo.GetRemoteURL(ctx, "origin") + return url, err +} + +func (u *gitUseCaseImpl) DetectFork(ctx context.Context) (bool, string, error) { + isRepo, err := u.repo.IsGitRepo(ctx) + if err != nil || !isRepo { + return false, "", err + } + url, found, err := u.repo.GetRemoteURL(ctx, "upstream") + if err != nil || !found { + return false, "", err + } + return true, url, nil +} + +func (u *gitUseCaseImpl) BeadsRole(ctx context.Context) (string, bool, error) { + return u.repo.GetConfig(ctx, beadsRoleConfigKey) +} + +func (u *gitUseCaseImpl) SetBeadsRole(ctx context.Context, role string) error { + if role == "" { + return fmt.Errorf("SetBeadsRole: role must not be empty") + } + return u.repo.SetConfig(ctx, beadsRoleConfigKey, role) +} + +func (u *gitUseCaseImpl) HasAnyRemotes(ctx context.Context) bool { + names, err := u.repo.ListRemoteNames(ctx) + if err != nil { + return false + } + return len(names) > 0 +} + +func (u *gitUseCaseImpl) HasUpstream(ctx context.Context) bool { + branch, err := u.repo.CurrentBranch(ctx) + if err != nil || branch == "" { + return false + } + ok, err := u.repo.BranchHasUpstream(ctx, branch) + if err != nil { + return false + } + return ok +} + +func (u *gitUseCaseImpl) CommitInitArtifacts(ctx context.Context, params CommitInitArtifactsParams) (CommitInitArtifactsResult, error) { + if params.BeadsDir == "" { + return CommitInitArtifactsResult{}, fmt.Errorf("CommitInitArtifacts: BeadsDir must not be empty") + } + if params.Message == "" { + return CommitInitArtifactsResult{}, fmt.Errorf("CommitInitArtifacts: Message must not be empty") + } + + paths := []string{params.BeadsDir} + for _, p := range params.OptionalPaths { + if p == "" { + continue + } + statPath := p + if !filepath.IsAbs(statPath) { + statPath = filepath.Join(u.workDir, statPath) + } + if _, err := os.Stat(statPath); err == nil { + paths = append(paths, p) + } + } + + if err := u.repo.Add(ctx, paths...); err != nil { + return CommitInitArtifactsResult{}, fmt.Errorf("CommitInitArtifacts: add: %w", err) + } + + commit, err := u.repo.Commit(ctx, GitCommitParams{Message: params.Message, NoVerify: params.NoVerify}) + if err != nil { + return CommitInitArtifactsResult{}, fmt.Errorf("CommitInitArtifacts: commit: %w", err) + } + return CommitInitArtifactsResult{StagedPaths: paths, DidCommit: commit.DidCommit}, nil +} diff --git a/internal/storage/domain/git/git.go b/internal/storage/domain/git/git.go new file mode 100644 index 000000000..11e89e49b --- /dev/null +++ b/internal/storage/domain/git/git.go @@ -0,0 +1,216 @@ +package git + +import ( + "bytes" + "context" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + + internalgit "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/storage/domain" +) + +func NewGitRepository(workDir string) domain.GitRepository { + return &gitRepositoryImpl{workDir: workDir} +} + +type gitRepositoryImpl struct { + workDir string +} + +var _ domain.GitRepository = (*gitRepositoryImpl)(nil) + +func (r *gitRepositoryImpl) gitCmd(ctx context.Context, args ...string) *exec.Cmd { + cmd := exec.CommandContext(ctx, "git", args...) + cmd.Dir = r.workDir + return cmd +} + +func (r *gitRepositoryImpl) IsGitRepo(ctx context.Context) (bool, error) { + if err := r.gitCmd(ctx, "rev-parse", "--git-dir").Run(); err != nil { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + return false, nil + } + return false, fmt.Errorf("git: IsGitRepo: %w", err) + } + return true, nil +} + +func (r *gitRepositoryImpl) IsBareGitRepo(ctx context.Context) (bool, error) { + out, err := r.gitCmd(ctx, "rev-parse", "--is-bare-repository").Output() + if err != nil { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + return false, nil + } + return false, fmt.Errorf("git: IsBareGitRepo: %w", err) + } + return strings.TrimSpace(string(out)) == "true", nil +} + +// IsJujutsuRepo walks upward from workDir looking for a .jj directory. +// Mirrors the boundary rule in internal/git.GetJujutsuRoot: a .git directory +// found before .jj terminates the walk so a nested git repo does not inherit +// an ancestor JJ workspace. +func (r *gitRepositoryImpl) IsJujutsuRepo(ctx context.Context) (bool, error) { + dir, err := filepath.Abs(r.workDir) + if err != nil { + return false, fmt.Errorf("git: IsJujutsuRepo: abs %s: %w", r.workDir, err) + } + for { + if info, err := os.Stat(filepath.Join(dir, ".jj")); err == nil && info.IsDir() { + return true, nil + } + if _, err := os.Stat(filepath.Join(dir, ".git")); err == nil { + return false, nil + } + parent := filepath.Dir(dir) + if parent == dir { + return false, nil + } + dir = parent + } +} + +func (r *gitRepositoryImpl) IsColocatedJJGit(ctx context.Context) (bool, error) { + isJJ, err := r.IsJujutsuRepo(ctx) + if err != nil || !isJJ { + return false, err + } + return r.IsGitRepo(ctx) +} + +func (r *gitRepositoryImpl) Init(ctx context.Context) error { + out, err := r.gitCmd(ctx, "init").CombinedOutput() + if err != nil { + return fmt.Errorf("git: Init: %w: %s", err, bytes.TrimSpace(out)) + } + internalgit.ResetCaches() + return nil +} + +func (r *gitRepositoryImpl) GetConfig(ctx context.Context, key string) (string, bool, error) { + if key == "" { + return "", false, fmt.Errorf("git: GetConfig: key must not be empty") + } + out, err := r.gitCmd(ctx, "config", "--get", key).Output() + if err != nil { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + return "", false, nil + } + return "", false, fmt.Errorf("git: GetConfig %s: %w", key, err) + } + value := strings.TrimSpace(string(out)) + if value == "" { + return "", false, nil + } + return value, true, nil +} + +func (r *gitRepositoryImpl) SetConfig(ctx context.Context, key, value string) error { + if key == "" { + return fmt.Errorf("git: SetConfig: key must not be empty") + } + out, err := r.gitCmd(ctx, "config", key, value).CombinedOutput() + if err != nil { + return fmt.Errorf("git: SetConfig %s: %w: %s", key, err, bytes.TrimSpace(out)) + } + return nil +} + +func (r *gitRepositoryImpl) GetRemoteURL(ctx context.Context, name string) (string, bool, error) { + if name == "" { + return "", false, fmt.Errorf("git: GetRemoteURL: name must not be empty") + } + out, err := r.gitCmd(ctx, "remote", "get-url", name).Output() + if err != nil { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + return "", false, nil + } + return "", false, fmt.Errorf("git: GetRemoteURL %s: %w", name, err) + } + url := strings.TrimSpace(string(out)) + if url == "" { + return "", false, nil + } + return url, true, nil +} + +func (r *gitRepositoryImpl) ListRemoteNames(ctx context.Context) ([]string, error) { + out, err := r.gitCmd(ctx, "remote").Output() + if err != nil { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + return nil, nil + } + return nil, fmt.Errorf("git: ListRemoteNames: %w", err) + } + trimmed := strings.TrimSpace(string(out)) + if trimmed == "" { + return nil, nil + } + return strings.Split(trimmed, "\n"), nil +} + +func (r *gitRepositoryImpl) CurrentBranch(ctx context.Context) (string, error) { + out, err := r.gitCmd(ctx, "symbolic-ref", "--short", "HEAD").Output() + if err != nil { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + return "", nil + } + return "", fmt.Errorf("git: CurrentBranch: %w", err) + } + return strings.TrimSpace(string(out)), nil +} + +func (r *gitRepositoryImpl) BranchHasUpstream(ctx context.Context, branch string) (bool, error) { + if branch == "" { + return false, fmt.Errorf("git: BranchHasUpstream: branch must not be empty") + } + if err := r.gitCmd(ctx, "config", "--get", "branch."+branch+".remote").Run(); err != nil { + return false, nil + } + if err := r.gitCmd(ctx, "config", "--get", "branch."+branch+".merge").Run(); err != nil { + return false, nil + } + return true, nil +} + +func (r *gitRepositoryImpl) Add(ctx context.Context, paths ...string) error { + if len(paths) == 0 { + return fmt.Errorf("git: Add: at least one path required") + } + args := append([]string{"add", "--"}, paths...) + out, err := r.gitCmd(ctx, args...).CombinedOutput() + if err != nil { + return fmt.Errorf("git: Add: %w: %s", err, bytes.TrimSpace(out)) + } + return nil +} + +func (r *gitRepositoryImpl) Commit(ctx context.Context, params domain.GitCommitParams) (domain.GitCommitResult, error) { + if params.Message == "" { + return domain.GitCommitResult{}, fmt.Errorf("git: Commit: Message must not be empty") + } + args := []string{"commit"} + if params.NoVerify { + args = append(args, "--no-verify") + } + args = append(args, "-m", params.Message) + out, err := r.gitCmd(ctx, args...).CombinedOutput() + if err != nil { + if bytes.Contains(out, []byte("nothing to commit")) || bytes.Contains(out, []byte("no changes added to commit")) { + return domain.GitCommitResult{DidCommit: false, Output: out}, nil + } + return domain.GitCommitResult{Output: out}, fmt.Errorf("git: Commit: %w: %s", err, bytes.TrimSpace(out)) + } + return domain.GitCommitResult{DidCommit: true, Output: out}, nil +} diff --git a/internal/storage/domain/git/git_test.go b/internal/storage/domain/git/git_test.go new file mode 100644 index 000000000..0f1e94edb --- /dev/null +++ b/internal/storage/domain/git/git_test.go @@ -0,0 +1,221 @@ +package git + +import ( + "os" + "path/filepath" + "strings" + + "github.com/steveyegge/beads/internal/storage/domain" +) + +func (s *testSuite) TestIsGitRepo_FalseOutsideRepo() { + ok, err := s.repo.IsGitRepo(s.Ctx()) + s.Require().NoError(err) + s.False(ok) +} + +func (s *testSuite) TestIsGitRepo_TrueInsideRepo() { + s.gitInit() + ok, err := s.repo.IsGitRepo(s.Ctx()) + s.Require().NoError(err) + s.True(ok) +} + +func (s *testSuite) TestIsBareGitRepo_FalseForRegularRepo() { + s.gitInit() + bare, err := s.repo.IsBareGitRepo(s.Ctx()) + s.Require().NoError(err) + s.False(bare) +} + +func (s *testSuite) TestIsBareGitRepo_FalseOutsideRepo() { + bare, err := s.repo.IsBareGitRepo(s.Ctx()) + s.Require().NoError(err) + s.False(bare) +} + +func (s *testSuite) TestInit_CreatesRepo() { + s.Require().NoError(s.repo.Init(s.Ctx())) + ok, err := s.repo.IsGitRepo(s.Ctx()) + s.Require().NoError(err) + s.True(ok) +} + +func (s *testSuite) TestConfig_GetMissing() { + s.gitInit() + value, found, err := s.repo.GetConfig(s.Ctx(), "beads.role") + s.Require().NoError(err) + s.False(found) + s.Empty(value) +} + +func (s *testSuite) TestConfig_RoundTrip() { + s.gitInit() + s.Require().NoError(s.repo.SetConfig(s.Ctx(), "beads.role", "maintainer")) + + value, found, err := s.repo.GetConfig(s.Ctx(), "beads.role") + s.Require().NoError(err) + s.True(found) + s.Equal("maintainer", value) +} + +func (s *testSuite) TestConfig_SetEmptyKeyErrors() { + s.gitInit() + err := s.repo.SetConfig(s.Ctx(), "", "x") + s.Require().Error(err) +} + +func (s *testSuite) TestRemote_GetMissing() { + s.gitInit() + url, found, err := s.repo.GetRemoteURL(s.Ctx(), "origin") + s.Require().NoError(err) + s.False(found) + s.Empty(url) +} + +func (s *testSuite) TestRemote_AddedRemoteVisible() { + s.gitInit() + s.run("git", "remote", "add", "origin", "https://example.com/repo.git") + + url, found, err := s.repo.GetRemoteURL(s.Ctx(), "origin") + s.Require().NoError(err) + s.True(found) + s.Equal("https://example.com/repo.git", url) +} + +func (s *testSuite) TestRemote_ListEmpty() { + s.gitInit() + names, err := s.repo.ListRemoteNames(s.Ctx()) + s.Require().NoError(err) + s.Empty(names) +} + +func (s *testSuite) TestRemote_ListMultiple() { + s.gitInit() + s.run("git", "remote", "add", "origin", "https://example.com/a.git") + s.run("git", "remote", "add", "upstream", "https://example.com/b.git") + + names, err := s.repo.ListRemoteNames(s.Ctx()) + s.Require().NoError(err) + s.ElementsMatch([]string{"origin", "upstream"}, names) +} + +func (s *testSuite) TestCurrentBranch_NoErrorOnFreshRepo() { + s.gitInit() + _, err := s.repo.CurrentBranch(s.Ctx()) + s.Require().NoError(err) +} + +func (s *testSuite) TestBranchHasUpstream_FalseWhenUnset() { + s.gitInit() + s.writeFile("a.txt", "x") + s.run("git", "add", "a.txt") + s.run("git", "commit", "-q", "-m", "init") + + branch, err := s.repo.CurrentBranch(s.Ctx()) + s.Require().NoError(err) + s.Require().NotEmpty(branch) + + has, err := s.repo.BranchHasUpstream(s.Ctx(), branch) + s.Require().NoError(err) + s.False(has) +} + +func (s *testSuite) TestBranchHasUpstream_TrueWhenSet() { + s.gitInit() + s.writeFile("a.txt", "x") + s.run("git", "add", "a.txt") + s.run("git", "commit", "-q", "-m", "init") + + branch, err := s.repo.CurrentBranch(s.Ctx()) + s.Require().NoError(err) + s.run("git", "config", "branch."+branch+".remote", "origin") + s.run("git", "config", "branch."+branch+".merge", "refs/heads/"+branch) + + has, err := s.repo.BranchHasUpstream(s.Ctx(), branch) + s.Require().NoError(err) + s.True(has) +} + +func (s *testSuite) TestAdd_StageAndCommitFile() { + s.gitInit() + s.writeFile("a.txt", "x") + + s.Require().NoError(s.repo.Add(s.Ctx(), "a.txt")) + result, err := s.repo.Commit(s.Ctx(), domain.GitCommitParams{Message: "test"}) + s.Require().NoError(err) + s.True(result.DidCommit) +} + +func (s *testSuite) TestCommit_NoVerifyBypassesHook() { + s.gitInit() + hookPath := filepath.Join(s.tmpDir, ".git", "hooks", "pre-commit") + s.Require().NoError(os.WriteFile(hookPath, []byte("#!/bin/sh\nexit 1\n"), 0755)) //nolint:gosec // test hook + s.writeFile("a.txt", "x") + s.Require().NoError(s.repo.Add(s.Ctx(), "a.txt")) + + result, err := s.repo.Commit(s.Ctx(), domain.GitCommitParams{Message: "test", NoVerify: true}) + s.Require().NoError(err) + s.True(result.DidCommit) +} + +func (s *testSuite) TestCommit_NothingToCommitDidCommitFalse() { + s.gitInit() + s.writeFile("a.txt", "x") + s.Require().NoError(s.repo.Add(s.Ctx(), "a.txt")) + _, err := s.repo.Commit(s.Ctx(), domain.GitCommitParams{Message: "first"}) + s.Require().NoError(err) + + result, err := s.repo.Commit(s.Ctx(), domain.GitCommitParams{Message: "second"}) + s.Require().NoError(err) + s.False(result.DidCommit) + s.True(strings.Contains(string(result.Output), "nothing to commit")) +} + +func (s *testSuite) TestAdd_EmptyPathsErrors() { + s.gitInit() + err := s.repo.Add(s.Ctx()) + s.Require().Error(err) +} + +func (s *testSuite) TestIsJujutsuRepo_FalseOnTempDir() { + ok, err := s.repo.IsJujutsuRepo(s.Ctx()) + s.Require().NoError(err) + s.False(ok) +} + +func (s *testSuite) TestIsJujutsuRepo_TrueWhenJJDirPresent() { + s.Require().NoError(os.MkdirAll(filepath.Join(s.tmpDir, ".jj"), 0700)) + ok, err := s.repo.IsJujutsuRepo(s.Ctx()) + s.Require().NoError(err) + s.True(ok) +} + +func (s *testSuite) TestIsColocatedJJGit_FalseOnTempDir() { + s.gitInit() + ok, err := s.repo.IsColocatedJJGit(s.Ctx()) + s.Require().NoError(err) + s.False(ok) +} + +func (s *testSuite) TestIsColocatedJJGit_TrueWhenBothPresent() { + s.gitInit() + s.Require().NoError(os.MkdirAll(filepath.Join(s.tmpDir, ".jj"), 0700)) + ok, err := s.repo.IsColocatedJJGit(s.Ctx()) + s.Require().NoError(err) + s.True(ok) +} + +func (s *testSuite) TestExec_HappensInWorkDir() { + // Confirms cmd.Dir is honored: chdir away, then init via repo bound to tmpDir. + wd, err := os.Getwd() + s.Require().NoError(err) + defer func() { _ = os.Chdir(wd) }() + s.Require().NoError(os.Chdir(s.T().TempDir())) // unrelated working directory + + s.Require().NoError(s.repo.Init(s.Ctx())) + + info, err := os.Stat(filepath.Join(s.tmpDir, ".git")) + s.Require().NoError(err) + s.True(info.IsDir()) +} diff --git a/internal/storage/domain/git/suite_test.go b/internal/storage/domain/git/suite_test.go new file mode 100644 index 000000000..faa966a78 --- /dev/null +++ b/internal/storage/domain/git/suite_test.go @@ -0,0 +1,58 @@ +package git + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "testing" + + "github.com/stretchr/testify/suite" + + "github.com/steveyegge/beads/internal/storage/domain" +) + +type testSuite struct { + suite.Suite + repo domain.GitRepository + tmpDir string +} + +func (s *testSuite) SetupSuite() { + if _, err := exec.LookPath("git"); err != nil { + s.T().Skip("git binary not found") + } +} + +func (s *testSuite) SetupTest() { + s.tmpDir = s.T().TempDir() + s.repo = NewGitRepository(s.tmpDir) +} + +func (s *testSuite) Ctx() context.Context { + return context.Background() +} + +func (s *testSuite) gitInit() { + s.T().Helper() + s.run("git", "init", "-q") + s.run("git", "config", "user.email", "test@example.com") + s.run("git", "config", "user.name", "test") + s.run("git", "config", "commit.gpgsign", "false") +} + +func (s *testSuite) run(name string, args ...string) { + s.T().Helper() + cmd := exec.Command(name, args...) + cmd.Dir = s.tmpDir + s.Require().NoError(cmd.Run()) +} + +func (s *testSuite) writeFile(rel, body string) { + s.T().Helper() + s.Require().NoError(os.WriteFile(filepath.Join(s.tmpDir, rel), []byte(body), 0600)) +} + +func TestDomainGit(t *testing.T) { + suite.Run(t, &testSuite{}) +} diff --git a/internal/storage/fs/provider.go b/internal/storage/fs/provider.go index 01cfc556c..8ffa7efb6 100644 --- a/internal/storage/fs/provider.go +++ b/internal/storage/fs/provider.go @@ -9,11 +9,17 @@ type FileSystemProvider interface { BeadsDirFSUseCase() domain.BeadsDirFSUseCase } -func NewFileSystemProvider(adapters domain.BeadsDirFSAdapters) FileSystemProvider { - return &fileSystemProviderImpl{adapters: adapters} +func NewFileSystemProvider(workDir string, templates domain.BeadsDirTemplates, adapters domain.BeadsDirFSAdapters) FileSystemProvider { + return &fileSystemProviderImpl{ + workDir: workDir, + templates: templates, + adapters: adapters, + } } type fileSystemProviderImpl struct { + workDir string + templates domain.BeadsDirTemplates adapters domain.BeadsDirFSAdapters beadsDirFSUseCase domain.BeadsDirFSUseCase } @@ -23,7 +29,7 @@ var _ FileSystemProvider = (*fileSystemProviderImpl)(nil) func (p *fileSystemProviderImpl) BeadsDirFSUseCase() domain.BeadsDirFSUseCase { if p.beadsDirFSUseCase == nil { p.beadsDirFSUseCase = domain.NewBeadsDirFSUseCase( - domainfs.NewBeadsDirFSRepository(), + domainfs.NewBeadsDirFSRepository(p.workDir, p.templates), p.adapters, ) } diff --git a/internal/storage/git/provider.go b/internal/storage/git/provider.go new file mode 100644 index 000000000..f5b77001b --- /dev/null +++ b/internal/storage/git/provider.go @@ -0,0 +1,28 @@ +package git + +import ( + "github.com/steveyegge/beads/internal/storage/domain" + domaingit "github.com/steveyegge/beads/internal/storage/domain/git" +) + +type GitProvider interface { + GitUseCase() domain.GitUseCase +} + +func NewGitProvider(workDir string) GitProvider { + return &gitProviderImpl{workDir: workDir} +} + +type gitProviderImpl struct { + workDir string + gitUseCase domain.GitUseCase +} + +var _ GitProvider = (*gitProviderImpl)(nil) + +func (p *gitProviderImpl) GitUseCase() domain.GitUseCase { + if p.gitUseCase == nil { + p.gitUseCase = domain.NewGitUseCase(p.workDir, domaingit.NewGitRepository(p.workDir)) + } + return p.gitUseCase +} From e9ece3a1272e7b9518908a50ba44d813fa553f3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?coffeegoddd=E2=98=95=EF=B8=8F=E2=9C=A8?= Date: Tue, 19 May 2026 15:47:57 -0700 Subject: [PATCH 3/5] /{cmd,internal}: cleanup --- cmd/bd/init_proxied_server.go | 36 ++++++++------------- internal/storage/domain/beads.go | 2 ++ internal/storage/uow/doltserver_provider.go | 2 -- 3 files changed, 16 insertions(+), 24 deletions(-) diff --git a/cmd/bd/init_proxied_server.go b/cmd/bd/init_proxied_server.go index 86eaccdd4..1f373b309 100644 --- a/cmd/bd/init_proxied_server.go +++ b/cmd/bd/init_proxied_server.go @@ -87,6 +87,8 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie } beadsDir, hasExplicitBeadsDir := proxiedInit.BeadsDir, proxiedInit.HasExplicit dbName, projectID := proxiedInit.DBName, proxiedInit.ProjectID + beadsDirIsLocal := proxiedInit.IsLocal + useLocalBeads := !hasExplicitBeadsDir || beadsDirIsLocal if strings.Contains(filepath.Clean(cwd), string(filepath.Separator)+".beads"+string(filepath.Separator)) || strings.HasSuffix(filepath.Clean(cwd), string(filepath.Separator)+".beads") { @@ -95,16 +97,6 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie os.Exit(1) } - beadsDirAbs, err := filepath.Abs(beadsDir) - if err != nil { - beadsDirAbs = filepath.Clean(beadsDir) - } - - cwdAbs, _ := filepath.Abs(cwd) - beadsDirIsLocal := strings.HasPrefix(beadsDirAbs, filepath.Clean(cwdAbs)+string(filepath.Separator)) || - filepath.Clean(beadsDirAbs) == filepath.Clean(cwdAbs) - useLocalBeads := !hasExplicitBeadsDir || beadsDirIsLocal - if !hasExplicitBeadsDir { res, err := gitUC.EnsureGitRepo(ctx) if err != nil { @@ -284,7 +276,9 @@ type runInitTailContext struct { } func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initProxiedServerInput, t runInitTailContext) { - if t.gitUC.IsGitRepo(ctx) { + isRepo := t.gitUC.IsGitRepo(ctx) + + if isRepo { role := in.roleFlag if role == "" { role = "maintainer" @@ -302,7 +296,7 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr if err := t.fsUseCase.SetupForkExclude(ctx, !in.quiet); err != nil { fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err) } - } else if !in.stealth && t.gitUC.IsGitRepo(ctx) { + } else if !in.stealth && isRepo { if isFork, upstreamURL, _ := t.gitUC.DetectFork(ctx); isFork { if in.nonInteractive { if err := t.fsUseCase.SetupForkExclude(ctx, !in.quiet); err != nil { @@ -341,7 +335,7 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr fmt.Printf(" Hooks installed (jujutsu mode - no staging)\n") } default: - if t.gitUC.IsGitRepo(ctx) { + if isRepo { hooksParams := domain.HooksInstallParams{ HookNames: managedHookNames, BeadsHooks: true, @@ -372,7 +366,8 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr if resolvedAgentsFile == "" { resolvedAgentsFile = config.SafeAgentsFile() } - if t.gitUC.IsBareGitRepo(ctx) { + isBare := t.gitUC.IsBareGitRepo(ctx) + if isBare { if !in.quiet { fmt.Printf(" Skipping %s generation in bare repository\n", resolvedAgentsFile) } @@ -384,16 +379,13 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr Profile: agentsProfileStr, HasRemote: t.remoteURL != "", }) + if err := t.fsUseCase.InstallClaudeProject(ctx, in.stealth); err != nil && !in.quiet { + fmt.Fprintf(os.Stderr, "Warning: failed to setup Claude hooks: %v\n", err) + } } } - if !in.stealth && !in.skipAgents && !t.gitUC.IsBareGitRepo(ctx) { - if err := t.fsUseCase.InstallClaudeProject(ctx, in.stealth); err != nil && !in.quiet { - fmt.Fprintf(os.Stderr, "Warning: failed to setup Claude hooks: %v\n", err) - } - } - - if !in.stealth && t.gitUC.IsGitRepo(ctx) && t.useLocalBeads { + if !in.stealth && isRepo && t.useLocalBeads { commitResult, err := t.gitUC.CommitInitArtifacts(ctx, domain.CommitInitArtifactsParams{ BeadsDir: ".beads/", OptionalPaths: []string{ @@ -413,7 +405,7 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr } } - if t.gitUC.IsGitRepo(ctx) && !in.quiet { + if isRepo && !in.quiet { if t.gitUC.HasAnyRemotes(ctx) && !t.gitUC.HasUpstream(ctx) { fmt.Fprintf(os.Stderr, "\n%s Git upstream not configured\n", ui.RenderWarn("⚠")) fmt.Fprintf(os.Stderr, " For sync workflows, set your upstream with:\n") diff --git a/internal/storage/domain/beads.go b/internal/storage/domain/beads.go index 09364f5db..cf882796c 100644 --- a/internal/storage/domain/beads.go +++ b/internal/storage/domain/beads.go @@ -54,6 +54,7 @@ type ResolveProxiedInitParams struct { type ResolveProxiedInitResult struct { BeadsDir string HasExplicit bool + IsLocal bool DBName string ProjectID string } @@ -143,6 +144,7 @@ func (u *beadsDirFSUseCaseImpl) ResolveProxiedInit(ctx context.Context, params R result := ResolveProxiedInitResult{ BeadsDir: resolution.BeadsDir, HasExplicit: resolution.HasExplicit, + IsLocal: u.fsRepo.BeadsDirIsLocal(ctx), } cfg, err := u.fsRepo.ReadBeadsConfig(ctx) diff --git a/internal/storage/uow/doltserver_provider.go b/internal/storage/uow/doltserver_provider.go index 637e37451..3bf158b4e 100644 --- a/internal/storage/uow/doltserver_provider.go +++ b/internal/storage/uow/doltserver_provider.go @@ -166,8 +166,6 @@ func openDB(ctx context.Context, dsn string) (*sql.DB, error) { func (p *doltServerProvider) initSchema(ctx context.Context, database string) error { bo := backoff.NewExponentialBackOff() bo.InitialInterval = 25 * time.Millisecond - // Must exceed schema.MigrateUpWithLock's 5s GET_LOCK wait so a - // contended schema migration can time out once and still retry. bo.MaxElapsedTime = 15 * time.Second return backoff.Retry(func() error { conn, err := p.db.Conn(ctx) From ba36b678c3167782370709fb4d3a40ad2fccf0b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?coffeegoddd=E2=98=95=EF=B8=8F=E2=9C=A8?= Date: Tue, 19 May 2026 16:00:25 -0700 Subject: [PATCH 4/5] /{cmd,internal}: more cleanup --- cmd/bd/init_templates.go | 5 ----- cmd/bd/main.go | 4 ++-- internal/storage/domain/beads.go | 25 ++++-------------------- internal/storage/domain/config.go | 3 --- internal/storage/domain/db/config.go | 4 ---- internal/storage/domain/fs/beads.go | 6 ------ internal/storage/domain/fs/suite_test.go | 2 -- 7 files changed, 6 insertions(+), 43 deletions(-) diff --git a/cmd/bd/init_templates.go b/cmd/bd/init_templates.go index 4ea3bb874..b1e25684f 100644 --- a/cmd/bd/init_templates.go +++ b/cmd/bd/init_templates.go @@ -24,9 +24,6 @@ func createConfigYaml(beadsDir string, noDbMode bool, prefix string) error { return nil } -// renderInitConfigYAML returns the canonical config.yaml body produced by -// bd init. When noDbMode is true, the prefix is baked into the file (since -// there's no database to store it). func renderInitConfigYAML(prefix string, noDbMode bool) []byte { noDbLine := "# no-db: false" if noDbMode { @@ -97,7 +94,6 @@ func renderInitConfigYAML(prefix string, noDbMode bool) []byte { return []byte(body) } -// BeadsReadmeTemplate is the canonical .beads/README.md content written during init. const BeadsReadmeTemplate = `# Beads - AI-Native Issue Tracking Welcome to Beads! This repository uses **Beads** for issue tracking - a modern, AI-native tool designed to live directly in your codebase alongside your code. @@ -181,7 +177,6 @@ bd create "Try out Beads" *Beads: Issue tracking that moves at the speed of thought* ⚡ ` -// createReadme creates the README.md file in the .beads directory. func createReadme(beadsDir string) error { readmePath := filepath.Join(beadsDir, "README.md") diff --git a/cmd/bd/main.go b/cmd/bd/main.go index 0a086fa06..71fa0b2bd 100644 --- a/cmd/bd/main.go +++ b/cmd/bd/main.go @@ -69,8 +69,8 @@ var changeDirEnvSnapshot map[string]envSnapshotValue var ( sandboxMode bool - globalFlag bool // Use the global shared-server database (beads_global) - serverMode bool // True when using external dolt sql-server (dolt_mode=server) + globalFlag bool + serverMode bool proxiedServerMode bool readonlyMode bool // Read-only mode: block write operations (for worker sandboxes) storeIsReadOnly bool // Track if store was opened read-only (for staleness checks) diff --git a/internal/storage/domain/beads.go b/internal/storage/domain/beads.go index cf882796c..2dfc058bc 100644 --- a/internal/storage/domain/beads.go +++ b/internal/storage/domain/beads.go @@ -59,9 +59,6 @@ type ResolveProxiedInitResult struct { ProjectID string } -// BeadsDirTemplates carries the text bodies the repository writes during init. -// Passing them in lets the CLI keep canonical copies (e.g. doctor.GitignoreTemplate) -// rather than maintaining duplicates inside the storage layer. type BeadsDirTemplates struct { BeadsGitignore string ProjectGitignoreHeader string @@ -70,22 +67,11 @@ type BeadsDirTemplates struct { } type InitializeBeadsDirParams struct { - MetadataJSONBody []byte - ConfigYAMLBody []byte - - // WriteProjectGitignore, when true, appends Dolt/beads patterns to the - // project-root .gitignore (workDir/.gitignore). + MetadataJSONBody []byte + ConfigYAMLBody []byte WriteProjectGitignore bool - - // SetNoCOW, when true, applies FS_NOCOW_FL to BeadsDir after creation. - // Best-effort: failures surface in InitializeBeadsDirResult.NoCOWErr, - // not the returned error. - SetNoCOW bool - - // LocalVersion, when non-empty, writes BeadsDir/.local_version with - // the given value. Best-effort: failures surface in - // InitializeBeadsDirResult.LocalVersionErr, not the returned error. - LocalVersion string + SetNoCOW bool + LocalVersion string } type InitializeBeadsDirResult struct { @@ -109,9 +95,6 @@ type AgentsFileParams struct { HasRemote bool } -// BeadsDirFSAdapters wires the use case's non-trivial side effects to the -// CLI-side helper implementations. Each adapter is optional at the type -// level; methods that depend on a nil adapter return a configuration error. type BeadsDirFSAdapters struct { ApplyNoCOW func(path string) error WriteLocalVersion func(path, version string) error diff --git a/internal/storage/domain/config.go b/internal/storage/domain/config.go index f9624928f..74c006cfe 100644 --- a/internal/storage/domain/config.go +++ b/internal/storage/domain/config.go @@ -11,7 +11,6 @@ type ConfigSQLRepository interface { SetLocalMetadata(ctx context.Context, key, value string) error GetConfig(ctx context.Context, key string) (string, error) SetConfig(ctx context.Context, key, value string) error - GetStatistics(ctx context.Context) (Statistics, error) } type ConfigUseCase interface { @@ -22,8 +21,6 @@ type Issue struct{} type BatchCreateOptions struct{} -type Statistics struct{} - type GlobalDatabaseParams struct{} type ImportResult struct{} diff --git a/internal/storage/domain/db/config.go b/internal/storage/domain/db/config.go index 9afddd360..4d4e9ac27 100644 --- a/internal/storage/domain/db/config.go +++ b/internal/storage/domain/db/config.go @@ -67,7 +67,3 @@ func (r *configSQLRepositoryImpl) SetConfig(ctx context.Context, key, value stri } return nil } - -func (r *configSQLRepositoryImpl) GetStatistics(ctx context.Context) (domain.Statistics, error) { - return domain.Statistics{}, nil -} diff --git a/internal/storage/domain/fs/beads.go b/internal/storage/domain/fs/beads.go index 4ee254bca..ba8e22e44 100644 --- a/internal/storage/domain/fs/beads.go +++ b/internal/storage/domain/fs/beads.go @@ -17,10 +17,6 @@ import ( "github.com/steveyegge/beads/internal/utils" ) -// NewBeadsDirFSRepository binds the repository to a project working directory -// and the canonical templates the caller wants written into .beads/. Paths are -// derived from workDir at construction time; the BEADS_DIR env variable, if set, -// still overrides the .beads location (HasExplicit will be true in that case). func NewBeadsDirFSRepository(workDir string, templates domain.BeadsDirTemplates) domain.BeadsDirFSRepository { beadsDir, hasExplicit := resolveBeadsDir(workDir) return &beadsDirFSRepositoryImpl{ @@ -44,8 +40,6 @@ func resolveBeadsDir(workDir string) (string, bool) { if envBeadsDir := os.Getenv("BEADS_DIR"); envBeadsDir != "" { return utils.CanonicalizePath(envBeadsDir), true } - // GetWorktreeFallbackBeadsDir still uses cwd-derived git context; in - // practice init runs with workDir == cwd, so this is consistent. if dir := beads.GetWorktreeFallbackBeadsDir(); dir != "" { return dir, false } diff --git a/internal/storage/domain/fs/suite_test.go b/internal/storage/domain/fs/suite_test.go index 5e92235eb..04967b398 100644 --- a/internal/storage/domain/fs/suite_test.go +++ b/internal/storage/domain/fs/suite_test.go @@ -18,8 +18,6 @@ func (s *testSuite) Ctx() context.Context { return context.Background() } -// newRepo returns a fresh (workDir, beadsDir, repo) for an isolated subtest. -// The repo is bound to workDir; beadsDir is workDir/.beads. func (s *testSuite) newRepo() (workDir, beadsDir string, repo domain.BeadsDirFSRepository) { s.T().Helper() s.T().Setenv("BEADS_DIR", "") From 24a1a93b0a8591e536914cf337d6ad66d635c337 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?coffeegoddd=E2=98=95=EF=B8=8F=E2=9C=A8?= Date: Tue, 19 May 2026 16:09:43 -0700 Subject: [PATCH 5/5] /.github/workflows/ci.yml: run tests in CI --- .github/workflows/ci.yml | 45 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6d73cf718..c7e2742dd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -209,6 +209,51 @@ jobs: report_type: test_results fail_ci_if_error: false + # Focused job for the hexagonal storage layer (internal/storage/domain/* and + # internal/storage/uow). These packages back the proxied-server init path and + # also live behind the existing ./... matrix, but TestDomainDB requires the + # Dolt sql-server image cached locally (testcontainers checks `docker image + # inspect` and skips otherwise). Pulling the image up front guarantees the + # suite actually runs and surfaces failures here with a clear job name. + test-domain-uow: + name: Test (storage domain + uow) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + + - name: Set up Go + uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6 + with: + go-version-file: 'go.mod' + + - name: Install Dolt CLI + run: curl -fsSL https://github.com/dolthub/dolt/releases/latest/download/install.sh | sudo bash + + - name: Verify dolt on PATH + run: dolt version + + - name: Configure Git and Dolt identity + run: | + git config --global user.name "CI Bot" + git config --global user.email "ci@beads.test" + dolt config --global --add user.name "CI Bot" + dolt config --global --add user.email "ci@beads.test" + + - name: Pull Dolt sql-server image + # Keep tag in sync with internal/testutil/testdoltcommon.go:DoltDockerImage. + # Without this, RequireDoltContainer reports doltNoImage and TestDomainDB skips. + run: docker pull dolthub/dolt-sql-server:1.88.1 + + - name: Pre-build bd binary for uow concurrent test + # internal/storage/uow tests spin up the proxy which re-execs `bd`. The + # BEADS_TEST_BD_BINARY env var lets the test skip the per-process build. + run: go build -tags gms_pure_go -o /tmp/bd-uow-test ./cmd/bd + + - name: Test domain + uow + env: + BEADS_TEST_BD_BINARY: /tmp/bd-uow-test + run: go test -tags gms_pure_go -race -count=1 -v ./internal/storage/domain/... ./internal/storage/uow/... + # Embedded Dolt tests - test the in-process Dolt engine (no server required) # # Split into: build → storage tests + parallel cmd test shards.