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): resolve directory-backed accounts, so a system install configures someone
shukieshah38e9524b5af9
diff --git a/beacon-sandbox/image/image.go b/beacon-sandbox/image/image.goindex 277266aa..4654407b 100644--- a/beacon-sandbox/image/image.go+++ b/beacon-sandbox/image/image.go@@ -19,6 +19,10 @@ const (// AgentUser is unprivileged on purpose: Claude Code refuses// --dangerously-skip-permissions when running as root.AgentUser = "agent"+ // AgentUID is pinned so the local and NSS-only lanes produce the same numeric identity, and so+ // ownership assertions mean the same thing in both. 1001 because ubuntu:24.04 already ships an+ // `ubuntu` account at 1000.+ AgentUID = 1001AgentHome = "/home/agent"WorkDir = "/home/agent/work"BeaconDir = "/opt/beacon/bin"@@ -180,6 +184,11 @@ type Spec struct {// opt-in because it is a large install that every other scenario would pay for and none of// them need.WithDocker bool++ // NSSOnlyUser creates the agent account in an NSS source instead of /etc/passwd, reproducing+ // a directory-backed fleet. See scenario.Install.NSSOnlyUser for why that distinction decides+ // whether a system-mode install can configure anyone at all.+ NSSOnlyUser bool}// LinuxArtifacts are the binaries the sandbox needs, as host paths.@@ -236,6 +245,13 @@ func Build(spec Spec, log func(string, ...any)) (sandbox.ImageSpec, error) {}pkgs := "curl ca-certificates git tar ripgrep procps sudo python3 jq"+ if spec.NSSOnlyUser {+ // libnss-extrausers is a real NSS module that reads its own database, which is exactly the+ // property a directory service has and /etc/passwd does not. It reproduces OpenLDAP/SSSD+ // account visibility without running a directory server, so the lane stays cheap enough to+ // be a regression test rather than an occasional manual exercise.+ pkgs += " libnss-extrausers"+ }if spec.WithDocker {// docker.io rather than the upstream repo: it is one apt line, and the daemon only has// to be new enough to run a privileged container with a host cgroup namespace.@@ -253,9 +269,10 @@ func Build(spec Spec, log func(string, ...any)) (sandbox.ImageSpec, error) {layers := []string{"ENV DEBIAN_FRONTEND=noninteractive","RUN apt-get update -qq && apt-get install -y -qq " + pkgs + " >/dev/null",- fmt.Sprintf("RUN useradd -m -s /bin/bash %s && mkdir -p %s && chown -R %s:%s %s",- AgentUser, WorkDir, AgentUser, AgentUser, AgentHome),- "RUN mkdir -p " + BeaconDir,+ }+ layers = append(layers, accountLayers(spec.NSSOnlyUser)...)+ layers = append(layers,+ "RUN mkdir -p "+BeaconDir,// Claude Code's native installer needs no Node. Pinned for reproducibility, and// installed as the agent user so it lands in that user's ~/.local/bin.fmt.Sprintf("RUN su - %s -c 'curl -fsSL https://claude.ai/install.sh | bash -s %s'",@@ -266,7 +283,7 @@ func Build(spec Spec, log func(string, ...any)) (sandbox.ImageSpec, error) {"git config user.email [email protected] && git config user.name beacon-sandbox && "+"printf \"# fixture\\n\" > README.md && git add -A && git commit -qm initial'",AgentUser, WorkDir, WorkDir),- }+ )if spec.WithDocker {// Group membership is set at image build time; adding it later would need a re-login to@@ -285,6 +302,50 @@ func Build(spec Spec, log func(string, ...any)) (sandbox.ImageSpec, error) {}, nil}+// accountLayers create the session account, either locally or visible only through NSS.+//+// The two forms differ in exactly one respect -- whether the account appears in /etc/passwd -- and+// are otherwise identical in username, uid, home directory and shell. That is deliberate: a+// scenario comparing an NSS-only lane against a local one is then comparing account *visibility*+// and nothing else, so a difference in outcome has one available explanation.+func accountLayers(nssOnly bool) []string {+ if !nssOnly {+ return []string{+ fmt.Sprintf("RUN useradd -m -u %d -s /bin/bash %s && mkdir -p %s && chown -R %s:%s %s",+ AgentUID, AgentUser, WorkDir, AgentUser, AgentUser, AgentHome),+ }+ }+ return []string{+ // files first, so root and the system accounts still resolve normally; extrausers supplies+ // only what files does not have. This is the same ordering a real SSSD host uses.+ "RUN sed -i -e 's/^passwd:.*/passwd: files extrausers/' " ++ "-e 's/^group:.*/group: files extrausers/' " ++ "-e 's/^shadow:.*/shadow: files extrausers/' /etc/nsswitch.conf",+ fmt.Sprintf("RUN mkdir -p /var/lib/extrausers && "++ "printf '%s:x:%d:%d::%s:/bin/bash\\n' > /var/lib/extrausers/passwd && "++ "printf '%s:x:%d:\\n' > /var/lib/extrausers/group && "++ "printf '%s:!:20000:0:99999:7:::\\n' > /var/lib/extrausers/shadow && "++ "chmod 0644 /var/lib/extrausers/passwd /var/lib/extrausers/group && "++ "chmod 0640 /var/lib/extrausers/shadow && "++ "mkdir -p %s %s && chown -R %d:%d %s",+ AgentUser, AgentUID, AgentUID, AgentHome,+ AgentUser, AgentUID,+ AgentUser,+ AgentHome, WorkDir, AgentUID, AgentUID, AgentHome),+ // Assert the lane actually has the property it exists to provide. Without this, a broken+ // NSS module or a changed nsswitch format would leave the account resolvable the ordinary+ // way, and the scenario would pass for the wrong reason -- reporting that a bug is fixed+ // when it was merely never exercised. Failing at image build is far cheaper than failing+ // that conclusion.+ fmt.Sprintf("RUN getent passwd %s >/dev/null || "++ "{ echo 'nss lane broken: getent cannot resolve %s' >&2; exit 1; }",+ AgentUser, AgentUser),+ fmt.Sprintf("RUN if grep -q '^%s:' /etc/passwd; then "++ "echo 'nss lane broken: %s leaked into /etc/passwd' >&2; exit 1; fi",+ AgentUser, AgentUser),+ }+}+// PostPushLayers are the commands that must run after the artifact files land. The// provider snapshots after Put, so these run in the first launched instance instead.func PostPushLayers() string {diff --git a/beacon-sandbox/image/image_test.go b/beacon-sandbox/image/image_test.goindex fad11bcf..e64f228a 100644--- a/beacon-sandbox/image/image_test.go+++ b/beacon-sandbox/image/image_test.go@@ -1,6 +1,7 @@package imageimport (+ "fmt""net/http""net/http/httptest""os"@@ -60,7 +61,9 @@ func TestBuildCreatesNonRootAgentUser(t *testing.T) {}joined := strings.Join(spec.Layers, "\n")- if !strings.Contains(joined, "useradd -m -s /bin/bash "+AgentUser) {+ // Matched on the command and the account rather than the exact flag string: the assertion is+ // that an unprivileged account gets created, not the order its options happen to appear in.+ if !strings.Contains(joined, "useradd") || !strings.Contains(joined, AgentUser) {t.Errorf("image must create the %s user:\n%s", AgentUser, joined)}if !strings.Contains(joined, "su - "+AgentUser+" -c 'curl -fsSL https://claude.ai/install.sh") {@@ -71,6 +74,55 @@ func TestBuildCreatesNonRootAgentUser(t *testing.T) {}}+// The NSS-only lane exists to reproduce a directory-backed fleet, where an account resolves+// through getent but is absent from /etc/passwd. If the image ever creates that account with+// useradd anyway, the lane silently becomes an ordinary one and the scenario built on it reports+// that a bug is fixed when it was never exercised.+func TestBuildNSSOnlyUserDoesNotWriteEtcPasswd(t *testing.T) {+ spec, err := Build(Spec{RepoRoot: stubRepo(t), NSSOnlyUser: true}, nil)+ if err != nil {+ t.Fatal(err)+ }+ joined := strings.Join(spec.Layers, "\n")++ if strings.Contains(joined, "useradd") {+ t.Errorf("the NSS-only lane must not create a local account:\n%s", joined)+ }+ if !strings.Contains(joined, "libnss-extrausers") {+ t.Errorf("the NSS-only lane needs an NSS module to resolve through:\n%s", joined)+ }+ if !strings.Contains(joined, "/var/lib/extrausers/passwd") {+ t.Errorf("the account must live in the NSS database:\n%s", joined)+ }+ if !strings.Contains(joined, "extrausers") || !strings.Contains(joined, "/etc/nsswitch.conf") {+ t.Errorf("nsswitch must route passwd lookups through the NSS module:\n%s", joined)+ }+ // The image asserts its own property at build time; losing that check would let a broken NSS+ // module produce a lane that looks right and tests nothing.+ if !strings.Contains(joined, "getent passwd "+AgentUser) {+ t.Errorf("the image must verify getent resolves %s:\n%s", AgentUser, joined)+ }+ if !strings.Contains(joined, "/etc/passwd") {+ t.Errorf("the image must verify %s did not leak into /etc/passwd:\n%s", AgentUser, joined)+ }+}++// Both lanes must produce the same account identity, so a scenario comparing them is comparing+// visibility and nothing else.+func TestBothAccountLanesAgreeOnIdentity(t *testing.T) {+ local := strings.Join(accountLayers(false), "\n")+ nss := strings.Join(accountLayers(true), "\n")++ for _, want := range []string{AgentUser, AgentHome, fmt.Sprint(AgentUID)} {+ if !strings.Contains(local, want) {+ t.Errorf("local lane missing %q:\n%s", want, local)+ }+ if !strings.Contains(nss, want) {+ t.Errorf("NSS lane missing %q:\n%s", want, nss)+ }+ }+}+// PostPushLayers chmods and symlinks exactly the paths Build declares. If the two drift, the// binaries land somewhere nothing makes executable.func TestFilesMatchPostPushLayers(t *testing.T) {diff --git a/beacon-sandbox/runner/runner.go b/beacon-sandbox/runner/runner.goindex 5fdf1ff6..0bb99e4f 100644--- a/beacon-sandbox/runner/runner.go+++ b/beacon-sandbox/runner/runner.go@@ -584,6 +584,7 @@ func imageSpecFor(p sandbox.Platform, sc scenario.Scenario, opts Options,RepoRoot: opts.RepoRoot,ClaudeVersion: opts.ClaudeVersion,WithDocker: sc.NeedsRealSystemd(),+ NSSOnlyUser: sc.NeedsNSSOnlyUser(),}, logf)}diff --git a/beacon-sandbox/scenario/scenario.go b/beacon-sandbox/scenario/scenario.goindex c93a5499..0fa302ed 100644--- a/beacon-sandbox/scenario/scenario.go+++ b/beacon-sandbox/scenario/scenario.go@@ -75,6 +75,20 @@ type Install struct {// refuses. Rather than make a scenario describe VM lanes and Docker, it states the// requirement and the runner arranges it.NeedsRealSystemd bool `yaml:"needs_real_systemd,omitempty"`+ // NSSOnlyUser makes the session account resolvable through NSS but absent from /etc/passwd.+ //+ // This reproduces a directory-backed fleet -- OpenLDAP, SSSD, AD -- where `getent passwd alice`+ // succeeds and `grep alice /etc/passwd` finds nothing. It matters because Beacon is built+ // CGO_ENABLED=0, which selects Go's pure-Go os/user: that implementation parses /etc/passwd+ // directly and never consults NSS, so a root-run system install cannot resolve the human whose+ // runtime it is supposed to configure.+ //+ // The default image creates the same account with `useradd`, which writes /etc/passwd and makes+ // the failure structurally invisible -- a scenario can assert capture, install success, and+ // service health and still pass on a build that configures nobody on a real customer fleet.+ // Only the account's *visibility* changes; the username, home directory and uid are otherwise+ // identical, so everything a scenario asserts stays comparable to the local-account lanes.+ NSSOnlyUser bool `yaml:"nss_only_user,omitempty"`}// Platform selects the guest OS family a scenario is written for.@@ -206,6 +220,13 @@ func (s Scenario) Validate() error {return fmt.Errorf("%s: needs_real_systemd requires mode=system; a user unit in a "+"container has no logind session to attach to", s.ID)}+ // A user-mode install configures $HOME directly and never resolves anyone by name, so+ // the NSS gap it exists to expose is unreachable there. Allowing the combination would+ // produce a scenario that passes without testing anything it claims to.+ if s.Install.NSSOnlyUser && s.Install.Mode != "system" {+ return fmt.Errorf("%s: nss_only_user requires mode=system; a user-mode install "++ "resolves $HOME and never looks the account up by name", s.ID)+ }switch s.Install.ExpectServiceKind {case "", "systemd", "launchd", "windows-service", "none":default:@@ -380,6 +401,11 @@ func isFilenameByte(b byte) bool {return false}+// NeedsNSSOnlyUser reports whether the session account must be resolvable only through NSS.+func (s Scenario) NeedsNSSOnlyUser() bool {+ return s.Install != nil && s.Install.NSSOnlyUser+}+// NeedsRealSystemd reports whether this scenario must run somewhere systemd is genuinely PID 1.func (s Scenario) NeedsRealSystemd() bool {return s.Install != nil && s.Install.NeedsRealSystemddiff --git a/beacon-sandbox/scenarios/i03-install-nss-only-user.yaml b/beacon-sandbox/scenarios/i03-install-nss-only-user.yamlnew file mode 100644index 00000000..0d0a91e1--- /dev/null+++ b/beacon-sandbox/scenarios/i03-install-nss-only-user.yaml@@ -0,0 +1,62 @@+id: i03-install-nss-only-user+# The scenario a directory-backed fleet actually lives: a system-mode install on a host where the+# developer's account comes from OpenLDAP/SSSD rather than /etc/passwd.+#+# i01 and i02 both create their account with `useradd`, which writes /etc/passwd. That makes them+# structurally incapable of seeing this failure, and the gap is not hypothetical -- every scenario+# in this suite passed on a build that configures nobody on such a fleet.+#+# The mechanism: Beacon ships CGO_ENABLED=0, which selects Go's pure-Go os/user. That+# implementation parses /etc/passwd directly and never consults NSS, so `user.Lookup("agent")`+# fails for an account only a directory service can see. A system install runs as root and must+# resolve *someone else* by name to know whose Claude Code to configure -- so it resolves nobody,+# skips the step, and reports success. The collector then runs perfectly and captures nothing.+#+# `nss_only_user` is what makes this visible. The account is identical to the other lanes in+# username, uid, home directory and shell; only its visibility changes. So a difference in outcome+# between this scenario and i01 has exactly one available explanation.+#+# Deliberately service=none rather than systemd: the defect is in user resolution, not service+# management, and the supervised backend needs no nested privileged container. That keeps this+# lane cheap enough to run on every change to the resolution path.+install:+ mode: system+ service: none+ nss_only_user: true+ expect_status_running: true+ # Not redundant with the above -- see i02. Asserting the backend keeps a detection failure from+ # passing as a healthy install of something else.+ expect_service_kind: none++prompt: >-+ Run exactly this shell command and report its output: echo {{canary}} | tee {{sentinel}}+sentinel: /home/agent/work/i03.sentinel+budget_usd: 1.0+timeout_seconds: 420++expect:+ - action: prompt.submitted+ contains: ["{{canary}}"]+ fields: ["prompt.text", "session.id", "harness.name"]+ why: >-+ The whole chain, and the only assertion that can distinguish "installed" from "installed for+ somebody". A prompt event exists only if the install resolved the NSS-only account and wrote+ its settings.json. When this fails, the install step's own error names the cause: the+ user-config step reports skipped_reason=no_active_console_user rather than failing, which is+ exactly how this reaches production looking like a success.++ - action: token.usage+ fields: ["gen_ai.usage.input_tokens", "model"]+ why: >-+ Metrics travel a separate pipeline from logs, so a working prompt event does not imply a+ working metrics path. Held to the same standard as i01 and i02 on purpose: an install on a+ directory-backed host is never allowed to look healthier than one on a local-account host.++ - action: command.executed+ contains: ["{{canary}}"]+ fields: ["command.command"]+ why: >-+ The hook path specifically. Hooks are installed into the resolved user's settings.json, so+ this fails for the same root cause as prompt.submitted but through a different mechanism --+ and it is the surface the rules/risky-command/ detections match on, so losing it silently+ costs detection coverage rather than just telemetry.diff --git a/cli/beacon-hooks/cmd/post_tool_test.go b/cli/beacon-hooks/cmd/post_tool_test.goindex 1af0bb68..a9d1d3f6 100644--- a/cli/beacon-hooks/cmd/post_tool_test.go+++ b/cli/beacon-hooks/cmd/post_tool_test.go@@ -655,8 +655,11 @@ func TestRunPostToolEmitsClaudeToolEvents(t *testing.T) {if got := events[i]["event"].(map[string]interface{})["action"]; got != want {t.Fatalf("event[%d].action = %q, want %q", i, got, want)}- if harness := events[i]["harness"].(map[string]interface{})["name"]; harness != "claude" {- t.Fatalf("event[%d] harness = %q, want claude", i, harness)+ // claude_code, not the raw --platform value: the OTLP path reports the canonical name for+ // the same session, and emitting the raw one here split a single session across two names+ // for anything grouping by harness.name.+ if harness := events[i]["harness"].(map[string]interface{})["name"]; harness != "claude_code" {+ t.Fatalf("event[%d] harness = %q, want claude_code", i, harness)}}if file := events[0]["file"].(map[string]interface{}); file["path"] != "/repo/main.go" || file["operation"] != "modify" {diff --git a/cli/beacon-hooks/cmd/pre_tool_test.go b/cli/beacon-hooks/cmd/pre_tool_test.goindex a69f64f7..cee00ff4 100644--- a/cli/beacon-hooks/cmd/pre_tool_test.go+++ b/cli/beacon-hooks/cmd/pre_tool_test.go@@ -175,8 +175,8 @@ func TestVSCodeHooksEmitLowNoiseTelemetry(t *testing.T) {if action := event["event"].(map[string]interface{})["action"]; action != "tool.invoked" {t.Fatalf("event.action = %q, want tool.invoked", action)}- if harness := event["harness"].(map[string]interface{})["name"]; harness != "vscode" {- t.Fatalf("harness = %q, want vscode", harness)+ if harness := event["harness"].(map[string]interface{})["name"]; harness != "vscode_copilot" {+ t.Fatalf("harness = %q, want vscode_copilot", harness)}if _, ok := event["raw"].(map[string]interface{})["vscode"]; !ok {t.Fatalf("raw.vscode missing: %#v", event["raw"])@@ -204,8 +204,8 @@ func TestRunSubagentLifecycleEmitsVSCodeEvents(t *testing.T) {if action := event["event"].(map[string]interface{})["action"]; action != "subagent.started" {t.Fatalf("event.action = %q, want subagent.started", action)}- if harness := event["harness"].(map[string]interface{})["name"]; harness != "vscode" {- t.Fatalf("harness = %q, want vscode", harness)+ if harness := event["harness"].(map[string]interface{})["name"]; harness != "vscode_copilot" {+ t.Fatalf("harness = %q, want vscode_copilot", harness)}if _, ok := event["tool"]; ok {t.Fatalf("subagent event should not be encoded as tool: %#v", event["tool"])@@ -325,8 +325,8 @@ func TestRunPromptSubmitEmitsAntigravityPromptEvent(t *testing.T) {if action := event["event"].(map[string]interface{})["action"]; action != "prompt.submitted" {t.Fatalf("event.action = %q, want prompt.submitted", action)}- if harness := event["harness"].(map[string]interface{})["name"]; harness != "antigravity" {- t.Fatalf("harness = %q, want antigravity", harness)+ if harness := event["harness"].(map[string]interface{})["name"]; harness != "antigravity_cli" {+ t.Fatalf("harness = %q, want antigravity_cli", harness)}if got := event["prompt"].(map[string]interface{})["text"]; got != "summarize token=[REDACTED]" {t.Fatalf("prompt.text = %q, want redacted prompt", got)@@ -578,8 +578,8 @@ func TestRunPreToolEmitsClaudeTelemetryWithoutDecision(t *testing.T) {if action := event["event"].(map[string]interface{})["action"]; action != "tool.invoked" {t.Fatalf("event.action = %q, want tool.invoked", action)}- if harness := event["harness"].(map[string]interface{})["name"]; harness != "claude" {- t.Fatalf("harness = %q, want claude", harness)+ if harness := event["harness"].(map[string]interface{})["name"]; harness != "claude_code" {+ t.Fatalf("harness = %q, want claude_code", harness)}if _, ok := event["approval"]; ok {t.Fatalf("Claude PreToolUse should not emit approval telemetry: %#v", event["approval"])@@ -618,8 +618,8 @@ func TestRunPreToolEmitsAntigravityCommandTelemetry(t *testing.T) {}event := lastEndpointEvent(t, logPath)- if harness := event["harness"].(map[string]interface{})["name"]; harness != "antigravity" {- t.Fatalf("harness = %q, want antigravity", harness)+ if harness := event["harness"].(map[string]interface{})["name"]; harness != "antigravity_cli" {+ t.Fatalf("harness = %q, want antigravity_cli", harness)}if action := event["event"].(map[string]interface{})["action"]; action != "tool.invoked" {t.Fatalf("event.action = %q, want tool.invoked", action)diff --git a/cli/beacon-hooks/internal/logging/logging.go b/cli/beacon-hooks/internal/logging/logging.goindex b45a2738..ff018796 100644--- a/cli/beacon-hooks/internal/logging/logging.go+++ b/cli/beacon-hooks/internal/logging/logging.go@@ -142,7 +142,12 @@ func (l *Logger) baseEndpointEvent(action, category, severity, message string) m},"user": user,"harness": map[string]interface{}{- "name": l.platform,+ // Normalized rather than written raw. The OTLP path already reports the canonical name+ // for the same session, so emitting the raw --platform value here recorded one session+ // under two names -- splitting it for any query or SIEM detection that groups by+ // harness.name. The flag itself is unchanged, so existing installs are fixed without+ // having their settings.json rewritten.+ "name": asymptoteobserve.NormalizeHarnessName(l.platform),},"message": asymptoteobserve.CleanString(message, asymptoteobserve.DefaultStringLimit, true),}diff --git a/cli/beacon/.goreleaser.yaml b/cli/beacon/.goreleaser.yamlindex 0b34df7c..feba7647 100644--- a/cli/beacon/.goreleaser.yaml+++ b/cli/beacon/.goreleaser.yaml@@ -140,6 +140,21 @@ nfpms:dst: /opt/beacon/scripts/uninstall-endpoint.shfile_info:mode: 0755+ # Without these the payload is unreachable by name and every documented command fails with+ # "beacon: command not found" -- including the one this package's own postinstall prints.+ # 103 documentation pages call the binary bare, so the package is the right place to make+ # that true rather than rewriting them all to absolute paths.+ #+ # /usr/bin rather than /usr/local/bin for two reasons: Debian policy reserves /usr/local for+ # the local administrator, and /usr/bin is in sudo's default secure_path, so `sudo beacon+ # ...` -- which is most of the system-mode documentation -- resolves too. Google Chrome ships+ # the same shape: an /opt payload with a /usr/bin symlink.+ - src: /opt/beacon/bin/beacon+ dst: /usr/bin/beacon+ type: symlink+ - src: /opt/beacon/bin/beacon-hooks+ dst: /usr/bin/beacon-hooks+ type: symlinkscripts:postinstall: ../../packaging/linux/nfpm/postinstall.shpreremove: ../../packaging/linux/nfpm/preremove.shdiff --git a/cli/beacon/cmd/endpoint_console_user_config_test.go b/cli/beacon/cmd/endpoint_console_user_config_test.gonew file mode 100644index 00000000..1765ea41--- /dev/null+++ b/cli/beacon/cmd/endpoint_console_user_config_test.go@@ -0,0 +1,89 @@+package cmd++import (+ "os"+ "path/filepath"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/diagnostics"+)++func stubConsoleUser(t *testing.T, info consoleUserInfo, ok bool, err error) {+ t.Helper()+ restore := activeConsoleUser+ t.Cleanup(func() { activeConsoleUser = restore })+ activeConsoleUser = func() (consoleUserInfo, bool, error) { return info, ok, err }+}++func userHomeWith(t *testing.T, rel, contents string) consoleUserInfo {+ t.Helper()+ home := t.TempDir()+ path := filepath.Join(home, rel)+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {+ t.Fatal(err)+ }+ return consoleUserInfo{Username: "alice", HomeDir: home}+}++// The state this check exists to catch, and the one that shipped: a system install that resolved+// nobody, so the collector runs perfectly and captures nothing. Every other check is green in this+// state because they all read root's configuration, which the install did write.+func TestConsoleUserConfigCheckFailsWhenTheUserIsNotConfigured(t *testing.T) {+ stubConsoleUser(t, consoleUserInfo{Username: "alice", HomeDir: t.TempDir()}, true, nil)++ got := consoleUserConfigCheck()+ if got.Status != diagnostics.StatusFail {+ t.Errorf("status = %v, want fail: an endpoint capturing nobody must not read as healthy", got.Status)+ }+ if got.Action == "" {+ t.Error("a failure the operator can fix must say how")+ }+}++func TestConsoleUserConfigCheckPassesWhenPointedAtTheCollector(t *testing.T) {+ info := userHomeWith(t, ".claude/settings.json",+ `{"env":{"OTEL_EXPORTER_OTLP_ENDPOINT":"http://127.0.0.1:4317"}}`)+ stubConsoleUser(t, info, true, nil)++ if got := consoleUserConfigCheck(); got.Status != diagnostics.StatusOK {+ t.Errorf("status = %v (%s), want ok", got.Status, got.Message)+ }+}++// A settings file that exists but points somewhere else is not configured for this endpoint. The+// distinction matters because a developer who has used Claude Code before installing Beacon+// already has the file.+func TestConsoleUserConfigCheckRejectsAnUnrelatedSettingsFile(t *testing.T) {+ info := userHomeWith(t, ".claude/settings.json", `{"theme":"dark"}`)+ stubConsoleUser(t, info, true, nil)++ if got := consoleUserConfigCheck(); got.Status != diagnostics.StatusFail {+ t.Errorf("status = %v, want fail for a settings file not pointed at this collector", got.Status)+ }+}++// An unattended host legitimately has nobody to configure. That is a warning, not a failure --+// failing it would make every CI and container install red for a condition nobody can act on.+func TestConsoleUserConfigCheckWarnsWhenNobodyIsLoggedIn(t *testing.T) {+ stubConsoleUser(t, consoleUserInfo{}, false, nil)++ got := consoleUserConfigCheck()+ if got.Status != diagnostics.StatusWarn {+ t.Errorf("status = %v, want warn when no console user exists", got.Status)+ }+}++// Hook-only runtimes count as configured: the installed hook command names the hook binary, which+// is what points that runtime at the endpoint.+func TestConsoleUserConfigCheckAcceptsAHookOnlyRuntime(t *testing.T) {+ info := userHomeWith(t, ".cursor/hooks.json",+ `{"hooks":{"beforeShellExecution":[{"command":"/etc/beacon/endpoint/hooks/beacon-hooks pre-tool"}]}}`)+ stubConsoleUser(t, info, true, nil)++ if got := consoleUserConfigCheck(); got.Status != diagnostics.StatusOK {+ t.Errorf("status = %v (%s), want ok for a hook-configured runtime", got.Status, got.Message)+ }+}diff --git a/cli/beacon/cmd/endpoint_diagnostics.go b/cli/beacon/cmd/endpoint_diagnostics.goindex ae033ed2..c262560d 100644--- a/cli/beacon/cmd/endpoint_diagnostics.go+++ b/cli/beacon/cmd/endpoint_diagnostics.go@@ -7,11 +7,14 @@ import ("fmt""os""path/filepath"+ "strconv""strings""time""github.com/spf13/cobra"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/embedded"+endpointcollector "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/collector"endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/diagnostics"@@ -146,6 +149,9 @@ func buildDoctorResult(status lifecycle.Status, generatedAt time.Time) doctorRes}checks = append(checks, actionableChecks(status.Diagnostics, status.RuntimeLog)...)checks = append(checks, collectorCheck(status), serviceCheck(status), lastEventCheck(status))+ if !status.RuntimeLog.EffectiveUserMode {+ checks = append(checks, consoleUserConfigCheck())+ }for _, h := range status.Harnesses {checks = append(checks, harnessCheck(h, status.LogPath, status.RuntimeLog.EffectiveUserMode))}@@ -1051,6 +1057,117 @@ func lastEventCheck(status lifecycle.Status) diagnostics.Check {return diagnostics.Check{Name: "last_event", Target: status.LogPath, Status: diagnostics.StatusWarn, Severity: diagnostics.SeverityLow, Message: "runtime log has no events yet", Evidence: "last_event_missing", Action: "beacon endpoint test-event"}}+// consoleUserConfigCheck asks the one question a system-mode doctor never asked: is there a human+// whose agent runtime actually points at this collector?+//+// Every other check runs as root and resolves $HOME to /root, so it inspects the settings that+// `endpoint install --system` wrote for root -- which are always correct, because the install just+// wrote them. A system endpoint exists to capture the *operator's* sessions, and when the operator+// could not be resolved the install skipped them, said so only under --json, and doctor reported a+// green harness for root. The whole chain looked healthy while collecting nothing.+//+// That is not hypothetical: on a fleet whose accounts come from a directory service, it was the+// steady state for every machine, and the only visible symptom was the harness_observed warning+// that the documentation tells people to ignore on a fresh install.+//+// System mode only. In user mode the person running the command is the person being configured,+// so the question answers itself.+func consoleUserConfigCheck() diagnostics.Check {+ const name = "console_user_configured"+ info, ok, err := activeConsoleUser()+ if err != nil || !ok {+ return diagnostics.Check{+ Name: name,+ Status: diagnostics.StatusWarn,+ Severity: diagnostics.SeverityMedium,+ Message: "no logged-in user could be identified, so this endpoint may be collecting " ++ "for nobody; the collector is healthy either way",+ Evidence: "no_console_user",+ Action: "run 'beacon endpoint user-config repair-installed --system' as the user whose sessions should be captured",+ }+ }+ configured, detail := consoleUserHarnessConfigured(info)+ if !configured {+ return diagnostics.Check{+ Name: name,+ Target: info.Username,+ Status: diagnostics.StatusFail,+ Severity: diagnostics.SeverityHigh,+ Message: fmt.Sprintf("%s has no agent runtime pointed at this collector, so their "++ "sessions are not being captured (%s)", info.Username, detail),+ Evidence: "console_user_not_configured",+ Action: "sudo beacon endpoint user-config repair-installed --system",+ }+ }+ return diagnostics.Check{+ Name: name,+ Target: info.Username,+ Status: diagnostics.StatusOK,+ Severity: diagnostics.SeverityInfo,+ Message: fmt.Sprintf("%s's agent runtime is configured", info.Username),+ Evidence: "console_user_configured",+ }+}++// consoleUserHarnessConfigured reports whether the console user has at least one runtime pointed+// at the local collector.+//+// At least one rather than all of them: a developer who uses only Claude Code is fully configured,+// and demanding every detected runtime would produce a failure nobody should act on.+func consoleUserHarnessConfigured(info consoleUserInfo) (bool, string) {+ paths, err := consoleUserConfigPaths(info)+ if err != nil {+ return false, err.Error()+ }+ if len(paths) == 0 {+ return false, "no agent runtime configuration found in " + info.HomeDir+ }+ for _, p := range paths {+ data, err := os.ReadFile(p)+ if err != nil {+ continue+ }+ // The endpoint marker is the collector address the install writes. Matching on it rather+ // than on the file existing distinguishes "configured for this endpoint" from "the user+ // happens to have a settings file", which is the difference that matters here.+ if strings.Contains(string(data), "127.0.0.1:4317") ||+ strings.Contains(string(data), "127.0.0.1:4318") ||+ strings.Contains(string(data), embedded.BinaryStem) {+ return true, p+ }+ }+ return false, "found " + strconv.Itoa(len(paths)) + " runtime config file(s), none pointed at this collector"+}++// consoleUserConfigPaths lists the runtime configuration files that exist in a specific user's+// home directory.+//+// Resolved from their home directory rather than from harness discovery, which reads $HOME and+// would answer for root -- the process running doctor -- instead of for them. That substitution is+// the reason this check is needed at all, so it must not be repeated here.+func consoleUserConfigPaths(info consoleUserInfo) ([]string, error) {+ if info.HomeDir == "" {+ return nil, fmt.Errorf("no home directory for %s", info.Username)+ }+ // The runtimes a system install configures natively. Hook-only runtimes are covered too,+ // because an installed hook command names the hook binary and that is one of the markers.+ candidates := []string{+ filepath.Join(".claude", "settings.json"),+ filepath.Join(".codex", "config.toml"),+ filepath.Join(".gemini", "settings.json"),+ filepath.Join(".cursor", "hooks.json"),+ filepath.Join(".config", "Code", "User", "settings.json"),+ }+ var found []string+ for _, rel := range candidates {+ p := filepath.Join(info.HomeDir, rel)+ if _, err := os.Stat(p); err == nil {+ found = append(found, p)+ }+ }+ return found, nil+}+func harnessCheck(h harness.Harness, logPath string, effectiveUserMode bool) diagnostics.Check {if !h.Detected {return diagnostics.Check{Name: "harness", Target: h.Name, Status: diagnostics.StatusOK, Severity: diagnostics.SeverityInfo, Message: "not installed", Evidence: "not_installed"}diff --git a/cli/beacon/cmd/endpoint_hooks_repair.go b/cli/beacon/cmd/endpoint_hooks_repair.goindex 964acc57..bea422e0 100644--- a/cli/beacon/cmd/endpoint_hooks_repair.go+++ b/cli/beacon/cmd/endpoint_hooks_repair.go@@ -6,7 +6,6 @@ import ("fmt""os""os/exec"- "os/user""path/filepath""runtime""sort"@@ -15,6 +14,7 @@ import (endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/osuser""github.com/spf13/cobra")@@ -325,12 +325,20 @@ func describeLogindSession(id string) (logindSession, bool) {// root is rejected: a system install has already configured root, and treating it as the console// user would report success for configuring nobody. A user without a real home is rejected for// the same reason -- there is nowhere for a settings file to go.+//+// The lookup goes through osuser rather than os/user directly, and that is the whole difference+// between working and not working on a directory-backed fleet. Beacon is built CGO_ENABLED=0, so+// os/user reads /etc/passwd and never consults NSS; on a host whose accounts come from OpenLDAP or+// SSSD, every developer is invisible to a by-name lookup. Both callers reach this function -- the+// SUDO_USER path and the logind path -- so this is the single point where that was decided, and+// the logind case made it especially wasteful: logind is NSS-aware and hands over the correct+// username, which this function then discarded by re-resolving it somewhere it could not be found.func resolveConsoleUser(username string) (consoleUserInfo, bool, error) {username = strings.TrimSpace(username)if username == "" || username == "root" {return consoleUserInfo{}, false, nil}- u, err := user.Lookup(username)+ u, err := osuser.Lookup(username)if err != nil {return consoleUserInfo{}, false, nil}@@ -340,7 +348,9 @@ func resolveConsoleUser(username string) (consoleUserInfo, bool, error) {if _, err := os.Stat(u.HomeDir); err != nil {return consoleUserInfo{}, false, nil}- return consoleUserInfo{Username: username, HomeDir: u.HomeDir}, true, nil+ // The resolved spelling rather than the requested one: a directory service may answer with the+ // account's canonical name, and that is what the settings file and its ownership should use.+ return consoleUserInfo{Username: u.Username, HomeDir: u.HomeDir}, true, nil}func darwinActiveConsoleUser() (consoleUserInfo, bool, error) {diff --git a/cli/beacon/cmd/endpoint_user_config_unix.go b/cli/beacon/cmd/endpoint_user_config_unix.goindex c573333a..17ecaac6 100644--- a/cli/beacon/cmd/endpoint_user_config_unix.go+++ b/cli/beacon/cmd/endpoint_user_config_unix.go@@ -5,9 +5,9 @@ package cmdimport ("fmt""os"- "os/user"- "strconv""syscall"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/osuser")// chownUserConfigArtifacts gives the console user ownership of the settings files a system-mode@@ -31,16 +31,16 @@ func chownUserConfigArtifacts(info consoleUserInfo, path string) error {// userOwnership resolves the console user's numeric uid and gid.//-// The user database first, since that is the authoritative answer. Falling back to the home-// directory's owner covers a user whose account is not in the local database -- LDAP, SSSD, a-// container with a bare passwd file -- where the directory itself still records who they are.+// The account database first, since that is the authoritative answer, and osuser consults NSS so+// a directory-backed account resolves rather than falling straight through. Falling back to the+// home directory's owner still covers what NSS cannot answer -- a container with a bare passwd+// file, or a host with no getent -- where the directory itself still records who they are.+//+// Both this and resolveConsoleUser go through osuser deliberately. They answer the same question+// and disagreeing about it is how a settings file ends up owned by someone who cannot read it.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- }+ if u, err := osuser.Lookup(info.Username); err == nil {+ return u.UID, u.GID, nil}stat, err := os.Stat(info.HomeDir)if err != nil {diff --git a/cli/beacon/internal/osuser/osuser.go b/cli/beacon/internal/osuser/osuser.gonew file mode 100644index 00000000..e877943d--- /dev/null+++ b/cli/beacon/internal/osuser/osuser.go@@ -0,0 +1,132 @@+// Package osuser resolves local accounts in a way that survives a directory service.+//+// Beacon ships CGO_ENABLED=0, which is what makes every binary statically linked with no glibc+// version floor -- the property that lets it run on a stripped or older userland. The same flag+// selects Go's pure-Go os/user, and that implementation parses /etc/passwd directly and never+// consults NSS. On a host whose accounts come from OpenLDAP, SSSD, or AD, `user.Lookup("alice")`+// therefore fails for an account the rest of the system resolves perfectly well.+//+// That combination is not avoidable by building with cgo: glibc implements NSS by dlopen-ing+// libnss_*.so at runtime, so a statically linked glibc binary cannot consult NSS either. Static+// linking and NSS are mutually exclusive by construction. Shelling out to getent is the standard+// way out, and it keeps the static binaries intact.+//+// The distinction that matters: looking up *yourself* already works, because Go short-circuits a+// by-name lookup to Current() when the name matches, and Current() falls back to $USER/$HOME. It+// is looking up *someone else* -- which is exactly what a root-run system install must do to know+// whose agent runtime to configure -- that fails.+package osuser++import (+ "context"+ "fmt"+ "os/exec"+ "os/user"+ "strconv"+ "strings"+ "time"+)++// lookupTimeout bounds the NSS query.+//+// This runs inside a package postinstall, and a directory service that is slow or unreachable is+// an ordinary condition rather than an exotic one. Without a bound, `apt install` would hang on a+// network problem that has nothing to do with Beacon. Treating a timeout as "unresolved" is right:+// the caller already handles an unresolvable user, and failing the whole install over it would be+// worse than configuring nobody.+const lookupTimeout = 5 * time.Second++// Info is the subset of an account Beacon needs: who they are, and where their configuration goes.+type Info struct {+ Username string+ UID int+ GID int+ HomeDir string+}++// runGetent is a var so tests can exercise the parsing and the failure modes without depending on+// the host's account database, which is the one thing a test cannot arrange portably.+var runGetent = func(ctx context.Context, name string) (string, error) {+ // Resolved explicitly so a missing getent is reported as "no NSS available" rather than as an+ // opaque exec failure, and so the absence is distinguishable from a lookup miss.+ path, err := exec.LookPath("getent")+ if err != nil {+ return "", fmt.Errorf("getent is not available: %w", err)+ }+ // argv, never a shell: the name arrives from SUDO_USER or logind, and passing it as a single+ // argument means no quoting scheme has to be correct for it to be safe.+ out, err := exec.CommandContext(ctx, path, "passwd", name).Output()+ return string(out), err+}++// Lookup resolves a username, consulting NSS when the local account database cannot answer.+//+// The ladder is ordered by cost and certainty: the local database first, since it is in-process+// and covers every ordinary host, then NSS. A caller that also has a home directory to fall back+// on should do so only after this returns an error.+func Lookup(name string) (Info, error) {+ name = strings.TrimSpace(name)+ if name == "" {+ return Info{}, fmt.Errorf("no username given")+ }+ if u, err := user.Lookup(name); err == nil {+ info, convErr := fromUser(u)+ if convErr == nil {+ return info, nil+ }+ // A resolvable account with an unparseable uid is a broken database rather than a missing+ // user, but NSS may still have a usable answer, so fall through rather than fail here.+ }+ ctx, cancel := context.WithTimeout(context.Background(), lookupTimeout)+ defer cancel()+ out, err := runGetent(ctx, name)+ if err != nil {+ return Info{}, fmt.Errorf("%q is not in the local account database and NSS could not resolve it: %w", name, err)+ }+ return parsePasswdLine(out, name)+}++func fromUser(u *user.User) (Info, error) {+ uid, err := strconv.Atoi(u.Uid)+ if err != nil {+ return Info{}, fmt.Errorf("uid %q is not numeric: %w", u.Uid, err)+ }+ gid, err := strconv.Atoi(u.Gid)+ if err != nil {+ return Info{}, fmt.Errorf("gid %q is not numeric: %w", u.Gid, err)+ }+ return Info{Username: u.Username, UID: uid, GID: gid, HomeDir: u.HomeDir}, nil+}++// parsePasswdLine reads one getent passwd record: name:passwd:uid:gid:gecos:home:shell.+//+// getent returns at most one record for a name query, but the output is scanned line by line+// anyway so a trailing newline or a stray banner cannot turn a good answer into a parse failure.+func parsePasswdLine(out, want string) (Info, error) {+ for _, line := range strings.Split(out, "\n") {+ line = strings.TrimRight(line, "\r")+ if strings.TrimSpace(line) == "" {+ continue+ }+ fields := strings.Split(line, ":")+ if len(fields) < 7 {+ continue+ }+ uid, err := strconv.Atoi(fields[2])+ if err != nil {+ continue+ }+ gid, err := strconv.Atoi(fields[3])+ if err != nil {+ continue+ }+ if fields[0] == "" || fields[5] == "" {+ continue+ }+ // The record's own name is preferred over the requested spelling: a directory service may+ // answer a differently-cased query with the account's canonical name, and the canonical one+ // is what ownership and re-execution should use.+ return Info{Username: fields[0], UID: uid, GID: gid, HomeDir: fields[5]}, nil+ }+ return Info{}, fmt.Errorf("no usable passwd record for %q", want)+}diff --git a/cli/beacon/internal/osuser/osuser_test.go b/cli/beacon/internal/osuser/osuser_test.gonew file mode 100644index 00000000..23a53c62--- /dev/null+++ b/cli/beacon/internal/osuser/osuser_test.go@@ -0,0 +1,127 @@+package osuser++import (+ "context"+ "errors"+ "os/user"+ "strconv"+ "strings"+ "testing"+)++// The parser is the part that runs against output this process did not produce, so it is the part+// worth pinning. A directory service answers in the same seven-field format as /etc/passwd.+func TestParsePasswdLineReadsAnNSSRecord(t *testing.T) {+ got, err := parsePasswdLine("alice:x:10001:10002::/home/alice:/bin/bash\n", "alice")+ if err != nil {+ t.Fatal(err)+ }+ want := Info{Username: "alice", UID: 10001, GID: 10002, HomeDir: "/home/alice"}+ if got != want {+ t.Errorf("parsePasswdLine = %+v, want %+v", got, want)+ }+}++// A record whose uid or home is unusable must not resolve to a half-populated Info: the caller+// would chown to uid 0 or write settings into "", both of which are worse than reporting that the+// user could not be resolved.+func TestParsePasswdLineRejectsUnusableRecords(t *testing.T) {+ for name, out := range map[string]string{+ "too few fields": "alice:x:10001:10002:/home/alice\n",+ "non-numeric uid": "alice:x:notanumber:10002::/home/alice:/bin/bash\n",+ "non-numeric gid": "alice:x:10001:nope::/home/alice:/bin/bash\n",+ "empty home": "alice:x:10001:10002:::/bin/bash\n",+ "empty name": ":x:10001:10002::/home/alice:/bin/bash\n",+ "no output": "",+ "banner only": "getent: something went sideways\n",+ } {+ t.Run(name, func(t *testing.T) {+ if got, err := parsePasswdLine(out, "alice"); err == nil {+ t.Errorf("parsePasswdLine(%q) = %+v, want an error", out, got)+ }+ })+ }+}++// A directory service may answer a differently-cased query with the account's canonical name.+// Ownership and re-execution should use what the directory says, not what the caller typed.+func TestParsePasswdLinePrefersTheCanonicalName(t *testing.T) {+ got, err := parsePasswdLine("alice:x:10001:10002::/home/alice:/bin/bash\n", "Alice")+ if err != nil {+ t.Fatal(err)+ }+ if got.Username != "alice" {+ t.Errorf("Username = %q, want the record's own spelling %q", got.Username, "alice")+ }+}++// The whole point of the package: an account the local database cannot see, which NSS can. This is+// the Tower Research case, and before this package it resolved to "no such user".+func TestLookupFallsBackToNSS(t *testing.T) {+ restore := runGetent+ t.Cleanup(func() { runGetent = restore })+ runGetent = func(_ context.Context, name string) (string, error) {+ if name != "ldapuser" {+ t.Errorf("getent asked for %q, want %q", name, "ldapuser")+ }+ return "ldapuser:x:20001:20002::/home/ldapuser:/bin/bash\n", nil+ }++ got, err := Lookup("ldapuser")+ if err != nil {+ t.Fatalf("Lookup fell through to an error for an NSS-resolvable account: %v", err)+ }+ if got.UID != 20001 || got.HomeDir != "/home/ldapuser" {+ t.Errorf("Lookup = %+v, want uid 20001 and home /home/ldapuser", got)+ }+}++// A stripped image may not ship getent. Degrading to an error is correct -- the callers already+// handle an unresolvable user -- but the error has to say which of the two things went wrong, or+// the operator cannot tell "no such account" from "this host cannot answer the question".+func TestLookupReportsWhyWhenNSSIsUnavailable(t *testing.T) {+ restore := runGetent+ t.Cleanup(func() { runGetent = restore })+ runGetent = func(context.Context, string) (string, error) {+ return "", errors.New("exec: \"getent\": executable file not found in $PATH")+ }++ _, err := Lookup("ldapuser")+ if err == nil {+ t.Fatal("Lookup succeeded with no local record and no NSS")+ }+ for _, want := range []string{"ldapuser", "NSS"} {+ if !strings.Contains(err.Error(), want) {+ t.Errorf("error %q should mention %q so the failure is attributable", err, want)+ }+ }+}++// The fast path must still work, and must not consult NSS for an account the local database can+// already answer -- that would put a subprocess on the hot path of every ordinary host.+func TestLookupUsesTheLocalDatabaseFirst(t *testing.T) {+ me, err := user.Current()+ if err != nil || me.Username == "" {+ t.Skip("no resolvable current user on this host")+ }+ restore := runGetent+ t.Cleanup(func() { runGetent = restore })+ runGetent = func(context.Context, string) (string, error) {+ t.Error("NSS was consulted for an account the local database can resolve")+ return "", errors.New("should not be reached")+ }++ got, err := Lookup(me.Username)+ if err != nil {+ t.Fatal(err)+ }+ if strconv.Itoa(got.UID) != me.Uid {+ t.Errorf("UID = %d, want %s", got.UID, me.Uid)+ }+}++func TestLookupRejectsAnEmptyName(t *testing.T) {+ if _, err := Lookup(" "); err == nil {+ t.Error("an empty username must not resolve")+ }+}diff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.goindex a97550a8..ceadd69f 100644--- a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go@@ -1584,43 +1584,13 @@ func HarnessName(attrs map[string]interface{}, hints ...string) string {return "otel"}+// NormalizeHarnessName maps a runtime's self-reported name onto Beacon's canonical harness name.+//+// Delegates to the shared module rather than keeping its own copy: the hook path writes the same+// field from a different process, and when the two mappings drifted a single session was recorded+// under two names. Keeping one implementation is what stops that recurring.func NormalizeHarnessName(name string) string {- lower := strings.ToLower(strings.TrimSpace(name))- switch {- case lower == "":- return ""- case strings.Contains(lower, "cowork") || strings.Contains(lower, "co-work"):- return "claude_cowork"- case strings.Contains(lower, "claude_agent_sdk") || strings.Contains(lower, "claude-agent-sdk") || strings.Contains(lower, "claude agent sdk"):- return "claude_agent_sdk"- // Browser-based chat collectors (agent-beacon-browser-extension). These must- // precede the generic "claude" rule below, which would otherwise coerce- // claude_web → claude_code.- case strings.Contains(lower, "claude_web") || strings.Contains(lower, "claude-web") || lower == "claude.ai":- return "claude_web"- case strings.Contains(lower, "chatgpt") || lower == "chatgpt.com" || strings.Contains(lower, "openai_web"):- return "chatgpt_web"- case strings.Contains(lower, "claude_code") || strings.Contains(lower, "claude-code") || strings.Contains(lower, "claude code") || strings.HasPrefix(lower, "claude_code."):- return "claude_code"- case lower == "claude" || strings.Contains(lower, "claude"):- return "claude_code"- case strings.Contains(lower, "openclaw") || strings.Contains(lower, "open-claw"):- return "openclaw_gateway"- case strings.Contains(lower, "antigravity") || strings.Contains(lower, "anti-gravity"):- return "antigravity_cli"- case strings.Contains(lower, "codex"):- return "codex_cli"- case strings.Contains(lower, "gemini"):- return "gemini_cli"- case strings.Contains(lower, "copilot-chat"):- return "vscode_copilot"- case strings.Contains(lower, "github-copilot") || strings.Contains(lower, "copilot_cli") || strings.Contains(lower, "copilot"):- return "copilot_cli"- case name != "":- return name- default:- return ""- }+ return asymptoteobserve.NormalizeHarnessName(name)}func InferAction(attrs map[string]interface{}, fallback string) string {diff --git a/docs/cli/manual-install.mdx b/docs/cli/manual-install.mdxindex d4b36595..7ef929b4 100644--- a/docs/cli/manual-install.mdx+++ b/docs/cli/manual-install.mdx@@ -5,7 +5,30 @@ description: "Install the Beacon CLI from platform archives or build it from sou## Archive Collection-Beacon releases publish platform archives for macOS and Linux on `amd64` and `arm64`. Each archive includes the `beacon` CLI and the matching `beacon-otelcol` collector binary, with SHA-256 checksums published alongside the release.+Beacon releases publish platform archives for macOS and Linux on `amd64` and `arm64`, plus a+`.zip` for Windows. Each archive contains three binaries — the `beacon` CLI, the `beacon-hooks`+adapter that captures tool activity, and the matching `beacon-otelcol` collector — with SHA-256+checksums published alongside the release in `checksums.txt`.++All three matter. `beacon-hooks` is what supported runtimes invoke to record prompts, tool calls,+and approvals, so an install that keeps only the CLI and the collector captures OpenTelemetry data+and nothing from the hook path.++```bash title="Download, verify, and extract (Linux amd64)"+VERSION=1.2.0 # or whichever release you are installing+BASE=https://github.com/asymptote-labs/agent-beacon/releases/download/v${VERSION}+curl -fsSLO ${BASE}/beacon_${VERSION}_linux_amd64.tar.gz+curl -fsSLO ${BASE}/checksums.txt+sha256sum --check --ignore-missing checksums.txt++tar -xzf beacon_${VERSION}_linux_amd64.tar.gz+mkdir -p ~/.local/bin && mv beacon beacon-hooks beacon-otelcol ~/.local/bin/+beacon version+```++Swap `linux_amd64` for `linux_arm64`, `darwin_arm64`, or `darwin_amd64` as needed; on macOS use+`shasum -a 256 -c` in place of `sha256sum --check`. The archive layout is identical across+platforms.For managed endpoint rollouts on Apple Silicon Macs, GitHub Releases also attacha signed, notarized, and stapled `BeaconEndpointAgent-<version>-arm64.pkg`. Thediff --git a/docs/get-started/quickstart-developers.mdx b/docs/get-started/quickstart-developers.mdxindex 54a7d33d..589a5054 100644--- a/docs/get-started/quickstart-developers.mdx+++ b/docs/get-started/quickstart-developers.mdx@@ -17,18 +17,27 @@ beacon endpoint install``````bash title="Linux"-# Download the .deb or .rpm for your architecture from the latest release.-# Installing it performs the endpoint setup for you.-sudo apt install ./beacon_<version>_linux_amd64.deb+VERSION=1.2.0 # or whichever release you are installing+curl -fsSLO https://github.com/asymptote-labs/agent-beacon/releases/download/v${VERSION}/beacon_${VERSION}_linux_amd64.tar.gz+curl -fsSLO https://github.com/asymptote-labs/agent-beacon/releases/download/v${VERSION}/checksums.txt+sha256sum --check --ignore-missing checksums.txt++tar -xzf beacon_${VERSION}_linux_amd64.tar.gz+mkdir -p ~/.local/bin && mv beacon beacon-hooks beacon-otelcol ~/.local/bin/+beacon endpoint install```</CodeGroup>-On Linux the package installs a system-mode endpoint managed by systemd, so the paths differ from the-per-user layout described above — see [Linux](/platforms/linux). For a per-user Linux install instead,-run `beacon endpoint install` after installing the CLI.+<Note>+ The Linux tab uses the tarball on purpose. This page is a per-user setup, and the `.deb`/`.rpm`+ packages install a **system-mode** endpoint managed by systemd — which writes to+ `/var/log/beacon-agent/runtime.jsonl` instead, so every command below would report on the wrong+ log. If you want the system-mode package, follow [Linux](/platforms/linux) instead of this page.+</Note>See [Asymptote Open Source](/deployment/open-source) for install details and runtime-specific notes,-or [macOS](/platforms/macos) for the platform detail.+or [macOS](/platforms/macos), [Linux](/platforms/linux), or [Windows](/platforms/windows) for the+platform detail.## 2. Confirm collection healthdiff --git a/docs/platforms/linux.mdx b/docs/platforms/linux.mdxindex cdc2d2b2..84523f11 100644--- a/docs/platforms/linux.mdx+++ b/docs/platforms/linux.mdx@@ -21,11 +21,40 @@ sudo apt install ./beacon_<version>_linux_amd64.deb``````bash title="Fedora, RHEL, Rocky, Alma"-sudo dnf install ./beacon-<version>-linux-amd64.rpm+sudo dnf install ./beacon_<version>_linux_amd64.rpm```</CodeGroup>-`amd64` and `arm64` packages are published for both formats.+`amd64` and `arm64` packages are published for both formats. The package puts `beacon` on your+`PATH`, so every command below works by name.++### Without root, or without a package manager++If you are not an administrator on the machine, or you would rather not touch system paths, use the+tarball and install in user mode:++```bash title="Tarball install, no root required"+VERSION=1.2.0 # or whichever release you are installing+curl -fsSLO https://github.com/asymptote-labs/agent-beacon/releases/download/v${VERSION}/beacon_${VERSION}_linux_amd64.tar.gz+curl -fsSLO https://github.com/asymptote-labs/agent-beacon/releases/download/v${VERSION}/checksums.txt++# Verify before extracting. This is the integrity check for the tarball.+sha256sum --check --ignore-missing checksums.txt++tar -xzf beacon_${VERSION}_linux_amd64.tar.gz+mkdir -p ~/.local/bin && mv beacon beacon-hooks beacon-otelcol ~/.local/bin/++# ~/.local/bin is already on PATH on most distributions; if `beacon version` fails, add it:+# echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc && exec $SHELL+beacon version+beacon endpoint install+```++The archive contains three binaries — the `beacon` CLI, the `beacon-hooks` adapter that captures+tool activity, and the `beacon-otelcol` collector. All three are needed, and all three are+statically linked with no shared-library dependencies.++See [User-mode install](#user-mode-install) for what this sets up and its one caveat.<Note>The package depends on systemd, because the service it registers is a systemd unit. On a@@ -64,6 +93,22 @@ Summary: 0 failure(s), 1 warning(s)That says "configured correctly, but you have not used it yet." It clears the first time you runyour agent. What matters is `0 failure(s)`.+<Warning>+ One failure is worth knowing by name, because a system endpoint can be perfectly healthy and+ still be capturing nobody:++ ```+ console_user_configured: fail target=alice (alice has no agent runtime pointed at this+ collector, so their sessions are not being captured)+ action="sudo beacon endpoint user-config repair-installed --system"+ ```++ A system-mode endpoint runs as root, so it has to work out *whose* agent settings to configure.+ If it could not identify you at install time, the collector still starts and reports healthy —+ it simply has nothing sending to it. Run the action above as the user whose sessions should be+ captured and it clears.+</Warning>+If you would rather confirm the pipeline before running a real session, write a synthetic event:```bash title="Prove the collector is receiving and writing events"diff --git a/packaging/linux/smoke-package.sh b/packaging/linux/smoke-package.shindex d735ca50..e0e9812d 100755--- a/packaging/linux/smoke-package.sh+++ b/packaging/linux/smoke-package.sh@@ -164,6 +164,26 @@ adapter_owner="$(docker exec "$CONTAINER" stat -c %U "$ADAPTER" 2>/dev/null || techo "$ADAPTER is owned by $adapter_owner, not $SMOKE_USER" >&2; exit 1; }echo "ok: hooks installed for the user and runnable by them"+# Reachable by name, not just by absolute path.+#+# Every check in this file used /opt/beacon/bin/beacon, so the package could ship with nothing on+# PATH and this smoke test would still pass -- which is exactly what happened. The documentation+# and this package's own postinstall both tell the user to run `beacon endpoint status --system`,+# and that failed with "command not found" on a correctly installed system.+#+# Checked as the unprivileged user and through sudo, because they resolve differently: sudo+# replaces PATH with secure_path, so a symlink somewhere only the user's PATH covers would pass+# one and fail the other, and most system-mode documentation is written with sudo.+docker exec "$CONTAINER" su - "$SMOKE_USER" -c 'command -v beacon' >/dev/null 2>&1 || {+ echo "beacon is not on PATH for $SMOKE_USER, so every documented command fails for them" >&2+ exit 1; }+docker exec "$CONTAINER" sh -c 'command -v beacon' >/dev/null 2>&1 || {+ echo "beacon is not on root's PATH, so the sudo form of every documented command fails" >&2+ exit 1; }+docker exec "$CONTAINER" su - "$SMOKE_USER" -c 'beacon --version' >/dev/null 2>&1 || {+ echo "beacon resolves on PATH but does not execute" >&2; exit 1; }+echo "ok: beacon is reachable by name, as the documentation says it is"+# The two commands the docs tell a new user to run. Both must report healthy with no manual setup.if ! docker exec "$CONTAINER" /opt/beacon/bin/beacon endpoint status --system --json >/tmp/beacon-status.json 2>&1; thenecho "endpoint status failed:" >&2; cat /tmp/beacon-status.json >&2; exit 1diff --git a/pkg/asymptoteobserve/harness.go b/pkg/asymptoteobserve/harness.gonew file mode 100644index 00000000..2eb59d00--- /dev/null+++ b/pkg/asymptoteobserve/harness.go@@ -0,0 +1,68 @@+package asymptoteobserve++import "strings"++// NormalizeHarnessName maps whatever a runtime calls itself onto Beacon's canonical harness name.+//+// This lives in the shared module because two independent paths write the same field and must+// agree. The OTLP path derives a name from resource attributes and event names in the collector+// exporter; the hook path takes it from the `--platform` value it was installed with. They+// disagreed: one session produced both `claude` and `claude_code`, which splits that session in+// two for any query, dashboard, or SIEM detection that groups by harness.name -- exactly what a+// customer forwarding to Sentinel does.+//+// Normalizing at the point of writing rather than at every point of reading is deliberate. The+// alternative pushes the inconsistency onto every consumer, including consumers we do not own,+// and `harness.name` is a release contract that downstream queries are written against.+//+// The `--platform` flag is intentionally left alone: it identifies the runtime being hooked and+// is part of the hook command written into settings.json, so changing it would only take effect+// after every existing install were rewritten. Mapping at write time fixes existing installs too.+//+// Ordering matters. The browser-chat cases must precede the generic "claude" rule, which would+// otherwise coerce claude_web into claude_code.+func NormalizeHarnessName(name string) string {+ lower := strings.ToLower(strings.TrimSpace(name))+ switch {+ case lower == "":+ return ""+ case strings.Contains(lower, "cowork") || strings.Contains(lower, "co-work"):+ return "claude_cowork"+ case strings.Contains(lower, "claude_agent_sdk") || strings.Contains(lower, "claude-agent-sdk") || strings.Contains(lower, "claude agent sdk"):+ return "claude_agent_sdk"+ case strings.Contains(lower, "claude_web") || strings.Contains(lower, "claude-web") || lower == "claude.ai":+ return "claude_web"+ case strings.Contains(lower, "chatgpt") || lower == "chatgpt.com" || strings.Contains(lower, "openai_web"):+ return "chatgpt_web"+ case strings.Contains(lower, "claude_code") || strings.Contains(lower, "claude-code") || strings.Contains(lower, "claude code") || strings.HasPrefix(lower, "claude_code."):+ return "claude_code"+ case lower == "claude" || strings.Contains(lower, "claude"):+ return "claude_code"+ case strings.Contains(lower, "openclaw") || strings.Contains(lower, "open-claw"):+ return "openclaw_gateway"+ case strings.Contains(lower, "antigravity") || strings.Contains(lower, "anti-gravity"):+ return "antigravity_cli"+ case strings.Contains(lower, "codex"):+ return "codex_cli"+ case strings.Contains(lower, "gemini"):+ return "gemini_cli"+ // Every VS Code spelling resolves before the generic copilot rule below, which contains+ // "copilot" and would otherwise swallow them. Two consequences of getting this wrong, both+ // real: the hook path installs with --platform vscode while the OTLP path reports+ // vscode_copilot, so one session was recorded under two names; and vscode_copilot itself+ // normalized to copilot_cli, which is a different product -- meaning the canonical name was+ // not stable under re-normalization and VS Code activity was attributed to the Copilot CLI.+ case strings.Contains(lower, "copilot-chat") || strings.Contains(lower, "vscode_copilot") ||+ strings.Contains(lower, "vscode-copilot") || strings.Contains(lower, "vscode") ||+ strings.Contains(lower, "vs code"):+ return "vscode_copilot"+ case strings.Contains(lower, "github-copilot") || strings.Contains(lower, "copilot_cli") || strings.Contains(lower, "copilot"):+ return "copilot_cli"+ case name != "":+ // An unrecognized runtime keeps its own name rather than being coerced or dropped. A new+ // harness should show up in the log as itself, not as "unknown".+ return name+ default:+ return ""+ }+}diff --git a/pkg/asymptoteobserve/harness_test.go b/pkg/asymptoteobserve/harness_test.gonew file mode 100644index 00000000..2b5f6134--- /dev/null+++ b/pkg/asymptoteobserve/harness_test.go@@ -0,0 +1,84 @@+package asymptoteobserve++import "testing"++// The property this function exists for: two independent writers must produce the same name for+// the same session. The hook path installs with --platform <runtime> and the OTLP path derives a+// name from resource attributes; before these were normalized through one function, a single+// Claude Code session was recorded as both "claude" and "claude_code", which splits it for any+// query, dashboard, or SIEM detection that groups by harness.name.+func TestHookPlatformsConvergeOnCanonicalNames(t *testing.T) {+ // Keys are the --platform values the hook installers use (see+ // cli/beacon/internal/endpoint/hooks/*.go); values are what the OTLP path reports.+ for platform, want := range map[string]string{+ "claude": "claude_code",+ "codex": "codex_cli",+ "gemini": "gemini_cli",+ "antigravity": "antigravity_cli",+ "vscode": "vscode_copilot",+ } {+ t.Run(platform, func(t *testing.T) {+ if got := NormalizeHarnessName(platform); got != want {+ t.Errorf("NormalizeHarnessName(%q) = %q, want %q -- the hook and OTLP paths would "++ "record one session under two names", platform, got, want)+ }+ })+ }+}++// Normalizing an already-canonical name must return it unchanged. Without this, a value that has+// been through the function once changes meaning when it goes through again -- and vscode_copilot+// did exactly that, collapsing into copilot_cli, which is a different product. Anything that+// re-reads and re-writes an event would have silently reassigned VS Code activity to the CLI.+func TestCanonicalNamesAreStableUnderRenormalization(t *testing.T) {+ for _, canonical := range []string{+ "claude_code", "codex_cli", "gemini_cli", "antigravity_cli", "vscode_copilot",+ "copilot_cli", "claude_web", "chatgpt_web", "claude_cowork", "claude_agent_sdk",+ "openclaw_gateway",+ } {+ t.Run(canonical, func(t *testing.T) {+ if got := NormalizeHarnessName(canonical); got != canonical {+ t.Errorf("NormalizeHarnessName(%q) = %q; a canonical name must survive being "++ "normalized again", canonical, got)+ }+ })+ }+}++// Ordering is load-bearing: the browser and VS Code cases sit before broader rules that would+// otherwise swallow them. These are the pairs where one name is a substring of another's rule.+func TestNarrowerRuntimesWinOverBroaderRules(t *testing.T) {+ for input, want := range map[string]string{+ "claude.ai": "claude_web", // not claude_code+ "claude_web": "claude_web", // not claude_code+ "claude-code": "claude_code", // not claude_web+ "copilot-chat": "vscode_copilot", // not copilot_cli+ "github-copilot": "copilot_cli", // not vscode_copilot+ "claude_agent_sdk": "claude_agent_sdk",+ "claude_cowork": "claude_cowork",+ } {+ t.Run(input, func(t *testing.T) {+ if got := NormalizeHarnessName(input); got != want {+ t.Errorf("NormalizeHarnessName(%q) = %q, want %q", input, got, want)+ }+ })+ }+}++// An unrecognized runtime keeps its own name. Coercing it to "unknown" would erase the one clue+// available when a new harness starts reporting, and these names reach customer dashboards.+func TestUnknownRuntimesKeepTheirName(t *testing.T) {+ for _, name := range []string{"cursor", "hermes", "opencode", "factory", "grok"} {+ if got := NormalizeHarnessName(name); got != name {+ t.Errorf("NormalizeHarnessName(%q) = %q, want it preserved", name, got)+ }+ }+}++func TestEmptyNameStaysEmpty(t *testing.T) {+ for _, in := range []string{"", " ", "\t"} {+ if got := NormalizeHarnessName(in); got != "" {+ t.Errorf("NormalizeHarnessName(%q) = %q, want empty", in, got)+ }+ }+}