From 822fd01aa8d16ad001dc36697f15b688b15cea3d Mon Sep 17 00:00:00 2001 From: matt wilkie Date: Fri, 31 Jul 2026 09:41:41 -0700 Subject: [PATCH] fix(init): re-init inherits the workspace's connection mode instead of silently rewriting it (#3885) (#5189) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(init): re-init inherits the workspace's connection mode instead of silently rewriting it (#3885) `bd init --from-jsonl --reinit-local` (and `--force`, its deprecated alias) on a server-mode project came back embedded. init derived the persisted mode from process state alone: switch { case usesProxiedServer(): cfg.DoltMode = DoltModeProxiedServer case usesSQLServer(): cfg.DoltMode = DoltModeServer default: cfg.DoltMode = DoltModeEmbedded } and the globals behind usesSQLServer()/usesProxiedServer() are seeded only from --server, the BEADS_DOLT_* env vars, or the global config.yaml dolt.mode — never from the existing metadata.json. So re-running init without re-passing --server wrote dolt_mode: embedded over a server config, with no warning. The project came back half-configured, exactly as reported. The fix seeds the mode from the existing workspace alongside the other mode sources, rather than patching cfg.DoltMode where it is persisted. That placement is the point: everything between the two — which engine init opens, which database-name rules apply, where the data lands — reads the process mode. A late fixup would write "server" into metadata.json describing a database init had just built embedded, trading a silent downgrade for a silent mismatch. Inheritance applies only when the invocation names no mode of its own, so an explicit --server/--shared-server/--proxied-server, the BEADS_DOLT_* env vars, and a global dolt.mode all still win. A flag set explicitly to its default (--server=false) counts as explicit too: the user typed it. Any actual mode change on an existing workspace is now announced on stderr, naming both modes, since it moves where the project's data lives. Two helpers, both mirroring existingWorkspaceDBName's established shape: - existingWorkspaceDoltMode() reads the raw DoltMode field, normalized for case/space like configfile's own IsServerMode. Unset stays distinguishable from "deliberately embedded" — defaulting would make every fresh init look like a mode change. - initModeExplicitlyRequested(cmd) is the flag/env/config decision, pure enough to table-test. Tests: cmd/bd/init_mode_inherit_test.go covers both helpers, including the regression direction that matters (a bare re-init must NOT count as an explicit request, or #3885 returns). Note on local validation: the pre-existing cmd/bd init suite cannot be run from a worktree nested under another beads workspace — those tests resolve the ambient .beads and fail identically on unmodified upstream/main in that layout. Verified that baseline before concluding this change is clean; the new tests and go vet pass, and full `make test` is in the local verification queue. Agent-Signature: claude-opus-5-medium on behalf of maphew * review fix: proxied-server re-init refuses instead of silently building embedded The inheritance block runs after the proxied init path has already dispatched on the explicit flag, so 'inheriting' proxied-server by setting only the process-mode globals built the database embedded while metadata.json kept claiming proxied-server — a worse mismatch than the bug being fixed, and it partially resurrected a dark-launched mode. The decision now lives in inheritWorkspaceDoltMode(): server inherits, proxied-server refuses with re-run guidance, and the composition has unit coverage for all four workspace shapes. Agent-Signature: claude-code-claude-fable-5-unknown-reasoning on behalf of Steve Yegge Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01Xmjba2GjaHnrvaU2sM8Kz5 --------- Co-authored-by: Beadwright Co-authored-by: Claude Fable 5 --- cmd/bd/init.go | 118 +++++++++++++++++++ cmd/bd/init_mode_inherit_test.go | 188 +++++++++++++++++++++++++++++++ 2 files changed, 306 insertions(+) create mode 100644 cmd/bd/init_mode_inherit_test.go diff --git a/cmd/bd/init.go b/cmd/bd/init.go index 2f7f8758d..7c546c138 100644 --- a/cmd/bd/init.go +++ b/cmd/bd/init.go @@ -552,6 +552,36 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): // Non-fatal - continue with defaults } + // Re-init inherits the existing workspace's connection mode (#3885). + // + // This must be seeded HERE, with the other mode sources, not patched + // onto cfg.DoltMode where it is persisted further down: everything + // between the two points — which engine init opens, which database + // name rules apply, where the data lands — reads the process mode. A + // late fixup would write "server" into metadata.json describing a + // database that init had just built embedded, trading a silent + // downgrade for a silent mismatch. + // + // Only applies when this invocation names no mode of its own, so an + // explicit --server/--shared-server/--proxied-server, the BEADS_DOLT_* + // env vars, and a global dolt.mode all still win. + if !initServerMode && !initModeExplicitlyRequested(cmd) { + inheritServer, inheritErr := inheritWorkspaceDoltMode() + if inheritErr != nil { + return inheritErr + } + if inheritServer { + initServerMode = true + serverMode = true + if cmdCtx != nil { + cmdCtx.ServerMode = true + } + if !quiet { + fmt.Fprintln(os.Stderr, "Preserving server mode from the existing .beads/metadata.json.") + } + } + } + // config.yaml fallback for dolt.mode: if --server wasn't passed and // env var didn't set it, check config.yaml for dolt.mode: server. if !initServerMode { @@ -1490,6 +1520,10 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): } // Persist the connection mode matching this build. + priorMode := "" + if existingCfg != nil { + priorMode = strings.ToLower(strings.TrimSpace(existingCfg.DoltMode)) + } switch { case usesProxiedServer(): cfg.DoltMode = configfile.DoltModeProxiedServer @@ -1498,6 +1532,17 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): default: cfg.DoltMode = configfile.DoltModeEmbedded } + // A mode change on an existing workspace is never silent + // (#3885). By this point the inheritance above has already + // preserved the old mode unless something explicitly asked to + // change it, so reaching here with a different mode means the + // user asked — but they still get told, because the change + // rewrites where this project's data lives. + if priorMode != "" && priorMode != cfg.DoltMode && !quiet { + fmt.Fprintf(os.Stderr, + "Connection mode changed: %s -> %s (recorded in .beads/metadata.json).\n", + priorMode, cfg.DoltMode) + } if !usesProxiedServer() { if serverHost != "" { @@ -2547,6 +2592,79 @@ func existingWorkspaceDBName() string { return cfg.DoltDatabase } +// existingWorkspaceDoltMode returns the connection mode recorded in the +// already-initialized workspace's metadata.json, or "" if there is none. +// +// Like existingWorkspaceDBName it reads the raw field rather than a getter: a +// getter that defaults to embedded would make "no recorded mode" and +// "deliberately embedded" indistinguishable, and this value is used to decide +// whether a re-init is about to change modes. +func existingWorkspaceDoltMode() string { + beadsDir := resolveInitBeadsDir() + if beadsDir == "" { + return "" + } + cfg, err := configfile.Load(beadsDir) + if err != nil || cfg == nil { + return "" + } + // Matched case-insensitively by callers, mirroring configfile's own + // IsServerMode/IsProxiedServerMode comparisons. + return strings.ToLower(strings.TrimSpace(cfg.DoltMode)) +} + +// inheritWorkspaceDoltMode is the decision half of #3885's fix: what a bare +// re-init adopts from the workspace it is re-initializing. It returns +// inheritServer=true when the workspace records server mode. +// +// Proxied-server is deliberately an error, not an inheritance: the dedicated +// proxied init path (runInitProxiedServer) dispatches on the explicit flag +// BEFORE the inheritance point in RunE, so inheriting by mutating only the +// process-mode globals would build the database embedded while metadata.json +// kept claiming proxied-server — the exact silent mismatch inheritance exists +// to prevent. The mode is experimental and dark-launched; a re-init of such a +// workspace must name it explicitly so it routes through the real init path. +func inheritWorkspaceDoltMode() (bool, error) { + switch existingWorkspaceDoltMode() { + case configfile.DoltModeServer: + return true, nil + case configfile.DoltModeProxiedServer: + return false, fmt.Errorf("this workspace is recorded as proxied-server in .beads/metadata.json; " + + "re-run with --proxied-server to keep it, or name another mode explicitly to change it") + default: + return false, nil + } +} + +// initModeExplicitlyRequested reports whether this invocation names a +// connection mode of its own, as opposed to falling back to the build default. +// +// Only an explicit request may change an existing workspace's mode. Without +// this distinction a bare `bd init --from-jsonl --reinit-local` on a +// server-mode project runs embedded and rewrites dolt_mode to embedded, which +// is #3885: the project comes back half-configured and the user is told +// nothing. +func initModeExplicitlyRequested(cmd *cobra.Command) bool { + for _, name := range []string{"server", "shared-server", "proxied-server"} { + if f := cmd.Flags().Lookup(name); f != nil && f.Changed { + return true + } + } + for _, env := range []string{ + "BEADS_DOLT_SERVER_MODE", + "BEADS_DOLT_SHARED_SERVER", + "BEADS_DOLT_PROXIED_SERVER", + } { + if os.Getenv(env) != "" { + return true + } + } + // A global config.yaml `dolt.mode` is a deliberate statement about this + // machine, so it counts as explicit too — the seeding block above already + // treats it like --server. + return config.GetYamlConfig("dolt.mode") != "" +} + func checkExistingBeadsData(prefix string) error { beadsDir := resolveInitBeadsDir() if beadsDir == "" { diff --git a/cmd/bd/init_mode_inherit_test.go b/cmd/bd/init_mode_inherit_test.go new file mode 100644 index 000000000..7f80637ca --- /dev/null +++ b/cmd/bd/init_mode_inherit_test.go @@ -0,0 +1,188 @@ +package main + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/spf13/cobra" + + "github.com/steveyegge/beads/internal/configfile" +) + +// writeWorkspaceMode lays down a .beads/metadata.json recording mode and +// points BEADS_DIR at it, which is what resolveInitBeadsDir consults first. +func writeWorkspaceMode(t *testing.T, mode string) string { + t.Helper() + beadsDir := filepath.Join(t.TempDir(), ".beads") + if err := os.MkdirAll(beadsDir, 0o755); err != nil { + t.Fatalf("mkdir .beads: %v", err) + } + body := map[string]string{"dolt_mode": mode, "dolt_database": "proj"} + blob, err := json.Marshal(body) + if err != nil { + t.Fatalf("marshal metadata: %v", err) + } + if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), blob, 0o644); err != nil { + t.Fatalf("write metadata.json: %v", err) + } + t.Setenv("BEADS_DIR", beadsDir) + return beadsDir +} + +// TestExistingWorkspaceDoltModeReadsRawField is the input half of #3885: the +// re-init path could not see the existing mode at all, because nothing read it. +func TestExistingWorkspaceDoltModeReadsRawField(t *testing.T) { + for _, tc := range []struct { + written string + want string + }{ + {configfile.DoltModeServer, configfile.DoltModeServer}, + {configfile.DoltModeProxiedServer, configfile.DoltModeProxiedServer}, + {configfile.DoltModeEmbedded, configfile.DoltModeEmbedded}, + // Case and whitespace are normalized, matching configfile's own + // IsServerMode comparison. + {" SERVER ", configfile.DoltModeServer}, + // Unset must stay distinguishable from "deliberately embedded"; + // defaulting here would make every fresh init look like a mode change. + {"", ""}, + } { + t.Run("mode="+tc.written, func(t *testing.T) { + writeWorkspaceMode(t, tc.written) + if got := existingWorkspaceDoltMode(); got != tc.want { + t.Errorf("existingWorkspaceDoltMode() = %q, want %q", got, tc.want) + } + }) + } +} + +func TestExistingWorkspaceDoltModeMissingWorkspace(t *testing.T) { + t.Setenv("BEADS_DIR", filepath.Join(t.TempDir(), "nope", ".beads")) + if got := existingWorkspaceDoltMode(); got != "" { + t.Errorf("existingWorkspaceDoltMode() = %q on a missing workspace, want \"\"", got) + } +} + +// newModeFlagCmd mirrors the mode-bearing flags init registers. +func newModeFlagCmd() *cobra.Command { + c := &cobra.Command{Use: "init"} + c.Flags().Bool("server", false, "") + c.Flags().Bool("shared-server", false, "") + c.Flags().Bool("proxied-server", false, "") + return c +} + +// TestInitModeExplicitlyRequested is the decision half: only an explicit +// request may change an existing workspace's mode. Get this wrong in the +// permissive direction and #3885 comes straight back — a bare re-init would +// once again count as "the user asked for embedded". +func TestInitModeExplicitlyRequested(t *testing.T) { + // Neutralize ambient signals; these tests are about the flags. + clearModeEnv := func(t *testing.T) { + t.Helper() + for _, e := range []string{ + "BEADS_DOLT_SERVER_MODE", + "BEADS_DOLT_SHARED_SERVER", + "BEADS_DOLT_PROXIED_SERVER", + } { + t.Setenv(e, "") + } + } + + t.Run("bare invocation is not explicit", func(t *testing.T) { + clearModeEnv(t) + if initModeExplicitlyRequested(newModeFlagCmd()) { + t.Error("a bare `bd init` counted as an explicit mode request; a re-init would silently rewrite the mode") + } + }) + + for _, flag := range []string{"server", "shared-server", "proxied-server"} { + t.Run("--"+flag+" is explicit", func(t *testing.T) { + clearModeEnv(t) + c := newModeFlagCmd() + if err := c.Flags().Set(flag, "true"); err != nil { + t.Fatalf("set --%s: %v", flag, err) + } + if !initModeExplicitlyRequested(c) { + t.Errorf("--%s was not treated as an explicit mode request", flag) + } + }) + } + + // A flag set to its default value still counts: the user typed it. + t.Run("--server=false is still explicit", func(t *testing.T) { + clearModeEnv(t) + c := newModeFlagCmd() + if err := c.Flags().Set("server", "false"); err != nil { + t.Fatalf("set --server=false: %v", err) + } + if !initModeExplicitlyRequested(c) { + t.Error("--server=false was ignored; an explicit downgrade request must not be overridden by inheritance") + } + }) + + for _, env := range []string{ + "BEADS_DOLT_SERVER_MODE", + "BEADS_DOLT_SHARED_SERVER", + "BEADS_DOLT_PROXIED_SERVER", + } { + t.Run(env+" is explicit", func(t *testing.T) { + clearModeEnv(t) + t.Setenv(env, "1") + if !initModeExplicitlyRequested(newModeFlagCmd()) { + t.Errorf("%s was not treated as an explicit mode request", env) + } + }) + } +} + +// TestInheritWorkspaceDoltMode covers the decision the RunE inheritance block +// applies — the composition a helper-only test suite would miss (#3885 review). +// The proxied-server case is the load-bearing one: the proxied init path +// dispatches on the explicit flag before the inheritance point, so "inherit" +// there would build embedded data under proxied-server metadata. It must +// refuse instead. +func TestInheritWorkspaceDoltMode(t *testing.T) { + t.Run("server mode is inherited", func(t *testing.T) { + writeWorkspaceMode(t, configfile.DoltModeServer) + inheritServer, err := inheritWorkspaceDoltMode() + if err != nil { + t.Fatalf("inheritWorkspaceDoltMode() error: %v", err) + } + if !inheritServer { + t.Error("server-mode workspace was not inherited") + } + }) + + t.Run("embedded mode inherits nothing", func(t *testing.T) { + writeWorkspaceMode(t, configfile.DoltModeEmbedded) + inheritServer, err := inheritWorkspaceDoltMode() + if err != nil || inheritServer { + t.Errorf("embedded workspace: got (%v, %v), want (false, nil)", inheritServer, err) + } + }) + + t.Run("missing workspace inherits nothing", func(t *testing.T) { + t.Setenv("BEADS_DIR", filepath.Join(t.TempDir(), "nope", ".beads")) + inheritServer, err := inheritWorkspaceDoltMode() + if err != nil || inheritServer { + t.Errorf("missing workspace: got (%v, %v), want (false, nil)", inheritServer, err) + } + }) + + t.Run("proxied-server refuses rather than silently building embedded", func(t *testing.T) { + writeWorkspaceMode(t, configfile.DoltModeProxiedServer) + inheritServer, err := inheritWorkspaceDoltMode() + if inheritServer { + t.Fatal("proxied-server workspace was inherited as server mode") + } + if err == nil { + t.Fatal("proxied-server workspace did not refuse; a bare re-init would build embedded data under proxied-server metadata") + } + if !strings.Contains(err.Error(), "--proxied-server") { + t.Errorf("refusal does not tell the user how to proceed: %v", err) + } + }) +}