Skip to content

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

Install and reconcile the scheduled inventory job in both modes

shukieshahe40a73a58034
diff --git a/cli/beacon/cmd/endpoint.go b/cli/beacon/cmd/endpoint.go
index 65c78fc9..3f4e39fe 100644
--- a/cli/beacon/cmd/endpoint.go
+++ b/cli/beacon/cmd/endpoint.go
@@ -374,6 +374,7 @@ func init() {
endpointCmd.AddCommand(endpointUserConfigCmd)
endpointCmd.AddCommand(endpointConfigCmd)
endpointInventoryCmd.AddCommand(endpointInventoryHeartbeatCmd)
+ endpointInventoryCmd.AddCommand(endpointInventoryInstallDaemonCmd)
endpointConfigCmd.AddCommand(endpointConfigShowCmd)
endpointConfigCmd.AddCommand(endpointConfigValidateCmd)
endpointIntegrationsCmd.AddCommand(endpointIntegrationsValidateCmd)
@@ -397,7 +398,7 @@ func init() {
endpointVSCodeCmd.AddCommand(endpointVSCodeStatusCmd)
endpointVSCodeCmd.AddCommand(endpointVSCodeValidateCmd)
- for _, c := range []*cobra.Command{endpointInstallCmd, endpointStatusCmd, endpointDoctorCmd, endpointInventoryCmd, endpointInventoryHeartbeatCmd, endpointDiscoverCmd, endpointTestEventCmd, endpointBundleDiagnosticsCmd, endpointUninstallCmd, endpointRepairCmd, endpointConfigShowCmd, endpointConfigValidateCmd, endpointIntegrationsValidateCmd, endpointUserConfigRepairInstalledCmd, topLevelDoctorCmd, topLevelStatusCmd, topLevelInventoryCmd} {
+ for _, c := range []*cobra.Command{endpointInstallCmd, endpointStatusCmd, endpointDoctorCmd, endpointInventoryCmd, endpointInventoryHeartbeatCmd, endpointInventoryInstallDaemonCmd, endpointDiscoverCmd, endpointTestEventCmd, endpointBundleDiagnosticsCmd, endpointUninstallCmd, endpointRepairCmd, endpointConfigShowCmd, endpointConfigValidateCmd, endpointIntegrationsValidateCmd, endpointUserConfigRepairInstalledCmd, topLevelDoctorCmd, topLevelStatusCmd, topLevelInventoryCmd} {
c.Flags().BoolVar(&endpointOpts.userMode, "user", true, "Use per-user endpoint paths")
c.Flags().BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths and the system collector service")
c.Flags().StringVar(&endpointOpts.logPath, "log-path", "", "Runtime JSONL log path")
diff --git a/cli/beacon/cmd/endpoint_diagnostics.go b/cli/beacon/cmd/endpoint_diagnostics.go
index 8bc931da..9f1a6d9b 100644
--- a/cli/beacon/cmd/endpoint_diagnostics.go
+++ b/cli/beacon/cmd/endpoint_diagnostics.go
@@ -845,10 +845,15 @@ func plannedInstallActions(repair bool, kind service.Kind) []plannedAction {
if unitPath, err := mgr.UnitPath(); err == nil {
serviceAction.Target = unitPath
}
+ inventoryAction := plannedAction{Action: "write_unit", Message: "scheduled inventory heartbeat job"}
+ if unitPath, err := (service.InventoryManager{UserMode: cfg.UserMode, Kind: kind}).UnitPath(); err == nil {
+ inventoryAction.Target = unitPath
+ }
actions = append(actions,
plannedAction{Action: "write_file", Target: cfg.Collector.ConfigPath, Message: "collector configuration"},
serviceAction,
plannedAction{Action: "write_file", Target: endpointconfig.ConfigPath(cfg.UserMode), Message: "endpoint configuration"},
+ inventoryAction,
)
for _, h := range otlpTargets {
actions = append(actions, plannedAction{Action: "configure_harness", Target: h})
@@ -857,14 +862,20 @@ func plannedInstallActions(repair bool, kind service.Kind) []plannedAction {
actions = append(actions, plannedAction{Action: "configure_harness", Target: h, Message: "install endpoint hook integration"})
}
if !endpointOpts.noStart {
- actions = append(actions, plannedAction{Action: "load_service", Message: "start endpoint collector service"})
+ actions = append(actions,
+ plannedAction{Action: "load_service", Message: "start endpoint collector service"},
+ plannedAction{Action: "load_service", Message: "start scheduled inventory heartbeat job"},
+ )
}
return actions
}
func plannedUninstallActions() []plannedAction {
cfg := loadOrDefaultConfig()
- actions := []plannedAction{{Action: "unload_service", Message: "stop endpoint collector service if present"}}
+ actions := []plannedAction{
+ {Action: "unload_service", Message: "stop endpoint collector service if present"},
+ {Action: "unload_service", Message: "remove scheduled inventory heartbeat job if present"},
+ }
if !endpointOpts.keepConfig {
actions = append(actions, plannedAction{Action: "restore_backup", Message: "restore backed up harness configs when available"})
}
diff --git a/cli/beacon/cmd/endpoint_install.go b/cli/beacon/cmd/endpoint_install.go
index e9025f2a..29777922 100644
--- a/cli/beacon/cmd/endpoint_install.go
+++ b/cli/beacon/cmd/endpoint_install.go
@@ -133,6 +133,12 @@ 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)
+ switch {
+ case result.InventoryJobPath != "":
+ fmt.Printf("Scheduled inventory job: %s\n", result.InventoryJobPath)
+ case result.InventoryJobDetail != "":
+ fmt.Printf("Scheduled inventory job not installed: %s\n", result.InventoryJobDetail)
+ }
printLingerGap(cmd.ErrOrStderr(), result)
if err := installHookTargetsFromEndpointInstall(hookHarnesses); err != nil {
return fmt.Errorf("endpoint install completed, but hook installation failed: %w", err)
@@ -187,6 +193,7 @@ func runEndpointStatus(cmd *cobra.Command, args []string) error {
fmt.Println("Last event: present")
}
fmt.Println(managedIngestStatusLine(status.ManagedIngest))
+ fmt.Println(inventoryHeartbeatStatusLine(status.InventoryHeartbeat))
return nil
}
diff --git a/cli/beacon/cmd/endpoint_inventory_service.go b/cli/beacon/cmd/endpoint_inventory_service.go
new file mode 100644
index 00000000..c77dfb99
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_inventory_service.go
@@ -0,0 +1,70 @@
+package cmd
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/spf13/cobra"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
+)
+
+// reconcileInventoryJob is indirected so the command can be tested without a scheduler.
+var reconcileInventoryJob = lifecycle.ReconcileInventoryJob
+
+// endpointInventoryInstallDaemonCmd is invoked by the package postinstall (and available to
+// operators) to make the scheduled inventory job match the endpoint config: installed and
+// loaded unless `inventory_heartbeat.enabled` is false. Loading fires a heartbeat at once.
+var endpointInventoryInstallDaemonCmd = &cobra.Command{
+ Use: "install-daemon",
+ Short: "Internal: reconcile the scheduled inventory job with the endpoint config",
+ Hidden: true,
+ SilenceUsage: true,
+ RunE: runInventoryInstallDaemon,
+}
+
+func runInventoryInstallDaemon(cmd *cobra.Command, args []string) error {
+ userMode := endpointUserMode()
+ if !userMode && !lifecycle.HasSystemPrivileges() {
+ return fmt.Errorf("managing the system inventory job needs elevated privileges; %s", lifecycle.SystemPrivilegeHint())
+ }
+ result, err := reconcileInventoryJob(lifecycle.InventoryJobOptions{
+ UserMode: userMode,
+ Program: lifecycle.DefaultInventoryJobProgram(userMode),
+ LogPath: endpointOpts.logPath,
+ Load: true,
+ })
+ if err != nil {
+ return err
+ }
+ fmt.Println(inventoryReconcileMessage(result))
+ return nil
+}
+
+func inventoryReconcileMessage(result lifecycle.InventoryJobResult) string {
+ switch {
+ case result.Skipped != "":
+ return "Scheduled inventory job not installed: " + result.Skipped
+ case result.Removed:
+ return "Inventory heartbeat is disabled in config; scheduled job removed."
+ default:
+ return "Scheduled inventory job installed (" + result.UnitPath + ")."
+ }
+}
+
+func inventoryHeartbeatStatusLine(status lifecycle.InventoryHeartbeatStatus) string {
+ if !status.Enabled {
+ return "Inventory heartbeat: disabled in config"
+ }
+ var b strings.Builder
+ fmt.Fprintf(&b, "Inventory heartbeat: scheduled every %s; job loaded=%t running=%t", status.Interval, status.Job.Loaded, status.Job.Running)
+ if !status.Job.Loaded && status.Job.Message != "" {
+ fmt.Fprintf(&b, " (%s)", status.Job.Message)
+ }
+ if status.LastEmittedAt != "" {
+ fmt.Fprintf(&b, "; last emitted %s", status.LastEmittedAt)
+ } else {
+ b.WriteString("; last emitted never")
+ }
+ return b.String()
+}
diff --git a/cli/beacon/cmd/endpoint_inventory_service_test.go b/cli/beacon/cmd/endpoint_inventory_service_test.go
new file mode 100644
index 00000000..972710e7
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_inventory_service_test.go
@@ -0,0 +1,65 @@
+package cmd
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"
+)
+
+func TestInventoryInstallDaemonReconcilesTheRequestedMode(t *testing.T) {
+ oldOpts := endpointOpts
+ oldReconcile := reconcileInventoryJob
+ t.Cleanup(func() {
+ endpointOpts = oldOpts
+ reconcileInventoryJob = oldReconcile
+ })
+ var got lifecycle.InventoryJobOptions
+ reconcileInventoryJob = func(opts lifecycle.InventoryJobOptions) (lifecycle.InventoryJobResult, error) {
+ got = opts
+ return lifecycle.InventoryJobResult{Enabled: true, UnitPath: "/fake/plist", Loaded: true}, nil
+ }
+ endpointOpts.userMode, endpointOpts.systemMode = true, false
+ endpointOpts.logPath = "/tmp/scratch/runtime.jsonl"
+ if err := runInventoryInstallDaemon(nil, nil); err != nil {
+ t.Fatal(err)
+ }
+ if !got.UserMode || !got.Load || got.LogPath != "/tmp/scratch/runtime.jsonl" || got.Program == "" {
+ t.Fatalf("reconcile options = %+v", got)
+ }
+}
+
+func TestInventoryReconcileMessages(t *testing.T) {
+ cases := map[string]lifecycle.InventoryJobResult{
+ "Scheduled inventory job not installed: no scheduler": {Skipped: "no scheduler"},
+ "Inventory heartbeat is disabled in config; scheduled job removed.": {Removed: true},
+ "Scheduled inventory job installed (/Library/LaunchDaemons/x.plist).": {Enabled: true, UnitPath: "/Library/LaunchDaemons/x.plist", Loaded: true},
+ }
+ for want, result := range cases {
+ if got := inventoryReconcileMessage(result); got != want {
+ t.Fatalf("message for %+v = %q, want %q", result, got, want)
+ }
+ }
+}
+
+func TestInventoryHeartbeatStatusLine(t *testing.T) {
+ disabled := inventoryHeartbeatStatusLine(lifecycle.InventoryHeartbeatStatus{Enabled: false})
+ if disabled != "Inventory heartbeat: disabled in config" {
+ t.Fatalf("disabled line = %q", disabled)
+ }
+ never := inventoryHeartbeatStatusLine(lifecycle.InventoryHeartbeatStatus{
+ Enabled: true, Interval: "6h0m0s", Job: service.Status{Loaded: false, Message: "Could not find service"},
+ })
+ for _, want := range []string{"scheduled every 6h0m0s", "job loaded=false running=false", "(Could not find service)", "last emitted never"} {
+ if !strings.Contains(never, want) {
+ t.Fatalf("line %q missing %q", never, want)
+ }
+ }
+ live := inventoryHeartbeatStatusLine(lifecycle.InventoryHeartbeatStatus{
+ Enabled: true, Interval: "6h0m0s", Job: service.Status{Loaded: true, Running: true}, LastEmittedAt: "2026-09-15T20:00:00Z",
+ })
+ if !strings.Contains(live, "job loaded=true running=true; last emitted 2026-09-15T20:00:00Z") || strings.Contains(live, "(") {
+ t.Fatalf("live line = %q", live)
+ }
+}
diff --git a/cli/beacon/cmd/endpoint_test.go b/cli/beacon/cmd/endpoint_test.go
index 5ba77cb3..a72760b5 100644
--- a/cli/beacon/cmd/endpoint_test.go
+++ b/cli/beacon/cmd/endpoint_test.go
@@ -94,6 +94,18 @@ func TestPlannedInstallActionsSeparatesHookHarnesses(t *testing.T) {
if counts["devin"] != 0 {
t.Fatalf("legacy devin alias should be deduped, counts=%#v", counts)
}
+ inventoryUnits := 0
+ for _, action := range actions {
+ if action.Action == "write_unit" && action.Message == "scheduled inventory heartbeat job" {
+ inventoryUnits++
+ }
+ if action.Action == "load_service" {
+ t.Fatalf("--no-start plan must not load anything: %+v", action)
+ }
+ }
+ if inventoryUnits != 1 {
+ t.Fatalf("plan should write the scheduled inventory job once, got %d in %+v", inventoryUnits, actions)
+ }
}
func TestRepairInstalledEndpointUserConfigConfiguresNativeAndHooks(t *testing.T) {
diff --git a/cli/beacon/internal/endpoint/lifecycle/inventory_job_test.go b/cli/beacon/internal/endpoint/lifecycle/inventory_job_test.go
new file mode 100644
index 00000000..7c8ab9d2
--- /dev/null
+++ b/cli/beacon/internal/endpoint/lifecycle/inventory_job_test.go
@@ -0,0 +1,240 @@
+package lifecycle
+
+import (
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"
+)
+
+// recordingInventoryJob stands in for service.InventoryManager and records what lifecycle asked of it.
+type recordingInventoryJob struct {
+ calls *[]string
+ supported bool
+ unitPath string
+}
+
+func (r recordingInventoryJob) Supported() bool { return r.supported }
+func (r recordingInventoryJob) UnsupportedReason() string { return "no scheduler in this test" }
+func (r recordingInventoryJob) UnitPath() (string, error) { return r.unitPath, nil }
+func (r recordingInventoryJob) WriteUnit(program, logPath string) (string, error) {
+ *r.calls = append(*r.calls, "write "+program+" "+logPath)
+ return r.unitPath, nil
+}
+func (r recordingInventoryJob) Load() error { *r.calls = append(*r.calls, "load"); return nil }
+func (r recordingInventoryJob) Unload() error { *r.calls = append(*r.calls, "unload"); return nil }
+func (r recordingInventoryJob) RemoveUnits() { *r.calls = append(*r.calls, "remove") }
+func (r recordingInventoryJob) Status() service.Status { return service.Status{} }
+
+func installFakeInventoryJob(t *testing.T, supported bool) *[]string {
+ t.Helper()
+ calls := &[]string{}
+ old := newInventoryJob
+ newInventoryJob = func(userMode bool, kind service.Kind) inventoryJobController {
+ return recordingInventoryJob{calls: calls, supported: supported, unitPath: "/fake/" + InventoryUnitName(userMode)}
+ }
+ t.Cleanup(func() { newInventoryJob = old })
+ return calls
+}
+
+func InventoryUnitName(userMode bool) string {
+ if userMode {
+ return "user.plist"
+ }
+ return "system.plist"
+}
+
+func writeInventoryConfig(t *testing.T, userMode bool, body string) {
+ t.Helper()
+ path := endpointconfig.ConfigPath(userMode)
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// No config at all is the fresh-install case, and it must mean enabled: the job is on by default.
+func TestReconcileInventoryJobWritesAndLoadsWhenEnabled(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ calls := installFakeInventoryJob(t, true)
+ result, err := ReconcileInventoryJob(InventoryJobOptions{UserMode: true, Program: "/usr/local/bin/beacon", LogPath: "/tmp/runtime.jsonl", Load: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !result.Enabled || !result.Loaded || result.Removed || result.Skipped != "" || result.UnitPath != "/fake/user.plist" {
+ t.Fatalf("result = %+v", result)
+ }
+ if got := strings.Join(*calls, ","); got != "write /usr/local/bin/beacon /tmp/runtime.jsonl,load" {
+ t.Fatalf("calls = %q", got)
+ }
+}
+
+func TestReconcileInventoryJobUnloadsAndRemovesWhenDisabled(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ writeInventoryConfig(t, true, `{"user_mode":true,"inventory_heartbeat":{"enabled":false}}`)
+ calls := installFakeInventoryJob(t, true)
+ result, err := ReconcileInventoryJob(InventoryJobOptions{UserMode: true, Program: "/usr/local/bin/beacon", Load: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if result.Enabled || !result.Removed || result.Loaded || result.UnitPath != "" {
+ t.Fatalf("result = %+v", result)
+ }
+ if got := strings.Join(*calls, ","); got != "unload,remove" {
+ t.Fatalf("calls = %q", got)
+ }
+}
+
+func TestReconcileInventoryJobSkipsUnsupportedWithoutError(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ calls := installFakeInventoryJob(t, false)
+ result, err := ReconcileInventoryJob(InventoryJobOptions{UserMode: true, Program: "/usr/local/bin/beacon", Load: true})
+ if err != nil {
+ t.Fatalf("an unsupported host must not error: %v", err)
+ }
+ if result.Skipped == "" || result.Loaded || result.UnitPath != "" || len(*calls) != 0 {
+ t.Fatalf("result = %+v calls = %q", result, *calls)
+ }
+}
+
+func TestReconcileInventoryJobWritesWithoutLoadingWhenAsked(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ calls := installFakeInventoryJob(t, true)
+ result, err := ReconcileInventoryJob(InventoryJobOptions{UserMode: true, Program: "/usr/local/bin/beacon", Load: false})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if result.Loaded || result.UnitPath == "" || strings.Join(*calls, ",") != "write /usr/local/bin/beacon " {
+ t.Fatalf("result = %+v calls = %q", result, *calls)
+ }
+}
+
+func TestInventoryEnabledFromConfigFileDefaultsToTrue(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "config.json")
+ if !inventoryEnabledFromConfigFile(path) {
+ t.Fatal("missing config must mean enabled")
+ }
+ for body, want := range map[string]bool{
+ `{}`: true,
+ `{"inventory_heartbeat":{}}`: true,
+ `{"inventory_heartbeat":{"enabled":true}}`: true,
+ `{"inventory_heartbeat":{"enabled":false}}`: false,
+ `{"inventory_heartbeat":{"enabled":false,"ttl_seconds":86400}}`: false,
+ `not json`: true,
+ } {
+ if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if got := inventoryEnabledFromConfigFile(path); got != want {
+ t.Fatalf("%s: enabled = %t, want %t", body, got, want)
+ }
+ }
+}
+
+// A package upgrade re-runs install, which rebuilds config.json from defaults. An operator's
+// explicit `enabled: false` has to survive that, or the job would silently come back.
+func TestBuildConfigPreservesInventoryBlock(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ writeInventoryConfig(t, true, `{"user_mode":true,"log_path":"/tmp/runtime.jsonl","inventory_heartbeat":{"enabled":false,"runtimes":["cursor"]}}`)
+ cfg := buildConfig(InstallOptions{UserMode: true})
+ if cfg.Inventory == nil || cfg.Inventory.Enabled == nil || *cfg.Inventory.Enabled || len(cfg.Inventory.Runtimes) != 1 {
+ t.Fatalf("buildConfig dropped the inventory block: %+v", cfg.Inventory)
+ }
+}
+
+func TestInstallWritesTheInventoryJobWithoutLoadingItOnNoStart(t *testing.T) {
+ if runtime.GOOS != "darwin" {
+ t.Skip("install preflight is macOS-only")
+ }
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ collectorPath := filepath.Join(home, "bin", "beacon-otelcol")
+ if err := os.MkdirAll(filepath.Dir(collectorPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(collectorPath, []byte("#!/bin/sh\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ calls := installFakeInventoryJob(t, true)
+ logPath := filepath.Join(home, ".beacon", "endpoint", "logs", "runtime.jsonl")
+ result, err := Install(InstallOptions{
+ UserMode: true,
+ LogPath: logPath,
+ Harnesses: []string{},
+ GRPCPort: freePort(t),
+ HTTPPort: freePort(t),
+ CollectorPath: collectorPath,
+ StartService: false,
+ })
+ if err != nil {
+ t.Fatalf("Install: %v", err)
+ }
+ if result.InventoryJobPath != "/fake/user.plist" || result.InventoryJobDetail != "" {
+ t.Fatalf("result inventory fields = %q / %q", result.InventoryJobPath, result.InventoryJobDetail)
+ }
+ if got := strings.Join(*calls, ","); !strings.HasPrefix(got, "write ") || strings.Contains(got, "load") {
+ t.Fatalf("--no-start must write the unit and not load it: %q", got)
+ }
+ if !strings.HasSuffix((*calls)[0], " "+logPath) {
+ t.Fatalf("the unit must pin the install's runtime log: %q", (*calls)[0])
+ }
+ manifest, err := ReadManifest(true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(manifest.Files) != 3 {
+ t.Fatalf("the inventory unit is owned by the reconcile, not the manifest: %#v", manifest.Files)
+ }
+}
+
+func TestInstallReportsAHostWithoutASchedulerAndStillSucceeds(t *testing.T) {
+ if runtime.GOOS != "darwin" {
+ t.Skip("install preflight is macOS-only")
+ }
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ collectorPath := filepath.Join(home, "bin", "beacon-otelcol")
+ if err := os.MkdirAll(filepath.Dir(collectorPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(collectorPath, []byte("#!/bin/sh\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ calls := installFakeInventoryJob(t, false)
+ result, err := Install(InstallOptions{
+ UserMode: true,
+ LogPath: filepath.Join(home, ".beacon", "endpoint", "logs", "runtime.jsonl"),
+ Harnesses: []string{},
+ GRPCPort: freePort(t),
+ HTTPPort: freePort(t),
+ CollectorPath: collectorPath,
+ StartService: false,
+ })
+ if err != nil {
+ t.Fatalf("a missing scheduler must not fail the install: %v", err)
+ }
+ if result.InventoryJobPath != "" || result.InventoryJobDetail == "" || len(*calls) != 0 {
+ t.Fatalf("result = %+v calls = %q", result, *calls)
+ }
+}
+
+func TestUninstallRemovesTheInventoryJobForTheMode(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ old := removeInventoryJob
+ var removedFor []bool
+ removeInventoryJob = func(userMode bool) { removedFor = append(removedFor, userMode) }
+ t.Cleanup(func() { removeInventoryJob = old })
+ if err := Uninstall(UninstallOptions{UserMode: true}); err != nil {
+ t.Fatal(err)
+ }
+ if len(removedFor) != 1 || !removedFor[0] {
+ t.Fatalf("uninstall should remove the user-mode inventory job once, got %v", removedFor)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
index 6cfe4b19..17950838 100644
--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
@@ -13,6 +13,7 @@ import (
endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/diagnostics"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/harness"
+ endpointinventory "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/inventory"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/selfupdate"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"
@@ -30,8 +31,143 @@ var (
_ = updater.Unload()
updater.RemoveUnits()
}
+ // newInventoryJob and removeInventoryJob are the seams tests replace so Install, Uninstall
+ // and Repair can be exercised without touching launchd or systemd.
+ newInventoryJob = func(userMode bool, kind service.Kind) inventoryJobController {
+ return service.InventoryManager{UserMode: userMode, Kind: kind}
+ }
+ removeInventoryJob = func(userMode bool) {
+ job := newInventoryJob(userMode, service.KindAuto)
+ _ = job.Unload()
+ job.RemoveUnits()
+ }
)
+// inventoryJobController is what lifecycle needs from service.InventoryManager.
+type inventoryJobController interface {
+ Supported() bool
+ UnsupportedReason() string
+ UnitPath() (string, error)
+ WriteUnit(program, logPath string) (string, error)
+ Load() error
+ Unload() error
+ RemoveUnits()
+ Status() service.Status
+}
+
+// InventoryJobOptions drives ReconcileInventoryJob.
+type InventoryJobOptions struct {
+ UserMode bool
+ Kind service.Kind
+ // Program is the beacon binary the scheduler invokes.
+ Program string
+ // LogPath pins the runtime log the inventory log sits beside; empty means the mode's default.
+ LogPath string
+ // Load activates the schedule after writing the unit. False writes the unit only (--no-start).
+ Load bool
+}
+
+// InventoryJobResult reports what ReconcileInventoryJob did.
+type InventoryJobResult struct {
+ Enabled bool `json:"enabled"`
+ UnitPath string `json:"unit_path,omitempty"`
+ Loaded bool `json:"loaded"`
+ Removed bool `json:"removed"`
+ // Skipped names why no job was installed on a host without a scheduler.
+ Skipped string `json:"skipped,omitempty"`
+}
+
+// ReconcileInventoryJob makes the scheduled inventory job match the endpoint config for the
+// mode: installed and loaded when `inventory_heartbeat.enabled` is true or absent (the default),
+// removed when it is false. It runs on every install, repair and package upgrade, which is how
+// an endpoint installed before the job existed gets it without anyone doing anything.
+func ReconcileInventoryJob(opts InventoryJobOptions) (InventoryJobResult, error) {
+ return reconcileInventoryJobWith(newInventoryJob(opts.UserMode, opts.Kind), opts)
+}
+
+func reconcileInventoryJobWith(job inventoryJobController, opts InventoryJobOptions) (InventoryJobResult, error) {
+ result := InventoryJobResult{Enabled: inventoryEnabledFromConfigFile(endpointconfig.ConfigPath(opts.UserMode))}
+ if !job.Supported() {
+ result.Skipped = job.UnsupportedReason()
+ return result, nil
+ }
+ if !result.Enabled {
+ _ = job.Unload()
+ job.RemoveUnits()
+ result.Removed = true
+ return result, nil
+ }
+ path, err := job.WriteUnit(opts.Program, opts.LogPath)
+ if err != nil {
+ return result, err
+ }
+ result.UnitPath = path
+ if opts.Load {
+ if err := job.Load(); err != nil {
+ return result, err
+ }
+ result.Loaded = true
+ }
+ return result, nil
+}
+
+// inventoryEnabledFromConfigFile reads only the inventory_heartbeat.enabled key. A missing or
+// unreadable config, or an absent key, means enabled: the job is on by default.
+func inventoryEnabledFromConfigFile(path string) bool {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return true
+ }
+ var partial struct {
+ Inventory *endpointconfig.Inventory `json:"inventory_heartbeat"`
+ }
+ if err := json.Unmarshal(data, &partial); err != nil || partial.Inventory == nil || partial.Inventory.Enabled == nil {
+ return true
+ }
+ return *partial.Inventory.Enabled
+}
+
+// DefaultInventoryJobProgram is the binary the scheduled job should run: this one. Under the
+// package postinstall that is /opt/beacon/bin/beacon; under Homebrew it is the keg's binary.
+func DefaultInventoryJobProgram(userMode bool) string {
+ if exe, err := os.Executable(); err == nil {
+ if resolved, err := filepath.EvalSymlinks(exe); err == nil {
+ return resolved
+ }
+ return exe
+ }
+ if !userMode {
+ return selfupdate.SystemBeaconPath()
+ }
+ return "beacon"
+}
+
+// InventoryHeartbeatStatus is the status view of the scheduled inventory job.
+type InventoryHeartbeatStatus struct {
+ Enabled bool `json:"enabled"`
+ Scheduled bool `json:"scheduled"`
+ Interval string `json:"interval"`
+ Job service.Status `json:"job"`
+ LastEmittedAt string `json:"last_emitted_at,omitempty"`
+ LogPath string `json:"log_path"`
+}
+
+func inventoryHeartbeatStatus(requestedUserMode bool, logPath string) InventoryHeartbeatStatus {
+ cfg := loadOrDefault(requestedUserMode, logPath)
+ job := newInventoryJob(requestedUserMode, service.KindAuto).Status()
+ status := InventoryHeartbeatStatus{
+ Enabled: endpointconfig.InventoryConfig(cfg).Enabled,
+ Scheduled: job.Loaded,
+ Interval: service.InventoryInterval().String(),
+ Job: job,
+ LogPath: endpointinventory.LogPath(cfg.LogPath, requestedUserMode),
+ }
+ if state, err := endpointinventory.ReadState(endpointinventory.StatePathForLog(cfg.LogPath, requestedUserMode)); err == nil {
+ status.LastEmittedAt = state.LastEmittedAt
+ }
+ return status
+}
+
type InstallOptions struct {
UserMode bool
LogPath string
@@ -71,6 +207,10 @@ type InstallResult struct {
LingerEnabled bool `json:"linger_enabled,omitempty"`
LingerDetail string `json:"linger_detail,omitempty"`
LingerRemediation string `json:"linger_remediation,omitempty"`
+ // The scheduled inventory job is reconciled on every install; a host without a scheduler
+ // reports why in InventoryJobDetail and the install still succeeds.
+ InventoryJobPath string `json:"inventory_job_path,omitempty"`
+ InventoryJobDetail string `json:"inventory_job_detail,omitempty"`
}
type Status struct {
@@ -85,6 +225,8 @@ type Status struct {
LastEvent string `json:"last_event,omitempty"`
Destinations DestinationStatus `json:"destinations"`
ManagedIngest asymptote.ManagedIngestStatus `json:"managed_ingest"`
+ // InventoryHeartbeat follows the requested mode, like ManagedIngest: each mode has its own job.
+ InventoryHeartbeat InventoryHeartbeatStatus `json:"inventory_heartbeat"`
}
type DestinationStatus struct {
@@ -277,6 +419,26 @@ func Install(opts InstallOptions) (InstallResult, error) {
return InstallResult{}, err
}
+ // The scheduled inventory job is on by default and reconciled on every install, which is
+ // how a package upgrade turns it on for an endpoint installed before it existed. The unit is
+ // tracked for rollback but kept out of the manifest, like the updater's, and a host with no
+ // scheduler does not fail the install: it is reported and the endpoint still collects.
+ inventoryJob := newInventoryJob(cfg.UserMode, opts.ServiceKind)
+ if path, err := inventoryJob.UnitPath(); err == nil {
+ tx.Track(path)
+ }
+ inventoryResult, inventoryErr := reconcileInventoryJobWith(inventoryJob, InventoryJobOptions{
+ UserMode: cfg.UserMode,
+ Kind: opts.ServiceKind,
+ Program: DefaultInventoryJobProgram(cfg.UserMode),
+ LogPath: cfg.LogPath,
+ Load: opts.StartService,
+ })
+ inventoryDetail := inventoryResult.Skipped
+ if inventoryErr != nil {
+ inventoryDetail = inventoryErr.Error()
+ }
+
harnessPaths, err := configureHarnesses(cfg)
manifest.HarnessConfigs = harnessPaths
manifest.Backups = discoverBackups(harnessPaths)
@@ -365,6 +527,8 @@ func Install(opts InstallOptions) (InstallResult, error) {
LingerEnabled: lingerOutcome.Enabled,
LingerDetail: lingerOutcome.Detail,
LingerRemediation: lingerOutcome.Remediation,
+ InventoryJobPath: inventoryResult.UnitPath,
+ InventoryJobDetail: inventoryDetail,
}, nil
}
@@ -406,6 +570,7 @@ func Uninstall(opts UninstallOptions) error {
if !cfg.UserMode && !opts.KeepUpdater {
removeUpdaterJob()
}
+ removeInventoryJob(cfg.UserMode)
// The managed-ingest forwarder and its credentials go with the endpoint; server-side the
// device stays registered until it is revoked from the dashboard.
fail("disconnect managed ingest", asymptote.Disconnect(asymptote.DisconnectOptions{
@@ -582,17 +747,18 @@ func buildStatus(requestedUserMode bool, effectiveCfg endpointconfig.Config, run
})
}
return Status{
- Version: version.GetVersion(),
- ConfigPath: endpointconfig.ConfigPath(effectiveCfg.UserMode),
- LogPath: effectiveCfg.LogPath,
- RuntimeLog: runtimeLog,
- Collector: endpointcollector.CheckStatus(effectiveCfg),
- Service: service.Manager{UserMode: effectiveCfg.UserMode}.Status(),
- Harnesses: harness.DiscoverAll(),
- Diagnostics: checks,
- LastEvent: last,
- Destinations: destinationStatus(effectiveCfg),
- ManagedIngest: asymptote.Status(requestedUserMode, managedOpts),
+ Version: version.GetVersion(),
+ ConfigPath: endpointconfig.ConfigPath(effectiveCfg.UserMode),
+ LogPath: effectiveCfg.LogPath,
+ RuntimeLog: runtimeLog,
+ Collector: endpointcollector.CheckStatus(effectiveCfg),
+ Service: service.Manager{UserMode: effectiveCfg.UserMode}.Status(),
+ Harnesses: harness.DiscoverAll(),
+ Diagnostics: checks,
+ LastEvent: last,
+ Destinations: destinationStatus(effectiveCfg),
+ ManagedIngest: asymptote.Status(requestedUserMode, managedOpts),
+ InventoryHeartbeat: inventoryHeartbeatStatus(requestedUserMode, runtimeLog.RequestedLogPath),
}
}
@@ -644,8 +810,15 @@ func buildConfig(opts InstallOptions) endpointconfig.Config {
}
// A re-install (upgrades run one) must not disconnect the machine on paper: the
// managed_ingest block is owned by connect/disconnect, so carry the existing one over.
- if existing, err := endpointconfig.Load(opts.UserMode); err == nil && existing.ManagedIngest != nil {
- cfg.ManagedIngest = existing.ManagedIngest
+ // The same goes for inventory_heartbeat: an operator's `enabled: false` must survive the
+ // package upgrade that re-runs install, or the scheduled job would come back.
+ if existing, err := endpointconfig.Load(opts.UserMode); err == nil {
+ if existing.ManagedIngest != nil {
+ cfg.ManagedIngest = existing.ManagedIngest
+ }
+ if existing.Inventory != nil {
+ cfg.Inventory = existing.Inventory
+ }
}
if opts.Harnesses != nil {
cfg.Harnesses = opts.Harnesses