diff --git a/CHANGELOG.md b/CHANGELOG.md index 22a59939b..cea8f907d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1869,6 +1869,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **`bd init` refuses to initialize directly in your home directory** + ([#4635](https://github.com/gastownhall/beads/issues/4635)). `bd init` sets + up the directory it runs in as a project: it runs `git init` there unless it + finds a repository, and installs agent files — `CLAUDE.md`, `AGENTS.md`, + `.gitignore`, `.claude/`, `.codex/`, `.cursor/`, `.agents/`. In your home + directory most of those are your agents' user-wide settings, so bd's hooks + ended up running in every project, and init did this silently under + `--non-interactive`, which engages automatically whenever stdin is not a TTY + (so: whenever an agent runs it). A project is virtually never the home + directory itself, so this now refuses with exit code `15` + (`ExitHomeDirRefused`; `13` and `14` already mean a lost conditional-write + race and a migration freeze), documented at + `docs/recovery/init-safety.md#init-home-refused`. + + Deliberately narrow: it fires only when the working directory is *exactly* + your home directory, your home is not itself a git repository (tracked + dotfiles are unaffected, but a home that only sits inside an enclosing + repository, or a `GIT_DIR` inherited from the environment, does not count), + and you did not name a `BEADS_DIR` yourself. A subdirectory of home is an + ordinary project and is never refused. If you do name a `BEADS_DIR` from + an untracked home, init sets up only that workspace: no `git init`, no + agent files or `.gitignore` in your home directory, and nothing in a + repository your home sits inside (no hooks, `beads.role`, Dolt remote taken + from its origin, or bootstrap commit) unless a flag such as `--stealth` or + `--setup-exclude` asks for it. `--force` and + `--reinit-local` do not override the refusal — they bypass the local + data-safety guard, which is a different question from "is this the right + directory". The guard runs first in init's `RunE`, ahead of every path with + an effect, including the proxied dispatch and the store-opening + `--reinit-local` pre-checks. + - **The managed shared Dolt server now opens its configured remotesapi listener** ([#6020](https://github.com/gastownhall/beads/pull/6020)). `dolt.remotesapi-port` (machine-global user config) and diff --git a/cmd/bd/BUILD.bazel b/cmd/bd/BUILD.bazel index ca00a91a6..1a6cf07fc 100644 --- a/cmd/bd/BUILD.bazel +++ b/cmd/bd/BUILD.bazel @@ -886,6 +886,8 @@ go_test( "init_git_bootstrap_routing_test.go", "init_guard_force_e2e_test.go", "init_guard_test.go", + "init_home_guard_cgo_test.go", + "init_home_guard_test.go", "init_hooks_test.go", "init_metrics_test.go", "init_mode_inherit_test.go", diff --git a/cmd/bd/init.go b/cmd/bd/init.go index 6377f3779..a5b9cd9c8 100644 --- a/cmd/bd/init.go +++ b/cmd/bd/init.go @@ -7,6 +7,7 @@ import ( "fmt" "os" "os/exec" + "os/user" "path/filepath" "runtime" "strconv" @@ -322,6 +323,152 @@ func seedInitWorkspaceIdentity( return nil } +// resolveUserHomeDir returns the user's home directory. +// +// It prefers the OS account database over $HOME so the guard keys off the real +// account home even when $HOME has been repointed — which happens constantly in +// this repo's own tests, and in any sandbox that fakes a home. Both sources are +// best-effort: in a CGO-free build user.Current() falls back to os.UserHomeDir() +// (i.e. $HOME on Unix) itself, so this is a preference, not a guarantee of +// $HOME-independence. Mirrors the home resolution in internal/beads' +// isPathInSafeBoundary. +// +// A package var so tests can stub it. +var resolveUserHomeDir = func() string { + if u, err := user.Current(); err == nil && u.HomeDir != "" { + return u.HomeDir + } + home, _ := os.UserHomeDir() + return home +} + +// isUserHomeDir reports whether dir is the user's home directory (path-boundary +// comparison, symlink/case tolerant). Used to guard `bd init` against turning +// $HOME into a git repo (GH#4635). +func isUserHomeDir(dir string) bool { + home := resolveUserHomeDir() + return home != "" && utils.PathsEqual(dir, home) +} + +// isGitWorkTreeRoot reports whether dir is itself the top level of a git work +// tree. It asks through initArtifactGitCommand, the way init's own `git init` +// decision does, so git's routing environment is scrubbed: an inherited +// GIT_DIR or GIT_WORK_TREE cannot vouch for a directory that init's probe will +// then find untracked and `git init`. And the top level must be dir itself: a +// home that merely sits inside an ancestor's work tree was never tracked on +// purpose, and init would still install agent files into it. +func isGitWorkTreeRoot(dir string) bool { + out, err := initArtifactGitCommand(dir, "rev-parse", "--show-toplevel").Output() + if err != nil { + return false + } + return utils.PathsEqual(strings.TrimSpace(string(out)), dir) +} + +// guardInitInHomeDir refuses `bd init` directly in the user's home directory +// when that directory is not itself a git repository and the caller did not +// name a BEADS_DIR. +// +// `bd init` sets up the directory it runs in as a project: it runs `git init` +// there unless it finds a repository, and installs agent files (CLAUDE.md, +// AGENTS.md, .gitignore, .agents/, .codex/, .cursor/, .claude/settings.json). +// In the home directory most of those are the agents' user-wide settings, so +// bd's hooks would run in every project — a silent footgun, especially under +// --non-interactive, which auto-engages whenever stdin is not a TTY, i.e. +// whenever an agent runs init (GH#4635). A real project is virtually never the +// home directory itself. +// +// This runs as the first thing in init's RunE, ahead of every path that has an +// effect: the proxied dispatch (runInitProxiedServer -> EnsureGitRepo -> git +// init), the --reinit-local/--force pre-checks (countExistingIssues opens a +// real store, which creates the data directory and can run migrations), and +// the mode globals RunE sets on itself. A guard placed after any of those +// refuses only after the damage it exists to prevent. +// +// Fail-open by construction: an unresolvable home, a working directory that is +// not home, or a home that is itself a git repository all mean "not the case +// this guards", and init proceeds unchanged. +// +// A caller-supplied BEADS_DIR is the opt-out the refusal offers, and keepHomeClean +// holds it to what the refusal promises. Init proceeds, but does not set the +// home directory up as a project: an explicit BEADS_DIR already skips the +// `git init`, and keepHomeClean tells RunE to skip the agent files and the +// project .gitignore too. Without that, the recommended escape hatch still +// installed the user-wide agent settings the refusal exists to keep out of +// $HOME. +// +// keepHomeClean also means "outside every repository". It is only ever true +// when the home is not itself a work-tree root, so any repository git finds +// from here is not the home's own: one enclosing it (a dotfiles or monorepo +// checkout above it), or one an inherited GIT_DIR names. The opt-out must not +// set that repository up as the project either: no hooks, no beads.role or +// fork setup, no Dolt remote taken from its origin, and no bootstrap commit, +// which would stage the legacy ~/.beads and whatever agent files the home +// already has into it. Each route gates those on keepHomeClean where it +// reaches them. Flags that ask for a change there still make it: --stealth +// and --setup-exclude write its .git/info/exclude, and the interactive +// --contributor and --team wizards work in it. +// +// The opt-out check reads beadsDirFromCaller, NOT os.Getenv("BEADS_DIR"). By the +// time this runs the root PersistentPreRunE has already exported a beads dir it +// discovered for itself, and beads.FindBeadsDir() accepts any ancestor .beads/ +// holding a config.yaml — including this project's own legacy user-level +// ~/.beads/config.yaml. Keying off the live environment therefore made the +// guard fail open for exactly the long-standing users most likely to have +// scaffolding in $HOME worth not clobbering. `bd -C init` exported one +// too, and that one does not even move the working directory the scaffolding +// lands in. +// +// Refusals carry ExitHomeDirRefused so a script can branch on the number, like +// init's three other refusal classes. The message is printed here rather than +// returned so the exit code is the error's whole payload; docs/recovery/ +// init-safety.md#init-home-refused is the recovery playbook it points at. +func guardInitInHomeDir() (keepHomeClean bool, err error) { + cwd, wdErr := os.Getwd() + if wdErr != nil || !isUserHomeDir(cwd) || isGitWorkTreeRoot(cwd) { + return false, nil + } + if beadsDirFromCaller != "" { + return true, nil + } + fmt.Fprintf(os.Stderr, "%s\n", homeDirRefusalMessage(cwd)) + return false, &exitError{Code: ExitHomeDirRefused} +} + +// homeDirRefusalMessage is the What/Why/Next refusal text for a `bd init` run +// directly in an untracked home directory. +// +// The BEADS_DIR escape hatch is described as what it is: not the refused init +// with the guard lifted, but a different one that sets up only the workspace +// the caller names (see keepHomeClean in guardInitInHomeDir). Saying "set +// BEADS_DIR if you really mean it" without that caveat sends the user somewhere +// they did not intend to go. The `mkdir -p` is load-bearing, not decoration: +// init refuses a BEADS_DIR whose parent directory does not exist yet. +func homeDirRefusalMessage(cwd string) string { + return fmt.Sprintf(`bd init refuses: %s is your home directory, and it is not itself a git repository. + + Why: init sets up the directory it runs in as a project: it runs + 'git init' there unless it finds a repository, and installs agent + files (CLAUDE.md, AGENTS.md, .gitignore, .claude/, .codex/, + .cursor/, .agents/). In your home directory most of those are + user-wide agent settings, so bd's hooks would run in every project. + A project is virtually never the home directory itself. + + Next: + Initialize a project instead (recommended): + cd ~/some-project && bd init + + Keep the workspace in a directory you name, without setting up your + home directory as a project: + mkdir -p && BEADS_DIR=/.beads bd init + (a BEADS_DIR you name runs a DIFFERENT init: no git init, agent + files, .gitignore, hooks or commit here or in a repository around + it; the workspace lives in ) + + Recovery playbook: + docs/recovery/init-safety.md#init-home-refused`, cwd) +} + var initCmd = &cobra.Command{ Use: "init", GroupID: "setup", @@ -362,6 +509,14 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): • --contributor and --team flags are rejected (wizards require interaction) Also auto-detected when stdin is not a terminal or CI=true is set.`, RunE: func(cmd *cobra.Command, _ []string) (retErr error) { + // First, before anything with an effect: never turn $HOME into a git + // repo or install agent files into it (GH#4635). See + // guardInitInHomeDir for why the position matters. + keepHomeClean, homeErr := guardInitInHomeDir() + if homeErr != nil { + return homeErr + } + prefix, _ := cmd.Flags().GetString("prefix") quiet, _ := cmd.Flags().GetBool("quiet") contributor, _ := cmd.Flags().GetBool("contributor") @@ -400,6 +555,23 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): // before config/dirname fallback and before normalization. destroyTokenPrefix := prefix + // The caller named a BEADS_DIR from an untracked home directory: the + // opt-out the home refusal offers, held to what it promises. Skipping + // the agent files and hooks here covers both routes (the proxied one + // reads both from its input); the project .gitignore, the role and + // fork setup, the origin-derived Dolt remote and the bootstrap commit + // are gated on keepHomeClean where each route reaches them, because + // any repository around the home is not the project's (see + // guardInitInHomeDir). + if keepHomeClean { + skipAgents = true + skipHooks = true + if !quiet { + fmt.Fprintln(os.Stderr, "Note: this is your home directory, so init sets up only the workspace BEADS_DIR names: no agent files, .gitignore, hooks or commit here or in a repository around it.") + fmt.Fprintln(os.Stderr, " To install an agent integration for every project on purpose: bd setup --global") + } + } + // --force is a deprecated alias for --reinit-local. They share // semantics for the local data-safety guard; both refuse remote // divergence unless --discard-remote is also passed. See @@ -668,6 +840,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): stealth: stealth, skipHooks: skipHooks, skipAgents: skipAgents, + keepHomeClean: keepHomeClean, reinitLocal: reinitLocal, contributor: contributor, team: team, @@ -898,7 +1071,10 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): // --reinit-local / local init. hasData, err := gitRemoteHasDoltDataRefStatus(earlySyncURL) earlyRemoteHasDoltData, earlyProbeNote = resolveRemoteHasDoltDataProbe(earlySyncURL, hasData, err) - } else if earlyRemoteSource == initSyncRemoteNone && !stealth && isGitRepo() && !isBareGitRepo() { + } else if earlyRemoteSource == initSyncRemoteNone && !stealth && !keepHomeClean && isGitRepo() && !isBareGitRepo() { + // Not under keepHomeClean: a repository git finds from the + // home is not the project's, so its origin is not this + // workspace's remote (see guardInitInHomeDir). if originURL, err := gitOriginGetURL(); err == nil && originURL != "" { earlySyncURL = normalizeRemoteURL(originURL) hasData, probeErr := gitOriginHasDoltDataRefStatus() @@ -966,6 +1142,14 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): return fmt.Errorf("failed to get current directory: %v", err) } + // KNOWN GAP: this is the live BEADS_DIR, which may be one the root + // pre-run exported for itself rather than one the caller named — the + // distinction beadsDirFromCaller (main.go) exists for, and the one + // guardInitInHomeDir keys on. So a discovered beads dir counts as + // explicit here and skips the git init below. Left unchanged on + // purpose: reconciling init's caller-intent reads (this, + // beadsDirFromCaller, beadsDirProvidedAtStartup) changes init well + // beyond the home guard and belongs in its own change. hasExplicitBeadsDir := os.Getenv("BEADS_DIR") != "" // Use the beadsDir computed earlier (before any directory creation) @@ -1114,9 +1298,12 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): // may not be a repo we should mutate (e.g. running from a worktree // with an external BEADS_DIR). When BEADS_DIR points to the same // repo's .beads/, the gitignore update is still appropriate. + // Also skip it in an untracked home directory (keepHomeClean): a + // BEADS_DIR the caller names under $HOME is still "local" by this + // test, and ~/.gitignore is not this init's to edit (GH#4635). cwdAbs, _ := filepath.Abs(cwd) beadsDirIsLocal := strings.HasPrefix(beadsDirAbs, filepath.Clean(cwdAbs)+string(filepath.Separator)) - if beadsDirIsLocal { + if beadsDirIsLocal && !keepHomeClean { if stealth { // Stealth mode: route Dolt-file ignore patterns into .git/info/exclude instead // of a tracked .gitignore so collaborators never see beads-related changes. @@ -1285,7 +1472,8 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): fmt.Printf(" %s Remote has no Dolt data yet; initialized a fresh local database\n", ui.RenderWarn("!")) } } - } else if syncRemoteSource == initSyncRemoteNone && !stealth && isGitRepo() && !isBareGitRepo() { + } else if syncRemoteSource == initSyncRemoteNone && !stealth && !keepHomeClean && isGitRepo() && !isBareGitRepo() { + // keepHomeClean: as in the early remote check above. if originURL, err := gitOriginGetURL(); err == nil && originURL != "" { syncURL = normalizeRemoteURL(originURL) syncURLFromGitOrigin = true @@ -1891,12 +2079,19 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): } } + // projectRoleRepo is isInitRoleGitRepo held to keepHomeClean. The role, + // the fork routing (which also creates ~/.beads-planning) and the fork + // exclude below all write into the repository that probe finds, and + // under keepHomeClean that repository encloses the home instead of + // holding the project (see guardInitInHomeDir). + projectRoleRepo := func() bool { return !keepHomeClean && isInitRoleGitRepo(ctx) } + // Prompt for contributor mode if: // - In a git repo (needed to set beads.role config) // - Interactive terminal (stdin is TTY) and not --non-interactive // - No explicit --contributor or --team flag provided // - No explicit --role flag provided - if isInitRoleGitRepo(ctx) && !contributor && !team && roleFlag == "" && !nonInteractive && shouldPromptForRole() { + if projectRoleRepo() && !contributor && !team && roleFlag == "" && !nonInteractive && shouldPromptForRole() { promptedContributor, err := promptContributorMode() if err != nil { if isCanceled(err) { @@ -1911,7 +2106,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): } else if promptedContributor { contributor = true // Triggers contributor wizard below } - } else if isInitRoleGitRepo(ctx) && !contributor && !team { + } else if projectRoleRepo() && !contributor && !team { // If prompt was skipped (non-interactive or CI environment), // ensure beads.role is set to avoid "not configured" warning // during diagnostics. Use --role flag if provided, otherwise default. @@ -1947,7 +2142,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): // Contributor setup must also pin role detection to contributor. // Without this, SSH remotes can be inferred as maintainer and bypass routing. - if isInitRoleGitRepo(ctx) { + if projectRoleRepo() { if err := setBeadsRole("contributor"); err != nil && !quiet { fmt.Fprintf(os.Stderr, "Warning: failed to set beads.role=contributor: %v\n", err) } @@ -1980,7 +2175,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): // the write will then fail to reach. Gating on the inherited isGitRepo() // instead is what used to make this safety net write the role into a // redirected repository. - if isInitRoleGitRepo(ctx) { + if projectRoleRepo() { if _, hasRole := getBeadsRole(); !hasRole { fallbackRole := "maintainer" if roleFlag != "" { @@ -1996,7 +2191,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): // Non-interactive, idempotent; only fires when upstream remote detected // and routing.contributor is not already set. // This gate also enables planning-repository creation and config.yaml updates. - if !contributor && isInitRoleGitRepo(ctx) { + if !contributor && projectRoleRepo() { if err := autoConfigureForkContributor(ctx, store, quiet || nonInteractive, roleFlag); err != nil && !quiet { fmt.Fprintf(os.Stderr, "Warning: failed to auto-configure fork contributor routing: %v\n", err) } @@ -2039,7 +2234,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): if err := setupForkExcludeAt(cwd, !quiet); err != nil { fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err) } - } else if !stealth && isInitRoleGitRepo(ctx) { + } else if !stealth && projectRoleRepo() { // Auto-detect fork and prompt (skip if stealth - it handles exclude already) if isFork, upstreamURL := detectForkSetup(); isFork { if nonInteractive { @@ -2156,14 +2351,19 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): } } - if !stealth && useLocalBeads { + // Not under keepHomeClean: the repository git finds from the home is + // not the project's, and the commit would stage the legacy ~/.beads + // and the home's own agent files into it (see guardInitInHomeDir). + if !stealth && useLocalBeads && !keepHomeClean { commitEmbeddedInitArtifacts(cwd, quiet) } // Check for missing git upstream and warn if not configured. // Only warn when remotes exist (has origin but no upstream). // Skip for brand-new repos with no remotes — the warning is noise there. - if isGitRepo() && !quiet { + // Skip under keepHomeClean too: that advice is for a repository that + // is not the project's. + if isGitRepo() && !keepHomeClean && !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") diff --git a/cmd/bd/init_home_guard_cgo_test.go b/cmd/bd/init_home_guard_cgo_test.go new file mode 100644 index 000000000..eaea414b9 --- /dev/null +++ b/cmd/bd/init_home_guard_cgo_test.go @@ -0,0 +1,264 @@ +//go:build cgo + +package main + +import ( + "bytes" + "io/fs" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/beads" + "github.com/steveyegge/beads/internal/git" +) + +// TestInitInUntrackedHomeWithCallerBeadsDir_SetsUpOnlyTheWorkspace runs the +// opt-out the home refusal offers (`mkdir -p && BEADS_DIR=/.beads +// bd init`) from an untracked home, end to end. The refusal promises a +// different init, one that sets up the workspace and leaves the home alone: +// no git init, no agent files, no .gitignore. So the home is seeded with the +// files a real one has, and every one of them must come out unchanged, with +// nothing added beside them. +// +// Two shapes, because they reach different writes. A workspace outside the +// home is not "local" to the working directory, so the direct route skips the +// project .gitignore on its own; one under the home is local, and only +// keepHomeClean keeps init from appending to ~/.gitignore. +// +// A third puts the home inside another repository, as a dotfiles or monorepo +// checkout above it does. That repository is not the project's either (see +// guardInitInHomeDir), so it must come out as it went in: no commit and +// nothing staged, though the home holds a legacy ~/.beads for a bootstrap +// commit to pick up; no core.hooksPath or beads.role; and its origin not +// taken as the workspace's Dolt remote. It has no upstream remote: fork +// routing would create ~/.beads-planning under the suite's real HOME. +// +// The last two give that repository an origin git cannot reach, and run init +// with --reinit-local and with --force. A failed probe counts as Dolt history, +// so an early remote-safety check that still consulted the origin would +// refuse both with exit 10 (ExitRemoteDivergenceRefused). +// +// The home is stubbed rather than set through $HOME: the guard resolves the OS +// account home (resolveUserHomeDir), and HOME stays the suite's, which is +// where Dolt keeps its own global config. That is tool state, not the project +// setup this checks for. +func TestInitInUntrackedHomeWithCallerBeadsDir_SetsUpOnlyTheWorkspace(t *testing.T) { + skipIfNoDolt(t) + + cases := []struct { + name string + // workspace returns the directory that will hold .beads. + workspace func(t *testing.T, home string) string + // enclosed puts the home inside a git repository. + enclosed bool + // originGone leaves nothing at that repository's origin. + originGone bool + // flags are added to init's arguments. + flags []string + }{ + {name: "workspace_outside_home", workspace: func(t *testing.T, _ string) string { return t.TempDir() }}, + {name: "workspace_under_home", workspace: func(_ *testing.T, home string) string { return filepath.Join(home, "notes") }}, + {name: "home_inside_a_repository", workspace: func(t *testing.T, _ string) string { return t.TempDir() }, enclosed: true}, + {name: "unreachable_origin_reinit_local", workspace: func(t *testing.T, _ string) string { return t.TempDir() }, enclosed: true, originGone: true, flags: []string{"--reinit-local"}}, + {name: "unreachable_origin_force", workspace: func(t *testing.T, _ string) string { return t.TempDir() }, enclosed: true, originGone: true, flags: []string{"--force"}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + resetInitFlagsForServerInit(t) + + home := t.TempDir() + enclosing := "" + if tc.enclosed { + enclosing, home = home, filepath.Join(home, "home") + if err := os.Mkdir(home, 0o750); err != nil { + t.Fatal(err) + } + } + stubHomeDir(t, home) + workspace := tc.workspace(t, home) + if err := os.MkdirAll(workspace, 0o750); err != nil { + t.Fatal(err) + } + beadsDir := filepath.Join(workspace, ".beads") + stubCallerBeadsDir(t, beadsDir) + t.Setenv("BEADS_DIR", beadsDir) + t.Setenv("BD_NON_INTERACTIVE", "1") + + // What a home already has, and what init would otherwise write or + // append to there. + if err := os.MkdirAll(filepath.Join(home, ".claude"), 0o750); err != nil { + t.Fatal(err) + } + writeTestFile(t, filepath.Join(home, "AGENTS.md"), "# my own agent notes\n") + writeTestFile(t, filepath.Join(home, ".claude", "settings.json"), "{\"model\": \"mine\"}\n") + writeTestFile(t, filepath.Join(home, ".gitignore"), "*.swp\n") + var enclosingConfig []byte + if tc.enclosed { + enclosingConfig = initEnclosingRepo(t, enclosing, home, !tc.originGone) + } + before := snapshotHomeTree(t, home, workspace) + + t.Chdir(home) + beads.ResetCaches() + git.ResetCaches() + origStore, origDBPath := store, dbPath + t.Cleanup(func() { + if store != nil && store != origStore { + _ = store.Close() + } + store, dbPath = origStore, origDBPath + rootCmd.SetArgs(nil) + beads.ResetCaches() + git.ResetCaches() + }) + store, dbPath = nil, "" + + // The enclosed home runs without --quiet: its repository has an + // origin and no upstream, which is when init advises setting one, + // and the opt-out's note has to show. + args := []string{"init", "--server", "--database", uniqueTestDBName(t), "--prefix", "hg"} + if !tc.enclosed { + args = append(args, "--quiet") + } + args = append(args, tc.flags...) + rootCmd.SetArgs(args) + var execErr error + stderr := captureStderr(t, func() { execErr = rootCmd.Execute() }) + if execErr != nil { + t.Fatalf("BEADS_DIR=%s bd init from an untracked home failed: %v\n%s", beadsDir, execErr, stderr) + } + + if _, err := os.Stat(filepath.Join(beadsDir, "metadata.json")); err != nil { + t.Fatalf("init did not set up the workspace it was named: %v", err) + } + after := snapshotHomeTree(t, home, workspace) + for path, was := range before { + if now, ok := after[path]; !ok { + t.Errorf("init removed ~/%s", path) + } else if now != was { + t.Errorf("init changed ~/%s:\nbefore: %q\nafter: %q", path, was, now) + } + } + for path := range after { + if _, ok := before[path]; !ok { + t.Errorf("init created ~/%s in the home directory", path) + } + } + if tc.enclosed { + if !strings.Contains(stderr, "this is your home directory") { + t.Errorf("init did not note what the opt-out sets up:\n%s", stderr) + } + if strings.Contains(stderr, "Git upstream not configured") { + t.Errorf("init advised an upstream for the repository around the home:\n%s", stderr) + } + assertEnclosingRepoUntouched(t, enclosing, enclosingConfig, beadsDir) + } + }) + } +} + +// initEnclosingRepo makes dir, the directory around home, a repository with +// one commit and an origin, and gives home a legacy ~/.beads for a bootstrap +// commit to pick up. Unless originReachable, nothing exists at the origin's +// path, so git cannot reach it. It returns the repository's config as it +// stands. +func initEnclosingRepo(t *testing.T, dir, home string, originReachable bool) []byte { + t.Helper() + gitInitAt(t, dir) + origin := filepath.Join(t.TempDir(), "dotfiles.git") + steps := [][]string{ + {"-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "-c", "commit.gpgSign=false", "-c", "core.hooksPath=", "commit", "--allow-empty", "--quiet", "-m", "dotfiles"}, + {"remote", "add", "origin", origin}, + } + if originReachable { + steps = append(steps, []string{"init", "--quiet", "--bare", origin}) + } + for _, args := range steps { + if out, err := initArtifactGitCommand(dir, args...).CombinedOutput(); err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + } + if err := os.Mkdir(filepath.Join(home, ".beads"), 0o750); err != nil { + t.Fatal(err) + } + writeTestFile(t, filepath.Join(home, ".beads", "config.yaml"), "# legacy user-level config\n") + gitConfig, err := os.ReadFile(filepath.Join(dir, ".git", "config")) + if err != nil { + t.Fatal(err) + } + return gitConfig +} + +// assertEnclosingRepoUntouched checks that init left the repository around the +// home as initEnclosingRepo made it: one commit, nothing staged, the same +// config (so no core.hooksPath and no beads.role), and its origin not taken as +// the workspace's Dolt remote. +func assertEnclosingRepoUntouched(t *testing.T, dir string, gitConfig []byte, beadsDir string) { + t.Helper() + run := func(args ...string) (string, error) { + out, err := initArtifactGitCommand(dir, args...).Output() + return strings.TrimSpace(string(out)), err + } + if count, err := run("rev-list", "--count", "HEAD"); err != nil || count != "1" { + t.Errorf("init committed to the repository around the home: %s commits (%v)", count, err) + } + if staged, err := run("diff", "--cached", "--name-only"); err != nil || staged != "" { + t.Errorf("init staged into the repository around the home: %q (%v)", staged, err) + } + for _, key := range []string{"core.hooksPath", "beads.role"} { + if value, err := run("config", "--local", "--get", key); err == nil { + t.Errorf("init set %s = %q in the repository around the home", key, value) + } + } + if now, err := os.ReadFile(filepath.Join(dir, ".git", "config")); err != nil { + t.Fatal(err) + } else if !bytes.Equal(now, gitConfig) { + t.Errorf("init changed the config of the repository around the home:\nbefore: %q\nafter: %q", gitConfig, now) + } + if data, err := os.ReadFile(filepath.Join(beadsDir, "config.yaml")); err == nil && strings.Contains(string(data), "dotfiles.git") { + t.Errorf("init took the origin of the repository around the home as the workspace's Dolt remote:\n%s", data) + } +} + +// snapshotHomeTree maps every path under home, relative to it, to its mode and, +// for a regular file, its content. It skips the workspace when that lives +// under home: the workspace is init's to write. +func snapshotHomeTree(t *testing.T, home, workspace string) map[string]string { + t.Helper() + tree := map[string]string{} + err := filepath.WalkDir(home, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if path == home { + return nil + } + if path == workspace { + return filepath.SkipDir + } + rel, err := filepath.Rel(home, path) + if err != nil { + return err + } + info, err := d.Info() + if err != nil { + return err + } + entry := info.Mode().String() + if info.Mode().IsRegular() { + data, err := os.ReadFile(path) + if err != nil { + return err + } + entry += " " + string(data) + } + tree[rel] = entry + return nil + }) + if err != nil { + t.Fatal(err) + } + return tree +} diff --git a/cmd/bd/init_home_guard_test.go b/cmd/bd/init_home_guard_test.go new file mode 100644 index 000000000..626885fb5 --- /dev/null +++ b/cmd/bd/init_home_guard_test.go @@ -0,0 +1,413 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// TestIsUserHomeDir covers the guard decision used to refuse `bd init` directly +// in the user's home directory (GH#4635). The resolver is stubbed so the test +// does not depend on (or touch) the real home directory. +func TestIsUserHomeDir(t *testing.T) { + home := t.TempDir() + stubHomeDir(t, home) + + if !isUserHomeDir(home) { + t.Errorf("isUserHomeDir(home) = false, want true for %q", home) + } + if sub := filepath.Join(home, "project"); isUserHomeDir(sub) { + t.Errorf("isUserHomeDir(%q) = true, want false (subdir of home)", sub) + } + if parent := filepath.Dir(home); isUserHomeDir(parent) { + t.Errorf("isUserHomeDir(%q) = true, want false (parent of home)", parent) + } +} + +// TestIsUserHomeDir_UnresolvableHome verifies the guard never fires when the +// home directory cannot be resolved (fail-open: better to allow init than to +// wrongly refuse every directory). +func TestIsUserHomeDir_UnresolvableHome(t *testing.T) { + stubHomeDir(t, "") + + if isUserHomeDir("/some/dir") { + t.Error("isUserHomeDir should be false when home is unresolvable") + } +} + +// TestGuardInitInHomeDir covers the guard's three answers: refuse (an +// untracked home, no BEADS_DIR from the caller), proceed but keep the home +// clean (the same home, with one), and stand aside (a home that is itself a +// git repository, or any directory that simply is not home). +func TestGuardInitInHomeDir(t *testing.T) { + t.Run("refuses_in_untracked_home", func(t *testing.T) { + home := t.TempDir() + stubHomeDir(t, home) + t.Chdir(home) + stubCallerBeadsDir(t, "") + + _, err := guardInitInHomeDir() + if err == nil { + t.Fatal("guardInitInHomeDir() = nil, want a refusal in an untracked home") + } + assertHomeDirRefusal(t, err) + }) + + // The opt-out the refusal offers is a different init, not this one with + // the guard lifted: it may proceed, but it must not set the home up as a + // project (TestInitInUntrackedHomeWithCallerBeadsDir_SetsUpOnlyTheWorkspace + // runs it). + t.Run("caller_beads_dir_proceeds_but_keeps_home_clean", func(t *testing.T) { + home := t.TempDir() + stubHomeDir(t, home) + t.Chdir(home) + stubCallerBeadsDir(t, filepath.Join(home, "elsewhere", ".beads")) + + keepHomeClean, err := guardInitInHomeDir() + if err != nil { + t.Fatalf("guardInitInHomeDir() = %v, want nil when the caller named a BEADS_DIR", err) + } + if !keepHomeClean { + t.Error("keepHomeClean = false, want true: init would install agent files into the untracked home") + } + }) + + // The bypass this guard shipped with: BEADS_DIR in the live environment is + // not evidence the caller asked for anything. bd exports one itself for + // every no-DB command, and beads.FindBeadsDir() accepts an ancestor + // .beads/ holding nothing but a config.yaml — which is where this + // project's own legacy user-level config lives, at ~/.beads/config.yaml. + // So the users most likely to have scaffolding in $HOME worth protecting + // were exactly the ones the guard failed open for. + t.Run("refuses_when_bd_exported_beads_dir_for_itself", func(t *testing.T) { + home := t.TempDir() + stubHomeDir(t, home) + t.Chdir(home) + stubCallerBeadsDir(t, "") + // What the root pre-run does, and what `bd -C ` does: set the + // live env without the caller having named anything. + t.Setenv("BEADS_DIR", filepath.Join(home, ".beads")) + + _, err := guardInitInHomeDir() + if err == nil { + t.Fatal("guardInitInHomeDir() = nil; a bd-exported BEADS_DIR is not caller opt-in") + } + assertHomeDirRefusal(t, err) + }) + + // "Is this home tracked?" has to be asked the way init's own `git init` + // decision asks it, with git's routing environment scrubbed. A plain probe + // believes an inherited GIT_DIR, while init does not: it would find the + // home untracked, `git init` it and install agent files there. + t.Run("refuses_when_git_dir_is_inherited", func(t *testing.T) { + other := t.TempDir() + gitInitAt(t, other) + home := t.TempDir() + stubHomeDir(t, home) + t.Chdir(home) + stubCallerBeadsDir(t, "") + t.Setenv("GIT_DIR", filepath.Join(other, ".git")) + if !isGitRepo() { + t.Fatal("precondition: isGitRepo() = false under an inherited GIT_DIR, so this no longer reproduces the plain probe's false positive") + } + + _, err := guardInitInHomeDir() + if err == nil { + t.Fatal("guardInitInHomeDir() = nil; an inherited GIT_DIR does not make the home a repository") + } + assertHomeDirRefusal(t, err) + }) + + // Only a repository rooted at the home itself means someone set the home + // up on purpose. A home that merely sits inside an enclosing work tree + // still gets init's agent files, so it is refused like any untracked one, + // and a caller BEADS_DIR there is the same opt-out: keepHomeClean, which + // also keeps init out of the enclosing repository + // (TestInitInUntrackedHomeWithCallerBeadsDir_SetsUpOnlyTheWorkspace). + t.Run("refuses_when_home_only_sits_inside_an_enclosing_repo", func(t *testing.T) { + root := t.TempDir() + gitInitAt(t, root) + home := filepath.Join(root, "home") + if err := os.Mkdir(home, 0o750); err != nil { + t.Fatal(err) + } + stubHomeDir(t, home) + t.Chdir(home) + stubCallerBeadsDir(t, "") + if !isGitRepo() { + t.Fatal("precondition: isGitRepo() = false inside the enclosing repository, so this no longer reproduces the plain probe's false positive") + } + + _, err := guardInitInHomeDir() + if err == nil { + t.Fatal("guardInitInHomeDir() = nil; an enclosing repository does not make the home itself tracked") + } + assertHomeDirRefusal(t, err) + + stubCallerBeadsDir(t, filepath.Join(t.TempDir(), ".beads")) + if keepHomeClean, err := guardInitInHomeDir(); err != nil || !keepHomeClean { + t.Errorf("with a caller BEADS_DIR: guardInitInHomeDir() = (%v, %v), want (true, nil)", keepHomeClean, err) + } + }) + + // A home that is itself a repository was set up as a project on purpose, + // so init runs there exactly as anywhere else, BEADS_DIR or not. + t.Run("stands_aside_when_home_is_itself_a_git_repo", func(t *testing.T) { + home := t.TempDir() + stubHomeDir(t, home) + t.Chdir(home) + gitInitAt(t, home) + + for _, callerBeadsDir := range []string{"", filepath.Join(home, "notes", ".beads")} { + stubCallerBeadsDir(t, callerBeadsDir) + if keepHomeClean, err := guardInitInHomeDir(); err != nil || keepHomeClean { + t.Errorf("caller BEADS_DIR %q: guardInitInHomeDir() = (%v, %v), want (false, nil) in a tracked home", callerBeadsDir, keepHomeClean, err) + } + } + }) + + t.Run("stands_aside_in_an_ordinary_project_dir", func(t *testing.T) { + home := t.TempDir() + stubHomeDir(t, home) + project := filepath.Join(home, "project") + if err := os.MkdirAll(project, 0o750); err != nil { + t.Fatal(err) + } + t.Chdir(project) + + for _, callerBeadsDir := range []string{"", filepath.Join(home, "notes", ".beads")} { + stubCallerBeadsDir(t, callerBeadsDir) + if keepHomeClean, err := guardInitInHomeDir(); err != nil || keepHomeClean { + t.Errorf("caller BEADS_DIR %q: guardInitInHomeDir() = (%v, %v), want (false, nil) for a project dir under home", callerBeadsDir, keepHomeClean, err) + } + } + }) +} + +// TestInitCommand_RefusesInHomeDirBeforeAnySideEffect runs the actual init +// command, which is where the guard's *position* is under test rather than its +// decision. Both flag shapes below reach a side effect before the guard's +// original location did: +// +// - --reinit-local / --force run countExistingIssues, which opens a real +// store (creating the data directory, and able to run migrations); +// - --proxied-server dispatches to runInitProxiedServer, which calls +// EnsureGitRepo — a `git init` in the current directory. +// +// So the assertion is not merely "it errors": the home must still be empty. +// +// Every case also names a backend that cannot exist, as a circuit breaker: if +// the guard ever fails open, init stops at the unknown-backend check, ahead of +// every effect, and the failure below names the guard instead of a store being +// built in the temp home. +func TestInitCommand_RefusesInHomeDirBeforeAnySideEffect(t *testing.T) { + cases := []struct { + name string + flags map[string]string + }{ + {name: "plain", flags: nil}, + {name: "reinit_local", flags: map[string]string{"reinit-local": "true"}}, + {name: "force", flags: map[string]string{"force": "true"}}, + {name: "proxied_server", flags: map[string]string{"proxied-server": "true"}}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + home := t.TempDir() + stubHomeDir(t, home) + t.Chdir(home) + stubCallerBeadsDir(t, "") + t.Setenv("BEADS_DIR", "") + t.Setenv("BD_NON_INTERACTIVE", "1") + setInitFlag(t, "backend", homeGuardSentinelBackend) + for name, value := range tc.flags { + setInitFlag(t, name, value) + } + + err := initCmd.RunE(initCmd, nil) + if err == nil { + t.Fatal("bd init in an untracked home returned nil, want a refusal") + } + if strings.Contains(err.Error(), homeGuardSentinelBackend) { + t.Fatalf("init ran past the home guard and got as far as backend selection: %v", err) + } + assertHomeDirRefusal(t, err) + + // A refusal that still left something behind is not a refusal. + entries, readErr := os.ReadDir(home) + if readErr != nil { + t.Fatal(readErr) + } + for _, entry := range entries { + t.Errorf("init created %s in the home directory despite refusing", entry.Name()) + } + }) + } +} + +// homeGuardSentinelBackend is a --backend no bd can have: the home-guard +// tests' circuit breaker. Init rejects it before any effect, so a guard that +// fails open ends at that error, which names it, instead of at a real store. +const homeGuardSentinelBackend = "review4795-home-guard-sentinel" + +// assertHomeDirRefusal checks that err is the home-directory refusal, by its +// exit code rather than its message: the code is the scriptable contract +// (docs/recovery/init-safety.md#init-home-refused), the wording is not. +func assertHomeDirRefusal(t *testing.T, err error) { + t.Helper() + code, ok := exitCodeFromError(err) + if !ok { + t.Fatalf("refusal did not carry an exit code: %v", err) + } + if code != ExitHomeDirRefused { + t.Fatalf("exit code = %d, want %d (ExitHomeDirRefused)", code, ExitHomeDirRefused) + } +} + +// stubCallerBeadsDir sets what the guard sees as the caller-supplied BEADS_DIR. +// The real value is captured at package init from the inherited environment, so +// a test cannot move it with t.Setenv — which is the whole point of the +// snapshot, and why it has to be stubbed here instead. +func stubCallerBeadsDir(t *testing.T, dir string) { + t.Helper() + orig := beadsDirFromCaller + beadsDirFromCaller = dir + t.Cleanup(func() { beadsDirFromCaller = orig }) +} + +// stubHomeDir points the guard's home resolver at dir for the duration of the +// test. Stubbing rather than setting $HOME is deliberate: the resolver prefers +// the OS account database, so $HOME alone would not move it. +func stubHomeDir(t *testing.T, dir string) { + t.Helper() + orig := resolveUserHomeDir + resolveUserHomeDir = func() string { return dir } + t.Cleanup(func() { resolveUserHomeDir = orig }) +} + +// gitInitAt makes dir a git repository, with git's routing environment +// scrubbed so an inherited GIT_DIR cannot send the init somewhere else. +func gitInitAt(t *testing.T, dir string) { + t.Helper() + cmd := initArtifactGitCommand(dir, "init") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git init failed: %v\n%s", err, out) + } +} + +// setInitFlag sets a flag on the shared initCmd and restores it afterwards — +// cobra commands are package-level singletons, so a leaked flag would bleed +// into every later test in this package. +func setInitFlag(t *testing.T, name, value string) { + t.Helper() + flag := initCmd.Flags().Lookup(name) + if flag == nil { + t.Fatalf("init has no --%s flag", name) + } + orig := flag.Value.String() + origChanged := flag.Changed + if err := initCmd.Flags().Set(name, value); err != nil { + t.Fatalf("setting --%s=%s: %v", name, value, err) + } + t.Cleanup(func() { + _ = initCmd.Flags().Set(name, orig) + flag.Changed = origChanged + }) +} + +// TestInitThroughRootCmd_RefusesInHomeDirWithDiscoveredBeadsDir is the +// regression for the bypass, and it has to run through rootCmd rather than +// calling initCmd.RunE directly — the whole failure lives in a hook RunE-only +// tests skip. +// +// Cobra's root PersistentPreRunE runs first, and for a no-DB command like init +// it resolves a beads dir and exports it (main.go, selectedNoDBBeadsDir -> +// prepareSelectedNoDBContext). That resolution accepts an ancestor .beads/ +// holding nothing but a config.yaml, which is precisely the shape of this +// project's legacy user-level ~/.beads/config.yaml. A guard reading the LIVE +// BEADS_DIR therefore saw a value it had set for itself and stood down. +// +// The half that made this worth blocking on: the `git init` is separately +// gated on the same env, so it stayed skipped — but the agent scaffolding is +// not. CLAUDE.md, AGENTS.md, .claude/, .codex/, .cursor/ and .agents/ are +// written relative to the working directory whatever BEADS_DIR says, so the +// bypass still installed into $HOME the user-wide agent settings the guard +// exists to keep out of it. +// +// --backend names a backend that cannot exist (homeGuardSentinelBackend), as +// a circuit breaker: if the guard ever fails open again, init stops at the +// unknown-backend error instead of building a real store in someone's home +// directory, and the assertion below reports that error rather than hanging +// on Dolt. +func TestInitThroughRootCmd_RefusesInHomeDirWithDiscoveredBeadsDir(t *testing.T) { + home := t.TempDir() + stubHomeDir(t, home) + t.Chdir(home) + stubCallerBeadsDir(t, "") + + // The caller named nothing. Anything in BEADS_DIR from here on was put + // there by bd itself. + t.Setenv("BEADS_DIR", "") + t.Setenv("HOME", home) + t.Setenv("BD_NON_INTERACTIVE", "1") + + // The legacy user-level config, which is all beads.FindBeadsDir needs. + beadsDir := filepath.Join(home, ".beads") + if err := os.MkdirAll(beadsDir, 0o750); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(beadsDir, "config.yaml"), []byte("actor: someone\n"), 0o600); err != nil { + t.Fatal(err) + } + + // Confirm the precondition rather than assuming it: if discovery stops + // resolving this, the test would pass for the wrong reason. Compared + // through EvalSymlinks because macOS reports the same temp dir as both + // /var/... and /private/var/.... + if got, want := evalSymlinks(t, selectedNoDBBeadsDir(initCmd)), evalSymlinks(t, beadsDir); got != want { + t.Fatalf("precondition: selectedNoDBBeadsDir = %q, want %q — pre-run no longer discovers a config.yaml-only .beads, so this test no longer reproduces the bypass", got, want) + } + + origStore, origDBPath := store, dbPath + t.Cleanup(func() { + rootCmd.SetArgs(nil) + store, dbPath = origStore, origDBPath + _ = initCmd.Flags().Set("backend", "") + _ = initCmd.Flags().Set("prefix", "") + }) + store, dbPath = nil, "" + + rootCmd.SetArgs([]string{"init", "--backend", homeGuardSentinelBackend, "--prefix", "hg"}) + err := rootCmd.Execute() + + if err == nil { + t.Fatal("bd init in an untracked home returned nil, want a refusal") + } + if strings.Contains(err.Error(), homeGuardSentinelBackend) { + t.Fatalf("init ran past the home guard and got as far as backend selection: %v", err) + } + assertHomeDirRefusal(t, err) + + // The files the bypass could still install, none of which is gated on + // BEADS_DIR: scaffolding is written relative to the working directory. + for _, name := range []string{".git", "CLAUDE.md", "AGENTS.md", ".gitignore", ".agents", ".codex", ".claude", ".cursor"} { + if _, statErr := os.Stat(filepath.Join(home, name)); statErr == nil { + t.Errorf("init created %s in the home directory despite refusing", name) + } + } +} + +// evalSymlinks resolves path for comparison, tolerating a path that does not +// exist (nothing to resolve is not a test failure here). +func evalSymlinks(t *testing.T, path string) string { + t.Helper() + if path == "" { + return "" + } + resolved, err := filepath.EvalSymlinks(path) + if err != nil { + return path + } + return resolved +} diff --git a/cmd/bd/init_proxied_server.go b/cmd/bd/init_proxied_server.go index e52944a66..6ab8486d8 100644 --- a/cmd/bd/init_proxied_server.go +++ b/cmd/bd/init_proxied_server.go @@ -41,6 +41,7 @@ type initProxiedServerInput struct { stealth bool skipHooks bool skipAgents bool + keepHomeClean bool // see guardInitInHomeDir reinitLocal bool contributor bool team bool @@ -166,7 +167,7 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie ConfigYAMLBody: configYAMLBody, ProxiedServerClientInfo: clientInfo, SetNoCOW: true, - WriteProjectGitignore: useLocalBeads && beadsDirIsLocal, + WriteProjectGitignore: useLocalBeads && beadsDirIsLocal && !in.keepHomeClean, } if useLocalBeads { fsParams.LocalVersion = Version @@ -328,7 +329,9 @@ func resolveProxiedInitRemoteURL(ctx context.Context, workDir string, in initPro if source != initSyncRemoteNone { return "" } - if !in.stealth { + // Under keepHomeClean the repository around the home is not the project's, + // so its origin is not this workspace's remote (see guardInitInHomeDir). + if !in.stealth && !in.keepHomeClean { // Origin belongs to the selected project, independently of Beads storage. gitUC := domain.NewGitUseCase(workDir, domaingit.NewInitGitRepository(workDir)) if originURL, err := gitUC.OriginRemoteURL(ctx); err == nil && originURL != "" { @@ -537,7 +540,13 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr // One probe answers both the role gate and the artifact gates: gitUC is the // scrubbed selected-directory repository whenever workDir is set, and the // supplied use case otherwise, so a separate role probe could only repeat it. - isRepo := gitUC.IsGitRepo(ctx) + // Under keepHomeClean the repository it can find encloses the home instead + // of holding the project, so the tail treats the home as outside every + // repository: no role, no fork exclude, no upstream advice and no bootstrap + // commit, which would stage the legacy ~/.beads and the home's agent files + // into it (see guardInitInHomeDir). RunE sets skipHooks for the same case, + // which also covers a colocated jj repository. + isRepo := !in.keepHomeClean && gitUC.IsGitRepo(ctx) if isRepo { role := in.roleFlag diff --git a/cmd/bd/init_proxied_server_test.go b/cmd/bd/init_proxied_server_test.go index 14617bb9f..320a0a39f 100644 --- a/cmd/bd/init_proxied_server_test.go +++ b/cmd/bd/init_proxied_server_test.go @@ -39,7 +39,7 @@ func TestProxiedInitRemoteURLUsesSelectedProject(t *testing.T) { require.NoError(t, err, "fixture git %v: %s", args, out) return strings.TrimSpace(string(out)) } - for _, name := range []string{"ordinary", "decoy", "invalid", "inline", "scp", "missing", "nonrepo", "bare", "stealth", "explicit", "explicit_empty", "configured", "configured_stealth", "legacy", "canceled"} { + for _, name := range []string{"ordinary", "decoy", "invalid", "inline", "scp", "missing", "nonrepo", "bare", "stealth", "keep_home_clean", "explicit", "explicit_empty", "configured", "configured_stealth", "configured_keep_home_clean", "legacy", "canceled"} { t.Run(name, func(t *testing.T) { home := t.TempDir() for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { @@ -80,6 +80,9 @@ func TestProxiedInitRemoteURLUsesSelectedProject(t *testing.T) { want = "git+ssh://git@github.com/fixture/selected.git" case "stealth": in.stealth, want = true, "" + case "keep_home_clean": + // The opt-out from a home inside another repository: its origin is not this workspace's remote. + in.keepHomeClean, want = true, "" case "explicit", "explicit_empty": in.initRemoteChanged = true in.initRemote = "dolthub://fixture/explicit" @@ -88,7 +91,7 @@ func TestProxiedInitRemoteURLUsesSelectedProject(t *testing.T) { } want = in.initRemote t.Setenv("BD_SYNC_REMOTE", "dolthub://fixture/configured") - case "configured", "configured_stealth", "legacy": + case "configured", "configured_stealth", "configured_keep_home_clean", "legacy": want = "dolthub://fixture/configured" key := "BD_SYNC_REMOTE" if name == "legacy" { @@ -96,6 +99,7 @@ func TestProxiedInitRemoteURLUsesSelectedProject(t *testing.T) { } t.Setenv(key, want) in.stealth = name == "configured_stealth" + in.keepHomeClean = name == "configured_keep_home_clean" } initConfigForTest(t) if name != "ordinary" { @@ -640,6 +644,65 @@ func TestProxiedInitTailGitUsesSelectedDirectory(t *testing.T) { } } +// TestProxiedInitTailKeepHomeCleanLeavesEnclosingRepoAlone runs the tail for +// the home-directory opt-out from a home inside another repository, as a +// dotfiles or monorepo checkout above it is. That repository is not the +// project's (see guardInitInHomeDir), so the tail must not give it a role, a +// fork exclude, upstream advice or a bootstrap commit of the home's legacy +// .beads and agent files. +func TestProxiedInitTailKeepHomeCleanLeavesEnclosingRepoAlone(t *testing.T) { + for _, entry := range os.Environ() { + key := gitenv.EntryKey(entry) + if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) { + t.Setenv(key, "") + require.NoError(t, os.Unsetenv(key)) + } + } + enclosing := t.TempDir() + home := filepath.Join(enclosing, "home") + require.NoError(t, os.MkdirAll(filepath.Join(home, ".beads"), 0755)) + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, home) + } + runGit := func(args ...string) string { + t.Helper() + cmd := gitCommand(args...) + cmd.Dir, cmd.Env = enclosing, gitenv.ScrubRouting(os.Environ()) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "fixture git %v: %s", args, out) + return strings.TrimSpace(string(out)) + } + runGit("init", "--quiet") + for key, value := range map[string]string{"user.name": "Fixture", "user.email": "fixture@example.test", "commit.gpgSign": "false", "core.hooksPath": ".git/hooks"} { + runGit("config", "--local", key, value) + } + runGit("-c", "core.hooksPath=", "commit", "--allow-empty", "--quiet", "-m", "dotfiles") + runGit("remote", "add", "origin", "https://example.test/dotfiles.git") + runGit("remote", "add", "upstream", "https://example.test/upstream.git") + require.NoError(t, os.WriteFile(filepath.Join(home, ".beads", "config.yaml"), []byte("# legacy\n"), 0600)) + require.NoError(t, os.WriteFile(filepath.Join(home, "CLAUDE.md"), []byte("mine\n"), 0600)) + configPath := filepath.Join(enclosing, ".git", "config") + configBefore, err := os.ReadFile(configPath) + require.NoError(t, err) + head := runGit("rev-parse", "HEAD") + t.Chdir(home) + cmd := &cobra.Command{} + cmd.Flags().Bool("setup-exclude", false, "") + fs := &initTailForkObservation{} + // What RunE hands the tail for the opt-out, with the workspace under the home. + in := initProxiedServerInput{keepHomeClean: true, skipHooks: true, skipAgents: true, nonInteractive: true} + stderr := captureStderr(t, func() { + require.NoError(t, runInitProxiedServerTail(cmd, t.Context(), in, runInitTailContext{workDir: home, beadsDir: filepath.Join(home, "notes", ".beads"), useLocalBeads: true, fsUseCase: fs, gitUC: storagegit.NewGitProvider(home).GitUseCase()})) + }) + require.Zero(t, fs.calls, "fork exclude written for the enclosing repository") + require.NotContains(t, stderr, "Git upstream not configured", "upstream advice given for the enclosing repository") + require.Equal(t, head, runGit("rev-parse", "HEAD"), "bootstrap commit made to the enclosing repository") + require.Empty(t, runGit("diff", "--cached", "--name-only"), "home staged into the enclosing repository") + configAfter, err := os.ReadFile(configPath) + require.NoError(t, err) + require.Equal(t, string(configBefore), string(configAfter), "enclosing repository config changed") +} + func TestProxiedInitExcludeUsesSelectedDirectory(t *testing.T) { for _, name := range []string{"stealth", "setup_exclude", "target_fork", "decoy_fork"} { t.Run(name, func(t *testing.T) { diff --git a/cmd/bd/init_safety.go b/cmd/bd/init_safety.go index a9631e639..416d6d43c 100644 --- a/cmd/bd/init_safety.go +++ b/cmd/bd/init_safety.go @@ -46,6 +46,25 @@ const ( // Supplying the matching token is the correct remedy for sources 1-3 // (format via `bd help init-safety`); source 4 was a deliberate decline. ExitDestroyTokenMissing = 12 + + // ExitHomeDirRefused signals `bd init` was run directly in the user's + // home directory, which is not itself a git repository, without the + // caller naming a BEADS_DIR. Refused because init would `git init` $HOME + // and install agent files into it, where most of them are user-wide + // agent settings (GH#4635). + // + // 15 because 13 and 14 are taken: ExitGuardMismatch (update.go, "racer + // won, skip gracefully") and ExitMigrationFrozen (errors.go). A wrapper + // that branches on bd's exit codes without regard to the subcommand must + // never read this refusal as a benign skip. + // + // Not part of protocol v0 §E3 (pinned in + // cmd/bd/protocol/exit_codes_init_test.go), which freezes 10/11/12/130 + // and says a new stable code needs a spec revision. This constant gives + // the refusal the same in-repo scriptability the other three have — a + // stable number instead of grepping stderr — without claiming wire + // status the spec has not granted. + ExitHomeDirRefused = 15 ) // RemoteSafetyAction names what the init command should do once it has diff --git a/cmd/bd/init_safety_help.go b/cmd/bd/init_safety_help.go index 29708f6a3..9f051656c 100644 --- a/cmd/bd/init_safety_help.go +++ b/cmd/bd/init_safety_help.go @@ -101,6 +101,8 @@ EXIT CODES over existing issues) without a valid --destroy-token (non-interactive mode); also returned when the interactive --discard-remote typed-token confirmation is declined + 15 refused: run directly in your home directory, which is not itself + a git repository, with no BEADS_DIR named by the caller RECOVERY diff --git a/cmd/bd/main.go b/cmd/bd/main.go index 493dfddd1..c083fed90 100644 --- a/cmd/bd/main.go +++ b/cmd/bd/main.go @@ -83,6 +83,33 @@ type envSnapshotValue struct { var changeDirEnvSnapshot map[string]envSnapshotValue +// beadsDirFromCaller is BEADS_DIR as the process INHERITED it, captured at +// package initialization — which the language guarantees runs before main, and +// therefore before any bd code exports a BEADS_DIR of its own. +// +// Reading os.Getenv("BEADS_DIR") later is a different question, and the wrong +// one for anything that needs to know what the CALLER asked for. By the time a +// command's RunE runs, bd has usually exported one itself: +// +// - the root PersistentPreRunE resolves a beads dir for every no-DB command +// and exports it (selectedNoDBBeadsDir -> prepareSelectedNoDBContext -> +// prepareSelectedCommandContext), and that resolution bottoms out in +// beads.FindBeadsDir(), which accepts any ancestor .beads/ carrying so much +// as a config.yaml — including the legacy user-level ~/.beads/config.yaml; +// - `bd -C ` exports one too (applyChangeDirSelection), which names a +// beads dir without moving the working directory. +// +// Neither is the caller saying "use this". Consult this snapshot, not the live +// environment, when the answer must mean caller intent (GH#4635). +// +// A BEADS_DIR imported from a .beads/.env file is deliberately left out too, +// although beadsDirProvidedAtStartup counts it as user selection for role +// detection: the loaders read the .env of the beads dir beads.FindBeadsDir() +// discovers from the working directory, which in a home directory is the legacy +// ~/.beads/.env. Counting it would let the same discovered ~/.beads opt out of +// the home-directory guard; the caller opts out by exporting BEADS_DIR. +var beadsDirFromCaller = os.Getenv("BEADS_DIR") + var ( noColorFlag bool sandboxMode bool diff --git a/docs/recovery/init-safety.md b/docs/recovery/init-safety.md index ae66f6095..d5051dca1 100644 --- a/docs/recovery/init-safety.md +++ b/docs/recovery/init-safety.md @@ -25,6 +25,7 @@ See also: `bd help init-safety`, and - [init-force-refused — `bd init --force`/`--reinit-local` refused because origin has Dolt history](#init-force-refused) - [init-token-missing — a destructive re-init refused because `--destroy-token` is missing or wrong](#init-token-missing) - [init-local-exists — `bd init --reinit-local` refused because local data already exists](#init-local-exists) +- [init-home-refused — `bd init` refused because the working directory is your home directory](#init-home-refused) - [init-missing-server-db — `bd init` refused because the configured server-side database is missing](#init-missing-server-db) - [pk-fork-refused — `bd dolt pull`/`push` refused because a table has different primary keys in its common ancestor](#pk-fork-refused) - [re-clone-gotchas — two gotchas hit during manual re-clone recovery: damaged stores left inside `data_dir`, and a fresh clone missing clone-local tables](#re-clone-gotchas) @@ -211,6 +212,107 @@ re-init won't fix. --- +## init-home-refused + +**Exit code:** `15` (`ExitHomeDirRefused`) + +**Symptom** + +``` +bd init refuses: /Users/you is your home directory, and it is not itself a git repository. + Why: init sets up the directory it runs in as a project: it runs + 'git init' there unless it finds a repository, and installs agent + files ... +``` + +**Why this happens** + +`bd init` sets up the directory it runs in as a project: it creates a git +repository there unless it finds one, then writes agent scaffolding next to it: +`CLAUDE.md`, `AGENTS.md`, `.gitignore`, `.claude/`, `.codex/`, `.cursor/`, +`.agents/`. Run in your home directory, that turns everything you own into one +git working tree, and most of those agent files are your agents' user-wide +settings there: `~/.claude/settings.json` is the file Claude Code reads in every +project, so bd's hooks would run everywhere. A project is virtually never the +home directory itself, so `bd init` refuses rather than ask. + +The refusal is deliberately narrow. It fires only when **all** of these hold: + +- the working directory is exactly your home directory (a subdirectory of home + is an ordinary project and is never refused); +- your home directory is not itself a git repository — if you deliberately + track your dotfiles in a repository at your home directory, nothing changes. + A home that only sits inside some enclosing repository, or a `GIT_DIR` + inherited from the environment, does not count, because init would still + write its files into your home; +- you did not name a beads directory yourself by exporting `BEADS_DIR`. A + `BEADS_DIR` that bd reads from a `.beads/.env` it discovered does not count: + from your home directory that file is the legacy `~/.beads/.env`. + +`--force` and `--reinit-local` do **not** override it. They bypass the local +data-safety guard, which is a different question from "is this the right +directory". + +**Recovery paths** + +Pick the one that matches your intent. + +*You meant to initialize a project.* This is almost always the case — the +working directory was simply not what you thought: + +```bash +cd ~/some-project +bd init +``` + +*You want a beads workspace in a directory you name, without setting up your +home directory as a project.* Name the beads directory explicitly. Its parent +directory has to exist first: + +```bash +mkdir -p ~/workspaces/notes +BEADS_DIR=~/workspaces/notes/.beads bd init +``` + +Note this is a **different** init, not the refused one with the guard lifted. +An explicit `BEADS_DIR` skips the `git init`, and from your home directory +`bd init` also skips the agent files and the `.gitignore` it would otherwise +write there (it prints a note saying so). It also treats your home directory +as outside every repository. If your home sits inside one, such as a dotfiles +or monorepo checkout above it, init installs no hooks in it, records no +`beads.role` there, takes no Dolt remote from its origin, and makes no +bootstrap commit to it. Flags that ask for a change there still make it: +`--stealth` and `--setup-exclude` add their patterns to that repository's +`.git/info/exclude`, the interactive `--contributor` wizard records +`beads.role` in it, and the interactive `--team` wizard can create a sync +branch in it. Your home directory is not set up as +a project; the workspace lives in `~/workspaces/notes`. That is the point, but +it also means you get no agent integration. To install one for every project +on purpose, use the global form of `bd setup`, for example +`bd setup claude --global`. + +*You really do want your home directory tracked by git and scaffolded.* Make it +a git repository first, deliberately, and the guard stands aside: + +```bash +cd ~ +git init +bd init +``` + +**How to detect this in a script** + +The refusal exits `15` and prints to stderr, so branch on the code rather than +the text: + +```bash +bd init || case $? in + 15) echo "wrong directory — cd into the project first" ;; +esac +``` + +--- + ## init-missing-server-db **Symptom** diff --git a/engdocs/adr/0002-init-safety-invariants.md b/engdocs/adr/0002-init-safety-invariants.md index 605f88c56..0759a4661 100644 --- a/engdocs/adr/0002-init-safety-invariants.md +++ b/engdocs/adr/0002-init-safety-invariants.md @@ -105,8 +105,14 @@ bd bootstrap adopt remote — signposted by init refusal 10 ExitRemoteDivergenceRefused local-source init without --discard-remote 11 ExitLocalExistsRefused existing local data, declined destroy confirm 12 ExitDestroyTokenMissing --discard-remote without valid --destroy-token +15 ExitHomeDirRefused run in an untracked home dir, no caller BEADS_DIR ``` +10/11/12, with 130 for a canceled prompt, are the codes protocol v0 §E3 +freezes (pinned in `cmd/bd/protocol/exit_codes_init_test.go`). 15 is stable +in-repo but not §E3-frozen (GH#4635); it skips 13 and 14, which bd already +uses for `ExitGuardMismatch` and `ExitMigrationFrozen`. + ### Deprecation cycle `--force` continues to work for ≥2 releases post-0.x, emitting a