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
enhance inventory
Justin D'Souza226cc3d43375
diff --git a/cli/beacon/cmd/endpoint.go b/cli/beacon/cmd/endpoint.goindex 3529244c..65e418e5 100644--- a/cli/beacon/cmd/endpoint.go+++ b/cli/beacon/cmd/endpoint.go@@ -85,6 +85,7 @@ var endpointOpts struct {dashboardOpen boolincludeEventSummaries boolincludeRawEvents bool+ writeInventoryEvent bool}var endpointCmd = &cobra.Command{@@ -814,10 +815,12 @@ func init() {endpointDoctorCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print doctor results as JSON")endpointInventoryCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print inventory as JSON")endpointInventoryCmd.Flags().BoolVar(&endpointOpts.allTargets, "all", false, "Include all supported targets")+ endpointInventoryCmd.Flags().BoolVar(&endpointOpts.writeInventoryEvent, "write-event", false, "Append config inventory events to the endpoint runtime log")topLevelDoctorCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print doctor results as JSON")topLevelStatusCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print status as JSON")topLevelInventoryCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print inventory as JSON")topLevelInventoryCmd.Flags().BoolVar(&endpointOpts.allTargets, "all", false, "Include all supported targets")+ topLevelInventoryCmd.Flags().BoolVar(&endpointOpts.writeInventoryEvent, "write-event", false, "Append config inventory events to the endpoint runtime log")endpointTestEventCmd.Flags().BoolVar(&endpointOpts.jsonOutput, "json", false, "Print validation stages as JSON")endpointBundleDiagnosticsCmd.Flags().StringVar(&endpointOpts.outputDir, "output", "", "Output directory for diagnostics bundle")endpointBundleDiagnosticsCmd.Flags().BoolVar(&endpointOpts.includeEventSummaries, "include-event-summaries", false, "Include redacted event summaries")diff --git a/cli/beacon/cmd/endpoint_diagnostics.go b/cli/beacon/cmd/endpoint_diagnostics.goindex 2e9fce1c..2c158414 100644--- a/cli/beacon/cmd/endpoint_diagnostics.go+++ b/cli/beacon/cmd/endpoint_diagnostics.go@@ -17,8 +17,10 @@ import (endpointhooks "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/integrations/cowork""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/integrations/openclaw"+ endpointinventory "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/inventory""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version")@@ -38,6 +40,9 @@ type inventoryResult struct {Hooks map[string]hookTargetResult `json:"hooks,omitempty"`Destinations lifecycle.DestinationStatus `json:"destinations"`LastEventObserved bool `json:"last_event_observed"`+ Configs []endpointinventory.Config `json:"configs,omitempty"`+ MCPServers []endpointinventory.MCPServer `json:"mcp_servers,omitempty"`+ UserScope endpointinventory.UserScope `json:"user_scope"`}type hookTargetResult struct {@@ -113,6 +118,7 @@ func runEndpointInventory(cmd *cobra.Command, args []string) error {if err != nil {return err}+ configInventory := endpointinventory.Scan(endpointinventory.Options{ContentRetention: string(effectiveCfg.ContentRetention)})result := inventoryResult{GeneratedAt: time.Now().UTC().Format(time.RFC3339),RuntimeLog: status.RuntimeLog,@@ -123,6 +129,14 @@ func runEndpointInventory(cmd *cobra.Command, args []string) error {Hooks: hookStatusesWithConfig(hookTargetNames, effectiveCfg),Destinations: status.Destinations,LastEventObserved: status.LastEvent != "",+ Configs: configInventory.Configs,+ MCPServers: configInventory.MCPServers,+ UserScope: configInventory.UserScope,+ }+ if endpointOpts.writeInventoryEvent {+ if err := writeInventoryEvents(effectiveCfg, configInventory); err != nil {+ return err+ }}if endpointOpts.jsonOutput {if !endpointOpts.allTargets {@@ -150,9 +164,71 @@ func runEndpointInventory(cmd *cobra.Command, args []string) error {fmt.Printf("Hook: %s status=%s installed=%t\n", name, hook.Status, hook.Installed)}}+ for _, config := range result.Configs {+ if !endpointOpts.allTargets && !config.Exists {+ continue+ }+ path := config.Path+ if path == "" {+ path = config.PathHash+ }+ fmt.Printf("Config: %s scope=%s status=%s mcp_servers=%d path=%s\n", config.Runtime, config.Scope, config.ParserStatus, config.MCPServerCount, path)+ }+ for _, server := range result.MCPServers {+ name := server.ServerName+ if name == "" {+ name = server.ServerNameHash+ }+ fmt.Printf("MCP: %s %s scope=%s transport=%s command_present=%t args=%d env_keys=%d\n", server.Runtime, name, server.SourceScope, server.Transport, server.CommandPresent, server.ArgsCount, server.EnvKeyCount)+ }return nil}+func writeInventoryEvents(cfg endpointconfig.Config, result endpointinventory.Result) error {+ for _, config := range result.Configs {+ if !config.Exists {+ continue+ }+ servers := mcpServersForConfig(result.MCPServers, config)+ event := schema.NewEvent(schema.NewEventOptions{+ Action: "config.inventory",+ Category: "inventory",+ Severity: schema.SeverityInfo,+ AgentVersion: version.GetVersion(),+ Harness: schema.HarnessInfo{+ Name: config.Runtime,+ ConfigPath: config.Path,+ },+ Message: fmt.Sprintf("%s config inventory observed", config.Runtime),+ })+ event.Content = &schema.ContentInfo{+ Retention: string(cfg.ContentRetention),+ Included: true,+ Redacted: true,+ }+ event.Raw = map[string]interface{}{+ "inventory": map[string]interface{}{+ "config": config,+ "mcp_servers": servers,+ },+ }+ if _, err := writer.AppendEvent(event, writer.Options{Path: cfg.LogPath, UserMode: cfg.UserMode}); err != nil {+ return err+ }+ }+ return nil+}++func mcpServersForConfig(servers []endpointinventory.MCPServer, config endpointinventory.Config) []endpointinventory.MCPServer {+ out := []endpointinventory.MCPServer{}+ for _, server := range servers {+ if server.Runtime == config.Runtime && server.SourcePathHash == config.PathHash {+ out = append(out, server)+ }+ }+ return out+}+func runEndpointTestEvent(cmd *cobra.Command, args []string) error {cfg := loadOrDefaultConfig()writableStage := stageFromCheck(checkLogWritable(cfg))diff --git a/cli/beacon/cmd/endpoint_test.go b/cli/beacon/cmd/endpoint_test.goindex dfcfdd43..51589e6f 100644--- a/cli/beacon/cmd/endpoint_test.go+++ b/cli/beacon/cmd/endpoint_test.go@@ -11,6 +11,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"+ endpointinventory "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/inventory""github.com/spf13/cobra")@@ -532,6 +533,60 @@ func TestRobustEndpointCommandsRegistered(t *testing.T) {}}+func TestWriteInventoryEventsAppendsConfigInventory(t *testing.T) {+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ cfg := endpointconfig.Default(true, logPath)+ result := endpointinventory.Result{+ Configs: []endpointinventory.Config{+ {+ Runtime: "claude_code",+ Path: filepath.Join(t.TempDir(), ".claude", "settings.json"),+ PathHash: "sha256:path",+ Scope: endpointinventory.ScopeUser,+ Exists: true,+ Readable: true,+ ParserStatus: endpointinventory.StatusOK,+ Redaction: endpointinventory.RedactionRedacted,+ },+ {+ Runtime: "cursor",+ PathHash: "sha256:missing",+ Scope: endpointinventory.ScopeUser,+ Exists: false,+ ParserStatus: endpointinventory.StatusNotFound,+ Redaction: endpointinventory.RedactionRedacted,+ },+ },+ MCPServers: []endpointinventory.MCPServer{+ {+ Runtime: "claude_code",+ ServerName: "filesystem",+ SourcePathHash: "sha256:path",+ SourceScope: endpointinventory.ScopeUser,+ Transport: endpointinventory.TransportStdio,+ DefinitionHash: "sha256:def",+ ParserStatus: endpointinventory.StatusOK,+ Redaction: endpointinventory.RedactionRedacted,+ },+ },+ }++ if err := writeInventoryEvents(cfg, result); err != nil {+ t.Fatalf("writeInventoryEvents returned error: %v", err)+ }+ data, err := os.ReadFile(logPath)+ if err != nil {+ t.Fatal(err)+ }+ text := string(data)+ if strings.Count(text, "config.inventory") != 1 {+ t.Fatalf("inventory events = %d, want 1; log=%s", strings.Count(text, "config.inventory"), text)+ }+ if !strings.Contains(text, "filesystem") {+ t.Fatalf("inventory log missing MCP server summary: %s", text)+ }+}+func TestTopLevelAliasesRegistered(t *testing.T) {for _, name := range []string{"doctor", "status", "inventory"} {cmd, _, err := rootCmd.Find([]string{name})diff --git a/cli/beacon/go.mod b/cli/beacon/go.modindex d8373865..d651d3d5 100644--- a/cli/beacon/go.mod+++ b/cli/beacon/go.mod@@ -4,6 +4,7 @@ go 1.24require (github.com/asymptote-labs/agent-beacon/pkg/asymptotetrace v0.0.0+ github.com/pelletier/go-toml/v2 v2.3.1github.com/spf13/cobra v1.8.1gopkg.in/yaml.v3 v3.0.1)diff --git a/cli/beacon/go.sum b/cli/beacon/go.sumindex 591f1ce0..90ab69a4 100644--- a/cli/beacon/go.sum+++ b/cli/beacon/go.sum@@ -2,12 +2,15 @@ github.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVgithub.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=+github.com/pelletier/go-toml/v2 v2.3.1 h1:MYEvvGnQjeNkRF1qUuGolNtNExTDwct51yp7olPtrEc=+github.com/pelletier/go-toml/v2 v2.3.1/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=diff --git a/cli/beacon/internal/endpoint/inventory/inventory.go b/cli/beacon/internal/endpoint/inventory/inventory.gonew file mode 100644index 00000000..dd93c2ea--- /dev/null+++ b/cli/beacon/internal/endpoint/inventory/inventory.go@@ -0,0 +1,464 @@+package inventory++import (+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+ "sort"+ "strings"+ "time"++ "github.com/pelletier/go-toml/v2"+)++const (+ TransportStdio = "stdio"+ TransportHTTP = "http"+ TransportSSE = "sse"+ TransportWebSocket = "websocket"+ TransportUnknown = "unknown"++ ScopeUser = "user"+ ScopeProject = "project"+ ScopeManaged = "managed"+ ScopeWorkspace = "workspace"+ ScopeSystem = "system"+ ScopeUnknown = "unknown"++ StatusOK = "ok"+ StatusPartial = "partial"+ StatusParseFailed = "parse_failed"+ StatusNotFound = "not_found"+ StatusUnreadable = "unreadable"+ StatusUnsupported = "unsupported"++ RedactionMetadata = "metadata"+ RedactionRedacted = "redacted"+ RedactionFull = "full"+)++type Options struct {+ ContentRetention string+ HomeDir string+ WorkingDir string+ Now func() time.Time+}++type Result struct {+ GeneratedAt string `json:"generated_at"`+ Configs []Config `json:"configs"`+ MCPServers []MCPServer `json:"mcp_servers"`+ UserScope UserScope `json:"user_scope"`+}++type UserScope struct {+ Mode string `json:"mode"`+ HomePath string `json:"home_path,omitempty"`+ HomeHash string `json:"home_hash,omitempty"`+ WorkingDir string `json:"working_dir,omitempty"`+ WorkDirHash string `json:"working_dir_hash,omitempty"`+}++type Config struct {+ Runtime string `json:"runtime"`+ Path string `json:"path,omitempty"`+ PathHash string `json:"path_hash,omitempty"`+ Scope string `json:"scope"`+ Exists bool `json:"exists"`+ Readable bool `json:"readable"`+ Reason string `json:"reason,omitempty"`+ ParserStatus string `json:"parser_status"`+ FileSHA256 string `json:"file_sha256,omitempty"`+ ModifiedAt string `json:"modified_at,omitempty"`+ MCPServerCount int `json:"mcp_server_count"`+ BeaconManaged bool `json:"beacon_managed"`+ Redaction string `json:"redaction"`+}++type MCPServer struct {+ Runtime string `json:"runtime"`+ ServerName string `json:"server_name,omitempty"`+ ServerNameHash string `json:"server_name_hash,omitempty"`+ SourcePath string `json:"source_path,omitempty"`+ SourcePathHash string `json:"source_path_hash,omitempty"`+ SourceScope string `json:"source_scope"`+ Transport string `json:"transport"`+ CommandPresent bool `json:"command_present"`+ CommandName string `json:"command_name,omitempty"`+ CommandNameHash string `json:"command_name_hash,omitempty"`+ ArgsCount int `json:"args_count,omitempty"`+ URLPresent bool `json:"url_present"`+ EnvKeys []string `json:"env_keys,omitempty"`+ EnvKeyCount int `json:"env_key_count,omitempty"`+ DefinitionHash string `json:"definition_hash"`+ ParserStatus string `json:"parser_status"`+ Redaction string `json:"redaction"`+}++type candidate struct {+ runtime string+ path string+ scope string+ format string+}++func Scan(opts Options) Result {+ redaction := normalizeRedaction(opts.ContentRetention)+ home := opts.HomeDir+ if home == "" {+ home, _ = os.UserHomeDir()+ }+ wd := opts.WorkingDir+ if wd == "" {+ wd, _ = os.Getwd()+ }+ now := opts.Now+ if now == nil {+ now = time.Now+ }+ result := Result{+ GeneratedAt: now().UTC().Format(time.RFC3339),+ UserScope: UserScope{+ Mode: "current_user",+ HomePath: valueForPath(home, redaction),+ HomeHash: hashString(home),+ WorkingDir: valueForPath(wd, redaction),+ WorkDirHash: hashString(wd),+ },+ }+ for _, item := range candidates(home, wd) {+ config, servers := inspectCandidate(item, redaction)+ result.Configs = append(result.Configs, config)+ result.MCPServers = append(result.MCPServers, servers...)+ }+ return result+}++func candidates(home, wd string) []candidate {+ items := []candidate{+ {runtime: "claude_code", path: filepath.Join(home, ".claude", "settings.json"), scope: ScopeUser, format: "json"},+ {runtime: "claude_code", path: filepath.Join(wd, ".claude", "settings.json"), scope: ScopeProject, format: "json"},+ {runtime: "claude_code", path: "/Library/Application Support/ClaudeCode/managed-settings.json", scope: ScopeManaged, format: "json"},+ {runtime: "codex_cli", path: filepath.Join(home, ".codex", "config.toml"), scope: ScopeUser, format: "toml"},+ {runtime: "cursor", path: filepath.Join(home, ".cursor", "mcp.json"), scope: ScopeUser, format: "json"},+ {runtime: "cursor", path: filepath.Join(wd, ".cursor", "mcp.json"), scope: ScopeProject, format: "json"},+ {runtime: "cursor", path: filepath.Join(home, ".cursor", "hooks.json"), scope: ScopeUser, format: "json"},+ {runtime: "cursor", path: filepath.Join(wd, ".cursor", "hooks.json"), scope: ScopeProject, format: "json"},+ }+ seen := map[string]bool{}+ out := make([]candidate, 0, len(items))+ for _, item := range items {+ key := item.runtime + "\x00" + item.path+ if seen[key] {+ continue+ }+ seen[key] = true+ out = append(out, item)+ }+ return out+}++func inspectCandidate(item candidate, redaction string) (Config, []MCPServer) {+ config := Config{+ Runtime: item.runtime,+ Path: valueForPath(item.path, redaction),+ PathHash: hashString(item.path),+ Scope: item.scope,+ ParserStatus: StatusNotFound,+ Redaction: redaction,+ }+ info, err := os.Stat(item.path)+ if err != nil {+ config.Reason = errReason(err)+ if !os.IsNotExist(err) {+ config.ParserStatus = StatusUnreadable+ }+ return config, nil+ }+ config.Exists = true+ config.ModifiedAt = info.ModTime().UTC().Format(time.RFC3339)+ if info.IsDir() {+ config.ParserStatus = StatusUnsupported+ config.Reason = "path is a directory"+ return config, nil+ }+ data, err := os.ReadFile(item.path)+ if err != nil {+ config.ParserStatus = StatusUnreadable+ config.Reason = errReason(err)+ return config, nil+ }+ config.Readable = true+ config.FileSHA256 = hashBytes(data)+ config.BeaconManaged = beaconManaged(data)++ servers, parseErr := parseMCPServers(item, data, redaction)+ config.MCPServerCount = len(servers)+ config.ParserStatus = StatusOK+ if parseErr != nil {+ config.ParserStatus = StatusParseFailed+ config.Reason = parseErr.Error()+ }+ return config, servers+}++func parseMCPServers(item candidate, data []byte, redaction string) ([]MCPServer, error) {+ switch item.format {+ case "json":+ var root map[string]interface{}+ if err := json.Unmarshal(data, &root); err != nil {+ return nil, err+ }+ return serversFromMap(item, root, redaction), nil+ case "toml":+ var root map[string]interface{}+ if err := toml.Unmarshal(data, &root); err != nil {+ return nil, err+ }+ return serversFromMap(item, root, redaction), nil+ default:+ return nil, fmt.Errorf("unsupported config format %q", item.format)+ }+}++func serversFromMap(item candidate, root map[string]interface{}, redaction string) []MCPServer {+ var servers []MCPServer+ for _, key := range []string{"mcpServers", "mcp_servers", "servers"} {+ if raw, ok := root[key]; ok {+ servers = append(servers, serversFromBlock(item, raw, redaction)...)+ }+ }+ if raw, ok := root["mcp"]; ok {+ servers = append(servers, serversFromBlock(item, raw, redaction)...)+ }+ return dedupeServers(servers)+}++func serversFromBlock(item candidate, raw interface{}, redaction string) []MCPServer {+ block, ok := raw.(map[string]interface{})+ if !ok {+ return nil+ }+ var servers []MCPServer+ for name, value := range block {+ def, ok := value.(map[string]interface{})+ if !ok {+ continue+ }+ if looksLikeServerDefinition(def) {+ servers = append(servers, serverFromDefinition(item, name, def, redaction))+ continue+ }+ for nestedName, nestedValue := range def {+ nestedDef, ok := nestedValue.(map[string]interface{})+ if ok && looksLikeServerDefinition(nestedDef) {+ servers = append(servers, serverFromDefinition(item, nestedName, nestedDef, redaction))+ }+ }+ }+ return servers+}++func looksLikeServerDefinition(def map[string]interface{}) bool {+ for _, key := range []string{"command", "args", "env", "url", "transport"} {+ if _, ok := def[key]; ok {+ return true+ }+ }+ return false+}++func serverFromDefinition(item candidate, name string, def map[string]interface{}, redaction string) MCPServer {+ command := firstString(def["command"])+ url := firstString(def["url"])+ envKeys := mapKeys(def["env"])+ server := MCPServer{+ Runtime: item.runtime,+ ServerName: valueForName(name, redaction),+ ServerNameHash: hashString(name),+ SourcePath: valueForPath(item.path, redaction),+ SourcePathHash: hashString(item.path),+ SourceScope: item.scope,+ Transport: inferTransport(def, url, command),+ CommandPresent: command != "",+ CommandName: valueForName(filepath.Base(command), redaction),+ ArgsCount: sliceLen(def["args"]),+ URLPresent: url != "",+ EnvKeys: valuesForEnvKeys(envKeys, redaction),+ EnvKeyCount: len(envKeys),+ DefinitionHash: "sha256:" + canonicalHash(def),+ ParserStatus: StatusOK,+ Redaction: redaction,+ }+ if command != "" {+ server.CommandNameHash = hashString(filepath.Base(command))+ }+ return server+}++func inferTransport(def map[string]interface{}, url, command string) string {+ transport := strings.ToLower(firstString(def["transport"]))+ switch transport {+ case TransportStdio, TransportHTTP, TransportSSE, TransportWebSocket:+ return transport+ }+ lowerURL := strings.ToLower(url)+ switch {+ case strings.HasPrefix(lowerURL, "ws://"), strings.HasPrefix(lowerURL, "wss://"):+ return TransportWebSocket+ case strings.Contains(lowerURL, "sse"):+ return TransportSSE+ case strings.HasPrefix(lowerURL, "http://"), strings.HasPrefix(lowerURL, "https://"):+ return TransportHTTP+ case command != "":+ return TransportStdio+ default:+ return TransportUnknown+ }+}++func dedupeServers(servers []MCPServer) []MCPServer {+ seen := map[string]bool{}+ out := make([]MCPServer, 0, len(servers))+ for _, server := range servers {+ key := server.Runtime + "\x00" + server.SourcePathHash + "\x00" + server.ServerNameHash + "\x00" + server.DefinitionHash+ if seen[key] {+ continue+ }+ seen[key] = true+ out = append(out, server)+ }+ sort.Slice(out, func(i, j int) bool {+ if out[i].Runtime == out[j].Runtime {+ if out[i].SourcePathHash == out[j].SourcePathHash {+ return out[i].ServerNameHash < out[j].ServerNameHash+ }+ return out[i].SourcePathHash < out[j].SourcePathHash+ }+ return out[i].Runtime < out[j].Runtime+ })+ return out+}++func normalizeRedaction(retention string) string {+ switch retention {+ case RedactionMetadata:+ return RedactionMetadata+ case RedactionFull:+ return RedactionFull+ default:+ return RedactionRedacted+ }+}++func valueForPath(value, redaction string) string {+ if redaction == RedactionMetadata {+ return ""+ }+ return value+}++func valueForName(value, redaction string) string {+ if redaction == RedactionMetadata {+ return ""+ }+ return value+}++func valuesForEnvKeys(keys []string, redaction string) []string {+ if redaction != RedactionRedacted && redaction != RedactionFull {+ return nil+ }+ out := make([]string, 0, len(keys))+ for _, key := range keys {+ if safeEnvKey(key) {+ out = append(out, key)+ }+ }+ return out+}++func safeEnvKey(key string) bool {+ upper := strings.ToUpper(key)+ for _, marker := range []string{"TOKEN", "SECRET", "PASSWORD", "KEY", "AUTH", "CREDENTIAL"} {+ if strings.Contains(upper, marker) {+ return false+ }+ }+ return true+}++func mapKeys(raw interface{}) []string {+ values, ok := raw.(map[string]interface{})+ if !ok {+ return nil+ }+ keys := make([]string, 0, len(values))+ for key := range values {+ keys = append(keys, key)+ }+ sort.Strings(keys)+ return keys+}++func sliceLen(raw interface{}) int {+ values, ok := raw.([]interface{})+ if !ok {+ return 0+ }+ return len(values)+}++func firstString(raw interface{}) string {+ switch typed := raw.(type) {+ case string:+ return typed+ default:+ return ""+ }+}++func beaconManaged(data []byte) bool {+ text := string(data)+ return strings.Contains(text, "BEACON_ENDPOINT_MODE=1") ||+ strings.Contains(text, "beacon-managed-opencode-plugin:v1") ||+ strings.Contains(text, "OTEL_EXPORTER_OTLP_ENDPOINT") && (strings.Contains(text, "127.0.0.1") || strings.Contains(text, "localhost"))+}++func hashString(value string) string {+ if value == "" {+ return ""+ }+ sum := sha256.Sum256([]byte(value))+ return "sha256:" + hex.EncodeToString(sum[:])+}++func hashBytes(value []byte) string {+ sum := sha256.Sum256(value)+ return "sha256:" + hex.EncodeToString(sum[:])+}++func canonicalHash(value interface{}) string {+ data, err := json.Marshal(value)+ if err != nil {+ return hashString(fmt.Sprint(value))+ }+ sum := sha256.Sum256(data)+ return hex.EncodeToString(sum[:])+}++func errReason(err error) string {+ if err == nil {+ return ""+ }+ if os.IsNotExist(err) {+ return "not found"+ }+ if os.IsPermission(err) {+ return "permission denied"+ }+ return err.Error()+}diff --git a/cli/beacon/internal/endpoint/inventory/inventory_test.go b/cli/beacon/internal/endpoint/inventory/inventory_test.gonew file mode 100644index 00000000..4e1de39a--- /dev/null+++ b/cli/beacon/internal/endpoint/inventory/inventory_test.go@@ -0,0 +1,200 @@+package inventory++import (+ "os"+ "path/filepath"+ "testing"+ "time"+)++func TestScanCurrentUserMCPInventory(t *testing.T) {+ home := t.TempDir()+ work := t.TempDir()+ writeFile(t, filepath.Join(home, ".claude", "settings.json"), `{+ "mcpServers": {+ "filesystem": {+ "command": "npx",+ "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],+ "env": {"NODE_ENV": "production"}+ }+ }+}`)+ writeFile(t, filepath.Join(home, ".codex", "config.toml"), `+[mcp_servers.github]+command = "gh"+args = ["mcp", "serve"]++[mcp_servers.github.env]+GITHUB_TOKEN = "secret"+`)+ writeFile(t, filepath.Join(home, ".cursor", "mcp.json"), `{+ "mcpServers": {+ "remote": {+ "url": "https://example.test/sse",+ "transport": "sse"+ }+ }+}`)++ result := Scan(Options{+ ContentRetention: RedactionRedacted,+ HomeDir: home,+ WorkingDir: work,+ Now: fixedNow,+ })++ if got, want := len(result.MCPServers), 3; got != want {+ t.Fatalf("MCPServers len = %d, want %d: %#v", got, want, result.MCPServers)+ }+ assertServer(t, result.MCPServers, "claude_code", "filesystem", TransportStdio, true, 3, 1, 1)+ assertServer(t, result.MCPServers, "codex_cli", "github", TransportStdio, true, 2, 0, 1)+ assertServer(t, result.MCPServers, "cursor", "remote", TransportSSE, false, 0, 0, 0)++ foundClaudeConfig := false+ for _, config := range result.Configs {+ if config.Runtime == "claude_code" && config.Scope == ScopeUser {+ foundClaudeConfig = true+ if !config.Exists || !config.Readable || config.ParserStatus != StatusOK {+ t.Fatalf("Claude config status = exists:%t readable:%t parser:%s", config.Exists, config.Readable, config.ParserStatus)+ }+ if config.MCPServerCount != 1 {+ t.Fatalf("Claude MCPServerCount = %d, want 1", config.MCPServerCount)+ }+ if config.FileSHA256 == "" || config.PathHash == "" {+ t.Fatal("Claude config missing hashes")+ }+ }+ }+ if !foundClaudeConfig {+ t.Fatal("Claude user config not found in inventory")+ }+}++func TestMetadataRedactionOmitsNamesAndPaths(t *testing.T) {+ home := t.TempDir()+ work := t.TempDir()+ writeFile(t, filepath.Join(home, ".claude", "settings.json"), `{+ "mcpServers": {+ "filesystem": {"command": "npx", "env": {"NODE_ENV": "production"}}+ }+}`)++ result := Scan(Options{+ ContentRetention: RedactionMetadata,+ HomeDir: home,+ WorkingDir: work,+ Now: fixedNow,+ })++ if len(result.MCPServers) != 1 {+ t.Fatalf("MCPServers len = %d, want 1", len(result.MCPServers))+ }+ server := result.MCPServers[0]+ if server.ServerName != "" || server.CommandName != "" || server.SourcePath != "" || len(server.EnvKeys) != 0 {+ t.Fatalf("metadata server leaked redacted fields: %#v", server)+ }+ if server.ServerNameHash == "" || server.CommandNameHash == "" || server.SourcePathHash == "" || server.DefinitionHash == "" {+ t.Fatalf("metadata server missing hashes: %#v", server)+ }+ for _, config := range result.Configs {+ if config.Exists && config.Path != "" {+ t.Fatalf("metadata config leaked path: %#v", config)+ }+ }+}++func TestScanKeepsPartialResultsWhenAConfigIsMalformed(t *testing.T) {+ home := t.TempDir()+ work := t.TempDir()+ writeFile(t, filepath.Join(home, ".claude", "settings.json"), `{bad json`)+ writeFile(t, filepath.Join(home, ".codex", "config.toml"), `+[mcp_servers.github]+command = "gh"+`)++ result := Scan(Options{+ ContentRetention: RedactionRedacted,+ HomeDir: home,+ WorkingDir: work,+ Now: fixedNow,+ })++ var malformedFound bool+ for _, config := range result.Configs {+ if config.Runtime == "claude_code" && config.Scope == ScopeUser {+ malformedFound = true+ if config.ParserStatus != StatusParseFailed {+ t.Fatalf("malformed Claude parser status = %s, want %s", config.ParserStatus, StatusParseFailed)+ }+ }+ }+ if !malformedFound {+ t.Fatal("malformed Claude config result not found")+ }+ assertServer(t, result.MCPServers, "codex_cli", "github", TransportStdio, true, 0, 0, 0)+}++func TestMissingCandidatesAreReportedAsNotFound(t *testing.T) {+ result := Scan(Options{+ ContentRetention: RedactionRedacted,+ HomeDir: t.TempDir(),+ WorkingDir: t.TempDir(),+ Now: fixedNow,+ })+ if len(result.Configs) == 0 {+ t.Fatal("expected candidate config results")+ }+ for _, config := range result.Configs {+ if config.Exists {+ continue+ }+ if config.ParserStatus != StatusNotFound {+ t.Fatalf("missing config status = %s, want %s", config.ParserStatus, StatusNotFound)+ }+ if config.PathHash == "" {+ t.Fatal("missing config should still include a path hash")+ }+ }+}++func fixedNow() time.Time {+ return time.Date(2026, 6, 5, 7, 0, 0, 0, time.UTC)+}++func writeFile(t *testing.T, path, content string) {+ t.Helper()+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte(content), 0600); err != nil {+ t.Fatal(err)+ }+}++func assertServer(t *testing.T, servers []MCPServer, runtime, name, transport string, commandPresent bool, argsCount, envKeys, envKeyCount int) {+ t.Helper()+ for _, server := range servers {+ if server.Runtime == runtime && server.ServerName == name {+ if server.Transport != transport {+ t.Fatalf("%s/%s transport = %s, want %s", runtime, name, server.Transport, transport)+ }+ if server.CommandPresent != commandPresent {+ t.Fatalf("%s/%s commandPresent = %t, want %t", runtime, name, server.CommandPresent, commandPresent)+ }+ if server.ArgsCount != argsCount {+ t.Fatalf("%s/%s argsCount = %d, want %d", runtime, name, server.ArgsCount, argsCount)+ }+ if len(server.EnvKeys) != envKeys {+ t.Fatalf("%s/%s EnvKeys len = %d, want %d (%#v)", runtime, name, len(server.EnvKeys), envKeys, server.EnvKeys)+ }+ if server.EnvKeyCount != envKeyCount {+ t.Fatalf("%s/%s EnvKeyCount = %d, want %d", runtime, name, server.EnvKeyCount, envKeyCount)+ }+ if server.DefinitionHash == "" || server.ServerNameHash == "" || server.SourcePathHash == "" {+ t.Fatalf("%s/%s missing hashes: %#v", runtime, name, server)+ }+ return+ }+ }+ t.Fatalf("server %s/%s not found in %#v", runtime, name, servers)+}