beads/cmd/bd/init_home_guard_cgo_test.go
gascity-eddie[bot] d2748411c4
fix(init): refuse to initialize directly in the home directory (#4635) (follow-up to #4795) (#7609)
* fix(init): refuse to initialize directly in the home directory

`bd init` in a directory that isn't a git repo (and has no explicit
BEADS_DIR) unconditionally `git init`s the directory, writes agent
scaffolding (CLAUDE.md, AGENTS.md, .gitignore, .agents/, .codex/,
.claude/settings.json), and commits — with no confirmation. Run in the
home directory this silently turns $HOME into a git repository and can
clobber an existing ~/CLAUDE.md. It's worse under --non-interactive
(auto-engaged whenever stdin isn't a TTY, i.e. whenever an agent runs
`bd init`): all of it happens with zero prompt (GH#4635).

Refuse the init when the current directory is the user's home directory
and it isn't already a git repo (and no explicit BEADS_DIR was given),
with a clear error pointing at the alternatives (cd into a project, or
set BEADS_DIR). The common fresh-project flow (mkdir proj && cd proj &&
bd init) and already-git-tracked homes are unaffected.

The guard runs as the first statement in init's RunE, ahead of every
path that has an effect. Position is the whole fix: --reinit-local /
--force reach countExistingIssues, which opens a real store (creating
the data directory, able to run migrations), and --proxied-server
dispatches to runInitProxiedServer -> EnsureGitRepo, i.e. a `git init`
in the current directory. Both run long before the point where a guard
placed with the rest of the path validation would fire.

Home is resolved from the OS account database (user.Current) in
preference to $HOME, so the guard keys off the real account home even
when $HOME is repointed — which this repo's own tests do constantly.
Both sources are best-effort: a CGO-free build's user.Current() falls
back to os.UserHomeDir() (i.e. $HOME on Unix) when the account is absent
from the passwd database, so this is a preference, not a guarantee of
$HOME-independence. Mirrors the home resolution in internal/beads'
isPathInSafeBoundary.

Tests: TestIsUserHomeDir and TestGuardInitInHomeDir cover the decision
(resolver stubbed, so the real home is never touched);
TestInitCommand_RefusesInHomeDirBeforeAnySideEffect runs the actual
command for plain / --reinit-local / --force / --proxied-server and
asserts not just the refusal but that nothing — .git, .beads, CLAUDE.md,
AGENTS.md, .gitignore, .agents, .codex, .claude — exists afterwards.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(init): key the home guard on caller intent, and give it a named exit code

Three blocking items, two reviewers converging on the first.

1. The guard read os.Getenv("BEADS_DIR") as "the user explicitly opted in".
   It is not. Cobra's root PersistentPreRunE runs before RunE and, for a
   no-DB command like init, resolves a beads dir and exports it
   (selectedNoDBBeadsDir -> prepareSelectedNoDBContext ->
   prepareSelectedCommandContext). That resolution bottoms out in
   beads.FindBeadsDir(), which accepts any ancestor .beads/ for which
   hasBeadsProjectFiles is true - and a config.yaml alone is enough. That is
   the shape of this project's own legacy user-level ~/.beads/config.yaml,
   so anyone carrying it got BEADS_DIR set for them and the guard failed
   open. `bd -C <dir> init` opened the same hole, and that one does not even
   move the working directory the scaffolding lands in.

   The damage is not self-cancelling. The `git init` half is separately
   gated on the same env so it stayed skipped, but the agent scaffolding is
   not gated at all: addAgentsInstructions, InstallClaudeProject,
   InstallCodexProject and InstallCursorProject all write relative to CWD.
   So the bypass still clobbered ~/CLAUDE.md, ~/AGENTS.md and
   ~/.claude/settings.json - the files the guard exists to protect.

   beadsDirFromCaller captures BEADS_DIR as the process INHERITED it, at
   package initialization, which the language guarantees runs before main
   and therefore before any bd code exports one of its own. The guard
   consults that snapshot, so the question it asks is "did the caller name a
   beads dir", not "does the process env happen to have one".

2. The refusal skipped all three of init's refusal conventions.
   ExitHomeDirRefused = 13 joins 10/11/12, the message is printed and the
   error carries only the code (the ExitLocalExistsRefused pattern), and
   docs/recovery/init-safety.md gains an init-home-refused anchor - TOC
   entry, symptom, why, three recovery paths, and the script-branching
   snippet - which the message points at. `bd help init-safety` lists it.

   NOT added: a cmd/bd/protocol case. That corpus states that §E3 freezes
   10/11/12/130 and that a new stable code requires a spec revision, so
   asserting 13 there would be claiming wire status the spec has not
   granted. The constant plus the docs anchor give the refusal the same
   in-repo scriptability without that claim; say the word if the spec should
   be revised and I will add the corpus case too.

3. CHANGELOG [Unreleased] entry, citing #4635 and stating the scope limits.

Also from review: the message's BEADS_DIR escape hatch said "set BEADS_DIR
if you really mean to initialize here", which is not what happens - an
explicit BEADS_DIR makes hasExplicitBeadsDir true, skipping the git init and
the CWD-local .beads. It now says so.

Test coverage answers the point both reviewers made about the RunE-only
tests. TestInitThroughRootCmd_RefusesInHomeDirWithDiscoveredBeadsDir runs
through rootCmd.Execute, in a home carrying only .beads/config.yaml, and
asserts the precondition (pre-run really does discover it) before asserting
the refusal and that no scaffolding landed. --backend names a backend that
cannot exist as a circuit breaker, so a future fail-open stops there instead
of building a store in someone's home directory. Against the old code it
reproduces maphew's observation verbatim:

    init ran past the home guard and got as far as backend selection:
    unknown backend "review4795-home-guard-sentinel"

plus a unit case pinning that a bd-exported BEADS_DIR is not caller opt-in.

Reported-by: maphew, bee-ghosttrack
Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Harry Miller

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(init): harden the home-dir guard (opt-out, git probe, exit 15)

Maintainer fixup on top of #4795 by harry-miller-trimble, for the three
majors and three of the minors from the adopt-pr review, the major, the
minor and the nit from its second round, and two of the minors from its
third. The contributor's commits are unchanged.

The BEADS_DIR opt-out still set up $HOME (major). The refusal said
`BEADS_DIR=<path>/.beads bd init` writes nothing in the home directory,
but an explicit BEADS_DIR only skips the git init. The agent files
(CLAUDE.md, AGENTS.md, .claude/, .codex/, .cursor/, .agents/) are
written relative to the working directory whatever BEADS_DIR says, and a
BEADS_DIR under $HOME counts as local, so ~/.gitignore was appended to
as well. guardInitInHomeDir now returns keepHomeClean for that case.
RunE forces skipAgents, which the proxied route also reads from its
input, and both routes gate the project .gitignore on keepHomeClean.
Init prints a note saying so, with a `bd setup <recipe> --global`
pointer for anyone who wanted an integration everywhere.

The refusal text, the CHANGELOG entry and the recovery playbook now say
what the opt-out does: it sets up only the named workspace, after a
`mkdir -p`, because init refuses a BEADS_DIR whose parent does not
exist. They no longer say nothing else is written, because Dolt and
metrics keep their own state under $HOME. The refusal's Why also stops
saying init overwrites existing files: it installs into them, and in
$HOME those are user-wide agent settings.

TestInitInUntrackedHomeWithCallerBeadsDir_SetsUpOnlyTheWorkspace runs
the direct route end to end against a Dolt server, once with the
workspace outside the home and once under it. Every seeded file must
come out unchanged, with nothing added. The proxied route's agent-file
and .gitignore gates are not covered by a test: there is no in-process
proxied init fixture to drive them.

The tracked-home probe trusted git's routing environment (major).
isGitRepo() is a plain `git rev-parse --git-dir`, so an inherited
GIT_DIR, or a home that only sits inside an enclosing work tree, stood
the guard down. Init's own git-init decision scrubs that environment,
then runs git init in the home and installs agent files into it. The
guard now asks isGitWorkTreeRoot(cwd), which runs
`rev-parse --show-toplevel` through initArtifactGitCommand and matches
the result against the home itself. Two new subtests pin both false
positives. Each asserts that isGitRepo() still reports true, so the
subtests keep reproducing the old probe.

Exit 13 was already taken (major). It is ExitGuardMismatch, "racer won,
skip gracefully", and 14 is ExitMigrationFrozen, so a wrapper branching
on exit codes would read this refusal as a benign skip. The refusal now
exits 15. The change is in init_safety.go, `bd help init-safety`,
ADR 0002, the playbook and the CHANGELOG. ADR 0002 also notes that 15
sits outside the protocol v0 §E3 freeze pinned in
cmd/bd/protocol/exit_codes_init_test.go.

The opt-out still set up a repository around the home (second round,
major). The tracked-home probe sends a home that only sits inside an
enclosing work tree, such as a dotfiles or monorepo checkout above it,
to the BEADS_DIR opt-out. Git finds that repository from the home, so
init set it up as the project: core.hooksPath, beads.role, fork routing
and the fork exclude, its origin as the workspace's Dolt remote, and a
bootstrap commit. That commit staged the home's legacy ~/.beads and then
whatever agent files the home holds, ~/.codex/auth.json among them, and
committed them with --no-verify. The proxied route did the same from its
tail.

keepHomeClean now also means "outside every repository". It is only
true when the home is not a work-tree root, so no repository git finds
from there is the home's own. On the direct route, RunE forces skipHooks
beside skipAgents; projectRoleRepo holds the six isInitRoleGitRepo
gates (the role prompt and pins, the GH#2950 safety net, fork routing,
the fork exclude) to keepHomeClean; and both origin-as-remote gates, the
bootstrap commit and the upstream advice are gated on it. On the proxied
route, the tail's isRepo probe, which gates the role, the fork exclude,
the commit and the upstream advice, and resolveProxiedInitRemoteURL are
gated on it; skipHooks reaches the tail through its input. What a flag
asks for still happens: --stealth and --setup-exclude write their
exclude, and an explicit --remote or a configured sync remote is still
used. The note, the refusal text, the CHANGELOG entry and the playbook
say what the opt-out leaves alone. Gating the commit also drops the
"skipped bootstrap commit" note the opt-out printed from an untracked
home.

Tests for it:
- The end-to-end test gains home_inside_a_repository. The home sits in
  a repository with one commit and an origin, and holds a legacy
  ~/.beads; init runs without --quiet. The repository must keep its one
  commit, nothing staged and its .git/config byte for byte (so no
  core.hooksPath or beads.role). The workspace must not take its origin
  as its Dolt remote, and init must print the note and no upstream
  advice. The repository has no upstream remote, because fork routing
  would create ~/.beads-planning under the suite's real HOME.
- TestProxiedInitTailKeepHomeCleanLeavesEnclosingRepoAlone runs the
  proxied tail from a home inside a repository with an origin and an
  upstream, so the fork exclude would fire. It requires no fork
  exclude, no commit, nothing staged and the same .git/config.
- TestProxiedInitRemoteURLUsesSelectedProject gains a keep_home_clean
  row (the origin is not used) and a configured_keep_home_clean row (a
  configured remote still is).
- The guard's enclosing-repository subtest also checks that a caller
  BEADS_DIR there returns keepHomeClean.

Second-round minor and nit:
- beadsDirFromCaller's comment and the playbook say why a BEADS_DIR read
  from a .beads/.env does not count as the caller's, although
  beadsDirProvidedAtStartup counts it for role detection. From the home
  that file is the legacy ~/.beads/.env, so counting it would let the
  same discovered ~/.beads opt out of the guard.
- The guard tests use t.Chdir, and the hand-rolled chdir helper is gone.

Validation: the init, home-guard and proxied-init tests pass against
the Dolt test container, as do the embedded init lane and the
proxied-server init integration tests. Mutation checks:
- Dropping the forced skipAgents fails both workspace subtests.
- Dropping the .gitignore gate fails the under-home subtest.
- Restoring the plain isGitRepo() probe fails both new false-positive
  subtests.
- Disabling the guard fails every refusal test at the sentinel backend.
- Second round: dropping the forced skipHooks, the projectRoleRepo
  gate, the commit gate, the late origin gate, the upstream advice gate
  or the note each fails home_inside_a_repository on its own check.
  Dropping the proxied tail's gate fails the tail test, and dropping the
  proxied remote gate fails the keep_home_clean row. The third round
  pins the early origin gate (below).

Third-round minors:
- The early origin gate picks the remote the early remote-safety check
  probes, and a failed probe counts as Dolt history. The end-to-end
  test gains unreachable_origin_reinit_local and
  unreachable_origin_force: the home sits in a repository whose origin
  path holds nothing, and init runs with --reinit-local or with --force.
  Both must succeed and leave the repository as it was. Dropping the
  early gate makes init probe that origin and refuse both rows with
  exit 10.
- The playbook, the CHANGELOG entry and guardInitInHomeDir's comment
  name the flags that still change the repository around the home:
  --stealth and --setup-exclude write its .git/info/exclude, and the
  interactive --contributor and --team wizards work in it (beads.role,
  and possibly a sync branch). The opt-out's note is unchanged: none of
  those writes is on its list.

Left for a follow-up:
- The proxied route's .gitignore gate is still unpinned. It needs an
  in-process proxied init fixture, or the
  `useLocalBeads && beadsDirIsLocal && !keepHomeClean` predicate pulled
  out into a table-tested helper.
- Both routes still record the enclosing repository's origin-derived
  repo_id, and its clone_id, on an opt-out workspace. That predates this
  PR for every explicit-BEADS_DIR init and writes nothing to the
  repository; skipping it is a behavior change of its own.

Third-round validation: the home-guard, init-tail and proxied-remote
tests pass in a hermetic env -i run against the Dolt 2.2.0 CI pin (41
tests and subtests, none skipped). Dropping !keepHomeClean from the
early origin gate fails both new rows with exit 10 and leaves the other
three rows passing. go vet, gofmt, the docsync test and the doc
freshness check pass.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Harry Miller <harry_miller@trimble.com>

---------

Co-authored-by: Harry Miller <harry_miller@trimble.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
2026-10-16 13:52:00 +00:00

264 lines
10 KiB
Go

//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 <dir> && BEADS_DIR=<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
}