Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

10.3 KB
Raw Blame
package asymptote

import (
	"errors"
	"os"
	"path/filepath"
	"slices"
	"strings"
	"testing"

	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
)

// isolateVectorDiscovery hides the machine's own Vector installs from FindVector.
func isolateVectorDiscovery(t *testing.T) {
	t.Helper()
	t.Setenv(VectorBinEnv, "")
	oldSearch, oldLook := vectorSearchPaths, lookPath
	vectorSearchPaths = func() []string { return nil }
	lookPath = func(string) (string, error) { return "", errors.New("not found") }
	t.Cleanup(func() { vectorSearchPaths, lookPath = oldSearch, oldLook })
}

func TestFindVectorPrefersExplicitThenEnvAndChecksVersion(t *testing.T) {
	isolateVectorDiscovery(t)
	explicit := fakeVector(t, "0.56.0", 0)
	fromEnv := fakeVector(t, "0.58.2", 0)
	t.Setenv(VectorBinEnv, fromEnv)

	got, err := FindVector(explicit)
	if err != nil || got.Path != explicit || got.Version != "0.56.0" {
		t.Fatalf("explicit: %+v %v", got, err)
	}
	got, err = FindVector("")
	if err != nil || got.Path != fromEnv || got.Version != "0.58.2" {
		t.Fatalf("env: %+v %v", got, err)
	}
	t.Setenv(VectorBinEnv, "")
	if _, err := FindVector(""); !errors.Is(err, ErrVectorNotFound) && !strings.Contains(err.Error(), "vector") {
		t.Fatalf("expected not found without candidates, got %v", err)
	}
}

func TestFindVectorRejectsTooOldOrUnparsableVersions(t *testing.T) {
	old := fakeVector(t, "0.44.0", 0)
	if _, err := FindVector(old); err == nil || !strings.Contains(err.Error(), "0.50.0 or newer") {
		t.Fatalf("expected too-old error, got %v", err)
	}
	dir := t.TempDir()
	garbage := filepath.Join(dir, "vector")
	if err := os.WriteFile(garbage, []byte("#!/bin/sh\necho not a version\n"), 0o755); err != nil {
		t.Fatal(err)
	}
	if _, err := FindVector(garbage); err == nil || !strings.Contains(err.Error(), "could not read a version") {
		t.Fatalf("expected parse error, got %v", err)
	}
}

func TestCompareVersions(t *testing.T) {
	cases := []struct {
		a, b string
		want int
	}{
		{"0.56.0", "0.56.0", 0},
		{"0.57.0", "0.56.0", 1},
		{"0.55.9", "0.56.0", -1},
		{"1.0.0", "0.99.9", 1},
		{"0.56", "0.56.0", 0},
	}
	for _, c := range cases {
		if got := compareVersions(c.a, c.b); got != c.want {
			t.Errorf("compareVersions(%q,%q) = %d, want %d", c.a, c.b, got, c.want)
		}
	}
}

func TestEnrollmentStoreUsesPrivatePermissionsAndAtomicWrites(t *testing.T) {
	home := t.TempDir()
	testenv.SetHome(t, home)
	if _, err := LoadEnrollment(true); !errors.Is(err, ErrNotEnrolled) {
		t.Fatalf("expected ErrNotEnrolled, got %v", err)
	}
	if err := WriteSecrets(true, "not-a-device-key"); err == nil {
		t.Fatal("must refuse to store a non-device key")
	}
	if err := WriteSecrets(true, "bcn_device_abcdefgh_"+strings.Repeat("k", 43)); err != nil {
		t.Fatal(err)
	}
	info, err := os.Stat(SecretsPath(true))
	if err != nil || (testenv.HasPOSIXFileModes() && info.Mode().Perm() != 0o600) {
		t.Fatalf("secrets mode: %v %v", info, err)
	}
	entries, _ := os.ReadDir(Dir(true))
	for _, e := range entries {
		if strings.HasPrefix(e.Name(), ".") {
			t.Fatalf("temp file left behind: %s", e.Name())
		}
	}
	key, err := ReadDeviceKey(true)
	if err != nil || !strings.HasPrefix(key, "bcn_device_abcdefgh_") {
		t.Fatalf("ReadDeviceKey = %q %v", key, err)
	}
	if err := RemoveState(true, false); err != nil {
		t.Fatal(err)
	}
	if _, err := os.Stat(Dir(true)); !os.IsNotExist(err) {
		t.Fatal("RemoveState should delete the directory")
	}
}

// TestDefaultVectorSearchPathsPrefersTheBeaconVectorKeg pins where a Homebrew-installed
// Vector is looked for. The tap mirrors Vector as the beacon-vector keg rather than as a
// formula named `vector`, because Homebrew allows one keg by that name and a `vector`
// dependency broke `brew upgrade beacon` for anyone already running vectordotdev/brew's.
// That keg keeps its binary in libexec, which Homebrew never links, so nothing finds it
// except this path -- and it is tried ahead of any linked vector because it is the copy
// whose version the tap pins, and FindVector treats a too-old binary as an error rather
// than a reason to keep looking.
func TestDefaultVectorSearchPathsPrefersTheBeaconVectorKeg(t *testing.T) {
	t.Setenv("HOMEBREW_PREFIX", filepath.Join("/fake", "brew"))
	cliDir := t.TempDir()
	oldExe := currentExecutable
	currentExecutable = func() (string, error) { return filepath.Join(cliDir, "beacon"), nil }
	t.Cleanup(func() { currentExecutable = oldExe })
	paths := defaultVectorSearchPaths()

	if len(paths) < 2 || paths[0] != filepath.Join(cliDir, ArchiveVectorName) || paths[1] != PackagedVectorPath {
		t.Fatalf("defaultVectorSearchPaths() = %q, want %s beside the CLI, then the packaged Vector",
			paths, ArchiveVectorName)
	}
	if slices.Contains(paths, filepath.Join(cliDir, "vector")) {
		t.Fatalf("defaultVectorSearchPaths() = %q: a plain vector beside a Homebrew beacon is the "+
			"user's own, and must not outrank the pinned keg", paths)
	}
	keg := filepath.Join("/fake", "brew", "opt", TapVectorFormula, "libexec", "vector")
	if !slices.Contains(paths, keg) {
		t.Fatalf("defaultVectorSearchPaths() = %q, want it to include the beacon-vector keg %q", paths, keg)
	}
	if linked := filepath.Join("/fake", "brew", "bin", "vector"); !slices.Contains(paths, linked) {
		t.Fatalf("defaultVectorSearchPaths() = %q, want it to include a linked Vector %q", paths, linked)
	}

	lastKeg, firstLinked := -1, len(paths)
	for i, path := range paths {
		switch {
		case strings.Contains(path, filepath.Join("opt", TapVectorFormula)):
			lastKeg = i
		case path != PackagedVectorPath && strings.HasSuffix(path, filepath.Join("bin", "vector")):
			firstLinked = min(firstLinked, i)
		}
	}
	if lastKeg > firstLinked {
		t.Errorf("defaultVectorSearchPaths() = %q, want every beacon-vector keg before every linked Vector; "+
			"interleaving lets an old linked Vector in one prefix mask the pinned keg in the next", paths)
	}
}

// TestHomebrewPrefixesDeduplicates covers HOMEBREW_PREFIX being set to the platform default,
// which would otherwise search the same prefix twice.
func TestHomebrewPrefixesDeduplicates(t *testing.T) {
	prefixes := homebrewPrefixes()
	if len(prefixes) == 0 {
		t.Skip("no Homebrew prefixes on this platform")
	}
	t.Setenv("HOMEBREW_PREFIX", prefixes[0])
	got := homebrewPrefixes()
	seen := make(map[string]bool, len(got))
	for _, prefix := range got {
		if seen[prefix] {
			t.Fatalf("homebrewPrefixes() = %q, want no duplicates", got)
		}
		seen[prefix] = true
	}
	if len(got) != len(prefixes) {
		t.Errorf("homebrewPrefixes() = %q, want the same %d prefixes as the unset default %q", got, len(prefixes), prefixes)
	}
}

// An extracted Linux release archive, or Homebrew-on-Linux, puts Vector beside beacon as
// beacon-vector. FindVector has to find it there without PATH or BEACON_VECTOR_BIN, or
// forwarding from a tarball install asks the user to install a Vector they already have.
func TestFindVectorFindsTheArchiveCopyBesideTheCLI(t *testing.T) {
	isolateVectorDiscovery(t)
	vectorSearchPaths = defaultVectorSearchPaths
	cliDir := t.TempDir()
	sibling := filepath.Join(cliDir, ArchiveVectorName)
	if err := os.Rename(fakeVector(t, "0.58.0", 0), sibling); err != nil {
		t.Fatal(err)
	}
	oldExe := currentExecutable
	currentExecutable = func() (string, error) { return filepath.Join(cliDir, "beacon"), nil }
	t.Cleanup(func() { currentExecutable = oldExe })

	got, err := FindVector("")
	if err != nil || got.Path != sibling || got.Version != "0.58.0" {
		t.Fatalf("FindVector() = %+v, %v; want %s", got, err, sibling)
	}
}

func TestVectorNotFoundMessageNamesWhereVectorComesFrom(t *testing.T) {
	cases := map[string][]string{
		"darwin":  {"brew install asymptote-labs/tap/" + TapVectorFormula, VectorBinEnv},
		"linux":   {PackagedVectorPath, ArchiveVectorName, "https://vector.dev", VectorBinEnv},
		"windows": {WindowsVectorName, `%ProgramFiles%\Beacon\bin`, "https://vector.dev", VectorBinEnv},
	}
	for goos, want := range cases {
		msg := vectorNotFoundMessage(goos)
		for _, part := range want {
			if !strings.Contains(msg, part) {
				t.Errorf("%s: %q does not mention %q", goos, msg, part)
			}
		}
	}
	if strings.Contains(vectorNotFoundMessage("linux"), "brew install") {
		t.Error("the Linux message should not send people to a macOS install command")
	}
}

// The MSI installs vector.exe beside beacon.exe. A beacon.exe run from elsewhere still finds the
// package's copy, and the package directory is not listed twice when that is where beacon.exe is.
func TestWindowsVectorSearchPathsFindTheMSICopy(t *testing.T) {
	programFiles := t.TempDir()
	t.Setenv("ProgramFiles", programFiles)
	packaged := filepath.Join(programFiles, "Beacon", "bin", WindowsVectorName)
	oldExe := currentExecutable
	t.Cleanup(func() { currentExecutable = oldExe })

	elsewhere := filepath.Join(t.TempDir(), "beacon.exe")
	currentExecutable = func() (string, error) { return elsewhere, nil }
	want := []string{filepath.Join(filepath.Dir(elsewhere), WindowsVectorName), packaged}
	if got := windowsVectorSearchPaths(); !slices.Equal(got, want) {
		t.Fatalf("beacon.exe outside the package: got %v, want %v", got, want)
	}

	currentExecutable = func() (string, error) { return filepath.Join(filepath.Dir(packaged), "beacon.exe"), nil }
	if got := windowsVectorSearchPaths(); !slices.Equal(got, []string{packaged}) {
		t.Fatalf("beacon.exe in the package: got %v, want only %s", got, packaged)
	}
}

// Under Homebrew the running CLI is in a versioned keg, and connect writes the Vector path into the
// forwarder's service unit. The keg path breaks at the next `brew upgrade`, so FindVector has to
// return the <prefix>/bin link instead.
func TestFindVectorReturnsTheHomebrewLinkNotTheKeg(t *testing.T) {
	isolateVectorDiscovery(t)
	vectorSearchPaths = defaultVectorSearchPaths
	prefix := t.TempDir()
	kegBin := filepath.Join(prefix, "Cellar", "beacon", "1.3.20", "bin")
	if err := os.MkdirAll(kegBin, 0o755); err != nil {
		t.Fatal(err)
	}
	keg := filepath.Join(kegBin, ArchiveVectorName)
	if err := os.Rename(fakeVector(t, "0.56.0", 0), keg); err != nil {
		t.Fatal(err)
	}
	link := filepath.Join(prefix, "bin", ArchiveVectorName)
	if err := os.MkdirAll(filepath.Dir(link), 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.Symlink(keg, link); err != nil {
		t.Fatal(err)
	}
	oldExe := currentExecutable
	currentExecutable = func() (string, error) { return filepath.Join(kegBin, "beacon"), nil }
	t.Cleanup(func() { currentExecutable = oldExe })

	got, err := FindVector("")
	if err != nil || got.Path != link {
		t.Fatalf("FindVector() = %+v, %v; want the Homebrew link %s, not the keg", got, err, link)
	}
}