Skip to content

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

fix(endpoint): repair user runtime config after package installs

shukieshah5e71998e3955
diff --git a/cli/beacon/cmd/endpoint.go b/cli/beacon/cmd/endpoint.go
index 9a462d8a..2869e2fb 100644
--- a/cli/beacon/cmd/endpoint.go
+++ b/cli/beacon/cmd/endpoint.go
@@ -365,6 +365,7 @@ func init() {
}
endpointCmd.AddCommand(endpointIntegrationsCmd)
endpointCmd.AddCommand(endpointHooksCmd)
+ endpointCmd.AddCommand(endpointUserConfigCmd)
endpointCmd.AddCommand(endpointConfigCmd)
endpointInventoryCmd.AddCommand(endpointInventoryHeartbeatCmd)
endpointConfigCmd.AddCommand(endpointConfigShowCmd)
@@ -377,6 +378,7 @@ func init() {
endpointHooksCmd.AddCommand(endpointHooksUninstallCmd)
endpointHooksCmd.AddCommand(endpointHooksStatusCmd)
endpointHooksCmd.AddCommand(endpointHooksRepairInstalledCmd)
+ endpointUserConfigCmd.AddCommand(endpointUserConfigRepairInstalledCmd)
endpointCoworkCmd.AddCommand(endpointCoworkPrintConfigCmd)
endpointCoworkCmd.AddCommand(endpointCoworkSetupCmd)
endpointCoworkCmd.AddCommand(endpointCoworkStatusCmd)
@@ -389,7 +391,7 @@ func init() {
endpointVSCodeCmd.AddCommand(endpointVSCodeStatusCmd)
endpointVSCodeCmd.AddCommand(endpointVSCodeValidateCmd)
- for _, c := range []*cobra.Command{endpointInstallCmd, endpointStatusCmd, endpointDoctorCmd, endpointInventoryCmd, endpointInventoryHeartbeatCmd, endpointDiscoverCmd, endpointTestEventCmd, endpointBundleDiagnosticsCmd, endpointUninstallCmd, endpointRepairCmd, endpointConfigShowCmd, endpointConfigValidateCmd, endpointIntegrationsValidateCmd, topLevelDoctorCmd, topLevelStatusCmd, topLevelInventoryCmd} {
+ for _, c := range []*cobra.Command{endpointInstallCmd, endpointStatusCmd, endpointDoctorCmd, endpointInventoryCmd, endpointInventoryHeartbeatCmd, endpointDiscoverCmd, endpointTestEventCmd, endpointBundleDiagnosticsCmd, endpointUninstallCmd, endpointRepairCmd, endpointConfigShowCmd, endpointConfigValidateCmd, endpointIntegrationsValidateCmd, endpointUserConfigRepairInstalledCmd, topLevelDoctorCmd, topLevelStatusCmd, topLevelInventoryCmd} {
c.Flags().BoolVar(&endpointOpts.userMode, "user", true, "Use per-user endpoint paths")
c.Flags().BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths and launch daemon")
c.Flags().StringVar(&endpointOpts.logPath, "log-path", "", "Runtime JSONL log path")
@@ -512,6 +514,9 @@ func init() {
endpointHooksRepairInstalledCmd.Flags().StringVar(&endpointOpts.hookHarnesses, "harness", "", "Comma-separated hook harnesses to refresh; empty refreshes already-installed Beacon hooks")
endpointHooksRepairInstalledCmd.Flags().StringVar(&endpointOpts.hookLevel, "level", "user", "Hook install level: user or project")
endpointHooksRepairInstalledCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print repair result as JSON")
+ endpointUserConfigRepairInstalledCmd.Flags().StringVar(&endpointOpts.hookHarnesses, "harness", "claude,codex,cursor", "Comma-separated user runtime configs to repair")
+ endpointUserConfigRepairInstalledCmd.Flags().StringVar(&endpointOpts.hookLevel, "level", "user", "Hook install level: user or project")
+ endpointUserConfigRepairInstalledCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print repair result as JSON")
endpointHooksInstallCmd.Flags().BoolVar(&endpointOpts.allTargets, "all", false, "Target all supported hook harnesses")
endpointHooksInstallCmd.Flags().BoolVar(&endpointOpts.dryRun, "dry-run", false, "Print planned hook actions without changing files")
endpointHooksUninstallCmd.Flags().BoolVar(&endpointOpts.allTargets, "all", false, "Target all supported hook harnesses")
diff --git a/cli/beacon/cmd/endpoint_hooks_repair.go b/cli/beacon/cmd/endpoint_hooks_repair.go
index 7629b142..ebd1163f 100644
--- a/cli/beacon/cmd/endpoint_hooks_repair.go
+++ b/cli/beacon/cmd/endpoint_hooks_repair.go
@@ -67,7 +67,7 @@ func repairInstalledEndpointHooks() (endpointHookRepairResult, error) {
logPath = writer.DefaultPath(false)
}
- targets, err := repairHookTargetsForUser(info, logPath)
+ targets, err := repairHookTargetsForUser(info, logPath, nil)
if err != nil {
return endpointHookRepairResult{}, err
}
@@ -79,9 +79,13 @@ func repairInstalledEndpointHooks() (endpointHookRepairResult, error) {
}, nil
}
-func repairHookTargetsForUser(info consoleUserInfo, logPath string) ([]string, error) {
+func repairHookTargetsForUser(info consoleUserInfo, logPath string, requestedTargets []string) ([]string, error) {
targetSet := map[string]bool{}
- if strings.TrimSpace(endpointOpts.hookHarnesses) != "" {
+ if requestedTargets != nil {
+ for _, target := range requestedTargets {
+ targetSet[target] = true
+ }
+ } else if strings.TrimSpace(endpointOpts.hookHarnesses) != "" {
targets, err := canonicalHookTargets(splitCSV(endpointOpts.hookHarnesses))
if err != nil {
return nil, err
diff --git a/cli/beacon/cmd/endpoint_test.go b/cli/beacon/cmd/endpoint_test.go
index e7de021e..36ae95db 100644
--- a/cli/beacon/cmd/endpoint_test.go
+++ b/cli/beacon/cmd/endpoint_test.go
@@ -96,6 +96,191 @@ func TestPlannedInstallActionsSeparatesHookHarnesses(t *testing.T) {
}
}
+func TestRepairInstalledEndpointUserConfigConfiguresNativeAndHooks(t *testing.T) {
+ oldOpts := endpointOpts
+ oldActiveConsoleUser := activeConsoleUser
+ oldRunHookRepairAsUser := runHookRepairAsUser
+ t.Cleanup(func() {
+ endpointOpts = oldOpts
+ activeConsoleUser = oldActiveConsoleUser
+ runHookRepairAsUser = oldRunHookRepairAsUser
+ })
+
+ home := t.TempDir()
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ claudeSettingsPath := filepath.Join(home, ".claude", "settings.json")
+ if err := os.MkdirAll(filepath.Dir(claudeSettingsPath), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(claudeSettingsPath, []byte(`{"env":{"KEEP_ME":"yes"}}`), 0600); err != nil {
+ t.Fatal(err)
+ }
+ endpointOpts.userMode = true
+ endpointOpts.systemMode = true
+ endpointOpts.logPath = logPath
+ endpointOpts.hookHarnesses = "claude,codex,cursor,gemini"
+ endpointOpts.hookLevel = "user"
+ activeConsoleUser = func() (consoleUserInfo, bool, error) {
+ return consoleUserInfo{Username: "alice", HomeDir: home}, true, nil
+ }
+ var repairArgs []string
+ runHookRepairAsUser = func(info consoleUserInfo, args ...string) error {
+ if info.Username != "alice" || info.HomeDir != home {
+ t.Fatalf("repair user = %#v, want alice/%s", info, home)
+ }
+ repairArgs = append([]string(nil), args...)
+ return nil
+ }
+
+ result, err := repairInstalledEndpointUserConfig()
+ if err != nil {
+ t.Fatalf("repairInstalledEndpointUserConfig returned error: %v", err)
+ }
+ if got, want := strings.Join(result.NativeConfigTargets, ","), "claude,codex,gemini"; got != want {
+ t.Fatalf("native targets = %q, want %q", got, want)
+ }
+ if got, want := strings.Join(result.HookTargets, ","), "claude,codex,cursor"; got != want {
+ t.Fatalf("hook targets = %q, want %q", got, want)
+ }
+ if got := strings.Join(repairArgs, " "); !strings.Contains(got, "endpoint hooks install") ||
+ !strings.Contains(got, "--harness claude,codex,cursor") ||
+ !strings.Contains(got, "--log-path "+logPath) {
+ t.Fatalf("hook repair args = %q, want endpoint hooks install for requested targets", got)
+ }
+ claudeSettings, err := os.ReadFile(claudeSettingsPath)
+ if err != nil {
+ t.Fatalf("read Claude settings: %v", err)
+ }
+ for _, want := range []string{
+ `"CLAUDE_CODE_ENABLE_TELEMETRY": "1"`,
+ `"OTEL_EXPORTER_OTLP_ENDPOINT": "http://127.0.0.1:4317"`,
+ } {
+ if !strings.Contains(string(claudeSettings), want) {
+ t.Fatalf("Claude settings missing %q:\n%s", want, claudeSettings)
+ }
+ }
+ if !strings.Contains(string(claudeSettings), `"KEEP_ME": "yes"`) {
+ t.Fatalf("Claude settings did not preserve existing env:\n%s", claudeSettings)
+ }
+ claudeBackup, err := os.ReadFile(claudeSettingsPath + ".beacon.bak")
+ if err != nil {
+ t.Fatalf("read rolling Claude backup: %v", err)
+ }
+ if !strings.Contains(string(claudeBackup), `"KEEP_ME":"yes"`) {
+ t.Fatalf("rolling Claude backup did not preserve original config: %s", claudeBackup)
+ }
+ timestampedBackups, err := filepath.Glob(claudeSettingsPath + ".beacon.*.bak")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(timestampedBackups) != 0 {
+ t.Fatalf("timestamped Claude backups = %v, want collapsed rolling backup only", timestampedBackups)
+ }
+ codexConfig, err := os.ReadFile(filepath.Join(home, ".codex", "config.toml"))
+ if err != nil {
+ t.Fatalf("read Codex config: %v", err)
+ }
+ for _, want := range []string{
+ "[otel]",
+ `endpoint = "http://127.0.0.1:4317"`,
+ "[otel.metrics_exporter.\"otlp-grpc\"]",
+ } {
+ if !strings.Contains(string(codexConfig), want) {
+ t.Fatalf("Codex config missing %q:\n%s", want, codexConfig)
+ }
+ }
+ geminiSettings, err := os.ReadFile(filepath.Join(home, ".gemini", "settings.json"))
+ if err != nil {
+ t.Fatalf("read Gemini settings: %v", err)
+ }
+ for _, want := range []string{
+ `"enabled": true`,
+ `"otlpEndpoint": "http://127.0.0.1:4317"`,
+ } {
+ if !strings.Contains(string(geminiSettings), want) {
+ t.Fatalf("Gemini settings missing %q:\n%s", want, geminiSettings)
+ }
+ }
+}
+
+func TestRepairInstalledEndpointUserConfigAllowsNativeOnlyHarness(t *testing.T) {
+ oldOpts := endpointOpts
+ oldActiveConsoleUser := activeConsoleUser
+ oldRunHookRepairAsUser := runHookRepairAsUser
+ t.Cleanup(func() {
+ endpointOpts = oldOpts
+ activeConsoleUser = oldActiveConsoleUser
+ runHookRepairAsUser = oldRunHookRepairAsUser
+ })
+
+ home := t.TempDir()
+ endpointOpts.userMode = true
+ endpointOpts.systemMode = true
+ endpointOpts.hookHarnesses = "gemini"
+ activeConsoleUser = func() (consoleUserInfo, bool, error) {
+ return consoleUserInfo{Username: "alice", HomeDir: home}, true, nil
+ }
+ runHookRepairAsUser = func(info consoleUserInfo, args ...string) error {
+ t.Fatalf("native-only Gemini repair should not invoke hook repair, args=%v", args)
+ return nil
+ }
+
+ result, err := repairInstalledEndpointUserConfig()
+ if err != nil {
+ t.Fatalf("repairInstalledEndpointUserConfig returned error: %v", err)
+ }
+ if got, want := strings.Join(result.NativeConfigTargets, ","), "gemini"; got != want {
+ t.Fatalf("native targets = %q, want %q", got, want)
+ }
+ if len(result.HookTargets) != 0 {
+ t.Fatalf("hook targets = %#v, want none", result.HookTargets)
+ }
+ if _, err := os.Stat(filepath.Join(home, ".gemini", "settings.json")); err != nil {
+ t.Fatalf("Gemini settings not written: %v", err)
+ }
+}
+
+func TestRepairInstalledEndpointUserConfigHonorsHookOnlyAliases(t *testing.T) {
+ oldOpts := endpointOpts
+ oldActiveConsoleUser := activeConsoleUser
+ oldRunHookRepairAsUser := runHookRepairAsUser
+ t.Cleanup(func() {
+ endpointOpts = oldOpts
+ activeConsoleUser = oldActiveConsoleUser
+ runHookRepairAsUser = oldRunHookRepairAsUser
+ })
+
+ home := t.TempDir()
+ endpointOpts.userMode = true
+ endpointOpts.systemMode = true
+ endpointOpts.hookHarnesses = "claude-hooks"
+ activeConsoleUser = func() (consoleUserInfo, bool, error) {
+ return consoleUserInfo{Username: "alice", HomeDir: home}, true, nil
+ }
+ var repairArgs []string
+ runHookRepairAsUser = func(info consoleUserInfo, args ...string) error {
+ repairArgs = append([]string(nil), args...)
+ return nil
+ }
+
+ result, err := repairInstalledEndpointUserConfig()
+ if err != nil {
+ t.Fatalf("repairInstalledEndpointUserConfig returned error: %v", err)
+ }
+ if len(result.NativeConfigTargets) != 0 || len(result.NativeConfigPaths) != 0 {
+ t.Fatalf("native config = %v %v, want none for hook-only alias", result.NativeConfigTargets, result.NativeConfigPaths)
+ }
+ if got, want := strings.Join(result.HookTargets, ","), "claude"; got != want {
+ t.Fatalf("hook targets = %q, want %q", got, want)
+ }
+ if _, err := os.Stat(filepath.Join(home, ".claude", "settings.json")); !os.IsNotExist(err) {
+ t.Fatalf("Claude native settings should not be written for hook-only alias, err=%v", err)
+ }
+ if got := strings.Join(repairArgs, " "); !strings.Contains(got, "--harness claude") {
+ t.Fatalf("hook repair args = %q, want claude hook install", got)
+ }
+}
+
func TestEndpointDashboardCommandRegistered(t *testing.T) {
cmd, _, err := endpointCmd.Find([]string{"dashboard"})
if err != nil {
diff --git a/cli/beacon/cmd/endpoint_user_config.go b/cli/beacon/cmd/endpoint_user_config.go
new file mode 100644
index 00000000..598f9788
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_user_config.go
@@ -0,0 +1,262 @@
+package cmd
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "os/user"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+ "syscall"
+
+ 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/writer"
+ "github.com/spf13/cobra"
+)
+
+var endpointUserConfigCmd = &cobra.Command{
+ Use: "user-config",
+ Short: "Repair active user endpoint runtime configuration",
+ Hidden: true,
+}
+
+var endpointUserConfigRepairInstalledCmd = &cobra.Command{
+ Use: "repair-installed",
+ Short: "Repair active console user runtime configuration for a system endpoint",
+ Hidden: true,
+ SilenceUsage: true,
+ RunE: runEndpointUserConfigRepairInstalled,
+}
+
+type endpointUserConfigRepairResult struct {
+ User string `json:"user,omitempty"`
+ HomeDir string `json:"home_dir,omitempty"`
+ RuntimeLogPath string `json:"runtime_log_path,omitempty"`
+ NativeConfigTargets []string `json:"native_config_targets,omitempty"`
+ NativeConfigPaths []string `json:"native_config_paths,omitempty"`
+ HookTargets []string `json:"hook_targets,omitempty"`
+ SkippedReason string `json:"skipped_reason,omitempty"`
+}
+
+type userConfigTargets struct {
+ native []string
+ hooks []string
+}
+
+func runEndpointUserConfigRepairInstalled(cmd *cobra.Command, args []string) error {
+ result, err := repairInstalledEndpointUserConfig()
+ if endpointOpts.jsonOutput {
+ _ = json.NewEncoder(cmd.OutOrStdout()).Encode(result)
+ }
+ return err
+}
+
+func repairInstalledEndpointUserConfig() (endpointUserConfigRepairResult, error) {
+ if endpointUserMode() {
+ return endpointUserConfigRepairResult{SkippedReason: "requires_system_endpoint"}, fmt.Errorf("endpoint user-config repair-installed is intended for system endpoint installs; pass --system")
+ }
+ info, ok, err := activeConsoleUser()
+ if err != nil {
+ return endpointUserConfigRepairResult{}, err
+ }
+ if !ok {
+ return endpointUserConfigRepairResult{SkippedReason: "no_active_console_user"}, nil
+ }
+
+ cfg := loadConfigForMode(false, endpointOpts.logPath)
+ if cfg.LogPath == "" {
+ cfg.LogPath = writer.DefaultPath(false)
+ }
+ targets, err := resolveUserConfigTargets(splitCSV(endpointOpts.hookHarnesses))
+ if err != nil {
+ return endpointUserConfigRepairResult{}, err
+ }
+ if len(targets.native) == 0 && len(targets.hooks) == 0 {
+ targets = userConfigTargets{
+ native: []string{"claude", "codex"},
+ hooks: []string{"claude", "codex", "cursor"},
+ }
+ }
+
+ nativeTargets, nativePaths, err := repairNativeRuntimeConfigForUser(info, cfg, targets.native)
+ if err != nil {
+ return endpointUserConfigRepairResult{}, err
+ }
+ var hookTargets []string
+ if len(targets.hooks) > 0 {
+ hookTargets, err = repairHookTargetsForUser(info, cfg.LogPath, targets.hooks)
+ if err != nil {
+ return endpointUserConfigRepairResult{}, err
+ }
+ }
+ return endpointUserConfigRepairResult{
+ User: info.Username,
+ HomeDir: info.HomeDir,
+ RuntimeLogPath: cfg.LogPath,
+ NativeConfigTargets: nativeTargets,
+ NativeConfigPaths: nativePaths,
+ HookTargets: hookTargets,
+ }, nil
+}
+
+func resolveUserConfigTargets(values []string) (userConfigTargets, error) {
+ seenNative := map[string]bool{}
+ seenHooks := map[string]bool{}
+ targets := userConfigTargets{native: []string{}, hooks: []string{}}
+ for _, value := range values {
+ if strings.TrimSpace(value) == "" {
+ continue
+ }
+ endpointTarget, endpointOK := normalizeEndpointTarget(value)
+ hookTarget, hookOK := normalizeHookTarget(value)
+ if !endpointOK && !hookOK {
+ return userConfigTargets{}, fmt.Errorf("unsupported user config harness %q", value)
+ }
+ if endpointOK && endpointTarget.Kind == endpointTargetOTLP {
+ switch endpointTarget.Name {
+ case "claude", "codex", "gemini":
+ if !seenNative[endpointTarget.Name] {
+ targets.native = append(targets.native, endpointTarget.Name)
+ seenNative[endpointTarget.Name] = true
+ }
+ }
+ }
+ if hookOK && !seenHooks[hookTarget] {
+ targets.hooks = append(targets.hooks, hookTarget)
+ seenHooks[hookTarget] = true
+ }
+ }
+ return targets, nil
+}
+
+func repairNativeRuntimeConfigForUser(info consoleUserInfo, cfg endpointconfig.Config, targets []string) ([]string, []string, error) {
+ grpcEndpoint := fmt.Sprintf("http://127.0.0.1:%d", cfg.Collector.GRPCPort)
+ seen := map[string]bool{}
+ var configured []string
+ var paths []string
+ _, err := withUserHome(info.HomeDir, func() (struct{}, error) {
+ for _, target := range targets {
+ switch strings.TrimSpace(target) {
+ case "claude":
+ if seen["claude"] {
+ continue
+ }
+ path, err := harness.ConfigureClaude(harness.ConfigureOptions{Endpoint: grpcEndpoint, UserMode: true})
+ if err != nil {
+ return struct{}{}, err
+ }
+ if err := collapseUserConfigBackups(path); err != nil {
+ return struct{}{}, err
+ }
+ if err := chownUserConfigArtifacts(info, path); err != nil {
+ return struct{}{}, err
+ }
+ configured = append(configured, "claude")
+ paths = append(paths, path)
+ seen["claude"] = true
+ case "codex":
+ if seen["codex"] {
+ continue
+ }
+ path, err := harness.ConfigureCodex(harness.ConfigureOptions{Endpoint: grpcEndpoint, UserMode: true})
+ if err != nil {
+ return struct{}{}, err
+ }
+ if err := collapseUserConfigBackups(path); err != nil {
+ return struct{}{}, err
+ }
+ if err := chownUserConfigArtifacts(info, path); err != nil {
+ return struct{}{}, err
+ }
+ configured = append(configured, "codex")
+ paths = append(paths, path)
+ seen["codex"] = true
+ case "gemini":
+ if seen["gemini"] {
+ continue
+ }
+ path, err := harness.ConfigureGemini(harness.ConfigureOptions{Endpoint: grpcEndpoint, UserMode: true})
+ if err != nil {
+ return struct{}{}, err
+ }
+ if err := collapseUserConfigBackups(path); err != nil {
+ return struct{}{}, err
+ }
+ if err := chownUserConfigArtifacts(info, path); err != nil {
+ return struct{}{}, err
+ }
+ configured = append(configured, "gemini")
+ paths = append(paths, path)
+ seen["gemini"] = true
+ }
+ }
+ return struct{}{}, nil
+ })
+ return configured, paths, err
+}
+
+func collapseUserConfigBackups(path string) error {
+ matches, err := filepath.Glob(path + ".beacon.*.bak")
+ if err != nil || len(matches) == 0 {
+ return err
+ }
+ sort.Strings(matches)
+ latest := matches[len(matches)-1]
+ data, err := os.ReadFile(latest)
+ if err != nil {
+ return err
+ }
+ if err := os.WriteFile(path+".beacon.bak", data, 0600); err != nil {
+ return err
+ }
+ for _, match := range matches {
+ if err := os.Remove(match); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ }
+ return nil
+}
+
+func chownUserConfigArtifacts(info consoleUserInfo, path string) error {
+ uid, gid, err := userOwnership(info)
+ if err != nil {
+ return err
+ }
+ for _, candidate := range userConfigArtifacts(path) {
+ if err := os.Chown(candidate, uid, gid); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ }
+ return nil
+}
+
+func userConfigArtifacts(path string) []string {
+ artifacts := []string{filepath.Dir(path), path}
+ if matches, err := filepath.Glob(path + ".beacon.*.bak"); err == nil {
+ artifacts = append(artifacts, matches...)
+ }
+ artifacts = append(artifacts, path+".beacon.bak")
+ return artifacts
+}
+
+func userOwnership(info consoleUserInfo) (int, int, error) {
+ if u, err := user.Lookup(info.Username); err == nil {
+ uid, uidErr := strconv.Atoi(u.Uid)
+ gid, gidErr := strconv.Atoi(u.Gid)
+ if uidErr == nil && gidErr == nil {
+ return uid, gid, nil
+ }
+ }
+ stat, err := os.Stat(info.HomeDir)
+ if err != nil {
+ return 0, 0, err
+ }
+ sys, ok := stat.Sys().(*syscall.Stat_t)
+ if !ok {
+ return 0, 0, fmt.Errorf("could not determine ownership for %s", info.HomeDir)
+ }
+ return int(sys.Uid), int(sys.Gid), nil
+}
diff --git a/cli/beacon/internal/endpoint/collector/collector.go b/cli/beacon/internal/endpoint/collector/collector.go
index 300aac7a..93f1d875 100644
--- a/cli/beacon/internal/endpoint/collector/collector.go
+++ b/cli/beacon/internal/endpoint/collector/collector.go
@@ -282,6 +282,28 @@ func WaitUntilReady(cfg endpointconfig.Config, timeout time.Duration) error {
}
}
+func WaitForPortsAvailable(grpcPort, httpPort int, timeout time.Duration) error {
+ deadline := time.Now().Add(timeout)
+ for {
+ grpcAvailable := PortAvailable(grpcPort)
+ httpAvailable := PortAvailable(httpPort)
+ if grpcAvailable && httpAvailable {
+ return nil
+ }
+ if time.Now().After(deadline) {
+ switch {
+ case !grpcAvailable && !httpAvailable:
+ return fmt.Errorf("OTLP gRPC port %d and HTTP port %d are already in use", grpcPort, httpPort)
+ case !grpcAvailable:
+ return fmt.Errorf("OTLP gRPC port %d is already in use", grpcPort)
+ default:
+ return fmt.Errorf("OTLP HTTP port %d is already in use", httpPort)
+ }
+ }
+ 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 {
diff --git a/cli/beacon/internal/endpoint/collector/collector_test.go b/cli/beacon/internal/endpoint/collector/collector_test.go
index 98cb1d38..2536ffb1 100644
--- a/cli/beacon/internal/endpoint/collector/collector_test.go
+++ b/cli/beacon/internal/endpoint/collector/collector_test.go
@@ -10,6 +10,7 @@ import (
"runtime"
"strings"
"testing"
+ "time"
endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
)
@@ -217,6 +218,48 @@ func TestWriteConfigUsesPrivatePermissionsWithFalconToken(t *testing.T) {
}
}
+func TestWaitForPortsAvailableWaitsForTransientListeners(t *testing.T) {
+ grpcListener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ httpListener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ _ = grpcListener.Close()
+ t.Fatal(err)
+ }
+ grpcPort := grpcListener.Addr().(*net.TCPAddr).Port
+ httpPort := httpListener.Addr().(*net.TCPAddr).Port
+ go func() {
+ time.Sleep(100 * time.Millisecond)
+ _ = grpcListener.Close()
+ _ = httpListener.Close()
+ }()
+
+ if err := WaitForPortsAvailable(grpcPort, httpPort, 2*time.Second); err != nil {
+ t.Fatalf("WaitForPortsAvailable returned error: %v", err)
+ }
+}
+
+func TestWaitForPortsAvailableReportsPersistentConflict(t *testing.T) {
+ grpcListener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer grpcListener.Close()
+ httpListener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ httpPort := httpListener.Addr().(*net.TCPAddr).Port
+ _ = httpListener.Close()
+
+ err = WaitForPortsAvailable(grpcListener.Addr().(*net.TCPAddr).Port, httpPort, 50*time.Millisecond)
+ if err == nil || !strings.Contains(err.Error(), "OTLP gRPC port") {
+ t.Fatalf("WaitForPortsAvailable error = %v, want gRPC port conflict", err)
+ }
+}
+
func TestDiscoverBinaryPrefersConfiguredExistingPath(t *testing.T) {
bin := filepath.Join(t.TempDir(), BinaryName)
if err := os.WriteFile(bin, []byte("#!/bin/sh\n"), 0755); err != nil {
diff --git a/cli/beacon/internal/endpoint/hooks/codex_test.go b/cli/beacon/internal/endpoint/hooks/codex_test.go
index c3fdae53..e00eeae5 100644
--- a/cli/beacon/internal/endpoint/hooks/codex_test.go
+++ b/cli/beacon/internal/endpoint/hooks/codex_test.go
@@ -9,7 +9,7 @@ import (
func TestInstallCodexHooksUsesInventoryHeartbeatOnly(t *testing.T) {
path := filepath.Join(t.TempDir(), "hooks.json")
- existing := `{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"echo keep"}]}]}}`
+ existing := `{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"echo keep"},{"type":"command","command":"BEACON_ENDPOINT_MODE=1 beacon-hooks --platform codex inventory-heartbeat"}]}],"Stop":[{"hooks":[{"type":"command","command":"BEACON_ENDPOINT_MODE=1 beacon-hooks --platform codex codex-usage-sync"}]}]}}`
if err := os.WriteFile(path, []byte(existing), 0600); err != nil {
t.Fatal(err)
}
@@ -36,11 +36,14 @@ func TestInstallCodexHooksUsesInventoryHeartbeatOnly(t *testing.T) {
t.Fatalf("Codex hooks missing %q:\n%s", want, text)
}
}
- for _, forbidden := range []string{"session-start", "prompt-submit"} {
+ for _, forbidden := range []string{"session-start", "prompt-submit", " stop", " session-end", "codex-usage-sync"} {
if strings.Contains(text, forbidden) {
t.Fatalf("Codex inventory hooks should not emit runtime hook events %q:\n%s", forbidden, text)
}
}
+ if !strings.Contains(text, "SessionStart") || strings.Contains(text, `"Stop"`) {
+ t.Fatalf("existing non-Beacon SessionStart should remain and old Beacon Stop should be removed:\n%s", text)
+ }
}
func TestRemoveCodexEndpointHooksPreservesOtherHooks(t *testing.T) {
diff --git a/cli/beacon/internal/endpoint/hooks/settings_hooks.go b/cli/beacon/internal/endpoint/hooks/settings_hooks.go
index 3b089987..1b1062bb 100644
--- a/cli/beacon/internal/endpoint/hooks/settings_hooks.go
+++ b/cli/beacon/internal/endpoint/hooks/settings_hooks.go
@@ -69,6 +69,7 @@ func installSettingsEndpointHooks(path, platform string, endpointHooks map[strin
if err != nil {
return err
}
+ removeSettingsEndpointHooksFromLoaded(&settings, platform)
for eventName, group := range endpointHooks {
settings.hooks[eventName] = mergeSettingsEndpointHook(settings.hooks[eventName], group, platform)
}
@@ -79,6 +80,32 @@ func installSettingsEndpointHooks(path, platform string, endpointHooks map[strin
return os.WriteFile(path, data, 0600)
}
+func removeSettingsEndpointHooksFromLoaded(settings *settingsHooksFile, platform string) bool {
+ if settings == nil {
+ return false
+ }
+ changed := false
+ for eventName, groups := range settings.hooks {
+ filtered := groups[:0]
+ for _, group := range groups {
+ withoutEndpointHooks, groupChanged := filterSettingsEndpointHooks(group, platform)
+ if groupChanged {
+ changed = true
+ }
+ if len(withoutEndpointHooks.Hooks) == 0 {
+ continue
+ }
+ filtered = append(filtered, withoutEndpointHooks)
+ }
+ if len(filtered) == 0 {
+ delete(settings.hooks, eventName)
+ } else {
+ settings.hooks[eventName] = filtered
+ }
+ }
+ return changed
+}
+
func mergeSettingsEndpointHook(existing []settingsHookGroup, group settingsHookGroup, platform string) []settingsHookGroup {
out := make([]settingsHookGroup, 0, len(existing)+1)
for _, item := range existing {
diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
index f78ee133..22121318 100644
--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
@@ -576,15 +576,16 @@ func preflight(cfg endpointconfig.Config, startService bool) error {
if !startService {
return nil
}
- if !endpointcollector.PortAvailable(cfg.Collector.GRPCPort) {
- if !existingCollectorReady(cfg) {
- return fmt.Errorf("OTLP gRPC port %d is already in use", cfg.Collector.GRPCPort)
- }
+ grpcAvailable := endpointcollector.PortAvailable(cfg.Collector.GRPCPort)
+ httpAvailable := endpointcollector.PortAvailable(cfg.Collector.HTTPPort)
+ if grpcAvailable && httpAvailable {
+ return nil
}
- if !endpointcollector.PortAvailable(cfg.Collector.HTTPPort) {
- if !existingCollectorReady(cfg) {
- return fmt.Errorf("OTLP HTTP port %d is already in use", cfg.Collector.HTTPPort)
- }
+ if existingCollectorReady(cfg) {
+ return nil
+ }
+ if err := endpointcollector.WaitForPortsAvailable(cfg.Collector.GRPCPort, cfg.Collector.HTTPPort, 10*time.Second); err != nil {
+ return fmt.Errorf("%w; if this persists, another process may be using Beacon's OTLP receiver ports", err)
}
return nil
}
diff --git a/packaging/macos/README.md b/packaging/macos/README.md
index 75e955ae..9d012896 100644
--- a/packaging/macos/README.md
+++ b/packaging/macos/README.md
@@ -34,6 +34,12 @@ The endpoint install creates system configuration and runtime state:
/var/log/beacon-agent/runtime.jsonl
```
+The package postinstall also repairs endpoint user configuration for the active
+console user when one is logged in. This user-context step points Claude Code and
+Codex native OTLP settings at the system collector and refreshes supported user
+hooks. Already-running Claude Code sessions may need to be restarted before
+settings-based OTLP environment changes take effect.
+
## Build A Test Package
Build Beacon, `beacon-otelcol`, and have the release Vector binary available,
@@ -247,6 +253,11 @@ Recommended rollout:
4. Scope repair/remediation to unhealthy devices.
5. Broaden deployment in stages after inventory and validation stay healthy.
+During install or repair, Beacon waits briefly for stale collector processes to
+release the configured OTLP ports before reporting a port conflict. Persistent
+`4317`/`4318` conflicts still fail because they may indicate another non-Beacon
+process owns the local receiver port.
+
Cursor, Devin CLI, Devin Desktop, Factory, Grok Build, and opencode hook
installation is separate from the base system package because these integrations
write per-user or per-project runtime settings. Run hook helpers only when an
@@ -321,8 +332,9 @@ environment that launches opencode to enable best-effort plugin debug logs.
## Jamf Pro
Upload the generated `.pkg` to Jamf Pro and create a Policy scoped to a pilot
-Smart Group. The package postinstall performs the default system install, so no
-script is required for the common path.
+Smart Group. The package postinstall performs the default system install and
+repairs the active console user's Claude/Codex native OTLP settings plus user
+hooks, so no script is required for the common path.
Use `/opt/beacon/jamf/scripts/install.sh` when a policy needs explicit
parameters or a reinstall action:
@@ -377,7 +389,9 @@ needs only to repair the system endpoint, prepare
`/var/log/beacon-agent/runtime.jsonl`,
`/var/log/beacon-agent/inventory_state.jsonl`, and the inventory heartbeat state
file for user-run hooks, reinstall Claude Code hooks for the interactive console
-user, and run a manual Claude hook smoke test.
+user, and run a manual Claude hook smoke test. Newer packages perform the
+console-user native OTLP repair in postinstall; Jamf scripts should not need to
+hand-edit Claude settings JSON.
`repair-hooks.sh` Jamf script parameters:
diff --git a/packaging/macos/pkgbuild.md b/packaging/macos/pkgbuild.md
index f0e7a512..6e6c7912 100644
--- a/packaging/macos/pkgbuild.md
+++ b/packaging/macos/pkgbuild.md
@@ -81,6 +81,11 @@ runs Gatekeeper's install assessment, and rewrites the SHA-256 checksum.
The package installs files under `/opt/beacon` and runs
`/opt/beacon/scripts/install-endpoint.sh` in `postinstall` with explicit
collector settings, matching the shared MDM install wrapper.
+After the system install step, postinstall runs Beacon's hidden
+`endpoint user-config repair-installed --system` helper. That helper resolves the
+active console user, configures that user's Claude/Codex native OTLP settings to
+use the system collector, and refreshes supported user hooks. This avoids writing
+per-user Claude/Codex settings as `root` during package or Jamf execution.
opencode support is intentionally not part of the default package install. To
enable opencode prompt/session/tool telemetry, run Beacon's hook installer in the
@@ -157,6 +162,10 @@ user-run hooks, reinstall Claude Code hooks for the console user, and run a
manual hook smoke test. Destination-specific forwarding policies live under
`/opt/beacon/jamf/claude/<destination>`, sourced from
[`packaging/macos/jamf/claude/<destination>`](https://github.com/Asymptote-Labs/agent-beacon/tree/main/packaging/macos/jamf/claude).
+Beacon endpoint repair waits briefly for previously loaded collectors to release
+OTLP ports before failing with a port conflict. If a port remains occupied after
+that bounded wait, treat it as a real local receiver conflict rather than adding
+unbounded Jamf retries.
Upload Extension Attributes from
`packaging/macos/jamf/extension-attributes` and build Smart Groups for missing,
diff --git a/packaging/macos/scripts/postinstall b/packaging/macos/scripts/postinstall
index 032172bd..0e2108fa 100755
--- a/packaging/macos/scripts/postinstall
+++ b/packaging/macos/scripts/postinstall
@@ -17,10 +17,10 @@ BEACON_SPLUNK_CA_FILE="${BEACON_SPLUNK_CA_FILE:-}" \
BEACON_NO_START=1 \
/opt/beacon/scripts/install-endpoint.sh
-"${BEACON_BIN:-/opt/beacon/bin/beacon}" endpoint hooks repair-installed \
+"${BEACON_BIN:-/opt/beacon/bin/beacon}" endpoint user-config repair-installed \
--system \
--harness "${BEACON_ENDPOINT_HARNESSES:-claude,codex}" || {
- echo "Warning: could not refresh installed user hooks after package install" >&2
+ echo "Warning: could not refresh installed user endpoint configuration after package install" >&2
}
forwarder_running() {
diff --git a/packaging/macos/test-endpoint-scripts.sh b/packaging/macos/test-endpoint-scripts.sh
index 3ab57e92..31120c24 100644
--- a/packaging/macos/test-endpoint-scripts.sh
+++ b/packaging/macos/test-endpoint-scripts.sh
@@ -33,8 +33,8 @@ if ! grep -q 'restore_existing_forwarder' "$ROOT_DIR/packaging/macos/scripts/pos
echo "postinstall should restore existing optional forwarders" >&2
exit 1
fi
-if ! grep -q 'endpoint hooks repair-installed' "$ROOT_DIR/packaging/macos/scripts/postinstall"; then
- echo "postinstall should refresh installed user hooks after package install" >&2
+if ! grep -q 'endpoint user-config repair-installed' "$ROOT_DIR/packaging/macos/scripts/postinstall"; then
+ echo "postinstall should refresh installed user endpoint configuration after package install" >&2
exit 1
fi
if ! grep -q 'launchctl kickstart -k' "$ROOT_DIR/packaging/macos/scripts/postinstall"; then