beads/cmd/bd/prime_git_remote_test.go
Vishnu J 892a438f1e
fix(prime): detect git remote from CWD, not BEADS_DIR context (#5139)
* fix(prime): detect git remote from CWD, not BEADS_DIR context

primeHasGitRemote and isEphemeralBranch used GetRepoContext(), which
validates BEADS_DIR against isPathInSafeBoundary. Cross-home agent
sandboxes mount host workspaces under another account path; BEADS_DIR
validation fails and was misreported as "no git remote" even when
`git remote` in the process CWD succeeds.

Probe git in the process CWD (and explicit dir helper) independently of
RepoContext / BEADS_DIR. SEC-003 boundary on BEADS_DIR is unchanged.

Fixes #4927

* test(prime): drop inverted !cgo constraint so the regression test actually runs

The new test carried //go:build !cgo while all 255 sibling test files in
cmd/bd use //go:build cgo, so under the default cgo build the test was
excluded entirely and never exercised the fix it was written for.
Removing the constraint lets it run in both modes.

* test(prime): make the git-remote test hit the boundary it claims to, unify gitDirHasRemote

Review follow-up on #4927 (maphew):

The poison BEADS_DIR value didn't exist on disk, so it tripped
FindBeadsDir()=="" (context.go:107) rather than isPathInSafeBoundary
(context.go:112), even though the test comment implied it exercised the
boundary check. Both funnel into the same err!=nil->false bug so the old
test was a fair proxy, but it didn't test what it said. Seed a real
directory under a rejected prefix (/var/tmp) so BEADS_DIR actually reaches
isPathInSafeBoundary, and add a second case for the FindBeadsDir()=="" path
so both RepoContext failure modes are covered and asserted against
directly via beads.GetRepoContext().

gitDirHasRemote had no production caller — prime only went through
gitCWDHasRemote, so the helper carrying the test's assertions wasn't the
one prime used. Make gitCWDHasRemote delegate to gitDirHasRemote("") so
there is one implementation and the test exercises the real production
path.

* test(prime): scope the unsafe-location subcase to Unix

SEC-003's unsafePrefixes are hardcoded forward-slash literals matched
via strings.HasPrefix. On Windows, filepath.Join renders the fixture
path with backslashes, so the prefix never matches and the assertion
would fail with err == nil. Move it into its own subtest and skip on
GOOS=="windows" rather than deleting or weakening it, so Case 2 (the
nonexistent-BEADS_DIR path, which doesn't touch unsafePrefixes) still
runs on every platform.

gitDirHasRemote / gitCWDHasRemote / primeHasGitRemote are untouched.

* test(prime): delete obsolete unsafe_location_rejected subtest

Upstream added an ALLOW carve-out for /var/tmp in isPathInSafeBoundary
(af076b628, #5028) after this test was written. resolvedPathWithinRoot
resolves both sides, so the carve-out now admits the poison dir on all
platforms and the subtest's premise (that /var/tmp is boundary-rejected)
is false on current main. Delete it rather than retarget at another
unsafe prefix -- none are writable in CI, so a retargeted assertion
would silently no-op via the existing t.Skipf fallback.

The CWD-based checks are unaffected and stay unconditional; update the
surrounding comments since they described the fixture as "a
boundary-rejected BEADS_DIR", which is no longer accurate anywhere in
the file.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* chore(bazel): sync cmd/bd BUILD.bazel srcs for prime_git_remote_test.go

Maintainer fixup during PR adoption. cmd/bd/BUILD.bazel enumerates an
explicit go_test srcs list, so the new prime_git_remote_test.go added by
this PR was not compiled into //cmd/bd:bd_test. bazel.yml (armed on this
fork PR: FORK=true => mode=local, not skip) runs make bazel-sync and
exit 1s on any resulting drift, and bazel-pure builds and runs
//cmd/bd:bd_test.

This hunk is the verbatim output of make bazel-sync (bazel run //:gazelle).

Verified: bazel build --config=pure //cmd/bd:bd_test exit 0 both ways;
bd_test -test.list went 1771 -> 1772 entries with
TestGitDirHasRemote_IndependentOfBeadsDir going 0 -> 1 and control
TestOutputContextFunction present in both arms. make bazel-sync is
idempotent (2nd run byte-identical). make bazel-sync-check exits 0 in
both states, so it cannot see this class.

* review(prime): address the three non-gating findings from PR review

Maintainer fixup for PR #5139 review iteration 1. The synthesis and the
quality scorecard both approve with no blocker or major findings; these are
the three non-gating maintainability items, all in scaffolding this PR
itself introduced.

- prime.go: delete the false clause in gitCWDHasRemote's doc comment ("so
  the production path and the test-driven path share one implementation").
  The pair has zero production callers -- the production probes build their
  own command in primeGitCmd -- so the comment now records that instead. Per
  the synthesis, only the false clause is removed: the following sentence is
  accurate, and the fallback is deliberately NOT routed through the helper
  merely to make the old sentence true.
- prime_git_remote_test.go: rename to TestPrimeGitProbes_IndependentOfBeadsDir
  so the test names its real subject, and pin isEphemeralBranch -- the second
  probe this fix repairs, and the source of the user-visible "ephemeral
  branch" half of GH#4927 -- which previously had zero references in the file.
- prime.go: record that primeGitCmd's error result is always nil today and is
  retained for future callers, so the now-unreachable err != nil arms are
  documented rather than mistaken for live error handling.

The isEphemeralBranch pin asserts BOTH polarities under the same poisoned
BEADS_DIR, which is what the codex lane asked for: with a remote but no
upstream the branch really is ephemeral, and after a purely local upstream is
configured the same probe must flip. The two assertions differ by exactly the
two upstream-setup lines, so the pair is its own non-vacuity proof.

On the test finding I took the harm rather than the literal means. The
prescription offered "drop or retarget the gitDirHasRemote/gitCWDHasRemote
assertions", but dropping them would falsify the very sentence the first
finding asks to preserve ("the BEADS_DIR-independent primitive the GH#4927
regression test drives directly"). They are instead kept explicitly as the
fixture/oracle checks -- the alternative the review's own pre-merge checklist
blesses -- and the unpinned-coverage harm is discharged by the new
isEphemeralBranch assertions.

The probe assertions move from t.Fatal to t.Error so a regression in one
probe cannot mask another's. That is what makes the new pin measurable:
reverting primeGitCmd's GetRepoContext() fallback to "return nil, err" (go
build rc 0, so the arm is not vacuous) reds both primeHasGitRemote and the
upstream-configured isEphemeralBranch assertion, while gitCWDHasRemote and
the no-upstream control stay green -- confirming the oracle bypasses the fix,
and that the new assertion does not.

The rename supersedes the test name quoted in the preceding bazel-sync
commit. BUILD.bazel is untouched because the filename is unchanged, and
bd_test -test.list still holds 1772 entries with the new name present once,
the old name absent, and control TestOutputContextFunction present.

Verified: gofmt, go vet ./cmd/bd/, git diff --check, make bazel-sync (rc 0,
no drift), bazel build --config=pure //cmd/bd:bd_test (rc 0), and go test
./cmd/bd/ over the renamed test plus the prime/backup_auto suites that stub
the probe vars.

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-30 20:27:21 -07:00

110 lines
4 KiB
Go

package main
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/git"
)
// GH#4927: prime's git probes must not depend on BEADS_DIR / RepoContext.
//
// buildRepoContext (internal/beads/context.go) can fail when FindBeadsDir()
// returns "" (context.go:107, e.g. BEADS_DIR doesn't exist). The pre-fix bug
// collapsed that GetRepoContext() error into "no git remote" / "ephemeral
// branch". This test poisons BEADS_DIR with a nonexistent path and verifies
// (a) that GetRepoContext() actually fails via FindBeadsDir()=="", and (b)
// that both probes the fix repairs -- primeHasGitRemote and isEphemeralBranch
// -- are unaffected by it.
//
// The probe assertions below use t.Error rather than t.Fatal so a regression
// in one probe does not mask the state of the others.
func TestPrimeGitProbes_IndependentOfBeadsDir(t *testing.T) {
dir := t.TempDir()
run := func(args ...string) {
t.Helper()
cmd := exec.Command(args[0], args[1:]...)
cmd.Dir = dir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("%v: %v\n%s", args, err, out)
}
}
run("git", "init", "-q")
run("git", "config", "user.name", "fixture")
run("git", "config", "user.email", "fixture@example.com")
run("git", "config", "commit.gpgsign", "false")
// gitDirHasRemote is the test-only oracle described in prime.go; these two
// assertions check that the fixture itself is built correctly, not the fix.
if gitDirHasRemote(dir) {
t.Fatal("expected no remote after init")
}
run("git", "remote", "add", "origin", "https://example.invalid/repo.git")
if !gitDirHasRemote(dir) {
t.Fatal("expected remote after git remote add origin")
}
// A committed branch that has a remote but no upstream -- the state in
// which the branch genuinely is ephemeral. The fixed branch name avoids
// depending on init.defaultBranch.
run("git", "commit", "-q", "--allow-empty", "-m", "fixture")
run("git", "checkout", "-q", "-B", "fixture-branch")
t.Cleanup(func() {
beads.ResetCaches()
git.ResetCaches()
})
// CWD-based probe: chdir into the fixture repo
wd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
if err := os.Chdir(dir); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chdir(wd) })
// BEADS_DIR points at a path that simply doesn't exist on disk — this is
// the FindBeadsDir()=="" failure mode (context.go:107). CWD is the
// fixture repo (no .beads anywhere in its ancestry), so the walk in
// FindBeadsDir also comes up empty.
t.Setenv("BEADS_DIR", filepath.Join(dir, "does-not-exist", ".beads"))
beads.ResetCaches()
git.ResetCaches()
if _, err := beads.GetRepoContext(); err == nil || !strings.Contains(err.Error(), "no .beads directory found") {
t.Fatalf("expected GetRepoContext() to fail via FindBeadsDir()==\"\", got err=%v", err)
}
if !gitCWDHasRemote() {
t.Error("gitCWDHasRemote should see origin even with a nonexistent BEADS_DIR set")
}
// The two probes the fix actually repairs. Both route through primeGitCmd,
// so both regress if its GetRepoContext() fallback is removed.
if !primeHasGitRemote() {
t.Error("primeHasGitRemote should see origin even with a nonexistent BEADS_DIR set")
}
// isEphemeralBranch, both polarities under the same poisoned BEADS_DIR.
// The branch has no upstream yet, so "ephemeral" is the correct answer
// here; this control is what proves the assertion below is reading git
// rather than returning a constant.
if !isEphemeralBranch() {
t.Error("isEphemeralBranch should report ephemeral while the branch has no upstream")
}
// Configure a real upstream -- entirely local, the remote is never
// contacted -- and the same probe must flip. Pre-fix it stayed true here,
// because the GetRepoContext() failure was itself reported as "ephemeral".
run("git", "update-ref", "refs/remotes/origin/fixture-branch", "HEAD")
run("git", "branch", "--set-upstream-to=origin/fixture-branch", "fixture-branch")
if isEphemeralBranch() {
t.Error("isEphemeralBranch should see the configured upstream even with a nonexistent BEADS_DIR set")
}
}