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
Make the inventory heartbeat a scheduled write with no TTL
shukieshah7714a36560dd
diff --git a/cli/beacon/cmd/endpoint.go b/cli/beacon/cmd/endpoint.goindex 9ad0413f..65c78fc9 100644--- a/cli/beacon/cmd/endpoint.go+++ b/cli/beacon/cmd/endpoint.go@@ -79,6 +79,7 @@ var endpointOpts struct {inventoryHooks boolinventoryContents boolinventoryHeartbeatForce bool+ inventoryScheduled boolinventoryHeartbeatConfig stringinventoryWorkingDir stringinventoryTrigger string@@ -454,11 +455,19 @@ func init() {endpointInventoryCmd.Flags().BoolVar(&endpointOpts.inventoryHooks, "hooks", false, "Show only hook integration and hook config inventory")endpointInventoryCmd.Flags().BoolVar(&endpointOpts.inventoryContents, "contents", false, "Include redacted, size-limited config/hook/skill file contents and full MCP server definitions")endpointInventoryCmd.Flags().BoolVar(&endpointOpts.writeInventoryEvent, "write-event", false, "Append inventory events to the endpoint runtime log")- endpointInventoryHeartbeatCmd.Flags().BoolVar(&endpointOpts.inventoryHeartbeatForce, "force", false, "Write inventory heartbeat even when TTL has not expired")+ endpointInventoryHeartbeatCmd.Flags().BoolVar(&endpointOpts.inventoryHeartbeatForce, "force", false, "Write the heartbeat even when inventory_heartbeat.enabled is false")+ endpointInventoryHeartbeatCmd.Flags().BoolVar(&endpointOpts.inventoryScheduled, "scheduled", false, "Internal: run as the scheduled inventory job")endpointInventoryHeartbeatCmd.Flags().StringVar(&endpointOpts.inventoryHeartbeatConfig, "config", "", "Endpoint config path")- endpointInventoryHeartbeatCmd.Flags().StringVar(&endpointOpts.inventoryWorkingDir, "working-dir", "", "Working directory for project inventory")- endpointInventoryHeartbeatCmd.Flags().StringVar(&endpointOpts.inventoryTrigger, "trigger", "manual", "Inventory trigger source")- endpointInventoryHeartbeatCmd.Flags().StringVar(&endpointOpts.inventoryTriggerHarness, "trigger-harness", "", "Harness that triggered inventory")+ // Hooks installed by older Beacon versions still invoke this command with these three flags on+ // every session start and prompt. They must keep parsing, and --trigger hook must stay a no-op,+ // or every prompt on an un-repaired machine would error or write a heartbeat.+ endpointInventoryHeartbeatCmd.Flags().StringVar(&endpointOpts.inventoryWorkingDir, "working-dir", "", "Ignored; kept for hook commands written by older versions")+ endpointInventoryHeartbeatCmd.Flags().StringVar(&endpointOpts.inventoryTrigger, "trigger", "", "Ignored; kept for hook commands written by older versions")+ endpointInventoryHeartbeatCmd.Flags().StringVar(&endpointOpts.inventoryTriggerHarness, "trigger-harness", "", "Ignored; kept for hook commands written by older versions")+ _ = endpointInventoryHeartbeatCmd.Flags().MarkHidden("scheduled")+ _ = endpointInventoryHeartbeatCmd.Flags().MarkHidden("working-dir")+ _ = endpointInventoryHeartbeatCmd.Flags().MarkHidden("trigger")+ _ = endpointInventoryHeartbeatCmd.Flags().MarkHidden("trigger-harness")endpointInventoryHeartbeatCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print heartbeat result as JSON")topLevelDoctorCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print doctor results as JSON")topLevelDoctorCmd.Flags().BoolVar(&endpointOpts.fix, "fix", false, "Apply safe endpoint doctor remediations")diff --git a/cli/beacon/cmd/endpoint_diagnostics.go b/cli/beacon/cmd/endpoint_diagnostics.goindex b5683ae3..8bc931da 100644--- a/cli/beacon/cmd/endpoint_diagnostics.go+++ b/cli/beacon/cmd/endpoint_diagnostics.go@@ -423,7 +423,7 @@ func inventoryConfigIncluded(config endpointinventory.Config) bool {func writeInventoryEvents(cfg endpointconfig.Config, result endpointinventory.Result) error {settings := endpointconfig.InventoryConfig(cfg)result = filterInventoryResult(result, settings.Runtimes)- _, err := writeInventorySnapshotEvents(cfg, settings, result, "manual", "", true, endpointinventory.State{})+ _, err := writeInventorySnapshotEvents(cfg, settings, result, "manual", endpointinventory.SnapshotDigest(result), true, endpointinventory.State{})return err}@@ -435,21 +435,60 @@ type inventoryHeartbeatWriteResult struct {PreviousDigest string `json:"previous_snapshot_digest,omitempty"`}-const inventoryAttemptBackoff = 5 * time.Minute+// heartbeatScope says whose runtimes the heartbeat inventories. In user mode the zero value+// means the current user. In system mode the job runs as root, whose home holds nothing, so+// the scan targets the active console user; when nobody is logged in the heartbeat is still+// written (it is the endpoint's liveness signal) but carries no snapshot.+type heartbeatScope struct {+ HomeDir string+ NoConsoleUser bool+}++const inventoryTriggerScheduled = "scheduled"func runEndpointInventoryHeartbeat(cmd *cobra.Command, args []string) error {+ if endpointOpts.inventoryTrigger == "hook" {+ // Hooks installed by older Beacon versions call this on every session start and prompt.+ // Inventory comes from the scheduled job now; honouring the old trigger would turn every+ // prompt into a heartbeat.+ if endpointOpts.jsonOutput {+ _ = json.NewEncoder(os.Stdout).Encode(inventoryHeartbeatWriteResult{SkippedReason: "hook_trigger_retired"})+ }+ return nil+ }cfg, err := loadInventoryHeartbeatConfig(endpointUserMode(), endpointOpts.logPath, endpointOpts.inventoryHeartbeatConfig)if err != nil {return err}settings := endpointconfig.InventoryConfig(cfg)- result, err := writeInventoryHeartbeat(cfg, settings, endpointOpts.inventoryHeartbeatForce, endpointOpts.inventoryWorkingDir, endpointOpts.inventoryTrigger, endpointOpts.inventoryTriggerHarness)+ trigger := "manual"+ if endpointOpts.inventoryScheduled {+ trigger = inventoryTriggerScheduled+ }+ scope := heartbeatScope{}+ if !cfg.UserMode {+ scope = systemHeartbeatScope()+ }+ result, err := writeInventoryHeartbeat(cfg, settings, endpointOpts.inventoryHeartbeatForce, trigger, scope)if endpointOpts.jsonOutput {_ = json.NewEncoder(os.Stdout).Encode(result)}return err}+// systemHeartbeatScope resolves the console user a system-mode heartbeat should inventory. A+// resolution failure is reported but never fatal: the liveness heartbeat still goes out.+func systemHeartbeatScope() heartbeatScope {+ info, ok, err := activeConsoleUser()+ if err != nil {+ fmt.Fprintf(os.Stderr, "warning: could not resolve the console user for inventory: %v\n", err)+ }+ if !ok || strings.TrimSpace(info.HomeDir) == "" {+ return heartbeatScope{NoConsoleUser: true}+ }+ return heartbeatScope{HomeDir: info.HomeDir}+}+func loadInventoryHeartbeatConfig(userMode bool, logPath, configPath string) (endpointconfig.Config, error) {if configPath == "" {return loadConfigForMode(userMode, logPath), nil@@ -475,7 +514,10 @@ func loadInventoryHeartbeatConfig(userMode bool, logPath, configPath string) (enreturn cfg, nil}-func writeInventoryHeartbeat(cfg endpointconfig.Config, settings endpointconfig.InventorySettings, force bool, workingDir, trigger, triggerHarness string) (inventoryHeartbeatWriteResult, error) {+// writeInventoryHeartbeat always appends an inventory.heartbeat and appends an inventory.snapshot+// only when the scan's digest differs from the last one written. There is no TTL: the caller+// (the scheduled job, or an operator running the command) decides when to run.+func writeInventoryHeartbeat(cfg endpointconfig.Config, settings endpointconfig.InventorySettings, force bool, trigger string, scope heartbeatScope) (inventoryHeartbeatWriteResult, error) {if !settings.Enabled && !force {return inventoryHeartbeatWriteResult{SkippedReason: "disabled"}, nil}@@ -486,30 +528,28 @@ func writeInventoryHeartbeat(cfg endpointconfig.Config, settings endpointconfig.return inventoryHeartbeatWriteResult{}, err}defer locked.Close()- if !force && !endpointinventory.TTLExpired(state, now, settings.TTLSeconds) {- return inventoryHeartbeatWriteResult{SkippedReason: "ttl_active", PreviousDigest: state.LastSnapshotDigest}, nil- }- if !force && endpointinventory.AttemptBackoffActive(state, now, inventoryAttemptBackoff) {- return inventoryHeartbeatWriteResult{SkippedReason: "attempt_backoff", PreviousDigest: state.LastSnapshotDigest}, nil- }- scanOpts := endpointinventory.Options{- WorkingDir: workingDir,- Runtimes: settings.Runtimes,- Now: func() time.Time { return now },- IncludeContents: settings.IncludeContents,- MaxContentBytes: settings.MaxContentBytes,- }- inventoryResult := endpointinventory.Scan(scanOpts)- digest := endpointinventory.SnapshotDigest(inventoryResult)- writeSnapshot := state.LastSnapshotDigest != digest- if err := locked.Save(endpointinventory.State{- LastEmittedAt: state.LastEmittedAt,- LastSnapshotDigest: state.LastSnapshotDigest,- LastAttemptAt: now.Format(time.RFC3339),- }); err != nil {- return inventoryHeartbeatWriteResult{SnapshotDigest: digest, PreviousDigest: state.LastSnapshotDigest}, err++ var inventoryResult endpointinventory.Result+ digest := state.LastSnapshotDigest+ writeSnapshot := false+ if scope.NoConsoleUser {+ inventoryResult = endpointinventory.Result{+ GeneratedAt: now.Format(time.RFC3339),+ UserScope: endpointinventory.UserScope{Mode: "no_console_user"},+ }+ } else {+ inventoryResult = endpointinventory.Scan(endpointinventory.Options{+ HomeDir: scope.HomeDir,+ SkipProjectScope: true,+ Runtimes: settings.Runtimes,+ Now: func() time.Time { return now },+ IncludeContents: settings.IncludeContents,+ MaxContentBytes: settings.MaxContentBytes,+ })+ digest = endpointinventory.SnapshotDigest(inventoryResult)+ writeSnapshot = state.LastSnapshotDigest != digest}- writeResult, err := writeInventorySnapshotEvents(cfg, settings, inventoryResult, trigger, triggerHarness, writeSnapshot, state)+ writeResult, err := writeInventorySnapshotEvents(cfg, settings, inventoryResult, trigger, digest, writeSnapshot, state)if err != nil {return writeResult, err}@@ -522,16 +562,13 @@ func writeInventoryHeartbeat(cfg endpointconfig.Config, settings endpointconfig.return writeResult, nil}-func writeInventorySnapshotEvents(cfg endpointconfig.Config, settings endpointconfig.InventorySettings, result endpointinventory.Result, trigger, triggerHarness string, writeSnapshot bool, state endpointinventory.State) (inventoryHeartbeatWriteResult, error) {- digest := endpointinventory.SnapshotDigest(result)+func writeInventorySnapshotEvents(cfg endpointconfig.Config, settings endpointconfig.InventorySettings, result endpointinventory.Result, trigger, digest string, writeSnapshot bool, state endpointinventory.State) (inventoryHeartbeatWriteResult, error) {previousDigest := state.LastSnapshotDigestcounts := endpointinventory.CountsFor(result)inventoryMeta := map[string]interface{}{"generated_at": result.GeneratedAt,"runtimes": settings.Runtimes,"trigger": trigger,- "trigger_harness": triggerHarness,- "ttl_seconds": settings.TTLSeconds,"snapshot_digest": digest,"previous_snapshot_digest": previousDigest,"counts": counts,@@ -557,7 +594,7 @@ func writeInventorySnapshotEvents(cfg endpointconfig.Config, settings endpointcoreturn inventoryHeartbeatWriteResult{SnapshotDigest: digest, PreviousDigest: previousDigest}, err}out := inventoryHeartbeatWriteResult{Written: true, SnapshotDigest: digest, PreviousDigest: previousDigest}- if !writeSnapshot && previousDigest != "" {+ if !writeSnapshot {return out, nil}snapshot := schema.NewEvent(schema.NewEventOptions{@@ -573,8 +610,6 @@ func writeInventorySnapshotEvents(cfg endpointconfig.Config, settings endpointco"generated_at": result.GeneratedAt,"runtimes": settings.Runtimes,"trigger": trigger,- "trigger_harness": triggerHarness,- "ttl_seconds": settings.TTLSeconds,"snapshot_digest": digest,"previous_snapshot_digest": previousDigest,"counts": counts,diff --git a/cli/beacon/cmd/endpoint_test.go b/cli/beacon/cmd/endpoint_test.goindex d5c9e081..5ba77cb3 100644--- a/cli/beacon/cmd/endpoint_test.go+++ b/cli/beacon/cmd/endpoint_test.go@@ -1062,48 +1062,39 @@ func TestWriteInventoryEventsHonorsConfiguredRuntimes(t *testing.T) {}}-func TestInventoryHeartbeatTTLAndSnapshotDigest(t *testing.T) {+func TestScheduledInventoryHeartbeatAlwaysWritesAndSnapshotsOnChange(t *testing.T) {home := t.TempDir()t.Setenv("HOME", home)- work := t.TempDir()logPath := filepath.Join(t.TempDir(), "runtime.jsonl")writeTestFile(t, filepath.Join(home, ".cursor", "mcp.json"), `{"mcpServers":{"one":{"command":"npx"}}}`)writeTestFile(t, filepath.Join(home, ".codex", "config.toml"), `[mcp_servers.github]command = "gh"`)cfg := endpointconfig.Default(true, logPath)- enabled := true- cfg.Inventory = &endpointconfig.Inventory{Enabled: &enabled, TTLSeconds: 86400}settings := endpointconfig.InventoryConfig(cfg)- first, err := writeInventoryHeartbeat(cfg, settings, false, work, "hook", "cursor")+ first, err := writeInventoryHeartbeat(cfg, settings, false, inventoryTriggerScheduled, heartbeatScope{})if err != nil {t.Fatalf("first heartbeat returned error: %v", err)}if !first.Written || !first.SnapshotWritten || first.SnapshotDigest == "" {t.Fatalf("first heartbeat = %#v, want heartbeat and snapshot", first)}- second, err := writeInventoryHeartbeat(cfg, settings, false, work, "hook", "cursor")+ // Nothing changed: the heartbeat (liveness) is still written, the snapshot is not. No TTL.+ second, err := writeInventoryHeartbeat(cfg, settings, false, inventoryTriggerScheduled, heartbeatScope{})if err != nil {t.Fatalf("second heartbeat returned error: %v", err)}- if second.Written || second.SkippedReason != "ttl_active" {- t.Fatalf("second heartbeat = %#v, want TTL skip", second)- }- forced, err := writeInventoryHeartbeat(cfg, settings, true, work, "hook", "cursor")- if err != nil {- t.Fatalf("forced heartbeat returned error: %v", err)- }- if !forced.Written || forced.SnapshotWritten {- t.Fatalf("forced unchanged heartbeat = %#v, want heartbeat only", forced)+ if !second.Written || second.SnapshotWritten || second.SkippedReason != "" {+ t.Fatalf("unchanged heartbeat = %#v, want heartbeat only", second)}writeTestFile(t, filepath.Join(home, ".cursor", "mcp.json"), `{"mcpServers":{"one":{"command":"npx"},"two":{"command":"uvx"}}}`)- changed, err := writeInventoryHeartbeat(cfg, settings, true, work, "hook", "cursor")+ changed, err := writeInventoryHeartbeat(cfg, settings, false, inventoryTriggerScheduled, heartbeatScope{})if err != nil {t.Fatalf("changed heartbeat returned error: %v", err)}- if !changed.Written || !changed.SnapshotWritten || changed.SnapshotDigest == forced.SnapshotDigest {+ if !changed.Written || !changed.SnapshotWritten || changed.SnapshotDigest == second.SnapshotDigest {t.Fatalf("changed heartbeat = %#v, want new snapshot digest", changed)}@@ -1122,11 +1113,15 @@ command = "gh"if strings.Count(text, "inventory.snapshot") != 2 {t.Fatalf("snapshot count = %d, want 2; log=%s", strings.Count(text, "inventory.snapshot"), text)}- if !strings.Contains(text, `"server_name":"two"`) {- t.Fatalf("changed snapshot missing new MCP server: %s", text)+ for _, want := range []string{`"trigger":"scheduled"`, `"server_name":"two"`, `"server_name":"github"`} {+ if !strings.Contains(text, want) {+ t.Fatalf("inventory log missing %q: %s", want, text)+ }}- if !strings.Contains(text, `"server_name":"github"`) {- t.Fatalf("default heartbeat should include Codex inventory from cursor trigger: %s", text)+ for _, forbidden := range []string{"ttl_seconds", "trigger_harness", `"scope":"project"`} {+ if strings.Contains(text, forbidden) {+ t.Fatalf("inventory log must not contain %q: %s", forbidden, text)+ }}if _, err := os.Stat(filepath.Join(filepath.Dir(logPath), "inventory-state.json")); err != nil {t.Fatalf("inventory state should live beside inventory log: %v", err)@@ -1136,10 +1131,9 @@ command = "gh"}}-func TestInventoryHeartbeatAppendFailureRecordsAttemptOnly(t *testing.T) {+func TestInventoryHeartbeatAppendFailureLeavesStateUntouched(t *testing.T) {home := t.TempDir()t.Setenv("HOME", home)- work := t.TempDir()logDir := t.TempDir()logPath := filepath.Join(logDir, "runtime.jsonl")inventoryLogPath := endpointinventory.LogPath(logPath, true)@@ -1148,34 +1142,92 @@ func TestInventoryHeartbeatAppendFailureRecordsAttemptOnly(t *testing.T) {}writeTestFile(t, filepath.Join(home, ".cursor", "mcp.json"), `{"mcpServers":{"one":{"command":"npx"}}}`)cfg := endpointconfig.Default(true, logPath)- cfg.Inventory = &endpointconfig.Inventory{TTLSeconds: 86400, Runtimes: []string{"cursor"}}+ cfg.Inventory = &endpointconfig.Inventory{Runtimes: []string{"cursor"}}settings := endpointconfig.InventoryConfig(cfg)- first, err := writeInventoryHeartbeat(cfg, settings, false, work, "hook", "cursor")+ first, err := writeInventoryHeartbeat(cfg, settings, false, inventoryTriggerScheduled, heartbeatScope{})if err == nil {t.Fatal("writeInventoryHeartbeat should fail when inventory log path is a directory")}if first.SnapshotDigest == "" {t.Fatalf("failed heartbeat should still report snapshot digest: %#v", first)}- statePath := endpointinventory.StatePathForLog(logPath, true)- state, err := endpointinventory.ReadState(statePath)+ state, err := endpointinventory.ReadState(endpointinventory.StatePathForLog(logPath, true))if err != nil {t.Fatal(err)}- if state.LastAttemptAt == "" {- t.Fatalf("failed append should persist attempt timestamp: %#v", state)- }if state.LastEmittedAt != "" || state.LastSnapshotDigest != "" {- t.Fatalf("failed append should not mark emission complete: %#v", state)+ t.Fatalf("failed append must leave the state untouched: %#v", state)+ }+ // No backoff: the next scheduled run is a plain retry.+ if _, err := writeInventoryHeartbeat(cfg, settings, false, inventoryTriggerScheduled, heartbeatScope{}); err == nil {+ t.Fatal("second run should retry and fail again, not be skipped")}+}- second, err := writeInventoryHeartbeat(cfg, settings, false, work, "hook", "cursor")+func TestScheduledHeartbeatInSystemModeScansTheConsoleUsersHome(t *testing.T) {+ consoleHome := t.TempDir()+ writeTestFile(t, filepath.Join(consoleHome, ".cursor", "mcp.json"), `{"mcpServers":{"console-one":{"command":"npx"}}}`)+ t.Setenv("HOME", t.TempDir()) // root's home: must not be what gets scanned+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ cfg := endpointconfig.Default(false, logPath)+ settings := endpointconfig.InventoryConfig(cfg)++ oldResolver := activeConsoleUser+ t.Cleanup(func() { activeConsoleUser = oldResolver })+ activeConsoleUser = func() (consoleUserInfo, bool, error) {+ return consoleUserInfo{Username: "console", HomeDir: consoleHome}, true, nil+ }+ if _, err := writeInventoryHeartbeat(cfg, settings, false, inventoryTriggerScheduled, systemHeartbeatScope()); err != nil {+ t.Fatalf("heartbeat with console user: %v", err)+ }+ inventoryLogPath := endpointinventory.LogPath(logPath, false)+ data, err := os.ReadFile(inventoryLogPath)if err != nil {- t.Fatalf("second heartbeat should be skipped by attempt backoff, got error: %v", err)+ t.Fatal(err)+ }+ if !strings.Contains(string(data), `"server_name":"console-one"`) {+ t.Fatalf("system-mode heartbeat should inventory the console user's home: %s", data)+ }+ stateBefore, _ := endpointinventory.ReadState(endpointinventory.StatePathForLog(logPath, false))++ // Nobody logged in: liveness only, no snapshot, digest untouched.+ activeConsoleUser = func() (consoleUserInfo, bool, error) { return consoleUserInfo{}, false, nil }+ result, err := writeInventoryHeartbeat(cfg, settings, false, inventoryTriggerScheduled, systemHeartbeatScope())+ if err != nil {+ t.Fatalf("heartbeat without console user: %v", err)+ }+ if !result.Written || result.SnapshotWritten {+ t.Fatalf("no-console-user heartbeat = %#v, want heartbeat only", result)+ }+ data, _ = os.ReadFile(inventoryLogPath)+ if strings.Count(string(data), "inventory.heartbeat") != 2 || strings.Count(string(data), "inventory.snapshot") != 1 {+ t.Fatalf("expected a second heartbeat and no second snapshot: %s", data)+ }+ stateAfter, _ := endpointinventory.ReadState(endpointinventory.StatePathForLog(logPath, false))+ // last_emitted_at has second resolution, so only the digest is a reliable assertion here.+ if stateAfter.LastSnapshotDigest != stateBefore.LastSnapshotDigest || stateAfter.LastEmittedAt == "" {+ t.Fatalf("no-console-user run must keep the digest: before=%#v after=%#v", stateBefore, stateAfter)+ }+}++// Hooks installed by older versions still run `inventory heartbeat --trigger hook` on every prompt.+func TestHeartbeatHookTriggerIsRetired(t *testing.T) {+ t.Setenv("HOME", t.TempDir())+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ oldOpts := endpointOpts+ t.Cleanup(func() { endpointOpts = oldOpts })+ endpointOpts.userMode, endpointOpts.systemMode = true, false+ endpointOpts.logPath = logPath+ endpointOpts.inventoryTrigger = "hook"+ endpointOpts.inventoryTriggerHarness = "claude"+ endpointOpts.inventoryWorkingDir = "/tmp"+ endpointOpts.jsonOutput = false+ if err := runEndpointInventoryHeartbeat(nil, nil); err != nil {+ t.Fatalf("retired hook trigger must exit cleanly: %v", err)}- if second.SkippedReason != "attempt_backoff" {- t.Fatalf("second heartbeat = %#v, want attempt_backoff", second)+ if _, err := os.Stat(endpointinventory.LogPath(logPath, true)); !os.IsNotExist(err) {+ t.Fatalf("retired hook trigger must not write inventory, stat err=%v", err)}}diff --git a/cli/beacon/internal/endpoint/config/config.go b/cli/beacon/internal/endpoint/config/config.goindex 5ce1db82..cab504f5 100644--- a/cli/beacon/internal/endpoint/config/config.go+++ b/cli/beacon/internal/endpoint/config/config.go@@ -132,9 +132,11 @@ type Collector struct {IncludeCodexSpans bool `json:"include_codex_spans,omitempty"`}+// Inventory is the `inventory_heartbeat` block. `enabled` nil means enabled; it governs both the+// scheduled job and the writer. A `ttl_seconds` key written by older versions is ignored: the+// heartbeat runs on the scheduler's interval, not a TTL.type Inventory struct {Enabled *bool `json:"enabled,omitempty"`- TTLSeconds int `json:"ttl_seconds,omitempty"`Runtimes []string `json:"runtimes,omitempty"`IncludeContents *bool `json:"include_contents,omitempty"`MaxContentBytes int `json:"max_content_bytes,omitempty"`@@ -142,7 +144,6 @@ type Inventory struct {type InventorySettings struct {Enabled bool- TTLSeconds intRuntimes []stringIncludeContents boolMaxContentBytes int@@ -192,9 +193,8 @@ func Default(userMode bool, logPath string) Config {func InventoryDefaults() InventorySettings {return InventorySettings{- Enabled: true,- TTLSeconds: 24 * 60 * 60,- Runtimes: []string{},+ Enabled: true,+ Runtimes: []string{},}}@@ -206,9 +206,6 @@ func InventoryConfig(cfg Config) InventorySettings {if cfg.Inventory.Enabled != nil {settings.Enabled = *cfg.Inventory.Enabled}- if cfg.Inventory.TTLSeconds > 0 {- settings.TTLSeconds = cfg.Inventory.TTLSeconds- }if len(cfg.Inventory.Runtimes) > 0 {settings.Runtimes = append([]string(nil), cfg.Inventory.Runtimes...)}diff --git a/cli/beacon/internal/endpoint/config/config_test.go b/cli/beacon/internal/endpoint/config/config_test.goindex 9b9c1169..2897f4d8 100644--- a/cli/beacon/internal/endpoint/config/config_test.go+++ b/cli/beacon/internal/endpoint/config/config_test.go@@ -30,7 +30,7 @@ func TestDefaultUserConfigUsesHomeScopedPaths(t *testing.T) {t.Fatalf("unexpected default harnesses: %#v", cfg.Harnesses)}inventory := InventoryConfig(cfg)- if !inventory.Enabled || inventory.TTLSeconds != 86400 || len(inventory.Runtimes) != 0 {+ if !inventory.Enabled || len(inventory.Runtimes) != 0 {t.Fatalf("unexpected inventory defaults: %#v", inventory)}if inventory.IncludeContents || inventory.MaxContentBytes != 0 {@@ -61,7 +61,7 @@ func TestSaveLoadRoundTrip(t *testing.T) {cfg.Collector.IncludeCodexSpans = truecfg.EventCategories = []string{"tool", "session"}enabled := true- cfg.Inventory = &Inventory{Enabled: &enabled, TTLSeconds: 30, Runtimes: []string{"cursor"}}+ cfg.Inventory = &Inventory{Enabled: &enabled, Runtimes: []string{"cursor"}}path, err := Save(cfg)if err != nil {@@ -91,7 +91,7 @@ func TestSaveLoadRoundTrip(t *testing.T) {t.Fatalf("EventCategories did not round-trip: %#v", loaded.EventCategories)}inventory := InventoryConfig(loaded)- if !inventory.Enabled || inventory.TTLSeconds != 30 || len(inventory.Runtimes) != 1 || inventory.Runtimes[0] != "cursor" {+ if !inventory.Enabled || len(inventory.Runtimes) != 1 || inventory.Runtimes[0] != "cursor" {t.Fatalf("Inventory did not round-trip: %#v", inventory)}data, err := os.ReadFile(path)diff --git a/cli/beacon/internal/endpoint/inventory/heartbeat.go b/cli/beacon/internal/endpoint/inventory/heartbeat.goindex a458c7e3..7d29cf7c 100644--- a/cli/beacon/internal/endpoint/inventory/heartbeat.go+++ b/cli/beacon/internal/endpoint/inventory/heartbeat.go@@ -7,7 +7,6 @@ import ("os""path/filepath""strings"- "time"endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config""github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"@@ -22,10 +21,11 @@ type Counts struct {Skills int `json:"skills"`}+// State is what the scheduled heartbeat remembers between runs. A run that fails to append+// leaves it untouched, so the next run is a plain retry.type State struct {LastEmittedAt string `json:"last_emitted_at,omitempty"`LastSnapshotDigest string `json:"last_snapshot_digest,omitempty"`- LastAttemptAt string `json:"last_attempt_at,omitempty"`}type LockedState struct {@@ -150,28 +150,6 @@ func SnapshotDigest(result Result) string {return "sha256:" + hex.EncodeToString(sum[:])}-func TTLExpired(state State, now time.Time, ttlSeconds int) bool {- if ttlSeconds <= 0 || state.LastEmittedAt == "" {- return true- }- last, err := time.Parse(time.RFC3339, state.LastEmittedAt)- if err != nil {- return true- }- return !now.Before(last.Add(time.Duration(ttlSeconds) * time.Second))-}--func AttemptBackoffActive(state State, now time.Time, backoff time.Duration) bool {- if backoff <= 0 || state.LastAttemptAt == "" {- return false- }- last, err := time.Parse(time.RFC3339, state.LastAttemptAt)- if err != nil {- return false- }- return now.Before(last.Add(backoff))-}-func existingConfigs(configs []Config) []Config {out := make([]Config, 0, len(configs))for _, config := range configs {diff --git a/cli/beacon/internal/endpoint/inventory/inventory.go b/cli/beacon/internal/endpoint/inventory/inventory.goindex e98bc396..74b3b6be 100644--- a/cli/beacon/internal/endpoint/inventory/inventory.go+++ b/cli/beacon/internal/endpoint/inventory/inventory.go@@ -61,8 +61,12 @@ const (type Options struct {HomeDir stringWorkingDir string- Runtimes []string- Now func() time.Time+ // SkipProjectScope leaves project-scoped config out of the scan and never falls back to the+ // process working directory. The scheduled heartbeat sets it: a job under launchd or systemd+ // has no meaningful cwd (it is `/`), so project scope belongs to `beacon endpoint inventory`.+ SkipProjectScope bool+ Runtimes []string+ Now func() time.Time// IncludeContents opts into capturing redacted, size-limited raw bodies of// config, hook, and skill files plus full (redacted) MCP server definitions.// When false (the default) inventory stays metadata- and hash-only.@@ -142,7 +146,7 @@ func Scan(opts Options) Result {home, _ = os.UserHomeDir()}wd := opts.WorkingDir- if wd == "" {+ if wd == "" && !opts.SkipProjectScope {wd, _ = os.Getwd()}now := opts.Now@@ -160,7 +164,7 @@ func Scan(opts Options) Result {},}co := contentOptions{include: opts.IncludeContents, maxBytes: opts.MaxContentBytes}- for _, item := range filterCandidates(candidates(home, wd), opts.Runtimes) {+ for _, item := range filterCandidates(withoutProjectScope(candidates(home, wd), wd), opts.Runtimes) {config, servers := inspectCandidate(item, redaction, co)result.Configs = append(result.Configs, config)result.MCPServers = append(result.MCPServers, servers...)@@ -169,6 +173,21 @@ func Scan(opts Options) Result {return result}+// withoutProjectScope drops project-scoped candidates when there is no working directory to+// scope them to; otherwise they would resolve relative to the process cwd.+func withoutProjectScope(items []candidate, wd string) []candidate {+ if wd != "" {+ return items+ }+ out := items[:0]+ for _, item := range items {+ if item.scope != ScopeProject {+ out = append(out, item)+ }+ }+ return out+}+func filterCandidates(items []candidate, runtimes []string) []candidate {allowed := runtimeSet(runtimes)if len(allowed) == 0 {diff --git a/cli/beacon/internal/endpoint/inventory/inventory_test.go b/cli/beacon/internal/endpoint/inventory/inventory_test.goindex 54392e17..19553d04 100644--- a/cli/beacon/internal/endpoint/inventory/inventory_test.go+++ b/cli/beacon/internal/endpoint/inventory/inventory_test.go@@ -1023,3 +1023,61 @@ func TestScanFxWithoutMCPConfigurationIsQuiet(t *testing.T) {t.Errorf("absent fx mcp.json reported as exists:%t parser:%s", config.Exists, config.ParserStatus)}}++// The scheduled heartbeat runs with no meaningful working directory (launchd and systemd start+// jobs in /). It must not fall back to the process cwd and scan whatever repo happens to be there.+func TestScanSkipProjectScopeIgnoresTheProcessCwd(t *testing.T) {+ home := t.TempDir()+ project := t.TempDir()+ if err := os.MkdirAll(filepath.Join(project, ".cursor"), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(project, ".cursor", "mcp.json"), []byte(`{"mcpServers":{"proj":{"command":"npx"}}}`), 0o644); err != nil {+ t.Fatal(err)+ }+ if err := os.MkdirAll(filepath.Join(project, ".claude", "skills", "s1"), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(project, ".claude", "skills", "s1", "SKILL.md"), []byte("---\nname: s1\ndescription: d\n---\n"), 0o644); err != nil {+ t.Fatal(err)+ }+ wd, err := os.Getwd()+ if err != nil {+ t.Fatal(err)+ }+ if err := os.Chdir(project); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = os.Chdir(wd) })++ withCwd := Scan(Options{HomeDir: home})+ if !hasScope(withCwd, ScopeProject) {+ t.Fatal("without SkipProjectScope the cwd project config should be scanned (control)")+ }+ skipped := Scan(Options{HomeDir: home, SkipProjectScope: true})+ if hasScope(skipped, ScopeProject) {+ t.Fatalf("SkipProjectScope must drop project-scoped configs and skills: %+v", skipped)+ }+ if skipped.UserScope.WorkingDir != "" || skipped.UserScope.WorkDirHash != "" {+ t.Fatalf("SkipProjectScope must leave the working dir empty: %+v", skipped.UserScope)+ }+ for _, server := range skipped.MCPServers {+ if server.ServerName == "proj" {+ t.Fatal("project MCP server leaked into a project-scope-free scan")+ }+ }+}++func hasScope(result Result, scope string) bool {+ for _, c := range result.Configs {+ if c.Scope == scope {+ return true+ }+ }+ for _, s := range result.Skills {+ if s.SourceScope == scope {+ return true+ }+ }+ return false+}diff --git a/cli/beacon/internal/endpoint/inventory/skills.go b/cli/beacon/internal/endpoint/inventory/skills.goindex e3a075b2..2449cb8f 100644--- a/cli/beacon/internal/endpoint/inventory/skills.go+++ b/cli/beacon/internal/endpoint/inventory/skills.go@@ -36,7 +36,17 @@ type skillRoot struct {func scanSkills(home, wd, redaction string, runtimes []string, co contentOptions) []Skill {var skills []Skill- for _, root := range filterSkillRoots(skillRoots(home, wd), runtimes) {+ roots := skillRoots(home, wd)+ if wd == "" {+ kept := roots[:0]+ for _, root := range roots {+ if root.scope != ScopeProject {+ kept = append(kept, root)+ }+ }+ roots = kept+ }+ for _, root := range filterSkillRoots(roots, runtimes) {skills = append(skills, inspectSkillRoot(root, redaction, co)...)}return dedupeSkills(skills)