/** * ReportPanel — Health Report. * * Reads as a structured audit rather than a dashboard: * * AUDIT (header + score anchor + diagnostic strip) * → FINDINGS (mode rail: architecture / api / hygiene / onboarding) * → EVIDENCE (bounded lists, progressive disclosure) * → PRIORITIES (ranked action issues) * → ACTION (export) * * Every number comes from `/report/{owner}/{repo}/build` unchanged. The one * score visualisation is the donut; the strip reports the other dimensions so * the overall figure is never repeated three times. */ import React, { useState, useEffect, useMemo, useCallback } from 'react'; import { apiUrl, extractErrorMessage } from '../../lib/api'; import { FileText, Download, Printer, AlertTriangle, ChevronDown, Layers, Globe, Trash2, BookOpen, ArrowRight, RefreshCw, } from 'lucide-react'; import { Button } from '../ui/Button'; import { EmptyState } from '../ui/EmptyState'; import { SkeletonCard, SkeletonGroup, Skeleton } from '../ui/Skeleton'; import { SVGDonut } from '../ui/SVGDonut'; import { AnimatedNumber } from '../ui/AnimatedNumber'; import { FilePath } from '../ui/FilePath'; import { Meter } from '../ui/Meter'; import { Reveal } from '../ui/Reveal'; import { SectionSeam } from '../ui/SectionSeam'; interface ScoreBreakdown { overall: number; architecture: number; api: number; hygiene: number; churn: number; readability: number; grade: string; } interface ReportMetadata { repo_name: string; owner: string; name: string; total_loc: number; commits_count: number; languages: Record; generated_at: string; execution_time_ms: number; } interface ArchReportSection { cycles_count: number; cycles: string[][]; strongly_connected_components: number; smells_count: number; smells: string[]; } interface ApiReportSection { total_exported_symbols: number; public_private_ratio: number; average_distance_main_sequence: number; unstable_modules_count: number; } interface HygieneReportSection { dead_functions_count: number; dead_functions: string[]; dead_code_ratio: number; } interface OnboardingReportSection { reading_path_completeness: number; core_entry_points: string[]; recommended_reading_path: string[]; } interface ReportDataModel { metadata: ReportMetadata; scores: ScoreBreakdown; architecture: ArchReportSection; api_surface: ApiReportSection; hygiene: HygieneReportSection; onboarding: OnboardingReportSection; refactoring_priorities: string[]; ai_summary?: string; } interface ReportPanelProps { repoName: string; /** * Switches the parent dashboard tab. Wired to the dashboard's existing * `handleTabChange`, so cross-surface links reuse current navigation rather * than introducing a second mechanism. */ onNavigate?: (tab: string) => void; } type SubTabId = 'architecture' | 'api' | 'hygiene' | 'onboarding'; const MODES: [SubTabId, string, React.ComponentType<{ className?: string }>][] = [ ['architecture', 'ARCHITECTURE', Layers], ['api', 'API SURFACE', Globe], ['hygiene', 'HYGIENE', Trash2], ['onboarding', 'ONBOARDING', BookOpen], ]; function gradeToneClass(grade: string): string { if (grade === 'A') return 'text-success'; if (grade === 'B') return 'text-primary'; if (grade === 'C') return 'text-warn'; return 'text-danger'; } function getScoreTone(score: number): 'success' | 'warn' | 'danger' { if (score >= 80) return 'success'; if (score >= 60) return 'warn'; return 'danger'; } function scoreBarClass(score: number): string { if (score >= 80) return 'bg-success'; if (score >= 60) return 'bg-warn'; return 'bg-danger'; } function relativeTime(iso: string): string { try { const diff = Math.round((Date.now() - new Date(iso).getTime()) / 60000); if (diff < 1) return 'just now'; if (diff < 60) return `${diff} min ago`; return `${Math.round(diff / 60)}h ago`; } catch { return iso; } } /** Cross-surface actions. Both use contracts the dashboard already listens for. */ function openInGraph(owner: string, repo: string, path: string) { window.dispatchEvent( new CustomEvent('aria-open-graph', { detail: { owner, repo, path, source: 'health-report' }, }) ); } function openInChat(owner: string, repo: string, path: string, prompt: string) { window.dispatchEvent( new CustomEvent('aria-open-chat', { detail: { owner, repo, path, source: 'health-report', prompt }, }) ); } // ── Small building blocks ────────────────────────────────────────────────── /** A hairline-separated diagnostic cell. */ const Readout: React.FC<{ label: string; value: React.ReactNode; detail?: React.ReactNode; tone?: string; index?: number; }> = ({ label, value, detail, tone = 'text-text', index = 0 }) => (
{label}
{value} {detail && ( {detail} )}
); /** Top-N list with a bounded scroll region behind "view all". */ const BoundedList: React.FC<{ total: number; preview: number; label: string; children: (limit: number | null) => React.ReactNode; }> = ({ total, preview, label, children }) => { const [expanded, setExpanded] = useState(false); const overflow = total > preview; return ( <>
{children(expanded ? null : preview)}
{overflow && ( )} ); }; // ── Prioritized issue row ────────────────────────────────────────────────── interface ParsedIssue { id: string; title: string; severity: 'critical' | 'high' | 'medium' | 'low'; category: string; icon: React.ComponentType<{ className?: string }>; affectedFile: string; impact: string; fix: string; } const SEVERITY_CLASS: Record = { critical: 'text-danger', high: 'text-warn', medium: 'text-primary', low: 'text-text-muted', }; const IssueRow: React.FC<{ issue: ParsedIssue; owner: string; repo: string; }> = ({ issue, owner, repo }) => { const [open, setOpen] = useState(false); const Icon = issue.icon; const hasFile = issue.affectedFile !== 'multiple files'; return (
{open && (
{hasFile && (
FILE PATH
)}
ESTIMATED IMPACT

{issue.impact}

RECOMMENDED FIX

{issue.fix}

{hasFile && (
)}
)}
); }; // ── Main component ───────────────────────────────────────────────────────── export const ReportPanel: React.FC = ({ repoName, onNavigate }) => { const [report, setReport] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [subTab, setSubTab] = useState('architecture'); const [owner, repo] = repoName.split('/'); /** Same endpoint and method as before; extracted so Refresh can re-run it. */ const loadReport = useCallback(() => { if (!owner || !repo) { setError('Invalid repository name'); setReport(null); setLoading(false); return; } setReport(null); setLoading(true); setError(null); fetch(apiUrl(`/api/v1/report/${owner}/${repo}/build`), { method: 'POST' }) .then((res) => { if (!res.ok) throw new Error('Failed to generate intelligence report'); return res.json(); }) .then((data) => { setReport(data); setLoading(false); }) .catch((err) => { setError(extractErrorMessage(err)); setLoading(false); }); }, [owner, repo]); useEffect(() => { loadReport(); }, [loadReport]); const handleExport = (format: 'html' | 'pdf' | 'markdown') => { if (!owner || !repo) return; const downloadUrl = apiUrl(`/api/v1/report/${owner}/${repo}/download?format=${format}`); window.open(downloadUrl, '_blank'); }; // Severity mapping preserved exactly as before. const parsedIssues = useMemo(() => { if (!report || !report.refactoring_priorities) return []; return report.refactoring_priorities.map((item, idx) => { const lower = item.toLowerCase(); let severity: 'critical' | 'high' | 'medium' | 'low' = 'low'; let category = 'Code Hygiene'; let icon: React.ComponentType<{ className?: string }> = Trash2; let impact = 'Optimizes code execution path and minimizes static memory leaks'; let fix = 'Refactor local calls and safely delete the unused function symbol'; if (lower.includes('volatile') || lower.includes('cycle') || lower.includes('coupling')) { severity = lower.includes('volatile') ? 'critical' : 'high'; category = 'Architecture'; icon = Layers; impact = 'Averts cycle propagation and compiler dependency locks'; fix = 'Abstract call layers into utilities or register interface handlers'; } else if (lower.includes('dead') || lower.includes('unused') || lower.includes('hygiene')) { severity = 'medium'; category = 'Code Hygiene'; icon = Trash2; impact = 'Cleans up orphan logic branches and improves project code cleanliness'; fix = 'Locate caller references and safely clean up dead function definitions'; } else if (lower.includes('api') || lower.includes('public') || lower.includes('export')) { severity = 'medium'; category = 'API Surface'; icon = Globe; impact = 'Tightens system boundary encapsulation and module stability'; fix = 'Mark exports as private or document usage metrics'; } else if (lower.includes('read') || lower.includes('onboard') || lower.includes('path')) { severity = 'low'; category = 'Onboarding'; icon = BookOpen; impact = 'Speeds up developer onboarding paths and code search indexing'; fix = 'Supplement code comments or update recommended reading lists'; } const pathMatch = item.match(/([a-zA-Z0-9_\-\/]+\.[a-zA-Z0-9]+)/); const affectedFile = pathMatch ? pathMatch[1] : 'multiple files'; return { id: `issue-${idx}`, title: item, severity, category, icon, affectedFile, impact, fix }; }); }, [report]); const attentionCount = useMemo( () => parsedIssues.filter((i) => i.severity === 'critical' || i.severity === 'high' || i.severity === 'medium').length, [parsedIssues] ); if (loading) { return (
); } if (error || !report) { return ( } title="Report Generation Failed" description={error || 'Could not compile report metadata.'} action={} /> ); } const scoreTone = getScoreTone(report.scores.overall); const isHighDebt = report.hygiene.dead_functions_count > 10; const isHighComplexity = report.scores.architecture < 70; const api = report.api_surface; const distanceOutOfRange = api.average_distance_main_sequence > 0.3; const ratioOutOfRange = api.public_private_ratio < 0.1 || api.public_private_ratio > 0.5; const ladder = [ { label: 'Architecture Stability', value: report.scores.architecture }, { label: 'API Quality & Encapsulation', value: report.scores.api }, { label: 'Code Hygiene & Pruning', value: report.scores.hygiene }, { label: 'Hotspot & Churn Control', value: report.scores.churn }, { label: 'Onboarding Clarity', value: report.scores.readability }, ]; return ( /* pb-24 keeps the sticky footer from ever covering the last section */
{/* ── Header ───────────────────────────────────────────────────────── */}
AUDIT / HEALTH REPORT

Health Report

Repository architecture, API quality, hygiene, and onboarding readiness.

{report.metadata.repo_name}
{/* ── Score anchor + diagnostic strip ──────────────────────────────── */}
{/* The single score visualisation */}
HEALTH } />
GRADE {report.scores.grade}
{/* Diagnostic ladder */}
{ladder.map((item, i) => (
{item.label}
/100
))}
{/* Remaining dimensions — hairline cells, not cards */}
%} detail="onboarding path coverage" /> %} detail={report.architecture.cycles_count > 0 ? 'cycles found' : 'acyclic graph'} tone={report.architecture.cycles_count > 0 ? 'text-warn' : 'text-success'} /> {/* The backend report carries no security scan or performance analysis, so these are reported as not measured rather than asserting a pass. */}
{/* ── Mode rail ────────────────────────────────────────────────────── */}
{MODES.map(([id, label, Icon]) => { const isActive = subTab === id; return ( ); })}
{/* ── Architecture ───────────────────────────────────────────────── */} {subTab === 'architecture' && (
} tone={report.architecture.cycles_count > 0 ? 'text-warn' : 'text-success'} /> } /> } />

DEPENDENCY DESIGN VIOLATIONS

{report.architecture.smells.length > 0 ? (
    {report.architecture.smells.map((smell, idx) => (
  • {String(idx + 1).padStart(2, '0')} {smell}
  • ))}
) : (

No dependency smells detected.

)}

CIRCULAR IMPORT PATHS

{report.architecture.cycles.length > 0 ? ( {(limit) => (
    {(limit === null ? report.architecture.cycles : report.architecture.cycles.slice(0, limit) ).map((cycle, idx) => { const entry = cycle[0]; const exit = cycle[cycle.length - 1] ?? entry; return (
  • {/* The loop stated explicitly: source → target → back */}
    imports
    {cycle.length > 2 && (

    VIA {cycle.length - 2} INTERMEDIATE{cycle.length - 2 === 1 ? '' : 'S'}

    )}
  • ); })}
)}
) : (

No circular import loops detected.

)}
)} {/* ── API Surface ────────────────────────────────────────────────── */} {subTab === 'api' && (
} /> } tone={ratioOutOfRange ? 'text-warn' : 'text-success'} /> } tone={distanceOutOfRange ? 'text-warn' : 'text-success'} />

API PACKAGING STABILITY

A stable design aligns packaging along the main sequence. A public-to-private symbol ratio below 0.5 suggests healthy encapsulation.

{/* Evidence table — emphasis only where a value is out of range */}
CATEGORY VALUE TARGET
{[ { k: 'Average Distance', v: api.average_distance_main_sequence.toFixed(2), t: '≤ 0.3', bad: distanceOutOfRange, }, { k: 'Public / Private Ratio', v: api.public_private_ratio.toFixed(2), t: '0.1 – 0.5', bad: ratioOutOfRange, }, ].map((row) => (
{row.k} {row.v} {row.t}
))}
{onNavigate && ( )}
)} {/* ── Hygiene ────────────────────────────────────────────────────── */} {subTab === 'hygiene' && (
} tone={report.hygiene.dead_functions_count > 0 ? 'text-warn' : 'text-success'} /> % } />

DEAD CODE REGISTRY

{report.hygiene.dead_functions.length > 0 ? ( {(limit) => (
    {(limit === null ? report.hygiene.dead_functions : report.hygiene.dead_functions.slice(0, limit) ).map((func, idx) => (
  • UNUSED
  • ))}
)}
) : (

No unused functions detected in call graph sweep.

)}
)} {/* ── Onboarding ─────────────────────────────────────────────────── */} {subTab === 'onboarding' && (
% } tone={report.onboarding.reading_path_completeness > 0 ? 'text-text' : 'text-warn'} /> } />

MAIN ENTRY POINTS

{report.onboarding.core_entry_points.length > 0 ? ( {(limit) => (
    {(limit === null ? report.onboarding.core_entry_points : report.onboarding.core_entry_points.slice(0, limit) ).map((entry, idx) => (
  1. {String(idx + 1).padStart(2, '0')}
  2. ))}
)}
) : (

No main code entry points detected.

)}

TOPOLOGICAL READING ORDER

Read these modules in sequence to move from base imports up to high-level controllers.

{report.onboarding.recommended_reading_path.length > 0 ? (
{(limit) => (
    {(limit === null ? report.onboarding.recommended_reading_path : report.onboarding.recommended_reading_path.slice(0, limit) ).map((path, idx) => (
  1. {String(idx + 1).padStart(2, '0')}
  2. ))}
)}
) : (

No reading path compiled.

)}
)}
{/* ── Prioritized action issues ────────────────────────────────────── */}

PRIORITIZED ACTION ISSUES

{attentionCount > 0 ? `${String(attentionCount).padStart(2, '0')} NEED ATTENTION` : `${String(parsedIssues.length).padStart(2, '0')} ITEMS`}
{parsedIssues.length > 0 ? (
{parsedIssues.map((issue) => ( ))}
) : (

No action items required.

)}
{/* ── Sticky export footer ─────────────────────────────────────────── */}
GRADE{' '} {report.scores.grade}
); }; export default ReportPanel;