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.

26.1 KB
Raw Blame
/**
 * AI Intelligence Store
 *
 * Central store for managing AI intelligence state:
 * - Unified findings (alerts + AI findings)
 * - Canonical intelligence summary
 * - Remediation plans
 */

import { createSignal } from 'solid-js';
import { AIAPI } from '@/api/ai';
import {
  acknowledgeFinding,
  resolveFinding,
  snoozeFinding,
  dismissFinding,
  reopenFinding,
  setFindingNote,
  getPatrolFindings,
  type Finding as PatrolFinding,
  type CapacityForecast,
  type FindingFlapping,
  type InvestigationOutcome,
} from '@/api/patrol';
import type { ResourceCriticality } from '@/api/resourceOperatorState';
import type {
  UnifiedFindingRecord,
  InvestigationRecord,
  ApprovalRequest,
  ApprovalExecutionResult,
  ApprovalDecisionResult,
} from '@/api/ai';
import {
  doesFindingNeedAttention,
  hasPendingInvestigationFixApproval,
  isPatrolInvestigationFixApproval,
  sortFindingsForAttentionQueue,
} from '@/utils/aiFindingPresentation';
import { getApprovalExpiryTime, isLivePendingApproval } from '@/utils/approvalState';
import { sortPendingApprovalsByUrgency } from '@/utils/approvalRiskPresentation';
import { logger } from '@/utils/logger';
import type { IntelligenceSummary } from '@/types/aiIntelligence';
import { normalizeIntelligenceSummary } from './aiIntelligenceSummaryModel';
import { presentationPolicyIsDemoMode } from './sessionPresentationPolicy';
import { eventBus } from './events';

// ============================================
// Enum validation helpers
// ============================================

const VALID_INVESTIGATION_STATUSES = new Set<string>([
  'pending',
  'running',
  'completed',
  'failed',
  'needs_attention',
]);
// Keyed by the API union so type-check fails here, rather than the value being
// dropped as unknown, when the backend gains an outcome.
const INVESTIGATION_OUTCOME_KEYS: Record<InvestigationOutcome, true> = {
  resolved: true,
  fix_queued: true,
  fix_executed: true,
  fix_failed: true,
  fix_rejected: true,
  needs_attention: true,
  cannot_fix: true,
  timed_out: true,
  unclassified: true,
  interrupted: true,
  fix_verified: true,
  fix_verification_failed: true,
  fix_verification_unknown: true,
};
const VALID_INVESTIGATION_OUTCOMES = new Set<string>(Object.keys(INVESTIGATION_OUTCOME_KEYS));
const VALID_SEVERITIES = new Set<string>(['critical', 'warning', 'info', 'watch']);
const VALID_RESOURCE_CRITICALITIES = new Set<string>(['high', 'medium', 'low', '']);
const VALID_SOURCES = new Set<string>([
  'threshold',
  'ai-patrol',
  'ai-chat',
  'anomaly',
  'correlation',
  'forecast',
]);

function validateInvestigationStatus(
  value: string | undefined,
): UnifiedFinding['investigationStatus'] {
  if (!value) return undefined;
  return VALID_INVESTIGATION_STATUSES.has(value)
    ? (value as UnifiedFinding['investigationStatus'])
    : undefined;
}

function validateInvestigationOutcome(
  value: string | undefined,
): UnifiedFinding['investigationOutcome'] {
  if (!value) return undefined;
  return VALID_INVESTIGATION_OUTCOMES.has(value)
    ? (value as UnifiedFinding['investigationOutcome'])
    : undefined;
}

function validateSeverity(value: string | undefined): UnifiedFinding['severity'] {
  if (value && VALID_SEVERITIES.has(value)) return value as UnifiedFinding['severity'];
  return 'info';
}

function validateResourceCriticality(value: string | undefined): ResourceCriticality | undefined {
  if (value === undefined) return undefined;
  const normalized = String(value).trim().toLowerCase();
  if (VALID_RESOURCE_CRITICALITIES.has(normalized)) return normalized as ResourceCriticality;
  return undefined;
}

function validateSource(value: string | undefined): UnifiedFinding['source'] {
  if (value && VALID_SOURCES.has(value)) return value as UnifiedFinding['source'];
  return 'ai-patrol';
}

type FindingStatusInput = {
  status?: string;
  resolved_at?: string;
  snoozed_until?: string;
  dismissed_reason?: string;
  suppressed?: boolean;
};

function normalizeFindingStatus(item: FindingStatusInput, now: number): UnifiedFinding['status'] {
  if (
    item.status === 'active' ||
    item.status === 'resolved' ||
    item.status === 'dismissed' ||
    item.status === 'snoozed'
  ) {
    return item.status;
  }
  if (item.resolved_at) return 'resolved';
  if (item.snoozed_until && new Date(item.snoozed_until).getTime() > now) return 'snoozed';
  if (item.dismissed_reason || item.suppressed) return 'dismissed';
  return 'active';
}

// ============================================
// Unified Findings
// ============================================

export interface UnifiedFinding {
  id: string;
  key?: string;
  source: 'threshold' | 'ai-patrol' | 'ai-chat' | 'anomaly' | 'correlation' | 'forecast';
  resourceId: string;
  resourceName: string;
  resourceType: string;
  node?: string;
  resourceCriticality?: ResourceCriticality;
  alertIdentifier?: string;
  alertType?: string;
  isThreshold?: boolean;
  category: string;
  severity: 'critical' | 'warning' | 'info' | 'watch';
  title: string;
  description: string;
  impact?: string;
  previousResolvedFixSummary?: string;
  recommendation?: string;
  evidence?: string;
  // Patrol runtime failure cause (for example budget_exhausted) carried by
  // the persisted runtime finding; drives the setup action after a restart.
  failureCause?: string;
  aiConfidence?: number;
  detectedAt: string;
  lastSeenAt?: string;
  resolvedAt?: string;
  acknowledgedAt?: string;
  snoozedUntil?: string;
  dismissedReason?: string;
  userNote?: string;
  // remindAt is the will_fix_later wake-up deadline. UI uses it to (a) preview
  // the deadline at dismiss time and (b) badge dismissed rows with "Reminding
  // <date>" so the operator sees their pending commitment.
  remindAt?: string;
  // autoResolved is true when Pulse's own detection logic auto-cleared the
  // condition; false when the operator manually clicked Mark resolved. The
  // resolution-reason copy uses this to attribute who closed the loop.
  autoResolved?: boolean;
  status: 'active' | 'resolved' | 'dismissed' | 'snoozed';
  correlatedFindingIds?: string[];
  remediationPlanId?: string;
  // Investigation fields (Patrol mode)
  investigationSessionId?: string;
  investigationStatus?: 'pending' | 'running' | 'completed' | 'failed' | 'needs_attention';
  investigationOutcome?: InvestigationOutcome;
  lastInvestigatedAt?: string;
  investigationAttempts?: number;
  investigationRecord?: InvestigationRecord;
  loopState?: string;
  lifecycle?: Array<{
    at: string;
    type: string;
    message?: string;
    from?: string;
    to?: string;
    metadata?: Record<string, string>;
  }>;
  timesRaised?: number;
  regressionCount?: number;
  lastRegressionAt?: string;
  // Deterministic capacity forecast (trend/eta), computed by Patrol
  // independently of the model prose. Surfaced as a first-class urgency
  // signal on capacity-relevant findings.
  capacityForecast?: CapacityForecast;
  // flapping is set while the finding keeps switching between open and
  // resolved (four or more transitions in 24 hours). The lifecycle log holds
  // one collapsed "flapping" row instead of one row per transition.
  flapping?: FindingFlapping;
  // mirrorsAlertId / mirrorsAlertType identify the active alert this finding
  // restates. Surfaces fold such findings under the alert rather than listing
  // the same problem twice.
  mirrorsAlertId?: string;
  mirrorsAlertType?: string;
}

const [unifiedFindings, setUnifiedFindings] = createSignal<UnifiedFinding[]>([]);
const [findingsLoading, setFindingsLoading] = createSignal(false);
const [findingsError, setFindingsError] = createSignal<string | null>(null);
const [patrolFindings, setPatrolFindings] = createSignal<UnifiedFinding[]>([]);
const [patrolFindingsLoading, setPatrolFindingsLoading] = createSignal(false);
const [patrolFindingsError, setPatrolFindingsError] = createSignal<string | null>(null);
// Sticky preference: once a surface asks for include-resolved data,
// subsequent unscoped loadPatrolFindings calls (from polling, dashboard
// refresh, etc.) keep returning the expanded set. Otherwise the
// Resolved/All tabs would intermittently empty whenever a polling
// loadDashboardData overwrote the include-resolved load with the
// active-only default. Reset to false when nothing on screen needs the
// expanded set (no current call site does this; FindingsPanel's effect
// would set it back to true the moment Resolved/All becomes active).
let patrolFindingsIncludeResolvedPreference = false;
const PATROL_FINDINGS_HISTORY_LIMIT = 200;

function normalizeUnifiedFindingRecord(item: UnifiedFindingRecord, now: number): UnifiedFinding {
  const alertIdentifier = item.alertIdentifier;
  return {
    id: item.id,
    source: validateSource(item.source),
    resourceId: item.resource_id,
    resourceName: item.resource_name || item.resource_id,
    resourceType: item.resource_type || 'unknown',
    node: item.node,
    resourceCriticality: validateResourceCriticality(item.resource_criticality),
    alertIdentifier,
    isThreshold: Boolean(item.is_threshold || item.source === 'threshold'),
    category: item.category || 'general',
    severity: validateSeverity(item.severity),
    title: item.title,
    description: item.description,
    impact: item.impact,
    previousResolvedFixSummary: item.previous_resolved_fix_summary,
    recommendation: item.recommendation,
    evidence: item.evidence,
    aiConfidence: item.ai_confidence,
    detectedAt: item.detected_at,
    lastSeenAt: item.last_seen_at || item.detected_at,
    resolvedAt: item.resolved_at,
    acknowledgedAt: item.acknowledged_at,
    snoozedUntil: item.snoozed_until,
    dismissedReason: item.dismissed_reason,
    userNote: item.user_note,
    remindAt: item.remind_at,
    autoResolved: item.auto_resolved,
    status: normalizeFindingStatus(item, now),
    correlatedFindingIds: item.correlated_ids,
    remediationPlanId: item.remediation_id,
    investigationSessionId: item.investigation_session_id || '',
    investigationStatus: validateInvestigationStatus(item.investigation_status),
    investigationOutcome: validateInvestigationOutcome(item.investigation_outcome),
    lastInvestigatedAt: item.last_investigated_at || undefined,
    investigationAttempts: item.investigation_attempts || 0,
    investigationRecord: item.investigation_record,
    loopState: item.loop_state || undefined,
    lifecycle: item.lifecycle || [],
    timesRaised: item.times_raised || 0,
    regressionCount: item.regression_count || 0,
    lastRegressionAt: item.last_regression_at || undefined,
  };
}

function normalizePatrolFindingRecord(item: PatrolFinding, now: number): UnifiedFinding {
  return {
    id: item.id,
    key: item.key,
    source: 'ai-patrol',
    resourceId: item.resource_id,
    resourceName: item.resource_name || item.resource_id,
    resourceType: item.resource_type || 'unknown',
    node: item.node,
    resourceCriticality: validateResourceCriticality(item.resource_criticality),
    alertIdentifier: item.alertIdentifier,
    isThreshold: false,
    category: item.category || 'general',
    severity: validateSeverity(item.severity),
    title: item.title,
    description: item.description,
    impact: item.impact,
    previousResolvedFixSummary: item.previous_resolved_fix_summary,
    recommendation: item.recommendation,
    evidence: item.evidence,
    // The shared Finding type in api/patrol.ts does not declare the wire
    // field yet, so read it through a narrow local shape.
    failureCause: (item as { failure_cause?: string }).failure_cause,
    detectedAt: item.detected_at,
    lastSeenAt: item.last_seen_at || item.detected_at,
    resolvedAt: item.resolved_at,
    acknowledgedAt: item.acknowledged_at,
    snoozedUntil: item.snoozed_until,
    dismissedReason: item.dismissed_reason,
    userNote: item.user_note,
    remindAt: item.remind_at,
    autoResolved: item.auto_resolved,
    status: normalizeFindingStatus(item, now),
    investigationSessionId: item.investigation_session_id || '',
    investigationStatus: validateInvestigationStatus(item.investigation_status),
    investigationOutcome: validateInvestigationOutcome(item.investigation_outcome),
    lastInvestigatedAt: item.last_investigated_at || undefined,
    investigationAttempts: item.investigation_attempts || 0,
    investigationRecord: item.investigation_record,
    loopState: item.loop_state || undefined,
    lifecycle: item.lifecycle || [],
    timesRaised: item.times_raised || 0,
    regressionCount: item.regression_count || 0,
    lastRegressionAt: item.last_regression_at || undefined,
    capacityForecast: item.capacity_forecast,
    flapping: item.flapping,
    mirrorsAlertId: item.mirrors_alert_id || undefined,
    mirrorsAlertType: item.mirrors_alert_type || undefined,
  };
}

// Findings are plain JSON from the API, so two reads of an unchanged finding
// are equal key by key.
function isSameFindingValue(left: unknown, right: unknown): boolean {
  if (left === right) return true;
  if (typeof left !== 'object' || typeof right !== 'object' || left === null || right === null) {
    return false;
  }
  if (Array.isArray(left) !== Array.isArray(right)) return false;
  const leftRecord = left as Record<string, unknown>;
  const rightRecord = right as Record<string, unknown>;
  const leftKeys = Object.keys(leftRecord);
  if (leftKeys.length !== Object.keys(rightRecord).length) return false;
  return leftKeys.every(
    (key) =>
      Object.prototype.hasOwnProperty.call(rightRecord, key) &&
      isSameFindingValue(leftRecord[key], rightRecord[key]),
  );
}

// Findings are re-read every few seconds (the open-work badges every 30s,
// the Patrol page every 60s), and every read parses new objects. Lists render
// findings with <For>, which keys rows by object, so each poll rebuilt every
// row and remounted an open review. A finding that comes back unchanged keeps
// its object, and a read that changes nothing keeps the list.
function reuseIdenticalFindings(
  previous: UnifiedFinding[],
  next: UnifiedFinding[],
): UnifiedFinding[] {
  const previousById = new Map(previous.map((finding) => [finding.id, finding]));
  let changed = next.length !== previous.length;
  const merged = next.map((finding, index) => {
    const prior = previousById.get(finding.id);
    if (prior && isSameFindingValue(prior, finding)) {
      if (prior !== previous[index]) changed = true;
      return prior;
    }
    changed = true;
    return finding;
  });
  return changed ? merged : previous;
}

// ============================================
// Pending Approvals
// ============================================

const [pendingApprovals, setPendingApprovals] = createSignal<ApprovalRequest[]>([]);
const [approvalsError, setApprovalsError] = createSignal<string | null>(null);
const [pendingApprovalsNow, setPendingApprovalsNow] = createSignal(Date.now());

let pendingApprovalExpiryTimer: ReturnType<typeof setTimeout> | undefined;

function syncPendingApprovalExpiryTimer(approvals: ApprovalRequest[]) {
  if (pendingApprovalExpiryTimer) {
    clearTimeout(pendingApprovalExpiryTimer);
    pendingApprovalExpiryTimer = undefined;
  }

  const now = Date.now();
  setPendingApprovalsNow(now);

  let nextExpiry: number | null = null;
  for (const approval of approvals) {
    if (approval.status !== 'pending') {
      continue;
    }

    const expiry = getApprovalExpiryTime(approval);
    if (expiry === null || expiry <= now) {
      continue;
    }

    if (nextExpiry === null || expiry < nextExpiry) {
      nextExpiry = expiry;
    }
  }

  if (nextExpiry === null) {
    return;
  }

  pendingApprovalExpiryTimer = setTimeout(
    () => {
      syncPendingApprovalExpiryTimer(pendingApprovals());
    },
    Math.max(0, nextExpiry - Date.now() + 1),
  );
}

function setPendingApprovalsWithExpiryTracking(approvals: ApprovalRequest[]) {
  setPendingApprovals(approvals);
  syncPendingApprovalExpiryTimer(approvals);
}

function getLivePendingApprovals() {
  const now = pendingApprovalsNow();
  return pendingApprovals().filter((approval) => isLivePendingApproval(approval, now));
}

function getLivePatrolPendingApprovals() {
  return getLivePendingApprovals().filter(isPatrolInvestigationFixApproval);
}

function getFindingsWithPendingApprovalsFor(findings: UnifiedFinding[]) {
  const approvals = getLivePatrolPendingApprovals();
  const approvalOrder = new Map(
    sortPendingApprovalsByUrgency(approvals).map((approval, index) => [approval.targetId, index]),
  );
  return findings
    .filter((finding) => hasPendingInvestigationFixApproval(finding.id, approvals))
    .sort(
      (a, b) =>
        (approvalOrder.get(a.id) ?? Number.MAX_SAFE_INTEGER) -
        (approvalOrder.get(b.id) ?? Number.MAX_SAFE_INTEGER),
    );
}

function getFindingsNeedingAttentionFor(findings: UnifiedFinding[]) {
  const approvals = getLivePatrolPendingApprovals();
  return sortFindingsForAttentionQueue(
    findings.filter((finding) => doesFindingNeedAttention(finding, approvals)),
  );
}

function getPatrolOpenWorkCount(): number {
  const activeFindingIds = new Set(
    patrolFindings()
      .filter((finding) => finding.status === 'active')
      .map((finding) => finding.id),
  );
  for (const approval of getLivePatrolPendingApprovals()) {
    if (approval.targetId) {
      activeFindingIds.add(approval.targetId);
    }
  }
  return activeFindingIds.size;
}

// ============================================
// Canonical Intelligence Summary
// ============================================

const [intelligenceSummary, setIntelligenceSummary] = createSignal<IntelligenceSummary | null>(
  null,
);

// ============================================
// Org Switch Reset
// ============================================

eventBus.on('org_switched', () => {
  setUnifiedFindings([]);
  setFindingsLoading(false);
  setFindingsError(null);
  setPatrolFindings([]);
  setPatrolFindingsLoading(false);
  setPatrolFindingsError(null);
  patrolFindingsIncludeResolvedPreference = false;
  setPendingApprovalsWithExpiryTracking([]);
  setApprovalsError(null);
  setIntelligenceSummary(null);
});

// ============================================
// Store API
// ============================================

export const aiIntelligenceStore = {
  // Unified Findings
  get findings() {
    return unifiedFindings();
  },
  get findingsLoading() {
    return findingsLoading();
  },
  get findingsError() {
    return findingsError();
  },
  findingsSignal: unifiedFindings,
  get patrolFindings() {
    return patrolFindings();
  },
  get patrolFindingsLoading() {
    return patrolFindingsLoading();
  },
  get patrolFindingsError() {
    return patrolFindingsError();
  },
  patrolFindingsSignal: patrolFindings,

  async loadFindings() {
    setFindingsLoading(true);
    setFindingsError(null);
    try {
      const resp = await AIAPI.getUnifiedFindings({ includeResolved: true });
      if (!resp) return;
      const now = Date.now();

      setUnifiedFindings((previous) =>
        reuseIdenticalFindings(
          previous,
          (resp.findings || []).map((item) => normalizeUnifiedFindingRecord(item, now)),
        ),
      );
    } catch (e) {
      logger.error('Failed to load unified findings:', e);
      setFindingsError(e instanceof Error ? e.message : 'Failed to load findings');
    } finally {
      setFindingsLoading(false);
    }
  },

  async loadPatrolFindings(options?: { includeResolved?: boolean }) {
    // Sticky preference: once a caller has explicitly asked for the
    // expanded set, treat all subsequent loads (including unscoped
    // polling refreshes) as expanded so the Resolved/All tab data does
    // not blink to empty between polls. The Patrol findings endpoint
    // is cheap; the per-finding cap keeps the payload bounded.
    if (options?.includeResolved) {
      patrolFindingsIncludeResolvedPreference = true;
    }
    const includeResolved =
      options?.includeResolved === true || patrolFindingsIncludeResolvedPreference;
    setPatrolFindingsLoading(true);
    setPatrolFindingsError(null);
    try {
      const findings = await getPatrolFindings(
        includeResolved
          ? { includeResolved: true, limit: PATROL_FINDINGS_HISTORY_LIMIT }
          : undefined,
      );
      const now = Date.now();
      setPatrolFindings((previous) =>
        reuseIdenticalFindings(
          previous,
          findings.map((item) => normalizePatrolFindingRecord(item, now)),
        ),
      );
    } catch (e) {
      logger.error('Failed to load Patrol findings:', e);
      setPatrolFindingsError(e instanceof Error ? e.message : 'Failed to load Patrol findings');
    } finally {
      setPatrolFindingsLoading(false);
    }
  },

  async acknowledgeFinding(findingId: string) {
    try {
      await acknowledgeFinding(findingId);
      await Promise.all([this.loadFindings(), this.loadPatrolFindings()]);
      return true;
    } catch (e) {
      logger.error('Failed to acknowledge finding:', e);
      return false;
    }
  },

  // Manually mark a finding as resolved when the operator has fixed it
  // out-of-band. Mirrors the existing acknowledge/snooze/dismiss store
  // pattern: call the server, refresh both finding sources, swallow errors
  // into a boolean for the caller's UX feedback.
  async resolveFinding(findingId: string) {
    try {
      await resolveFinding(findingId);
      await Promise.all([this.loadFindings(), this.loadPatrolFindings()]);
      return true;
    } catch (e) {
      logger.error('Failed to resolve finding:', e);
      return false;
    }
  },

  async snoozeFinding(findingId: string, durationHours: number) {
    try {
      await snoozeFinding(findingId, durationHours);
      await Promise.all([this.loadFindings(), this.loadPatrolFindings()]);
      return true;
    } catch (e) {
      logger.error('Failed to snooze finding:', e);
      return false;
    }
  },

  async dismissFinding(
    findingId: string,
    reason: 'not_an_issue' | 'expected_behavior' | 'will_fix_later',
    note?: string,
  ) {
    try {
      await dismissFinding(findingId, reason, note);
      await Promise.all([this.loadFindings(), this.loadPatrolFindings()]);
      return true;
    } catch (e) {
      logger.error('Failed to dismiss finding:', e);
      return false;
    }
  },

  async reopenFinding(findingId: string) {
    try {
      await reopenFinding(findingId);
      await Promise.all([this.loadFindings(), this.loadPatrolFindings({ includeResolved: true })]);
      return true;
    } catch (e) {
      logger.error('Failed to reopen finding:', e);
      return false;
    }
  },

  async setFindingNote(findingId: string, note: string) {
    try {
      await setFindingNote(findingId, note);
      // Update local state immediately for responsiveness
      setUnifiedFindings((prev) =>
        prev.map((f) => (f.id === findingId ? { ...f, userNote: note } : f)),
      );
      setPatrolFindings((prev) =>
        prev.map((f) => (f.id === findingId ? { ...f, userNote: note } : f)),
      );
      return true;
    } catch (e) {
      logger.error('Failed to set finding note:', e);
      return false;
    }
  },

  // Pending Approvals
  get pendingApprovals() {
    return sortPendingApprovalsByUrgency(getLivePendingApprovals());
  },
  get patrolPendingApprovals() {
    return sortPendingApprovalsByUrgency(getLivePatrolPendingApprovals());
  },
  get approvalsError() {
    return approvalsError();
  },
  pendingApprovalsSignal: getLivePendingApprovals,

  get pendingApprovalCount() {
    return getLivePendingApprovals().length;
  },
  get patrolPendingApprovalCount() {
    return getLivePatrolPendingApprovals().length;
  },

  get findingsWithPendingApprovals() {
    return getFindingsWithPendingApprovalsFor(unifiedFindings());
  },
  get patrolFindingsWithPendingApprovals() {
    return getFindingsWithPendingApprovalsFor(patrolFindings());
  },

  get findingsNeedingAttention() {
    return getFindingsNeedingAttentionFor(unifiedFindings());
  },
  get patrolFindingsNeedingAttention() {
    return getFindingsNeedingAttentionFor(patrolFindings());
  },

  get needsAttentionCount() {
    return this.findingsNeedingAttention.length;
  },
  get patrolNeedsAttentionCount() {
    return this.patrolFindingsNeedingAttention.length;
  },
  get patrolOpenWorkCount() {
    return getPatrolOpenWorkCount();
  },

  async loadPendingApprovals() {
    setApprovalsError(null);
    if (presentationPolicyIsDemoMode()) {
      setPendingApprovalsWithExpiryTracking([]);
      return;
    }
    try {
      const approvals = await AIAPI.getPendingApprovals();
      setPendingApprovalsWithExpiryTracking(approvals);
    } catch (e) {
      logger.error('Failed to load pending approvals:', e);
      setApprovalsError(e instanceof Error ? e.message : 'Failed to load approvals');
    }
  },

  async approveInvestigationFix(approvalId: string): Promise<ApprovalExecutionResult | null> {
    const result = await this.approvePendingApproval(approvalId);
    return result as ApprovalExecutionResult | null;
  },

  async approvePendingApproval(approvalId: string): Promise<ApprovalDecisionResult | null> {
    try {
      const result = await AIAPI.approvePendingApproval(approvalId);
      await this.loadPendingApprovals();
      await Promise.all([this.loadFindings(), this.loadPatrolFindings()]);
      return result;
    } catch (e) {
      logger.error('Failed to approve fix:', e);
      return null;
    }
  },

  async denyInvestigationFix(approvalId: string, reason?: string) {
    return this.denyPendingApproval(approvalId, reason);
  },

  async denyPendingApproval(approvalId: string, reason?: string) {
    try {
      await AIAPI.denyPendingApproval(approvalId, reason);
      await this.loadPendingApprovals();
      await Promise.all([this.loadFindings(), this.loadPatrolFindings()]);
      return true;
    } catch (e) {
      logger.error('Failed to deny fix:', e);
      return false;
    }
  },

  // Canonical Intelligence Summary
  get intelligenceSummary() {
    return intelligenceSummary();
  },
  intelligenceSummarySignal: intelligenceSummary,

  async loadDashboardData() {
    await Promise.all([
      this.loadIntelligenceSummary(),
      this.loadFindings(),
      this.loadPatrolFindings(),
      this.loadPendingApprovals(),
    ]);
  },

  async loadIntelligenceSummary() {
    try {
      const summary = await AIAPI.getIntelligenceSummary();
      setIntelligenceSummary(normalizeIntelligenceSummary(summary));
      return summary;
    } catch (e) {
      logger.error('Failed to load intelligence summary:', e);
      setIntelligenceSummary(null);
      return null;
    }
  },
};

export default aiIntelligenceStore;