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
feat(endpoint): verify installs in the sandbox, close Linux correctness gaps
shukieshah8ada58442fac
diff --git a/beacon-sandbox/runner/runner.go b/beacon-sandbox/runner/runner.goindex c0b324a9..0e9c7b17 100644--- a/beacon-sandbox/runner/runner.go+++ b/beacon-sandbox/runner/runner.go@@ -191,23 +191,46 @@ func Run(ctx context.Context, p sandbox.Provider, sc scenario.Scenario, opts Optlogf("argv sampler failed to start: %v", err)}- // The collector is started by `beacon ci exec`, which wraps the agent session. That is a- // real shipping code path -- it is how Beacon collects in GitHub Actions and cloud agent- // sandboxes -- and it needs no persistent service manager, so it works on any host.- logf("running session (budget $%.2f, timeout %s)", sc.Budget(), sc.Timeout())- res, err := p.Exec(ctx, inst, sessionScript(sc, prompt, logPath), sandbox.ExecOpts{- User: image.AgentUser, Dir: workDirFor(sc), HomeDir: image.AgentHome,- PreserveEnv: true, PathPrepend: image.PathPrepend(), Timeout: sc.Timeout() + time.Minute,- })- if err != nil {- logf("session exec error: %v", err)- }- art.Meta["ci_exec"] = oneLine(res.Stdout)- // Recorded explicitly so a failing collector is visible in the run metadata rather than- // inferred from a missing log later.- art.Meta["ci_exec_rc"] = fmt.Sprintf("%d", res.ExitCode)- if res.ExitCode != 0 {- logf("beacon ci exec exited %d -- the collected log may be incomplete", res.ExitCode)+ // Two ways to get a collector, and which one a scenario uses is the whole point of the+ // distinction. `beacon ci exec` wraps the session in an ephemeral collector -- a real+ // shipping path, used in GitHub Actions and cloud agent sandboxes, needing no service+ // manager. A persistent install instead exercises `beacon endpoint install`: service+ // manager selection, unit installation, status reporting, and whether an installed+ // collector actually receives telemetry. Nothing else in the suite can tell you that.+ var res sandbox.Result+ if sc.Install != nil {+ installedLog, err := doInstall(ctx, p, inst, sc, agent, &art, logf)+ if err != nil {+ return art, err+ }+ logPath = installedLog+ logf("running session against the installed endpoint (budget $%.2f, timeout %s)",+ sc.Budget(), sc.Timeout())+ res, err = p.Exec(ctx, inst, plainSessionScript(sc, prompt), sandbox.ExecOpts{+ User: image.AgentUser, Dir: workDirFor(sc), HomeDir: image.AgentHome,+ PreserveEnv: true, PathPrepend: image.PathPrepend(), Timeout: sc.Timeout() + time.Minute,+ })+ if err != nil {+ logf("session exec error: %v", err)+ }+ art.Meta["session"] = oneLine(res.Stdout)+ } else {+ logf("running session (budget $%.2f, timeout %s)", sc.Budget(), sc.Timeout())+ var err error+ res, err = p.Exec(ctx, inst, sessionScript(sc, prompt, logPath), sandbox.ExecOpts{+ User: image.AgentUser, Dir: workDirFor(sc), HomeDir: image.AgentHome,+ PreserveEnv: true, PathPrepend: image.PathPrepend(), Timeout: sc.Timeout() + time.Minute,+ })+ if err != nil {+ logf("session exec error: %v", err)+ }+ art.Meta["ci_exec"] = oneLine(res.Stdout)+ // Recorded explicitly so a failing collector is visible in the run metadata rather+ // than inferred from a missing log later.+ art.Meta["ci_exec_rc"] = fmt.Sprintf("%d", res.ExitCode)+ if res.ExitCode != 0 {+ logf("beacon ci exec exited %d -- the collected log may be incomplete", res.ExitCode)+ }}// Claude's own result JSON tells us whether the session itself succeeded, which@@ -550,3 +573,117 @@ func sampleCountOf(verdict string) string {}return "0"}++// doInstall performs a persistent `beacon endpoint install` and returns the runtime log the+// installed collector writes to.+//+// The log path comes from `endpoint status --json` rather than being assumed, because the whole+// point of an install scenario is to check what Beacon actually did — hardcoding the expected+// path would make the scenario agree with itself instead of with Beacon.+func doInstall(ctx context.Context, p sandbox.Provider, inst sandbox.Instance,+ sc scenario.Scenario, agent sandbox.ExecOpts, art *Artifacts, logf func(string, ...any)) (string, error) {++ in := sc.Install+ system := in.Mode == "system"+ scope := "--user"+ if system {+ scope = "--system"+ }+ svc := ""+ if in.Service != "" {+ svc = " --service=" + in.Service+ }+ // System-mode install requires root; user mode must not have it, or the install would+ // write system paths while claiming to be a user install.+ opts := agent+ if system {+ opts = sandbox.ExecOpts{User: "root", Dir: image.WorkDir, Timeout: 5 * time.Minute,+ PathPrepend: image.PathPrepend()}+ }+ art.Meta["install_mode"] = in.Mode+ art.Meta["install_service"] = in.Service++ // Dry run first. It is free, and it is where a plan that advertises the wrong service+ // manager for the host would show up — so a regression there needs no second scenario.+ if r, err := p.Exec(ctx, inst, "beacon endpoint install "+scope+svc+" --harness claude --dry-run 2>&1", opts); err == nil {+ art.Meta["install_dry_run"] = oneLine(r.Stdout)+ logf("dry-run plan: %s", art.Meta["install_dry_run"])+ }++ r, err := p.Exec(ctx, inst, "beacon endpoint install "+scope+svc+" --harness claude 2>&1", opts)+ art.Meta["install_output"] = oneLine(r.Stdout + r.Stderr)+ if err != nil || r.ExitCode != 0 {+ logf("install FAILED rc=%d: %s", r.ExitCode, art.Meta["install_output"])+ return "", fmt.Errorf("endpoint install failed (rc=%d): %s",+ r.ExitCode, oneLine(r.Stdout+r.Stderr))+ }+ logf("install ok: %s", art.Meta["install_output"])++ logPath, err := installedLogPath(ctx, p, inst, scope, opts, in, art, logf)+ if err != nil {+ return "", err+ }+ // Doctor output is recorded whether or not it passes: on a failure it is the first thing+ // worth reading, and it costs one exec.+ if d, err := p.Exec(ctx, inst, "beacon endpoint doctor "+scope+" --json 2>&1", opts); err == nil {+ art.Meta["install_doctor"] = oneLine(d.Stdout)+ }+ return logPath, nil+}++// installedLogPath reads `endpoint status --json` for the service state and log path.+//+// A status that cannot be parsed is not fatal — the run can still proceed against the+// documented default path — but ExpectStatusRunning is enforced, since a scenario asking for a+// running service and silently accepting an unparseable status would verify nothing.+func installedLogPath(ctx context.Context, p sandbox.Provider, inst sandbox.Instance,+ scope string, opts sandbox.ExecOpts, in *scenario.Install, art *Artifacts,+ logf func(string, ...any)) (string, error) {++ s, err := p.Exec(ctx, inst, "beacon endpoint status "+scope+" --json 2>&1", opts)+ if err == nil {+ art.Meta["install_status"] = oneLine(s.Stdout)+ var status struct {+ LogPath string `json:"log_path"`+ Service struct {+ Label string `json:"label"`+ Loaded bool `json:"loaded"`+ Running bool `json:"running"`+ Kind string `json:"kind"`+ Message string `json:"message"`+ } `json:"service"`+ }+ if json.Unmarshal([]byte(s.Stdout), &status) == nil {+ art.Meta["service_kind"] = status.Service.Kind+ art.Meta["service_label"] = status.Service.Label+ art.Meta["service_loaded"] = fmt.Sprintf("%v", status.Service.Loaded)+ art.Meta["service_running"] = fmt.Sprintf("%v", status.Service.Running)+ logf("service: kind=%s label=%s loaded=%v running=%v %s",+ status.Service.Kind, status.Service.Label, status.Service.Loaded,+ status.Service.Running, status.Service.Message)+ if in.ExpectStatusRunning && !status.Service.Running {+ return "", fmt.Errorf("service did not report running after install: %s",+ status.Service.Message)+ }+ if status.LogPath != "" {+ return status.LogPath, nil+ }+ }+ }+ if in.ExpectStatusRunning {+ return "", fmt.Errorf("could not read service status, so a running service cannot be " ++ "confirmed; refusing to report a pass the run did not earn")+ }+ logf("status unparseable; falling back to the documented default log path")+ if in.Mode == "system" {+ return "/var/log/beacon-agent/runtime.jsonl", nil+ }+ return image.AgentHome + "/.beacon/endpoint/logs/runtime.jsonl", nil+}++// plainSessionScript runs the agent with no collector wrapper, for install scenarios where a+// persistent collector is already running as a service.+func plainSessionScript(sc scenario.Scenario, prompt string) string {+ return "claude " + strings.Join(claudeFlags(sc, prompt), " ") ++ " > claude-out.json 2> claude-err.txt; echo CLAUDE_RC=$?"+}diff --git a/beacon-sandbox/scenario/scenario.go b/beacon-sandbox/scenario/scenario.goindex 470b501a..4fad7540 100644--- a/beacon-sandbox/scenario/scenario.go+++ b/beacon-sandbox/scenario/scenario.go@@ -38,10 +38,29 @@ type Expect struct {Why string `yaml:"why,omitempty"`}+// Install describes a persistent `beacon endpoint install` to perform before the session,+// instead of the default ephemeral `beacon ci exec` collector.+//+// This is what exercises the parity surface: service manager selection, unit installation,+// status reporting, and whether a real installed collector actually receives telemetry. A+// scenario without it tests capture through the CI path, which is a different shipping path+// and cannot tell you whether `endpoint install` works at all.+type Install struct {+ // Mode is "user" (default) or "system". System mode runs as root.+ Mode string `yaml:"mode,omitempty"`+ // Service selects the service manager: empty auto-detects, or "systemd" / "none".+ Service string `yaml:"service,omitempty"`+ // ExpectStatusRunning requires the collector service to report running after install.+ ExpectStatusRunning bool `yaml:"expect_status_running,omitempty"`+}+// Scenario is one declarative case.type Scenario struct {ID string `yaml:"id"`Prompt string `yaml:"prompt"`+ // Install, when set, performs a persistent endpoint install and runs the session against+ // it, with no `beacon ci exec` wrapper anywhere.+ Install *Install `yaml:"install,omitempty"`// Sentinel is a path the agent's work must create. Its presence proves the agent// acted; its absence makes the run inconclusive.Sentinel string `yaml:"sentinel,omitempty"`@@ -100,6 +119,22 @@ func (s Scenario) Validate() error {if strings.TrimSpace(e.Action) == "" {return fmt.Errorf("%s: expect[%d] is missing action", s.ID, i)}+ // An unrecognised mode or service would reach the guest as a bad flag and fail mid-run,+ // after a sandbox has already been paid for. Catch it here instead.+ if s.Install != nil {+ switch s.Install.Mode {+ case "", "user", "system":+ default:+ return fmt.Errorf("%s: install.mode %q must be user or system", s.ID, s.Install.Mode)+ }+ switch s.Install.Service {+ case "", "auto", "systemd", "launchd", "none":+ default:+ return fmt.Errorf("%s: install.service %q must be auto, systemd, launchd, or none",+ s.ID, s.Install.Service)+ }+ }+// A setup step that writes the sentinel makes the gate unfalsifiable: the file is present// before the agent runs, so INCONCLUSIVE can never fire and an idle agent is misreported as// a capture failure. s04 shipped with exactly this mistake, so the rule is enforced herediff --git a/beacon-sandbox/scenario/scenario_test.go b/beacon-sandbox/scenario/scenario_test.goindex 3fe4de03..392cd3c7 100644--- a/beacon-sandbox/scenario/scenario_test.go+++ b/beacon-sandbox/scenario/scenario_test.go@@ -315,3 +315,35 @@ func TestSentinelBasenameMatchRespectsPathBoundaries(t *testing.T) {}}}++// An install scenario reaches the guest as CLI flags, so a typo would fail mid-run after a+// sandbox has already been paid for. Validate catches it while it is still free.+func TestInstallModeAndServiceAreValidated(t *testing.T) {+ base := func(in *Install) Scenario {+ return Scenario{ID: "i", Prompt: "do a thing", Install: in,+ Expect: []Expect{{Action: "prompt.submitted", Why: "baseline"}}}+ }+ for _, in := range []*Install{+ {Mode: "systemwide"},+ {Mode: "root"},+ {Service: "launchd2"},+ {Service: "upstart"},+ } {+ if err := base(in).Validate(); err == nil {+ t.Errorf("install %+v must be rejected", in)+ }+ }+ // Every documented spelling must be accepted, including the empty auto-detect default.+ for _, in := range []*Install{+ {},+ {Mode: "user"},+ {Mode: "system", Service: "systemd"},+ {Service: "none"},+ {Service: "auto"},+ {Mode: "user", Service: "launchd", ExpectStatusRunning: true},+ } {+ if err := base(in).Validate(); err != nil {+ t.Errorf("install %+v must be accepted: %v", in, err)+ }+ }+}diff --git a/beacon-sandbox/scenarios/i01-install-supervised.yaml b/beacon-sandbox/scenarios/i01-install-supervised.yamlnew file mode 100644index 00000000..016dadd0--- /dev/null+++ b/beacon-sandbox/scenarios/i01-install-supervised.yaml@@ -0,0 +1,48 @@+id: i01-install-supervised+# Does `beacon endpoint install` actually work, and does an installed collector receive telemetry?+#+# Every s0* scenario collects through `beacon ci exec`, an ephemeral collector that needs no+# service manager. That is a real shipping path, but it cannot tell you whether a persistent+# install works -- and until recently on Linux it did not: preflight refused before writing+# anything, and Load/Restart silently returned nil so an install could report success while+# starting nothing.+#+# This installs for real, then runs a plain `claude` session against the installed collector with+# no wrapper anywhere. In a gVisor sandbox PID 1 is not systemd, so this exercises the supervised+# backend -- the fallback for containers. The systemd path is covered separately, because systemd+# cannot be PID 1 here.+#+# What this proves that s01-s07 cannot: config written where Beacon says it did, a service that+# reports itself running, and a persistent collector receiving OTLP on loopback.+install:+ mode: user+ service: none+ expect_status_running: true++prompt: >-+ Run exactly this shell command and report its output: echo {{canary}} | tee {{sentinel}}+sentinel: /home/agent/work/i01.sentinel+budget_usd: 1.0+timeout_seconds: 420++expect:+ - action: prompt.submitted+ contains: ["{{canary}}"]+ fields: ["prompt.text", "session.id", "harness.name"]+ why: >-+ Telemetry reaching a persistently installed collector is the whole point of this scenario.+ If this fails, install wrote files but the collector is not receiving OTLP.++ - action: token.usage+ fields: ["gen_ai.usage.input_tokens", "model"]+ why: >-+ Confirms the metrics pipeline works through an installed collector and not only through the+ CI one, which is a separate code path.++ - action: command.executed+ contains: ["{{canary}}"]+ fields: ["command.command"]+ why: >-+ The same detection surface s02 protects, checked through the install path. Keeping it+ non-optional means the installed collector is never allowed to look healthier than the CI+ one for the same telemetry.diff --git a/cli/beacon/cmd/endpoint.go b/cli/beacon/cmd/endpoint.goindex 0270ffa4..6b80e040 100644--- a/cli/beacon/cmd/endpoint.go+++ b/cli/beacon/cmd/endpoint.go@@ -394,7 +394,7 @@ func init() {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().BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths and the system collector service")c.Flags().StringVar(&endpointOpts.logPath, "log-path", "", "Runtime JSONL log path")}@@ -427,7 +427,7 @@ func init() {registerSplunkFlags(endpointRepairCmd)registerFalconFlags(endpointRepairCmd)endpointDashboardCmd.Flags().BoolVar(&endpointOpts.userMode, "user", true, "Use per-user endpoint paths")- endpointDashboardCmd.Flags().BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths and launch daemon")+ endpointDashboardCmd.Flags().BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths and the system collector service")endpointDashboardCmd.Flags().StringVar(&endpointOpts.logPath, "log-path", "", "Runtime JSONL log path")endpointDashboardCmd.Flags().StringVar(&endpointOpts.dashboardAddr, "addr", dashboard.DefaultAddr, "Local dashboard listen address")endpointDashboardCmd.Flags().BoolVar(&endpointOpts.dashboardOpen, "open", false, "Open the dashboard in a browser")@@ -468,7 +468,7 @@ func init() {endpointIntegrationsValidateCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print validation as JSON")for _, c := range []*cobra.Command{endpointCoworkPrintConfigCmd, endpointCoworkSetupCmd, endpointCoworkStatusCmd, endpointCoworkValidateCmd} {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().BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths and the system collector service")c.Flags().StringVar(&endpointOpts.logPath, "log-path", "", "Runtime JSONL log path")}endpointCoworkPrintConfigCmd.Flags().StringVar(&endpointOpts.coworkHeaders, "headers", "", "Optional OTLP headers to show in setup guidance")@@ -486,7 +486,7 @@ func init() {endpointCoworkStatusCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print status as JSON")for _, c := range []*cobra.Command{endpointOpenClawPrintConfigCmd, endpointOpenClawStatusCmd, endpointOpenClawValidateCmd} {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().BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths and the system collector service")c.Flags().StringVar(&endpointOpts.logPath, "log-path", "", "Runtime JSONL log path")}endpointOpenClawPrintConfigCmd.Flags().StringVar(&endpointOpts.openClawEndpoint, "endpoint", "", "OTLP HTTP endpoint to show in setup guidance")@@ -495,7 +495,7 @@ func init() {endpointOpenClawStatusCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print status as JSON")for _, c := range []*cobra.Command{endpointVSCodePrintConfigCmd, endpointVSCodeSetupCmd, endpointVSCodeStatusCmd, endpointVSCodeValidateCmd} {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().BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths and the system collector service")c.Flags().StringVar(&endpointOpts.logPath, "log-path", "", "Runtime JSONL log path")c.Flags().StringVar(&endpointOpts.vscodeEndpoint, "endpoint", "", "OTLP HTTP endpoint for VS Code Copilot")c.Flags().StringVar(&endpointOpts.vscodeWorkspace, "workspace", "", "Workspace path for .vscode/settings.json")@@ -506,13 +506,13 @@ func init() {endpointVSCodeStatusCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print status as JSON")for _, c := range []*cobra.Command{endpointHooksInstallCmd, endpointHooksUninstallCmd, endpointHooksStatusCmd} {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().BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths and the system collector service")c.Flags().StringVar(&endpointOpts.logPath, "log-path", "", "Runtime JSONL log path")c.Flags().StringVar(&endpointOpts.hookHarnesses, "harness", "cursor", "Comma-separated hook harnesses")c.Flags().StringVar(&endpointOpts.hookLevel, "level", "user", "Hook install level: user or project")}endpointHooksRepairInstalledCmd.Flags().BoolVar(&endpointOpts.userMode, "user", true, "Use per-user endpoint paths")- endpointHooksRepairInstalledCmd.Flags().BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths and launch daemon")+ endpointHooksRepairInstalledCmd.Flags().BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths and the system collector service")endpointHooksRepairInstalledCmd.Flags().StringVar(&endpointOpts.logPath, "log-path", "", "Runtime JSONL log path")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")diff --git a/cli/beacon/cmd/endpoint_destinations.go b/cli/beacon/cmd/endpoint_destinations.goindex 5f79503b..2c28caf5 100644--- a/cli/beacon/cmd/endpoint_destinations.go+++ b/cli/beacon/cmd/endpoint_destinations.go@@ -427,7 +427,7 @@ func buildDestinationGroup(d siemDestination) *cobra.Command {// shared by every destination subcommand.func addEndpointPathFlags(cmd *cobra.Command) {cmd.Flags().BoolVar(&endpointOpts.userMode, "user", true, "Use per-user endpoint paths")- cmd.Flags().BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths and launch daemon")+ cmd.Flags().BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths and the system collector service")cmd.Flags().StringVar(&endpointOpts.logPath, "log-path", "", "Runtime JSONL log path")}diff --git a/cli/beacon/cmd/endpoint_diagnostics.go b/cli/beacon/cmd/endpoint_diagnostics.goindex 7749aa92..42f0f20c 100644--- a/cli/beacon/cmd/endpoint_diagnostics.go+++ b/cli/beacon/cmd/endpoint_diagnostics.go@@ -7,7 +7,6 @@ import ("fmt""os""path/filepath"- "runtime""strings""time"@@ -793,17 +792,10 @@ func plannedInstallActions(repair bool, kind service.Kind) []plannedAction {// announced a launchd plist on every platform without consulting GOOS, so a Linux// --dry-run advertised steps that could not execute.mgr := service.Manager{UserMode: cfg.UserMode, Kind: kind}- serviceAction := plannedAction{Action: "write_unit", Message: "launchd service definition"}+ serviceAction := plannedAction{Action: "write_unit", Message: mgr.ResolvedKind().ServiceNoun()}if unitPath, err := mgr.UnitPath(); err == nil {serviceAction.Target = unitPath}- switch mgr.ResolvedKind() {- case service.KindSystemd:- serviceAction.Message = "systemd unit definition"- case service.KindSupervised:- serviceAction.Message = "supervised collector state (no service manager on this host)"- }-actions = append(actions,plannedAction{Action: "write_file", Target: cfg.Collector.ConfigPath, Message: "collector configuration"},serviceAction,@@ -1143,12 +1135,23 @@ func planDoctorFixes(result doctorResult, status lifecycle.Status) doctorFixPlan} else if check.Evidence == "last_event_missing" {addSkip(plannedAction{Action: "manual_fix", Target: check.Target, Message: "run beacon endpoint test-event or generate a runtime event"})}- case "collector_config", "launchd_plist", "collector_health", "collector_reachability", "service":- if runtime.GOOS != "darwin" {- addSkip(plannedAction{Action: "repair_collector_service", Target: endpointconfig.ConfigPath(status.RuntimeLog.EffectiveUserMode), Message: "launchd service repair is only available on macOS"})- } else if configUsable {- addFix(plannedAction{Action: "repair_collector_service", Target: endpointconfig.ConfigPath(status.RuntimeLog.EffectiveUserMode), Message: "recreate managed collector config and launchd service"})- } else {+ // systemd_unit belongs here alongside launchd_plist: diagnostics emits whichever the+ // resolved backend uses, and omitting it meant a broken systemd unit produced neither a+ // fix nor a skip -- it fell through the switch and was silently unreported.+ //+ // The repair itself is platform-neutral (repairCollectorServiceFromStatus goes through+ // UnitPath/WriteUnit), so the check is whether a service manager is usable here rather+ // than what the OS is called. The old GOOS gate additionally printed "launchd service+ // repair is only available on macOS", which stopped being true when systemd support+ // landed.+ case "collector_config", "launchd_plist", "systemd_unit", "collector_health", "collector_reachability", "service":+ mgr := service.Manager{UserMode: status.RuntimeLog.EffectiveUserMode}+ switch {+ case !mgr.Available():+ addSkip(plannedAction{Action: "repair_collector_service", Target: endpointconfig.ConfigPath(status.RuntimeLog.EffectiveUserMode), Message: mgr.UnsupportedReason()})+ case configUsable:+ addFix(plannedAction{Action: "repair_collector_service", Target: endpointconfig.ConfigPath(status.RuntimeLog.EffectiveUserMode), Message: "recreate managed collector config and " + mgr.ResolvedKind().ServiceNoun()})+ default:addSkip(plannedAction{Action: "repair_collector_service", Target: endpointconfig.ConfigPath(status.RuntimeLog.EffectiveUserMode), Message: "skipped because endpoint config is invalid"})}case "config", "config_valid":diff --git a/cli/beacon/cmd/ingest.go b/cli/beacon/cmd/ingest.goindex 7e8d90b9..a9ee3e51 100644--- a/cli/beacon/cmd/ingest.go+++ b/cli/beacon/cmd/ingest.go@@ -85,7 +85,7 @@ func init() {for _, c := range []*cobra.Command{ingestStatusCmd, ingestEndpointStatusCmd, ingestEndpointUploadCmd} {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().BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths and the system collector service")c.Flags().StringVar(&endpointOpts.logPath, "log-path", "", "Runtime JSONL log path")c.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print output as JSON")}diff --git a/cli/beacon/cmd/token_usage.go b/cli/beacon/cmd/token_usage.goindex 7fe38577..d401b3bd 100644--- a/cli/beacon/cmd/token_usage.go+++ b/cli/beacon/cmd/token_usage.go@@ -92,7 +92,7 @@ func runTokenUsage(cmd *cobra.Command, args []string) error {func init() {rootCmd.AddCommand(tokenUsageCmd)tokenUsageCmd.Flags().BoolVar(&tokenUsageOpts.userMode, "user", true, "Use per-user endpoint paths")- tokenUsageCmd.Flags().BoolVar(&tokenUsageOpts.systemMode, "system", false, "Use system endpoint paths and launch daemon")+ tokenUsageCmd.Flags().BoolVar(&tokenUsageOpts.systemMode, "system", false, "Use system endpoint paths and the system collector service")tokenUsageCmd.Flags().StringVar(&tokenUsageOpts.logPath, "log-path", "", "Runtime JSONL log path (defaults to the local runtime log; in CI point at the session log)")tokenUsageCmd.Flags().BoolVar(&tokenUsageOpts.jsonOutput, "json", false, "Print the token usage report as JSON")tokenUsageCmd.Flags().StringVar(&tokenUsageOpts.since, "since", "", "Only include events at or after this RFC3339 timestamp")diff --git a/cli/beacon/internal/endpoint/diagnostics/diagnostics.go b/cli/beacon/internal/endpoint/diagnostics/diagnostics.goindex ea3fffd5..56e5c9f6 100644--- a/cli/beacon/internal/endpoint/diagnostics/diagnostics.go+++ b/cli/beacon/internal/endpoint/diagnostics/diagnostics.go@@ -3,6 +3,7 @@ package diagnosticsimport ("fmt""os"+ "os/user""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/collector"endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"@@ -52,10 +53,33 @@ func Run(cfg endpointconfig.Config) []Check {if path, err := mgr.UnitPath(); err == nil {checks = append(checks, checkFile("systemd_unit", path, true))}+ // A --user unit stops at logout unless linger is set, and that failure is invisible+ // until the user next logs out and telemetry quietly stops. Surfaced as a warning+ // rather than a failure: collecting until logout is degraded, not broken.+ if cfg.UserMode {+ checks = append(checks, lingerCheck())+ }}return checks}+func lingerCheck() Check {+ u, err := user.Current()+ if err != nil || u.Username == "" {+ return Check{Name: "systemd_user_linger", Status: StatusWarn,+ Message: "could not determine the current user, so logout persistence is unverified",+ Evidence: "linger_unknown"}+ }+ if service.LingerEnabled(u.Username) {+ return Check{Name: "systemd_user_linger", Status: StatusOK, Target: u.Username,+ Message: "user unit will survive logout"}+ }+ return Check{Name: "systemd_user_linger", Status: StatusWarn, Target: u.Username,+ Message: "linger is not enabled, so the collector stops when this user logs out",+ Evidence: "linger_disabled",+ Action: "sudo loginctl enable-linger " + u.Username}+}+func checkCollectorHealth(cfg endpointconfig.Config) Check {status := collector.CheckStatus(cfg)if status.HealthReady {diff --git a/cli/beacon/internal/endpoint/inventory/skills.go b/cli/beacon/internal/endpoint/inventory/skills.goindex f90df632..e3a075b2 100644--- a/cli/beacon/internal/endpoint/inventory/skills.go+++ b/cli/beacon/internal/endpoint/inventory/skills.go@@ -10,18 +10,18 @@ import (const maxSkillsPerRoot = 200type Skill struct {- Runtime string `json:"runtime"`- SkillName string `json:"skill_name,omitempty"`- SkillNameHash string `json:"skill_name_hash,omitempty"`- RootPath string `json:"root_path,omitempty"`- RootPathHash string `json:"root_path_hash,omitempty"`- SourceScope string `json:"source_scope"`- ManifestPath string `json:"manifest_path,omitempty"`- ManifestPathHash string `json:"manifest_path_hash,omitempty"`- Exists bool `json:"exists"`- Readable bool `json:"readable"`- Reason string `json:"reason,omitempty"`- ParserStatus string `json:"parser_status"`+ Runtime string `json:"runtime"`+ SkillName string `json:"skill_name,omitempty"`+ SkillNameHash string `json:"skill_name_hash,omitempty"`+ RootPath string `json:"root_path,omitempty"`+ RootPathHash string `json:"root_path_hash,omitempty"`+ SourceScope string `json:"source_scope"`+ ManifestPath string `json:"manifest_path,omitempty"`+ ManifestPathHash string `json:"manifest_path_hash,omitempty"`+ Exists bool `json:"exists"`+ Readable bool `json:"readable"`+ Reason string `json:"reason,omitempty"`+ ParserStatus string `json:"parser_status"`FileSHA256 string `json:"file_sha256,omitempty"`ModifiedAt string `json:"modified_at,omitempty"`Redaction string `json:"redaction"`diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.goindex be371fab..09b22bef 100644--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go@@ -111,6 +111,11 @@ type Manifest struct {HarnessConfigs []string `json:"harness_configs,omitempty"`ServiceLabel string `json:"service_label"`LogPath string `json:"log_path"`+ // LingerEnabled and LingerDetail record whether a systemd --user unit was made to survive+ // logout. Recorded rather than silently attempted, so status and doctor can report the gap+ // instead of the user discovering it after their next logout. Absent on other backends.+ LingerEnabled bool `json:"linger_enabled,omitempty"`+ LingerDetail string `json:"linger_detail,omitempty"`}type fileSnapshot struct {@@ -218,6 +223,18 @@ func Install(opts InstallOptions) (InstallResult, error) {return InstallResult{}, err}tx.ServiceLoaded = true+ // A systemd --user unit is torn down when the user logs out unless linger is set, so+ // without this a user-mode install silently stops collecting at logout. launchd has no+ // equivalent: its gui/<uid> domain persists for the login session on its own.+ //+ // Best-effort and non-fatal: enabling linger needs privileges a plain user may not+ // have, and refusing to install over it would be worse than collecting until logout.+ // The outcome is recorded so status and doctor can report the gap rather than leaving+ // the user to discover it after their next logout.+ if ok, detail := manager.EnableLingerIfNeeded(); detail != "" {+ manifest.LingerEnabled = ok+ manifest.LingerDetail = detail+ }if err := endpointcollector.WaitUntilReady(cfg, 10*time.Second); err != nil {tx.Rollback(manifest)return InstallResult{}, err@@ -600,7 +617,7 @@ func preflight(cfg endpointconfig.Config, startService bool, kind service.Kind)if grpcAvailable && httpAvailable {return nil}- if existingCollectorReady(cfg) {+ if existingCollectorReady(cfg, kind) {return nil}if err := endpointcollector.WaitForPortsAvailable(cfg.Collector.GRPCPort, cfg.Collector.HTTPPort, 10*time.Second); err != nil {@@ -609,8 +626,11 @@ func preflight(cfg endpointconfig.Config, startService bool, kind service.Kind)return nil}-func existingCollectorReady(cfg endpointconfig.Config) bool {- if !(service.Manager{UserMode: cfg.UserMode}).Status().Loaded {+// The kind is threaded through rather than re-detected: preflight already honours an explicit+// --service=, and auto-detecting here would consult a different backend than the one the install+// is about to use.+func existingCollectorReady(cfg endpointconfig.Config, kind service.Kind) bool {+ if !(service.Manager{UserMode: cfg.UserMode, Kind: kind}).Status().Loaded {return false}status := endpointcollector.CheckStatus(cfg)diff --git a/cli/beacon/internal/endpoint/selfupdate/mode.go b/cli/beacon/internal/endpoint/selfupdate/mode.goindex 09aee851..c4ca03f4 100644--- a/cli/beacon/internal/endpoint/selfupdate/mode.go+++ b/cli/beacon/internal/endpoint/selfupdate/mode.go@@ -29,7 +29,9 @@ const AutoUpdateEnv = "BEACON_AUTO_UPDATE"// ManagedConfigPath is where an MDM/enterprise profile can drop settings that// override the local config (but not an explicit env override).-var ManagedConfigPath = filepath.Join(SystemSupportDir, "managed.json")+// ManagedConfigPath is the MDM-dropped override. A var so tests can redirect it, but computed+// through SystemSupportDir() so it is correct per platform rather than fixed at macOS.+var ManagedConfigPath = filepath.Join(SystemSupportDir(), "managed.json")// ParseMode normalizes a mode string. It accepts the canonical values plus the// legacy boolean forms (1/true/on => auto, 0/false/off/no => off).diff --git a/cli/beacon/internal/endpoint/selfupdate/selfupdate.go b/cli/beacon/internal/endpoint/selfupdate/selfupdate.goindex 42cf6e35..2dc3f67e 100644--- a/cli/beacon/internal/endpoint/selfupdate/selfupdate.go+++ b/cli/beacon/internal/endpoint/selfupdate/selfupdate.go@@ -5,20 +5,27 @@package selfupdateimport (+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config""os""path/filepath""strings")-// SystemInstallDir is where the signed macOS .pkg installs Beacon.+// SystemInstallDir is where a native package installs Beacon. Shared by the macOS .pkg and the+// Linux .deb/.rpm, so classifyInstall recognises both as a system install.const (SystemInstallDir = "/opt/beacon"SystemBinDir = "/opt/beacon/bin"- // SystemSupportDir holds endpoint config and self-update state for the- // system install.- SystemSupportDir = "/Library/Application Support/Beacon/Endpoint")+// SystemSupportDir holds endpoint config and self-update state for the system install.+//+// A function rather than a const, because the location differs by platform:+// /Library/Application Support/... on macOS, /etc/beacon/endpoint on Linux. It was previously+// hardcoded to the macOS path, so on Linux the update state directory and the managed-config+// path both resolved somewhere that does not exist.+func SystemSupportDir() string { return endpointconfig.SystemBaseDir() }+// InstallKind classifies how the running beacon binary was installed, which// determines whether seamless self-update is possible.type InstallKind string@@ -87,7 +94,7 @@ func isHomebrewPath(path string) bool {// StateDir is where the updater stores its lock, staged packages, and state// for the system install.func StateDir() string {- return filepath.Join(SystemSupportDir, "updates")+ return filepath.Join(SystemSupportDir(), "updates")}// SystemBeaconPath is the installed beacon binary the launchd updater invokes.diff --git a/cli/beacon/internal/endpoint/service/service.go b/cli/beacon/internal/endpoint/service/service.goindex 59acaf02..d24830e6 100644--- a/cli/beacon/internal/endpoint/service/service.go+++ b/cli/beacon/internal/endpoint/service/service.go@@ -15,6 +15,7 @@ package serviceimport ("fmt""os"+ "os/user""path/filepath""runtime""strings"@@ -64,6 +65,43 @@ func ParseKind(s string) (Kind, error) {}}+// EnableLingerIfNeeded makes a systemd --user unit survive logout, where that applies.+//+// Returns ("", ) for every other case -- system mode, and every backend but systemd -- so the+// caller records nothing rather than reporting a step that was never relevant. launchd needs no+// equivalent: its gui/<uid> domain persists for the login session by itself.+func (m Manager) EnableLingerIfNeeded() (bool, string) {+ if !m.UserMode || m.resolvedKind() != KindSystemd {+ return false, ""+ }+ u, err := user.Current()+ if err != nil || u.Username == "" {+ return false, "could not determine the current user, so logout persistence is unverified"+ }+ if LingerEnabled(u.Username) {+ return true, "linger already enabled for " + u.Username+ }+ return EnableLinger(u.Username)+}++// ServiceNoun names what this backend installs, for user-facing messages.+//+// Shared rather than duplicated: the install planner and the doctor fix planner both describe+// the same artifact, and the codebase already had several independently hardcoded copies of+// macOS-specific wording that had to be hunted down when systemd support landed.+func (k Kind) ServiceNoun() string {+ switch k {+ case KindLaunchd:+ return "launchd service definition"+ case KindSystemd:+ return "systemd unit definition"+ case KindSupervised:+ return "supervised collector state (no service manager on this host)"+ default:+ return "collector service definition"+ }+}+// Manager controls the collector service.type Manager struct {UserMode booldiff --git a/cli/beacon/internal/endpoint/service/service_test.go b/cli/beacon/internal/endpoint/service/service_test.goindex 086510d1..a61a438e 100644--- a/cli/beacon/internal/endpoint/service/service_test.go+++ b/cli/beacon/internal/endpoint/service/service_test.go@@ -549,3 +549,50 @@ func TestDetectKindMatchesHost(t *testing.T) {}}}++// Linger is the one behavior with no launchd counterpart: a systemd --user unit is torn down at+// logout unless it is set, so a user-mode install silently stops collecting. EnableLinger and+// LingerEnabled existed but had zero callers, which meant every user-mode systemd install+// inherited exactly that bug. These pin the wrapper that now invokes them.+func TestEnableLingerIfNeededOnlyAppliesToSystemdUserUnits(t *testing.T) {+ // Not applicable: nothing should be attempted or reported, so the caller records nothing.+ for _, m := range []Manager{+ {UserMode: false, Kind: KindSystemd}, // system units are not session-scoped+ {UserMode: true, Kind: KindLaunchd}, // gui/<uid> persists on its own+ {UserMode: true, Kind: KindSupervised},+ {UserMode: false, Kind: KindLaunchd},+ } {+ ok, detail := m.EnableLingerIfNeeded()+ if ok || detail != "" {+ t.Errorf("%+v should not attempt linger, got ok=%v detail=%q", m, ok, detail)+ }+ }+}++// The applicable case must actually report something, or the manifest and doctor would have+// nothing to show and the gap would stay invisible.+func TestEnableLingerIfNeededReportsForSystemdUserUnits(t *testing.T) {+ _, detail := (Manager{UserMode: true, Kind: KindSystemd}).EnableLingerIfNeeded()+ if detail == "" {+ t.Error("a systemd user unit must report a linger outcome, whether or not it succeeded")+ }+}++// The noun is shared by the install planner and the doctor fix planner. Duplicating it is how+// macOS-specific wording survived into the Linux paths in the first place.+func TestServiceNounNamesEachBackend(t *testing.T) {+ cases := map[Kind]string{+ KindLaunchd: "launchd",+ KindSystemd: "systemd",+ KindSupervised: "supervised",+ }+ for k, want := range cases {+ if got := k.ServiceNoun(); !strings.Contains(got, want) {+ t.Errorf("%s noun = %q, want it to mention %q", k, got, want)+ }+ }+ // An unknown kind must still describe something rather than returning empty.+ if Kind("weird").ServiceNoun() == "" {+ t.Error("an unrecognised kind must still yield a description")+ }+}