beads/cmd/bd/reset_global_guard_test.go
matt wilkie d2f12f2dcb
fix(reset): refuse to delete the user-global .beads from a repo reset (#5223)
* fix(reset): decide hook deletion from provenance, not the word "beads"

`bd admin reset --force` deletes git hooks it believes bd installed. isBdHook
decided that by scanning the first ten lines for the substring "beads" —
anywhere, in any context. A comment, a path, a call to another tool: any of them
made a hook bd's to delete.

The repository's own tracked .githooks/pre-commit is such a file. It is composed
by hand, carries guards bd knows nothing about, and says "the beads section at
the bottom must run for non-Go commits too" on line 9. The old scan matched that
comment and would have removed the whole file. Nothing brings it back:
performReset's restore path renames <hook>.backup into place, and a backup
exists only for hooks bd itself displaced, so a hook bd never installed is
deleted with no restore.

The same scan was wrong in the other direction too — a marker past the tenth
line was invisible — but that failure is merely untidy, and this one loses work.

Provenance is not something reset has to guess at. bd writes markers when it
installs (hookVersionPrefix, shimVersionPrefix, inlineHookMarker) and wraps
injected blocks in section markers, and preservePreexistingHooks already has a
worked-out model of what those mean (GH#3536). classifyResetHook uses the same
markers and the same rules, and returns three states rather than a boolean,
because "bd installed this" and "bd may delete this" are different questions:

  hookBdOwned                 bd wrote the whole file; removing it restores the
                              state before bd touched the repo.
  hookUserOwnedWithBdSection  the user's hook with bd's block injected. The file
                              is theirs. Reset reports it and leaves it.
  hookNotOurs                 no marker. Not ours to remove or to mention.

The middle state is the one the old boolean could not express, and it is not
rare: it is what every marker-managed install since v0.49 produces. Under the
old code such a hook was deleted whole whenever "beads" fell inside the first
ten lines — which the generated section itself guarantees when it lands near the
top, since its second line reads "# This section is managed by beads."

Preserved hooks are reported in both the preview and the --force path, and in
--json as a "preserved" key. Saying nothing would leave the user believing a
reset removed a beads integration that is in fact still live in their hook.

Tests cover each state, both directions of the old first-ten-lines window, and
the missing-file case. TestClassifyResetHook_AgreesWithHookPreservation pins the
invariant across the two functions that decide this independently: if
shouldPreserveHookContent would carry content forward, reset must not delete the
file, and vice versa. It runs over the repo's own .githooks so the inputs are
hooks a person actually wrote, and asserts the agreement rather than a verdict
per file, so editing those hooks cannot make it lie.

Agent-Signature: claude-opus-5-high on behalf of matt wilkie

* docs(uninstall): stop telling users reset removes hook sections

Two claims in docs/recovery/uninstalling.md do not match what the code does,
and both point the same way — at deleting a hook file that is the user's.

The reset section said `bd admin reset` removes "beads-managed git hook
sections". It has never worked on sections; it removes whole files. With the
ownership check in this branch it removes only files beads generated in full,
and reports the ones it left alone, so say that instead.

The manual-cleanup section is worse: it hands the user five unconditional
`rm -f .git/hooks/<name>` lines. Those are the standard git hook names, not
names beads reserves, so any of them may be a hook they wrote — and the section
directly above it explains that `bd hooks uninstall` is preferable precisely
because beads preserves content outside its markers. Someone who reaches
manual cleanup is already in the case where the safe command did not work.

Name the markers so the check is something a reader can actually perform, and
say what to do with a hook that only has a beads block in it.

Agent-Signature: claude-opus-5-high on behalf of matt wilkie

* fix(reset): refuse to delete the user-global .beads from a repo reset

`bd -C <dir> admin reset --force` can resolve its target to `~/.beads` and
remove it, taking a user's global beads state with a reset that named a
repository.

The `-C` path resolves through `beads.FindBeadsDirFrom` (main.go:789), which
walks up from the given directory to the filesystem root — `repoRoot` is read
inside the loop to classify a hit, never to stop the climb. So a `-C` target
with no `.beads` of its own does not error; the walk leaves the repository and
returns the first ancestor `.beads` it finds, and under a home directory that
is the global one. `applyChangeDirSelection` then exports it as `BEADS_DIR`,
which `FindBeadsDir` takes as its highest-priority source, and reset deletes
whatever comes back.

`hasBeadsProjectFiles` is documented as the thing that keeps `~/.beads` from
being returned, but it is a content guard rather than a boundary guard: it
holds only while the global directory is not itself a real project. Once a
user has one, it stops holding — which is exactly when there is something
there to lose.

This is the shape of the 2026-07-21 incident recorded on mybd-3bevm, where a
reset aimed at a temp repository removed the global `.beads` along with hooks
from an unrelated checkout.

The rule here is deliberately narrow. It decides nothing about what `-C`
should mean, and nothing about how `runReset`'s two independently-resolved
targets (`git.GetGitCommonDir()` from cwd, `beads.FindBeadsDir()` from
`BEADS_DIR`) ought to be reconciled — both are open questions that change
behaviour for every command, not just this one. It says only that a reset run
against some project is never a request to delete the user's global directory,
and it stays out of the way when the home directory genuinely is the
repository, where `~/.beads` is that repository's own beads dir.

Refusing is the whole remedy: the failure mode is a destructive action on the
wrong target, so converting it to an error naming both paths cannot itself
destroy anything.

Agent-Signature: claude-opus-5-high on behalf of matt wilkie
2026-08-01 13:28:28 -07:00

100 lines
3 KiB
Go

package main
import (
"path/filepath"
"strings"
"testing"
)
// FindBeadsDir walks up from the working directory with no upper boundary, so a
// repository under $HOME that has no .beads of its own resolves to ~/.beads.
// Reset then removes it. These pin that it refuses instead — and that the
// refusal is narrow enough not to break the case where the home directory
// genuinely is the repository.
func TestRefuseGlobalBeadsDir(t *testing.T) {
home := filepath.Join("/", "home", "someone")
globalBeads := filepath.Join(home, ".beads")
project := filepath.Join(home, "dev", "project")
tests := []struct {
name string
beadsDir string
repoRoot string
home string
wantError bool
}{
{
// The incident shape: a reset inside a project whose walk climbed
// out of the repository and landed on the user's global directory.
name: "project reset that resolved to the global beads dir",
beadsDir: globalBeads,
repoRoot: project,
home: home,
wantError: true,
},
{
// Not an over-reach: here ~/.beads IS the repository's beads dir,
// and removing it is exactly what was asked for.
name: "home directory is itself the repository",
beadsDir: globalBeads,
repoRoot: home,
home: home,
wantError: false,
},
{
name: "ordinary repo-local beads dir",
beadsDir: filepath.Join(project, ".beads"),
repoRoot: project,
home: home,
wantError: false,
},
{
// A directory that merely lives under $HOME is not the global one.
name: "beads dir under home but not the global path",
beadsDir: filepath.Join(home, ".beads-backup"),
repoRoot: project,
home: home,
wantError: false,
},
{
name: "no home directory: nothing global to protect",
beadsDir: globalBeads,
repoRoot: project,
home: "",
wantError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := refuseGlobalBeadsDir(tt.beadsDir, tt.repoRoot, tt.home)
if tt.wantError && err == nil {
t.Fatalf("refuseGlobalBeadsDir() = nil, want a refusal")
}
if !tt.wantError && err != nil {
t.Fatalf("refuseGlobalBeadsDir() = %v, want nil", err)
}
if err == nil {
return
}
// The message has to name both paths: the whole failure mode is a
// user who cannot tell which directory the command was about.
for _, want := range []string{tt.repoRoot, tt.beadsDir} {
if !strings.Contains(err.Error(), want) {
t.Errorf("refusal message does not name %q:\n%s", want, err)
}
}
})
}
}
// Trailing separators and unclean paths are a normal way for these to arrive,
// and a guard that a separator defeats is not a guard.
func TestRefuseGlobalBeadsDir_NormalizesPaths(t *testing.T) {
home := filepath.Join("/", "home", "someone")
beadsDir := filepath.Join(home, "dev", "..", ".beads") + string(filepath.Separator)
if err := refuseGlobalBeadsDir(beadsDir, filepath.Join(home, "dev", "project"), home); err == nil {
t.Fatalf("refuseGlobalBeadsDir(%q) = nil, want a refusal", beadsDir)
}
}