beads/cmd/bd/worktree_test.go
ecuthiell cefcabb1e3
fix(gitenv): retain explicit null config suppression (#6461)
* fix(exec): match Windows environment key identity (#5618)

Centralize os/exec-compatible environment-key comparison and use it for credential, metrics, Git-hook, trace, and repro subprocess filters. Preserve exact Unix semantics and Unicode near-collisions.

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>

* fix(worktree): scrub inherited Git routing state

Establish CWD as the worktree repository boundary before discovery can consume inherited Git routing. Fence the startup config probe, clear routing in-process before root pre-run discovery, and retain command-owned subprocess scrubbing as defense in depth without changing PID or signal semantics.

Fixes #5531

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell

* refactor(worktree): explain owned filtering and remove an unused shim

Document why filtering the fresh routing slice in place is safe and call
the shared routing-key classifier directly from tests. Retain the two
forwarders used by production worktree subprocess/removal paths.

Review: https://github.com/gastownhall/beads/pull/5623#pullrequestreview-5098421671
Bead: saa-cgh.23
Agent-Signature: unknown-model/unknown-reasoning

* fix(config): isolate identity and tracked-file Git probes from routing

Reuse the worktree routing owner for GetIdentity and isGitTracked so
explicit cwd/path selection is not displaced by inherited repository,
index or injected config state. Preserve identity precedence and the
tracked-secret refusal contract, with real target/decoy regressions.

Follow-up: https://github.com/gastownhall/beads/issues/6222
Dependency: https://github.com/gastownhall/beads/pull/5623
Reported-by: bee-ghosttrack
Bead: saa-cgh.93
Agent-Signature: unknown-model/unknown-reasoning

* test(execenv): exercise every environment operation under both host rules

Thread the host choice through narrow private helpers behind the existing
exported functions. Keep one normalization owner and retain native wrapper
tests; the additional table covers both host branches for equality, prefix
matching, last-wins lookup, filtering and input preservation.

Review: https://github.com/gastownhall/beads/pull/5672#pullrequestreview-5096948965
Bead: saa-cgh.78
Agent-Signature: unknown-model/unknown-reasoning

* docs(worktree): explain startup Git environment scope (saa-cgh.23)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(execenv): exercise exported host policy wiring (saa-cgh.78)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(config): share subprocess key identity for Git routing (saa-cgh.93)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(config): isolate role commands from Git routing (saa-cgh.99)

Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6357.

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(env): exercise shared key helpers on native Windows (saa-cgh.78)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* refactor(gitenv): share key parsing and normalize routing membership once (saa-cgh.93)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* docs(config): explain role command routing policy (saa-cgh.99)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(config): isolate role readers from inherited Git routing (saa-cgh.109.1)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(doctor): isolate role lookups from inherited Git routing (saa-cgh.109.2)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(git): isolate domain role configuration from inherited routing (saa-cgh.109.5)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(doctor): isolate explicit-path worktree fallback from Git routing (saa-cgh.109.6)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): probe the selected repository before configuring roles (saa-cgh.109.8)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(beads): cover common-directory role routing (saa-cgh.109.1)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(git): explain system config routing flags (saa-cgh.109.6)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* docs(init): explain role probe discovery ceiling behavior (saa-cgh.109.8)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(beads): scope stable worktree probes to selected path (saa-cgh.109.13)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(init): bind proxied tail Git operations to selected directory (saa-cgh.109.14)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* Clarify selected discovery probes and cover separate routing vectors (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Keep init role operations on the captured selected Git context (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Observe inline Git configuration directly in linked-worktree fixture (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* Align selected-tail fixtures with captured role authority (saa-cgh.120)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* fix(beads): select explicit directory discovery context (GH#6384) (saa-cgh.120.6)

Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* fix(gitenv): retain explicit Git config suppression (saa-cgh.120.7)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* test(config): pin identity under null config suppression (saa-cgh.120.7)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell

* fix(gitenv): keep role authority off inherited config suppression

Maintainer review fixes for PR #6461 (adopt-pr iterations 1-2). Addresses the
three major findings raised against the contributor branch, plus the major,
three minors and nit that iteration 2 raised against the first fixup; each fix
is pinned by a test that was mutation-proved against the pre-fix source.

F1 (major, security) — the leaf exempts GIT_CONFIG_GLOBAL=/dev/null,
GIT_CONFIG_SYSTEM=/dev/null and GIT_CONFIG_NOSYSTEM from ScrubRouting. Null
suppression cannot redirect a read, but it can blind one, and DetectUserRole
answers a missed read with detectFromURL, whose no-remote and SSH arms both
return Maintainer. Reproduced on this branch: a global beads.role=contributor
with GIT_CONFIG_GLOBAL=/dev/null resolved to maintainer, where the leaf's
parent fb7a93ad4 scrubbed the entry and read contributor.

Taken the synthesis's alternative arm (a): keep the exemption where the value
has no authority, drop it where it does. New ScrubRoutingAndSuppression
applies at every beads.role reader — internal/routing, doctor/role.go,
config_show.go, RepoContext.Role, bd config get/set/unset/set-many, and the
domain adapter's key-specific arms (see A1: iteration 1 claimed that last site
and did not actually reach it). Arm (b), making roleFromGitConfig's miss
non-permissive, was declined: "no beads.role and no remote implies maintainer"
is documented base behavior for local projects, so closing it there would
reclassify every such user rather than the blinded slice this PR introduced.

F2 (major, blast radius) — the stack hardened every role reader and left four
writer/reader sites fully inherited, a divergence that did not exist at base:
an inherited GIT_DIR sends setBeadsRole's write to another repository while
the scrubbed readers look at the one the user is standing in. All four now
share the same boundary (init.go's getBeadsRole/setBeadsRole,
init_contributor.go, hooks.go's uninstall --get/--unset pair).

The required fix also asked for cmd.Dir = repoRoot on the init.go pair. Still
not taken, but not on the grounds iteration 1 recorded (see A2). What holds is
the measurement against the vector the fix targets: with GIT_DIR, GIT_WORK_TREE
and GIT_COMMON_DIR gone, no production path chdirs away from the invocation
directory — `grep -rn 'os\.Chdir' --include='*.go'` over production cmd/bd
returns nothing and `bd init` takes no path argument — so threading a repoRoot
through both signatures and their eight call sites buys no behavior change
against a redirect.

F3 (major, security) — this PR converted internal/config's isGitTracked probe
from inherited to scrub-only. The guard is fail-open by construction, so in a
legitimately routed checkout (bare repo.git, GIT_DIR/GIT_WORK_TREE exported,
no in-tree .git) the probe stopped answering and `bd config set
linear.api_key` would have written the credential into a tracked file.
Restored the two-probe shape sibling #6464 applied to the structural twin:
scrubbed probe first, inherited second, either "tracked" refuses.

F5 (minor) — disclose that scrubbing GIT_CEILING_DIRECTORIES widens upward
discovery rather than bounding it, in the worktree comment and the docs
paragraph that asserted only the narrowing effect. F2's fix extends that
trade-off to two more sites, so the disclosure is now load-bearing.

F7 (minor) — renamed isConfigSuppression to isConfigSuppressionControl and
documented why the NOSYSTEM arm is deliberately value-blind. Took the
rename/document arm rather than restricting the arm to git-true values, which
would have contradicted the PR's own pinned table.

F10 (nit) — pinned both suppression tables in the windows-latest required
list; verified each name matches the gate's grep exactly once.

--- Iteration 2 ---

The first fixup's F1 census named a site it did not reach, and its cmd.Dir
rationale named a mechanism that does not hold. Both are corrected here.

A1 (major, security) — the domain adapter's key-specific arm was guarded by
`key == "beads.role" && r.env == nil`, which is dead on the only production
role path: runInitProxiedServerTail rebinds the use case to
NewInitGitRepository whenever t.workDir != "" (its sole construction site
passes cwd), and that constructor captures ScrubRouting(os.Environ()) —
non-nil, suppression retained. The nil-env constructor has no
BeadsRole/SetBeadsRole caller, so the arm could only fire from tests, while
`bd init` under an inherited GIT_CONFIG_GLOBAL=/dev/null still missed a global
role, took hasRole=false, and persisted beads.role=maintainer into
repository-local config, where it outranks the global value for every later
read in a clean environment. Iteration 1 therefore left F1's escalation not
just alive but durable, on the one path the fix was supposed to close.

Fixed by keying the strict scrub on the config key alone and applying it to
whichever environment the repository already carries (roleAuthorityEnv). That
preserves capture semantics — NewInitGitRepository keeps its captured HOME,
the property git_test.go's captured_home case pins — and removes only the
suppression entries. Codex's alternative of rebuilding the constructor's whole
env was declined: it moves every key for no gain on this finding.

A2 (minor, contract fidelity) — iteration 1 justified declining cmd.Dir with
"repository selection is left to the working directory — the one input the
scrub keeps". That is false, and false in the file a future reader consults
before deciding whether to bound the pair: GIT_CEILING_DIRECTORIES is a routing
key too, so the scrub removes a bound rather than installing one. Measured from
a non-repository directory nested under a repository: `git config beads.role
<value>` fails "not in a git directory" while a ceiling below that repository is
inherited, and writes that repository's local config once the ceiling is
scrubbed. The decline itself stands, since the measurement behind it was made
against the GIT_DIR vector; getBeadsRole now records selection as the working
directory *or a containing ancestor*, which is also what makes
clearWorktreeGitRoutingEnv's existing cross-reference to "init's role probe"
true.

A3 (minor, consistency) — `bd config unset beads.role` and `bd config set-many
beads.role=` were the two spellings of that mutation still on ScrubRouting, in
the same file as the two that moved. Both measured inert: `git config <key>
<value>` and `--unset <key>` target the repository-local file, which the
suppression variables cannot select. Moved for parity rather than annotated,
because a divergence inside one file is how the next one starts.

Test evidence (minor) — the writer pair's two subtests both pass on the
redirect alone, so downgrading getBeadsRole back to ScrubRouting left them
green even though suppression is the load-bearing half at those sites
(init.go treats a getBeadsRole miss as permission to write a default role).
Added a global_null blinding subtest with the same unblinded fixture guard.

A4 (nit) — doctor/role.go's isGitRepo was the last probe in that file on the
suppression-retaining scrub, and it gates the "beads.role not configured"
warning. rev-parse is config-sensitive through safe.directory, which lives in
global config, so a retained GIT_CONFIG_GLOBAL=/dev/null can downgrade that
warning to "N/A (not a git repository)". Moved onto the same boundary as its
two siblings. As the finding records, the safe.directory precondition was not
reproduced end to end; the change is uniformity within the file.

Tests. Every pin reds only on its own defect:
- routing: reverting to ScrubRouting reds only the blinded-read subtest; the
  unblinded fixture guard and the PR's inject-vector table stay green.
- gitenv: keeping suppression reds 10 of 16 new subtests, none of the PR's.
- cmd/bd: restoring the inherited env reds both redirect subtests and names
  both halves ("the write did not land where bd is standing" / "an inherited
  GIT_DIR captured the write"), while the PR's own role roundtrip stays green
  — it followed the same redirect on both sides, so it never saw this.
- config: the two arms are proved separately. Scrub-only reds only the
  legitimate-routing subtest; inherited-only reds only the poisoned-routing
  subtest, so the new fallback cannot be read as a way around the scrub.
- domain/git (A1): restoring the r.env == nil provenance guard reds
  global_null only; unblinded stays green, and no other test in the package
  moves — which is the same measurement that confirms the arm had no coverage
  before this iteration.

Deferred to follow-up, recorded for the approval summary: F4 (delete
isRoleGitRepo and resolve the dead else-if), F6 (user.name degrading to
hostname, which needs the PR's own subtest re-pointed), F8 (execenv fold
divergence), F9 and F11 (GetIdentity hostname degradation under inherited
suppression). F9's mechanism is confirmed — identity supplied only via
GIT_CONFIG_COUNT is lost when GIT_CONFIG_* is stripped, git reports "Please
tell me who you are", while GIT_AUTHOR_*/GIT_COMMITTER_* survive — but its
"leave artifact commits on the inherited environment" arm would re-open the
GIT_DIR redirect this PR's tail swap closed, and the non-regressing arm
(re-injecting inline identity pre-scrub) is a design change with no observed
victim in this repo.

Validation (iteration 2): internal/{gitenv,routing,storage/domain/git} full
packages green; cmd/bd/doctor full package run; targeted cmd/bd run over the
role, config and init blast radius green at 54 tests; go build ./... clean; go
vet plus CGO_ENABLED=0 and GOOS=windows CGO_ENABLED=0 vet clean on every
changed package. Remaining local reds are base-parity, each matching the
recorded cause: cmd/bd/doctor's seven (the launcher's global
beads.role=maintainer short-circuits CheckBeadsRole before isGitRepo is
reached, plus Dolt server availability) and
TestInitContributorSetsBeadsRoleContributor ("--contributor requires
interactive prompts", this session's stdin is not a TTY).

--- Iteration 3 ---

Iteration 3 reviewed 0220eed32 and approved it: claude filed no findings,
codex's six fix validations all came back correct, synthesis recorded
Decision: approve, and the scorecard scored 881/1000 with Required Changes:
None. The residual was two minors and a nit, none of them merge gates. All
three are taken here because they are comment-and-constant scope, so nothing
in the approved behavior moves.

B1 (minor, blast radius; codex filed it as major, demoted at synthesis) — the
isGitRepo() gate that decides whether the role pair runs is still fully
inherited while the pair it guards is now strict, so from a non-repository
directory with an inherited GIT_DIR the gate opens, the scrubbed read misses,
and the safety-net write fails "not in a git directory". Recorded at the
GH#2950 safety net rather than restructured, for the three reasons the
demotion rests on. The achievable outcome is base parity: sync_git.go is
byte-identical at base and the pair was inherited there too, so a GIT_DIR
holder already reached Maintainer before this PR — more directly, by pointing
at a repository whose beads.role is maintainer. The failure is not silent:
init prints "Warning: failed to set beads.role" unless --quiet, and every
later detection prints "beads.role not configured (GH#2950)" with two Fix
lines. And the prescribed roleRepoAvailable() gate provably does not close it:
all five gate sites are bare `if isGitRepo()` with no else, so a strict gate
answers false in exactly the described band, nothing is written, the role
stays unset, and detection still falls to detectFromURL. The optional
hardening is therefore declined rather than deferred — it would delete a
warning and change no role — and the comment says so, so the next reader does
not mistake a gate change for closing the fail-open path.

B2 (minor, contract fidelity) — the getBeadsRole rationale iteration 2 wrote
to close A2 introduced a new overstatement in its closing sentence: "bd init
takes no path argument — the residual is upward discovery from an unintended
cwd, not a redirect". `bd -C <dir>` is a redirect and takes no path argument.
Verified in tree rather than from the finding: applyChangeDirSelection
(main.go) resolves the target's .beads dir and sets BEADS_DIR with no chdir,
it runs from the root PersistentPreRunE ahead of every init-related early
return in that hook, and init honors BEADS_DIR for workspace selection — so
`bd -C other init` acts on other/.beads while the pair reads and writes
beads.role in the invocation repository. init.go's own "PersistentPreRun
doesn't run for init command" note is about the later skipsStoreInit return,
not about -C, which is what made this vector easy to miss twice. Reachability
is bounded: -C requires an existing beads project at the target, so the
pairing arises on re-init rather than first init. Comment narrowed to name the
residual; threading init's resolved project root through the pair is the
stronger arm and stays out of scope as a behavior change.

B3 (nit, architectural consistency) — the adapter selected the role-authority
boundary on a bare "beads.role" literal while the use case passed the
unexported beadsRoleConfigKey, two spellings of one contract the compiler
could not couple. Exported it as domain.BeadsRoleConfigKey and compared
against it at both adapter arms; no new import edge, since package git already
imports domain. Mutation-proved rather than asserted: replacing the
comparison with the case-variant "Beads.Role" the finding names reds
TestInitGitRepositoryRoleIgnoresInheritedConfigSuppression/global_null alone
while unblinded stays green, so the drift the nit describes is caught by an
existing pin. The comparison is still exact, not case-folded: git config names
are case-insensitive, so a caller hand-writing a variant spelling would bypass
roleAuthorityEnv, but folding widens which keys take the strict environment
and no production caller passes anything but the const — a behavior change the
nit did not ask for.

Validation (iteration 3): go build ./... clean; go vet plus CGO_ENABLED=0 and
GOOS=windows CGO_ENABLED=0 vet clean on cmd/bd, cmd/bd/doctor,
internal/storage/domain, internal/storage/domain/git and internal/gitenv;
internal/storage/domain/... full packages green (domain, db, fs, git); targeted
cmd/bd role run green at 19 subtests with no skips
(TestBeadsRoleCommandsIgnoreInheritedGitRouting and
TestBeadsRoleWriterIgnoresInheritedGitRouting, including the suppression
subtest added in iteration 2); gofmt and git diff --check clean. Full cmd/bd is
still not run locally: it times out at base as well. The iteration-1 deferrals
are unchanged and still owed follow-up bead ids at finalize (F4, F6/F11, F8,
F9).

---------

Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
Co-authored-by: Bee <bee@ghosttrack.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-27 15:59:08 -07:00

517 lines
18 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"strings"
"testing"
"github.com/steveyegge/beads/internal/gitenv"
)
func TestTruncateForBox(t *testing.T) {
tests := []struct {
name string
path string
maxLen int
want string
}{
{
name: "short path no truncate",
path: "/home/user",
maxLen: 20,
want: "/home/user",
},
{
name: "exact length",
path: "12345",
maxLen: 5,
want: "12345",
},
{
name: "needs truncate",
path: "/very/long/path/to/somewhere/deep",
maxLen: 15,
want: "...mewhere/deep",
},
{
name: "truncate to minimum",
path: "abcdefghij",
maxLen: 5,
want: "...ij",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := truncateForBox(tt.path, tt.maxLen)
if got != tt.want {
t.Errorf("truncateForBox(%q, %d) = %q, want %q", tt.path, tt.maxLen, got, tt.want)
}
if len(got) > tt.maxLen {
t.Errorf("truncateForBox(%q, %d) returned %q with length %d > maxLen %d",
tt.path, tt.maxLen, got, len(got), tt.maxLen)
}
})
}
}
func TestGitRevParse(t *testing.T) {
// Basic test - should either return a value or empty string (if not in git repo)
result := gitRevParse("--git-dir")
// Just verify it doesn't panic and returns a string
if result != "" {
// In a git repo
t.Logf("Git dir: %s", result)
} else {
// Not in a git repo or error
t.Logf("Not in git repo or error")
}
}
func TestGitCmdInDirSuppressesHooksViaGitConfig(t *testing.T) {
t.Setenv("GIT_DIR", "/wrong")
t.Setenv("GIT_OPTIONAL_LOCKS", "1")
suppression := map[string]string{"GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.DevNull, "GIT_CONFIG_SYSTEM": os.DevNull}
for key, value := range suppression {
t.Setenv(key, value)
}
cmd := gitCmdInDir(t.Context(), "/tmp/example", "status", "--porcelain")
if cmd.Dir != "/tmp/example" {
t.Fatalf("cmd.Dir = %q, want /tmp/example", cmd.Dir)
}
wantArgs := []string{"-c", "core.hooksPath=", "status", "--porcelain"}
if len(cmd.Args) != len(wantArgs)+1 {
t.Fatalf("cmd.Args = %#v, want git plus %#v", cmd.Args, wantArgs)
}
for i, want := range wantArgs {
if got := cmd.Args[i+1]; got != want {
t.Fatalf("cmd.Args[%d] = %q, want %q; full args: %#v", i+1, got, want, cmd.Args)
}
}
hasTemplateSuppression := false
hasOptionalLocks := false
for _, env := range cmd.Env {
if env == "GIT_HOOKS_PATH=" {
t.Fatal("cmd.Env contains dead GIT_HOOKS_PATH hook suppression")
}
if env == "GIT_TEMPLATE_DIR=" {
hasTemplateSuppression = true
}
if env == "GIT_OPTIONAL_LOCKS=1" {
hasOptionalLocks = true
}
key := worktreeGitEnvKey(env)
if want, ok := suppression[key]; ok {
if env != key+"="+want {
t.Fatalf("changed config suppression: %q", env)
}
delete(suppression, key)
continue
}
if gitenv.IsRoutingKeyForOS(worktreeGitEnvKey(env), runtime.GOOS) && env != "GIT_TEMPLATE_DIR=" {
t.Fatalf("cmd.Env retains Git routing state: %q", env)
}
}
if !hasTemplateSuppression {
t.Fatal("cmd.Env missing GIT_TEMPLATE_DIR suppression")
}
if !hasOptionalLocks {
t.Fatal("cmd.Env did not preserve GIT_OPTIONAL_LOCKS")
}
if len(suppression) != 0 {
t.Fatalf("cmd.Env dropped explicit config suppression: %v", suppression)
}
}
func TestScrubWorktreeRemovalGitEnvUsesSharedWindowsKeyIdentity(t *testing.T) {
// os/exec identifies Windows keys with ToLower, which keeps the dotless i
// distinct. A ToUpper fold would map GıT_OPTIONAL_LOCKS onto
// GIT_OPTIONAL_LOCKS and strip an unrelated variable from the child.
input := []string{
"GıT_OPTIONAL_LOCKS=1", "git_optional_locks=1",
"GIT_NO_REPLACE_OBJECTS=1", "KEEP=value",
}
want := []string{"GıT_OPTIONAL_LOCKS=1", "KEEP=value"}
if got := scrubWorktreeRemovalGitEnvForOS(input, "windows"); !reflect.DeepEqual(got, want) {
t.Fatalf("scrubWorktreeRemovalGitEnvForOS(windows) = %q, want %q", got, want)
}
}
func TestClearWorktreeGitRoutingEnvPreservesNonRoutingVariables(t *testing.T) {
// ClearRouting is deliberately process-lifetime state for the real CLI.
// Register restorations for every routing key inherited by the test process
// before exercising that boundary in-process.
for _, entry := range os.Environ() {
key := worktreeGitEnvKey(entry)
if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) {
t.Setenv(key, os.Getenv(key))
}
}
t.Setenv("GIT_DIR", "/wrong")
t.Setenv("GIT_CONFIG_COUNT", "1")
t.Setenv("GIT_OPTIONAL_LOCKS", "1")
t.Setenv("GIT_NO_REPLACE_OBJECTS", "1")
t.Setenv("BD_WORKTREE_ENV_SENTINEL", "keep")
if err := clearWorktreeGitRoutingEnv(worktreeListCmd); err != nil {
t.Fatalf("clearWorktreeGitRoutingEnv() error = %v", err)
}
for _, key := range []string{"GIT_DIR", "GIT_CONFIG_COUNT"} {
if value, ok := os.LookupEnv(key); ok {
t.Fatalf("%s remains set to %q", key, value)
}
}
for key, want := range map[string]string{
"GIT_OPTIONAL_LOCKS": "1",
"GIT_NO_REPLACE_OBJECTS": "1",
"BD_WORKTREE_ENV_SENTINEL": "keep",
} {
if got := os.Getenv(key); got != want {
t.Fatalf("%s = %q, want %q", key, got, want)
}
}
}
func TestWorktreeCommandsIgnoreInheritedGitRoutingState(t *testing.T) {
bdBinary := buildBDForInitTests(t)
decoyRepo := newGitRepo(t)
commitTestFile(t, decoyRepo, "README.md", "decoy\n", "decoy commit")
decoyBeadsDir := filepath.Join(decoyRepo, ".beads")
writeTestConfigYAML(t, decoyBeadsDir, "issue-prefix: decoy\n")
if err := os.WriteFile(
filepath.Join(decoyBeadsDir, ".env"),
[]byte("BEADS_DIR="+filepath.ToSlash(decoyBeadsDir)+"\n"),
0o600,
); err != nil {
t.Fatalf("write decoy selector environment: %v", err)
}
// An unsanitized post-create status check would see this file and reject an
// otherwise clean target worktree.
if err := os.WriteFile(filepath.Join(decoyRepo, "decoy-dirty.txt"), []byte("dirty\n"), 0600); err != nil {
t.Fatal(err)
}
poisonConfig := filepath.Join(t.TempDir(), "poison.gitconfig")
if err := os.WriteFile(poisonConfig, []byte("[core]\n\tworktree = "+filepath.ToSlash(decoyRepo)+"\n"), 0600); err != nil {
t.Fatal(err)
}
poisonEnv := []string{
"GIT_DIR=" + filepath.Join(decoyRepo, ".git"),
"GIT_WORK_TREE=" + decoyRepo,
"GIT_COMMON_DIR=" + filepath.Join(decoyRepo, ".git"),
"GIT_INDEX_FILE=" + filepath.Join(decoyRepo, ".git", "index"),
"GIT_OBJECT_DIRECTORY=" + filepath.Join(decoyRepo, ".git", "objects"),
"GIT_ALTERNATE_OBJECT_DIRECTORIES=" + filepath.Join(decoyRepo, ".git", "objects"),
"GIT_EXEC_PATH=" + filepath.Join(decoyRepo, "missing-git-exec"),
"GIT_NAMESPACE=poison",
"GIT_CONFIG_GLOBAL=" + poisonConfig,
"GIT_CONFIG_SYSTEM=" + poisonConfig,
"GIT_CONFIG_NOSYSTEM=0",
"GIT_CONFIG_COUNT=1",
"GIT_CONFIG_KEY_0=core.worktree",
"GIT_CONFIG_VALUE_0=" + decoyRepo,
"GIT_OPTIONAL_LOCKS=1",
"BEADS_DIR=",
"BEADS_DB=",
"BD_DB=",
}
t.Run("create list and remove stay in the target repository", func(t *testing.T) {
targetRepo := newGitRepo(t)
commitTestFile(t, targetRepo, "README.md", "target\n", "target commit")
writeTestConfigYAML(t, filepath.Join(targetRepo, ".beads"), "issue-prefix: target\n")
decoyRegistryBefore := gitWorktreeRegistry(t, decoyRepo)
create := runWorktreeCommandProcess(t, bdBinary, targetRepo, "create", poisonEnv, "lane")
create.requireSuccess(t)
var created struct {
Path string `json:"path"`
Branch string `json:"branch"`
}
decodeWorktreeCommandJSON(t, create.stdout, &created)
lane := filepath.Join(targetRepo, "lane")
if !sameWorktreePath(created.Path, lane) || created.Branch != "lane" {
t.Fatalf("create result = %#v, want target lane %q", created, lane)
}
assertGitWorktreePaths(t, targetRepo, targetRepo, lane)
if got := gitWorktreeRegistry(t, decoyRepo); got != decoyRegistryBefore {
t.Fatalf("create mutated decoy worktree registry:\n--- before ---\n%s\n--- after ---\n%s", decoyRegistryBefore, got)
}
list := runWorktreeCommandProcess(t, bdBinary, targetRepo, "list", poisonEnv)
list.requireSuccess(t)
var listed []WorktreeInfo
decodeWorktreeCommandJSON(t, list.stdout, &listed)
if len(listed) != 2 ||
!sameWorktreePath(listed[0].Path, targetRepo) || listed[0].BeadsState != "shared" ||
!sameWorktreePath(listed[1].Path, lane) || listed[1].BeadsState != "none" {
t.Fatalf("list resolved outside target repository or beads state: %#v", listed)
}
info := runWorktreeCommandProcess(t, bdBinary, lane, "info", poisonEnv)
info.requireSuccess(t)
var details struct {
IsWorktree bool `json:"is_worktree"`
Path string `json:"path"`
MainRepo string `json:"main_repo"`
Branch string `json:"branch"`
BeadsRedirected bool `json:"beads_redirected"`
}
decodeWorktreeCommandJSON(t, info.stdout, &details)
if !details.IsWorktree ||
!sameWorktreePath(details.Path, lane) ||
!sameWorktreePath(details.MainRepo, targetRepo) ||
details.Branch != "lane" ||
details.BeadsRedirected {
t.Fatalf("info resolved outside the target worktree: %#v", details)
}
remove := runWorktreeCommandProcess(t, bdBinary, targetRepo, "remove", poisonEnv, lane, "--force")
remove.requireSuccess(t)
if _, err := os.Stat(lane); !os.IsNotExist(err) {
t.Fatalf("remove left target worktree behind: %v", err)
}
assertGitWorktreePaths(t, targetRepo, targetRepo)
if _, err := os.Stat(filepath.Join(decoyRepo, "decoy-dirty.txt")); err != nil {
t.Fatalf("remove mutated decoy repository: %v", err)
}
})
t.Run("create refuses a target without a beads workspace", func(t *testing.T) {
targetRepo := newGitRepo(t)
commitTestFile(t, targetRepo, "README.md", "target without beads\n", "target commit")
lane := filepath.Join(targetRepo, "lane")
registryBefore := gitWorktreeRegistry(t, targetRepo)
create := runWorktreeCommandProcess(t, bdBinary, targetRepo, "create", poisonEnv, "lane")
if create.exitCode == 0 {
t.Fatalf("create accepted the decoy beads workspace\nstdout:\n%s\nstderr:\n%s", create.stdout, create.stderr)
}
if _, err := os.Stat(lane); !os.IsNotExist(err) {
t.Fatalf("refused create mutated target path: %v", err)
}
if got := gitWorktreeRegistry(t, targetRepo); got != registryBefore {
t.Fatalf("refused create mutated target worktree registry:\n--- before ---\n%s\n--- after ---\n%s", registryBefore, got)
}
if _, err := os.Stat(filepath.Join(targetRepo, ".gitignore")); !os.IsNotExist(err) {
t.Fatalf("refused create mutated target gitignore: %v", err)
}
})
t.Run("startup ignores malformed config selected by linked-worktree routing", func(t *testing.T) {
targetRepo := newGitRepo(t)
commitTestFile(t, targetRepo, "README.md", "target\n", "target commit")
decoyMain := newGitRepo(t)
commitTestFile(t, decoyMain, "README.md", "linked decoy\n", "decoy commit")
writeTestConfigYAML(t, filepath.Join(decoyMain, ".beads"), "json: [\n")
decoyLane := filepath.Join(t.TempDir(), "linked-decoy")
command := exec.Command("git", "worktree", "add", "-b", "linked-decoy", decoyLane)
command.Dir = decoyMain
if output, err := command.CombinedOutput(); err != nil {
t.Fatalf("create decoy linked worktree: %v\n%s", err, output)
}
decoyAdminDir := gitRevParsePath(t, decoyLane, "--absolute-git-dir")
decoyCommonDir := gitRevParsePath(t, decoyLane, "--git-common-dir")
linkedPoisonEnv := append(append([]string(nil), poisonEnv...),
"GIT_DIR="+decoyAdminDir,
"GIT_WORK_TREE="+decoyLane,
"GIT_COMMON_DIR="+decoyCommonDir,
"GIT_INDEX_FILE="+filepath.Join(decoyAdminDir, "index"),
"GIT_OBJECT_DIRECTORY="+filepath.Join(decoyCommonDir, "objects"),
"GIT_ALTERNATE_OBJECT_DIRECTORIES="+filepath.Join(decoyCommonDir, "objects"),
"BEADS_TEST_IGNORE_REPO_CONFIG=",
)
list := runWorktreeCommandProcess(t, bdBinary, targetRepo, "list", linkedPoisonEnv)
list.requireSuccess(t)
if strings.Contains(strings.ToLower(list.stderr), "failed to initialize config") {
t.Fatalf("malformed decoy config reached startup initialization:\n%s", list.stderr)
}
var listed []WorktreeInfo
decodeWorktreeCommandJSON(t, list.stdout, &listed)
if len(listed) != 1 || !sameWorktreePath(listed[0].Path, targetRepo) {
t.Fatalf("list resolved outside target repository: %#v", listed)
}
})
}
func runWorktreeCommandProcess(t *testing.T, bdBinary, dir, action string, extraEnv []string, args ...string) worktreeRemoveProcessResult {
t.Helper()
commandArgs := append([]string{"--json", "worktree", action}, args...)
command := exec.Command(bdBinary, commandArgs...)
command.Dir = dir
command.Env = overrideWorktreeRemoveEnv(os.Environ(), append([]string{
"BD_DISABLE_METRICS=1",
"BD_DISABLE_EVENT_FLUSH=1",
"BEADS_TEST_MODE=1",
}, extraEnv...))
var stdout, stderr bytes.Buffer
command.Stdout, command.Stderr = &stdout, &stderr
err := command.Run()
exitCode := 0
if err != nil {
var exitError *exec.ExitError
if !errors.As(err, &exitError) {
t.Fatalf("launch worktree command helper: %v", err)
}
exitCode = exitError.ExitCode()
}
return worktreeRemoveProcessResult{stdout: stdout.String(), stderr: stderr.String(), exitCode: exitCode}
}
func decodeWorktreeCommandJSON(t *testing.T, output string, target any) {
t.Helper()
if err := json.NewDecoder(strings.NewReader(output)).Decode(target); err != nil {
t.Fatalf("decode helper JSON: %v\noutput:\n%s", err, output)
}
}
func gitWorktreeRegistry(t *testing.T, repoDir string) string {
t.Helper()
command := exec.Command("git", "worktree", "list", "--porcelain")
command.Dir = repoDir
output, err := command.CombinedOutput()
if err != nil {
t.Fatalf("list Git worktree registry for %q: %v\n%s", repoDir, err, output)
}
return strings.TrimSpace(string(output))
}
func assertGitWorktreePaths(t *testing.T, repoDir string, want ...string) {
t.Helper()
var got []string
for _, line := range strings.Split(gitWorktreeRegistry(t, repoDir), "\n") {
if path, ok := strings.CutPrefix(strings.TrimSpace(line), "worktree "); ok {
got = append(got, filepath.FromSlash(path))
}
}
if len(got) != len(want) {
t.Fatalf("Git worktree paths = %#v, want %#v", got, want)
}
matched := make([]bool, len(got))
for _, wantPath := range want {
found := false
for index, gotPath := range got {
if !matched[index] && sameWorktreePath(gotPath, wantPath) {
matched[index] = true
found = true
break
}
}
if !found {
t.Fatalf("Git worktree paths = %#v, missing %q", got, wantPath)
}
}
}
func gitRevParsePath(t *testing.T, repoDir, selector string) string {
t.Helper()
command := exec.Command("git", "rev-parse", selector)
command.Dir = repoDir
output, err := command.CombinedOutput()
if err != nil {
t.Fatalf("git rev-parse %s in %q: %v\n%s", selector, repoDir, err, output)
}
path := filepath.FromSlash(strings.TrimSpace(string(output)))
if !filepath.IsAbs(path) {
path = filepath.Join(repoDir, path)
}
return filepath.Clean(path)
}
// TestResolveWorktreePathByName verifies that resolveWorktreePath can find
// worktrees by name (basename) when they're in subdirectories like .worktrees/
func TestResolveWorktreePathByName(t *testing.T) {
// Create a temp directory for the main repo
mainDir := newGitRepo(t)
// Create initial commit (required for worktrees)
if err := os.WriteFile(filepath.Join(mainDir, "README.md"), []byte("# Test\n"), 0644); err != nil {
t.Fatalf("Failed to create test file: %v", err)
}
cmd := exec.Command("git", "add", ".")
cmd.Dir = mainDir
_ = cmd.Run()
cmd = exec.Command("git", "commit", "-m", "Initial commit")
cmd.Dir = mainDir
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("Failed to create initial commit: %v\n%s", err, output)
}
// Create .worktrees subdirectory
worktreesDir := filepath.Join(mainDir, ".worktrees")
if err := os.MkdirAll(worktreesDir, 0755); err != nil {
t.Fatalf("Failed to create .worktrees dir: %v", err)
}
// Create a worktree inside .worktrees/
worktreePath := filepath.Join(worktreesDir, "test-wt")
cmd = exec.Command("git", "worktree", "add", "-b", "test-wt", worktreePath)
cmd.Dir = mainDir
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("Failed to create worktree: %v\n%s", err, output)
}
defer func() {
// Cleanup worktree
cmd := exec.Command("git", "worktree", "remove", worktreePath, "--force")
cmd.Dir = mainDir
_ = cmd.Run()
}()
ctx := context.Background()
t.Run("resolves by name when worktree is in subdirectory", func(t *testing.T) {
// This should find the worktree by consulting git's registry
resolved, err := resolveWorktreePath(ctx, mainDir, "test-wt")
if err != nil {
t.Errorf("resolveWorktreePath(repoRoot, \"test-wt\") failed: %v", err)
return
}
// Compare resolved paths to handle symlinks (e.g., /var -> /private/var on macOS)
wantResolved, _ := filepath.EvalSymlinks(worktreePath)
gotResolved, _ := filepath.EvalSymlinks(resolved)
if gotResolved != wantResolved {
t.Errorf("resolveWorktreePath returned %q, want %q", resolved, worktreePath)
}
})
t.Run("resolves by relative path", func(t *testing.T) {
// This should work via the existing relative-to-repo-root logic
resolved, err := resolveWorktreePath(ctx, mainDir, ".worktrees/test-wt")
if err != nil {
t.Errorf("resolveWorktreePath(repoRoot, \".worktrees/test-wt\") failed: %v", err)
return
}
if resolved != worktreePath {
t.Errorf("resolveWorktreePath returned %q, want %q", resolved, worktreePath)
}
})
t.Run("resolves by absolute path", func(t *testing.T) {
resolved, err := resolveWorktreePath(ctx, mainDir, worktreePath)
if err != nil {
t.Errorf("resolveWorktreePath(repoRoot, absolutePath) failed: %v", err)
return
}
if resolved != worktreePath {
t.Errorf("resolveWorktreePath returned %q, want %q", resolved, worktreePath)
}
})
t.Run("returns error for non-existent worktree", func(t *testing.T) {
_, err := resolveWorktreePath(ctx, mainDir, "non-existent")
if err == nil {
t.Error("resolveWorktreePath should return error for non-existent worktree")
}
})
}