Skip to content

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

81.9 KB
Raw Blame
package cmd

import (
	"crypto/sha256"
	"encoding/json"
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"regexp"
	"runtime"
	"strconv"
	"strings"
	"time"

	"github.com/spf13/cobra"

	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/atomicfile"
	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/dshsession"
	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/embedded"

	endpointcollector "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/collector"
	endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/diagnostics"
	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/harness"
	endpointhooks "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks"
	endpointintegrations "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/integrations"
	"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/service"
	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/sysacl"
	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs"
	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version"
	"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
)

type doctorResult struct {
	Status      string              `json:"status"`
	Checks      []diagnostics.Check `json:"checks"`
	Fixes       []plannedAction     `json:"fixes,omitempty"`
	Skipped     []plannedAction     `json:"skipped,omitempty"`
	GeneratedAt string              `json:"generated_at"`
}

type inventoryResult struct {
	GeneratedAt       string                        `json:"generated_at"`
	RuntimeLog        lifecycle.RuntimeLogSource    `json:"runtime_log"`
	ConfigPath        string                        `json:"config_path"`
	LogPath           string                        `json:"log_path"`
	Harnesses         []harness.Harness             `json:"harnesses"`
	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"`
	Skills            []endpointinventory.Skill     `json:"skills,omitempty"`
	UserScope         endpointinventory.UserScope   `json:"user_scope"`
}

type hookTargetResult struct {
	Target    string      `json:"target"`
	Status    string      `json:"status"`
	Installed bool        `json:"installed,omitempty"`
	Message   string      `json:"message,omitempty"`
	Path      string      `json:"path,omitempty"`
	Raw       interface{} `json:"raw,omitempty"`
}

type validationStage struct {
	Name     string `json:"name"`
	Target   string `json:"target,omitempty"`
	Status   string `json:"status"`
	Severity string `json:"severity"`
	Message  string `json:"message,omitempty"`
	Evidence string `json:"evidence,omitempty"`
}

type plannedAction struct {
	Action  string `json:"action"`
	Target  string `json:"target,omitempty"`
	Message string `json:"message,omitempty"`
}

type repairServiceManager interface {
	UnitPath() (string, error)
	WriteUnit(program, configPath string) (string, error)
	Load() error
	Unload() error
}

type repairFileSnapshot struct {
	existed bool
	data    []byte
	mode    os.FileMode
	// secret is set for a file carrying sysacl.SecretFileDACL (on Windows, a system file holding a
	// credential), so a rollback restores it SYSTEM/Administrators-only rather than with the tree's
	// DACL that every user can read.
	secret  bool
	readErr error
}

type repairRollback struct {
	manager          repairServiceManager
	serviceWasLoaded bool
	serviceLoaded    bool
	files            []string
	snapshots        map[string]repairFileSnapshot
}

var (
	repairLoadEndpointConfig     = endpointconfig.Load
	repairSaveEndpointConfig     = endpointconfig.Save
	repairResolveCollectorBinary = endpointcollector.ResolveBinary
	repairWriteCollectorConfig   = endpointcollector.WriteConfig
	repairWaitCollectorReady     = endpointcollector.WaitUntilReady
	newRepairServiceManager      = func(userMode bool) repairServiceManager {
		return service.Manager{UserMode: userMode}
	}
)

func runEndpointDoctor(cmd *cobra.Command, args []string) error {
	status := lifecycle.GetStatus(endpointUserMode(), endpointOpts.logPath)
	result := buildDoctorResult(status, time.Now())
	if endpointOpts.fix {
		fixPlan := planDoctorFixes(result, status)
		result.Fixes = fixPlan.Fixes
		result.Skipped = fixPlan.Skipped
		var fixErr error
		if err := applyDoctorFixes(fixPlan, status); err != nil {
			fixErr = err
		}
		status = lifecycle.GetStatus(endpointUserMode(), endpointOpts.logPath)
		result = buildDoctorResult(status, time.Now())
		result.Fixes = fixPlan.Fixes
		result.Skipped = fixPlan.Skipped
		if err := printDoctorResult(result); err != nil {
			return err
		}
		if fixErr != nil {
			return fixErr
		}
	} else {
		if err := printDoctorResult(result); err != nil {
			return err
		}
	}
	if result.Status == diagnostics.StatusFail {
		return fmt.Errorf("endpoint health checks failed")
	}
	return nil
}

func buildDoctorResult(status lifecycle.Status, generatedAt time.Time) doctorResult {
	checks := []diagnostics.Check{
		configValidationCheck(status.RuntimeLog.EffectiveUserMode),
	}
	checks = append(checks, actionableChecks(status.Diagnostics, status.RuntimeLog)...)
	checks = append(checks, collectorCheck(status), serviceCheck(status), lastEventCheck(status))
	if !status.RuntimeLog.EffectiveUserMode {
		checks = append(checks, consoleUserConfigCheck())
	}
	codexDetected := false
	dshDetected := false
	for _, h := range status.Harnesses {
		checks = append(checks, harnessCheck(h, status.LogPath, status.RuntimeLog.EffectiveUserMode))
		if h.Detected && h.Name == "codex_cli" {
			codexDetected = true
		}
		if h.Detected && h.Name == dshsession.Harness {
			dshDetected = true
		}
	}
	if codexDetected {
		checks = append(checks, codexTokenAttributionCheck(status.LogPath, status.RuntimeLog.EffectiveUserMode))
	}
	if dshDetected {
		bridgeUnavailable := false
		if check, ok := doctorDshHookBridgeCheck(); ok {
			checks = append(checks, check)
			bridgeUnavailable = check.Evidence == "dsh_hook_bridge_unavailable"
		}
		// When dsh cannot load the bridge at all, every session runs without hook events and the
		// capture check would blame the sandbox for it. The bridge check has already said why.
		if !bridgeUnavailable {
			if check, ok := doctorDshHookCaptureCheck(status.LogPath); ok {
				checks = append(checks, check)
			}
		}
	}
	if check, ok := gitHookBudgetCheck(status.LogPath, generatedAt); ok {
		checks = append(checks, check)
	}
	var spoolRoots []string
	if cfg, err := endpointconfig.Load(status.RuntimeLog.EffectiveUserMode); err == nil {
		spoolRoots = cfg.WorkspaceSpoolRoots
	}
	if check, ok := doctorWorkspaceSpoolCheck(status.LogPath, spoolRoots); ok {
		checks = append(checks, check)
	}
	result := doctorResult{
		Status:      aggregateCheckStatus(checks),
		Checks:      checks,
		GeneratedAt: generatedAt.UTC().Format(time.RFC3339),
	}
	return result
}

func printDoctorResult(result doctorResult) error {
	if endpointOpts.jsonOutput {
		return json.NewEncoder(os.Stdout).Encode(result)
	}
	fmt.Printf("Beacon endpoint doctor: %s\n", result.Status)
	printDoctorChecks(result.Checks, diagnostics.StatusFail)
	printDoctorChecks(result.Checks, diagnostics.StatusWarn)
	if len(result.Fixes) > 0 {
		fmt.Println("Applied fixes:")
		for _, fix := range result.Fixes {
			printPlannedAction(fix)
		}
	}
	if len(result.Skipped) > 0 {
		fmt.Println("Skipped fixes:")
		for _, skipped := range result.Skipped {
			printPlannedAction(skipped)
		}
	}
	failures, warnings := checkCounts(result.Checks)
	fmt.Printf("Summary: %d failure(s), %d warning(s)\n", failures, warnings)
	if result.Status == diagnostics.StatusOK {
		fmt.Println("All endpoint health checks passed.")
	}
	return nil
}

func printDoctorChecks(checks []diagnostics.Check, status string) {
	for _, check := range checks {
		if check.Status != status {
			continue
		}
		fmt.Printf("%s: %s", check.Name, check.Status)
		if check.Target != "" {
			fmt.Printf(" target=%s", check.Target)
		}
		if check.Message != "" {
			fmt.Printf(" (%s)", check.Message)
		}
		if check.Action != "" {
			fmt.Printf(" action=%q", check.Action)
		}
		fmt.Println()
	}
}

func runEndpointInventory(cmd *cobra.Command, args []string) error {
	status := lifecycle.GetStatus(endpointUserMode(), endpointOpts.logPath)
	effectiveCfg := loadConfigForMode(status.RuntimeLog.EffectiveUserMode, status.LogPath)
	hookTargetNames, err := inventoryHookTargets()
	if err != nil {
		return err
	}
	inventorySettings := endpointconfig.InventoryConfig(effectiveCfg)
	configInventory := endpointinventory.Scan(endpointinventory.Options{
		IncludeContents: endpointOpts.inventoryContents || inventorySettings.IncludeContents,
		MaxContentBytes: inventorySettings.MaxContentBytes,
	})
	result := inventoryResult{
		GeneratedAt:       time.Now().UTC().Format(time.RFC3339),
		RuntimeLog:        status.RuntimeLog,
		ConfigPath:        status.ConfigPath,
		LogPath:           status.LogPath,
		Harnesses:         status.Harnesses,
		Hooks:             hookStatusesWithConfig(hookTargetNames, effectiveCfg),
		Destinations:      status.Destinations,
		LastEventObserved: status.LastEvent != "",
		Configs:           configInventory.Configs,
		MCPServers:        configInventory.MCPServers,
		Skills:            configInventory.Skills,
		UserScope:         configInventory.UserScope,
	}
	if endpointOpts.jsonOutput {
		result = filterInventoryDefaults(result)
		result = filterInventorySections(result)
		if err := json.NewEncoder(os.Stdout).Encode(result); err != nil {
			return err
		}
		if endpointOpts.writeInventoryEvent {
			return writeInventoryEvents(effectiveCfg, configInventory)
		}
		return nil
	}
	showAllInventorySections := !inventorySectionFilterActive()
	if showAllInventorySections {
		fmt.Printf("Config: %s\n", result.ConfigPath)
		fmt.Printf("Runtime log: %s\n", result.LogPath)
		for _, h := range result.Harnesses {
			if !endpointOpts.allTargets && !h.Detected {
				continue
			}
			fmt.Printf("Harness: %s detected=%t telemetry=%s\n", h.DisplayName, h.Detected, h.TelemetryStatus)
		}
	}
	if showAllInventorySections || endpointOpts.inventoryHooks {
		for _, name := range hookTargetNames {
			if hook, ok := result.Hooks[name]; ok {
				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
		}
		if !inventoryConfigIncluded(config) {
			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)
		printInventoryContent(config.Content)
	}
	if showAllInventorySections || endpointOpts.inventoryMCP {
		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", server.Runtime, name, server.SourceScope, server.Transport, server.CommandPresent, server.ArgsCount, server.EnvKeyCount)
			if server.PackageRegistry != "" {
				fmt.Printf(" package_registry=%s", server.PackageRegistry)
			}
			if server.Package != "" {
				fmt.Printf(" package=%s", server.Package)
			}
			fmt.Println()
			printInventoryDefinition(server.Definition)
		}
	}
	if showAllInventorySections || endpointOpts.inventorySkills {
		for _, skill := range result.Skills {
			if !endpointOpts.allTargets && !skill.Exists {
				continue
			}
			name := skill.SkillName
			if name == "" {
				name = skill.SkillNameHash
			}
			path := skill.ManifestPath
			if path == "" {
				path = skill.RootPath
			}
			if path == "" {
				path = skill.ManifestPathHash
			}
			fmt.Printf("Skill: %s %s scope=%s status=%s path=%s", skill.Runtime, name, skill.SourceScope, skill.ParserStatus, path)
			if skill.IntelKey != "" {
				fmt.Printf(" intel_key=%s", skill.IntelKey)
			}
			fmt.Println()
			printInventoryContent(skill.Content)
		}
	}
	if endpointOpts.writeInventoryEvent {
		return writeInventoryEvents(effectiveCfg, configInventory)
	}
	return nil
}

func printInventoryContent(content *endpointinventory.CapturedContent) {
	if content == nil {
		return
	}
	fmt.Printf("  --- content (%d bytes, redactions=%d, truncated=%t) ---\n", content.Bytes, content.RedactedCount, content.Truncated)
	for _, line := range strings.Split(content.Text, "\n") {
		fmt.Printf("  %s\n", line)
	}
	fmt.Println("  --- end content ---")
}

func printInventoryDefinition(def map[string]interface{}) {
	if len(def) == 0 {
		return
	}
	encoded, err := json.MarshalIndent(def, "  ", "  ")
	if err != nil {
		return
	}
	fmt.Printf("  --- definition ---\n  %s\n  --- end definition ---\n", string(encoded))
}

func filterInventoryDefaults(result inventoryResult) inventoryResult {
	if endpointOpts.allTargets {
		return result
	}
	filtered := []harness.Harness{}
	for _, h := range result.Harnesses {
		if h.Detected {
			filtered = append(filtered, h)
		}
	}
	result.Harnesses = filtered

	filteredConfigs := []endpointinventory.Config{}
	existingPaths := map[string]bool{}
	for _, c := range result.Configs {
		if c.Exists {
			filteredConfigs = append(filteredConfigs, c)
			existingPaths[c.PathHash] = true
		}
	}
	result.Configs = filteredConfigs

	filteredServers := []endpointinventory.MCPServer{}
	for _, s := range result.MCPServers {
		if existingPaths[s.SourcePathHash] {
			filteredServers = append(filteredServers, s)
		}
	}
	result.MCPServers = filteredServers

	filteredSkills := []endpointinventory.Skill{}
	for _, s := range result.Skills {
		if s.Exists {
			filteredSkills = append(filteredSkills, s)
		}
	}
	result.Skills = filteredSkills
	return result
}

func inventorySectionFilterActive() bool {
	return endpointOpts.inventoryMCP || endpointOpts.inventorySkills || endpointOpts.inventoryHooks
}

func filterInventorySections(result inventoryResult) inventoryResult {
	if !inventorySectionFilterActive() {
		return result
	}
	result.Harnesses = nil
	if !endpointOpts.inventoryHooks {
		result.Hooks = nil
	}
	if !endpointOpts.inventoryMCP {
		result.MCPServers = nil
	}
	if !endpointOpts.inventorySkills {
		result.Skills = nil
	}
	filteredConfigs := []endpointinventory.Config{}
	for _, config := range result.Configs {
		if inventoryConfigIncluded(config) {
			filteredConfigs = append(filteredConfigs, config)
		}
	}
	result.Configs = filteredConfigs
	return result
}

func inventoryConfigIncluded(config endpointinventory.Config) bool {
	if !inventorySectionFilterActive() {
		return true
	}
	return (endpointOpts.inventoryMCP && config.MCPServerCount > 0) ||
		(endpointOpts.inventoryHooks && config.ConfigKind == endpointinventory.KindHookConfig)
}

func writeInventoryEvents(cfg endpointconfig.Config, result endpointinventory.Result) error {
	settings := endpointconfig.InventoryConfig(cfg)
	result = filterInventoryResult(result, settings.Runtimes)
	_, err := writeInventorySnapshotEvents(cfg, settings, result, "manual", endpointinventory.SnapshotDigest(result), "", true)
	return err
}

type inventoryHeartbeatWriteResult struct {
	Written         bool   `json:"written"`
	SnapshotWritten bool   `json:"snapshot_written"`
	SkippedReason   string `json:"skipped_reason,omitempty"`
	SnapshotDigest  string `json:"snapshot_digest,omitempty"`
	PreviousDigest  string `json:"previous_snapshot_digest,omitempty"`
}

// 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)
	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 || !isInventoriableUser(info) {
		return heartbeatScope{NoConsoleUser: true}
	}
	return heartbeatScope{HomeDir: info.HomeDir}
}

// isInventoriableUser rejects the accounts that can own /dev/console without being a person:
// macOS service accounts (underscore-prefixed, home /var/empty) hold it at the login window and
// during setup, and root holds it on a headless box. Inventorying their homes yields an empty
// snapshot that then flips the digest back and forth with the real user's.
func isInventoriableUser(info consoleUserInfo) bool {
	home := strings.TrimSpace(info.HomeDir)
	name := strings.TrimSpace(info.Username)
	if home == "" || name == "root" || name == "loginwindow" || strings.HasPrefix(name, "_") {
		return false
	}
	switch home {
	case "/", "/var/empty", "/var/root", "/nonexistent":
		return false
	}
	return true
}

func loadInventoryHeartbeatConfig(userMode bool, logPath, configPath string) (endpointconfig.Config, error) {
	if configPath == "" {
		return loadConfigForMode(userMode, logPath), nil
	}
	data, err := os.ReadFile(configPath)
	if err != nil {
		return endpointconfig.Config{}, err
	}
	var cfg endpointconfig.Config
	if err := json.Unmarshal(data, &cfg); err != nil {
		return endpointconfig.Config{}, err
	}
	endpointconfig.NormalizeDestinations(&cfg)
	if err := endpointconfig.ValidateDestinations(cfg.Destinations); err != nil {
		return endpointconfig.Config{}, err
	}
	if logPath != "" {
		cfg.LogPath = logPath
	}
	if cfg.LogPath == "" {
		cfg.LogPath = writer.DefaultPath(cfg.UserMode)
	}
	return cfg, nil
}

// 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
	}
	now := time.Now().UTC()
	statePath := endpointinventory.StatePathForLog(cfg.LogPath, cfg.UserMode)
	locked, state, err := endpointinventory.LockState(statePath)
	if err != nil {
		return inventoryHeartbeatWriteResult{}, err
	}
	defer locked.Close()

	var inventoryResult endpointinventory.Result
	digest := state.LastSnapshotDigest
	previous := state.LastSnapshotDigest
	writeSnapshot := false
	next := state
	release := func() {}
	var resolvePackages packageResolver
	if !scope.NoConsoleUser {
		confined, resolver, err := confineInventoryScan(scope.HomeDir)
		if err != nil {
			// Never scan a home root does not own without the confinement; the liveness heartbeat
			// still goes out.
			fmt.Fprintf(os.Stderr, "warning: inventory scan skipped: %v\n", err)
			scope = heartbeatScope{NoConsoleUser: true}
		} else {
			release, resolvePackages = confined, resolver
		}
	}
	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,
			ResolvePackages:  resolvePackages,
		})
		release()
		digest = endpointinventory.SnapshotDigest(inventoryResult)
		// Compare against the last digest for *this* home: a multi-user machine alternates
		// console users, and a switch is not a change in anyone's inventory.
		previous = state.DigestFor(inventoryResult.UserScope.HomeHash)
		writeSnapshot = previous != digest
		next = state.WithDigest(inventoryResult.UserScope.HomeHash, digest)
	}
	writeResult, err := writeInventorySnapshotEvents(cfg, settings, inventoryResult, trigger, digest, previous, writeSnapshot)
	if err != nil {
		return writeResult, err
	}
	next.LastEmittedAt = now.Format(time.RFC3339)
	if err := locked.Save(next); err != nil {
		return inventoryHeartbeatWriteResult{SnapshotDigest: digest, PreviousDigest: previous}, err
	}
	return writeResult, nil
}

func writeInventorySnapshotEvents(cfg endpointconfig.Config, settings endpointconfig.InventorySettings, result endpointinventory.Result, trigger, digest, previousDigest string, writeSnapshot bool) (inventoryHeartbeatWriteResult, error) {
	counts := endpointinventory.CountsFor(result)
	inventoryMeta := map[string]interface{}{
		"generated_at":             result.GeneratedAt,
		"runtimes":                 settings.Runtimes,
		"trigger":                  trigger,
		"snapshot_digest":          digest,
		"previous_snapshot_digest": previousDigest,
		"counts":                   counts,
		// Metadata only (mode and hashes). It is what distinguishes a liveness heartbeat written
		// with nobody at the console from one for an unchanged inventory.
		"user_scope": result.UserScope,
	}
	if edition := version.ReportedEdition(); edition != "" {
		inventoryMeta["edition"] = edition
	}
	if previousDigest == "" {
		inventoryMeta["change_reason"] = "initial"
	} else if previousDigest != digest {
		inventoryMeta["change_reason"] = "changed"
	} else {
		inventoryMeta["change_reason"] = "unchanged"
	}
	heartbeat := schema.NewEvent(schema.NewEventOptions{
		Action:       "inventory.heartbeat",
		Category:     "inventory",
		Severity:     schema.SeverityInfo,
		AgentVersion: version.GetVersion(),
		Harness:      schema.HarnessInfo{Name: "endpoint"},
		Message:      "Agent configuration inventory heartbeat observed",
	})
	heartbeat.Raw = map[string]interface{}{"inventory": inventoryMeta}
	inventoryLogPath := endpointinventory.LogPath(cfg.LogPath, cfg.UserMode)
	if _, err := writer.AppendEvent(heartbeat, writer.Options{Path: inventoryLogPath, UserMode: cfg.UserMode}); err != nil {
		return inventoryHeartbeatWriteResult{SnapshotDigest: digest, PreviousDigest: previousDigest}, err
	}
	out := inventoryHeartbeatWriteResult{Written: true, SnapshotDigest: digest, PreviousDigest: previousDigest}
	if !writeSnapshot {
		return out, nil
	}
	snapshot := schema.NewEvent(schema.NewEventOptions{
		Action:       "inventory.snapshot",
		Category:     "inventory",
		Severity:     schema.SeverityInfo,
		AgentVersion: version.GetVersion(),
		Harness:      schema.HarnessInfo{Name: "endpoint"},
		Message:      "Agent configuration inventory snapshot observed",
	})
	// The scanner has already redacted what it captures and cut file contents to max_content_bytes;
	// an MCP server definition, whose keys come from the user's config, had the field-name and flag
	// rules applied (inventory.redactStructured). CleanValue redacts every string in them again and
	// leaves our own field names such as env_keys, a list of variable names, as they are. Its limit
	// is max_content_bytes, so captured contents are not cut again, but never below the raw-field
	// limit the event writer applies to other raw strings, so a small max_content_bytes does not cut
	// paths, names and hashes.
	contentLimit := max(endpointinventory.ContentLimit(settings.MaxContentBytes), asymptoteobserve.DefaultRawStringLimit)
	snapshot.Raw = map[string]interface{}{
		"inventory": map[string]interface{}{
			"generated_at":             result.GeneratedAt,
			"runtimes":                 settings.Runtimes,
			"trigger":                  trigger,
			"snapshot_digest":          digest,
			"previous_snapshot_digest": previousDigest,
			"counts":                   counts,
			"user_scope":               result.UserScope,
			"configs":                  asymptoteobserve.CleanValue(existingInventoryConfigs(result.Configs), contentLimit),
			"mcp_servers":              asymptoteobserve.CleanValue(result.MCPServers, contentLimit),
			"skills":                   asymptoteobserve.CleanValue(existingInventorySkills(result.Skills), contentLimit),
		},
	}
	if _, err := writer.AppendEvent(snapshot, writer.Options{Path: inventoryLogPath, UserMode: cfg.UserMode}); err != nil {
		return out, err
	}
	out.SnapshotWritten = true
	return out, nil
}

func existingInventoryConfigs(configs []endpointinventory.Config) []endpointinventory.Config {
	out := make([]endpointinventory.Config, 0, len(configs))
	for _, config := range configs {
		if config.Exists {
			out = append(out, config)
		}
	}
	return out
}

func existingInventorySkills(skills []endpointinventory.Skill) []endpointinventory.Skill {
	out := make([]endpointinventory.Skill, 0, len(skills))
	for _, skill := range skills {
		if skill.Exists {
			out = append(out, skill)
		}
	}
	return out
}

func filterInventoryResult(result endpointinventory.Result, runtimes []string) endpointinventory.Result {
	allowed := map[string]bool{}
	for _, runtime := range runtimes {
		runtime = strings.TrimSpace(runtime)
		if runtime != "" {
			allowed[runtime] = true
		}
	}
	if len(allowed) == 0 {
		return result
	}
	configs := make([]endpointinventory.Config, 0, len(result.Configs))
	for _, config := range result.Configs {
		if allowed[config.Runtime] {
			configs = append(configs, config)
		}
	}
	servers := make([]endpointinventory.MCPServer, 0, len(result.MCPServers))
	for _, server := range result.MCPServers {
		if allowed[server.Runtime] {
			servers = append(servers, server)
		}
	}
	skills := make([]endpointinventory.Skill, 0, len(result.Skills))
	for _, skill := range result.Skills {
		if allowed[skill.Runtime] {
			skills = append(skills, skill)
		}
	}
	result.Configs = configs
	result.MCPServers = servers
	result.Skills = skills
	return result
}

func runEndpointTestEvent(cmd *cobra.Command, args []string) error {
	cfg := loadOrDefaultConfig()
	writableStage := stageFromCheck(checkLogWritable(cfg))
	stages := []validationStage{writableStage}
	if writableStage.Status != "ok" {
		if endpointOpts.jsonOutput {
			_ = json.NewEncoder(os.Stdout).Encode(stages)
		} else {
			fmt.Printf("%s: %s", writableStage.Name, writableStage.Status)
			if writableStage.Target != "" {
				fmt.Printf(" target=%s", writableStage.Target)
			}
			if writableStage.Message != "" {
				fmt.Printf(" (%s)", writableStage.Message)
			}
			fmt.Println()
		}
		return fmt.Errorf("runtime log is not writable: %s", writableStage.Evidence)
	}
	path, err := writeValidationEvent(cfg, "pipeline")
	if err != nil {
		stages = append(stages, validationStage{Name: "write_test_event", Target: cfg.LogPath, Status: "fail", Severity: "high", Message: err.Error(), Evidence: "append_failed"})
		if endpointOpts.jsonOutput {
			_ = json.NewEncoder(os.Stdout).Encode(stages)
		}
		return err
	}
	stages = append(stages, validationStage{Name: "write_test_event", Target: path, Status: "ok", Severity: "info", Message: "synthetic validation event written", Evidence: "append_succeeded"})
	if endpointOpts.jsonOutput {
		return json.NewEncoder(os.Stdout).Encode(stages)
	}
	for _, stage := range stages {
		fmt.Printf("%s: %s", stage.Name, stage.Status)
		if stage.Target != "" {
			fmt.Printf(" target=%s", stage.Target)
		}
		if stage.Message != "" {
			fmt.Printf(" (%s)", stage.Message)
		}
		fmt.Println()
	}
	return nil
}

func runEndpointBundleDiagnostics(cmd *cobra.Command, args []string) error {
	cfg := loadOrDefaultConfig()
	out := endpointOpts.outputDir
	if out == "" {
		out = filepath.Join(endpointconfig.BaseDir(endpointUserMode()), "diagnostics-"+time.Now().UTC().Format("20060102T150405Z"))
	}
	if err := os.MkdirAll(out, 0755); err != nil {
		return err
	}
	status := lifecycle.GetStatus(endpointUserMode(), endpointOpts.logPath)
	status.LastEvent = redactLastEvent(status.LastEvent)
	if err := writeJSONFile(filepath.Join(out, "status.json"), status); err != nil {
		return err
	}
	if err := writeJSONFile(filepath.Join(out, "config.redacted.json"), redactConfig(cfg)); err != nil {
		return err
	}
	if endpointOpts.includeEventSummaries || endpointOpts.includeRawEvents {
		if err := writeEventBundleFiles(out, cfg.LogPath, endpointOpts.includeRawEvents); err != nil {
			return err
		}
	}
	fmt.Printf("Diagnostics bundle written to %s\n", out)
	if !endpointOpts.includeRawEvents {
		fmt.Println("Raw runtime events were not included.")
	}
	return nil
}

func runEndpointConfigShow(cmd *cobra.Command, args []string) error {
	return json.NewEncoder(os.Stdout).Encode(redactConfig(loadOrDefaultConfig()))
}

func runEndpointConfigValidate(cmd *cobra.Command, args []string) error {
	cfg := loadOrDefaultConfig()
	if err := endpointconfig.ValidateDestinations(cfg.Destinations); err != nil {
		return err
	}
	fmt.Printf("Endpoint config is valid: %s\n", endpointconfig.ConfigPath(cfg.UserMode))
	return nil
}

func runEndpointIntegrationsValidate(cmd *cobra.Command, args []string) error {
	targets := []string{"claude-cowork", "openclaw"}
	if !endpointOpts.allTargets {
		return fmt.Errorf("specify --all to validate all admin integrations, or use a specific integration validate command")
	}
	cfg := loadOrDefaultConfig()
	results := map[string]validationStage{}
	broken := []string{}
	for _, target := range targets {
		switch target {
		case "claude-cowork":
			status := cowork.GetStatus(cfg.LogPath)
			stage := validationStage{Name: "integration_validate", Target: target, Status: "broken", Severity: "medium", Message: status.Message, Evidence: "not_observed"}
			if status.LastEventObserved {
				stage.Status = "configured"
				stage.Severity = "info"
				stage.Evidence = "last_event_observed"
			}
			if stage.Status == "broken" {
				broken = append(broken, target)
			}
			results[target] = stage
		case "openclaw":
			status := openclaw.GetStatus(cfg.LogPath)
			stage := validationStage{Name: "integration_validate", Target: target, Status: "broken", Severity: "medium", Message: status.Message, Evidence: "not_observed"}
			if status.LastEventObserved {
				stage.Status = "configured"
				stage.Severity = "info"
				stage.Evidence = "last_event_observed"
			}
			if stage.Status == "broken" {
				broken = append(broken, target)
			}
			results[target] = stage
		}
	}
	if endpointOpts.jsonOutput {
		if err := json.NewEncoder(os.Stdout).Encode(results); err != nil {
			return err
		}
		if len(broken) > 0 {
			return fmt.Errorf("integration validation failed for %s", strings.Join(broken, ", "))
		}
		return nil
	}
	for _, target := range targets {
		stage := results[target]
		fmt.Printf("%s: %s", target, stage.Status)
		if stage.Message != "" {
			fmt.Printf(" (%s)", stage.Message)
		}
		fmt.Println()
	}
	if len(broken) > 0 {
		return fmt.Errorf("integration validation failed for %s", strings.Join(broken, ", "))
	}
	return nil
}

func plannedInstallActions(repair bool, kind service.Kind, otlpTargets, hookTargets []string) []plannedAction {
	cfg := endpointconfig.Default(endpointUserMode(), endpointOpts.logPath)
	if endpointOpts.logPath != "" {
		cfg.LogPath = endpointOpts.logPath
	}
	actions := []plannedAction{}
	if repair {
		actions = append(actions, plannedAction{Action: "unload_service", Message: "repair unloads existing endpoint service if present"})
	}

	// The plan has to reflect the service manager that will actually be used. It previously
	// announced a launchd plist on every platform without consulting GOOS, so a Linux
	// --dry-run advertised steps that could not execute.
	mgr := service.Manager{UserMode: cfg.UserMode, Kind: kind}
	serviceAction := plannedAction{Action: "write_unit", Message: mgr.ResolvedKind().ServiceNoun()}
	if unitPath, err := mgr.UnitPath(); err == nil {
		serviceAction.Target = unitPath
	}
	inventoryAction, inventoryScheduled := plannedScheduledJob(service.InventoryManager{UserMode: cfg.UserMode, Kind: kind}, "scheduled inventory heartbeat job")
	actions = append(actions,
		plannedAction{Action: "write_file", Target: cfg.Collector.ConfigPath, Message: "collector configuration"},
		serviceAction,
		plannedAction{Action: "write_file", Target: endpointconfig.ConfigPath(cfg.UserMode), Message: "endpoint configuration"},
		inventoryAction,
	)
	// The session sync job follows --session-sync/--no-session-sync, or else the setting the
	// endpoint already records, as buildConfig resolves it.
	sessionSync, sessionSyncChosen := false, false
	if existing, err := endpointconfig.Load(cfg.UserMode); err == nil {
		sessionSync = endpointconfig.SessionSyncEnabled(existing)
	}
	if on, _ := sessionSyncOption(); on != nil {
		sessionSync, sessionSyncChosen = *on, true
	}
	sessionSyncScheduled := false
	switch {
	case sessionSync:
		var sessionSyncAction plannedAction
		sessionSyncAction, sessionSyncScheduled = plannedScheduledJob(service.SessionSyncManager{UserMode: cfg.UserMode, Kind: kind}, "scheduled session sync job")
		actions = append(actions, sessionSyncAction)
	case sessionSyncChosen:
		actions = append(actions, plannedAction{Action: "unload_service", Message: "remove scheduled session sync job if present"})
	}
	for _, h := range otlpTargets {
		actions = append(actions, plannedAction{Action: "configure_harness", Target: h})
	}
	for _, h := range hookTargets {
		actions = append(actions, plannedAction{Action: "configure_harness", Target: h, Message: "install endpoint hook integration"})
	}
	if !endpointOpts.noStart {
		actions = append(actions, plannedAction{Action: "load_service", Message: "start endpoint collector service"})
		if inventoryScheduled {
			actions = append(actions, plannedAction{Action: "load_service", Message: "start scheduled inventory heartbeat job"})
		}
		if sessionSyncScheduled {
			actions = append(actions, plannedAction{Action: "load_service", Message: "start scheduled session sync job"})
		}
	}
	return actions
}

// plannedScheduledJob is the plan's line for one scheduled job, and whether the install will start
// it. An install skips a job on a host with no scheduler for it (Windows, or a supervised collector
// in a container or under WSL) and says why, so the plan says the same. It used to name a launchd
// plist under ~/Library/LaunchAgents there, and a step that started the job, neither of which the
// install does.
func plannedScheduledJob(job service.ScheduledJob, name string) (plannedAction, bool) {
	if !job.Supported() {
		return plannedAction{Action: "skip_unit", Message: name + " not installed: " + job.UnsupportedReason()}, false
	}
	action := plannedAction{Action: "write_unit", Message: name}
	if unitPath, err := job.UnitPath(); err == nil {
		action.Target = unitPath
	}
	return action, true
}

func plannedUninstallActions() []plannedAction {
	cfg := loadOrDefaultConfig()
	actions := []plannedAction{
		{Action: "unload_service", Message: "stop endpoint collector service if present"},
		{Action: "unload_service", Message: "remove scheduled inventory heartbeat job if present"},
		{Action: "unload_service", Message: "remove scheduled session sync job if present"},
	}
	if !cfg.UserMode && runtime.GOOS == "darwin" {
		actions = append(actions, plannedAction{Action: "unload_service", Message: "stop and remove the S3, GCS and Falcon forwarders if present"})
		if !endpointOpts.keepConfig {
			actions = append(actions, plannedAction{Action: "remove_file", Target: service.ScriptForwarderConfigDir(), Message: "forwarder config and credentials"})
		}
	}
	if !endpointOpts.keepConfig {
		actions = append(actions, plannedAction{Action: "restore_backup", Message: "restore backed up harness configs when available"})
	}
	actions = append(actions, plannedAction{Action: "remove_file", Target: endpointconfig.ConfigPath(cfg.UserMode), Message: "endpoint config"})
	if !endpointOpts.keepLogs {
		actions = append(actions, plannedAction{Action: "remove_file", Target: cfg.LogPath, Message: "runtime log"})
	}
	return actions
}

func printPlannedActions(actions []plannedAction) error {
	if endpointOpts.jsonOutput {
		return json.NewEncoder(os.Stdout).Encode(actions)
	}
	for _, action := range actions {
		printPlannedAction(action)
	}
	return nil
}

func printPlannedAction(action plannedAction) {
	fmt.Printf("%s", action.Action)
	if action.Target != "" {
		fmt.Printf(" %s", action.Target)
	}
	if action.Message != "" {
		fmt.Printf(" (%s)", action.Message)
	}
	fmt.Println()
}

func inventoryHookTargets() ([]string, error) {
	if endpointOpts.inventoryHooks && !endpointOpts.allTargets && strings.TrimSpace(endpointOpts.hookHarnesses) == "" {
		return allHookTargetsForLevel(), nil
	}
	return hookTargets()
}

func hookTargets() ([]string, error) {
	if endpointOpts.allTargets {
		return allHookTargetsForLevel(), nil
	}
	return canonicalHookTargets(splitCSV(endpointOpts.hookHarnesses))
}

// userScopeOnlyHookTargets are the targets whose installers refuse LevelProject outright, because
// the runtime registers hooks only from a user-level config: Hermes has no project config at all,
// Muse's project .muse/hooks.json is ignored by the shipping build, and DeepSeek Harness composes
// its plugin tree from the Harness home, so there is nowhere in a repository to mount a hook
// bridge from.
//
// They are filtered out of the project-level --all list rather than left in to fail. Install and
// uninstall both return on the first target error, so one refusing target does not just report
// itself -- it aborts the sweep and silently skips every target after it in the list.
var userScopeOnlyHookTargets = map[string]bool{
	"hermes": true,
	"muse":   true,
	"dsh":    true,
	// Kimi Code reads one user-level config.toml and has no project-level config mechanism at
	// all: its project-local .kimi-code directory holds a workspace override and an MCP server
	// list, neither of which can register a hook.
	"kimi": true,
}

func allHookTargetsForLevel() []string {
	all := []string{"cursor", "codex", "vscode", "factory", "opencode", "openhands", "kiro", "kimi", "dsh", "cline", "pi", "omp", "prime", "omo", "openclaw", "grok", "qwen", "muse", "hermes", "devin-cli", "devin-desktop", "antigravity"}
	if endpointOpts.hookLevel != "project" {
		return all
	}
	filtered := all[:0:0]
	for _, t := range all {
		if userScopeOnlyHookTargets[t] {
			continue
		}
		filtered = append(filtered, t)
	}
	return filtered
}

func hookStatuses(targets []string) map[string]hookTargetResult {
	cfg := loadOrDefaultConfig()
	return hookStatusesWithConfig(targets, cfg)
}

func hookStatusesWithConfig(targets []string, cfg endpointconfig.Config) map[string]hookTargetResult {
	statuses := map[string]hookTargetResult{}
	canonical, err := canonicalHookTargets(targets)
	if err != nil {
		return statuses
	}
	for _, name := range canonical {
		switch strings.TrimSpace(name) {
		case "antigravity":
			status := endpointhooks.AntigravityHookStatus(endpointhooks.AntigravityOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			result := hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.ConfigPath, Raw: status}
			// Installed stays true for a legacy block so repair rewrites it, but Antigravity does
			// not run it, so it must not read as configured.
			if status.NeedsReinstall {
				result.Status = "needs_reinstall"
			}
			statuses[name] = result
		case "cursor":
			status := endpointhooks.CursorHookStatus(endpointhooks.CursorOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.HooksJSONPath, Raw: status}
		case "claude":
			status := endpointhooks.ClaudeHookStatus(endpointhooks.ClaudeOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.SettingsPath, Raw: status}
		case "codex":
			status := endpointhooks.CodexHookStatus(endpointhooks.CodexOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.HooksPath, Raw: status}
		case "vscode":
			status := endpointhooks.VSCodeHookStatus(endpointhooks.VSCodeOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.HooksPath, Raw: status}
		case "factory":
			status := endpointhooks.FactoryHookStatus(endpointhooks.FactoryOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.SettingsPath, Raw: status}
		case "opencode":
			status := endpointhooks.OpenCodeHookStatus(endpointhooks.OpenCodeOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.PluginPath, Raw: status}
		case "cline":
			status := endpointhooks.ClineHookStatus(endpointhooks.ClineOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.PluginPath, Raw: status}
		case "pi":
			status := endpointhooks.PiHookStatus(endpointhooks.PiOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.ExtensionPath, Raw: status}
		case "omp":
			status := endpointhooks.OmpHookStatus(endpointhooks.OmpOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.ExtensionPath, Raw: status}
		case "prime":
			status := endpointhooks.PrimeHookStatus(endpointhooks.PrimeOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.ExtensionPath, Raw: status}
		case "omo":
			status := endpointhooks.OmoHookStatus(endpointhooks.OmoOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.ExtensionPath, Raw: status}
		case "openclaw":
			status := endpointhooks.OpenClawHookStatus(endpointhooks.OpenClawOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.PluginPath, Raw: status}
		case "grok":
			status := endpointhooks.GrokHookStatus(endpointhooks.GrokOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.HooksPath, Raw: status}
		case "openhands":
			status := endpointhooks.OpenHandsHookStatus(endpointhooks.OpenHandsOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.HooksPath, Raw: status}
		case "dsh":
			status := endpointhooks.DshHookStatus(endpointhooks.DshOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			// Path is the hooks file, which is the one a person would open. The patch file that
			// mounts the bridge at it rides along in Raw, where the JSON output keeps it -- this
			// struct carries one path and the install has two.
			statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.HooksPath, Raw: status}
		case "kimi":
			status := endpointhooks.KimiHookStatus(endpointhooks.KimiOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.HooksPath, Raw: status}
		case "kiro":
			status := endpointhooks.KiroHookStatus(endpointhooks.KiroOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.HooksPath, Raw: status}
		case "muse":
			status := endpointhooks.MuseHookStatus(endpointhooks.MuseOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.HooksPath, Raw: status}
		case "qwen":
			status := endpointhooks.QwenHookStatus(endpointhooks.QwenOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.SettingsPath, Raw: status}
		case "hermes":
			status := endpointhooks.HermesHookStatus(endpointhooks.HermesOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses[name] = hookTargetResult{Target: name, Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.ConfigPath, Raw: status}
		case "devin-cli":
			status := endpointhooks.DevinHookStatus(endpointhooks.DevinOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses["devin-cli"] = hookTargetResult{Target: "devin-cli", Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.ConfigPath, Raw: status}
		case "devin-desktop":
			status := endpointhooks.DevinDesktopHookStatus(endpointhooks.DevinDesktopOptions{Level: endpointhooks.Level(endpointOpts.hookLevel), LogPath: cfg.LogPath, UserMode: cfg.UserMode})
			statuses["devin-desktop"] = hookTargetResult{Target: "devin-desktop", Status: targetStatus(status.Installed), Installed: status.Installed, Message: status.Message, Path: status.ConfigPath, Raw: status}
		}
	}
	return statuses
}

func targetStatus(installed bool) string {
	if installed {
		return "configured"
	}
	return "not_installed"
}

func configValidationCheck(userMode bool) diagnostics.Check {
	path := endpointconfig.ConfigPath(userMode)
	if _, err := endpointconfig.Load(userMode); err != nil {
		action := doctorInstallCommand(userMode)
		if !os.IsNotExist(err) {
			action = "fix the endpoint config JSON or run " + doctorRepairCommand(userMode)
		}
		return diagnostics.Check{
			Name:     "config_valid",
			Target:   path,
			Status:   diagnostics.StatusFail,
			Severity: diagnostics.SeverityHigh,
			Message:  err.Error(),
			Evidence: "config_load_failed",
			Action:   action,
		}
	}
	return diagnostics.Check{
		Name:     "config_valid",
		Target:   path,
		Status:   diagnostics.StatusOK,
		Severity: diagnostics.SeverityInfo,
		Message:  "endpoint config is valid",
		Evidence: "config_load_succeeded",
	}
}

func actionableChecks(checks []diagnostics.Check, runtimeLog lifecycle.RuntimeLogSource) []diagnostics.Check {
	out := make([]diagnostics.Check, 0, len(checks))
	for _, check := range checks {
		if check.Action == "" {
			check.Action = actionForCheck(check, runtimeLog)
		}
		out = append(out, check)
	}
	return out
}

func actionForCheck(check diagnostics.Check, runtimeLog lifecycle.RuntimeLogSource) string {
	switch check.Name {
	case "config", "collector_config", "launchd_plist", "collector_health":
		return doctorRepairCommand(runtimeLog.EffectiveUserMode)
	case "runtime_log":
		return "beacon endpoint doctor --fix"
	case "runtime_log_permissions":
		// Branch on evidence rather than falling through to chmod. Windows reaches this check too
		// now, and chmod neither exists there nor would restore an ACL if it did -- so the single
		// most consequential remediation string on that platform, the one printed for a system-mode
		// log that hooks cannot write, was advice that could not work.
		switch check.Evidence {
		case "runtime_log_missing", "missing_optional_file":
			return "beacon endpoint doctor --fix"
		case "acl_missing_interactive_write", "acl_too_broad":
			// Printed rather than only offered through --fix: this one needs an elevated shell, and
			// an operator who cannot elevate right now still deserves to know the exact command.
			if hint := writer.GrantCommandHint(check.Target); hint != "" {
				return hint
			}
			return "beacon endpoint doctor --fix"
		case "acl_not_writable_by_user":
			return "grant your account write access to " + check.Target
		case "acl_unreadable":
			return "inspect the access control list on " + check.Target
		}
		if runtimeLog.EffectiveUserMode {
			// A user-mode log is written only by processes running as its owner, so owner
			// read/write is the whole fix. Advising 666 here would hand the user's prompts and
			// command output to every local account.
			return "chmod 600 " + check.Target
		}
		return "chmod 666 " + check.Target
	case "runtime_log_source":
		if runtimeLog.RequestedUserMode && !runtimeLog.EffectiveUserMode {
			return "stop the system collector or run beacon endpoint install --user"
		}
		return "review the requested and effective runtime log paths"
	}
	return ""
}

func aggregateCheckStatus(checks []diagnostics.Check) string {
	out := diagnostics.StatusOK
	for _, check := range checks {
		if check.Status == diagnostics.StatusFail {
			return diagnostics.StatusFail
		}
		if check.Status == diagnostics.StatusWarn {
			out = diagnostics.StatusWarn
		}
	}
	return out
}

func collectorCheck(status lifecycle.Status) diagnostics.Check {
	if status.Collector.BinaryPath == "" {
		return diagnostics.Check{Name: "collector_reachability", Target: status.ConfigPath, Status: diagnostics.StatusFail, Severity: diagnostics.SeverityHigh, Message: status.Collector.Message, Evidence: "collector_binary_missing", Action: doctorRepairCommand(status.RuntimeLog.EffectiveUserMode)}
	}
	if status.Collector.GRPCReady && status.Collector.HTTPReady {
		return diagnostics.Check{Name: "collector_reachability", Target: status.ConfigPath, Status: diagnostics.StatusOK, Severity: diagnostics.SeverityInfo, Message: status.Collector.Message, Evidence: "collector_ready"}
	}
	if status.Collector.GRPCReady || status.Collector.HTTPReady {
		return diagnostics.Check{Name: "collector_reachability", Target: status.ConfigPath, Status: diagnostics.StatusWarn, Severity: diagnostics.SeverityMedium, Message: "only one OTLP receiver is listening", Evidence: "collector_partially_ready", Action: doctorRepairCommand(status.RuntimeLog.EffectiveUserMode)}
	}
	return diagnostics.Check{Name: "collector_reachability", Target: status.ConfigPath, Status: diagnostics.StatusFail, Severity: diagnostics.SeverityHigh, Message: status.Collector.Message, Evidence: "collector_not_ready", Action: doctorRepairCommand(status.RuntimeLog.EffectiveUserMode)}
}

func serviceCheck(status lifecycle.Status) diagnostics.Check {
	if status.Service.Running {
		return diagnostics.Check{Name: "service", Status: diagnostics.StatusOK, Severity: diagnostics.SeverityInfo, Message: status.Service.Message, Evidence: "service_running"}
	}
	if status.Service.Loaded {
		return diagnostics.Check{Name: "service", Status: diagnostics.StatusWarn, Severity: diagnostics.SeverityMedium, Message: status.Service.Message, Evidence: "service_loaded_not_running", Action: doctorRepairCommand(status.RuntimeLog.EffectiveUserMode)}
	}
	return diagnostics.Check{Name: "service", Status: diagnostics.StatusWarn, Severity: diagnostics.SeverityMedium, Message: status.Service.Message, Evidence: "service_not_loaded", Action: doctorRepairCommand(status.RuntimeLog.EffectiveUserMode)}
}

func lastEventCheck(status lifecycle.Status) diagnostics.Check {
	if status.LastEvent != "" {
		return diagnostics.Check{Name: "last_event", Target: status.LogPath, Status: diagnostics.StatusOK, Severity: diagnostics.SeverityInfo, Message: "runtime log has events", Evidence: "last_event_present"}
	}
	return diagnostics.Check{Name: "last_event", Target: status.LogPath, Status: diagnostics.StatusWarn, Severity: diagnostics.SeverityLow, Message: "runtime log has no events yet", Evidence: "last_event_missing", Action: "beacon endpoint test-event"}
}

// consoleUserConfigCheck asks the one question a system-mode doctor never asked: is there a human
// whose agent runtime actually points at this collector?
//
// Every other check runs as root and resolves $HOME to /root, so it inspects the settings that
// `endpoint install --system` wrote for root -- which are always correct, because the install just
// wrote them. A system endpoint exists to capture the *operator's* sessions, and when the operator
// could not be resolved the install skipped them, said so only under --json, and doctor reported a
// green harness for root. The whole chain looked healthy while collecting nothing.
//
// That is not hypothetical: on a fleet whose accounts come from a directory service, it was the
// steady state for every machine, and the only visible symptom was the harness_observed warning
// that the documentation tells people to ignore on a fresh install.
//
// System mode only. In user mode the person running the command is the person being configured,
// so the question answers itself.
func consoleUserConfigCheck() diagnostics.Check {
	const name = "console_user_configured"
	info, ok, err := activeConsoleUser()
	if err != nil || !ok {
		return diagnostics.Check{
			Name:     name,
			Status:   diagnostics.StatusWarn,
			Severity: diagnostics.SeverityMedium,
			Message: "no logged-in user could be identified, so this endpoint may be collecting " +
				"for nobody; the collector is healthy either way",
			Evidence: "no_console_user",
			Action:   "run 'beacon endpoint user-config repair-installed --system' as the user whose sessions should be captured",
		}
	}
	configured, detail := consoleUserHarnessConfigured(info, loadConfigForMode(false, endpointOpts.logPath))
	if !configured {
		return diagnostics.Check{
			Name:     name,
			Target:   info.Username,
			Status:   diagnostics.StatusFail,
			Severity: diagnostics.SeverityHigh,
			Message: fmt.Sprintf("%s has no agent runtime pointed at this collector, so their "+
				"sessions are not being captured (%s)", info.Username, detail),
			Evidence: "console_user_not_configured",
			Action:   "sudo beacon endpoint user-config repair-installed --system",
		}
	}
	return diagnostics.Check{
		Name:     name,
		Target:   info.Username,
		Status:   diagnostics.StatusOK,
		Severity: diagnostics.SeverityInfo,
		Message:  fmt.Sprintf("%s's agent runtime is configured", info.Username),
		Evidence: "console_user_configured",
	}
}

// consoleUserHarnessConfigured reports whether the console user has at least one runtime pointed
// at the local collector.
//
// At least one rather than all of them: a developer who uses only Claude Code is fully configured,
// and demanding every detected runtime would produce a failure nobody should act on.
//
// The markers come from the endpoint's own configuration rather than from constants. An install
// with --otlp-grpc-port writes that port into the user's settings, and a check that only knew the
// defaults would call a correctly configured user unconfigured -- a false failure in the one check
// whose entire value is being trusted when it says something is wrong.
func consoleUserHarnessConfigured(info consoleUserInfo, cfg endpointconfig.Config) (bool, string) {
	paths, err := consoleUserConfigPaths(info)
	if err != nil {
		return false, err.Error()
	}
	if len(paths) == 0 {
		return false, "no agent runtime configuration found in " + info.HomeDir
	}
	grpc, http := collectorPorts(cfg)
	for _, p := range paths {
		data, err := os.ReadFile(p)
		if err != nil {
			continue
		}
		// Matching on the collector address, or on the hook binary for hook-only runtimes, rather
		// than on the file existing: that is the difference between "configured for this endpoint"
		// and "the user happens to have used this agent before".
		text := string(data)
		if strings.Contains(text, embedded.BinaryStem) {
			return true, p
		}
		if targetsCollectorPort(text, grpc, http) {
			return true, p
		}
	}
	return false, "found " + strconv.Itoa(len(paths)) + " runtime config file(s), none pointed at this collector"
}

// loopbackEndpointPattern finds loopback addresses and captures the port as a whole number.
//
// All three spellings, because Beacon writes 127.0.0.1 but a user or an MDM profile may have
// written localhost or ::1 against the same collector, and reporting that as unconfigured would be
// wrong.
var loopbackEndpointPattern = regexp.MustCompile(`(?:127\.0\.0\.1|\[::1\]|localhost):(\d+)`)

// targetsCollectorPort reports whether the text points at this endpoint's collector.
//
// The port is captured and compared as a number rather than matched as a substring. A substring
// has no right-hand boundary, so an endpoint configured on port 431 would match a file pointing at
// 4317 -- a false OK on the one check that is being trusted when it says the user *is* captured,
// which is the direction that matters most here: a false failure sends someone to run a repair,
// while a false pass tells them a silent capture gap is fine.
func targetsCollectorPort(text string, grpc, http int) bool {
	for _, match := range loopbackEndpointPattern.FindAllStringSubmatch(text, -1) {
		port, err := strconv.Atoi(match[1])
		if err != nil {
			continue
		}
		if port == grpc || port == http {
			return true
		}
	}
	return false
}

// collectorPorts resolves the ports this endpoint actually listens on, falling back to the
// defaults for a configuration that predates them being recorded.
func collectorPorts(cfg endpointconfig.Config) (int, int) {
	grpc := cfg.Collector.GRPCPort
	if grpc == 0 {
		grpc = endpointconfig.DefaultGRPCPort
	}
	http := cfg.Collector.HTTPPort
	if http == 0 {
		http = endpointconfig.DefaultHTTPPort
	}
	return grpc, http
}

// consoleUserConfigPaths lists the runtime configuration files that exist in a specific user's
// home directory.
//
// Resolved from their home directory rather than from harness discovery, which reads $HOME and
// would answer for root -- the process running doctor -- instead of for them. That substitution is
// the reason this check is needed at all, so it must not be repeated here.
func consoleUserConfigPaths(info consoleUserInfo) ([]string, error) {
	if info.HomeDir == "" {
		return nil, fmt.Errorf("no home directory for %s", info.Username)
	}
	// The runtimes a system install configures natively. Hook-only runtimes are covered too,
	// because an installed hook command names the hook binary and that is one of the markers.
	candidates := []string{
		filepath.Join(".claude", "settings.json"),
		filepath.Join(".codex", "config.toml"),
		filepath.Join(".gemini", "settings.json"),
		filepath.Join(".cursor", "hooks.json"),
		filepath.Join(".config", "Code", "User", "settings.json"),
	}
	var found []string
	for _, rel := range candidates {
		p := filepath.Join(info.HomeDir, rel)
		if _, err := os.Stat(p); err == nil {
			found = append(found, p)
		}
	}
	return found, nil
}

func harnessCheck(h harness.Harness, logPath string, effectiveUserMode bool) diagnostics.Check {
	if !h.Detected {
		return diagnostics.Check{Name: "harness", Target: h.Name, Status: diagnostics.StatusOK, Severity: diagnostics.SeverityInfo, Message: "not installed", Evidence: "not_installed"}
	}
	if h.TelemetryStatus == harness.TelemetryEnabled {
		if !harnessEventObserved(logPath, h.Name) {
			return diagnostics.Check{Name: "harness_observed", Target: h.Name, Status: diagnostics.StatusWarn, Severity: diagnostics.SeverityLow, Message: "telemetry is configured but no matching event has been observed yet", Evidence: "configured_not_observed", Action: "run " + h.DisplayName + " or beacon endpoint test-event"}
		}
		return diagnostics.Check{Name: "harness", Target: h.Name, Status: diagnostics.StatusOK, Severity: diagnostics.SeverityInfo, Message: h.Message, Evidence: "configured"}
	}
	return diagnostics.Check{Name: "harness", Target: h.Name, Status: diagnostics.StatusWarn, Severity: diagnostics.SeverityMedium, Message: h.Message, Evidence: string(h.TelemetryStatus), Action: harnessAction(h, effectiveUserMode)}
}

func harnessEventObserved(logPath, name string) bool {
	return endpointintegrations.HasRecentHarnessEvent(logPath, name)
}

func codexTokenAttributionCheck(logPath string, effectiveUserMode bool) diagnostics.Check {
	signals := endpointintegrations.ScanCodexUsageSignals(logPath)
	check := diagnostics.Check{
		Name:     "codex_token_attribution",
		Target:   "codex_cli",
		Severity: diagnostics.SeverityInfo,
	}
	switch {
	case signals.TurnSpans > 0:
		check.Status = diagnostics.StatusOK
		check.Message = "session-attributed Codex turn usage is present"
		check.Evidence = "codex_turn_usage_observed"
	case signals.SessionContexts > 0:
		check.Status = diagnostics.StatusWarn
		check.Severity = diagnostics.SeverityMedium
		check.Message = "Codex session context is present but no attributable turn usage span has arrived"
		check.Evidence = "codex_session_without_turn_usage"
		check.Action = doctorRepairCommand(effectiveUserMode) + " and restart Codex"
	case signals.LegacyMetrics > 0:
		check.Status = diagnostics.StatusWarn
		check.Severity = diagnostics.SeverityLow
		check.Message = "only legacy aggregate Codex token metrics are present; session and user attribution are unavailable"
		check.Evidence = "codex_legacy_usage_metrics"
		check.Action = doctorRepairCommand(effectiveUserMode) + " and restart Codex"
	default:
		check.Status = diagnostics.StatusOK
		check.Message = "no Codex token usage has been observed yet"
		check.Evidence = "codex_usage_not_observed"
	}
	return check
}

func harnessAction(h harness.Harness, effectiveUserMode bool) string {
	switch h.Capability {
	case "hooks", "plugin":
		return "beacon endpoint hooks install --harness " + h.Name
	case "otel_env", "otel_config":
		return doctorRepairCommand(effectiveUserMode)
	case "admin_otel":
		return "beacon endpoint integrations claude-cowork setup"
	// fx has nothing to install into, so the remedy is to run a collection sweep rather than to
	// configure the runtime. Pointing at `hooks install` here would name a command that cannot
	// succeed for this harness.
	case "session_log":
		return "beacon endpoint fx sync"
	// Grok has both paths. This check only runs when neither is carrying telemetry, and the hooks
	// are the remedy worth naming: they capture live and cover sessions still open, where a sync
	// sweep can only read what Grok has already committed. The check's message names the sweep for
	// the cases where that is what is behind.
	case "hooks+session_log":
		// DeepSeek Harness hooks that are installed but cannot be loaded are not fixed by
		// installing again, which would refuse: the bridge has to be installed into dsh first,
		// and the dsh_hook_bridge check names the command.
		// Discovery points ConfigPath at the hooks file only when the hooks are installed.
		if h.Name == dshsession.Harness && h.TelemetryStatus == harness.TelemetryMisconfigured &&
			filepath.Base(h.ConfigPath) == "beacon-endpoint-hooks.json" {
			return "see the dsh_hook_bridge check; until then run beacon endpoint dsh sync"
		}
		return "beacon endpoint hooks install --harness " + h.Name
	}
	return ""
}

func checkCounts(checks []diagnostics.Check) (int, int) {
	failures := 0
	warnings := 0
	for _, check := range checks {
		switch check.Status {
		case diagnostics.StatusFail:
			failures++
		case diagnostics.StatusWarn:
			warnings++
		}
	}
	return failures, warnings
}

func doctorRepairCommand(userMode bool) string {
	if userMode {
		return "beacon endpoint repair --user"
	}
	return "sudo beacon endpoint repair --system"
}

func doctorInstallCommand(userMode bool) string {
	if userMode {
		return "beacon endpoint install --user"
	}
	return "sudo beacon endpoint install --system"
}

type doctorFixPlan struct {
	Fixes   []plannedAction
	Skipped []plannedAction
}

func planDoctorFixes(result doctorResult, status lifecycle.Status) doctorFixPlan {
	plan := doctorFixPlan{}
	addFix := func(action plannedAction) {
		for _, existing := range plan.Fixes {
			if existing.Action == action.Action && existing.Target == action.Target {
				return
			}
		}
		plan.Fixes = append(plan.Fixes, action)
	}
	addSkip := func(action plannedAction) {
		for _, existing := range plan.Skipped {
			if existing.Action == action.Action && existing.Target == action.Target {
				return
			}
		}
		plan.Skipped = append(plan.Skipped, action)
	}

	configUsable := true
	for _, check := range result.Checks {
		if check.Name == "config_valid" && check.Status == diagnostics.StatusFail {
			configUsable = false
			addSkip(plannedAction{Action: "manual_fix", Target: check.Target, Message: "endpoint config could not be repaired safely: " + check.Message})
		}
	}

	for _, check := range result.Checks {
		if check.Status == diagnostics.StatusOK {
			continue
		}
		switch check.Name {
		case "runtime_log", "runtime_log_permissions", "last_event":
			switch check.Evidence {
			case "missing_optional_file", "runtime_log_missing":
				addFix(plannedAction{Action: "create_runtime_log", Target: status.LogPath, Message: "create runtime log file and parent directory"})
			case "last_event_missing":
				addSkip(plannedAction{Action: "manual_fix", Target: check.Target, Message: "run beacon endpoint test-event or generate a runtime event"})
			// The one permission failure that is repairable in place, and the one that matters
			// most: without this grant a system-mode Windows endpoint runs a healthy collector
			// that records nothing an agent did, because hooks cannot write to its log.
			case "acl_missing_interactive_write", "acl_too_broad":
				// Target is the log itself: the repair creates the log and its lock, which needs
				// their name, not just the directory the check reports.
				addFix(plannedAction{Action: "grant_log_access", Target: status.LogPath, Message: "reset the log directory ACL so interactive users can append to the runtime log and nothing more"})
			default:
				// Anything else here is a permission problem doctor cannot repair. Reported as a
				// skip rather than dropped: falling out of this switch is how a broken systemd unit
				// once produced neither a fix nor a skip, and a check that silently repairs nothing
				// reads exactly like a check that found nothing.
				if check.Name == "runtime_log_permissions" {
					message := "review the log permissions manually"
					if check.Action != "" {
						message = "run " + check.Action
					}
					addSkip(plannedAction{Action: "manual_fix", Target: check.Target, Message: message})
				}
			}
		// systemd_unit belongs here alongside launchd_plist: diagnostics emits whichever the
		// resolved backend uses, and omitting it meant a broken systemd unit produced neither a
		// fix nor a skip -- it fell through the switch and was silently unreported.
		//
		// The repair itself is platform-neutral (repairCollectorServiceFromStatus goes through
		// UnitPath/WriteUnit), so the check is whether a service manager is usable here rather
		// than what the OS is called. The old GOOS gate additionally printed "launchd service
		// repair is only available on macOS", which stopped being true when systemd support
		// landed.
		case "collector_config", "launchd_plist", "systemd_unit", "collector_health", "collector_reachability", "service":
			mgr := service.Manager{UserMode: status.RuntimeLog.EffectiveUserMode}
			switch {
			case !mgr.Available():
				addSkip(plannedAction{Action: "repair_collector_service", Target: endpointconfig.ConfigPath(status.RuntimeLog.EffectiveUserMode), Message: mgr.UnsupportedReason()})
			case configUsable:
				addFix(plannedAction{Action: "repair_collector_service", Target: endpointconfig.ConfigPath(status.RuntimeLog.EffectiveUserMode), Message: "recreate managed collector config and " + mgr.ResolvedKind().ServiceNoun()})
			default:
				addSkip(plannedAction{Action: "repair_collector_service", Target: endpointconfig.ConfigPath(status.RuntimeLog.EffectiveUserMode), Message: "skipped because endpoint config is invalid"})
			}
		case "config", "config_valid":
			if check.Status == diagnostics.StatusFail {
				addSkip(plannedAction{Action: "manual_fix", Target: check.Target, Message: "review endpoint config or run " + doctorInstallCommand(status.RuntimeLog.EffectiveUserMode)})
			}
		case "harness":
			message := "review harness configuration manually"
			if check.Action != "" {
				message = "run " + check.Action
			}
			addSkip(plannedAction{Action: "manual_fix", Target: check.Target, Message: message})
		case "runtime_log_source":
			addSkip(plannedAction{Action: "manual_fix", Target: check.Target, Message: check.Action})
		// Nothing here is Beacon's to repair: the sandbox mode is the operator's choice in dsh, and
		// widening it on their behalf would be the wrong fix even if doctor could. Reported as a
		// skip so --fix does not read as having found nothing.
		// A LaunchAgents directory on an external volume is a layout, not damage: when Beacon can
		// stage the plists (warn) the install already works and there is nothing to repair; when it
		// cannot (fail) the remedy is the manual bootstrap in the check's action.
		case "launch_agents_volume":
			if check.Status == diagnostics.StatusFail {
				addSkip(plannedAction{Action: "manual_fix", Target: check.Target, Message: check.Action})
			}
		case "dsh_hook_capture":
			addSkip(plannedAction{Action: "manual_fix", Target: check.Target, Message: check.Action})
		// The budget is fixed, so there is nothing to repair; a commit the hook left unlinked is
		// linked by hand.
		case "git_hook_budget":
			addSkip(plannedAction{Action: "manual_fix", Target: check.Target, Message: check.Action})
		}
	}
	return plan
}

func applyDoctorFixes(plan doctorFixPlan, status lifecycle.Status) error {
	var errs []error
	for _, action := range plan.Fixes {
		switch action.Action {
		case "create_runtime_log":
			if err := ensureLogFile(action.Target); err != nil {
				errs = append(errs, fmt.Errorf("%s %s: %w", action.Action, action.Target, err))
			}
		case "repair_collector_service":
			if err := repairCollectorServiceFromStatus(status); err != nil {
				errs = append(errs, fmt.Errorf("%s %s: %w", action.Action, action.Target, err))
			}
		case "grant_log_access":
			// The same call install makes, so a repaired endpoint and a fresh one end up with the
			// same ACL rather than two grants that drift.
			if err := writer.EnsureSystemLogWritable(action.Target); err != nil {
				errs = append(errs, fmt.Errorf("%s %s: %w", action.Action, action.Target, err))
			}
		}
	}
	return errors.Join(errs...)
}

func repairCollectorServiceFromStatus(status lifecycle.Status) error {
	userMode := status.RuntimeLog.EffectiveUserMode
	cfg, err := repairLoadEndpointConfig(userMode)
	if err != nil {
		return err
	}
	manager := newRepairServiceManager(userMode)
	plistPath, err := manager.UnitPath()
	if err != nil {
		return err
	}
	rollback := newRepairRollback(manager, status.Service.Loaded)
	rollback.Track(endpointconfig.ConfigPath(userMode))
	rollback.Track(cfg.Collector.ConfigPath)
	rollback.Track(plistPath)

	if endpointOpts.logPath != "" {
		cfg.LogPath = endpointOpts.logPath
		if _, err := repairSaveEndpointConfig(cfg); err != nil {
			return rollbackRepairError(err, rollback)
		}
	}
	binary, err := repairResolveCollectorBinary(cfg.Collector.BinaryPath)
	if err != nil {
		return rollbackRepairError(err, rollback)
	}
	if err := repairWriteCollectorConfig(cfg); err != nil {
		return rollbackRepairError(err, rollback)
	}
	if _, err := manager.WriteUnit(binary, cfg.Collector.ConfigPath); err != nil {
		return rollbackRepairError(err, rollback)
	}
	if err := manager.Load(); err != nil {
		return rollbackRepairError(err, rollback)
	}
	rollback.serviceLoaded = true
	if err := repairWaitCollectorReady(cfg, 10*time.Second); err != nil {
		return rollbackRepairError(err, rollback)
	}
	return nil
}

func newRepairRollback(manager repairServiceManager, serviceWasLoaded bool) *repairRollback {
	return &repairRollback{
		manager:          manager,
		serviceWasLoaded: serviceWasLoaded,
		snapshots:        map[string]repairFileSnapshot{},
	}
}

func (r *repairRollback) Track(path string) {
	if r == nil || path == "" {
		return
	}
	if _, ok := r.snapshots[path]; ok {
		return
	}
	r.snapshots[path] = snapshotRepairFile(path)
	r.files = append(r.files, path)
}

func (r *repairRollback) Rollback() error {
	if r == nil {
		return nil
	}
	var errs []error
	if r.serviceLoaded {
		if err := r.manager.Unload(); err != nil {
			errs = append(errs, err)
		}
	}
	for i := len(r.files) - 1; i >= 0; i-- {
		path := r.files[i]
		if err := restoreRepairFile(path, r.snapshots[path]); err != nil {
			errs = append(errs, err)
		}
	}
	if r.serviceWasLoaded {
		if err := r.manager.Load(); err != nil {
			errs = append(errs, err)
		}
	}
	return errors.Join(errs...)
}

func rollbackRepairError(err error, rollback *repairRollback) error {
	if rollbackErr := rollback.Rollback(); rollbackErr != nil {
		return errors.Join(err, fmt.Errorf("rollback collector service repair: %w", rollbackErr))
	}
	return err
}

func snapshotRepairFile(path string) repairFileSnapshot {
	data, err := os.ReadFile(path)
	if err != nil {
		if errors.Is(err, os.ErrNotExist) {
			return repairFileSnapshot{}
		}
		return repairFileSnapshot{existed: true, readErr: err}
	}
	snapshot := repairFileSnapshot{existed: true, data: data}
	if info, statErr := os.Stat(path); statErr == nil {
		snapshot.mode = info.Mode().Perm()
	}
	snapshot.secret = sysacl.IsSecretFile(path)
	return snapshot
}

func restoreRepairFile(path string, snapshot repairFileSnapshot) error {
	if !snapshot.existed {
		if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
			return err
		}
		return nil
	}
	if snapshot.readErr != nil {
		return fmt.Errorf("cannot restore %s: pre-repair snapshot failed: %w", path, snapshot.readErr)
	}
	if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
		return err
	}
	if snapshot.secret {
		return sysacl.WriteSecretFile(path, snapshot.data)
	}
	mode := snapshot.mode
	if mode == 0 {
		mode = 0600
	}
	return atomicfile.Write(path, snapshot.data, mode)
}

func checkLogWritable(cfg endpointconfig.Config) diagnostics.Check {
	dir := filepath.Dir(cfg.LogPath)
	if err := os.MkdirAll(dir, 0755); err != nil {
		return diagnostics.Check{Name: "runtime_log_writable", Target: cfg.LogPath, Status: "fail", Severity: "high", Message: err.Error(), Evidence: "mkdir_failed"}
	}
	file, err := os.OpenFile(cfg.LogPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		return diagnostics.Check{Name: "runtime_log_writable", Target: cfg.LogPath, Status: "fail", Severity: "high", Message: err.Error(), Evidence: "open_failed"}
	}
	_ = file.Close()
	return diagnostics.Check{Name: "runtime_log_writable", Target: cfg.LogPath, Status: "ok", Severity: "info", Message: "runtime log is writable", Evidence: "open_succeeded"}
}

func stageFromCheck(check diagnostics.Check) validationStage {
	return validationStage{Name: check.Name, Target: check.Target, Status: check.Status, Severity: check.Severity, Message: check.Message, Evidence: check.Evidence}
}

func redactLastEvent(raw string) string {
	if raw == "" {
		return ""
	}
	return "[present]"
}

func redactConfig(cfg endpointconfig.Config) endpointconfig.Config {
	if cfg.Destinations == nil {
		return cfg
	}
	destinations := *cfg.Destinations
	changed := false
	if cfg.Destinations.SplunkHEC != nil && cfg.Destinations.SplunkHEC.Token != "" {
		splunk := *cfg.Destinations.SplunkHEC
		splunk.Token = "[REDACTED]"
		destinations.SplunkHEC = &splunk
		changed = true
	}
	if cfg.Destinations.FalconHEC != nil && cfg.Destinations.FalconHEC.Token != "" {
		falcon := *cfg.Destinations.FalconHEC
		falcon.Token = "[REDACTED]"
		destinations.FalconHEC = &falcon
		changed = true
	}
	if cfg.Destinations.OTLPForward != nil && len(cfg.Destinations.OTLPForward.Headers) > 0 {
		forward := *cfg.Destinations.OTLPForward
		forward.Headers = make(map[string]string, len(cfg.Destinations.OTLPForward.Headers))
		for name := range cfg.Destinations.OTLPForward.Headers {
			forward.Headers[name] = "[REDACTED]"
		}
		destinations.OTLPForward = &forward
		changed = true
	}
	if changed {
		cfg.Destinations = &destinations
	}
	return cfg
}

func writeJSONFile(path string, value interface{}) error {
	data, err := json.MarshalIndent(value, "", "  ")
	if err != nil {
		return err
	}
	return os.WriteFile(path, append(data, '\n'), 0644)
}

func writeEventBundleFiles(out, logPath string, includeRaw bool) error {
	data, err := os.ReadFile(logPath)
	if err != nil {
		if os.IsNotExist(err) {
			return writeJSONFile(filepath.Join(out, "event-summaries.json"), []map[string]interface{}{})
		}
		return err
	}
	lines := strings.Split(strings.TrimSpace(string(data)), "\n")
	summaries := []map[string]interface{}{}
	for _, line := range lines {
		if strings.TrimSpace(line) == "" {
			continue
		}
		var event schema.Event
		if err := json.Unmarshal([]byte(line), &event); err != nil {
			continue
		}
		hash := fmt.Sprintf("%x", sha256.Sum256([]byte(line)))
		summaries = append(summaries, map[string]interface{}{
			"timestamp": event.Timestamp,
			"category":  event.Event.Category,
			"action":    event.Event.Action,
			"severity":  event.Severity,
			"harness":   event.Harness.Name,
			"hash":      hash,
		})
	}
	if err := writeJSONFile(filepath.Join(out, "event-summaries.json"), summaries); err != nil {
		return err
	}
	if includeRaw {
		return os.WriteFile(filepath.Join(out, "runtime.raw.jsonl"), data, 0600)
	}
	return nil
}

func syntheticEvent(destination string) schema.Event {
	mode := "local_jsonl"
	message := "Beacon endpoint pipeline validation event"
	// Forwarding-destination modes/messages come from the destination registry
	// (see siemDestinations); everything else keeps the generic pipeline default.
	if m, msg, ok := destinationValidationMeta(destination); ok {
		mode = m
		message = msg
	}
	event := schema.NewEvent(schema.NewEventOptions{
		Action:       "agent.detected",
		Category:     "validation",
		Severity:     schema.SeverityInfo,
		AgentVersion: version.GetVersion(),
		Harness:      schema.HarnessInfo{Name: "test_harness", Version: "test"},
		Message:      message,
	})
	event.Destination = &schema.DestinationInfo{Type: destination, Mode: mode, Status: "configured"}
	return event
}

// confineInventoryScan confines the inventory scan of home with sessionfs when this process is root
// scanning a home it does not own -- the system job reading the console user's home. That user can
// plant anything there: a symlink to a root-only file (whose content or hash would land in the
// world-readable system log), a FIFO that hangs the job while it holds the inventory lock, or a
// link to /dev/zero. Confined, those read as absent. It returns the release to call after the scan
// and, confined, the resolver the scan names MCP server packages with: the console user's own (see
// packagesAsUser), since the launcher config it reads is wherever that user pointed it. Without
// one, a confined scan holds every package back as private.
func confineInventoryScan(home string) (func(), packageResolver, error) {
	if strings.TrimSpace(home) == "" || os.Geteuid() != 0 {
		return func() {}, nil, nil
	}
	uid, err := sessionfs.OwnerUID(home)
	if err != nil {
		return nil, nil, fmt.Errorf("could not read the owner of %s: %w", home, err)
	}
	if uid == 0 {
		return func() {}, nil, nil
	}
	confined, err := sessionfs.Confine(home, uid, sessionfs.Options{})
	if err != nil {
		return nil, nil, err
	}
	resolver, err := packagesAsUser(uid, home)
	if err != nil {
		fmt.Fprintf(os.Stderr, "warning: MCP server packages are held back as private: %v\n", err)
	}
	return confined.Release, resolver, nil
}