The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
feat(endpoint): add check-only self-update monitor
shukieshahd6c8faa7c4cc
diff --git a/cli/beacon/cmd/endpoint_test.go b/cli/beacon/cmd/endpoint_test.goindex b417607c..45ba40a6 100644--- a/cli/beacon/cmd/endpoint_test.go+++ b/cli/beacon/cmd/endpoint_test.go@@ -1143,6 +1143,26 @@ func TestRunEndpointInventoryWriteEventHonorsConfigContentOptIn(t *testing.T) {}}+func TestEndpointUpdateCommandsRegistered(t *testing.T) {+ for _, path := range [][]string{+ {"update"},+ {"update", "enable"},+ {"update", "disable"},+ {"update", "status"},+ } {+ cmd, _, err := endpointCmd.Find(path)+ if err != nil {+ t.Fatalf("endpoint command %v not registered: %v", path, err)+ }+ if cmd == nil {+ t.Fatalf("endpoint command %v not registered", path)+ }+ }+ if cmd, _, err := rootCmd.Find([]string{"update"}); err == nil && cmd != nil && cmd.Name() == "update" {+ t.Fatal("top-level update command should not be registered")+ }+}+func TestCompletionAndDocsCommandsRegistered(t *testing.T) {for _, name := range []string{"completion", "docs"} {cmd, _, err := rootCmd.Find([]string{name})diff --git a/cli/beacon/cmd/endpoint_update.go b/cli/beacon/cmd/endpoint_update.gonew file mode 100644index 00000000..85563245--- /dev/null+++ b/cli/beacon/cmd/endpoint_update.go@@ -0,0 +1,124 @@+package cmd++import (+ "context"+ "fmt"+ "time"++ "github.com/spf13/cobra"++ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/selfupdate"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version"+)++var endpointUpdateOpts struct {+ check bool+}++var endpointUpdateCmd = &cobra.Command{+ Use: "update",+ Short: "Check for Beacon endpoint agent updates",+ Long: `Check for a newer signed and notarized Beacon endpoint package without+downloading or applying it. Phase 1 is check-only: it can surface update status+and write local system-log events, but it never mutates the install.`,+ SilenceUsage: true,+ RunE: runEndpointUpdate,+}++func init() {+ // `update` lives under `endpoint` only; a top-level `update` command is+ // intentionally not exposed (the public command-tree smoke test forbids it).+ endpointCmd.AddCommand(endpointUpdateCmd)+ endpointUpdateCmd.Flags().BoolVar(&endpointUpdateOpts.check, "check", false, "Only report whether an update is available; do not apply")+}++// configAutoUpdateMode returns the locally configured auto-update mode.+//+// The system config is authoritative for the system install the self-updater+// governs: if it loads at all, its value wins (empty means "use the default"),+// and we never fall through to a user-mode config an operator could set under+// ~/.beacon — which, being visible under sudo, would otherwise override the+// system/managed intent. The user config is consulted only when there is no+// system config (i.e. a user-mode install).+func configAutoUpdateMode() string {+ if cfg, err := endpointconfig.Load(false); err == nil {+ if cfg.AutoUpdate != nil {+ return cfg.AutoUpdate.Mode+ }+ return ""+ }+ if cfg, err := endpointconfig.Load(true); err == nil && cfg.AutoUpdate != nil {+ return cfg.AutoUpdate.Mode+ }+ return ""+}++func runEndpointUpdate(cmd *cobra.Command, args []string) error {+ if endpointUpdateServiceOpts.scheduled {+ return runScheduledUpdate(cmd.Context())+ }++ ctx, cancel := context.WithTimeout(cmd.Context(), 15*time.Second)+ defer cancel()++ current := version.GetVersion()+ res, err := selfupdate.CheckWithMode(ctx, current, configAutoUpdateMode())+ if err != nil {+ _ = selfupdate.EmitCheckEvent(selfupdate.CheckEventOptions{+ Result: res,+ Action: selfupdate.EventCheckFailed,+ Reason: err.Error(),+ LogPath: endpointSystemLogPath(),+ AgentVersion: current,+ })+ return fmt.Errorf("update check failed: %w", err)+ }+ action, reason := selfupdate.CheckOutcome(res)+ if err := selfupdate.EmitCheckEvent(selfupdate.CheckEventOptions{+ Result: res,+ Action: action,+ Reason: reason,+ LogPath: endpointSystemLogPath(),+ AgentVersion: current,+ }); err != nil {+ return fmt.Errorf("write update check event: %w", err)+ }++ switch {+ case res.CurrentIsDev:+ fmt.Println("beacon is a dev build; skipping update check.")+ return nil+ case res.UnsupportedCurrentVersion:+ fmt.Printf("beacon version %q cannot be compared to releases; skipping update check.\n", current)+ return nil+ }++ if !res.UpdateAvailable {+ fmt.Printf("beacon %s is up to date.\n", res.CurrentVersion)+ return nil+ }++ fmt.Printf("Beacon %s is available (current: %s).\n", res.LatestVersion, res.CurrentVersion)+ if res.BelowMinSupported {+ fmt.Printf("This build is below the minimum supported version; updating is strongly recommended.\n")+ }++ switch res.Install.Kind {+ case selfupdate.InstallHomebrew:+ fmt.Println("Installed via Homebrew. Update with:")+ fmt.Println(" brew upgrade beacon")+ return nil+ case selfupdate.InstallOther:+ fmt.Printf("Endpoint package checks apply only to the system package install.\n")+ return nil+ }++ if !res.HasArtifact {+ fmt.Printf("No signed endpoint package artifact is available for %s.\n", res.ArchKey)+ return nil+ }++ fmt.Println("Check-only mode: no package was downloaded or applied.")+ return nil+}diff --git a/cli/beacon/cmd/endpoint_update_service.go b/cli/beacon/cmd/endpoint_update_service.gonew file mode 100644index 00000000..7b8efc88--- /dev/null+++ b/cli/beacon/cmd/endpoint_update_service.go@@ -0,0 +1,189 @@+package cmd++import (+ "context"+ "fmt"+ "os"+ "time"++ "github.com/spf13/cobra"++ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/selfupdate"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version"+)++var endpointUpdateServiceOpts struct {+ checkOnly bool+ scheduled bool+}++var endpointUpdateEnableCmd = &cobra.Command{+ Use: "enable",+ Short: "Enable check-only update monitoring",+ SilenceUsage: true,+ RunE: runUpdateEnable,+}++var endpointUpdateDisableCmd = &cobra.Command{+ Use: "disable",+ Short: "Disable automatic updates and remove the background updater",+ SilenceUsage: true,+ RunE: runUpdateDisable,+}++var endpointUpdateStatusCmd = &cobra.Command{+ Use: "status",+ Short: "Show auto-update mode and updater daemon status",+ SilenceUsage: true,+ RunE: runUpdateStatus,+}++func init() {+ endpointUpdateCmd.AddCommand(endpointUpdateEnableCmd)+ endpointUpdateCmd.AddCommand(endpointUpdateDisableCmd)+ endpointUpdateCmd.AddCommand(endpointUpdateStatusCmd)+ endpointUpdateEnableCmd.Flags().BoolVar(&endpointUpdateServiceOpts.checkOnly, "check-only", false, "Enable periodic checks without applying updates")+ // The launchd job runs `update --scheduled`; Phase 1 is check-only. Hidden+ // from the user-facing help.+ endpointUpdateCmd.Flags().BoolVar(&endpointUpdateServiceOpts.scheduled, "scheduled", false, "Internal: run as the scheduled updater job")+ _ = endpointUpdateCmd.Flags().MarkHidden("scheduled")+}++// setConfigAutoUpdateMode persists the auto-update mode in the system endpoint+// config, creating a default config if none exists.+func setConfigAutoUpdateMode(mode string) error {+ cfg, err := endpointconfig.Load(false)+ if err != nil {+ if !os.IsNotExist(err) {+ return err+ }+ cfg = endpointconfig.Default(false, writer.DefaultPath(false))+ }+ cfg.UserMode = false+ cfg.AutoUpdate = &endpointconfig.AutoUpdate{Mode: mode}+ _, err = endpointconfig.Save(cfg)+ return err+}++func requireRootForUpdater() error {+ if os.Geteuid() != 0 {+ return fmt.Errorf("managing the background updater requires root; rerun with sudo")+ }+ return nil+}++func runUpdateEnable(cmd *cobra.Command, args []string) error {+ if err := requireRootForUpdater(); err != nil {+ return err+ }+ if !endpointUpdateServiceOpts.checkOnly {+ return fmt.Errorf("phase 1 supports check-only monitoring only; rerun with --check-only")+ }+ mode := selfupdate.ModeCheckOnly+ if err := setConfigAutoUpdateMode(string(mode)); err != nil {+ return fmt.Errorf("write auto-update config: %w", err)+ }+ mgr := service.UpdaterManager{}+ if _, err := mgr.WritePlist(selfupdate.SystemBeaconPath()); err != nil {+ return fmt.Errorf("write updater plist: %w", err)+ }+ if err := mgr.Load(); err != nil {+ return fmt.Errorf("load updater job: %w", err)+ }+ fmt.Printf("Update checks enabled (mode: %s).\n", mode)+ return nil+}++func runUpdateDisable(cmd *cobra.Command, args []string) error {+ if err := requireRootForUpdater(); err != nil {+ return err+ }+ if err := setConfigAutoUpdateMode(string(selfupdate.ModeOff)); err != nil {+ return fmt.Errorf("write auto-update config: %w", err)+ }+ mgr := service.UpdaterManager{}+ if err := mgr.Unload(); err != nil {+ return fmt.Errorf("unload updater job: %w", err)+ }+ _ = os.Remove(mgr.PlistPath())+ fmt.Println("Update checks disabled; background updater removed.")+ return nil+}++func runUpdateStatus(cmd *cobra.Command, args []string) error {+ mode := selfupdate.ResolveMode(configAutoUpdateMode())+ install := selfupdate.DetectInstall()+ fmt.Printf("Update mode: %s\n", mode)+ fmt.Printf("Install kind: %s\n", install.Kind)+ st := service.UpdaterManager{}.Status()+ fmt.Printf("Updater daemon: loaded=%t running=%t\n", st.Loaded, st.Running)+ if st.Message != "" {+ fmt.Printf(" %s\n", st.Message)+ }+ return nil+}++// runScheduledUpdate is the entrypoint the launchd job calls. Phase 1 only+// performs check-only monitoring and writes a local system-log event.+func runScheduledUpdate(parent context.Context) error {+ mode := selfupdate.ResolveMode(configAutoUpdateMode())+ if mode == selfupdate.ModeOff {+ current := version.GetVersion()+ res := selfupdate.CheckResult{Mode: mode}+ _ = selfupdate.EmitCheckEvent(selfupdate.CheckEventOptions{+ Result: res,+ Action: selfupdate.EventUnsupported,+ Reason: "mode_off",+ LogPath: endpointSystemLogPath(),+ AgentVersion: current,+ })+ fmt.Println("Update checks are off; nothing to do.")+ return nil+ }+ if mode != selfupdate.ModeCheckOnly {+ return fmt.Errorf("phase 1 scheduled updater supports check-only mode only (resolved: %s)", mode)+ }++ current := version.GetVersion()+ ctx, cancel := context.WithTimeout(parent, 30*time.Second)+ defer cancel()+ res, err := selfupdate.CheckWithMode(ctx, current, configAutoUpdateMode())+ if err != nil {+ _ = selfupdate.EmitCheckEvent(selfupdate.CheckEventOptions{+ Result: res,+ Action: selfupdate.EventCheckFailed,+ Reason: err.Error(),+ LogPath: endpointSystemLogPath(),+ AgentVersion: current,+ })+ return fmt.Errorf("update check failed: %w", err)+ }+ action, reason := selfupdate.CheckOutcome(res)+ if err := selfupdate.EmitCheckEvent(selfupdate.CheckEventOptions{+ Result: res,+ Action: action,+ Reason: reason,+ LogPath: endpointSystemLogPath(),+ AgentVersion: current,+ }); err != nil {+ return fmt.Errorf("write update check event: %w", err)+ }+ if action == selfupdate.EventAvailable {+ fmt.Printf("Update available: %s (current %s). check-only mode; not applying.\n", res.LatestVersion, res.CurrentVersion)+ }+ return nil+}++func endpointSystemLogPath() string {+ if endpointUpdateServiceOpts.scheduled {+ return selfupdate.SystemLogPath(writer.DefaultPath(false), false)+ }+ cfg := loadOrDefaultConfig()+ if endpointOpts.logPath != "" {+ cfg.LogPath = endpointOpts.logPath+ }+ return selfupdate.SystemLogPath(cfg.LogPath, cfg.UserMode)+}diff --git a/cli/beacon/internal/endpoint/config/config.go b/cli/beacon/internal/endpoint/config/config.goindex 440bb7f8..1f0775c7 100644--- a/cli/beacon/internal/endpoint/config/config.go+++ b/cli/beacon/internal/endpoint/config/config.go@@ -30,6 +30,13 @@ type Config struct {Inventory *Inventory `json:"inventory_heartbeat,omitempty"`Destinations *Destinations `json:"destinations,omitempty"`ManagedUpload *ManagedUpload `json:"managed_upload,omitempty"`+ AutoUpdate *AutoUpdate `json:"auto_update,omitempty"`+}++// AutoUpdate controls Beacon's endpoint update checker. Phase 1 supports+// check-only/off behavior; an empty mode uses the built-in default of off.+type AutoUpdate struct {+ Mode string `json:"mode,omitempty"`}type Collector struct {diff --git a/cli/beacon/internal/endpoint/selfupdate/check.go b/cli/beacon/internal/endpoint/selfupdate/check.gonew file mode 100644index 00000000..647470c5--- /dev/null+++ b/cli/beacon/internal/endpoint/selfupdate/check.go@@ -0,0 +1,69 @@+package selfupdate++import (+ "context"+ "net/http"+ "os"+ "strings"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/updatecheck"+)++// CheckResult is the outcome of a read-only update check.+type CheckResult struct {+ updatecheck.ManifestResult+ Install Install+ Mode Mode+ ArchKey string+ Artifact updatecheck.Artifact+ HasArtifact bool+}++// resolveManifestURL picks the manifest URL with precedence env > managed >+// default, mirroring ResolveMode's "managed can override default, env wins".+func resolveManifestURL() string {+ if v := strings.TrimSpace(os.Getenv(updatecheck.ManifestURLEnv)); v != "" {+ return v+ }+ if m := ManagedManifestURL(); m != "" {+ return m+ }+ return updatecheck.DefaultManifestURL+}++// Check fetches the manifest and compares it to the running build with the+// default mode resolution (no local config input). It performs no privileged+// actions and makes a single network request.+func Check(ctx context.Context, currentVersion string) (CheckResult, error) {+ return CheckWithMode(ctx, currentVersion, "")+}++// CheckWithMode is Check with the local config mode value as the+// lowest-precedence input to mode resolution (env > managed > localMode).+func CheckWithMode(ctx context.Context, currentVersion, localMode string) (CheckResult, error) {+ res := CheckResult{+ Install: DetectInstall(),+ Mode: ResolveMode(localMode),+ ArchKey: updatecheck.RuntimeArchKey(),+ }++ src := updatecheck.ManifestSource{+ Client: &http.Client{Timeout: 10 * time.Second},+ Endpoint: resolveManifestURL(),+ }+ manifest, err := src.Fetch(ctx)+ if err != nil {+ return res, err+ }+ eval, err := updatecheck.EvaluateManifest(currentVersion, manifest)+ if err != nil {+ return res, err+ }+ res.ManifestResult = eval+ if a, ok := manifest.ArtifactFor(res.ArchKey); ok {+ res.Artifact = a+ res.HasArtifact = true+ }+ return res, nil+}diff --git a/cli/beacon/internal/endpoint/selfupdate/mode.go b/cli/beacon/internal/endpoint/selfupdate/mode.gonew file mode 100644index 00000000..09aee851--- /dev/null+++ b/cli/beacon/internal/endpoint/selfupdate/mode.go@@ -0,0 +1,101 @@+package selfupdate++import (+ "encoding/json"+ "os"+ "path/filepath"+ "strings"+)++// Mode controls self-updater behavior.+type Mode string++const (+ // ModeAuto checks for and applies updates seamlessly.+ ModeAuto Mode = "auto"+ // ModeCheckOnly surfaces an available update but never applies it.+ ModeCheckOnly Mode = "check-only"+ // ModeOff disables the background updater entirely.+ ModeOff Mode = "off"+)++// DefaultMode is the built-in default when nothing overrides it. Auto-update is+// off by default: the background updater is opt-in via `beacon endpoint update+// enable`, an env override, or a managed profile.+const DefaultMode = ModeOff++// AutoUpdateEnv overrides the resolved mode for a single invocation.+const AutoUpdateEnv = "BEACON_AUTO_UPDATE"++// ManagedConfigPath is where an MDM/enterprise profile can drop settings that+// override the local config (but not an explicit env override).+var ManagedConfigPath = filepath.Join(SystemSupportDir, "managed.json")++// ParseMode normalizes a mode string. It accepts the canonical values plus the+// legacy boolean forms (1/true/on => auto, 0/false/off/no => off).+func ParseMode(s string) (Mode, bool) {+ switch strings.ToLower(strings.TrimSpace(s)) {+ case "auto", "1", "true", "on", "enable", "enabled":+ return ModeAuto, true+ case "check-only", "check", "checkonly":+ return ModeCheckOnly, true+ case "off", "0", "false", "no", "disable", "disabled":+ return ModeOff, true+ default:+ return "", false+ }+}++// managedConfig is the subset of the managed profile the updater reads.+type managedConfig struct {+ AutoUpdate *struct {+ Mode string `json:"mode"`+ } `json:"auto_update"`+ ManifestURL string `json:"manifest_url"`+}++func loadManagedConfig() (managedConfig, bool) {+ data, err := os.ReadFile(ManagedConfigPath)+ if err != nil {+ return managedConfig{}, false+ }+ var mc managedConfig+ if err := json.Unmarshal(data, &mc); err != nil {+ return managedConfig{}, false+ }+ return mc, true+}++// ResolveMode determines the effective mode using the precedence:+// 1. BEACON_AUTO_UPDATE env+// 2. managed config dropped by MDM/enterprise+// 3. the local config value (localMode)+// 4. DefaultMode+//+// A managed layer can therefore always override the local default without a+// code change, which keeps the door open for an enterprise update path.+func ResolveMode(localMode string) Mode {+ if env := os.Getenv(AutoUpdateEnv); strings.TrimSpace(env) != "" {+ if m, ok := ParseMode(env); ok {+ return m+ }+ }+ if mc, ok := loadManagedConfig(); ok && mc.AutoUpdate != nil {+ if m, ok := ParseMode(mc.AutoUpdate.Mode); ok {+ return m+ }+ }+ if m, ok := ParseMode(localMode); ok {+ return m+ }+ return DefaultMode+}++// ManagedManifestURL returns a manifest URL forced by the managed profile, if+// any. Empty means "use the built-in/env default".+func ManagedManifestURL() string {+ if mc, ok := loadManagedConfig(); ok {+ return strings.TrimSpace(mc.ManifestURL)+ }+ return ""+}diff --git a/cli/beacon/internal/endpoint/selfupdate/selfupdate.go b/cli/beacon/internal/endpoint/selfupdate/selfupdate.gonew file mode 100644index 00000000..42cf6e35--- /dev/null+++ b/cli/beacon/internal/endpoint/selfupdate/selfupdate.go@@ -0,0 +1,96 @@+// Package selfupdate implements Beacon's endpoint update checks. Phase 1 is+// check-only: it discovers newer signed/notarized/stapled .pkg artifacts from a+// release manifest and records local system telemetry without downloading or+// applying package updates.+package selfupdate++import (+ "os"+ "path/filepath"+ "strings"+)++// SystemInstallDir is where the signed macOS .pkg installs Beacon.+const (+ SystemInstallDir = "/opt/beacon"+ SystemBinDir = "/opt/beacon/bin"+ // SystemSupportDir holds endpoint config and self-update state for the+ // system install.+ SystemSupportDir = "/Library/Application Support/Beacon/Endpoint"+)++// InstallKind classifies how the running beacon binary was installed, which+// determines whether seamless self-update is possible.+type InstallKind string++const (+ // InstallSystemPkg is the MDM/.pkg install under /opt/beacon. This is the+ // only kind the seamless updater applies to.+ InstallSystemPkg InstallKind = "system_pkg"+ // InstallHomebrew is a `brew install beacon` binary; updates go through brew.+ InstallHomebrew InstallKind = "homebrew"+ // InstallOther is any other location (manual download, user dir, go run).+ InstallOther InstallKind = "other"+)++// Install describes the running beacon binary's provenance.+type Install struct {+ Kind InstallKind+ BinaryPath string+}++// SupportsSeamlessUpdate reports whether the .pkg-based updater applies here.+func (i Install) SupportsSeamlessUpdate() bool {+ return i.Kind == InstallSystemPkg+}++// DetectInstall classifies the currently running beacon binary.+func DetectInstall() Install {+ exe, err := os.Executable()+ if err != nil {+ return Install{Kind: InstallOther}+ }+ if resolved, err := filepath.EvalSymlinks(exe); err == nil {+ exe = resolved+ }+ return classifyInstall(exe)+}++// classifyInstall is the testable core of DetectInstall.+func classifyInstall(exe string) Install {+ clean := filepath.Clean(exe)+ switch {+ case clean == filepath.Join(SystemBinDir, "beacon") || strings.HasPrefix(clean, SystemInstallDir+string(filepath.Separator)):+ return Install{Kind: InstallSystemPkg, BinaryPath: clean}+ case isHomebrewPath(clean):+ return Install{Kind: InstallHomebrew, BinaryPath: clean}+ default:+ return Install{Kind: InstallOther, BinaryPath: clean}+ }+}++func isHomebrewPath(path string) bool {+ // Homebrew installs land under the Cellar (then symlinked into bin). We+ // resolve symlinks in DetectInstall, so the real path is in the Cellar, but+ // also match common prefixes defensively.+ if strings.Contains(path, string(filepath.Separator)+"Cellar"+string(filepath.Separator)) {+ return true+ }+ for _, prefix := range []string{"/opt/homebrew/", "/usr/local/Homebrew/", "/home/linuxbrew/.linuxbrew/"} {+ if strings.HasPrefix(path, prefix) {+ return true+ }+ }+ return false+}++// StateDir is where the updater stores its lock, staged packages, and state+// for the system install.+func StateDir() string {+ return filepath.Join(SystemSupportDir, "updates")+}++// SystemBeaconPath is the installed beacon binary the launchd updater invokes.+func SystemBeaconPath() string {+ return filepath.Join(SystemBinDir, "beacon")+}diff --git a/cli/beacon/internal/endpoint/selfupdate/selfupdate_test.go b/cli/beacon/internal/endpoint/selfupdate/selfupdate_test.gonew file mode 100644index 00000000..e0403ee9--- /dev/null+++ b/cli/beacon/internal/endpoint/selfupdate/selfupdate_test.go@@ -0,0 +1,222 @@+package selfupdate++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/updatecheck"+)++func TestClassifyInstall(t *testing.T) {+ cases := []struct {+ path string+ want InstallKind+ }{+ {"/opt/beacon/bin/beacon", InstallSystemPkg},+ {"/opt/beacon/bin/nested/beacon", InstallSystemPkg},+ {"/opt/homebrew/Cellar/beacon/0.0.1/bin/beacon", InstallHomebrew},+ {"/usr/local/Homebrew/x/beacon", InstallHomebrew},+ {"/home/linuxbrew/.linuxbrew/bin/beacon", InstallHomebrew},+ {"/Users/x/go/bin/beacon", InstallOther},+ {"/tmp/beacon", InstallOther},+ }+ for _, c := range cases {+ got := classifyInstall(c.path)+ if got.Kind != c.want {+ t.Errorf("classifyInstall(%q) = %q, want %q", c.path, got.Kind, c.want)+ }+ if got.BinaryPath != filepath.Clean(c.path) {+ t.Errorf("classifyInstall(%q) path = %q", c.path, got.BinaryPath)+ }+ }+}++func TestSupportsSeamlessUpdate(t *testing.T) {+ if !(Install{Kind: InstallSystemPkg}).SupportsSeamlessUpdate() {+ t.Error("system pkg should support seamless update")+ }+ if (Install{Kind: InstallHomebrew}).SupportsSeamlessUpdate() {+ t.Error("homebrew should not support seamless update")+ }+}++func TestParseMode(t *testing.T) {+ cases := map[string]Mode{+ "auto": ModeAuto, "AUTO": ModeAuto, "1": ModeAuto, "true": ModeAuto, "on": ModeAuto,+ "check-only": ModeCheckOnly, "check": ModeCheckOnly,+ "off": ModeOff, "0": ModeOff, "false": ModeOff, "disable": ModeOff,+ }+ for in, want := range cases {+ got, ok := ParseMode(in)+ if !ok || got != want {+ t.Errorf("ParseMode(%q) = %q,%v want %q", in, got, ok, want)+ }+ }+ if _, ok := ParseMode("bogus"); ok {+ t.Error("bogus mode should not parse")+ }+}++func TestResolveModePrecedence(t *testing.T) {+ // Point the managed config at a temp dir so the test is hermetic.+ dir := t.TempDir()+ origManaged := ManagedConfigPath+ ManagedConfigPath = filepath.Join(dir, "managed.json")+ t.Cleanup(func() { ManagedConfigPath = origManaged })++ // No env, no managed, no local => default off (auto-update is opt-in).+ if got := ResolveMode(""); got != ModeOff {+ t.Fatalf("default = %q", got)+ }++ // Local config wins over default.+ if got := ResolveMode("auto"); got != ModeAuto {+ t.Fatalf("local auto = %q", got)+ }++ // Managed overrides local.+ if err := writeFile(ManagedConfigPath, `{"auto_update":{"mode":"check-only"}}`); err != nil {+ t.Fatal(err)+ }+ if got := ResolveMode("off"); got != ModeCheckOnly {+ t.Fatalf("managed override = %q", got)+ }++ // Env overrides everything.+ t.Setenv(AutoUpdateEnv, "off")+ if got := ResolveMode("auto"); got != ModeOff {+ t.Fatalf("env override = %q", got)+ }+}++func TestResolveManifestURLPrecedence(t *testing.T) {+ dir := t.TempDir()+ origManaged := ManagedConfigPath+ ManagedConfigPath = filepath.Join(dir, "managed.json")+ t.Cleanup(func() { ManagedConfigPath = origManaged })++ if got := resolveManifestURL(); got != updatecheck.DefaultManifestURL {+ t.Fatalf("default = %q", got)+ }++ if err := writeFile(ManagedConfigPath, `{"manifest_url":"https://managed.example/m.json"}`); err != nil {+ t.Fatal(err)+ }+ if got := resolveManifestURL(); got != "https://managed.example/m.json" {+ t.Fatalf("managed = %q", got)+ }++ t.Setenv(updatecheck.ManifestURLEnv, "https://env.example/m.json")+ if got := resolveManifestURL(); got != "https://env.example/m.json" {+ t.Fatalf("env = %q", got)+ }+}++func TestCheck(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ _, _ = w.Write([]byte(`{"schema":1,"version":"9.9.9","artifacts":{` ++ `"` + updatecheck.RuntimeArchKey() + `":{"url":"https://x/p.pkg","sha256":"deadbeef"}}}`))+ }))+ defer srv.Close()+ t.Setenv(updatecheck.ManifestURLEnv, srv.URL)++ res, err := Check(context.Background(), "0.0.1")+ if err != nil {+ t.Fatalf("Check: %v", err)+ }+ if !res.UpdateAvailable {+ t.Fatalf("expected update available: %+v", res)+ }+ if !res.HasArtifact || res.Artifact.URL != "https://x/p.pkg" {+ t.Fatalf("artifact not resolved for running arch: %+v", res)+ }+}++func TestCheckMissingArtifactIsNotError(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ _, _ = w.Write([]byte(`{"schema":1,"version":"9.9.9","artifacts":{"darwin_arm64":{"url":"https://x/p.pkg","sha256":"deadbeef"}}}`))+ }))+ defer srv.Close()+ t.Setenv(updatecheck.ManifestURLEnv, srv.URL)++ res, err := Check(context.Background(), "0.0.1")+ if err != nil {+ t.Fatalf("Check: %v", err)+ }+ if !res.UpdateAvailable {+ t.Fatalf("expected update available: %+v", res)+ }+ if res.ArchKey != "darwin_arm64" && res.HasArtifact {+ t.Fatalf("non-arm64 platforms should not resolve an artifact from arm64-only manifest: %+v", res)+ }+}++func TestSystemLogPathFollowsRuntimeLog(t *testing.T) {+ runtimeLog := filepath.Join(t.TempDir(), "runtime.jsonl")+ if got, want := SystemLogPath(runtimeLog, false), filepath.Join(filepath.Dir(runtimeLog), SystemLogFileName); got != want {+ t.Fatalf("SystemLogPath = %q, want %q", got, want)+ }+}++func TestCheckOutcome(t *testing.T) {+ res := CheckResult{+ ManifestResult: updatecheck.ManifestResult{UpdateAvailable: true},+ Install: Install{Kind: InstallSystemPkg},+ ArchKey: "darwin_arm64",+ HasArtifact: true,+ }+ if action, reason := CheckOutcome(res); action != EventAvailable || reason != "update_available" {+ t.Fatalf("available outcome = %s/%s", action, reason)+ }+ res.HasArtifact = false+ if action, reason := CheckOutcome(res); action != EventUnsupported || reason != "no_artifact_for_arch" {+ t.Fatalf("missing artifact outcome = %s/%s", action, reason)+ }+ res.UpdateAvailable = false+ if action, reason := CheckOutcome(res); action != EventCurrent || reason != "already_current" {+ t.Fatalf("current outcome = %s/%s", action, reason)+ }+}++func TestEmitCheckEventWritesSystemLog(t *testing.T) {+ path := filepath.Join(t.TempDir(), "system.jsonl")+ res := CheckResult{+ ManifestResult: updatecheck.ManifestResult{+ CurrentVersion: "v0.0.76",+ LatestVersion: "v0.0.77",+ UpdateAvailable: true,+ },+ Install: Install{Kind: InstallSystemPkg},+ Mode: ModeCheckOnly,+ ArchKey: "darwin_arm64",+ Artifact: updatecheck.Artifact{URL: "https://example.test/p.pkg", SHA256: "abc"},+ HasArtifact: true,+ }+ if err := EmitCheckEvent(CheckEventOptions{Result: res, LogPath: path, AgentVersion: "0.0.76"}); err != nil {+ t.Fatalf("EmitCheckEvent: %v", err)+ }+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ var event map[string]interface{}+ if err := json.Unmarshal(data, &event); err != nil {+ t.Fatalf("decode event: %v", err)+ }+ if got := event["event"].(map[string]interface{})["action"]; got != EventAvailable {+ t.Fatalf("event.action = %q, want %s", got, EventAvailable)+ }+ raw := event["raw"].(map[string]interface{})+ if raw["component"] != "selfupdate" || raw["artifact_arch"] != "darwin_arm64" {+ t.Fatalf("raw = %#v", raw)+ }+}++func writeFile(path, content string) error {+ return os.WriteFile(path, []byte(content), 0o644)+}diff --git a/cli/beacon/internal/endpoint/selfupdate/systemlog.go b/cli/beacon/internal/endpoint/selfupdate/systemlog.gonew file mode 100644index 00000000..e0ab0ac5--- /dev/null+++ b/cli/beacon/internal/endpoint/selfupdate/systemlog.go@@ -0,0 +1,87 @@+package selfupdate++import (+ "path/filepath"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"+)++const SystemLogFileName = "system.jsonl"++const (+ EventAvailable = "update.available"+ EventCurrent = "update.current"+ EventUnsupported = "update.unsupported"+ EventCheckFailed = "update.check_failed"+)++// SystemLogPath returns the local-only Beacon system/debug log that sits beside+// runtime.jsonl and inventory_state.jsonl. It is not a forwarding source.+func SystemLogPath(runtimeLogPath string, userMode bool) string {+ if runtimeLogPath != "" {+ return filepath.Join(filepath.Dir(runtimeLogPath), SystemLogFileName)+ }+ if userMode {+ return filepath.Join(filepath.Dir(writer.DefaultPath(true)), SystemLogFileName)+ }+ return filepath.Join("/var/log", "beacon-agent", SystemLogFileName)+}++type CheckEventOptions struct {+ Result CheckResult+ Action string+ Reason string+ LogPath string+ AgentVersion string+}++func CheckOutcome(res CheckResult) (string, string) {+ switch {+ case res.CurrentIsDev:+ return EventUnsupported, "dev_build"+ case res.UnsupportedCurrentVersion:+ return EventUnsupported, "unsupported_current_version"+ case res.Install.Kind == InstallHomebrew:+ return EventUnsupported, "homebrew_install"+ case res.Install.Kind != "" && res.Install.Kind != InstallSystemPkg:+ return EventUnsupported, "not_system_package"+ case res.UpdateAvailable && !res.HasArtifact:+ return EventUnsupported, "no_artifact_for_arch"+ case res.UpdateAvailable:+ return EventAvailable, "update_available"+ default:+ return EventCurrent, "already_current"+ }+}++func EmitCheckEvent(opts CheckEventOptions) error {+ action := opts.Action+ if action == "" {+ action, opts.Reason = CheckOutcome(opts.Result)+ }+ event := schema.NewEvent(schema.NewEventOptions{+ Action: action,+ Category: "system",+ Severity: schema.SeverityInfo,+ Harness: schema.HarnessInfo{Name: "beacon"},+ AgentVersion: opts.AgentVersion,+ Message: opts.Reason,+ })+ event.Event.Kind = "beacon_system"+ event.Raw = map[string]interface{}{+ "component": "selfupdate",+ "current_version": opts.Result.CurrentVersion,+ "latest_version": opts.Result.LatestVersion,+ "artifact_arch": opts.Result.ArchKey,+ "manifest_url": resolveManifestURL(),+ "install_kind": string(opts.Result.Install.Kind),+ "mode": string(opts.Result.Mode),+ "reason": opts.Reason,+ }+ if opts.Result.HasArtifact {+ event.Raw["artifact_url"] = opts.Result.Artifact.URL+ }+ _, err := writer.AppendEvent(event, writer.Options{Path: opts.LogPath})+ return err+}diff --git a/cli/beacon/internal/endpoint/service/updater.go b/cli/beacon/internal/endpoint/service/updater.gonew file mode 100644index 00000000..e8815e19--- /dev/null+++ b/cli/beacon/internal/endpoint/service/updater.go@@ -0,0 +1,110 @@+package service++import (+ "fmt"+ "os"+ "path/filepath"+ "runtime"+ "strings"+)++// UpdaterLabel is the launchd label for the periodic update-check job. Phase 1+// is check-only and does not apply package updates.+const UpdaterLabel = "com.beacon.endpoint.updater"++// UpdaterManager manages the update-check launchd job. Unlike the collector+// service it is system-only and runs on a schedule rather than KeepAlive.+type UpdaterManager struct{}++// PlistPath returns the LaunchDaemon plist path for the updater job.+func (UpdaterManager) PlistPath() string {+ return filepath.Join("/Library/LaunchDaemons", UpdaterLabel+".plist")+}++// WritePlist writes the updater LaunchDaemon plist invoking the given program.+func (m UpdaterManager) WritePlist(program string) (string, error) {+ if runtime.GOOS != "darwin" {+ return "", fmt.Errorf("launchd service management is supported only on macOS")+ }+ path := m.PlistPath()+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {+ return "", err+ }+ return path, os.WriteFile(path, []byte(updaterPlist(UpdaterLabel, program)), 0644)+}++// Load bootstraps the updater job into the system domain.+func (m UpdaterManager) Load() error {+ if runtime.GOOS != "darwin" {+ return nil+ }+ path := m.PlistPath()+ out, err := runLaunchctlCommand("bootstrap", "system", path)+ if err == nil {+ return nil+ }+ if strings.Contains(strings.TrimSpace(out), "already bootstrapped") {+ target := "system/" + UpdaterLabel+ if err := runLaunchctlWithContext("system", UpdaterLabel, "", "bootout", target); err != nil {+ return err+ }+ return runLaunchctlWithContext("system", UpdaterLabel, path, "bootstrap", "system", path)+ }+ return launchctlError(strings.TrimSpace(out), err, "system", UpdaterLabel, path, "bootstrap", "system", path)+}++// Unload boots the updater job out of the system domain.+func (m UpdaterManager) Unload() error {+ if runtime.GOOS != "darwin" {+ return nil+ }+ return runLaunchctlWithContext("system", UpdaterLabel, "", "bootout", "system/"+UpdaterLabel)+}++// Status reports whether the updater job is loaded.+func (m UpdaterManager) Status() Status {+ status := Status{Label: UpdaterLabel}+ if runtime.GOOS != "darwin" {+ status.Message = "service status is available only on macOS"+ return status+ }+ out, err := runLaunchctlCommand("print", "system/"+UpdaterLabel)+ if err != nil {+ status.Message = strings.TrimSpace(out)+ return status+ }+ status.Loaded = true+ status.Running = strings.Contains(out, "state = running") || strings.Contains(out, "pid =")+ return status+}++// updaterPlist renders the check-only LaunchDaemon. Phase 1 runs every ten+// minutes so update detection can be dogfooded quickly without install risk.+// It does not RunAtLoad and is not KeepAlive (one-shot scheduled job).+func updaterPlist(label, program string) string {+ return fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key>+ <string>%s</string>+ <key>ProgramArguments</key>+ <array>+ <string>%s</string>+ <string>endpoint</string>+ <string>update</string>+ <string>--check</string>+ <string>--scheduled</string>+ </array>+ <key>StartInterval</key>+ <integer>600</integer>+ <key>RunAtLoad</key>+ <false/>+ <key>StandardOutPath</key>+ <string>/tmp/%s.out</string>+ <key>StandardErrorPath</key>+ <string>/tmp/%s.err</string>+</dict>+</plist>+`, label, program, label, label)+}diff --git a/cli/beacon/internal/endpoint/service/updater_test.go b/cli/beacon/internal/endpoint/service/updater_test.gonew file mode 100644index 00000000..f3da00b2--- /dev/null+++ b/cli/beacon/internal/endpoint/service/updater_test.go@@ -0,0 +1,45 @@+package service++import (+ "runtime"+ "strings"+ "testing"+)++func TestUpdaterPlistContent(t *testing.T) {+ out := updaterPlist(UpdaterLabel, "/opt/beacon/bin/beacon")+ for _, want := range []string{+ "<string>com.beacon.endpoint.updater</string>",+ "<string>/opt/beacon/bin/beacon</string>",+ "<string>--check</string>",+ "<string>--scheduled</string>",+ "<key>StartInterval</key>",+ "<integer>600</integer>",+ } {+ if !strings.Contains(out, want) {+ t.Errorf("plist missing %q", want)+ }+ }+ // One-shot scheduled job: must not RunAtLoad or KeepAlive.+ if strings.Contains(out, "<key>KeepAlive</key>") {+ t.Errorf("updater plist should not set KeepAlive")+ }+ if !strings.Contains(out, "<key>RunAtLoad</key>\n <false/>") {+ t.Errorf("updater plist should set RunAtLoad false")+ }+}++func TestUpdaterPlistPath(t *testing.T) {+ if got := (UpdaterManager{}).PlistPath(); got != "/Library/LaunchDaemons/com.beacon.endpoint.updater.plist" {+ t.Errorf("PlistPath = %q", got)+ }+}++func TestUpdaterWritePlistNonDarwinContract(t *testing.T) {+ if runtime.GOOS == "darwin" {+ t.Skip("darwin writes the plist; this asserts the non-darwin contract")+ }+ if _, err := (UpdaterManager{}).WritePlist("/opt/beacon/bin/beacon"); err == nil {+ t.Error("expected error writing updater plist on non-darwin")+ }+}diff --git a/cli/beacon/internal/updatecheck/manifest.go b/cli/beacon/internal/updatecheck/manifest.gonew file mode 100644index 00000000..8d0e4534--- /dev/null+++ b/cli/beacon/internal/updatecheck/manifest.go@@ -0,0 +1,170 @@+package updatecheck++import (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "os"+ "runtime"+ "strings"+)++// ManifestURLEnv overrides the update manifest location. This is the seam a+// managed/enterprise update path uses to point Beacon at an internal host+// without a code change.+const ManifestURLEnv = "BEACON_UPDATE_MANIFEST_URL"++// DefaultManifestURL resolves to the manifest published with the most recent+// GitHub release. GitHub's `releases/latest/download/<asset>` path redirects to+// the latest release's asset, so the updater does not need the GitHub API here.+const DefaultManifestURL = "https://github.com/asymptote-labs/agent-beacon/releases/latest/download/update-manifest.json"++// CurrentManifestSchema is the manifest schema version this build understands.+const CurrentManifestSchema = 1++// Artifact is a single downloadable update package and its expected digest.+type Artifact struct {+ URL string `json:"url"`+ SHA256 string `json:"sha256"`+}++// UpdateManifest is the small JSON document published as a release asset that+// tells an installed agent what the latest version is and where to fetch it.+type UpdateManifest struct {+ Schema int `json:"schema"`+ Version string `json:"version"`+ MinSupportedVersion string `json:"min_supported_version,omitempty"`+ TeamID string `json:"team_id,omitempty"`+ PkgIdentifier string `json:"pkg_identifier,omitempty"`+ Artifacts map[string]Artifact `json:"artifacts"`+}++// ManifestURL returns the configured manifest URL, honoring the env override.+func ManifestURL() string {+ if v := strings.TrimSpace(os.Getenv(ManifestURLEnv)); v != "" {+ return v+ }+ return DefaultManifestURL+}++// RuntimeArchKey is the artifacts map key for the running platform, e.g.+// "darwin_arm64".+func RuntimeArchKey() string {+ return runtime.GOOS + "_" + runtime.GOARCH+}++// ParseManifest decodes and validates a manifest document.+func ParseManifest(data []byte) (UpdateManifest, error) {+ var m UpdateManifest+ if err := json.Unmarshal(data, &m); err != nil {+ return UpdateManifest{}, fmt.Errorf("decode update manifest: %w", err)+ }+ if m.Schema == 0 {+ return UpdateManifest{}, fmt.Errorf("update manifest missing schema")+ }+ if m.Schema > CurrentManifestSchema {+ return UpdateManifest{}, fmt.Errorf("update manifest schema %d is newer than supported %d", m.Schema, CurrentManifestSchema)+ }+ if strings.TrimSpace(m.Version) == "" {+ return UpdateManifest{}, fmt.Errorf("update manifest missing version")+ }+ if _, ok := parseReleaseVersion(m.Version); !ok {+ return UpdateManifest{}, fmt.Errorf("update manifest version %q is not a release version", m.Version)+ }+ return m, nil+}++// ArtifactFor returns the artifact for the given arch key, if present.+func (m UpdateManifest) ArtifactFor(archKey string) (Artifact, bool) {+ a, ok := m.Artifacts[archKey]+ if !ok || strings.TrimSpace(a.URL) == "" || strings.TrimSpace(a.SHA256) == "" {+ return Artifact{}, false+ }+ return a, true+}++// ManifestSource fetches the update manifest over HTTP.+type ManifestSource struct {+ Client *http.Client+ Endpoint string+}++// Fetch retrieves and parses the manifest.+func (s ManifestSource) Fetch(ctx context.Context) (UpdateManifest, error) {+ endpoint := s.Endpoint+ if endpoint == "" {+ endpoint = ManifestURL()+ }+ client := s.Client+ if client == nil {+ client = http.DefaultClient+ }++ req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)+ if err != nil {+ return UpdateManifest{}, err+ }+ req.Header.Set("Accept", "application/json")+ req.Header.Set("User-Agent", "beacon-self-update")++ resp, err := client.Do(req)+ if err != nil {+ return UpdateManifest{}, err+ }+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ return UpdateManifest{}, fmt.Errorf("update manifest lookup returned HTTP %d", resp.StatusCode)+ }++ // Cap the body; the manifest is tiny.+ data, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))+ if err != nil {+ return UpdateManifest{}, err+ }+ return ParseManifest(data)+}++// ManifestResult describes the outcome of comparing the running build against a+// fetched manifest.+type ManifestResult struct {+ CurrentVersion string+ LatestVersion string+ UpdateAvailable bool+ CurrentIsDev bool+ UnsupportedCurrentVersion bool+ BelowMinSupported bool+ Manifest UpdateManifest+}++// EvaluateManifest compares the current build version to a manifest. It mirrors+// Checker.Check's dev/unsupported handling so callers behave consistently.+func EvaluateManifest(current string, m UpdateManifest) (ManifestResult, error) {+ result := ManifestResult{+ CurrentVersion: displayVersion(current),+ LatestVersion: displayVersion(m.Version),+ Manifest: m,+ }+ if strings.TrimSpace(current) == "dev" {+ result.CurrentIsDev = true+ return result, nil+ }+ if !CanCheckVersion(current) {+ result.UnsupportedCurrentVersion = true+ return result, nil+ }++ cmp, ok := compareVersions(current, m.Version)+ if !ok {+ return result, fmt.Errorf("%w: %q", ErrUncomparableVersion, m.Version)+ }+ result.UpdateAvailable = cmp < 0++ if m.MinSupportedVersion != "" {+ if minCmp, ok := compareVersions(current, m.MinSupportedVersion); ok && minCmp < 0 {+ result.BelowMinSupported = true+ }+ }+ return result, nil+}diff --git a/cli/beacon/internal/updatecheck/manifest_test.go b/cli/beacon/internal/updatecheck/manifest_test.gonew file mode 100644index 00000000..937e6822--- /dev/null+++ b/cli/beacon/internal/updatecheck/manifest_test.go@@ -0,0 +1,162 @@+package updatecheck++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"+)++const sampleManifest = `{+ "schema": 1,+ "version": "0.0.69",+ "min_supported_version": "0.0.40",+ "team_id": "TEAMID",+ "pkg_identifier": "ai.asymptote.beacon.endpoint",+ "artifacts": {+ "darwin_arm64": {"url": "https://example.test/Beacon-0.0.69-arm64.pkg", "sha256": "aaa"}+ }+}`++func TestParseManifest(t *testing.T) {+ m, err := ParseManifest([]byte(sampleManifest))+ if err != nil {+ t.Fatalf("ParseManifest: %v", err)+ }+ if m.Version != "0.0.69" {+ t.Fatalf("version = %q", m.Version)+ }+ if m.TeamID != "TEAMID" || m.PkgIdentifier != "ai.asymptote.beacon.endpoint" {+ t.Fatalf("metadata not parsed: %+v", m)+ }+ a, ok := m.ArtifactFor("darwin_arm64")+ if !ok || a.URL == "" || a.SHA256 != "aaa" {+ t.Fatalf("arm64 artifact = %+v ok=%v", a, ok)+ }+ if _, ok := m.ArtifactFor("linux_arm64"); ok {+ t.Fatalf("unexpected artifact for linux_arm64")+ }+ if _, ok := m.ArtifactFor("darwin_amd64"); ok {+ t.Fatalf("unexpected amd64 artifact in arm64-only manifest")+ }+}++func TestParseManifestRejectsBadInput(t *testing.T) {+ cases := map[string]string{+ "empty version": `{"schema":1,"artifacts":{}}`,+ "missing schema": `{"version":"0.0.1","artifacts":{}}`,+ "future schema": `{"schema":99,"version":"0.0.1","artifacts":{}}`,+ "non-release ver": `{"schema":1,"version":"latest","artifacts":{}}`,+ "malformed json": `{`,+ }+ for name, body := range cases {+ if _, err := ParseManifest([]byte(body)); err == nil {+ t.Errorf("%s: expected error, got nil", name)+ }+ }+}++func TestArtifactForRequiresURLAndSHA(t *testing.T) {+ m := UpdateManifest{Artifacts: map[string]Artifact{+ "darwin_arm64": {URL: "https://x", SHA256: ""},+ "darwin_amd64": {URL: "", SHA256: "abc"},+ }}+ if _, ok := m.ArtifactFor("darwin_arm64"); ok {+ t.Errorf("artifact without sha256 should be rejected")+ }+ if _, ok := m.ArtifactFor("darwin_amd64"); ok {+ t.Errorf("artifact without url should be rejected")+ }+}++func TestEvaluateManifest(t *testing.T) {+ m, err := ParseManifest([]byte(sampleManifest))+ if err != nil {+ t.Fatal(err)+ }++ t.Run("update available", func(t *testing.T) {+ r, err := EvaluateManifest("0.0.67", m)+ if err != nil {+ t.Fatal(err)+ }+ if !r.UpdateAvailable {+ t.Fatalf("expected update available")+ }+ if r.BelowMinSupported {+ t.Fatalf("0.0.67 should be above min supported")+ }+ if r.LatestVersion != "v0.0.69" || r.CurrentVersion != "v0.0.67" {+ t.Fatalf("display versions: %+v", r)+ }+ })++ t.Run("already current", func(t *testing.T) {+ r, _ := EvaluateManifest("0.0.69", m)+ if r.UpdateAvailable {+ t.Fatalf("should not report update when current")+ }+ })++ t.Run("newer than manifest", func(t *testing.T) {+ r, _ := EvaluateManifest("0.0.80", m)+ if r.UpdateAvailable {+ t.Fatalf("should not downgrade")+ }+ })++ t.Run("below min supported", func(t *testing.T) {+ r, _ := EvaluateManifest("0.0.30", m)+ if !r.UpdateAvailable || !r.BelowMinSupported {+ t.Fatalf("expected update + below-min: %+v", r)+ }+ })++ t.Run("dev build", func(t *testing.T) {+ r, _ := EvaluateManifest("dev", m)+ if !r.CurrentIsDev || r.UpdateAvailable {+ t.Fatalf("dev build should be skipped: %+v", r)+ }+ })+}++func TestManifestSourceFetch(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(sampleManifest))+ }))+ defer srv.Close()++ src := ManifestSource{Client: &http.Client{Timeout: 2 * time.Second}, Endpoint: srv.URL}+ m, err := src.Fetch(context.Background())+ if err != nil {+ t.Fatalf("Fetch: %v", err)+ }+ if m.Version != "0.0.69" {+ t.Fatalf("version = %q", m.Version)+ }+}++func TestManifestSourceFetchHTTPError(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusNotFound)+ }))+ defer srv.Close()++ src := ManifestSource{Endpoint: srv.URL}+ if _, err := src.Fetch(context.Background()); err == nil {+ t.Fatalf("expected error on HTTP 404")+ }+}++func TestManifestURLEnvOverride(t *testing.T) {+ t.Setenv(ManifestURLEnv, "https://internal.example/manifest.json")+ if got := ManifestURL(); got != "https://internal.example/manifest.json" {+ t.Fatalf("ManifestURL = %q", got)+ }+ t.Setenv(ManifestURLEnv, "")+ if got := ManifestURL(); got != DefaultManifestURL {+ t.Fatalf("ManifestURL fallback = %q", got)+ }+}diff --git a/docs/changelog/cli.mdx b/docs/changelog/cli.mdxindex 0afd84f6..dda418e1 100644--- a/docs/changelog/cli.mdx+++ b/docs/changelog/cli.mdx@@ -11,6 +11,10 @@ Stay up to date with the latest changes to the Agent Beacon CLI.## June 2026+### Unreleased++- **Check-only endpoint update monitoring** · Apple Silicon package installs can opt into a local `launchd` job that checks the release manifest every 10 minutes and writes local-only update status events to `system.jsonl`. This phase does not download or apply packages.+### v0.0.76 · June 24, 2026- **Signed Apple Silicon endpoint package releases** · A pushed version tag now runs the release pipeline end-to-end: GoReleaser publishes CLI archives and updates Homebrew, then CI builds, signs, notarizes, staples, and uploads the Apple Silicon endpoint `.pkg`, `.sha256`, and `update-manifest.json` assets to GitHub Releases for direct MDM/manual download.diff --git a/docs/cli/upgrade.mdx b/docs/cli/upgrade.mdxindex 40c2280b..47a0f773 100644--- a/docs/cli/upgrade.mdx+++ b/docs/cli/upgrade.mdx@@ -23,6 +23,24 @@ brew upgrade beaconbeacon version```+## Check-only endpoint update monitoring++For Apple Silicon systems installed from the signed endpoint package, Beacon can+periodically check the GitHub Release manifest without downloading or applying+updates. This writes local-only update status events to `system.jsonl` beside the+runtime log.++```bash title="Enable check-only endpoint update monitoring"+sudo /opt/beacon/bin/beacon endpoint update enable --check-only+sudo /opt/beacon/bin/beacon endpoint update status+```++Disable the background check job with:++```bash title="Disable endpoint update monitoring"+sudo /opt/beacon/bin/beacon endpoint update disable+```+## Repair endpoint configurationIf you run Beacon as a local endpoint service, reapply managed service files and telemetry configuration after upgrading: