import { beginActivity, showActivityFrame } from '../../platform/activity-store'; import { buildUnifiedResultCsv, unifiedResultCsvFileName } from '../../exports/unified-result-csv'; import { useCallback, useEffect, useState } from 'react'; import { AssessorApiClient } from '../../api/assessor-api-client'; import { resultSourceToolLabel, type UnifiedResultFacetResult, type UnifiedResultProjection, type UnifiedResultQuery, type UnifiedResultQueryResult } from '../../domain/unified-result'; import { discloseResultDbProjection, removeResultDbScopeIdentifiers } from '../../domain/result-db-disclosure'; import { ResultsFilterPanel } from './ResultsFilterPanel'; import { PanelLoadingState } from '../../components/PanelLoadingState/PanelLoadingState'; import { FilterEmptyState } from '../../components/FilterEmptyState/FilterEmptyState'; import { TriangleIcon } from '../../components/TriangleIcon'; import { browserDownloadAdapter, downloadBrowserBlob } from '../../platform/browser/browser-download-adapter'; import { downloadText } from '../../exports/text-download'; import { buildUnifiedResultJsonl, queryAllUnifiedResults, unifiedResultJsonlFileName } from '../../exports/unified-result-jsonl'; import { hasSelectedTimeslotScope } from '../../app/work-scope'; import { POLICY_CLASSIFICATION_LABELS } from '../../domain/policy-status-labels'; import { BackendConnectionDialog } from '../../components/BackendConnectionDialog/BackendConnectionDialog'; import { formatPolicyComparisonValue } from '../../profiles/group-policy/presentation'; import type { ResultDbMaterializationStatus } from '../../domain/result-db-materialization'; const assessorApi = new AssessorApiClient(); const PAGE_SIZE = 50; const MAX_QUERY_PAGE_SIZE = 10000; export const DEFAULT_RESULT_DB_FILTERS: UnifiedResultQuery = { deviation: true }; type BackendStatus = 'connected' | 'checking' | 'unavailable'; interface ResultsBrowserProps { backendStatus: BackendStatus; projectId?: string; scanRunIds?: string[]; assessmentIds?: string[]; /** Work records holding the original of a row; the Result DB itself never shows originals. */ workRecordIds?(row: UnifiedResultProjection): string[]; onOpenInWork?(recordIds: string[]): void; } export function ResultsBrowser({ backendStatus, projectId, scanRunIds, assessmentIds, workRecordIds, onOpenInWork }: ResultsBrowserProps) { const [filters, setFilters] = useState(() => ({ ...DEFAULT_RESULT_DB_FILTERS })); const [limit, setLimit] = useState(PAGE_SIZE); const [loadAll, setLoadAll] = useState(false); const [facetResult, setFacetResult] = useState(null); const [resultDbStatus, setResultDbStatus] = useState(null); const [queryResult, setQueryResult] = useState(null); const [loading, setLoading] = useState(true); const [exporting, setExporting] = useState<'jsonl' | 'excel' | 'csv' | null>(null); const [error, setError] = useState(null); const [expandedId, setExpandedId] = useState(null); const hasTimeslotScope = hasSelectedTimeslotScope(scanRunIds, assessmentIds); const load = useCallback(async () => { if (backendStatus !== 'connected' || !projectId || !hasTimeslotScope) { setFacetResult(null); setQueryResult(null); setLoading(false); return; } setLoading(true); setError(null); try { const scopedQuery: UnifiedResultQuery = { ...filters, projectId, scanRunIds, assessmentIds }; const [facets, firstPage] = await Promise.all([ assessorApi.queryUnifiedResultFacets(scopedQuery), assessorApi.queryUnifiedResults({ ...scopedQuery, offset: 0, limit }) ]); const items = [...firstPage.items]; while (loadAll && items.length < firstPage.total) { const nextPage = await assessorApi.queryUnifiedResults({ ...scopedQuery, offset: items.length, limit: MAX_QUERY_PAGE_SIZE }); if (!nextPage.items.length) break; items.push(...nextPage.items); } setFacetResult(facets); setQueryResult({ ...firstPage, items }); // Read after the rows: serving them guarantees the stored Result DB is current. setResultDbStatus(await assessorApi.getResultDbStatus().catch(() => null)); } catch (reason) { setError(reason instanceof Error ? reason.message : 'Results could not be loaded.'); } finally { setLoading(false); } }, [backendStatus, projectId, scanRunIds, assessmentIds, hasTimeslotScope, filters, limit, loadAll]); useEffect(() => { void load(); }, [load]); const updateFilters = (next: UnifiedResultQuery) => { setExpandedId(null); setLimit(PAGE_SIZE); setLoadAll(false); setFilters(next); }; const exportFilteredResults = async (format: 'jsonl' | 'excel' | 'csv') => { if (!projectId || !hasTimeslotScope) return; const activity = beginActivity('Core Engine', `Exporting Result DB as ${format === 'excel' ? 'Excel' : format.toUpperCase()}`); setExporting(format); setError(null); try { const scopedQuery: UnifiedResultQuery = { ...filters, projectId, scanRunIds, assessmentIds }; const results = await queryAllUnifiedResults(query => assessorApi.queryUnifiedResults(query), scopedQuery); activity.update('Preparing the filtered export file'); await showActivityFrame(); const generatedAt = new Date().toISOString(); if (format === 'excel') { const { buildUnifiedResultExcel, unifiedResultExcelFileName, RESULT_DB_EXCEL_MEDIA_TYPE } = await import('../../exports/unified-result-excel'); downloadBrowserBlob(new Blob([buildUnifiedResultExcel(scopedQuery, results, generatedAt)], { type: RESULT_DB_EXCEL_MEDIA_TYPE }), unifiedResultExcelFileName(generatedAt)); } else if (format === 'csv') { downloadText(browserDownloadAdapter, unifiedResultCsvFileName(generatedAt), buildUnifiedResultCsv(scopedQuery, results, generatedAt), 'text/csv;charset=utf-8'); } else downloadText( browserDownloadAdapter, unifiedResultJsonlFileName(generatedAt), buildUnifiedResultJsonl(scopedQuery, results, generatedAt), 'application/x-ndjson;charset=utf-8' ); } catch (reason) { activity.fail(); setError(reason instanceof Error ? reason.message : 'Filtered results could not be exported.'); } finally { activity.complete(); setExporting(null); } }; const processingFacet = facetResult?.facets.find(facet => facet.id === 'processingStatus'); const processingWarnings = processingFacet?.values.filter(value => ['unknown', 'incompatible', 'reimport-recommended'].includes(value.value)) ?? []; if (backendStatus !== 'connected') { return
; } if (!projectId) { return

No client selected

Open a client in the Datahub first to browse its results.

; } if (!hasTimeslotScope) { return

No timeslot selected

Select a timeslot in Work to browse exactly this assessment state.

; } return
{error &&
{error}
} {loading && !queryResult ? :
updateFilters({ ...DEFAULT_RESULT_DB_FILTERS })}/>
{processingWarnings.length > 0 &&
Processing readiness: {processingWarnings.map(value => `${processingStatusLabel(value.value)} (${value.count.toLocaleString('en-US')})`).join(' · ')}. Comparisons with unknown or incompatible contracts are blocked; reimport the original source with the current profile where recommended.
}

{(queryResult?.total ?? 0).toLocaleString('en-US')} hits{queryResult && queryResult.total > queryResult.items.length ? ` · ${queryResult.items.length.toLocaleString('en-US')} loaded` : ''}{resultDbStatus && <>
{resultDbStatusText(resultDbStatus)}}

{!queryResult?.items.length ? updateFilters({ ...DEFAULT_RESULT_DB_FILTERS })} onSearchAll={() => updateFilters({})}>No result matches the current filter combination. :
TitleSource Rule IDSeverityOutcomeResult TypeIOEDeviationToolProcessing
{queryResult.items.map(item => setExpandedId(current => current === item.resultProjectionId ? null : item.resultProjectionId)}/>)}
} {queryResult && queryResult.total > queryResult.items.length &&
}
}
; } export function ResultRow({ item: sourceItem, expanded, onToggle, workRecordIds = [], onOpenInWork }: { item: UnifiedResultProjection; expanded: boolean; onToggle(): void; workRecordIds?: string[]; onOpenInWork?(recordIds: string[]): void; }) { const item = removeResultDbScopeIdentifiers(discloseResultDbProjection(sourceItem)); const environment = item.sourceKind === 'environment-observation'; const policyObservation = item.sourceKind === 'policy-observation'; const policyComparison = item.sourceKind === 'policy-evaluation' && Boolean(item.policyBaselineLabel); const policyIdentity = displayPolicyIdentity(item); const contextRecord = environment || policyObservation; return
{expanded &&
{environment &&
{item.environmentProperty}

{displayEnvironmentValue(item.environmentNormalizedValue)}

} {policyObservation &&
{item.policyIdentityKey}

{displayEnvironmentValue(item.policyValues)}

} {item.description &&

{item.description}

} {item.recommendation &&

Recommendation: {item.recommendation}

} {policyComparison &&
Expected baseline value

{displayPolicyValue(item.policyBaselineValue)}

}
  • Source: {item.sourceProfileId ?? '–'}@{item.sourceProfileVersion ?? '–'}
  • Processing: profile {item.sourceProfileVersion ?? '–'} · mapping {item.mappingRuleVersion ?? '–'} · normalization {item.normalizationRuleVersion ?? '–'} · presentation {item.presentationVersion ?? '–'}
  • Compatibility: {item.processingCompatibilityKey ?? 'unknown'} · {processingStatusLabel(item.processingStatus)}
  • {item.policyClassification &&
  • Result Status: {POLICY_CLASSIFICATION_LABELS[item.policyClassification]}{item.policySourceCount ? ` · ${item.policySourceCount.toLocaleString('en-US')} sources` : ''}
  • } {item.processingStatus === 'reimport-recommended' &&
  • Reprocessing: {item.reprocessingAvailable ? 'retained source available' : 'original source must be uploaded again'}
  • } {environment ? <>
  • Subject class: {item.environmentSubjectType ?? '–'}
  • State: {item.environmentState ?? 'unknown'} · Value type: {item.environmentValueType ?? 'unknown'}
  • Disclosure: {item.supplementalDisclosureClass ?? '–'} · policy {item.supplementalDisclosurePolicyVersion ?? '–'}
  • : policyObservation ? <>
  • Scope: {item.policyScope ?? '–'} · Delivery: {item.policyDeliveryMechanism ?? '–'}
  • Policy state: {item.policyState ?? '–'} · Identity: {item.policyIdentityStatus ?? 'unresolved'}
  • Backup instance: {item.policyBackupInstanceId ?? '–'}
  • Diagnostics: {item.policyDiagnosticCodes?.join(', ') || 'none'}
  • Source locator: {displayEnvironmentValue(item.sourceLocator)}
  • : policyComparison ? <> {policyIdentity &&
  • Technical setting ID: {policyIdentity}
  • }
  • Baseline: {item.policyBaselineLabel}
  • Scope: {item.policyScope ?? '–'} · Delivery: {item.policyDeliveryMechanism ?? '–'}
  • {item.policyBaselineVariantAssessment ?
  • {disclosedBaselineDecision(item.policyBaselineVariantAssessment.decision)}

    No effective device state or GPO application is established by this backup comparison.

      {item.policyBaselineVariantAssessment.variants.map(variant =>
    • Value comparison: {variant.comparator.relation}

      Expected: {displayPolicyValue(variant.comparator.baseline)}

      Original baseline value: {displayPolicyValue(variant.baselineValues)}

    • )}
  • : null}
  • Comparison: {item.policyComparisonRelation ?? '–'} · Customer state: {item.policyCustomerState ?? '–'}
  • Diagnostics: {item.policyDiagnosticCodes?.join(', ') || 'none'}
  • : <>
  • Rule ID: {item.sourceRuleId ?? '–'}
  • Affected Object: {item.affectedAsset ?? '–'}
  • }
  • Categories: {item.categories.map(category => category.categoryLabel).join(', ') || '–'}
}
; } function displayEnvironmentValue(value: unknown): string { if (value === undefined) return '–'; if (typeof value === 'string') return value || '–'; if (typeof value === 'number' || typeof value === 'boolean') return String(value); if (value === null) return 'null'; return JSON.stringify(value); } function displayPolicyValue(value: unknown): string { return value === undefined ? '–' : formatPolicyComparisonValue(JSON.stringify(value)); } /** Result DB collapses identical baseline expectations, so it states the decision without a variant count. */ function disclosedBaselineDecision(decision: string): string { if (decision === 'all-pass') return 'Matches every assessed baseline expectation (backup configuration only)'; if (decision === 'all-fail') return 'Differs from every assessed baseline expectation (backup configuration only)'; if (decision === 'mixed') return 'Review required: baseline expectations lead to different results'; return 'Review required: comparison evidence or applicability is incomplete'; } function displayPolicyIdentity(item: UnifiedResultProjection): string | undefined { const identity = item.policyIdentityKey ?? item.sourceRuleId; return identity && !/^gpo-policy-identity-[0-9a-f]+$/i.test(identity) ? identity : undefined; } function processingStatusLabel(value: string | undefined): string { if (value === 'current') return 'Current'; if (value === 'compatible-older') return 'Compatible older'; if (value === 'reimport-recommended') return 'Reimport recommended'; if (value === 'incompatible') return 'Incompatible'; return 'Unknown'; } const traceFieldLabels: Record = { title: 'Title', description: 'Description', recommendation: 'Recommendation', sourceRuleId: 'Source Rule ID', policyBaselineLabel: 'Baseline', policyBaselineValue: 'Expected baseline value', policyBaselineVariantAssessment: 'Baseline expectations', environmentNormalizedValue: 'Value', categories: 'Categories' }; function resultDbStatusText(status: ResultDbMaterializationStatus): string { if (status.state === 'not-built') return 'Result DB not built yet'; const checked = status.materializedAt ? status.materializedAt.slice(0, 16).replace('T', ' ') : '–'; return [ status.state === 'current' ? `Checked ${checked} UTC` : `Outdated: checked ${checked} UTC, rebuilding`, `policy ${status.disclosurePolicyVersion ?? '–'}`, `identity guard ${status.identityGuardVersion ?? '–'}`, `${status.rowCount.toLocaleString('en-US')} rows`, `${status.redactionCount.toLocaleString('en-US')} redactions`, `${status.guardWithheldRowCount.toLocaleString('en-US')} rows with withheld fields` ].join(' · '); } /** Content-free trace of the stored row: what was redacted and withheld, never the original. */ function DisclosureTraceDetail({ item, workRecordIds, onOpenInWork }: { item: UnifiedResultProjection; workRecordIds: string[]; onOpenInWork?(recordIds: string[]): void; }) { const trace = item.disclosureTrace; if (!trace) return null; const byField = new Map(); for (const entry of trace.redactions) { byField.set(entry.field, [...(byField.get(entry.field) ?? []), `${entry.rule} × ${entry.count.toLocaleString('en-US')}`]); } const hasOriginal = item.sourceKind === 'scanner-finding' || item.sourceKind === 'policy-evaluation'; return
Checked content
  • Policy {trace.disclosurePolicyVersion} · identity guard {trace.identityGuardVersion}
  • {[...byField].map(([field, rules]) =>
  • Redacted in {traceFieldLabels[field] ?? field}: {rules.join(', ')}
  • )} {!byField.size &&
  • No redaction in the disclosed fields
  • } {trace.withheldFields.length > 0 &&
  • Withheld fields: {trace.withheldFields.join(', ')}
  • } {trace.guardWithheldFields.length > 0 &&
  • Withheld by identity guard: {trace.guardWithheldFields.map(field => traceFieldLabels[field] ?? field).join(', ')}
  • }
{hasOriginal && (workRecordIds.length && onOpenInWork ? :

The original is not part of the loaded Work scope.

)}
; }