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.

55.9 KB
Raw Blame
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
import {
  buildPatrolFindingDisplayGroups,
  buildFindingFilterOptions,
  formatFindingForClipboard,
  formatFindingLifecycleType,
  formatOperatorStateDismissCauseLabel,
  getOperatorStateDismissCause,
  formatFindingLoopState,
  getFindingActiveRuntimeSortOrder,
  getFindingEmptyStateCopy,
  getFindingManualControlsPresentation,
  getFindingPrimaryActionPresentation,
  getFindingSubjectPresentation,
  getFindingTitlePresentation,
  getFindingPatrolWorkflowPresentation,
  getPatrolFindingIssueCountLabel,
  getPatrolFindingClassification,
  getFindingSeverityCompactLabel,
  getFindingSeveritySortOrder,
  getFindingResolutionReason,
  getFindingRecencyPresentation,
  getFindingReminderPresentation,
  getFindingSnoozePresentation,
  getFindingLoopStateBadgeClasses,
  getFindingLoopStateBadgeTone,
  getFindingSeverityBadgeClasses,
  getFindingSeverityPresentation,
  getFindingStatusBadgeClasses,
  getFindingStatusBadgeTone,
  getFindingStatusLabel,
  getFindingSeverityToneClasses,
  getPatrolFindingsBadgePresentation,
  getFindingSourceBadgeClasses,
  getFindingSourceBadgeTone,
  getFindingSourceLabel,
  hasFindingInvestigationDetails,
  hasPendingInvestigationFixApproval,
  isPatrolInvestigationFixApproval,
  getInvestigationOutcomeBadgeClasses,
  getInvestigationOutcomeBadgeTone,
  getInvestigationOutcomeLabel,
  getInvestigationOutcomeSortOrder,
  getInvestigationStatusLabel,
  getInvestigationStatusBadgeClasses,
  getInvestigationStatusBadgeTone,
  getInvestigationConfidenceBadgeTone,
  doesFindingNeedAttention,
  reuseIdenticalPatrolFindingDisplayGroups,
} from '@/utils/aiFindingPresentation';
import { PATROL_PROVIDER_SETTINGS_ACTION } from '@/utils/patrolRuntimeActions';

const findingsPanelSource = readFileSync(resolve(__dirname, '..', 'FindingsPanel.tsx'), 'utf-8');
const patrolWorkspaceSource = readFileSync(
  resolve(__dirname, '..', '..', '..', 'features', 'patrol', 'PatrolIntelligenceWorkspace.tsx'),
  'utf-8',
);
const aiFindingPresentationSource = readFileSync(
  resolve(__dirname, '..', '..', '..', 'utils', 'aiFindingPresentation.ts'),
  'utf-8',
);

describe('FindingsPanel source wiring', () => {
  it('passes stale Patrol coverage into the current-work empty-state presenter', () => {
    expect(findingsPanelSource).toContain('coverageStale?: boolean');
    expect(findingsPanelSource).toContain('coverageStale: props.coverageStale');
    expect(patrolWorkspaceSource).toContain('coverageStale={coverageStale()}');
  });

  // The panel renders what it is handed (FindingsPanel.links.test.tsx covers the
  // rendering); only the workspace decides to hand the Pro handoff and the
  // Watch-only nudge over, and which findings source to read.
  it('hands the Pro handoff, the Watch-only nudge and the Patrol source from the Patrol workspace', () => {
    expect(patrolWorkspaceSource).toContain('getPatrolProInvestigationHandoff');
    expect(patrolWorkspaceSource).toContain('patrolProHandoff=');
    expect(patrolWorkspaceSource).toContain('getPatrolWatchOnlyInvestigationNudge');
    expect(patrolWorkspaceSource).toContain("handleAutonomyChange('approval')");
    expect(patrolWorkspaceSource).toContain('findingsSource="patrol"');
  });

  it('surfaces only actionable Patrol workflow states from the shared presentation model', () => {
    // Collapsed Patrol rows should stay issue-focused. Workflow state can
    // drive a direct approval action, but it must not add process badges such
    // as "detected", "investigating", or "verify outcome" to the scan view.
    expect(findingsPanelSource).toContain('getFindingPatrolWorkflowPresentation');
    expect(findingsPanelSource).toContain(
      'getFindingPatrolWorkflowPresentation(finding, aiIntelligenceStore.patrolPendingApprovals)',
    );
    expect(findingsPanelSource).toContain("workflow?.stage === 'approval'");
    expect(findingsPanelSource).not.toContain("workflow.stage === 'investigating'");
    expect(findingsPanelSource).not.toContain("workflow.stage === 'verification'");
    expect(findingsPanelSource).not.toContain("workflow.stage === 'attention'");
    expect(findingsPanelSource).not.toContain("workflow.stage === 'recorded'");
    expect(findingsPanelSource).not.toContain("workflow.stage === 'paused'");
  });

  it('keeps approval decisions inside the selected Patrol issue review', () => {
    expect(findingsPanelSource).toContain('const collapsedApprovalAction = () => {');
    expect(findingsPanelSource).toContain("workflow?.stage === 'approval'");
    expect(findingsPanelSource).toContain(
      '!isPatrolFindingsSource() && expandedId() !== finding.id',
    );
    expect(findingsPanelSource).toContain('title={action().detail}');
    expect(findingsPanelSource).toContain('{action().label}');
  });
});

describe('aiFindingPresentation', () => {
  describe('severity presentation', () => {
    it('has correct sort order for critical', () => {
      expect(getFindingSeveritySortOrder('critical')).toBe(0);
    });

    it('has correct sort order for warning', () => {
      expect(getFindingSeveritySortOrder('warning')).toBe(1);
    });

    it('has correct sort order for watch', () => {
      expect(getFindingSeveritySortOrder('watch')).toBe(2);
    });

    it('has correct sort order for info', () => {
      expect(getFindingSeveritySortOrder('info')).toBe(3);
    });

    it('prioritizes active patrol runtime findings within the same severity tier', () => {
      expect(
        getFindingActiveRuntimeSortOrder({
          status: 'active',
          resourceId: 'ai-service',
          resourceName: 'Pulse Patrol Service',
          title: 'Pulse Patrol: Provider billing or quota issue',
        }),
      ).toBe(0);
      expect(
        getFindingActiveRuntimeSortOrder({
          status: 'active',
          resourceId: 'vm-101',
          resourceName: 'db-01',
          title: 'Disk nearly full',
        }),
      ).toBe(1);
    });

    it('returns compact severity labels', () => {
      expect(getFindingSeverityCompactLabel('critical')).toBe('CRIT');
      expect(getFindingSeverityCompactLabel('warning')).toBe('WARN');
      expect(getFindingSeverityCompactLabel('watch')).toBe('WATCH');
      expect(getFindingSeverityCompactLabel('info')).toBe('INFO');
    });
  });

  describe('sourceLabels', () => {
    it('has correct label for threshold', () => {
      expect(getFindingSourceLabel('threshold')).toBe('Alert');
    });

    it('has correct label for ai-patrol', () => {
      expect(getFindingSourceLabel('ai-patrol')).toBe('Pulse Patrol');
    });

    it('has correct label for anomaly', () => {
      expect(getFindingSourceLabel('anomaly')).toBe('Anomaly');
    });

    it('has correct label for ai-chat', () => {
      expect(getFindingSourceLabel('ai-chat')).toBe('Pulse Assistant');
    });

    it('has correct label for correlation', () => {
      expect(getFindingSourceLabel('correlation')).toBe('Correlation');
    });

    it('has correct label for forecast', () => {
      expect(getFindingSourceLabel('forecast')).toBe('Forecast');
    });
  });

  describe('severityColors', () => {
    it('contains critical color classes', () => {
      expect(getFindingSeverityBadgeClasses('critical')).toContain('red-200');
      expect(getFindingSeverityBadgeClasses('critical')).toContain('red-700');
    });

    it('contains warning color classes', () => {
      expect(getFindingSeverityBadgeClasses('warning')).toContain('amber-200');
      expect(getFindingSeverityBadgeClasses('warning')).toContain('amber-700');
    });

    it('contains info color classes', () => {
      expect(getFindingSeverityBadgeClasses('info')).toContain('blue-200');
      expect(getFindingSeverityBadgeClasses('info')).toContain('blue-700');
    });

    it('contains watch color classes', () => {
      expect(getFindingSeverityBadgeClasses('watch')).toContain('bg-surface-alt');
    });

    it('contains compact tone classes for critical severity', () => {
      expect(getFindingSeverityToneClasses('critical')).toContain('bg-red-100');
    });

    it('keeps ordinary infrastructure severity badges generic', () => {
      expect(
        getFindingSeverityPresentation({
          severity: 'warning',
          resourceId: 'vm-101',
          resourceName: 'db-01',
          title: 'Disk nearly full',
        }),
      ).toEqual({
        label: 'warning',
        badgeClasses: getFindingSeverityBadgeClasses('warning'),
        badgeTone: 'warning',
        uppercase: true,
      });
    });

    it('renders runtime-qualified severity badges for patrol runtime findings', () => {
      expect(
        getFindingSeverityPresentation({
          severity: 'warning',
          resourceId: 'ai-service',
          resourceName: 'Pulse Patrol Service',
          title: 'Pulse Patrol: Provider billing or quota issue',
        }),
      ).toEqual({
        label: 'Runtime issue',
        badgeClasses:
          'border-sky-200 bg-sky-50 text-sky-700 dark:border-sky-800 dark:bg-sky-900/25 dark:text-sky-300',
        badgeTone: 'sky',
        uppercase: false,
      });
    });

    it('uses patrol runtime badge tones when only runtime findings are active', () => {
      expect(
        getPatrolFindingsBadgePresentation([
          {
            status: 'active',
            severity: 'warning',
            resourceId: 'ai-service',
            resourceName: 'Pulse Patrol Service',
            title: 'Pulse Patrol: Provider billing or quota issue',
          },
        ]),
      ).toEqual({
        tone: 'info',
      });
    });

    it('keeps warning tones for infrastructure warning findings', () => {
      expect(
        getPatrolFindingsBadgePresentation([
          {
            status: 'active',
            severity: 'warning',
            resourceId: 'vm-101',
            resourceName: 'db-01',
            title: 'Disk nearly full',
          },
        ]),
      ).toEqual({
        tone: 'warning',
      });
    });
  });

  describe('findingStatusPresentation', () => {
    it('returns canonical badge classes', () => {
      expect(getFindingStatusBadgeClasses('resolved')).toContain('green');
      expect(getFindingStatusBadgeTone('resolved')).toBe('success');
      expect(getFindingStatusBadgeClasses('snoozed')).toContain('blue');
      expect(getFindingStatusBadgeTone('snoozed')).toBe('info');
      expect(getFindingStatusBadgeClasses('dismissed')).toContain('bg-surface-alt');
      expect(getFindingStatusBadgeTone('dismissed')).toBe('muted');
      expect(getFindingStatusBadgeClasses('unexpected')).toContain('bg-surface-alt');
      expect(getFindingStatusBadgeTone('unexpected')).toBe('muted');
    });

    it('returns canonical labels', () => {
      expect(getFindingStatusLabel('resolved')).toBe('Resolved');
      expect(getFindingStatusLabel('snoozed')).toBe('Snoozed');
      expect(getFindingStatusLabel('dismissed')).toBe('Dismissed');
      expect(getFindingStatusLabel('unexpected')).toBe('Dismissed');
    });
  });

  describe('findingRecencyPresentation', () => {
    it('uses last seen recency for active findings', () => {
      expect(
        getFindingRecencyPresentation({
          status: 'active',
          detectedAt: '2026-03-01T00:00:00Z',
          lastSeenAt: '2026-03-25T12:00:00Z',
        }),
      ).toEqual({
        label: 'last seen',
        timestamp: '2026-03-25T12:00:00Z',
      });
    });

    it('falls back to detected recency for inactive findings', () => {
      expect(
        getFindingRecencyPresentation({
          status: 'resolved',
          detectedAt: '2026-03-01T00:00:00Z',
          lastSeenAt: '2026-03-25T12:00:00Z',
        }),
      ).toEqual({
        label: 'detected',
        timestamp: '2026-03-01T00:00:00Z',
      });
    });
  });

  describe('findingReminderAndSnoozePresentation', () => {
    const now = Date.parse('2026-03-25T12:00:00Z');

    it('counts down to a will_fix_later reminder instead of reading it as just now', () => {
      const reminder = getFindingReminderPresentation(
        { dismissedReason: 'will_fix_later', remindAt: '2026-03-31T12:00:00Z' },
        now,
        false,
      );
      expect(reminder?.label).toBe('Reminding in 6d');
      expect(reminder?.title).toMatch(
        /^Reminder due .+\. Pulse brings this finding back on its first reminder check after that\.$/,
      );
      expect(reminder?.title).not.toContain('still tripping');
      expect(
        getFindingReminderPresentation(
          { dismissedReason: 'will_fix_later', remindAt: '2026-03-25T15:00:00Z' },
          now,
          false,
        )?.label,
      ).toBe('Reminding in 3h');
    });

    it('calls a reminder overdue once the Overdue commitments list holds it', () => {
      const reminder = getFindingReminderPresentation(
        { dismissedReason: 'will_fix_later', remindAt: '2026-03-25T11:00:00Z' },
        now,
        true,
      );
      expect(reminder?.label).toBe('Reminder overdue');
      expect(reminder?.title).toMatch(
        /^Reminder was due .+\. Pulse brings this finding back on its next reminder check\.$/,
      );
      // Past the deadline but not yet on the list (it is sampled on the next
      // clock tick), so the chip and filter would not count it yet.
      expect(
        getFindingReminderPresentation(
          { dismissedReason: 'will_fix_later', remindAt: '2026-03-25T11:59:50Z' },
          now,
          false,
        )?.label,
      ).toBe('Reminder due');
    });

    it('shows no reminder for other dismissals or an unusable remind time', () => {
      expect(
        getFindingReminderPresentation(
          { dismissedReason: 'not_an_issue', remindAt: '2026-03-31T12:00:00Z' },
          now,
          false,
        ),
      ).toBeNull();
      expect(
        getFindingReminderPresentation({ dismissedReason: 'will_fix_later' }, now, false),
      ).toBeNull();
      expect(
        getFindingReminderPresentation(
          { dismissedReason: 'will_fix_later', remindAt: 'not a date' },
          now,
          true,
        ),
      ).toBeNull();
    });

    it('counts down to the end of a snooze and keeps the exact time on hover', () => {
      const snooze = getFindingSnoozePresentation(
        { status: 'snoozed', snoozedUntil: '2026-03-25T15:00:00Z' },
        now,
      );
      expect(snooze?.label).toBe('snoozed, returns in 3h');
      expect(snooze?.title).toMatch(/^Snoozed until .+/);
      expect(
        getFindingSnoozePresentation(
          { status: 'snoozed', snoozedUntil: '2026-03-25T11:00:00Z' },
          now,
        )?.label,
      ).toBe('snooze ended');
      expect(
        getFindingSnoozePresentation(
          { status: 'active', snoozedUntil: '2026-03-25T15:00:00Z' },
          now,
        ),
      ).toBeNull();
    });
  });

  describe('patrolFindingClassification', () => {
    it('describes grouped Patrol findings as issues instead of internal signals', () => {
      expect(getPatrolFindingIssueCountLabel(0)).toBe('0 issues');
      expect(getPatrolFindingIssueCountLabel(1)).toBe('1 issue');
      expect(getPatrolFindingIssueCountLabel(2)).toBe('2 issues');
      expect(getPatrolFindingIssueCountLabel(2.9)).toBe('2 issues');
      expect(aiFindingPresentationSource).toContain('getPatrolFindingIssueCountLabel');
      expect(aiFindingPresentationSource).not.toContain('getPatrolFindingSignalCountLabel');
    });

    it('classifies ai-service findings as patrol runtime issues', () => {
      expect(
        getPatrolFindingClassification({
          resourceId: 'ai-service',
          resourceName: 'Pulse Patrol Service',
          title: 'Pulse Patrol: Provider billing or quota issue',
        }),
      ).toEqual({
        kind: 'runtime',
        label: 'Patrol runtime',
        badgeClasses:
          'border-sky-200 bg-sky-50 text-sky-700 dark:border-sky-800 dark:bg-sky-900/25 dark:text-sky-300',
      });
    });

    it('keeps ordinary findings classified as infrastructure', () => {
      expect(
        getPatrolFindingClassification({
          resourceId: 'vm-101',
          resourceName: 'db-01',
          title: 'Disk nearly full',
        }),
      ).toEqual({
        kind: 'infrastructure',
        label: 'Infrastructure',
        badgeClasses: 'border-border bg-surface-alt text-muted',
      });
    });
  });

  describe('findingSubjectPresentation', () => {
    it('renders patrol-owned service findings as patrol runtime', () => {
      expect(
        getFindingSubjectPresentation({
          resourceId: 'ai-service',
          resourceName: 'Pulse Patrol Service',
          resourceType: 'service',
          title: 'Pulse Patrol: Provider billing or quota issue',
        }),
      ).toEqual({
        label: 'Patrol runtime',
      });
    });

    it('normalizes ordinary resource type labels', () => {
      expect(
        getFindingSubjectPresentation({
          resourceId: 'ct-101',
          resourceName: 'app-ct',
          resourceType: 'system-container',
          title: 'Disk nearly full',
        }),
      ).toEqual({
        label: 'app-ct (system-container)',
      });
    });
  });

  describe('findingPrimaryActionPresentation', () => {
    it('offers Patrol provider settings as the primary action for Patrol runtime findings', () => {
      expect(
        getFindingPrimaryActionPresentation({
          resourceId: 'ai-service',
          resourceName: 'Pulse Patrol Service',
          title: 'Pulse Patrol: Provider billing or quota issue',
        }),
      ).toEqual(PATROL_PROVIDER_SETTINGS_ACTION);
    });

    it('does not expose Patrol provider settings as the primary action for infrastructure findings', () => {
      expect(
        getFindingPrimaryActionPresentation({
          resourceId: 'vm-101',
          resourceName: 'db-01',
          title: 'Disk nearly full',
        }),
      ).toBeUndefined();
    });

    it('keeps Patrol runtime actions keyed to the shared runtime identity even without product-prefixed titles', () => {
      expect(
        getFindingPrimaryActionPresentation({
          resourceId: 'ai-service',
          resourceName: 'Pulse Patrol Service',
          title: 'Provider billing or quota issue',
        }),
      ).toEqual(PATROL_PROVIDER_SETTINGS_ACTION);
    });
  });

  describe('findingTitlePresentation', () => {
    it('normalizes legacy Patrol runtime credit titles', () => {
      expect(
        getFindingTitlePresentation({
          resourceId: 'ai-service',
          resourceName: 'Pulse Patrol Service',
          title: 'Pulse Patrol: Insufficient API credits',
        }),
      ).toEqual({
        label: 'Provider billing or quota issue',
      });
    });

    it('keeps infrastructure finding titles unchanged', () => {
      expect(
        getFindingTitlePresentation({
          resourceId: 'vm-101',
          resourceName: 'db-01',
          title: 'Disk nearly full',
        }),
      ).toEqual({
        label: 'Disk nearly full',
      });
    });
  });

  describe('findingManualControlsPresentation', () => {
    it('disables generic feedback controls for patrol runtime findings', () => {
      expect(
        getFindingManualControlsPresentation({
          resourceId: 'ai-service',
          resourceName: 'Pulse Patrol Service',
          title: 'Pulse Patrol: Provider billing or quota issue',
        }),
      ).toEqual({
        acknowledge: false,
        snooze: false,
        dismiss: false,
      });
    });

    it('keeps generic feedback controls for infrastructure findings', () => {
      expect(
        getFindingManualControlsPresentation({
          resourceId: 'vm-101',
          resourceName: 'db-01',
          title: 'Disk nearly full',
        }),
      ).toEqual({
        acknowledge: true,
        snooze: true,
        dismiss: true,
      });
    });
  });

  describe('filterPresentation', () => {
    it('builds canonical filter options', () => {
      expect(
        buildFindingFilterOptions({
          needsAttentionCount: 2,
          pendingApprovalCount: 1,
        }),
      ).toEqual([
        { value: 'active', label: 'Active' },
        { value: 'all', label: 'All' },
        { value: 'resolved', label: 'Resolved' },
        { value: 'attention', label: 'Needs Attention', tone: 'warning', count: 2 },
        { value: 'approvals', label: 'Approvals', tone: 'warning', count: 1 },
      ]);
    });

    it('returns canonical empty-state copy', () => {
      expect(getFindingEmptyStateCopy('active')).toEqual({
        title: 'No active findings',
        body: 'Your infrastructure looks healthy!',
      });
      expect(getFindingEmptyStateCopy('attention')).toEqual({
        title: 'No findings need attention right now.',
      });
      expect(getFindingEmptyStateCopy('approvals')).toEqual({
        title: 'No pending approvals.',
      });
      expect(getFindingEmptyStateCopy('resolved')).toEqual({
        title: 'No Patrol findings to display',
      });
    });
  });

  describe('patrol empty-state presentation', () => {
    it('passes Patrol history regression evidence into the findings empty-state helper', () => {
      expect(findingsPanelSource).toContain('historicalRegressionCount?: number');
      expect(findingsPanelSource).toContain(
        'historicalRegressionCount: props.historicalRegressionCount',
      );
      expect(patrolWorkspaceSource).toContain(
        'historicalRegressionCount={state.historicalRegressionCount()}',
      );
    });

    it('uses an informational icon for non-warning Patrol empty-state context', () => {
      expect(findingsPanelSource).toContain("import InfoIcon from 'lucide-solid/icons/info';");
      expect(findingsPanelSource).toContain("when={emptyStateCopy().tone === 'warning'}");
      expect(findingsPanelSource).toContain(
        '<InfoIcon class={`w-10 h-10 ${emptyStateTone().iconClass}`} />',
      );
    });

    it('only shows the sort control when there are multiple Patrol findings to sort', () => {
      expect(findingsPanelSource).toContain('patrolFindingDisplayGroups().length > 1');
      expect(findingsPanelSource).toContain('FormSelect');
      expect(findingsPanelSource).toContain('label="Sort findings"');
      expect(findingsPanelSource).toContain('<option value="severity">By Severity</option>');
      expect(findingsPanelSource).not.toContain('<select');
    });

    it('keeps Patrol review and sort controls touch-sized on phones', () => {
      expect(findingsPanelSource).toContain(
        'class="inline-flex min-h-11 items-center gap-1 rounded-sm border border-border',
      );
      expect(findingsPanelSource).toContain(
        'selectBaseClass="min-h-11 rounded-sm border border-border',
      );
      expect(findingsPanelSource).toContain('sm:min-h-0');
    });

    it('hides the filter bar when there are no Patrol findings or special buckets to navigate', () => {
      expect(findingsPanelSource).toContain('const showFilterControls = createMemo(');
      expect(findingsPanelSource).toContain('const hasUnknownRunSnapshot = createMemo(');
      expect(findingsPanelSource).toContain('const useRunSnapshotScopedControls = createMemo(');
      expect(findingsPanelSource).toContain('const runSnapshotScopedPatrolFindings = createMemo(');
      expect(findingsPanelSource).toContain('const filterCounts = createMemo(() => ({');
      expect(findingsPanelSource).toContain('filterCounts().needsAttentionCount > 0');
      expect(findingsPanelSource).toContain('filterCounts().pendingApprovalCount > 0');
      expect(findingsPanelSource).toContain('allPatrolFindings().length > 0');
      expect(findingsPanelSource).toContain('<Show when={showFilterControls()}>');
    });

    it('auto-resets conditional filters from the same scoped count model used by the filter bar', () => {
      expect(findingsPanelSource).toContain(
        "if (filter() === 'attention' && filterCounts().needsAttentionCount === 0)",
      );
      expect(findingsPanelSource).toContain(
        "if (filter() === 'approvals' && filterCounts().pendingApprovalCount === 0)",
      );
      expect(findingsPanelSource).toContain('buildFindingFilterOptions(filterCounts())');
    });

    it('fails closed on legacy run snapshots instead of showing global findings in a selected run view', () => {
      expect(findingsPanelSource).toContain('if (hasUnknownRunSnapshot()) {');
      expect(findingsPanelSource).toContain('return [];');
      expect(findingsPanelSource).toContain(
        '() => props.runSnapshot !== undefined && props.filterFindingIds === undefined',
      );
    });

    it('does not let global Patrol loading mask a selected run empty snapshot', () => {
      expect(findingsPanelSource).toContain('const hasEmptyRunSnapshot = createMemo(');
      expect(findingsPanelSource).toContain(
        'const canRenderRunSnapshotWithoutSourceFindings = createMemo(',
      );
      expect(findingsPanelSource).toContain('!canRenderRunSnapshotWithoutSourceFindings()');
      expect(findingsPanelSource).toContain('const shouldShowRichEmptyState = createMemo(');
      expect(findingsPanelSource).toContain("filter() === 'active' || props.runSnapshot");
    });

    it('uses explicit textual separators in finding metadata instead of relying on visual spacing', () => {
      expect(findingsPanelSource).toContain("{' · '}acknowledged");
      expect(findingsPanelSource).toContain("{' · '}last investigated");
      expect(findingsPanelSource).toMatch(/\{' · '\}\s*\{snooze\(\)\.label\}/);
      expect(findingsPanelSource).toMatch(/\{' · '\}\s*\{reminder\(\)\.label\}/);
    });

    it('keeps the Open work heading free of a duplicate count badge', () => {
      expect(patrolWorkspaceSource).toContain('queueAffectedResourceCount');
      expect(patrolWorkspaceSource).not.toContain('getPatrolQueueBadgeLabel');
      expect(patrolWorkspaceSource).not.toContain('{queueBadgeLabel()}');
    });

    it('surfaces work-type composition in the workspace description', () => {
      expect(aiFindingPresentationSource).toContain(
        'export function classifyPatrolFindingWorkType',
      );
      expect(aiFindingPresentationSource).toContain('export function getPatrolWorkTypeComposition');
      expect(aiFindingPresentationSource).toContain('getPatrolWorkTypeCompositionClause');
      expect(patrolWorkspaceSource).toContain('getPatrolWorkTypeComposition');
      expect(patrolWorkspaceSource).toContain('workTypeComposition');
    });

    it('shows contract-sanctioned actionable state badges on collapsed Patrol rows', () => {
      expect(findingsPanelSource).toContain('getPatrolFindingActionableState');
      expect(findingsPanelSource).toContain('patrolActionableState');
      expect(findingsPanelSource).toContain('when={isPatrolFindingsSource()}');
      expect(findingsPanelSource).toContain("patrolActionableState()?.label ?? 'Needs review'");
    });

    it('keeps collapsed Patrol rows compact and moves full context into focused review', () => {
      expect(findingsPanelSource).toContain('getPatrolFindingQueueSummary');
      expect(findingsPanelSource).toContain("'Needs review'");
      expect(findingsPanelSource).toContain("'Review issue'");
      expect(findingsPanelSource).toContain('selectedPatrolFinding');
      expect(findingsPanelSource).toContain('renderExpandedContent(finding()');
      expect(findingsPanelSource).not.toContain('aria-label="Patrol issue summary"');
      expect(findingsPanelSource).not.toContain('getPatrolFindingRowScaffold');
      expect(findingsPanelSource).not.toContain('Patrol trust summary');
      expect(findingsPanelSource).not.toContain('Patrol proof strip');
    });

    it('does not stack a default detected loop-state badge on active findings', () => {
      expect(findingsPanelSource).toContain('const shouldShowLoopStateBadge = () =>');
      expect(findingsPanelSource).toContain('!isPatrolFindingsSource()');
      expect(findingsPanelSource).toContain("finding.status === 'active'");
      expect(findingsPanelSource).toContain("finding.source !== 'ai-patrol'");
      expect(findingsPanelSource).toContain("finding.loopState !== 'detected'");
      expect(findingsPanelSource).toContain('when={shouldShowLoopStateBadge()}');
      expect(findingsPanelSource).toContain('Patrol status:');
      expect(findingsPanelSource).not.toContain('Patrol loop:');
    });

    it('keeps raw Patrol process badges out of the collapsed Patrol issue row', () => {
      expect(findingsPanelSource).toContain('const shouldShowInvestigationStatusBadge = () =>');
      expect(findingsPanelSource).toContain('const shouldShowInvestigationOutcomeBadge = () =>');
      expect(findingsPanelSource).toContain('const shouldShowInvestigationConfidenceBadge = () =>');
      expect(findingsPanelSource).toContain('!isPatrolFindingsSource() &&');
      expect(findingsPanelSource).not.toContain('const collapsedPatrolStatusBadge = () => {');
      expect(findingsPanelSource).not.toContain(
        "workflow?.stage === 'review' ? undefined : workflow",
      );
      expect(findingsPanelSource).not.toContain('<Show when={collapsedPatrolStatusBadge()}>');
    });

    it('groups active Patrol queue findings by API-owned resource, node, and correlation facts', () => {
      expect(findingsPanelSource).toContain('buildPatrolFindingDisplayGroups');
      expect(findingsPanelSource).toContain('getPatrolFindingIssueCountLabel');
      expect(findingsPanelSource).toContain('const shouldGroupActivePatrolFindings');
      expect(findingsPanelSource).toContain("filter() === 'active'");
      expect(findingsPanelSource).toContain('props.runSnapshot === undefined');
      expect(findingsPanelSource).toContain(
        'aria-label={`${group.label}: ${getPatrolFindingIssueCountLabel(',
      );
      expect(findingsPanelSource).toContain(
        '{getPatrolFindingIssueCountLabel(group.findings.length)}',
      );
      expect(findingsPanelSource).toContain('renderFindingItem(group.primaryFinding, false, {');
      expect(findingsPanelSource).toContain('relatedFindings: group.relatedFindings');
      expect(findingsPanelSource).not.toContain('<For each={group.findings}>');
      expect(findingsPanelSource).toContain('hideSubject: true');
      expect(aiFindingPresentationSource).toContain('correlatedFindingIds');
      expect(aiFindingPresentationSource).toContain("String(finding.node || '').trim()");
    });
  });

  describe('sourceColors', () => {
    it('has threshold color', () => {
      expect(getFindingSourceBadgeClasses('threshold')).toContain('orange');
      expect(getFindingSourceBadgeTone('threshold')).toBe('orange');
    });

    it('has ai-patrol color', () => {
      expect(getFindingSourceBadgeClasses('ai-patrol')).toContain('blue');
      expect(getFindingSourceBadgeTone('ai-patrol')).toBe('info');
    });

    it('has ai-chat color', () => {
      expect(getFindingSourceBadgeClasses('ai-chat')).toContain('teal');
      expect(getFindingSourceBadgeTone('ai-chat')).toBe('teal');
    });
  });

  describe('investigationStatusColors', () => {
    it('has pending color', () => {
      expect(getInvestigationStatusBadgeClasses('pending')).toContain('bg-surface-alt');
      expect(getInvestigationStatusBadgeTone('pending')).toBe('muted');
    });

    it('has running color', () => {
      expect(getInvestigationStatusBadgeClasses('running')).toContain('blue');
      expect(getInvestigationStatusBadgeTone('running')).toBe('info');
    });

    it('has completed color', () => {
      expect(getInvestigationStatusBadgeClasses('completed')).toContain('green');
      expect(getInvestigationStatusBadgeTone('completed')).toBe('success');
    });

    it('has failed color', () => {
      expect(getInvestigationStatusBadgeClasses('failed')).toContain('red');
      expect(getInvestigationStatusBadgeTone('failed')).toBe('danger');
    });

    it('returns canonical status labels', () => {
      expect(getInvestigationStatusLabel('pending')).toBe('Pending');
      expect(getInvestigationStatusLabel('running')).toBe('Running');
      expect(getInvestigationStatusLabel('completed')).toBe('Completed');
      expect(getInvestigationStatusLabel('failed')).toBe('Failed');
      expect(getInvestigationStatusLabel('needs_attention')).toBe('Needs Attention');
    });
  });

  describe('investigationOutcomePresentation', () => {
    it('returns canonical outcome labels and badge classes', () => {
      expect(getInvestigationOutcomeLabel('fix_verified')).toBe('Fix verified');
      expect(getInvestigationOutcomeBadgeClasses('fix_failed')).toContain('red');
      expect(getInvestigationOutcomeBadgeTone('fix_failed')).toBe('danger');
      expect(getInvestigationOutcomeLabel('fix_rejected')).toBe('Fix rejected');
      expect(getInvestigationOutcomeBadgeTone('fix_rejected')).toBe('warning');
      expect(getInvestigationOutcomeBadgeClasses('cannot_fix')).toContain('bg-surface-alt');
      expect(getInvestigationOutcomeBadgeTone('cannot_fix')).toBe('muted');
      expect(getInvestigationOutcomeSortOrder('fix_failed')).toBe(0);
      expect(getInvestigationOutcomeSortOrder('needs_attention')).toBe(1);
      expect(getInvestigationOutcomeSortOrder('fix_queued')).toBe(2);
      expect(getInvestigationOutcomeSortOrder(undefined)).toBe(3);
      expect(getInvestigationConfidenceBadgeTone('high')).toBe('success');
      expect(getInvestigationConfidenceBadgeTone('medium')).toBe('neutral');
      expect(getInvestigationConfidenceBadgeTone('low')).toBe('warning');
    });

    it('treats any investigation metadata as enough to render investigation details', () => {
      expect(
        hasFindingInvestigationDetails({
          investigationSessionId: '',
          investigationStatus: 'failed',
          investigationOutcome: undefined,
          investigationAttempts: 0,
        } as never),
      ).toBe(true);
      expect(
        hasFindingInvestigationDetails({
          investigationSessionId: '',
          investigationStatus: undefined,
          investigationOutcome: 'fix_queued',
          investigationAttempts: 0,
        } as never),
      ).toBe(true);
      expect(
        hasFindingInvestigationDetails({
          investigationSessionId: '',
          investigationStatus: undefined,
          investigationOutcome: undefined,
          investigationAttempts: 2,
        } as never),
      ).toBe(true);
      expect(
        hasFindingInvestigationDetails({
          investigationSessionId: 'session-1',
          investigationStatus: undefined,
          investigationOutcome: undefined,
          investigationAttempts: 0,
        } as never),
      ).toBe(true);
      expect(
        hasFindingInvestigationDetails({
          investigationSessionId: '   ',
          investigationStatus: undefined,
          investigationOutcome: undefined,
          investigationAttempts: 0,
        } as never),
      ).toBe(false);
    });

    it('promotes queued fixes without a pending approval into the needs-attention bucket', () => {
      expect(
        hasPendingInvestigationFixApproval('finding-1', [
          {
            status: 'pending',
            toolId: 'investigation_fix',
            targetId: 'finding-1',
            expiresAt: '2026-12-30T00:06:00Z',
          },
        ] as never),
      ).toBe(true);

      expect(
        doesFindingNeedAttention(
          {
            id: 'finding-1',
            status: 'active',
            investigationOutcome: 'fix_queued',
          } as never,
          [],
        ),
      ).toBe(true);

      expect(
        doesFindingNeedAttention(
          {
            id: 'finding-1',
            status: 'active',
            investigationOutcome: 'fix_queued',
          } as never,
          [
            {
              status: 'pending',
              toolId: 'investigation_fix',
              targetId: 'finding-1',
              expiresAt: '2026-12-30T00:06:00Z',
            },
          ] as never,
        ),
      ).toBe(false);

      expect(
        hasPendingInvestigationFixApproval(
          'finding-1',
          [
            {
              status: 'pending',
              toolId: 'investigation_fix',
              targetId: 'finding-1',
              expiresAt: '2026-03-01T00:06:00Z',
            },
          ] as never,
          Date.parse('2026-03-01T00:06:01Z'),
        ),
      ).toBe(false);

      expect(isPatrolInvestigationFixApproval({ toolId: 'investigation_fix' } as never)).toBe(true);
      expect(isPatrolInvestigationFixApproval({ toolId: 'run_command' } as never)).toBe(false);
    });
  });

  describe('loopStateColors', () => {
    it('has detected color', () => {
      expect(getFindingLoopStateBadgeClasses('detected')).toContain('blue');
      expect(getFindingLoopStateBadgeTone('detected')).toBe('info');
    });

    it('has resolved color', () => {
      expect(getFindingLoopStateBadgeClasses('resolved')).toContain('green');
      expect(getFindingLoopStateBadgeTone('resolved')).toBe('success');
    });

    it('has remediation_failed color', () => {
      expect(getFindingLoopStateBadgeClasses('remediation_failed')).toContain('red');
      expect(getFindingLoopStateBadgeTone('remediation_failed')).toBe('danger');
    });
  });

  describe('formatLoopState', () => {
    it('replaces underscores with spaces', () => {
      expect(formatFindingLoopState('in_progress')).toBe('in progress');
    });

    it('handles single word', () => {
      expect(formatFindingLoopState('detected')).toBe('detected');
    });

    it('handles multiple underscores', () => {
      expect(formatFindingLoopState('remediation_planned')).toBe('remediation planned');
    });
  });

  describe('Patrol workflow presentation', () => {
    const baseFinding = {
      id: 'finding-1',
      source: 'ai-patrol',
      status: 'active',
      resourceId: 'vm-101',
      resourceName: 'database-01',
      title: 'Disk pressure',
    } as const;

    it('does not invent a workflow badge for plain active Patrol findings', () => {
      expect(getFindingPatrolWorkflowPresentation(baseFinding)).toBeUndefined();
    });

    it('keeps Patrol runtime setup copy neutral to watch-only and paid control modes', () => {
      expect(
        getFindingPatrolWorkflowPresentation({
          ...baseFinding,
          resourceId: 'ai-service',
          resourceName: 'Pulse Patrol service',
          title: 'Pulse Patrol: Provider connection issue',
        }),
      ).toMatchObject({
        stage: 'attention',
        label: 'Fix Patrol setup',
        detail:
          'Patrol needs runtime or provider setup before it can check infrastructure reliably.',
        tone: 'info',
      });
    });

    it('promotes live governed approvals above generic review context', () => {
      expect(
        getFindingPatrolWorkflowPresentation(
          {
            ...baseFinding,
            investigationOutcome: 'fix_queued',
          },
          [
            {
              status: 'pending',
              toolId: 'investigation_fix',
              targetId: 'finding-1',
              expiresAt: '2026-06-20T18:15:00Z',
            },
          ],
          Date.parse('2026-06-20T18:00:00Z'),
        ),
      ).toMatchObject({
        stage: 'approval',
        label: 'Approve or reject',
        tone: 'warning',
      });
    });

    it('asks the operator to recover a queued fix when no live approval exists', () => {
      expect(
        getFindingPatrolWorkflowPresentation(
          {
            ...baseFinding,
            investigationOutcome: 'fix_queued',
          },
          [
            {
              status: 'pending',
              toolId: 'investigation_fix',
              targetId: 'finding-1',
              expiresAt: '2026-06-20T17:59:00Z',
            },
          ],
          Date.parse('2026-06-20T18:00:00Z'),
        ),
      ).toMatchObject({
        stage: 'approval',
        label: 'Recover action',
        tone: 'warning',
      });
    });

    it('separates rejected, executed, and verified outcomes into distinct operator next steps', () => {
      expect(
        getFindingPatrolWorkflowPresentation({
          ...baseFinding,
          investigationOutcome: 'fix_rejected',
        }),
      ).toMatchObject({
        stage: 'attention',
        label: 'Decide follow-up',
      });

      expect(
        getFindingPatrolWorkflowPresentation({
          ...baseFinding,
          investigationOutcome: 'fix_executed',
        }),
      ).toMatchObject({
        stage: 'verification',
        label: 'Verify outcome',
      });

      expect(
        getFindingPatrolWorkflowPresentation({
          ...baseFinding,
          investigationOutcome: 'fix_verified',
        }),
      ).toMatchObject({
        stage: 'recorded',
        label: 'Outcome recorded',
      });
    });

    it('uses concrete labels for failed or input-needed Patrol outcomes', () => {
      expect(
        getFindingPatrolWorkflowPresentation({
          ...baseFinding,
          investigationOutcome: 'fix_failed',
        }),
      ).toMatchObject({
        stage: 'attention',
        label: 'Fix failed',
      });

      expect(
        getFindingPatrolWorkflowPresentation({
          ...baseFinding,
          investigationOutcome: 'needs_attention',
        }),
      ).toMatchObject({
        stage: 'attention',
        label: 'Needs input',
      });
    });

    it('does not attach the Patrol operations loop to threshold alerts', () => {
      expect(
        getFindingPatrolWorkflowPresentation({
          ...baseFinding,
          source: 'threshold',
        }),
      ).toBeUndefined();
    });
  });

  describe('Patrol finding display groups', () => {
    it('keeps a group across rebuilds while its findings are the same objects', () => {
      const usage = {
        id: 'usage',
        resourceId: 'storage:tower-array',
        resourceName: 'Tower Array',
        resourceType: 'storage',
        title: 'High usage',
      };
      const parity = { ...usage, id: 'parity', title: 'No parity protection' };
      const provider = {
        id: 'provider',
        resourceId: 'ai-service',
        resourceName: 'Pulse Patrol service',
        resourceType: 'service',
        title: 'Provider connection issue',
      };
      const first = buildPatrolFindingDisplayGroups([usage, parity, provider]);

      // Rows are keyed by group, so a refresh that changed only the provider
      // finding leaves the storage group, and its rows, as they were.
      const changedProvider = { ...provider, title: 'Provider rejected the API key' };
      const second = reuseIdenticalPatrolFindingDisplayGroups(
        first,
        buildPatrolFindingDisplayGroups([usage, parity, changedProvider]),
      );
      expect(second[0]).toBe(first[0]);
      expect(second[1]).not.toBe(first[1]);
      expect(second[1].primaryFinding).toBe(changedProvider);

      // A group whose members changed is rebuilt.
      const third = reuseIdenticalPatrolFindingDisplayGroups(
        second,
        buildPatrolFindingDisplayGroups([usage, changedProvider]),
      );
      expect(third[0]).not.toBe(second[0]);
      expect(third[0].findings).toEqual([usage]);
      expect(third[1]).toBe(second[1]);
    });

    it('groups findings with the same resource identity while preserving sorted order', () => {
      const groups = buildPatrolFindingDisplayGroups([
        {
          id: 'critical',
          resourceId: 'storage:tower-array',
          resourceName: 'Tower Array',
          resourceType: 'storage',
          title: 'No parity protection',
        },
        {
          id: 'warning',
          resourceId: 'storage:tower-array',
          resourceName: 'Tower Array',
          resourceType: 'storage',
          title: 'High usage',
        },
        {
          id: 'provider',
          resourceId: 'ai-service',
          resourceName: 'Pulse Patrol service',
          resourceType: 'service',
          title: 'Provider connection issue',
        },
      ]);

      expect(groups).toHaveLength(2);
      expect(groups[0]).toMatchObject({
        affectedResourceCount: 1,
        kind: 'resource',
        label: 'Tower Array (storage)',
      });
      expect(groups[0].primaryFinding.id).toBe('critical');
      expect(groups[0].findings.map((finding) => finding.id)).toEqual(['critical', 'warning']);
      expect(groups[0].relatedFindings.map((finding) => finding.id)).toEqual(['warning']);
      expect(groups[1].findings.map((finding) => finding.id)).toEqual(['provider']);
      expect(groups[1].relatedFindings).toEqual([]);
    });

    it('keeps display-identical resources separate when canonical resource ids differ', () => {
      const groups = buildPatrolFindingDisplayGroups([
        {
          id: 'array-risk',
          resourceId: 'unraid:array:tower',
          resourceName: 'Tower Array',
          resourceType: 'storage',
          title: 'No parity protection',
        },
        {
          id: 'pool-usage',
          resourceId: 'unraid:pool:tower-array',
          resourceName: 'Tower Array',
          resourceType: 'storage',
          title: 'High usage',
        },
      ]);

      expect(groups).toHaveLength(2);
      expect(groups.map((group) => group.primaryFinding.id)).toEqual(['array-risk', 'pool-usage']);
    });

    it('groups different resources under their shared API-owned node', () => {
      const groups = buildPatrolFindingDisplayGroups([
        {
          id: 'portal-restarts',
          resourceId: 'container:portal',
          resourceName: 'customer-portal',
          resourceType: 'app-container',
          node: 'edge-apps-01',
          title: 'Container is restarting repeatedly',
        },
        {
          id: 'inventory-restarts',
          resourceId: 'container:inventory',
          resourceName: 'inventory-api',
          resourceType: 'app-container',
          node: 'edge-apps-01',
          title: 'Container is restarting repeatedly',
        },
      ]);

      expect(groups).toHaveLength(1);
      expect(groups[0]).toMatchObject({
        affectedResourceCount: 2,
        kind: 'node',
        label: 'Edge Apps 01',
      });
    });

    it('groups explicitly correlated findings across different nodes', () => {
      const groups = buildPatrolFindingDisplayGroups([
        {
          id: 'gateway',
          resourceId: 'service:gateway',
          resourceName: 'mail-gateway',
          resourceType: 'pmg',
          node: 'edge-01',
          correlatedFindingIds: ['backup-link'],
          title: 'Mail gateway is degraded',
        },
        {
          id: 'backup-link',
          resourceId: 'service:backup',
          resourceName: 'dr-vault',
          resourceType: 'pbs',
          node: 'backup-01',
          title: 'Backup connection is degraded',
        },
      ]);

      expect(groups).toHaveLength(1);
      expect(groups[0]).toMatchObject({
        affectedResourceCount: 2,
        kind: 'correlated',
        label: '2 related resources',
      });
    });

    it('keeps findings without resource identity separate instead of inventing duplicates', () => {
      const groups = buildPatrolFindingDisplayGroups([
        { id: 'a', resourceId: '', resourceName: '', resourceType: '', title: 'First' },
        { id: 'b', resourceId: '', resourceName: '', resourceType: '', title: 'Second' },
      ]);

      expect(groups).toHaveLength(2);
      expect(groups.map((group) => group.kind)).toEqual(['finding', 'finding']);
      expect(groups.map((group) => group.label)).toEqual(['', '']);
    });
  });

  describe('lifecycleLabels', () => {
    it('has detected label', () => {
      expect(formatFindingLifecycleType('detected')).toBe('Detected');
    });

    it('has resolved label', () => {
      expect(formatFindingLifecycleType('resolved')).toBe('Resolved');
    });

    it('has snoozed label', () => {
      expect(formatFindingLifecycleType('snoozed')).toBe('Snoozed');
    });

    it('has dismissed label', () => {
      expect(formatFindingLifecycleType('dismissed')).toBe('Dismissed');
    });

    it('labels a key-collision content replacement as a re-detection with different details', () => {
      // Backend emits content_replaced when a same-key re-detection's text
      // is substantially different from the existing finding (a key
      // collision); the timeline label must explain the shift in operator
      // language rather than the raw identifier fallback.
      expect(formatFindingLifecycleType('content_replaced')).toBe(
        'Re-detected with different details',
      );
    });
  });

  describe('formatLifecycleType', () => {
    it('returns known label for known value', () => {
      expect(formatFindingLifecycleType('detected')).toBe('Detected');
    });

    it('replaces underscores for unknown value', () => {
      expect(formatFindingLifecycleType('some_unknown_event')).toBe('some unknown event');
    });

    it('handles auto_resolved', () => {
      expect(formatFindingLifecycleType('auto_resolved')).toBe('Auto-resolved');
    });

    it('handles verification_passed', () => {
      expect(formatFindingLifecycleType('verification_passed')).toBe('Fix verified');
    });
  });

  describe('resolutionReasonPresentation', () => {
    it('returns canonical threshold resolution reasons', () => {
      expect(
        getFindingResolutionReason(
          {
            isThreshold: true,
            source: 'threshold',
            alertType: 'cpu',
            investigationOutcome: undefined,
          } as never,
          '2m ago',
        ),
      ).toBe('CPU returned to normal 2m ago');
    });

    it('formats findings as a Markdown summary mirroring the seven-question schema for paste-into-chat sharing', () => {
      // The Copy summary action must produce paste-ready Markdown that
      // mirrors render order: severity + title + resource header, then
      // description, impact, recommendation, plus trust signals
      // (confidence, regression count). Anything beyond that — evidence,
      // rollback plans, internal IDs — is deferred to the Discuss flow
      // because that's conversation context, not "share this finding"
      // context. Pin the exact shape so the operator-facing output
      // doesn't drift between releases.
      const formatted = formatFindingForClipboard({
        severity: 'warning',
        title: 'Disk pressure',
        resourceName: 'db-01',
        resourceType: 'vm',
        description: 'Datastore is at 92% capacity.',
        impact: 'Backups will be skipped if free space drops below 5%.',
        recommendation: 'Free 200GB before the next backup window.',
        investigationRecord: { confidence: 'medium' } as never,
        regressionCount: 2,
      } as never);
      expect(formatted).toContain('**[WARNING] Disk pressure**');
      expect(formatted).toContain('Resource: db-01 (vm)');
      expect(formatted).toContain('Description: Datastore is at 92% capacity.');
      expect(formatted).toContain('Impact: Backups will be skipped if free space drops below 5%.');
      expect(formatted).not.toContain('Recommendation: Free 200GB before the next backup window.');
      expect(formatted).toContain('Confidence: medium');
      expect(formatted).toContain('Regressed: 2×');
    });

    it('omits empty fields cleanly when the finding has not been investigated yet', () => {
      // A threshold-only finding (no InvestigationRecord, no Impact) must
      // still produce useful Markdown — the formatter must not include
      // empty "Impact:" or "Confidence:" lines that read as alarm signals.
      const formatted = formatFindingForClipboard({
        severity: 'critical',
        title: 'Host offline',
        resourceName: 'pve-01',
        resourceType: 'node',
        description: 'Host is not responding.',
      } as never);
      expect(formatted).toContain('**[CRITICAL] Host offline**');
      expect(formatted).toContain('Resource: pve-01 (node)');
      expect(formatted).toContain('Description: Host is not responding.');
      expect(formatted).not.toContain('Impact:');
      expect(formatted).not.toContain('Recommendation:');
      expect(formatted).not.toContain('Confidence:');
      expect(formatted).not.toContain('Regressed:');
    });

    it('returns canonical patrol resolution reasons', () => {
      expect(
        getFindingResolutionReason(
          {
            isThreshold: false,
            source: 'ai-patrol',
            alertType: undefined,
            investigationOutcome: 'fix_verified',
          } as never,
          '1h ago',
        ),
      ).toBe('Fixed by Patrol 1h ago');
    });

    it('attributes operator-driven Mark resolved closures to "Resolved by you"', () => {
      // Slice 22 added the manual Mark resolved button which sets
      // auto_resolved=false. The resolution-reason copy must distinguish
      // operator-driven closure from Pulse's auto-detection so the timeline
      // reads honestly. This branch must take priority over the
      // category-specific "Condition cleared" / "CPU returned to normal"
      // copy (those describe Pulse's auto-detection).
      expect(
        getFindingResolutionReason(
          {
            isThreshold: true,
            source: 'threshold',
            alertType: 'cpu',
            investigationOutcome: undefined,
            autoResolved: false,
          } as never,
          '5m ago',
        ),
      ).toBe('Resolved by you 5m ago');

      expect(
        getFindingResolutionReason(
          {
            isThreshold: false,
            source: 'ai-patrol',
            alertType: undefined,
            investigationOutcome: 'cannot_fix',
            autoResolved: false,
          } as never,
          '20m ago',
        ),
      ).toBe('Resolved by you 20m ago');
    });

    it('keeps Patrol fix-applied copy when Pulse closed the loop autonomously', () => {
      // Patrol's own fix outcomes (fix_verified, fix_executed, resolved) are
      // more specific than "auto-resolved" — they describe Pulse's actual
      // remediation. The autoResolved branch must NOT override those.
      expect(
        getFindingResolutionReason(
          {
            isThreshold: false,
            source: 'ai-patrol',
            alertType: undefined,
            investigationOutcome: 'fix_verified',
            autoResolved: true,
          } as never,
          '2h ago',
        ),
      ).toBe('Fixed by Patrol 2h ago');
    });
  });

  describe('operator-state dismiss cause attribution', () => {
    it('reports the most recent operator_state_cause from the lifecycle', () => {
      // Lifecycle scan must be newest-first so a later auto-dismiss
      // overrides an older manual one. Mirror the Go-side helper's
      // contract — the rendering branch depends on it for the badge.
      expect(
        getOperatorStateDismissCause({
          lifecycle: [
            {
              at: '2026-04-01T00:00:00Z',
              type: 'dismissed',
              metadata: { reason: 'expected_behavior' },
            },
            { at: '2026-04-02T00:00:00Z', type: 'undismissed' },
            {
              at: '2026-04-03T00:00:00Z',
              type: 'dismissed',
              metadata: { operator_state_cause: 'maintenance_window' },
            },
          ],
        } as never),
      ).toBe('maintenance_window');
    });

    it('returns empty when the most recent dismissed event is a manual operator dismissal', () => {
      // A manual dismiss that supersedes an earlier auto-dismiss must
      // NOT report the stale auto-dismiss cause — that would falsely
      // badge the finding as auto-suppressed when the operator
      // overrode it.
      expect(
        getOperatorStateDismissCause({
          lifecycle: [
            {
              at: '2026-04-01T00:00:00Z',
              type: 'dismissed',
              metadata: { operator_state_cause: 'maintenance_window' },
            },
            { at: '2026-04-02T00:00:00Z', type: 'undismissed' },
            {
              at: '2026-04-03T00:00:00Z',
              type: 'dismissed',
              metadata: { reason: 'expected_behavior' },
            },
          ],
        } as never),
      ).toBe('');
    });

    it('returns empty for findings without lifecycle entries', () => {
      expect(getOperatorStateDismissCause({ lifecycle: undefined } as never)).toBe('');
      expect(getOperatorStateDismissCause({ lifecycle: [] } as never)).toBe('');
    });

    it('formats canonical operator-state causes as human labels', () => {
      expect(formatOperatorStateDismissCauseLabel('maintenance_window')).toBe('maintenance');
      expect(formatOperatorStateDismissCauseLabel('intentionally_offline')).toBe(
        'intentionally offline',
      );
      // Unknown causes return empty so render code can gate cleanly
      // and not show a bogus "auto: <unknown>" badge.
      expect(formatOperatorStateDismissCauseLabel('something_new')).toBe('');
      expect(formatOperatorStateDismissCauseLabel('')).toBe('');
    });
  });
});