Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

27.2 KB
Raw Blame
package ai

import (
	"context"
	"sort"
	"sync"
	"time"

	"github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts"
	"github.com/rs/zerolog/log"
)

// TriggerReason describes why a patrol was triggered
type TriggerReason string

// PatrolEventTriggerConfig controls which event sources may enqueue scoped patrol runs.
type PatrolEventTriggerConfig struct {
	AlertTriggersEnabled   bool `json:"alert_triggers_enabled"`
	AnomalyTriggersEnabled bool `json:"anomaly_triggers_enabled"`
}

const EventTriggerBlockReasonBackgroundAutomationDisabled = "background_automation_disabled"

const eventTriggerBlockMessageBackgroundAutomationDisabled = "Automatic Patrol checks from alerts and anomalies are paused by the local development safety guard. Manual Patrol still works."

// PatrolEventTriggerBlock explains why event-driven trigger sources are paused
// even when the user's scoped trigger preferences remain enabled.
type PatrolEventTriggerBlock struct {
	Reason  string
	Message string
}

func (block PatrolEventTriggerBlock) active() bool {
	return block.Reason != ""
}

func BackgroundAutomationEventTriggerBlock() PatrolEventTriggerBlock {
	return PatrolEventTriggerBlock{
		Reason:  EventTriggerBlockReasonBackgroundAutomationDisabled,
		Message: eventTriggerBlockMessageBackgroundAutomationDisabled,
	}
}

// Trigger priority values control which scoped patrol runs first when multiple are queued.
const (
	triggerPriorityManual       = 100 // User-initiated patrols run first
	triggerPriorityAlertFired   = 80  // New alerts are high priority
	triggerPriorityObjective    = 70  // Retained-objective evidence needs prompt investigation
	triggerPriorityAnomaly      = 60  // Anomaly detection is medium-high
	triggerPriorityAlertCleared = 40  // Cleared alerts are lower priority
	triggerPriorityUserAction   = 30  // User finding actions
	triggerPriorityScheduled    = 20  // Periodic background patrol
)

const (
	TriggerReasonScheduled         TriggerReason = "scheduled"          // Regular interval trigger
	TriggerReasonManual            TriggerReason = "manual"             // User-initiated patrol
	TriggerReasonAlertFired        TriggerReason = "alert_fired"        // New alert triggered
	TriggerReasonAlertCleared      TriggerReason = "alert_cleared"      // Alert was resolved
	TriggerReasonAlertFlapping     TriggerReason = "alert_flapping"     // Alert flapping detected and suppressed
	TriggerReasonAnomalyDetected   TriggerReason = "anomaly"            // Baseline breach detected
	TriggerReasonUserAction        TriggerReason = "user_action"        // User dismissed/snoozed finding
	TriggerReasonConfigChanged     TriggerReason = "config_changed"     // System configuration changed
	TriggerReasonStartup           TriggerReason = "startup"            // Service startup
	TriggerReasonVerification      TriggerReason = "verification"       // Post-fix verification
	TriggerReasonObjectiveChanged  TriggerReason = "objective_changed"  // Operator created or materially changed a retained objective
	TriggerReasonObjectiveEvidence TriggerReason = "objective_evidence" // Local observer detected an objective breach
)

// PatrolScope defines the scope of a patrol run
type PatrolScope struct {
	// ResourceIDs limits patrol to specific resources (empty = all resources)
	ResourceIDs []string
	// ResourceTypes limits patrol to specific resource types (empty = all types)
	ResourceTypes []string
	// Depth controls how thorough the patrol should be
	Depth PatrolDepth
	// Reason why this patrol was triggered
	Reason TriggerReason
	// Context provides additional information about the trigger
	Context string
	// ObjectiveContext carries the exact retained objective and local evidence
	// that caused an objective_evidence run. It is model context only and grants
	// no mutation or approval authority.
	ObjectiveContext *aicontracts.PatrolObjectiveContext
	// Priority indicates relative urgency (higher = more urgent)
	Priority int
	// AlertIdentifier is the canonical ID of the alert that triggered this patrol (if applicable)
	AlertIdentifier string
	// AlertContext carries the firing alert's specifics (metric, value, threshold)
	// so an alert-triggered patrol can investigate the actual breach instead of
	// re-checking the resource generically. Nil for non-alert triggers.
	AlertContext *PatrolAlertContext
	// FindingID is the ID of the finding that triggered this patrol (if applicable)
	FindingID string
	// NoStream skips streaming updates (phase, content, subscriber notifications).
	// Used for verification runs that are consumed programmatically.
	NoStream bool
	// RetryCount tracks how many times this scoped patrol has been re-queued after a drop
	RetryCount int
	// RetryAfter prevents processing before this time (for backoff on re-queued patrols)
	RetryAfter time.Time
	// resolvedIdentityOnly is set only by the canonical scope resolver. It
	// prevents an authoritative ID from subsequently matching a different
	// resource whose display alias happens to contain the same string.
	resolvedIdentityOnly bool
	// resolvedResourceTypes is the core-derived type set for exact resource-ID
	// scopes. It is used only to reduce the provider tool manifest; it never
	// broadens collection scope or mutation authority.
	resolvedResourceTypes []string
	// Alert constructors receive the producer's type hint. Current canonical
	// ownership can replace that hint when an agent is linked into a guest/node.
	alertResourceTypeHint bool
}

// PatrolScopeResolution records how caller-supplied identities map onto the
// exact runtime resources consumed by Patrol's normal collection paths.
type PatrolScopeResolution struct {
	RequestedResourceIDs []string `json:"requested_resource_ids"`
	ResolvedResourceIDs  []string `json:"resolved_resource_ids,omitempty"`
	EffectiveResourceIDs []string `json:"effective_resource_ids,omitempty"`
	UnmatchedResourceIDs []string `json:"unmatched_resource_ids,omitempty"`
	AmbiguousResourceIDs []string `json:"ambiguous_resource_ids,omitempty"`
}

// PatrolAlertContext describes the alert that triggered a scoped patrol, so the
// patrol prompt can focus the investigation on the specific breach.
type PatrolAlertContext struct {
	ResourceID   string
	ResourceName string
	Mountpoint   string
	Device       string
	AlertType    string  // cpu, memory, disk, etc.
	Level        string  // warning | critical
	Value        float64 // observed metric value at fire time
	Threshold    float64 // threshold that was crossed
	Message      string  // human-readable alert message
}

// PatrolDepth controls how thorough a patrol run should be
type PatrolDepth int

const (
	// PatrolDepthQuick is a fast, focused check on specific resources
	PatrolDepthQuick PatrolDepth = iota
	// PatrolDepthNormal is the standard patrol depth
	PatrolDepthNormal
)

// String returns the depth as a string
func (d PatrolDepth) String() string {
	switch d {
	case PatrolDepthQuick:
		return "quick"
	case PatrolDepthNormal:
		return "normal"
	default:
		return "unknown"
	}
}

// TriggerManager manages patrol triggers with rate limiting and prioritization
type TriggerManager struct {
	mu sync.Mutex

	// Rate limiting per resource
	lastPatrolByResource map[string]time.Time
	minResourceInterval  time.Duration

	// Global rate limiting
	lastGlobalPatrol  time.Time
	minGlobalInterval time.Duration

	// Pending triggers queue (priority queue)
	pendingTriggers    []PatrolScope
	maxPendingTriggers int

	// Adaptive interval management
	baseInterval    time.Duration
	currentInterval time.Duration
	busyThreshold   int // Number of alerts/anomalies to consider "busy"
	recentEvents    []time.Time
	eventWindow     time.Duration

	// Event trigger gating - event-driven reasons are checked against the per-source
	// scoped patrol trigger configuration.
	eventTriggerConfig PatrolEventTriggerConfig
	eventTriggerBlock  PatrolEventTriggerBlock

	// Callback to execute patrol
	onTrigger func(ctx context.Context, scope PatrolScope)

	// Stop channel
	stopCh  chan struct{}
	running bool
}

// TriggerManagerConfig configures the trigger manager
type TriggerManagerConfig struct {
	MinResourceInterval time.Duration // Minimum time between patrols for same resource
	MinGlobalInterval   time.Duration // Minimum time between any patrols
	MaxPendingTriggers  int           // Maximum pending triggers to queue
	BaseInterval        time.Duration // Base scheduled interval
	BusyThreshold       int           // Events to trigger "busy" mode
	EventWindow         time.Duration // Window to count events for busy detection
}

// DefaultTriggerManagerConfig returns sensible defaults
func DefaultTriggerManagerConfig() TriggerManagerConfig {
	return TriggerManagerConfig{
		MinResourceInterval: 2 * time.Minute,
		MinGlobalInterval:   30 * time.Second,
		MaxPendingTriggers:  10,
		BaseInterval:        15 * time.Minute,
		BusyThreshold:       5,
		EventWindow:         5 * time.Minute,
	}
}

// NewTriggerManager creates a new trigger manager
func NewTriggerManager(cfg TriggerManagerConfig) *TriggerManager {
	if cfg.MinResourceInterval <= 0 {
		cfg.MinResourceInterval = 2 * time.Minute
	}
	if cfg.MinGlobalInterval <= 0 {
		cfg.MinGlobalInterval = 30 * time.Second
	}
	if cfg.MaxPendingTriggers <= 0 {
		cfg.MaxPendingTriggers = 10
	}
	if cfg.BaseInterval <= 0 {
		cfg.BaseInterval = 15 * time.Minute
	}
	if cfg.BusyThreshold <= 0 {
		cfg.BusyThreshold = 5
	}
	if cfg.EventWindow <= 0 {
		cfg.EventWindow = 5 * time.Minute
	}

	return &TriggerManager{
		lastPatrolByResource: make(map[string]time.Time),
		minResourceInterval:  cfg.MinResourceInterval,
		minGlobalInterval:    cfg.MinGlobalInterval,
		maxPendingTriggers:   cfg.MaxPendingTriggers,
		baseInterval:         cfg.BaseInterval,
		currentInterval:      cfg.BaseInterval,
		busyThreshold:        cfg.BusyThreshold,
		eventWindow:          cfg.EventWindow,
		recentEvents:         make([]time.Time, 0),
		pendingTriggers:      make([]PatrolScope, 0),
		eventTriggerConfig: PatrolEventTriggerConfig{
			AlertTriggersEnabled:   true,
			AnomalyTriggersEnabled: true,
		},
		stopCh: make(chan struct{}),
	}
}

// SetOnTrigger sets the callback function to execute when a patrol should run
func (tm *TriggerManager) SetOnTrigger(fn func(ctx context.Context, scope PatrolScope)) {
	tm.mu.Lock()
	defer tm.mu.Unlock()
	tm.onTrigger = fn
}

// Start begins the trigger manager's background processing
func (tm *TriggerManager) Start(ctx context.Context) {
	tm.mu.Lock()
	if tm.running {
		tm.mu.Unlock()
		return
	}
	tm.running = true
	tm.stopCh = make(chan struct{})
	tm.mu.Unlock()

	go tm.processLoop(ctx)
	log.Info().Msg("patrol trigger manager started")
}

// Stop stops the trigger manager
func (tm *TriggerManager) Stop() {
	tm.mu.Lock()
	if !tm.running {
		tm.mu.Unlock()
		return
	}
	tm.running = false
	close(tm.stopCh)
	tm.mu.Unlock()
	log.Info().Msg("patrol trigger manager stopped")
}

// processLoop processes pending triggers and handles scheduled patrols
func (tm *TriggerManager) processLoop(ctx context.Context) {
	ticker := time.NewTicker(1 * time.Second)
	defer ticker.Stop()

	for {
		select {
		case <-ctx.Done():
			return
		case <-tm.stopCh:
			return
		case <-ticker.C:
			tm.processPendingTriggers(ctx)
		}
	}
}

// processPendingTriggers checks and executes pending triggers
func (tm *TriggerManager) processPendingTriggers(ctx context.Context) {
	tm.mu.Lock()

	if len(tm.pendingTriggers) == 0 || tm.onTrigger == nil {
		tm.mu.Unlock()
		return
	}

	// Compute adaptive global rate limit based on activity level
	// When busy (currentInterval < baseInterval), process triggers faster
	// When quiet (currentInterval > baseInterval), space them out more
	adaptiveGlobalInterval := tm.minGlobalInterval
	if tm.baseInterval > 0 {
		ratio := float64(tm.currentInterval) / float64(tm.baseInterval)
		adaptiveGlobalInterval = time.Duration(float64(tm.minGlobalInterval) * ratio)
		// Clamp to reasonable bounds: 10 seconds to 2 minutes
		if adaptiveGlobalInterval < 10*time.Second {
			adaptiveGlobalInterval = 10 * time.Second
		}
		if adaptiveGlobalInterval > 2*time.Minute {
			adaptiveGlobalInterval = 2 * time.Minute
		}
	}

	// Check global rate limit with adaptive interval
	if time.Since(tm.lastGlobalPatrol) < adaptiveGlobalInterval {
		tm.mu.Unlock()
		return
	}

	// Get highest priority trigger
	now := time.Now()
	highestPriority := -1
	highestIndex := -1
	for i, trigger := range tm.pendingTriggers {
		// Skip triggers that are waiting for retry backoff
		if !trigger.RetryAfter.IsZero() && now.Before(trigger.RetryAfter) {
			continue
		}
		if trigger.Priority > highestPriority {
			// Check resource rate limit
			if len(trigger.ResourceIDs) > 0 {
				canRun := true
				for _, rid := range trigger.ResourceIDs {
					if lastPatrol, ok := tm.lastPatrolByResource[rid]; ok {
						if time.Since(lastPatrol) < tm.minResourceInterval {
							canRun = false
							break
						}
					}
				}
				if !canRun {
					continue
				}
			}
			highestPriority = trigger.Priority
			highestIndex = i
		}
	}

	if highestIndex < 0 {
		tm.mu.Unlock()
		return
	}

	// Remove trigger from queue
	trigger := tm.pendingTriggers[highestIndex]
	tm.pendingTriggers = append(tm.pendingTriggers[:highestIndex], tm.pendingTriggers[highestIndex+1:]...)

	// Update rate limiting
	tm.lastGlobalPatrol = time.Now()
	for _, rid := range trigger.ResourceIDs {
		tm.lastPatrolByResource[rid] = time.Now()
	}

	callback := tm.onTrigger
	tm.mu.Unlock()

	// Execute callback outside lock
	log.Info().
		Str("reason", string(trigger.Reason)).
		Int("priority", trigger.Priority).
		Str("depth", trigger.Depth.String()).
		Strs("resources", trigger.ResourceIDs).
		Msg("Executing triggered patrol")

	callback(ctx, trigger)
}

// SetEventTriggerConfig controls which event-driven trigger sources (alerts, anomalies)
// are accepted. Manual, scheduled, startup, user_action, and verification triggers are unaffected.
func (tm *TriggerManager) SetEventTriggerConfig(cfg PatrolEventTriggerConfig) {
	tm.mu.Lock()
	defer tm.mu.Unlock()
	tm.eventTriggerConfig = cfg
	log.Info().
		Bool("alert_triggers_enabled", cfg.AlertTriggersEnabled).
		Bool("anomaly_triggers_enabled", cfg.AnomalyTriggersEnabled).
		Msg("patrol event trigger config updated")
}

// SetEventTriggerBlock pauses event-driven triggers without changing the user's
// configured trigger source preferences.
func (tm *TriggerManager) SetEventTriggerBlock(block PatrolEventTriggerBlock) {
	tm.mu.Lock()
	wasBlocked := tm.eventTriggerBlock.active()
	tm.eventTriggerBlock = block
	isBlocked := tm.eventTriggerBlock.active()
	tm.mu.Unlock()

	switch {
	case isBlocked:
		log.Info().
			Str("reason", block.Reason).
			Msg("patrol event triggers blocked by runtime policy")
	case wasBlocked:
		log.Info().Msg("patrol event trigger runtime block cleared")
	}
}

// SetEventTriggersEnabled is a compatibility wrapper for the legacy aggregate toggle.
func (tm *TriggerManager) SetEventTriggersEnabled(enabled bool) {
	tm.SetEventTriggerConfig(PatrolEventTriggerConfig{
		AlertTriggersEnabled:   enabled,
		AnomalyTriggersEnabled: enabled,
	})
}

// isEventDrivenTrigger returns true for trigger reasons that are event-driven
// (alerts firing/clearing, anomaly detection) as opposed to user-initiated or scheduled triggers.
func isEventDrivenTrigger(reason TriggerReason) bool {
	switch reason {
	case TriggerReasonAlertFired, TriggerReasonAlertCleared, TriggerReasonAlertFlapping, TriggerReasonAnomalyDetected, TriggerReasonObjectiveEvidence:
		return true
	default:
		return false
	}
}

func (cfg PatrolEventTriggerConfig) allows(reason TriggerReason) bool {
	switch reason {
	case TriggerReasonAlertFired, TriggerReasonAlertCleared, TriggerReasonAlertFlapping:
		return cfg.AlertTriggersEnabled
	case TriggerReasonAnomalyDetected:
		return cfg.AnomalyTriggersEnabled
	default:
		return true
	}
}

// TriggerPatrol queues a patrol run with the given scope
// Returns true if the trigger was accepted, false if rate limited or queue full
func (tm *TriggerManager) TriggerPatrol(scope PatrolScope) bool {
	tm.mu.Lock()
	defer tm.mu.Unlock()

	// Runtime policy blocks event-driven triggers without rewriting the
	// configured alert/anomaly source preferences shown to the user.
	if isEventDrivenTrigger(scope.Reason) && tm.eventTriggerBlock.active() {
		log.Debug().
			Str("reason", string(scope.Reason)).
			Str("block_reason", tm.eventTriggerBlock.Reason).
			Msg("event-driven patrol trigger rejected by runtime policy")
		return false
	}

	// Gate event-driven triggers according to the canonical scoped trigger config
	if isEventDrivenTrigger(scope.Reason) && !tm.eventTriggerConfig.allows(scope.Reason) {
		log.Debug().
			Str("reason", string(scope.Reason)).
			Bool("alert_triggers_enabled", tm.eventTriggerConfig.AlertTriggersEnabled).
			Bool("anomaly_triggers_enabled", tm.eventTriggerConfig.AnomalyTriggersEnabled).
			Msg("event-driven patrol trigger rejected by trigger config")
		return false
	}

	// Check if queue is full
	if len(tm.pendingTriggers) >= tm.maxPendingTriggers {
		// Replace lowest priority if new trigger is higher priority
		lowestPriority := scope.Priority
		lowestIndex := -1
		for i, t := range tm.pendingTriggers {
			if t.Priority < lowestPriority {
				lowestPriority = t.Priority
				lowestIndex = i
			}
		}
		if lowestIndex < 0 {
			log.Debug().
				Str("reason", string(scope.Reason)).
				Msg("Patrol trigger rejected: queue full and lower priority")
			return false
		}
		// Remove lowest priority trigger
		tm.pendingTriggers = append(tm.pendingTriggers[:lowestIndex], tm.pendingTriggers[lowestIndex+1:]...)
	}

	// Check for duplicate triggers (same reason and resources)
	for i := range tm.pendingTriggers {
		if patrolTriggersEquivalent(tm.pendingTriggers[i], scope) {
			// Update priority if new trigger is higher priority
			if scope.Priority > tm.pendingTriggers[i].Priority {
				tm.pendingTriggers[i].Priority = scope.Priority
			}
			log.Debug().
				Str("reason", string(scope.Reason)).
				Msg("Patrol trigger merged with existing")
			return true
		}
	}

	// Record event for adaptive interval
	tm.recentEvents = append(tm.recentEvents, time.Now())
	tm.cleanupOldEvents()
	tm.updateAdaptiveInterval()

	// Add to queue
	tm.pendingTriggers = append(tm.pendingTriggers, scope)

	log.Debug().
		Str("reason", string(scope.Reason)).
		Int("queue_size", len(tm.pendingTriggers)).
		Msg("Patrol trigger queued")

	return true
}

func patrolTriggersEquivalent(left, right PatrolScope) bool {
	if left.Reason != right.Reason || !slicesEqual(left.ResourceIDs, right.ResourceIDs) {
		return false
	}
	if left.Reason != TriggerReasonObjectiveEvidence && left.Reason != TriggerReasonObjectiveChanged {
		return true
	}
	if left.ObjectiveContext == nil || right.ObjectiveContext == nil {
		return left.ObjectiveContext == nil && right.ObjectiveContext == nil
	}
	return left.ObjectiveContext.ObjectiveID == right.ObjectiveContext.ObjectiveID &&
		left.ObjectiveContext.Revision == right.ObjectiveContext.Revision &&
		left.ObjectiveContext.ObserverID == right.ObjectiveContext.ObserverID &&
		left.ObjectiveContext.ObserverVersion == right.ObjectiveContext.ObserverVersion
}

// cleanupOldEvents removes events outside the event window
func (tm *TriggerManager) cleanupOldEvents() {
	cutoff := time.Now().Add(-tm.eventWindow)
	kept := make([]time.Time, 0, len(tm.recentEvents))
	for _, t := range tm.recentEvents {
		if t.After(cutoff) {
			kept = append(kept, t)
		}
	}
	tm.recentEvents = kept
}

// updateAdaptiveInterval adjusts the scheduled interval based on activity
func (tm *TriggerManager) updateAdaptiveInterval() {
	eventCount := len(tm.recentEvents)

	if eventCount >= tm.busyThreshold {
		// Busy mode: reduce interval to 5 minutes
		tm.currentInterval = 5 * time.Minute
	} else if eventCount == 0 {
		// Quiet mode: extend interval to 30 minutes
		tm.currentInterval = 30 * time.Minute
	} else {
		// Normal mode: use base interval
		tm.currentInterval = tm.baseInterval
	}
}

// GetCurrentInterval returns the current adaptive interval
func (tm *TriggerManager) GetCurrentInterval() time.Duration {
	tm.mu.Lock()
	defer tm.mu.Unlock()
	return tm.currentInterval
}

// GetPendingCount returns the number of pending triggers
func (tm *TriggerManager) GetPendingCount() int {
	tm.mu.Lock()
	defer tm.mu.Unlock()
	return len(tm.pendingTriggers)
}

// TriggerStatus returns the current status of the trigger manager
type TriggerStatus struct {
	Running                bool  `json:"running"`
	PendingTriggers        int   `json:"pending_triggers"`
	CurrentInterval        int64 `json:"current_interval_ms"` // Milliseconds (converted from time.Duration)
	RecentEvents           int   `json:"recent_events"`
	IsBusyMode             bool  `json:"is_busy_mode"`
	AlertTriggersEnabled   bool  `json:"alert_triggers_enabled"`
	AnomalyTriggersEnabled bool  `json:"anomaly_triggers_enabled"`
	EventTriggersBlocked   bool  `json:"event_triggers_blocked"`
	// EventTriggersBlockedReason is stable for clients; Message is safe to show to users.
	EventTriggersBlockedReason  string `json:"event_triggers_blocked_reason,omitempty"`
	EventTriggersBlockedMessage string `json:"event_triggers_blocked_message,omitempty"`
}

// GetStatus returns the current status
func (tm *TriggerManager) GetStatus() TriggerStatus {
	tm.mu.Lock()
	defer tm.mu.Unlock()

	tm.cleanupOldEvents()
	// Recompute the adaptive interval after pruning old events.
	// Without this, currentInterval can remain stuck in busy/quiet mode
	// after events age out of the window.
	tm.updateAdaptiveInterval()

	return TriggerStatus{
		Running:                     tm.running,
		PendingTriggers:             len(tm.pendingTriggers),
		CurrentInterval:             int64(tm.currentInterval / time.Millisecond),
		RecentEvents:                len(tm.recentEvents),
		IsBusyMode:                  len(tm.recentEvents) >= tm.busyThreshold,
		AlertTriggersEnabled:        tm.eventTriggerConfig.AlertTriggersEnabled,
		AnomalyTriggersEnabled:      tm.eventTriggerConfig.AnomalyTriggersEnabled,
		EventTriggersBlocked:        tm.eventTriggerBlock.active(),
		EventTriggersBlockedReason:  tm.eventTriggerBlock.Reason,
		EventTriggersBlockedMessage: tm.eventTriggerBlock.Message,
	}
}

// Helper functions

func slicesEqual(a, b []string) bool {
	if len(a) != len(b) {
		return false
	}
	if len(a) == 0 {
		return true
	}
	if len(a) == 1 {
		return a[0] == b[0]
	}
	aSorted := append([]string(nil), a...)
	bSorted := append([]string(nil), b...)
	sort.Strings(aSorted)
	sort.Strings(bSorted)
	for i := range aSorted {
		if aSorted[i] != bSorted[i] {
			return false
		}
	}
	return true
}

func canonicalPatrolScopeResourceType(resourceType string) string {
	normalized := canonicalizeAICompatibilityResourceType(resourceType)
	if normalized == "" {
		return ""
	}
	if isUnsupportedLegacyAIResourceTypeToken(normalized) {
		return ""
	}
	switch normalized {
	case "vm":
		return "vm"
	case "system-container":
		return "system-container"
	case "app-container":
		return "app-container"
	case "docker-host":
		return "docker-host"
	case "k8s-cluster":
		return "k8s-cluster"
	case "agent":
		return "agent"
	case "node":
		return "node"
	case "physical_disk":
		return "physical_disk"
	default:
		return normalized
	}
}

func patrolScopeResourceTypes(resourceType string) []string {
	normalized := canonicalPatrolScopeResourceType(resourceType)
	if normalized == "" {
		return nil
	}
	return []string{normalized}
}

// AlertTriggeredPatrolScope creates a patrol scope for an alert that fired
func AlertTriggeredPatrolScope(alertIdentifier, resourceID, resourceType, alertType string) PatrolScope {
	return PatrolScope{
		ResourceIDs:           []string{resourceID},
		ResourceTypes:         patrolScopeResourceTypes(resourceType),
		Depth:                 PatrolDepthQuick,
		Reason:                TriggerReasonAlertFired,
		Context:               "Alert: " + alertType,
		Priority:              triggerPriorityAlertFired,
		AlertIdentifier:       alertIdentifier,
		alertResourceTypeHint: true,
	}
}

// AlertClearedPatrolScope creates a patrol scope for an alert that cleared
func AlertClearedPatrolScope(alertIdentifier, resourceID, resourceType string) PatrolScope {
	return PatrolScope{
		ResourceIDs:           []string{resourceID},
		ResourceTypes:         patrolScopeResourceTypes(resourceType),
		Depth:                 PatrolDepthQuick,
		Reason:                TriggerReasonAlertCleared,
		Context:               "Verify resolution",
		Priority:              triggerPriorityAlertCleared,
		AlertIdentifier:       alertIdentifier,
		alertResourceTypeHint: true,
	}
}

// AnomalyDetectedPatrolScope creates a patrol scope for an anomaly detection
func AnomalyDetectedPatrolScope(resourceID, resourceType, metric string, value, baseline float64) PatrolScope {
	return PatrolScope{
		ResourceIDs:   []string{resourceID},
		ResourceTypes: patrolScopeResourceTypes(resourceType),
		Depth:         PatrolDepthNormal,
		Reason:        TriggerReasonAnomalyDetected,
		Context:       "Anomaly: " + metric,
		Priority:      triggerPriorityAnomaly,
	}
}

// AnomalyTriggeredPatrolScope creates a patrol scope for a significant anomaly event
// This is a simplified version that takes severity as a string for use in callbacks
func AnomalyTriggeredPatrolScope(resourceID, resourceType, metric, severity string) PatrolScope {
	priority := 60 // default
	if severity == "critical" {
		priority = 85
	} else if severity == "high" {
		priority = 70
	}
	return PatrolScope{
		ResourceIDs:   []string{resourceID},
		ResourceTypes: patrolScopeResourceTypes(resourceType),
		Depth:         PatrolDepthQuick,
		Reason:        TriggerReasonAnomalyDetected,
		Context:       "Anomaly: " + metric + " (" + severity + ")",
		Priority:      priority,
	}
}

// UserActionPatrolScope creates a patrol scope for a user action on a finding
func UserActionPatrolScope(findingID, resourceID, action string) PatrolScope {
	return PatrolScope{
		ResourceIDs: []string{resourceID},
		Depth:       PatrolDepthQuick,
		Reason:      TriggerReasonUserAction,
		Context:     "User action: " + action,
		Priority:    triggerPriorityUserAction,
		FindingID:   findingID,
	}
}

// ManualPatrolScope creates a patrol scope for a manual patrol request
func ManualPatrolScope(resourceIDs []string, depth PatrolDepth) PatrolScope {
	return PatrolScope{
		ResourceIDs: resourceIDs,
		Depth:       depth,
		Reason:      TriggerReasonManual,
		Context:     "Manual request",
		Priority:    triggerPriorityManual,
	}
}

// ScheduledPatrolScope creates a patrol scope for a scheduled patrol
func ScheduledPatrolScope() PatrolScope {
	return PatrolScope{
		Depth:    PatrolDepthNormal,
		Reason:   TriggerReasonScheduled,
		Context:  "Scheduled patrol",
		Priority: triggerPriorityScheduled,
	}
}

// FlappingPostmortemPatrolScope creates a patrol scope for an alert that the
// alerts manager has just transitioned into flapping suppression. The intent
// is to produce a finding that explains WHAT is flapping, WHY Pulse suppressed
// it, and what the operator can do about it -- so users see the diagnosis,
// not silence. Priority matches anomaly detection (medium-high) because a
// suppressed flap is operationally similar: signal Pulse already saw, that
// the user has not yet.
func FlappingPostmortemPatrolScope(alertIdentifier, resourceID, resourceType, alertType string) PatrolScope {
	context := "Flapping: " + alertType
	if alertType == "" {
		context = "Flapping detected"
	}
	return PatrolScope{
		ResourceIDs:     []string{resourceID},
		ResourceTypes:   patrolScopeResourceTypes(resourceType),
		Depth:           PatrolDepthQuick,
		Reason:          TriggerReasonAlertFlapping,
		Context:         context,
		Priority:        triggerPriorityAnomaly,
		AlertIdentifier: alertIdentifier,
	}
}