Skip to content

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

30.1 KB
Raw Blame
package lifecycle

import (
	"encoding/json"
	"errors"
	"net"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"sync"
	"testing"

	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/asymptote"
	endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/harness"
	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/selfupdate"
	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"
	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
)

func TestBuildConfigAppliesInstallOptions(t *testing.T) {
	home := t.TempDir()
	testenv.SetHome(t, home)
	logPath := filepath.Join(home, "runtime.jsonl")
	collectorPath := filepath.Join(home, "bin", "otelcol")

	cfg := buildConfig(InstallOptions{
		UserMode:      true,
		LogPath:       logPath,
		Harnesses:     []string{"codex"},
		GRPCPort:      54317,
		HTTPPort:      54318,
		CollectorPath: collectorPath,
		SplunkHEC: &endpointconfig.SplunkHEC{
			Endpoint: "https://splunk.example:8088/services/collector",
			Token:    "hec-token",
			Index:    "beacon",
		},
		FalconHEC: &endpointconfig.FalconHEC{
			Endpoint: "https://cloud.us.humio.com/api/v1/ingest/hec",
			Token:    "ingest-token",
			Index:    "beacon-repo",
		},
	})

	if !cfg.UserMode || cfg.LogPath != logPath {
		t.Fatalf("unexpected mode/log path: %#v", cfg)
	}
	if got := cfg.Harnesses; len(got) != 1 || got[0] != "codex" {
		t.Fatalf("Harnesses = %#v, want codex", got)
	}
	if cfg.Collector.GRPCPort != 54317 || cfg.Collector.HTTPPort != 54318 {
		t.Fatalf("unexpected ports: %#v", cfg.Collector)
	}
	if cfg.Collector.BinaryPath != collectorPath {
		t.Fatalf("BinaryPath = %q, want %q", cfg.Collector.BinaryPath, collectorPath)
	}
	if cfg.Destinations == nil || cfg.Destinations.SplunkHEC == nil || !cfg.Destinations.SplunkHEC.Enabled {
		t.Fatalf("Splunk destination not configured: %#v", cfg.Destinations)
	}
	if got := cfg.Destinations.SplunkHEC.Source; got != endpointconfig.DefaultSplunkSource {
		t.Fatalf("Splunk source = %q, want default", got)
	}
	if cfg.Destinations.FalconHEC == nil || !cfg.Destinations.FalconHEC.Enabled {
		t.Fatalf("Falcon destination not configured: %#v", cfg.Destinations)
	}
	if got := cfg.Destinations.FalconHEC.Sourcetype; got != endpointconfig.DefaultFalconSourcetype {
		t.Fatalf("Falcon sourcetype = %q, want default", got)
	}
}

func TestBuildConfigPreservesAutoUpdateMode(t *testing.T) {
	home := t.TempDir()
	testenv.SetHome(t, home)
	configPath := endpointconfig.ConfigPath(true)
	if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(configPath, []byte(`{"auto_update":{"mode":"check-only"}}`), 0o644); err != nil {
		t.Fatal(err)
	}
	cfg := buildConfig(InstallOptions{UserMode: true})
	if cfg.AutoUpdate == nil || cfg.AutoUpdate.Mode != "check-only" {
		t.Fatalf("AutoUpdate = %#v, want check-only", cfg.AutoUpdate)
	}
}

func TestBuildConfigPreservesExplicitEmptyHarnesses(t *testing.T) {
	cfg := buildConfig(InstallOptions{UserMode: true, Harnesses: []string{}})
	if cfg.Harnesses == nil || len(cfg.Harnesses) != 0 {
		t.Fatalf("Harnesses = %#v, want explicit empty slice", cfg.Harnesses)
	}
	defaultCfg := buildConfig(InstallOptions{UserMode: true})
	if len(defaultCfg.Harnesses) == 0 {
		t.Fatalf("default harnesses should be preserved when Harnesses is nil")
	}
}

func TestSelectRuntimeLogWarnsWhenSystemCollectorConflictsWithUserMode(t *testing.T) {
	userLog := filepath.Join(t.TempDir(), "user-runtime.jsonl")
	systemLog := filepath.Join(t.TempDir(), "system-runtime.jsonl")
	source := RuntimeLogSource{
		RequestedUserMode: true,
		EffectiveUserMode: true,
		RequestedLogPath:  userLog,
		EffectiveLogPath:  userLog,
	}
	systemCfg := endpointconfig.Config{LogPath: systemLog}

	got := selectRuntimeLog(
		source,
		service.Status{Label: service.UserLabel, Loaded: false, Running: false},
		service.Status{Label: service.SystemLabel, Loaded: true, Running: true},
		systemCfg,
	)

	if got.EffectiveUserMode {
		t.Fatal("expected effective system mode")
	}
	if got.EffectiveLogPath != systemLog {
		t.Fatalf("EffectiveLogPath = %q, want %q", got.EffectiveLogPath, systemLog)
	}
	if got.Warning == "" || !strings.Contains(got.Warning, userLog) || !strings.Contains(got.Warning, systemLog) {
		t.Fatalf("Warning = %q, want user/system log paths", got.Warning)
	}
}

func TestSelectRuntimeLogKeepsUserLogWhenUserCollectorIsRunning(t *testing.T) {
	userLog := filepath.Join(t.TempDir(), "user-runtime.jsonl")
	systemLog := filepath.Join(t.TempDir(), "system-runtime.jsonl")
	source := RuntimeLogSource{
		RequestedUserMode: true,
		EffectiveUserMode: true,
		RequestedLogPath:  userLog,
		EffectiveLogPath:  userLog,
	}
	systemCfg := endpointconfig.Config{LogPath: systemLog}

	got := selectRuntimeLog(
		source,
		service.Status{Label: service.UserLabel, Loaded: true, Running: true},
		service.Status{Label: service.SystemLabel, Loaded: true, Running: true},
		systemCfg,
	)

	if !got.EffectiveUserMode {
		t.Fatal("expected effective user mode")
	}
	if got.EffectiveLogPath != userLog {
		t.Fatalf("EffectiveLogPath = %q, want %q", got.EffectiveLogPath, userLog)
	}
	if got.Warning != "" {
		t.Fatalf("Warning = %q, want empty", got.Warning)
	}
}

// Each refusal names what does work instead: the launch environment, with this install's HTTP
// port, for the MDM-managed runtimes, and the hooks command for the hook-managed ones. The generic
// "unsupported harness" is only for names Beacon does not know, since it reads as "not supported
// at all".
func TestConfigureHarnessesRejectsRuntimesItCannotConfigure(t *testing.T) {
	for name, want := range map[string][]string{
		"unknown":   {"unsupported harness"},
		"factory":   {"Factory Droid telemetry is MDM-managed", "54318"},
		"copilot":   {"Copilot CLI telemetry is MDM-managed", "54318"},
		"opencode":  {"endpoint hooks install --harness opencode"},
		"cline":     {"endpoint hooks install --harness cline"},
		"qwen":      {"endpoint hooks install --harness qwen"},
		"qwen_code": {"endpoint hooks install --harness qwen"},
	} {
		cfg := endpointconfig.Config{Harnesses: []string{name}, Collector: endpointconfig.Collector{GRPCPort: 54317, HTTPPort: 54318}}
		_, err := configureHarnesses(cfg)
		if err == nil {
			t.Fatalf("configureHarnesses(%q) succeeded, want a refusal", name)
		}
		for _, w := range want {
			if !strings.Contains(err.Error(), w) {
				t.Fatalf("configureHarnesses(%q) error = %v, want it to contain %q", name, err, w)
			}
		}
	}
}

// Claude Code and Gemini CLI export over gRPC, VS Code Copilot over HTTP: each runtime's settings
// must point at the collector port it speaks.
func TestConfigureHarnessesPointsEachRuntimeAtItsOTLPPort(t *testing.T) {
	home := t.TempDir()
	testenv.SetHome(t, home)
	vscodeSettings, err := harness.VSCodeUserSettingsPath()
	if err != nil {
		t.Fatalf("VSCodeUserSettingsPath returned error: %v", err)
	}
	for _, tc := range []struct {
		harness, path string
		want          []string
	}{
		{"claude", filepath.Join(home, ".claude", "settings.json"), []string{`"CLAUDE_CODE_ENABLE_TELEMETRY": "1"`, `"OTEL_EXPORTER_OTLP_ENDPOINT": "http://127.0.0.1:54317"`}},
		{"gemini", filepath.Join(home, ".gemini", "settings.json"), []string{`"otlpEndpoint": "http://127.0.0.1:54317"`, `"logPrompts": true`}},
		{"vscode", vscodeSettings, []string{`"github.copilot.chat.otel.otlpEndpoint": "http://127.0.0.1:54318"`, `"github.copilot.chat.otel.captureContent": false`}},
	} {
		cfg := endpointconfig.Config{UserMode: true, Harnesses: []string{tc.harness}, Collector: endpointconfig.Collector{GRPCPort: 54317, HTTPPort: 54318}}
		paths, err := configureHarnesses(cfg)
		if err != nil {
			t.Fatalf("configureHarnesses(%q) returned error: %v", tc.harness, err)
		}
		if len(paths) != 1 || paths[0] != tc.path {
			t.Fatalf("configureHarnesses(%q) paths = %#v, want %q", tc.harness, paths, tc.path)
		}
		data, err := os.ReadFile(tc.path)
		if err != nil {
			t.Fatal(err)
		}
		for _, want := range tc.want {
			if !strings.Contains(string(data), want) {
				t.Fatalf("%s settings missing %s:\n%s", tc.harness, want, data)
			}
		}
	}
}

func TestAutoUpdateModeFromConfigFileIgnoresDestinationValidation(t *testing.T) {
	path := filepath.Join(t.TempDir(), "config.json")
	if err := os.WriteFile(path, []byte(`{
  "user_mode": false,
  "log_path": "/var/log/beacon-agent/runtime.jsonl",
  "collector": {"grpc_port":4317,"http_port":4318},
  "harnesses": ["claude"],
  "destinations": {"splunk_hec": {"endpoint": "https://splunk.example"}},
  "auto_update": {"mode": "auto"}
}`), 0o600); err != nil {
		t.Fatal(err)
	}
	mode, err := autoUpdateModeFromConfigFile(path)
	if err != nil {
		t.Fatalf("autoUpdateModeFromConfigFile: %v", err)
	}
	if mode != "auto" {
		t.Fatalf("mode = %q, want auto", mode)
	}
	if err := setAutoUpdateModeInConfigFile(path, "check-only"); err != nil {
		t.Fatalf("setAutoUpdateModeInConfigFile: %v", err)
	}
	if info, err := os.Stat(path); err != nil {
		t.Fatal(err)
	} else if got := info.Mode().Perm(); testenv.HasPOSIXFileModes() && got != 0o600 {
		t.Fatalf("permissions = %v, want 0600", got)
	}
	data, err := os.ReadFile(path)
	if err != nil {
		t.Fatal(err)
	}
	var raw map[string]json.RawMessage
	if err := json.Unmarshal(data, &raw); err != nil {
		t.Fatal(err)
	}
	if _, ok := raw["destinations"]; !ok {
		t.Fatalf("destinations were not preserved: %s", data)
	}
	mode, err = autoUpdateModeFromConfigFile(path)
	if err != nil {
		t.Fatal(err)
	}
	if mode != "check-only" {
		t.Fatalf("mode after set = %q, want check-only", mode)
	}
}

func TestReconcileUpdaterSkipsNonPackageInstalls(t *testing.T) {
	oldDetect := detectUpdaterInstall
	t.Cleanup(func() { detectUpdaterInstall = oldDetect })
	detectUpdaterInstall = func() selfupdate.Install {
		return selfupdate.Install{Kind: selfupdate.InstallHomebrew, BinaryPath: "/opt/homebrew/bin/beacon"}
	}
	if err := reconcileUpdaterFromConfig(filepath.Join(t.TempDir(), "runtime.jsonl")); err != nil {
		t.Fatalf("reconcileUpdaterFromConfig should ignore non-package install, got %v", err)
	}
}

func TestDiscoverAndRestoreBackups(t *testing.T) {
	dir := t.TempDir()
	target := filepath.Join(dir, "settings.json")
	backup := target + ".beacon.20260512T120000Z.bak"
	if err := os.WriteFile(backup, []byte("restored"), 0600); err != nil {
		t.Fatalf("write backup: %v", err)
	}

	backups := discoverBackups([]string{target})
	if len(backups) != 1 || backups[0] != backup {
		t.Fatalf("discoverBackups = %#v, want %q", backups, backup)
	}
	restoreBackups(backups)
	data, err := os.ReadFile(target)
	if err != nil {
		t.Fatalf("read restored target: %v", err)
	}
	if string(data) != "restored" {
		t.Fatalf("restored target = %q", string(data))
	}
}

func TestRollbackRestoresBackupsAndRemovesFiles(t *testing.T) {
	dir := t.TempDir()
	target := filepath.Join(dir, "settings.json")
	backup := target + ".beacon.bak"
	created := filepath.Join(dir, "created.txt")
	if err := os.WriteFile(backup, []byte("original"), 0600); err != nil {
		t.Fatalf("write backup: %v", err)
	}
	if err := os.WriteFile(created, []byte("created"), 0600); err != nil {
		t.Fatalf("write created file: %v", err)
	}

	rollback(Manifest{Files: []string{created}, Backups: []string{backup}})

	if _, err := os.Stat(created); !os.IsNotExist(err) {
		t.Fatalf("created file still exists or unexpected error: %v", err)
	}
	data, err := os.ReadFile(target)
	if err != nil {
		t.Fatalf("read restored target: %v", err)
	}
	if string(data) != "original" {
		t.Fatalf("restored target = %q", string(data))
	}
}

func TestPreflightRejectsPortInUse(t *testing.T) {
	if runtime.GOOS != "darwin" {
		t.Skip("preflight is macOS-only")
	}
	shortTimeouts(t)
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatalf("listen: %v", err)
	}
	defer ln.Close()
	port := ln.Addr().(*net.TCPAddr).Port

	cfg := endpointconfig.Default(true, filepath.Join(t.TempDir(), "runtime.jsonl"))
	cfg.Collector.GRPCPort = port
	cfg.Collector.HTTPPort = freePort(t)

	err = preflight(cfg, true, service.KindAuto)
	if err == nil || !strings.Contains(err.Error(), "OTLP gRPC port") {
		t.Fatalf("preflight error = %v, want gRPC port in use", err)
	}
}

func TestPreflightAllowsPortInUseWhenServiceWillNotStart(t *testing.T) {
	if runtime.GOOS != "darwin" {
		t.Skip("preflight is macOS-only")
	}
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatalf("listen: %v", err)
	}
	defer ln.Close()
	port := ln.Addr().(*net.TCPAddr).Port

	cfg := endpointconfig.Default(true, filepath.Join(t.TempDir(), "runtime.jsonl"))
	cfg.Collector.GRPCPort = port
	cfg.Collector.HTTPPort = freePort(t)

	if err := preflight(cfg, false, service.KindAuto); err != nil {
		t.Fatalf("preflight returned error for no-start install: %v", err)
	}
}

func TestUninstallFallbackRemovesKnownFiles(t *testing.T) {
	if runtime.GOOS != "darwin" {
		t.Skip("launchd paths are macOS-only")
	}
	home := t.TempDir()
	testenv.SetHome(t, home)
	logPath := filepath.Join(home, ".beacon", "endpoint", "logs", "runtime.jsonl")
	cfg := endpointconfig.Default(true, logPath)
	for _, path := range []string{endpointconfig.ConfigPath(true), endpointconfig.OTLPForwardSecretsPath(true), cfg.Collector.ConfigPath, logPath} {
		if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
			t.Fatalf("mkdir %s: %v", path, err)
		}
		if err := os.WriteFile(path, []byte("data"), 0600); err != nil {
			t.Fatalf("write %s: %v", path, err)
		}
	}

	if err := Uninstall(UninstallOptions{UserMode: true, LogPath: logPath}); err != nil {
		t.Fatalf("Uninstall returned error: %v", err)
	}
	for _, path := range []string{endpointconfig.ConfigPath(true), endpointconfig.OTLPForwardSecretsPath(true), cfg.Collector.ConfigPath, logPath} {
		if _, err := os.Stat(path); !os.IsNotExist(err) {
			t.Fatalf("%s still exists or unexpected error: %v", path, err)
		}
	}
}

func TestInstallUserModeWithoutStartingService(t *testing.T) {
	if runtime.GOOS != "darwin" {
		t.Skip("install preflight is macOS-only")
	}
	home := t.TempDir()
	testenv.SetHome(t, home)
	collectorPath := filepath.Join(home, "bin", "beacon-otelcol")
	if err := os.MkdirAll(filepath.Dir(collectorPath), 0755); err != nil {
		t.Fatalf("mkdir fake collector dir: %v", err)
	}
	if err := os.WriteFile(collectorPath, []byte("#!/bin/sh\n"), 0755); err != nil {
		t.Fatalf("write fake collector: %v", err)
	}
	logPath := filepath.Join(home, ".beacon", "endpoint", "logs", "runtime.jsonl")

	result, err := Install(InstallOptions{
		UserMode:      true,
		LogPath:       logPath,
		Harnesses:     []string{},
		GRPCPort:      freePort(t),
		HTTPPort:      freePort(t),
		CollectorPath: collectorPath,
		StartService:  false,
	})
	if err != nil {
		t.Fatalf("Install returned error: %v", err)
	}
	for _, path := range []string{result.ConfigPath, result.CollectorConfigPath, result.PlistPath, result.ManifestPath, result.LogPath} {
		if _, err := os.Stat(path); err != nil {
			t.Fatalf("expected install artifact %s: %v", path, err)
		}
	}
	manifest, err := ReadManifest(true)
	if err != nil {
		t.Fatalf("ReadManifest returned error: %v", err)
	}
	if len(manifest.Files) != 3 {
		t.Fatalf("manifest files = %#v, want collector config, plist, config", manifest.Files)
	}
	if len(result.HarnessConfigPaths) != 0 {
		t.Fatalf("unexpected harness config paths: %#v", result.HarnessConfigPaths)
	}
	// Linger is only ever attempted as part of starting the service, so a --no-start install has
	// not learned anything about logout persistence. Reporting it as applicable-and-off would put
	// a logout warning on an install that never started a collector to lose.
	if result.LingerApplicable || result.LingerEnabled || result.LingerDetail != "" || result.LingerRemediation != "" {
		t.Errorf("a --no-start install should report no linger outcome, got %+v", result)
	}
}

// Upgrades re-run install. The managed_ingest block belongs to connect/disconnect, so a
// re-install must carry it over instead of silently disconnecting the machine on paper.
func TestInstallPreservesManagedIngestBlock(t *testing.T) {
	if runtime.GOOS != "darwin" {
		t.Skip("install preflight is macOS-only")
	}
	home := t.TempDir()
	testenv.SetHome(t, home)
	collectorPath := filepath.Join(home, "bin", "beacon-otelcol")
	if err := os.MkdirAll(filepath.Dir(collectorPath), 0755); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(collectorPath, []byte("#!/bin/sh\n"), 0755); err != nil {
		t.Fatal(err)
	}
	logPath := filepath.Join(home, ".beacon", "endpoint", "logs", "runtime.jsonl")
	opts := InstallOptions{UserMode: true, LogPath: logPath, Harnesses: []string{}, GRPCPort: freePort(t), HTTPPort: freePort(t), CollectorPath: collectorPath, StartService: false}
	if _, err := Install(opts); err != nil {
		t.Fatalf("first install: %v", err)
	}
	cfg, err := endpointconfig.Load(true)
	if err != nil {
		t.Fatal(err)
	}
	if cfg.ManagedIngest != nil {
		t.Fatalf("a fresh install must not invent a managed_ingest block: %+v", cfg.ManagedIngest)
	}
	managed := &endpointconfig.ManagedIngest{Enabled: true, IngestURL: "https://ingest.example", DeviceID: "dev-1", OrganizationID: "org-1"}
	cfg.ManagedIngest = managed
	if _, err := endpointconfig.Save(cfg); err != nil {
		t.Fatal(err)
	}

	if _, err := Install(opts); err != nil {
		t.Fatalf("re-install: %v", err)
	}
	after, err := endpointconfig.Load(true)
	if err != nil {
		t.Fatal(err)
	}
	if after.ManagedIngest == nil || *after.ManagedIngest != *managed {
		t.Fatalf("re-install dropped or changed managed_ingest: %+v", after.ManagedIngest)
	}
}

func TestInstallFailsBeforeWritingArtifactsWhenCollectorMissing(t *testing.T) {
	if runtime.GOOS != "darwin" {
		t.Skip("install preflight is macOS-only")
	}
	home := t.TempDir()
	testenv.SetHome(t, home)
	logPath := filepath.Join(home, ".beacon", "endpoint", "logs", "runtime.jsonl")
	missingCollector := filepath.Join(home, "bin", "beacon-otelcol")

	_, err := Install(InstallOptions{
		UserMode:      true,
		LogPath:       logPath,
		Harnesses:     []string{},
		GRPCPort:      freePort(t),
		HTTPPort:      freePort(t),
		CollectorPath: missingCollector,
		StartService:  false,
	})
	if err == nil || !strings.Contains(err.Error(), "collector binary") || !strings.Contains(err.Error(), "not usable") {
		t.Fatalf("Install error = %v, want missing collector error", err)
	}
	for _, path := range []string{endpointconfig.ConfigPath(true), logPath} {
		if _, statErr := os.Stat(path); !os.IsNotExist(statErr) {
			t.Fatalf("%s exists or unexpected error after failed install: %v", path, statErr)
		}
	}
}

func TestInstallRollsBackArtifactsWhenFinalEventFails(t *testing.T) {
	if runtime.GOOS != "darwin" {
		t.Skip("install preflight is macOS-only")
	}
	home := t.TempDir()
	testenv.SetHome(t, home)
	collectorPath := filepath.Join(home, "bin", "beacon-otelcol")
	if err := os.MkdirAll(filepath.Dir(collectorPath), 0755); err != nil {
		t.Fatalf("mkdir fake collector dir: %v", err)
	}
	if err := os.WriteFile(collectorPath, []byte("#!/bin/sh\n"), 0755); err != nil {
		t.Fatalf("write fake collector: %v", err)
	}
	oldAppend := appendInstallEvent
	appendInstallEvent = func(event schema.Event, opts writer.Options) (string, error) {
		return "", errors.New("append failed")
	}
	t.Cleanup(func() {
		appendInstallEvent = oldAppend
	})
	logPath := filepath.Join(home, ".beacon", "endpoint", "logs", "runtime.jsonl")

	_, err := Install(InstallOptions{
		UserMode:      true,
		LogPath:       logPath,
		Harnesses:     []string{},
		GRPCPort:      freePort(t),
		HTTPPort:      freePort(t),
		CollectorPath: collectorPath,
		StartService:  false,
	})
	if err == nil || !strings.Contains(err.Error(), "append failed") {
		t.Fatalf("Install error = %v, want append failure", err)
	}
	cfg := endpointconfig.Default(true, logPath)
	for _, path := range []string{endpointconfig.ConfigPath(true), cfg.Collector.ConfigPath, manifestPath(true)} {
		if _, statErr := os.Stat(path); !os.IsNotExist(statErr) {
			t.Fatalf("%s exists or unexpected error after rollback: %v", path, statErr)
		}
	}
}

func TestRepairPreservesExistingConfigWhenReinstallFails(t *testing.T) {
	if runtime.GOOS != "darwin" {
		t.Skip("install preflight is macOS-only")
	}
	home := t.TempDir()
	testenv.SetHome(t, home)
	logPath := filepath.Join(home, ".beacon", "endpoint", "logs", "runtime.jsonl")
	configPath := endpointconfig.ConfigPath(true)
	if err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {
		t.Fatalf("mkdir config dir: %v", err)
	}
	const originalConfig = `{"user_mode":true,"log_path":"original","collector":{"config_path":"original","grpc_port":4317,"http_port":4318}}`
	if err := os.WriteFile(configPath, []byte(originalConfig), 0600); err != nil {
		t.Fatalf("write original config: %v", err)
	}
	collectorPath := filepath.Join(home, "bin", "beacon-otelcol")
	if err := os.MkdirAll(filepath.Dir(collectorPath), 0755); err != nil {
		t.Fatalf("mkdir fake collector dir: %v", err)
	}
	if err := os.WriteFile(collectorPath, []byte("#!/bin/sh\n"), 0755); err != nil {
		t.Fatalf("write fake collector: %v", err)
	}
	oldAppend := appendInstallEvent
	appendInstallEvent = func(event schema.Event, opts writer.Options) (string, error) {
		return "", errors.New("append failed")
	}
	t.Cleanup(func() {
		appendInstallEvent = oldAppend
	})

	_, err := Repair(InstallOptions{
		UserMode:      true,
		LogPath:       logPath,
		Harnesses:     []string{},
		GRPCPort:      freePort(t),
		HTTPPort:      freePort(t),
		CollectorPath: collectorPath,
		StartService:  false,
	})
	if err == nil {
		t.Fatal("Repair returned nil, want append failure")
	}
	data, readErr := os.ReadFile(configPath)
	if readErr != nil {
		t.Fatalf("read restored config: %v", readErr)
	}
	if string(data) != originalConfig {
		t.Fatalf("config was not restored: %s", string(data))
	}
}

// Repair tears the endpoint down before it reinstalls, and a failed reinstall restores only the
// endpoint config. A collector the reinstall would refuse (an older beacon-otelcol, as sudo finds
// Homebrew's on a Mac that also has the package) left the endpoint with no collector unit or
// config, so repair refuses it before the teardown.
func TestRepairRefusesAnOlderCollectorBeforeTearingDown(t *testing.T) {
	if runtime.GOOS != "darwin" {
		t.Skip("install preflight is macOS-only")
	}
	testenv.RequirePOSIXExecutableFixtures(t)
	home := t.TempDir()
	testenv.SetHome(t, home)
	logPath := filepath.Join(home, ".beacon", "endpoint", "logs", "runtime.jsonl")
	bin := filepath.Join(home, "bin")
	if err := os.MkdirAll(bin, 0755); err != nil {
		t.Fatal(err)
	}
	current := filepath.Join(bin, "beacon-otelcol")
	if err := os.WriteFile(current, []byte("#!/bin/sh\n"), 0755); err != nil {
		t.Fatal(err)
	}
	older := filepath.Join(bin, "beacon-otelcol-older")
	if err := os.WriteFile(older, []byte("#!/bin/sh\n[ \"$1\" = components ] && printf 'processors:\\n  - name: batch\\n'\n"), 0755); err != nil {
		t.Fatal(err)
	}
	opts := InstallOptions{
		UserMode:      true,
		LogPath:       logPath,
		Harnesses:     []string{},
		GRPCPort:      freePort(t),
		HTTPPort:      freePort(t),
		CollectorPath: current,
		StartService:  false,
	}
	if _, err := Install(opts); err != nil {
		t.Fatalf("Install: %v", err)
	}
	cfg := endpointconfig.Default(true, logPath)
	installed := []string{endpointconfig.ConfigPath(true), cfg.Collector.ConfigPath, manifestPath(true)}
	for _, path := range installed {
		if _, err := os.Stat(path); err != nil {
			t.Fatalf("install did not write %s: %v", path, err)
		}
	}

	opts.CollectorPath = older
	if _, err := Repair(opts); err == nil || !strings.Contains(err.Error(), "older than this beacon CLI") {
		t.Fatalf("Repair error = %v, want the older collector refused", err)
	}
	for _, path := range installed {
		if _, err := os.Stat(path); err != nil {
			t.Fatalf("a refused repair removed %s: %v", path, err)
		}
	}
}

var (
	freePortsMu     sync.Mutex
	freePortsIssued = map[int]bool{}
)

// freePort returns a port that was free when asked and that no earlier call
// in this test binary returned. The listener is closed before returning, so
// the kernel can hand the same port out again; without the record, two ports
// of one install (say the health port and an OTLP port) could collide.
func freePort(t *testing.T) int {
	t.Helper()
	freePortsMu.Lock()
	defer freePortsMu.Unlock()
	for attempt := 0; attempt < 100; attempt++ {
		ln, err := net.Listen("tcp", "127.0.0.1:0")
		if err != nil {
			t.Fatalf("listen for free port: %v", err)
		}
		port := ln.Addr().(*net.TCPAddr).Port
		ln.Close()
		if !freePortsIssued[port] {
			freePortsIssued[port] = true
			return port
		}
	}
	t.Fatal("no unused free port after 100 attempts")
	return 0
}

func TestLoadOrDefaultFallsBackToDefaultThenLoadsSavedConfig(t *testing.T) {
	home := t.TempDir()
	testenv.SetHome(t, home)
	logPath := filepath.Join(home, "runtime.jsonl")

	// No config saved yet: returns a default with the requested log path.
	got := loadOrDefault(true, logPath)
	if got.LogPath != logPath {
		t.Fatalf("default LogPath = %q, want %q", got.LogPath, logPath)
	}
	if !got.UserMode {
		t.Fatal("default config should preserve user mode")
	}

	// Persist a config and confirm it is loaded back.
	saved := endpointconfig.Default(true, filepath.Join(home, "saved.jsonl"))
	if _, err := endpointconfig.Save(saved); err != nil {
		t.Fatalf("Save returned error: %v", err)
	}
	loaded := loadOrDefault(true, "")
	if loaded.LogPath != saved.LogPath {
		t.Fatalf("loaded LogPath = %q, want %q", loaded.LogPath, saved.LogPath)
	}
	// An explicit log path overrides the saved value.
	overridden := loadOrDefault(true, logPath)
	if overridden.LogPath != logPath {
		t.Fatalf("override LogPath = %q, want %q", overridden.LogPath, logPath)
	}
}

func TestInstallRollbackTracksAndRestoresFiles(t *testing.T) {
	dir := t.TempDir()
	existing := filepath.Join(dir, "existing.json")
	if err := os.WriteFile(existing, []byte("before"), 0640); err != nil {
		t.Fatalf("write existing fixture: %v", err)
	}
	created := filepath.Join(dir, "created.json")

	rollback := newInstallRollback(service.Manager{UserMode: true})
	rollback.Track(existing)
	rollback.Track(created)
	rollback.Track("")       // ignored
	rollback.Track(existing) // de-duplicated

	if err := os.WriteFile(existing, []byte("after"), 0640); err != nil {
		t.Fatalf("mutate existing: %v", err)
	}
	if err := os.WriteFile(created, []byte("new"), 0640); err != nil {
		t.Fatalf("write created: %v", err)
	}

	rollback.Rollback(Manifest{})

	data, err := os.ReadFile(existing)
	if err != nil {
		t.Fatalf("read restored existing: %v", err)
	}
	if string(data) != "before" {
		t.Fatalf("existing file not restored to original: %q", string(data))
	}
	if _, err := os.Stat(created); !os.IsNotExist(err) {
		t.Fatalf("newly created file should be removed on rollback, stat err = %v", err)
	}
}

func TestDestinationStatusAndInstallDestinationReportEnabledHEC(t *testing.T) {
	cfg := endpointconfig.Config{
		Destinations: &endpointconfig.Destinations{
			SplunkHEC: &endpointconfig.SplunkHEC{
				Enabled:    true,
				Endpoint:   "https://splunk.example/services/collector",
				Index:      "main",
				Source:     "beacon",
				Sourcetype: "beacon:endpoint",
			},
			FalconHEC: &endpointconfig.FalconHEC{
				Enabled:  true,
				Endpoint: "https://falcon.example/services/collector",
			},
		},
	}

	status := destinationStatus(cfg)
	if !status.SplunkHEC.Configured || status.SplunkHEC.Endpoint != "https://splunk.example/services/collector" {
		t.Fatalf("Splunk destination status not reported: %#v", status.SplunkHEC)
	}
	if !status.FalconHEC.Configured {
		t.Fatalf("Falcon destination status not reported: %#v", status.FalconHEC)
	}

	info := installDestination(cfg)
	if !strings.Contains(info.Type, "splunk_hec") || !strings.Contains(info.Type, "falcon_hec") {
		t.Fatalf("installDestination type missing HEC destinations: %q", info.Type)
	}
	if !strings.Contains(info.Mode, "hec") {
		t.Fatalf("installDestination mode missing hec: %q", info.Mode)
	}

	// With no destinations configured, status is empty and only local JSONL is reported.
	empty := destinationStatus(endpointconfig.Config{})
	if empty.SplunkHEC.Configured || empty.FalconHEC.Configured {
		t.Fatalf("empty config should report no destinations: %#v", empty)
	}
	localOnly := installDestination(endpointconfig.Config{})
	if localOnly.Type != "local_jsonl" {
		t.Fatalf("installDestination with no HEC = %q, want local_jsonl", localOnly.Type)
	}
}

// `status --user` on a machine whose system collector holds the OTLP ports switches the
// runtime-log view to the system install, but the managed-ingest connection it reports must
// still be the user's: each mode has its own enrollment, and the system one is root-only.
func TestStatusReportsManagedIngestForRequestedMode(t *testing.T) {
	home := t.TempDir()
	testenv.SetHome(t, home)
	if err := asymptote.SaveEnrollment(true, asymptote.Enrollment{InstallID: "i", IngestURL: "https://ingest.example", DeviceID: "user-device", OrganizationID: "org", OrganizationName: "Org"}); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(asymptote.VectorConfigPath(true), []byte("# rendered"), 0o644); err != nil {
		t.Fatal(err)
	}
	systemCfg := endpointconfig.Default(false, filepath.Join(home, "system", "runtime.jsonl"))
	runtimeLog := RuntimeLogSource{RequestedUserMode: true, EffectiveUserMode: false, EffectiveLogPath: systemCfg.LogPath}

	status := buildStatus(true, systemCfg, runtimeLog, asymptote.StatusOptions{SkipCredentialCheck: true})
	if !status.ManagedIngest.Enabled || status.ManagedIngest.DeviceID != "user-device" {
		t.Fatalf("status --user must report the user-mode connection, got %+v", status.ManagedIngest)
	}
	if status.LogPath != systemCfg.LogPath {
		t.Fatalf("runtime log view should still follow the effective (system) config, got %q", status.LogPath)
	}
}

func TestGetStatusAndResolveRuntimeLogReportRequestedConfig(t *testing.T) {
	home := t.TempDir()
	testenv.SetHome(t, home)
	logPath := filepath.Join(home, "runtime.jsonl")

	source := ResolveRuntimeLog(true, logPath)
	if source.EffectiveLogPath != logPath || source.Reason != "explicit runtime log path" {
		t.Fatalf("ResolveRuntimeLog explicit path = %#v", source)
	}

	status := GetStatus(true, logPath)
	if status.LogPath != logPath {
		t.Fatalf("GetStatus LogPath = %q, want %q", status.LogPath, logPath)
	}
	if status.ConfigPath != endpointconfig.ConfigPath(true) {
		t.Fatalf("GetStatus ConfigPath = %q, want %q", status.ConfigPath, endpointconfig.ConfigPath(true))
	}
	if status.Version == "" {
		t.Fatal("GetStatus should populate Version")
	}
}