The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
add robustness improvements
Justin D'Souzaaa7375a869b5
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex e2b45fd8..6969525b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -54,6 +54,15 @@ jobs:test -x packaging/macos/smoke-endpoint.shtest -f collector-builder/builder.yamlsh packaging/macos/test-endpoint-scripts.sh+ - name: Build macOS package skeleton+ run: |+ (cd cli/beacon && go build -o beacon .)+ mkdir -p /tmp/beacon-collector+ printf '#!/bin/sh\nexit 0\n' > /tmp/beacon-collector/beacon-otelcol+ chmod +x /tmp/beacon-collector/beacon-otelcol+ OUT_DIR=/tmp/beacon-pkg BEACON_COLLECTOR=/tmp/beacon-collector/beacon-otelcol packaging/macos/build-pkg.sh+ pkgutil --payload-files /tmp/beacon-pkg/*.pkg | awk '$0 == "./opt/beacon/bin/beacon" { found = 1 } END { exit !found }'+ pkgutil --payload-files /tmp/beacon-pkg/*.pkg | awk '$0 == "./opt/beacon/bin/beacon-otelcol" { found = 1 } END { exit !found }'- name: Endpoint install smoke testrun: sh packaging/macos/smoke-endpoint.shdiff --git a/cli/beacon-hooks/cmd/endpoint_events.go b/cli/beacon-hooks/cmd/endpoint_events.goindex ee7a5fea..b2d8f746 100644--- a/cli/beacon-hooks/cmd/endpoint_events.go+++ b/cli/beacon-hooks/cmd/endpoint_events.go@@ -31,7 +31,9 @@ func emitHookEvent(logger *logging.Logger, action, category, severity, message sif branch := getFirstStr(input, "branch", "git_branch"); branch != "" {fields["branch"] = branch}- logger.EndpointEvent(action, category, severity, message, fields)+ if err := logger.EndpointEvent(action, category, severity, message, fields); err != nil {+ logger.Error("Failed to write endpoint event", "error", err.Error(), "action", action)+ }}func sessionFields(sessionID string, input map[string]interface{}) map[string]interface{} {diff --git a/cli/beacon-hooks/cmd/pre_tool.go b/cli/beacon-hooks/cmd/pre_tool.goindex a46e82a1..288c33f0 100644--- a/cli/beacon-hooks/cmd/pre_tool.go+++ b/cli/beacon-hooks/cmd/pre_tool.go@@ -111,7 +111,9 @@ func emitAntigravityPromptFromTranscript(logger *logging.Logger, input map[strinfields["prompt"] = map[string]interface{}{"text": prompt}}emitHookEvent(logger, "prompt.submitted", "prompt", "info", "Prompt submitted to agent", input, fields)- st.SetPromptEmitted()+ if err := st.SetPromptEmitted(); err != nil {+ logger.Warn("Failed to persist prompt state", "error", err.Error())+ }}func antigravityPromptFromTranscript(input map[string]interface{}, sessionID string) string {diff --git a/cli/beacon-hooks/cmd/prompt_submit.go b/cli/beacon-hooks/cmd/prompt_submit.goindex 39298bf2..3ca170e8 100644--- a/cli/beacon-hooks/cmd/prompt_submit.go+++ b/cli/beacon-hooks/cmd/prompt_submit.go@@ -51,7 +51,9 @@ func runPromptSubmit(cmd *cobra.Command, args []string) {if platformFlag == "antigravity" && sessionID != "" && hasPrompt {st := state.NewSessionState(sessionID, "antigravity")- st.SetPromptEmitted()+ if err := st.SetPromptEmitted(); err != nil {+ logger.Warn("Failed to persist prompt state", "error", err.Error())+ }}outputJSON(noopResponse)diff --git a/cli/beacon-hooks/cmd/session_start.go b/cli/beacon-hooks/cmd/session_start.goindex 3a74528d..76edc621 100644--- a/cli/beacon-hooks/cmd/session_start.go+++ b/cli/beacon-hooks/cmd/session_start.go@@ -56,8 +56,11 @@ func runSessionStart(cmd *cobra.Command, args []string) {// Persist model name so post-tool can include it in evaluationsif model, ok := input["model"].(string); ok && model != "" {st := state.NewSessionState(sessionID, platformFlag)- st.SetModel(model)- logger.Debug("Stored session model", "model", model)+ if err := st.SetModel(model); err != nil {+ logger.Warn("Failed to persist session model", "model", model, "error", err.Error())+ } else {+ logger.Debug("Stored session model", "model", model)+ }}logger.Info("Session initialized", "session_id", sessionID, "platform", platformFlag)diff --git a/cli/beacon-hooks/cmd/stop.go b/cli/beacon-hooks/cmd/stop.goindex 4528dc64..49849485 100644--- a/cli/beacon-hooks/cmd/stop.go+++ b/cli/beacon-hooks/cmd/stop.go@@ -64,8 +64,11 @@ func runStop(cmd *cobra.Command, args []string) {// left over from older hook versions instead of polling a hosted service.pendingEvals := st.GetPendingEvaluations()if len(pendingEvals) > 0 {- st.ClearEvaluations()- logger.Warn("Cleared stale remote evaluations in local-only build", "count", len(pendingEvals))+ if err := st.ClearEvaluations(); err != nil {+ logger.Warn("Failed to clear stale remote evaluations in local-only build", "count", len(pendingEvals), "error", err.Error())+ } else {+ logger.Warn("Cleared stale remote evaluations in local-only build", "count", len(pendingEvals))+ }}elapsed := time.Since(start)diff --git a/cli/beacon-hooks/internal/config/config.go b/cli/beacon-hooks/internal/config/config.goindex d9127005..8880e226 100644--- a/cli/beacon-hooks/internal/config/config.go+++ b/cli/beacon-hooks/internal/config/config.go@@ -2,8 +2,10 @@ package configimport ("encoding/json"+ "fmt""os""path/filepath"+ "strconv""strings")@@ -23,7 +25,8 @@ var (// Log rotationconst (- LogMaxSizeBytes = 10 * 1024 * 1024 // 10 MB+ LogMaxSizeBytes = 10 * 1024 * 1024 // 10 MB+ LogRotateArchives = 5)type ContentRetention string@@ -129,7 +132,7 @@ func EnsureSessionLogDir(platform string) error {return os.MkdirAll(GetSessionLogDir(platform), 0755)}-// RotateLogIfNeededForPlatform clears the platform-specific log file if it exceeds LogMaxSizeBytes+// RotateLogIfNeededForPlatform rotates the platform-specific log file if it exceeds LogMaxSizeBytes.func RotateLogIfNeededForPlatform(platform string) bool {logFile := GetLogFile(platform)info, err := os.Stat(logFile)@@ -138,13 +141,53 @@ func RotateLogIfNeededForPlatform(platform string) bool {}if info.Size() > LogMaxSizeBytes {- os.WriteFile(logFile, []byte{}, 0644)- return true+ return rotateLog(logFile, LogRotateArchives) == nil}return false}+func rotateLog(path string, archives int) error {+ if archives < 1 {+ archives = LogRotateArchives+ }+ if err := removeOverflowArchives(path, archives); err != nil {+ return err+ }+ for i := archives - 1; i >= 1; i-- {+ from := path + fmt.Sprintf(".%d", i)+ to := path + fmt.Sprintf(".%d", i+1)+ if err := os.Rename(from, to); err != nil && !os.IsNotExist(err) {+ return err+ }+ }+ return os.Rename(path, path+".1")+}++func removeOverflowArchives(path string, archives int) error {+ dir := filepath.Dir(path)+ base := filepath.Base(path)+ entries, err := os.ReadDir(dir)+ if err != nil {+ return err+ }+ prefix := base + "."+ for _, entry := range entries {+ suffix, ok := strings.CutPrefix(entry.Name(), prefix)+ if !ok {+ continue+ }+ index, err := strconv.Atoi(suffix)+ if err != nil || index < archives {+ continue+ }+ if err := os.Remove(filepath.Join(dir, entry.Name())); err != nil && !os.IsNotExist(err) {+ return err+ }+ }+ return nil+}+// EnsureStateDir ensures the state directory for the given platform existsfunc EnsureStateDir(platform string) error {return os.MkdirAll(GetStateDir(platform), 0755)diff --git a/cli/beacon-hooks/internal/config/config_test.go b/cli/beacon-hooks/internal/config/config_test.goindex 96e71166..59523df6 100644--- a/cli/beacon-hooks/internal/config/config_test.go+++ b/cli/beacon-hooks/internal/config/config_test.go@@ -175,3 +175,35 @@ func TestContentRetentionModePreservesExplicitMetadata(t *testing.T) {t.Fatalf("ContentRetentionMode() = %q, want %q", got, ContentRetentionMetadata)}}++func TestRotateLogIfNeededForPlatformArchivesExistingLog(t *testing.T) {+ dir := t.TempDir()+ oldCursorDir := CursorDir+ CursorDir = dir+ t.Cleanup(func() {+ CursorDir = oldCursorDir+ })+ logFile := GetLogFile("cursor")+ if err := os.WriteFile(logFile, []byte("old log"), 0644); err != nil {+ t.Fatalf("write hook log: %v", err)+ }+ if err := os.WriteFile(logFile+".1", []byte("older log"), 0644); err != nil {+ t.Fatalf("write hook archive: %v", err)+ }+ if err := os.Truncate(logFile, LogMaxSizeBytes+1); err != nil {+ t.Fatalf("inflate hook log: %v", err)+ }++ if !RotateLogIfNeededForPlatform("cursor") {+ t.Fatal("RotateLogIfNeededForPlatform returned false, want rotation")+ }+ if _, err := os.Stat(logFile); !os.IsNotExist(err) {+ t.Fatalf("active log should be rotated away, stat err=%v", err)+ }+ if info, err := os.Stat(logFile + ".1"); err != nil || info.Size() != LogMaxSizeBytes+1 {+ t.Fatalf(".1 archive info=%v err=%v, want rotated active log", info, err)+ }+ if data, err := os.ReadFile(logFile + ".2"); err != nil || string(data) != "older log" {+ t.Fatalf(".2 archive = %q err=%v, want older log", string(data), err)+ }+}diff --git a/cli/beacon-hooks/internal/logging/endpoint_event_test.go b/cli/beacon-hooks/internal/logging/endpoint_event_test.goindex c84e0268..861caa29 100644--- a/cli/beacon-hooks/internal/logging/endpoint_event_test.go+++ b/cli/beacon-hooks/internal/logging/endpoint_event_test.go@@ -31,7 +31,9 @@ func TestEndpointEventStillWritesStructuredTelemetry(t *testing.T) {t.Setenv("BEACON_ENDPOINT_LOG", logPath)logger := NewLoggerForPlatform("pre-tool", "test")- logger.EndpointEvent("approval.allowed", "approval", "info", "Pre-tool observed", nil)+ if err := logger.EndpointEvent("approval.allowed", "approval", "info", "Pre-tool observed", nil); err != nil {+ t.Fatalf("EndpointEvent returned error: %v", err)+ }if data, err := os.ReadFile(logPath); err != nil || len(data) == 0 {t.Fatalf("expected structured endpoint event, len=%d err=%v", len(data), err)@@ -55,3 +57,17 @@ func TestEndpointEventRotatesRuntimeLog(t *testing.T) {t.Fatalf("expected current log to contain new event, data=%q err=%v", string(current), err)}}++func TestEndpointEventSurfacesWriteFailure(t *testing.T) {+ dir := t.TempDir()+ logPath := filepath.Join(dir, "runtime.jsonl")+ if err := os.Mkdir(logPath, 0755); err != nil {+ t.Fatalf("mkdir log path: %v", err)+ }+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ logger := NewLoggerForPlatform("pre-tool", "test")+ if err := logger.EndpointEvent("approval.allowed", "approval", "info", "Pre-tool observed", nil); err == nil {+ t.Fatal("EndpointEvent returned nil, want write failure")+ }+}diff --git a/cli/beacon-hooks/internal/logging/logging.go b/cli/beacon-hooks/internal/logging/logging.goindex 4725428d..e987331d 100644--- a/cli/beacon-hooks/internal/logging/logging.go+++ b/cli/beacon-hooks/internal/logging/logging.go@@ -101,10 +101,10 @@ func (l *Logger) write(entry map[string]interface{}) {}}-func (l *Logger) EndpointEvent(action, category, severity, message string, fields map[string]interface{}) {+func (l *Logger) EndpointEvent(action, category, severity, message string, fields map[string]interface{}) error {path := endpointLogPath()if path == "" {- return+ return nil}if severity == "" {severity = "info"@@ -128,7 +128,11 @@ func (l *Logger) EndpointEvent(action, category, severity, message string, fieldif raw, ok := event["raw"].(map[string]interface{}); ok {event["raw"] = retentionAwareRaw(raw, retention)}- writeEndpointJSON(path, event)+ if err := writeEndpointJSON(path, event); err != nil {+ fmt.Fprintf(os.Stderr, "logging: failed to write endpoint event to %s: %v\n", path, err)+ return err+ }+ return nil}func (l *Logger) baseEndpointEvent(action, category, severity, message string) map[string]interface{} {@@ -162,13 +166,13 @@ func (l *Logger) baseEndpointEvent(action, category, severity, message string) mreturn event}-func writeEndpointJSON(path string, event map[string]interface{}) {+func writeEndpointJSON(path string, event map[string]interface{}) error {if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {- return+ return err}data, err := json.Marshal(sanitizeEndpointMap(event))if err != nil {- return+ return err}if len(data) > 64*1024 {event["field_truncated"] = true@@ -176,10 +180,10 @@ func writeEndpointJSON(path string, event map[string]interface{}) {event["message"] = truncateEndpoint(fmt.Sprint(event["message"]), 1024)data, err = json.Marshal(sanitizeEndpointMap(event))if err != nil {- return+ return err}}- _ = appendEndpointJSONL(path, append(data, '\n'), defaultEndpointRotateBytes, defaultEndpointRotateArchives)+ return appendEndpointJSONL(path, append(data, '\n'), defaultEndpointRotateBytes, defaultEndpointRotateArchives)}func endpointLogPath() string {diff --git a/cli/beacon-hooks/internal/state/state.go b/cli/beacon-hooks/internal/state/state.goindex e482794d..9278c934 100644--- a/cli/beacon-hooks/internal/state/state.go+++ b/cli/beacon-hooks/internal/state/state.go@@ -63,7 +63,9 @@ func (s *SessionState) loadStateFile() map[string]*SessionData {}func (s *SessionState) saveStateFile(state map[string]*SessionData) error {- config.EnsureStateDir(s.platform)+ if err := config.EnsureStateDir(s.platform); err != nil {+ return err+ }data, err := json.MarshalIndent(state, "", " ")if err != nil {@@ -90,14 +92,14 @@ func (s *SessionState) ensureSession(state map[string]*SessionData) {}// SetModel stores the AI model name for this session-func (s *SessionState) SetModel(model string) {+func (s *SessionState) SetModel(model string) error {stateMutex.Lock()defer stateMutex.Unlock()state := s.loadStateFile()s.ensureSession(state)state[s.sessionID].Model = model- s.saveStateFile(state)+ return s.saveStateFile(state)}// GetModel returns the AI model name for this session@@ -123,32 +125,34 @@ func (s *SessionState) HasPromptEmitted() bool {return false}-func (s *SessionState) SetPromptEmitted() {+func (s *SessionState) SetPromptEmitted() error {stateMutex.Lock()defer stateMutex.Unlock()state := s.loadStateFile()s.ensureSession(state)state[s.sessionID].PromptEmitted = true- s.saveStateFile(state)+ return s.saveStateFile(state)}-func (s *SessionState) MarkPromptEmittedIfNeeded() bool {+func (s *SessionState) MarkPromptEmittedIfNeeded() (bool, error) {stateMutex.Lock()defer stateMutex.Unlock()state := s.loadStateFile()s.ensureSession(state)if state[s.sessionID].PromptEmitted {- return false+ return false, nil}state[s.sessionID].PromptEmitted = true- s.saveStateFile(state)- return true+ if err := s.saveStateFile(state); err != nil {+ return false, err+ }+ return true, nil}// AddEvaluation adds a new pending evaluation-func (s *SessionState) AddEvaluation(evaluationID, filePath string) {+func (s *SessionState) AddEvaluation(evaluationID, filePath string) error {stateMutex.Lock()defer stateMutex.Unlock()@@ -161,7 +165,7 @@ func (s *SessionState) AddEvaluation(evaluationID, filePath string) {CreatedAt: time.Now().UTC().Format(time.RFC3339),})- s.saveStateFile(state)+ return s.saveStateFile(state)}// GetPendingEvaluations returns pending evaluations for this session@@ -177,14 +181,14 @@ func (s *SessionState) GetPendingEvaluations() []Evaluation {}// ClearEvaluations removes all evaluations for this session-func (s *SessionState) ClearEvaluations() {+func (s *SessionState) ClearEvaluations() error {stateMutex.Lock()defer stateMutex.Unlock()state := s.loadStateFile()s.ensureSession(state)state[s.sessionID].Evaluations = []Evaluation{}- s.saveStateFile(state)+ return s.saveStateFile(state)}// GetRepromptCount returns the current re-prompt count@@ -200,7 +204,7 @@ func (s *SessionState) GetRepromptCount() int {}// IncrementRepromptCount increments and returns the re-prompt count-func (s *SessionState) IncrementRepromptCount() int {+func (s *SessionState) IncrementRepromptCount() (int, error) {stateMutex.Lock()defer stateMutex.Unlock()@@ -208,19 +212,21 @@ func (s *SessionState) IncrementRepromptCount() int {s.ensureSession(state)state[s.sessionID].RepromptCount++newCount := state[s.sessionID].RepromptCount- s.saveStateFile(state)- return newCount+ if err := s.saveStateFile(state); err != nil {+ return 0, err+ }+ return newCount, nil}// ResetRepromptCount resets the re-prompt count to 0-func (s *SessionState) ResetRepromptCount() {+func (s *SessionState) ResetRepromptCount() error {stateMutex.Lock()defer stateMutex.Unlock()state := s.loadStateFile()s.ensureSession(state)state[s.sessionID].RepromptCount = 0- s.saveStateFile(state)+ return s.saveStateFile(state)}// CleanupStaleForPlatform removes stale evaluations for the given platformdiff --git a/cli/beacon-hooks/internal/state/state_test.go b/cli/beacon-hooks/internal/state/state_test.goindex b8fc704d..8f70f06d 100644--- a/cli/beacon-hooks/internal/state/state_test.go+++ b/cli/beacon-hooks/internal/state/state_test.go@@ -82,3 +82,21 @@ func TestSessionStateFileLocation(t *testing.T) {t.Errorf("state.json not found at expected path %s: %v", stateFile, err)}}++func TestSessionStateSurfacesSaveFailure(t *testing.T) {+ tmpDir := t.TempDir()+ stateDirPath := filepath.Join(tmpDir, "not-a-dir")+ if err := os.WriteFile(stateDirPath, []byte("file"), 0644); err != nil {+ t.Fatalf("write blocking file: %v", err)+ }+ origCursorDir := config.CursorDir+ config.CursorDir = stateDirPath+ t.Cleanup(func() {+ config.CursorDir = origCursorDir+ })++ st := NewSessionState("test-session", "cursor")+ if err := st.SetModel("gpt-5.5"); err == nil {+ t.Fatal("SetModel returned nil, want save failure")+ }+}diff --git a/cli/beacon/cmd/endpoint.go b/cli/beacon/cmd/endpoint.goindex ca5eb432..89390c1e 100644--- a/cli/beacon/cmd/endpoint.go+++ b/cli/beacon/cmd/endpoint.go@@ -1625,7 +1625,9 @@ func runEndpointDiscover(cmd *cobra.Command, args []string) error {},Message: h.DisplayName + " detected",})- _, _ = writer.AppendEvent(event, writer.Options{Path: cfg.LogPath, UserMode: cfg.UserMode})+ if _, err := writer.AppendEvent(event, writer.Options{Path: cfg.LogPath, UserMode: cfg.UserMode}); err != nil {+ return err+ }}}return nildiff --git a/cli/beacon/internal/endpoint/collector/collector.go b/cli/beacon/internal/endpoint/collector/collector.goindex 23a70163..5cac3e90 100644--- a/cli/beacon/internal/endpoint/collector/collector.go+++ b/cli/beacon/internal/endpoint/collector/collector.go@@ -3,10 +3,12 @@ package collectorimport ("fmt""net"+ "net/http""os""os/exec""path/filepath""strings"+ "time"endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config")@@ -14,6 +16,7 @@ import (const (BinaryName = "beacon-otelcol"PackagedBinaryPath = "/opt/beacon/bin/beacon-otelcol"+ HealthCheckPort = 13133)var (@@ -23,13 +26,14 @@ var ()type Status struct {- BinaryPath string `json:"binary_path,omitempty"`- ConfigPath string `json:"config_path,omitempty"`- GRPCPort int `json:"grpc_port"`- HTTPPort int `json:"http_port"`- GRPCReady bool `json:"grpc_ready"`- HTTPReady bool `json:"http_ready"`- Message string `json:"message,omitempty"`+ BinaryPath string `json:"binary_path,omitempty"`+ ConfigPath string `json:"config_path,omitempty"`+ GRPCPort int `json:"grpc_port"`+ HTTPPort int `json:"http_port"`+ GRPCReady bool `json:"grpc_ready"`+ HTTPReady bool `json:"http_ready"`+ HealthReady bool `json:"health_ready"`+ Message string `json:"message,omitempty"`}func ResolveBinary(configured string) (string, error) {@@ -245,21 +249,41 @@ func falconHECYAML(cfg endpointconfig.Config) string {func CheckStatus(cfg endpointconfig.Config) Status {binary := DiscoverBinary(cfg.Collector.BinaryPath)status := Status{- BinaryPath: binary,- ConfigPath: cfg.Collector.ConfigPath,- GRPCPort: cfg.Collector.GRPCPort,- HTTPPort: cfg.Collector.HTTPPort,- GRPCReady: portOpen(cfg.Collector.GRPCPort),- HTTPReady: portOpen(cfg.Collector.HTTPPort),+ BinaryPath: binary,+ ConfigPath: cfg.Collector.ConfigPath,+ GRPCPort: cfg.Collector.GRPCPort,+ HTTPPort: cfg.Collector.HTTPPort,+ GRPCReady: portOpen(cfg.Collector.GRPCPort),+ HTTPReady: portOpen(cfg.Collector.HTTPPort),+ HealthReady: healthReady(),}if binary == "" {status.Message = "OpenTelemetry Collector binary was not found on PATH"} else if !status.GRPCReady && !status.HTTPReady {status.Message = "Collector ports are not listening"+ } else if !status.HealthReady {+ status.Message = "Collector health check is not ready"}return status}+func WaitUntilReady(cfg endpointconfig.Config, timeout time.Duration) error {+ deadline := time.Now().Add(timeout)+ for {+ status := CheckStatus(cfg)+ if status.GRPCReady && status.HTTPReady && status.HealthReady {+ return nil+ }+ if time.Now().After(deadline) {+ if status.Message != "" {+ return fmt.Errorf("%s", status.Message)+ }+ return fmt.Errorf("collector did not become ready before timeout")+ }+ time.Sleep(250 * time.Millisecond)+ }+}+func PortAvailable(port int) bool {ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))if err != nil {@@ -278,6 +302,16 @@ func portOpen(port int) bool {return true}+func healthReady() bool {+ client := http.Client{Timeout: 500 * time.Millisecond}+ resp, err := client.Get(fmt.Sprintf("http://127.0.0.1:%d/", HealthCheckPort))+ if err != nil {+ return false+ }+ defer resp.Body.Close()+ return resp.StatusCode >= 200 && resp.StatusCode < 300+}+func LaunchAgentPlist(cfg endpointconfig.Config) string {binary := DiscoverBinary(cfg.Collector.BinaryPath)if binary == "" {diff --git a/cli/beacon/internal/endpoint/collector/collector_test.go b/cli/beacon/internal/endpoint/collector/collector_test.goindex fbeef2ec..e265edbb 100644--- a/cli/beacon/internal/endpoint/collector/collector_test.go+++ b/cli/beacon/internal/endpoint/collector/collector_test.go@@ -3,6 +3,7 @@ package collectorimport ("errors""net"+ "net/http""os""os/exec""path/filepath"@@ -303,6 +304,67 @@ func TestPortAvailabilityAndOpenChecks(t *testing.T) {}}+func TestCheckStatusDoesNotTreatOpenOTLPPortsAsHealthy(t *testing.T) {+ if healthReady() {+ t.Skip("collector health check endpoint is already active")+ }+ bin := filepath.Join(t.TempDir(), BinaryName)+ if err := os.WriteFile(bin, []byte("#!/bin/sh\n"), 0755); err != nil {+ t.Fatalf("write fake collector: %v", err)+ }+ grpcLn, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatalf("listen grpc: %v", err)+ }+ defer grpcLn.Close()+ httpLn, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatalf("listen http: %v", err)+ }+ defer httpLn.Close()+ cfg := testConfig(t)+ cfg.Collector.BinaryPath = bin+ cfg.Collector.GRPCPort = grpcLn.Addr().(*net.TCPAddr).Port+ cfg.Collector.HTTPPort = httpLn.Addr().(*net.TCPAddr).Port++ status := CheckStatus(cfg)+ if !status.GRPCReady || !status.HTTPReady {+ t.Fatalf("OTLP ports should appear open: %#v", status)+ }+ if status.HealthReady {+ t.Fatalf("HealthReady = true for unrelated listeners: %#v", status)+ }+ if !strings.Contains(status.Message, "health check") {+ t.Fatalf("Message = %q, want health check warning", status.Message)+ }+}++func TestHealthReadyChecksCollectorHealthEndpoint(t *testing.T) {+ if !PortAvailable(HealthCheckPort) {+ t.Skip("collector health check port is already in use")+ }+ server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusOK)+ })}+ ln, err := net.Listen("tcp", "127.0.0.1:13133")+ if err != nil {+ t.Fatalf("listen health: %v", err)+ }+ done := make(chan struct{})+ go func() {+ _ = server.Serve(ln)+ close(done)+ }()+ t.Cleanup(func() {+ _ = server.Close()+ <-done+ })++ if !healthReady() {+ t.Fatal("healthReady() = false, want true")+ }+}+func TestLaunchAgentPlistUsesFallbackBinaryAndUserLabel(t *testing.T) {cfg := testConfig(t)cfg.UserMode = truediff --git a/cli/beacon/internal/endpoint/diagnostics/diagnostics.go b/cli/beacon/internal/endpoint/diagnostics/diagnostics.goindex 9c580f59..6b850c8b 100644--- a/cli/beacon/internal/endpoint/diagnostics/diagnostics.go+++ b/cli/beacon/internal/endpoint/diagnostics/diagnostics.go@@ -6,6 +6,7 @@ import ("path/filepath""runtime"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/collector"endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service")@@ -25,6 +26,7 @@ func Run(cfg endpointconfig.Config) []Check {checkFile("collector_config", cfg.Collector.ConfigPath, true),checkFile("runtime_log", cfg.LogPath, false),checkLogPermissions(cfg.LogPath),+ checkCollectorHealth(cfg),}if runtime.GOOS == "darwin" {checks = append(checks, checkFile("launchd_plist", launchPlistPath(cfg.UserMode), true))@@ -32,9 +34,21 @@ func Run(cfg endpointconfig.Config) []Check {return checks}+func checkCollectorHealth(cfg endpointconfig.Config) Check {+ status := collector.CheckStatus(cfg)+ if status.HealthReady {+ return Check{Name: "collector_health", Target: fmt.Sprintf("127.0.0.1:%d", collector.HealthCheckPort), Status: "ok", Severity: "info", Message: "collector health check is ready", Evidence: "health_check_ready"}+ }+ message := status.Message+ if message == "" {+ message = "collector health check is not ready"+ }+ return Check{Name: "collector_health", Target: fmt.Sprintf("127.0.0.1:%d", collector.HealthCheckPort), Status: "warn", Severity: "medium", Message: message, Evidence: "health_check_unavailable"}+}+func HasFailures(checks []Check) bool {for _, check := range checks {- if check.Status != "ok" {+ if check.Status == "fail" {return true}}diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.goindex da0e744b..b5023f89 100644--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go@@ -18,6 +18,12 @@ import ("github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version")+var (+ writeCollectorConfig = endpointcollector.WriteConfig+ saveEndpointConfig = endpointconfig.Save+ appendInstallEvent = writer.AppendEvent+)+type InstallOptions struct {UserMode boolLogPath string@@ -94,6 +100,69 @@ type Manifest struct {LogPath string `json:"log_path"`}+type fileSnapshot struct {+ Existed bool+ Data []byte+ Mode os.FileMode+}++type installRollback struct {+ Manager service.Manager+ ServiceLoaded bool+ files []string+ snapshots map[string]fileSnapshot+}++func newInstallRollback(manager service.Manager) *installRollback {+ return &installRollback{+ Manager: manager,+ snapshots: map[string]fileSnapshot{},+ }+}++func (r *installRollback) Track(path string) {+ if r == nil || path == "" {+ return+ }+ if _, ok := r.snapshots[path]; ok {+ return+ }+ snapshot := fileSnapshot{}+ if data, err := os.ReadFile(path); err == nil {+ snapshot.Existed = true+ snapshot.Data = data+ if info, statErr := os.Stat(path); statErr == nil {+ snapshot.Mode = info.Mode().Perm()+ }+ }+ r.snapshots[path] = snapshot+ r.files = append(r.files, path)+}++func (r *installRollback) Rollback(manifest Manifest) {+ if r == nil {+ rollback(manifest)+ return+ }+ if r.ServiceLoaded {+ _ = r.Manager.Unload()+ }+ restoreBackups(manifest.Backups)+ for i := len(r.files) - 1; i >= 0; i-- {+ path := r.files[i]+ snapshot := r.snapshots[path]+ if snapshot.Existed {+ mode := snapshot.Mode+ if mode == 0 {+ mode = 0600+ }+ _ = os.WriteFile(path, snapshot.Data, mode)+ continue+ }+ _ = os.Remove(path)+ }+}+func Install(opts InstallOptions) (InstallResult, error) {cfg := buildConfig(opts)if err := preflight(cfg, opts.StartService); err != nil {@@ -111,38 +180,57 @@ func Install(opts InstallOptions) (InstallResult, error) {ServiceLabel: manager.Label(),LogPath: cfg.LogPath,}- if err := endpointcollector.WriteConfig(cfg); err != nil {++ tx := newInstallRollback(manager)+ tx.Track(cfg.Collector.ConfigPath)+ manifest.Files = append(manifest.Files, cfg.Collector.ConfigPath)+ if err := writeCollectorConfig(cfg); err != nil {+ tx.Rollback(manifest)return InstallResult{}, err}- manifest.Files = append(manifest.Files, cfg.Collector.ConfigPath)- plistPath, err := manager.WritePlist(collectorBinary, cfg.Collector.ConfigPath)++ plistPath, err := manager.PlistPath()if err != nil {- rollback(manifest)+ tx.Rollback(manifest)return InstallResult{}, err}+ tx.Track(plistPath)manifest.Files = append(manifest.Files, plistPath)- configPath, err := endpointconfig.Save(cfg)- if err != nil {- rollback(manifest)+ if _, err := manager.WritePlist(collectorBinary, cfg.Collector.ConfigPath); err != nil {+ tx.Rollback(manifest)return InstallResult{}, err}++ configPath := endpointconfig.ConfigPath(cfg.UserMode)+ tx.Track(configPath)manifest.Files = append(manifest.Files, configPath)- harnessPaths, err := configureHarnesses(cfg)- if err != nil {- rollback(manifest)+ if _, err := saveEndpointConfig(cfg); err != nil {+ tx.Rollback(manifest)return InstallResult{}, err}++ harnessPaths, err := configureHarnesses(cfg)manifest.HarnessConfigs = harnessPathsmanifest.Backups = discoverBackups(harnessPaths)+ if err != nil {+ tx.Rollback(manifest)+ return InstallResult{}, err+ }if opts.StartService {if err := manager.Load(); err != nil {- rollback(manifest)+ tx.Rollback(manifest)+ return InstallResult{}, err+ }+ tx.ServiceLoaded = true+ if err := endpointcollector.WaitUntilReady(cfg, 10*time.Second); err != nil {+ tx.Rollback(manifest)return InstallResult{}, err}}+ tx.Track(manifestPath(cfg.UserMode))manifestPath, err := writeManifest(cfg.UserMode, manifest)if err != nil {- rollback(manifest)+ tx.Rollback(manifest)return InstallResult{}, err}event := schema.NewEvent(schema.NewEventOptions{@@ -154,7 +242,8 @@ func Install(opts InstallOptions) (InstallResult, error) {Message: "Beacon endpoint local telemetry configured",})event.Destination = installDestination(cfg)- if _, err := writer.AppendEvent(event, writer.Options{Path: cfg.LogPath, UserMode: cfg.UserMode}); err != nil {+ if _, err := appendInstallEvent(event, writer.Options{Path: cfg.LogPath, UserMode: cfg.UserMode}); err != nil {+ tx.Rollback(manifest)return InstallResult{}, err}return InstallResult{@@ -193,7 +282,6 @@ func Uninstall(opts UninstallOptions) error {}func Repair(opts InstallOptions) (InstallResult, error) {- _ = Uninstall(UninstallOptions{UserMode: opts.UserMode, LogPath: opts.LogPath, KeepLogs: true, KeepConfig: true})return Install(opts)}@@ -377,14 +465,26 @@ func preflight(cfg endpointconfig.Config, startService bool) error {return nil}if !endpointcollector.PortAvailable(cfg.Collector.GRPCPort) {- return fmt.Errorf("OTLP gRPC port %d is already in use", cfg.Collector.GRPCPort)+ if !existingCollectorReady(cfg) {+ return fmt.Errorf("OTLP gRPC port %d is already in use", cfg.Collector.GRPCPort)+ }}if !endpointcollector.PortAvailable(cfg.Collector.HTTPPort) {- return fmt.Errorf("OTLP HTTP port %d is already in use", cfg.Collector.HTTPPort)+ if !existingCollectorReady(cfg) {+ return fmt.Errorf("OTLP HTTP port %d is already in use", cfg.Collector.HTTPPort)+ }}return nil}+func existingCollectorReady(cfg endpointconfig.Config) bool {+ if !(service.Manager{UserMode: cfg.UserMode}).Status().Loaded {+ return false+ }+ status := endpointcollector.CheckStatus(cfg)+ return status.GRPCReady && status.HTTPReady && status.HealthReady+}+func configureHarnesses(cfg endpointconfig.Config) ([]string, error) {grpcEndpoint := fmt.Sprintf("http://127.0.0.1:%d", cfg.Collector.GRPCPort)httpEndpoint := fmt.Sprintf("http://127.0.0.1:%d", cfg.Collector.HTTPPort)diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle_test.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle_test.goindex b3054a55..615845ef 100644--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle_test.go+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle_test.go@@ -1,6 +1,7 @@package lifecycleimport (+ "errors""net""os""path/filepath"@@ -9,7 +10,9 @@ import ("testing"endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer")func TestRestoreTargetTimestampedBackup(t *testing.T) {@@ -471,6 +474,99 @@ func TestInstallFailsBeforeWritingArtifactsWhenCollectorMissing(t *testing.T) {}}+func TestInstallRollsBackArtifactsWhenFinalEventFails(t *testing.T) {+ if runtime.GOOS != "darwin" {+ t.Skip("install preflight is macOS-only")+ }+ home := t.TempDir()+ t.Setenv("HOME", 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()+ t.Setenv("HOME", 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},"content_retention":"full"}`+ 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))+ }+}+func freePort(t *testing.T) int {t.Helper()ln, err := net.Listen("tcp", "127.0.0.1:0")diff --git a/cli/beacon/internal/endpoint/service/service.go b/cli/beacon/internal/endpoint/service/service.goindex 5c476686..f84fccbe 100644--- a/cli/beacon/internal/endpoint/service/service.go+++ b/cli/beacon/internal/endpoint/service/service.go@@ -73,7 +73,19 @@ func (m Manager) Load() error {return err}domain := serviceDomain(m.UserMode)- return runLaunchctlWithContext(domain, m.Label(), path, "bootstrap", domain, path)+ out, err := runLaunchctlCommand("bootstrap", domain, path)+ if err == nil {+ return nil+ }+ text := strings.TrimSpace(out)+ if strings.Contains(text, "already bootstrapped") {+ target := domain + "/" + m.Label()+ if err := runLaunchctlWithContext(domain, m.Label(), "", "bootout", target); err != nil {+ return err+ }+ return runLaunchctlWithContext(domain, m.Label(), path, "bootstrap", domain, path)+ }+ return launchctlError(text, err, domain, m.Label(), path, "bootstrap", domain, path)}func (m Manager) Unload() error {@@ -90,13 +102,13 @@ func (m Manager) Status() Status {status.Message = "service status is available only on macOS"return status}- out, err := exec.Command("launchctl", "print", serviceDomain(m.UserMode)+"/"+m.Label()).CombinedOutput()+ out, err := runLaunchctlCommand("print", serviceDomain(m.UserMode)+"/"+m.Label())if err != nil {- status.Message = strings.TrimSpace(string(out))+ status.Message = strings.TrimSpace(out)return status}status.Loaded = true- text := string(out)+ text := outstatus.Running = strings.Contains(text, "state = running") || strings.Contains(text, "pid =")return status}@@ -111,9 +123,13 @@ func runLaunchctlWithContext(domain, label, plistPath string, args ...string) erreturn nil}text := strings.TrimSpace(out)- if strings.Contains(text, "already bootstrapped") || strings.Contains(text, "No such process") {+ if strings.Contains(text, "No such process") {return nil}+ return launchctlError(text, err, domain, label, plistPath, args...)+}++func launchctlError(text string, err error, domain, label, plistPath string, args ...string) error {context := launchctlContext(domain, label, plistPath)guidance := launchctlGuidance(text, domain, label)if guidance != "" {diff --git a/cli/beacon/internal/endpoint/service/service_test.go b/cli/beacon/internal/endpoint/service/service_test.goindex 6c5f2207..dc10ef28 100644--- a/cli/beacon/internal/endpoint/service/service_test.go+++ b/cli/beacon/internal/endpoint/service/service_test.go@@ -127,3 +127,60 @@ func TestRunLaunchctlWithContextExplainsBootstrapIOError(t *testing.T) {}}}++func TestManagerLoadReloadsAlreadyBootstrappedJob(t *testing.T) {+ if runtime.GOOS != "darwin" {+ t.Skip("launchd reload is macOS-only")+ }+ home := t.TempDir()+ t.Setenv("HOME", home)+ var calls []string+ oldRun := runLaunchctlCommand+ runLaunchctlCommand = func(args ...string) (string, error) {+ calls = append(calls, strings.Join(args, " "))+ switch len(calls) {+ case 1:+ return "Bootstrap failed: 5: already bootstrapped", errors.New("exit status 5")+ case 2, 3:+ return "", nil+ default:+ return "", errors.New("unexpected launchctl call")+ }+ }+ t.Cleanup(func() {+ runLaunchctlCommand = oldRun+ })++ if err := (Manager{UserMode: true}).Load(); err != nil {+ t.Fatalf("Load returned error: %v", err)+ }+ if len(calls) != 3 {+ t.Fatalf("launchctl calls = %#v, want bootstrap/bootout/bootstrap", calls)+ }+ if !strings.HasPrefix(calls[0], "bootstrap gui/") || !strings.Contains(calls[1], "bootout gui/") || !strings.HasPrefix(calls[2], "bootstrap gui/") {+ t.Fatalf("unexpected launchctl call sequence: %#v", calls)+ }+}++func TestManagerLoadReturnsBootoutFailureWhenReloadFails(t *testing.T) {+ if runtime.GOOS != "darwin" {+ t.Skip("launchd reload is macOS-only")+ }+ home := t.TempDir()+ t.Setenv("HOME", home)+ oldRun := runLaunchctlCommand+ runLaunchctlCommand = func(args ...string) (string, error) {+ if len(args) > 0 && args[0] == "bootstrap" {+ return "Bootstrap failed: 5: already bootstrapped", errors.New("exit status 5")+ }+ return "Boot-out failed", errors.New("exit status 5")+ }+ t.Cleanup(func() {+ runLaunchctlCommand = oldRun+ })++ err := (Manager{UserMode: true}).Load()+ if err == nil || !strings.Contains(err.Error(), "Boot-out failed") {+ t.Fatalf("Load error = %v, want bootout failure", err)+ }+}diff --git a/packaging/macos/build-pkg.sh b/packaging/macos/build-pkg.shindex 493df4e4..b80e5fab 100755--- a/packaging/macos/build-pkg.sh+++ b/packaging/macos/build-pkg.sh@@ -17,6 +17,13 @@ PKG_ROOT="$WORK_DIR/pkgroot"PKG_SCRIPTS="$WORK_DIR/scripts"PKG_PATH="$OUT_DIR/$PKG_NAME-$VERSION.pkg"+copy_file() {+ if cp -X "$1" "$2" 2>/dev/null; then+ return 0+ fi+ cp "$1" "$2"+}+if [ ! -x "$BEACON_BIN" ]; thenecho "beacon binary not found or not executable: $BEACON_BIN" >&2echo "Build it first, for example: (cd cli/beacon && make build)" >&2@@ -32,16 +39,16 @@ fimkdir -p "$OUT_DIR" "$PKG_ROOT/opt/beacon/bin" "$PKG_ROOT/opt/beacon/scripts" \"$PKG_ROOT/opt/beacon/jamf" "$PKG_ROOT/opt/beacon/fleet" "$PKG_SCRIPTS"-cp "$BEACON_BIN" "$PKG_ROOT/opt/beacon/bin/beacon"-cp "$COLLECTOR_BIN" "$PKG_ROOT/opt/beacon/bin/beacon-otelcol"-cp "$ROOT_DIR/packaging/macos/install-endpoint.sh" "$PKG_ROOT/opt/beacon/scripts/install-endpoint.sh"-cp "$ROOT_DIR/packaging/macos/uninstall-endpoint.sh" "$PKG_ROOT/opt/beacon/scripts/uninstall-endpoint.sh"-cp "$ROOT_DIR/packaging/macos/scripts/postinstall" "$PKG_SCRIPTS/postinstall"-cp "$ROOT_DIR/packaging/macos/scripts/preinstall" "$PKG_SCRIPTS/preinstall"+copy_file "$BEACON_BIN" "$PKG_ROOT/opt/beacon/bin/beacon"+copy_file "$COLLECTOR_BIN" "$PKG_ROOT/opt/beacon/bin/beacon-otelcol"+copy_file "$ROOT_DIR/packaging/macos/install-endpoint.sh" "$PKG_ROOT/opt/beacon/scripts/install-endpoint.sh"+copy_file "$ROOT_DIR/packaging/macos/uninstall-endpoint.sh" "$PKG_ROOT/opt/beacon/scripts/uninstall-endpoint.sh"+copy_file "$ROOT_DIR/packaging/macos/scripts/postinstall" "$PKG_SCRIPTS/postinstall"+copy_file "$ROOT_DIR/packaging/macos/scripts/preinstall" "$PKG_SCRIPTS/preinstall"if command -v ditto >/dev/null 2>&1; then- ditto --norsrc "$ROOT_DIR/packaging/macos/jamf" "$PKG_ROOT/opt/beacon/jamf"- ditto --norsrc "$ROOT_DIR/packaging/macos/fleet" "$PKG_ROOT/opt/beacon/fleet"+ ditto --norsrc --noextattr --noqtn "$ROOT_DIR/packaging/macos/jamf" "$PKG_ROOT/opt/beacon/jamf"+ ditto --norsrc --noextattr --noqtn "$ROOT_DIR/packaging/macos/fleet" "$PKG_ROOT/opt/beacon/fleet"elsecp -R "$ROOT_DIR/packaging/macos/jamf/." "$PKG_ROOT/opt/beacon/jamf/"cp -R "$ROOT_DIR/packaging/macos/fleet/." "$PKG_ROOT/opt/beacon/fleet/"@@ -50,7 +57,7 @@ fiif [ -d "$ROOT_DIR/cli/beacon/internal/endpoint/wazuh/pack" ]; thenmkdir -p "$PKG_ROOT/opt/beacon/wazuh"if command -v ditto >/dev/null 2>&1; then- ditto --norsrc "$ROOT_DIR/cli/beacon/internal/endpoint/wazuh/pack" "$PKG_ROOT/opt/beacon/wazuh"+ ditto --norsrc --noextattr --noqtn "$ROOT_DIR/cli/beacon/internal/endpoint/wazuh/pack" "$PKG_ROOT/opt/beacon/wazuh"elsecp -R "$ROOT_DIR/cli/beacon/internal/endpoint/wazuh/pack/." "$PKG_ROOT/opt/beacon/wazuh/"fi@@ -80,6 +87,7 @@ if [ -n "${PKG_SIGN_IDENTITY:-}" ]; then--version "$VERSION" \--install-location / \--filter '(^|/)\._[^/]*$' \+ --filter '.*\._.*' \--filter '/\.DS_Store$' \--filter '(^|/)CVS($|/)' \--filter '(^|/)\.svn($|/)' \@@ -93,6 +101,7 @@ else--version "$VERSION" \--install-location / \--filter '(^|/)\._[^/]*$' \+ --filter '.*\._.*' \--filter '/\.DS_Store$' \--filter '(^|/)CVS($|/)' \--filter '(^|/)\.svn($|/)' \diff --git a/packaging/macos/scripts/postinstall b/packaging/macos/scripts/postinstallindex 415837f4..6d967883 100755--- a/packaging/macos/scripts/postinstall+++ b/packaging/macos/scripts/postinstall@@ -18,9 +18,9 @@ BEACON_NO_START=1 \/opt/beacon/scripts/install-endpoint.shif command -v launchctl >/dev/null 2>&1; then- launchctl bootstrap system /Library/LaunchDaemons/com.beacon.endpoint.collector.plist >/dev/null 2>&1 || {- launchctl print system/com.beacon.endpoint.collector >/dev/null 2>&1 || exit 1- }+ launchctl bootout system/com.beacon.endpoint.collector >/dev/null 2>&1 || true+ launchctl bootstrap system /Library/LaunchDaemons/com.beacon.endpoint.collector.plist >/dev/null 2>&1+ launchctl print system/com.beacon.endpoint.collector >/dev/null 2>&1fiexit 0