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
fix(endpoint): report linger from logind state, not from loginctl's exit code
Claudebf372ca1228c
diff --git a/cli/beacon/cmd/endpoint_install.go b/cli/beacon/cmd/endpoint_install.goindex ef1c8139..7e091ab1 100644--- a/cli/beacon/cmd/endpoint_install.go+++ b/cli/beacon/cmd/endpoint_install.go@@ -3,6 +3,7 @@ package cmdimport ("encoding/json""fmt"+ "io""os""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/dashboard"@@ -128,6 +129,7 @@ func runEndpointInstall(cmd *cobra.Command, args []string) error {fmt.Printf("Service definition written to %s\n", result.PlistPath)fmt.Printf("Install manifest written to %s\n", result.ManifestPath)fmt.Printf("Runtime log: %s\n", result.LogPath)+ printLingerGap(cmd.ErrOrStderr(), result)if err := installHookTargetsFromEndpointInstall(hookHarnesses); err != nil {return fmt.Errorf("endpoint install completed, but hook installation failed: %w", err)}@@ -270,12 +272,37 @@ func runEndpointRepair(cmd *cobra.Command, args []string) error {return err}fmt.Printf("Endpoint repaired. Manifest: %s\n", result.ManifestPath)+ printLingerGap(cmd.ErrOrStderr(), result)if err := installHookTargetsFromEndpointInstall(hookHarnesses); err != nil {return fmt.Errorf("endpoint repair completed, but hook installation failed: %w", err)}return nil}+// printLingerGap says so when the collector is running but will not outlive this login session.+//+// Install used to print an unbroken run of success lines here even when the systemd --user unit+// had no linger, so the user learned about it at their next logout, with collection already+// stopped. The headline is chosen by whether a remediation is known rather than by inspecting+// the detail text: a known-off linger gets the fact and the exact command, and an unverifiable+// one is reported as unverified instead of asserted as broken.+func printLingerGap(out io.Writer, result lifecycle.InstallResult) {+ if !result.LingerApplicable || result.LingerEnabled {+ return+ }+ if result.LingerRemediation == "" {+ fmt.Fprintln(out, "Warning: could not verify that collection survives logout.")+ } else {+ fmt.Fprintln(out, "Warning: the collector is running, but collection will stop when this user logs out.")+ }+ if result.LingerDetail != "" {+ fmt.Fprintf(out, "Detail: %s\n", result.LingerDetail)+ }+ if result.LingerRemediation != "" {+ fmt.Fprintf(out, "To keep collecting after logout, run: %s\n", result.LingerRemediation)+ }+}+func installHookTargetsFromEndpointInstall(targets []string) error {if len(targets) == 0 {return nildiff --git a/cli/beacon/cmd/endpoint_install_linger_test.go b/cli/beacon/cmd/endpoint_install_linger_test.gonew file mode 100644index 00000000..c04a3c1b--- /dev/null+++ b/cli/beacon/cmd/endpoint_install_linger_test.go@@ -0,0 +1,101 @@+package cmd++import (+ "bytes"+ "strings"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"+)++// The reported Linux install printed an unbroken run of success lines while the collector had no+// logout persistence, so the user found out at their next logout with collection already stopped.+// These pin what install and repair now say instead -- and, just as importantly, when they stay+// quiet, because a logout warning on a backend that has no such concept is its own bug.+func TestPrintLingerGapSaysNothingWhenThereIsNoGap(t *testing.T) {+ for _, tc := range []struct {+ name string+ result lifecycle.InstallResult+ }{+ {+ // launchd, system mode, the supervised backend, and any --no-start install: linger+ // is not a question, so there is nothing to warn about.+ name: "not applicable",+ result: lifecycle.InstallResult{},+ },+ {+ // Applicable and satisfied. The install is fully persistent; saying so again here+ // would just be noise in a transcript that already reported success.+ name: "already enabled",+ result: lifecycle.InstallResult{LingerApplicable: true, LingerEnabled: true, LingerDetail: "linger already enabled for someone"},+ },+ {+ // A detail is recorded on the success path too. It belongs in the manifest, not in+ // a warning that has nothing to warn about.+ name: "enabled during this install",+ result: lifecycle.InstallResult{LingerApplicable: true, LingerEnabled: true, LingerDetail: "linger enabled for someone"},+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ var out bytes.Buffer+ printLingerGap(&out, tc.result)+ if out.Len() != 0 {+ t.Errorf("printLingerGap wrote %q, want silence", out.String())+ }+ })+ }+}++// The gap the feedback was about: running now, not running after logout. The user should not have+// to know what linger is, or go find the command themselves.+func TestPrintLingerGapNamesTheGapAndTheFix(t *testing.T) {+ var out bytes.Buffer+ printLingerGap(&out, lifecycle.InstallResult{+ LingerApplicable: true,+ LingerDetail: "linger is disabled for someone; enabling it needs administrator approval",+ LingerRemediation: "sudo loginctl enable-linger someone",+ })+ got := out.String()++ for _, want := range []string{+ // What is wrong, in terms of what the user loses rather than which flag is unset.+ "logs out",+ // Why, kept verbatim from the outcome so the reason is never paraphrased away.+ "administrator approval",+ // The exact command, copy-pasteable, no placeholder left to substitute.+ "sudo loginctl enable-linger someone",+ } {+ if !strings.Contains(got, want) {+ t.Errorf("output should mention %q, got:\n%s", want, got)+ }+ }+ // It is a warning about a degraded install, not a failure: the collector is running.+ if !strings.Contains(got, "collector is running") {+ t.Errorf("output should say the collector is running, got:\n%s", got)+ }+}++// The unverifiable case: os/user could not name the current user, so the linger state was never+// read. Claiming collection will stop would be asserting something unknown, and printing a+// remediation would name a user this code could not resolve.+func TestPrintLingerGapReportsAnUnverifiedStateAsUnverified(t *testing.T) {+ var out bytes.Buffer+ printLingerGap(&out, lifecycle.InstallResult{+ LingerApplicable: true,+ LingerDetail: "could not determine the current user, so logout persistence is unverified",+ })+ got := out.String()++ if !strings.Contains(got, "could not verify") {+ t.Errorf("output should report the state as unverified, got:\n%s", got)+ }+ if strings.Contains(got, "will stop") {+ t.Errorf("an unverified state must not be asserted as broken, got:\n%s", got)+ }+ if strings.Contains(got, "loginctl") {+ t.Errorf("no fix should be offered for a user this code could not resolve, got:\n%s", got)+ }+ if !strings.Contains(got, "unverified") {+ t.Errorf("output should carry the recorded detail, got:\n%s", got)+ }+}diff --git a/cli/beacon/internal/endpoint/diagnostics/diagnostics.go b/cli/beacon/internal/endpoint/diagnostics/diagnostics.goindex 0083f8a2..e330e6e4 100644--- a/cli/beacon/internal/endpoint/diagnostics/diagnostics.go+++ b/cli/beacon/internal/endpoint/diagnostics/diagnostics.go@@ -80,7 +80,7 @@ func lingerCheck() Check {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}+ Action: service.LingerRemediation(u.Username)}}func checkCollectorHealth(cfg endpointconfig.Config) Check {diff --git a/cli/beacon/internal/endpoint/diagnostics/diagnostics_test.go b/cli/beacon/internal/endpoint/diagnostics/diagnostics_test.goindex c46156bd..870c76d9 100644--- a/cli/beacon/internal/endpoint/diagnostics/diagnostics_test.go+++ b/cli/beacon/internal/endpoint/diagnostics/diagnostics_test.go@@ -2,6 +2,7 @@ package diagnosticsimport ("os"+ "os/user""path/filepath""testing"@@ -164,3 +165,27 @@ func servicePlistPathForTest(userMode bool) string {}return path}++// Install, repair, and doctor all tell the user how to give the collector logout persistence, and+// the user should get the same command from each. They used to write it out independently, which+// is how a command meant for copy-and-paste drifts between the places that print it.+func TestLingerCheckOffersTheSharedRemediation(t *testing.T) {+ u, err := user.Current()+ if err != nil || u.Username == "" {+ t.Skip("needs a resolvable current user")+ }+ check := lingerCheck()+ if check.Status == StatusOK {+ // Linger is already on for this user, so there is nothing to remediate.+ if check.Action != "" {+ t.Errorf("an enabled linger needs no action, got %q", check.Action)+ }+ return+ }+ if check.Evidence == "linger_unknown" {+ t.Skip("linger state is unverifiable on this host")+ }+ if want := service.LingerRemediation(u.Username); check.Action != want {+ t.Errorf("doctor action = %q, want the shared remediation %q", check.Action, want)+ }+}diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.goindex 31066d9c..1a592d7c 100644--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go@@ -66,6 +66,13 @@ type InstallResult struct {LogPath string `json:"log_path"`ManifestPath string `json:"manifest_path"`HarnessConfigPaths []string `json:"harness_config_paths,omitempty"`+ // The linger fields report the optional logout-persistence step, so a caller can tell a+ // fully persistent install from one that collects only until this user logs out. Flat rather+ // than nested, matching how Manifest already records the same outcome.+ LingerApplicable bool `json:"linger_applicable,omitempty"`+ LingerEnabled bool `json:"linger_enabled,omitempty"`+ LingerDetail string `json:"linger_detail,omitempty"`+ LingerRemediation string `json:"linger_remediation,omitempty"`}type Status struct {@@ -279,6 +286,9 @@ func Install(opts InstallOptions) (InstallResult, error) {tx.Rollback(manifest)return InstallResult{}, err}+ // Declared out here so the outcome survives the StartService block and reaches the result.+ // A --no-start install never reaches the attempt, and reports the zero value: not applicable.+ var lingerOutcome service.LingerOutcomeif opts.StartService {// Restart when something is already running, rather than Load.//@@ -317,9 +327,10 @@ func Install(opts InstallOptions) (InstallResult, error) {// 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+ lingerOutcome = manager.EnableLingerIfNeeded()+ if lingerOutcome.Applicable {+ manifest.LingerEnabled = lingerOutcome.Enabled+ manifest.LingerDetail = lingerOutcome.Detail}if err := endpointcollector.WaitUntilReady(cfg, 10*time.Second); err != nil {tx.Rollback(manifest)@@ -352,6 +363,10 @@ func Install(opts InstallOptions) (InstallResult, error) {LogPath: cfg.LogPath,ManifestPath: manifestPath,HarnessConfigPaths: harnessPaths,+ LingerApplicable: lingerOutcome.Applicable,+ LingerEnabled: lingerOutcome.Enabled,+ LingerDetail: lingerOutcome.Detail,+ LingerRemediation: lingerOutcome.Remediation,}, nil}diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle_test.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle_test.goindex f69ee3e5..858099b6 100644--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle_test.go+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle_test.go@@ -578,6 +578,12 @@ func TestInstallUserModeWithoutStartingService(t *testing.T) {if len(result.HarnessConfigPaths) != 0 {t.Fatalf("unexpected harness config paths: %#v", result.HarnessConfigPaths)}+ // Linger is only ever attempted as part of starting the service, so a --no-start install has+ // not learned anything about logout persistence. Reporting it as applicable-and-off would put+ // a logout warning on an install that never started a collector to lose.+ if result.LingerApplicable || result.LingerEnabled || result.LingerDetail != "" || result.LingerRemediation != "" {+ t.Errorf("a --no-start install should report no linger outcome, got %+v", result)+ }}func TestInstallFailsBeforeWritingArtifactsWhenCollectorMissing(t *testing.T) {diff --git a/cli/beacon/internal/endpoint/service/linger_test.go b/cli/beacon/internal/endpoint/service/linger_test.gonew file mode 100644index 00000000..e8547065--- /dev/null+++ b/cli/beacon/internal/endpoint/service/linger_test.go@@ -0,0 +1,274 @@+package service++import (+ "errors"+ "os/user"+ "strings"+ "testing"+)++// Linger is the one install step whose reported result used to be inferred from the wrong signal.+// `loginctl enable-linger` can exit non-zero because a helper it spawned is missing while the+// enable itself lands, and it can exit zero without the state changing. What the user cares about+// is whether the collector survives logout, so these drive both signals independently and pin the+// outcome to the state read back from logind.+//+// Everything here is deterministic: loginctl is a stub and the systemd gate is stubbed, so the+// same branches run on macOS, on a Linux container without systemd, and on a systemd host,+// without touching the host's real logind state.++// fakeLoginctl replaces the loginctl runner and the systemd gate for one test.+//+// The linger field is read and written by the stub the way logind would: `show-user` reports it, and+// `enable-linger` sets it only when enableSets says the call actually took effect. That+// separation is the whole point -- it lets a test express "the command failed but linger is on"+// and "the command succeeded but linger is off", which are the two cases the old exit-code+// reading got wrong.+type fakeLoginctl struct {+ linger bool+ enableSets bool+ enableOut string+ enableErr error+ calls [][]string+}++func (f *fakeLoginctl) install(t *testing.T) {+ t.Helper()+ prevRun, prevInit := runLoginctlCommand, lingerSystemdPresent+ t.Cleanup(func() { runLoginctlCommand, lingerSystemdPresent = prevRun, prevInit })+ lingerSystemdPresent = func() bool { return true }+ runLoginctlCommand = func(args ...string) (string, error) {+ f.calls = append(f.calls, args)+ for _, arg := range args {+ switch arg {+ case "enable-linger":+ if f.enableSets {+ f.linger = true+ }+ return f.enableOut, f.enableErr+ case "show-user":+ if f.linger {+ return "yes\n", nil+ }+ return "no\n", nil+ }+ }+ return "", nil+ }+}++func (f *fakeLoginctl) called(verb string) bool {+ for _, args := range f.calls {+ for _, arg := range args {+ if arg == verb {+ return true+ }+ }+ }+ return false+}++// The core inversion: the outcome follows the state, not the exit code.+func TestEnableLingerReportsStateRatherThanExitCode(t *testing.T) {+ authRequired := "Failed to enable linger: Interactive authentication required."+ pkttyagent := "Failed to execute /usr/bin/pkttyagent: No such file or directory"++ for _, tc := range []struct {+ name string+ fake fakeLoginctl+ wantEnabled bool+ wantDetail []string+ denyDetail []string+ }{+ {+ // The ordinary success: privileged enough to set it, and logind confirms.+ name: "applied and confirmed",+ fake: fakeLoginctl{enableSets: true},+ wantEnabled: true,+ wantDetail: []string{"enabled"},+ },+ {+ // The reported failure that is not one. loginctl exits non-zero because the+ // PolicyKit text agent it tried to spawn is missing, but linger is set regardless.+ // Reading the exit code here would report a gap that does not exist and send the+ // user off to run sudo for nothing.+ name: "helper failed noisily but linger landed",+ fake: fakeLoginctl{enableSets: true, enableOut: pkttyagent, enableErr: errors.New("exit status 1")},+ wantEnabled: true,+ wantDetail: []string{"enabled"},+ },+ {+ // The inverse, and the one that produced a success transcript the next logout+ // disproved: nothing failed loudly, and linger is still off.+ name: "zero exit that changed nothing",+ fake: fakeLoginctl{enableSets: false},+ wantEnabled: false,+ wantDetail: []string{"disabled", "no error"},+ },+ {+ // The reported Linux install. The user gets told what is actually wrong -- they+ // are not an administrator -- and never sees a path to a file they never asked+ // about and cannot usefully install.+ name: "auth agent chatter is not the explanation",+ fake: fakeLoginctl{enableOut: pkttyagent, enableErr: errors.New("exit status 1")},+ wantEnabled: false,+ wantDetail: []string{"disabled", "administrator approval"},+ denyDetail: []string{"pkttyagent"},+ },+ {+ // Chatter is filtered, not everything. A real reason from logind is the most+ // useful sentence available and must survive.+ name: "a real reason survives the filter",+ fake: fakeLoginctl{enableOut: pkttyagent + "\n" + authRequired, enableErr: errors.New("exit status 1")},+ wantEnabled: false,+ wantDetail: []string{"Interactive authentication required"},+ denyDetail: []string{"pkttyagent"},+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ fake := tc.fake+ fake.install(t)+ enabled, detail := EnableLinger("someone")+ if enabled != tc.wantEnabled {+ t.Errorf("EnableLinger enabled = %v, want %v (detail %q)", enabled, tc.wantEnabled, detail)+ }+ for _, want := range tc.wantDetail {+ if !strings.Contains(detail, want) {+ t.Errorf("detail %q should mention %q", detail, want)+ }+ }+ for _, deny := range tc.denyDetail {+ if strings.Contains(detail, deny) {+ t.Errorf("detail %q should not relay %q", detail, deny)+ }+ }+ if detail == "" {+ t.Error("every applicable outcome must report a detail")+ }+ })+ }+}++// --no-ask-password is the fix for the noise itself, not just for how it is reported: without it+// loginctl spawns a PolicyKit text agent, which is what wrote the unexplained pkttyagent line+// into the middle of a successful install transcript. It also writes to the controlling terminal+// rather than the stderr a caller captures, so suppressing the prompt is the only reliable way to+// keep it out of the transcript.+func TestEnableLingerDoesNotAskForAPassword(t *testing.T) {+ fake := fakeLoginctl{enableSets: true}+ fake.install(t)+ EnableLinger("someone")++ for _, args := range fake.calls {+ if args[0] == "show-user" {+ continue+ }+ if args[0] != "--no-ask-password" {+ t.Errorf("loginctl %v: --no-ask-password must come before the verb", args)+ }+ }+ if !fake.called("enable-linger") {+ t.Fatal("EnableLinger did not run enable-linger")+ }+}++// A remediation is a promise that running that exact command closes the gap. It belongs on the+// outcome only when linger is genuinely off and the user it applies to is known -- printing it+// after a success would be noise, and printing it when the username is unresolvable would name+// the wrong user.+func TestEnableLingerIfNeededAttachesRemediationOnlyWhenLingerIsOff(t *testing.T) {+ u, err := user.Current()+ if err != nil || u.Username == "" {+ t.Skip("needs a resolvable current user")+ }+ manager := Manager{UserMode: true, Kind: KindSystemd}++ t.Run("off", func(t *testing.T) {+ fake := fakeLoginctl{}+ fake.install(t)+ got := manager.EnableLingerIfNeeded()+ if !got.Applicable || got.Enabled {+ t.Fatalf("outcome = %+v, want applicable and disabled", got)+ }+ if want := "sudo loginctl enable-linger " + u.Username; got.Remediation != want {+ t.Errorf("remediation = %q, want %q", got.Remediation, want)+ }+ })++ t.Run("already on", func(t *testing.T) {+ fake := fakeLoginctl{linger: true}+ fake.install(t)+ got := manager.EnableLingerIfNeeded()+ if !got.Applicable || !got.Enabled {+ t.Fatalf("outcome = %+v, want applicable and enabled", got)+ }+ if got.Remediation != "" {+ t.Errorf("remediation = %q, want none once linger is on", got.Remediation)+ }+ // Nothing to do, so nothing should be attempted: an install that re-enables linger on+ // every run would ask for privileges it does not need.+ if fake.called("enable-linger") {+ t.Error("enable-linger should not run when linger is already on")+ }+ })+}++// Chatter filtering is line-based, so a reason that arrives alongside noise has to survive intact+// and a multi-line reason has to stay readable on the single line the caller prints.+func TestWithoutAuthAgentChatterKeepsEverythingElse(t *testing.T) {+ for _, tc := range []struct{ name, in, want string }{+ {"empty", "", ""},+ {"only chatter", "Failed to execute /usr/bin/pkttyagent: No such file or directory\n", ""},+ {"only agent registration chatter", "Error registering polkit-agent: whatever\n", ""},+ {"reason kept", "Failed to enable linger: Access denied.\n", "Failed to enable linger: Access denied."},+ {+ "reason kept alongside chatter",+ "Failed to execute /usr/bin/pkttyagent: No such file or directory\nAccess denied.\n",+ "Access denied.",+ },+ {"multiple lines joined", "first problem\nsecond problem\n", "first problem; second problem"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if got := withoutAuthAgentChatter(tc.in); got != tc.want {+ t.Errorf("withoutAuthAgentChatter(%q) = %q, want %q", tc.in, got, tc.want)+ }+ })+ }+}++// The guard exists so linger reporting stays inert off systemd. Without it, the stubbed tests+// above would be the only thing standing between a macOS install and a logout warning about a+// service manager it does not use.+func TestLingerHelpersAreInertWithoutSystemd(t *testing.T) {+ prev := lingerSystemdPresent+ t.Cleanup(func() { lingerSystemdPresent = prev })+ lingerSystemdPresent = func() bool { return false }++ prevRun := runLoginctlCommand+ t.Cleanup(func() { runLoginctlCommand = prevRun })+ runLoginctlCommand = func(args ...string) (string, error) {+ t.Errorf("loginctl %v should not run without systemd as PID 1", args)+ return "", nil+ }++ if enabled, detail := EnableLinger("someone"); enabled || detail == "" {+ t.Errorf("EnableLinger = %v, %q; want a reported no-op", enabled, detail)+ }+ if LingerEnabled("someone") {+ t.Error("LingerEnabled should be false without systemd as PID 1")+ }+}++// The remediation is printed for the user to paste, so it has to be complete: the command, the+// privilege it needs, and the account it applies to, with nothing left to substitute.+func TestLingerRemediationIsRunnableAsPrinted(t *testing.T) {+ got := LingerRemediation("someone")+ for _, want := range []string{"sudo", "loginctl enable-linger", "someone"} {+ if !strings.Contains(got, want) {+ t.Errorf("LingerRemediation = %q, want it to contain %q", got, want)+ }+ }+ if strings.ContainsAny(got, "<>$") {+ t.Errorf("LingerRemediation = %q, want no placeholder left for the user to fill in", got)+ }+}diff --git a/cli/beacon/internal/endpoint/service/service.go b/cli/beacon/internal/endpoint/service/service.goindex 7674b668..de62fa75 100644--- a/cli/beacon/internal/endpoint/service/service.go+++ b/cli/beacon/internal/endpoint/service/service.go@@ -88,25 +88,53 @@ func ParseKind(s string) (Kind, error) {}}+// LingerOutcome is the result of the optional logout-persistence step of a service install.+//+// Applicable says whether linger is a question on this host at all -- it is false in system mode+// and on every backend but systemd. That used to be encoded as an empty Detail, which meant a+// caller could not distinguish "we did not try" from "we tried and said nothing", and made the+// one outcome worth recording the one most easily dropped. Enabled is the state read back from+// logind afterwards, not the exit status of the attempt. Remediation is set only when linger is+// applicable and off: the exact command that closes the gap, ready to print.+type LingerOutcome struct {+ Applicable bool+ Enabled bool+ Detail string+ Remediation string+}+// EnableLingerIfNeeded makes a systemd --user unit survive logout, where that applies.//-// The empty detail means exactly one thing: linger does not apply here -- system mode, or any-// backend but systemd. Every applicable case reports a detail, success included, so a caller can-// use an empty detail to mean "we did not try" without that also swallowing "we tried and it-// worked". launchd needs no equivalent: its gui/<uid> domain persists for the login session by-// itself.-func (m Manager) EnableLingerIfNeeded() (bool, string) {+// launchd needs no equivalent: its gui/<uid> domain persists for the login session by itself.+func (m Manager) EnableLingerIfNeeded() LingerOutcome {if !m.UserMode || m.resolvedKind() != KindSystemd {- return false, ""+ return LingerOutcome{}}u, err := user.Current()if err != nil || u.Username == "" {- return false, "could not determine the current user, so logout persistence is unverified"+ return LingerOutcome{+ Applicable: true,+ Detail: "could not determine the current user, so logout persistence is unverified",+ }}if LingerEnabled(u.Username) {- return true, "linger already enabled for " + u.Username+ return LingerOutcome{Applicable: true, Enabled: true, Detail: "linger already enabled for " + u.Username}}- return EnableLinger(u.Username)+ enabled, detail := EnableLinger(u.Username)+ outcome := LingerOutcome{Applicable: true, Enabled: enabled, Detail: detail}+ if !enabled {+ outcome.Remediation = LingerRemediation(u.Username)+ }+ return outcome+}++// LingerRemediation is the command that gives a user's systemd units logout persistence.+//+// Shared rather than written out at each call site: install, repair, and doctor all tell the user+// how to close this gap, and three independent copies of a command a user is meant to paste is+// how they drift apart.+func LingerRemediation(username string) string {+ return "sudo loginctl enable-linger " + username}// ServiceNoun names what this backend installs, for user-facing messages.diff --git a/cli/beacon/internal/endpoint/service/service_test.go b/cli/beacon/internal/endpoint/service/service_test.goindex 53e3e2e7..acc335ad 100644--- a/cli/beacon/internal/endpoint/service/service_test.go+++ b/cli/beacon/internal/endpoint/service/service_test.go@@ -5,7 +5,6 @@ import ("fmt""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv""os"- "os/user""path/filepath""runtime""strings"@@ -565,16 +564,16 @@ func TestDetectKindMatchesHost(t *testing.T) {// 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.+ // Not applicable: nothing should be attempted or reported, so the caller records nothing and+ // no install prints a logout warning that does not apply to its backend.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)+ if got := m.EnableLingerIfNeeded(); got != (LingerOutcome{}) {+ t.Errorf("%+v should not attempt linger, got %+v", m, got)}}}@@ -582,8 +581,11 @@ func TestEnableLingerIfNeededOnlyAppliesToSystemdUserUnits(t *testing.T) {// 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 == "" {+ got := (Manager{UserMode: true, Kind: KindSystemd}).EnableLingerIfNeeded()+ if !got.Applicable {+ t.Fatal("a systemd user unit must mark linger applicable")+ }+ if got.Detail == "" {t.Error("a systemd user unit must report a linger outcome, whether or not it succeeded")}}@@ -607,29 +609,11 @@ func TestServiceNounNamesEachBackend(t *testing.T) {}}-// The success path is the one that used to report nothing. EnableLinger returned an empty detail on-// success, and the install path reads an empty detail as "linger does not apply" -- so linger-// actually being enabled was the single outcome the manifest dropped.-func TestEnableLingerReportsSuccessAndFailureDistinctly(t *testing.T) {- if !systemdIsInit() {- t.Skip("needs systemd as PID 1; linger does not apply otherwise")- }- u, err := user.Current()- if err != nil || u.Username == "" {- t.Skip("needs a resolvable current user")- }- ok, detail := EnableLinger(u.Username)- if detail == "" {- t.Fatalf("EnableLinger(%q) = %v with no detail; an empty detail means "+- "\"does not apply\" to the caller, so every applicable outcome must say something",- u.Username, ok)- }-}--// The contract the install path depends on: an empty detail means "not applicable", never-// "succeeded" and never "failed quietly".-func TestEnableLingerNeverReportsAnEmptyDetailWhenItApplies(t *testing.T) {- // The non-applicable cases, which are the only ones allowed to be silent.+// The contract the install path depends on: every outcome says something. An outcome that reports+// nothing is indistinguishable from "linger does not apply here", which is how a successfully+// enabled linger used to go unrecorded in the manifest.+func TestEnableLingerAlwaysReportsADetail(t *testing.T) {+ // The guard cases, which never reach loginctl at all.if _, detail := EnableLinger(""); detail == "" {t.Error("an empty username is a reportable problem, not a silent skip")}diff --git a/cli/beacon/internal/endpoint/service/systemd.go b/cli/beacon/internal/endpoint/service/systemd.goindex fdec3535..f19e06d5 100644--- a/cli/beacon/internal/endpoint/service/systemd.go+++ b/cli/beacon/internal/endpoint/service/systemd.go@@ -32,6 +32,13 @@ var runLoginctlCommand = func(args ...string) (string, error) {return string(out), err}+// lingerSystemdPresent gates the linger helpers on systemd being PID 1.+//+// Separate from the systemdIsInit call in backend detection so linger tests can drive every+// branch on any host. Stubbing detection itself would change which backend Manager picks, which+// is a different question with its own tests.+var lingerSystemdPresent = systemdIsInit+// systemdIsInit reports whether systemd is PID 1.//// Checked by reading /proc/1/comm rather than by probing for the systemctl binary: many@@ -201,32 +208,68 @@ func systemctlError(out string, err error, what string) error {// login session, whereas a systemd user manager is torn down at logout unless linger is set.// Without it a user-mode install silently stops collecting the moment the user logs out.// Best-effort, since it needs privileges that a plain user may not have.+//+// The reported outcome is whether linger is actually set afterwards, read back from logind,+// rather than whether the loginctl call exited zero. Those differ in both directions:+// authentication can be declined after a zero exit on some logind versions, and the enable can+// land while a helper process the call spawned fails noisily. Logout persistence is the thing+// the user cares about, so it is the thing that gets checked.func EnableLinger(username string) (bool, string) {- if !systemdIsInit() {+ if !lingerSystemdPresent() {return false, "systemd is not PID 1; linger does not apply"}if username == "" {return false, "no username provided"}- out, err := runLoginctlCommand("enable-linger", username)+ // --no-ask-password keeps loginctl from launching a PolicyKit text agent to prompt for+ // authentication. Linger is an optional, best-effort step during install; a password prompt+ // mid-install is worse than reporting the gap and printing the one command that closes it.+ out, err := runLoginctlCommand("--no-ask-password", "enable-linger", username)+ if LingerEnabled(username) {+ // The success path must say so. It previously returned an empty detail, which the install+ // path reads as "not applicable" -- so the one outcome worth recording, linger actually+ // being enabled, was the one the manifest silently dropped.+ return true, "linger enabled for " + username+ }+ return false, lingerFailureDetail(username, out, err)+}++// lingerFailureDetail explains an unset linger in terms the user can act on.+//+// loginctl can spawn a PolicyKit text agent, and on a host without /usr/bin/pkttyagent that+// prints "Failed to execute /usr/bin/pkttyagent: No such file or directory" -- naming a file the+// user never asked about, in the middle of an otherwise successful install, and not the actual+// reason linger is off. That chatter is dropped. Everything else loginctl says is kept, because+// "Interactive authentication required" and a genuinely broken logind are worth reading.+func lingerFailureDetail(username, out string, err error) string {+ detail := "linger is disabled for " + username+ if reason := withoutAuthAgentChatter(out); reason != "" {+ return detail + ": " + reason+ }if err != nil {- // loginctl does not always print anything on failure, and an empty detail here is- // indistinguishable from "linger does not apply" -- which is what the caller uses an empty- // detail to mean. The error is folded in so the outcome is always attributable.- if detail := strings.TrimSpace(out); detail != "" {- return false, detail+ return detail + "; enabling it needs administrator approval"+ }+ // Zero exit, nothing printed, and linger still unset: logind accepted the call and did not+ // apply it. Saying so beats reporting a success the next logout would disprove.+ return detail + " even though loginctl reported no error"+}++// withoutAuthAgentChatter drops PolicyKit-agent noise and returns what is left, on one line.+func withoutAuthAgentChatter(out string) string {+ var kept []string+ for _, line := range strings.Split(out, "\n") {+ line = strings.TrimSpace(line)+ if line == "" || strings.Contains(line, "pkttyagent") || strings.Contains(line, "polkit-agent") {+ continue}- return false, "loginctl enable-linger " + username + " failed: " + err.Error()+ kept = append(kept, line)}- // The success path must say so. It previously returned an empty detail, which the install path- // reads as "not applicable" -- so the one outcome worth recording, linger actually being- // enabled, was the one the manifest silently dropped.- return true, "linger enabled for " + username+ return strings.Join(kept, "; ")}// LingerEnabled reports whether linger is on for a user, so doctor can flag the gap.func LingerEnabled(username string) bool {- if !systemdIsInit() || username == "" {+ if !lingerSystemdPresent() || username == "" {return false}out, err := runLoginctlCommand("show-user", username, "--property=Linger", "--value")diff --git a/docs/platforms/linux.mdx b/docs/platforms/linux.mdxindex f2209220..326d8b96 100644--- a/docs/platforms/linux.mdx+++ b/docs/platforms/linux.mdx@@ -225,15 +225,17 @@ beacon endpoint installThis writes everything under `~/.beacon/endpoint` and registers a `systemctl --user` unit. Onecaveat has no macOS equivalent and is worth stating plainly: **a `--user` unit stops when you log-out**, unless linger is enabled for your account. Beacon enables it during install when it can, and-`beacon endpoint doctor` reports it when it could not:+out**, unless linger is enabled for your account. Beacon enables it during install when it can:```bash title="Keep a user-mode collector running after logout"sudo loginctl enable-linger $USER```-Without linger, a user-mode collector works while you are logged in and silently stops collecting-after you log out.+When it could not, `beacon endpoint install` and `beacon endpoint repair` say so at the end of the+run and print that exact command, and `beacon endpoint doctor` keeps reporting it until it is+fixed. Beacon checks the resulting linger state rather than the exit status of its own attempt, so+this reflects whether the collector really will survive logout. Without linger, a user-mode+collector works while you are logged in and stops collecting after you log out.## Without systemd