/** * DeadCodeAnalyzer — reachability audit. * * Reads as one forensic engineering report rather than a stack of cards: * * HEADER → SPECIFICATION STRIP → RECOMMENDATIONS (editorial list) * → UNUSED FILES (column registry) → ORPHAN MODULES (labelled records) * → DEAD CHAINS (directional trace) → RUN SUMMARY * * The four evidence types are deliberately given four different shapes — a * ranked list, a tabular registry, labelled key/value records and a directional * trace — so a reader can tell which kind of finding they are looking at from * the layout alone. * * Typography rule: uppercase monospace is reserved for labels, statuses, * telemetry and paths. Titles, explanations and reasoning keep the backend's own * readable casing. * * Every figure comes from `POST /api/v1/dead-code/analyze` unchanged. The score * is presented as a measured value, not a pass/fail verdict, and red is reserved * for genuine risk — "unused" and "orphaned" are findings, not failures. */ import React, { useCallback, useMemo, useState } from 'react'; import { apiUrl, extractErrorMessage } from '../../lib/api'; import { AlertTriangle, ArrowRight, Loader2 } from 'lucide-react'; import { PrerequisitesBanner } from './pr/PrerequisitesBanner'; import { usePrerequisites } from './pr/usePrerequisites'; import { SkeletonCard, SkeletonGroup } from '../ui/Skeleton'; import { FilePath } from '../ui/FilePath'; import { SectionSeam } from '../ui/SectionSeam'; import { Reveal } from '../ui/Reveal'; interface DeadFile { file_path: string; confidence: number; risk_level: string; recommendation: string; } interface OrphanModule { file_path: string; confidence: number; risk_level: string; recommendation: string; last_reachable_parent?: string; } interface DeadDependencyChain { chain: string[]; confidence: number; risk_level: string; recommendation: string; length: number; total_nodes: number; max_centrality: number; } interface DeadCodeResult { repo: string; cleanup_score: number; previous_cleanup_score?: number; estimated_cleanup_effort: string; unused_files: DeadFile[]; orphan_modules: OrphanModule[]; dead_dependency_chains: DeadDependencyChain[]; cleanup_recommendations: string[]; analyzed_at: string; } interface Props { repoName?: string } function resolveRepo(repoName?: string): string { if (repoName) return repoName; if (typeof window !== 'undefined') { const urlParams = new URLSearchParams(window.location.search); const owner = urlParams.get('owner'); const repo = urlParams.get('repo'); if (owner && repo) return `${owner}/${repo}`; const stored = localStorage.getItem('activeRepo'); if (stored) return stored; } return ''; } /** * Risk tone. Only genuinely risky levels reach red; "safe" is informational * green and "review" is amber. Unknown levels stay neutral rather than guessing. */ function riskToneClass(level: string): string { const l = (level || '').toLowerCase(); if (l === 'safe' || l === 'low') return 'text-success'; if (l === 'review' || l === 'medium' || l === 'moderate') return 'text-warn'; if (l === 'high' || l === 'critical' || l === 'danger') return 'text-danger'; return 'text-text-muted'; } /** Effort is not risk, so high effort reads amber rather than red. */ function effortToneClass(effort: string): string { const e = (effort || '').toLowerCase(); if (e === 'high') return 'text-warn'; if (e === 'low') return 'text-success'; return 'text-text'; } function pct(value: number): string { return `${(value * 100).toFixed(0)}%`; } /** `15 AUG 2026 · 09:00` — compact enough to sit in a strip cell on one line. */ function formatAnalyzed(iso: string): string { const d = new Date(iso); if (Number.isNaN(d.getTime())) return iso; const day = String(d.getDate()).padStart(2, '0'); const month = d.toLocaleString('en-US', { month: 'short' }).toUpperCase(); const hh = String(d.getHours()).padStart(2, '0'); const mm = String(d.getMinutes()).padStart(2, '0'); return `${day} ${month} ${d.getFullYear()} · ${hh}:${mm}`; } 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 navigation via the contracts the dashboard already listens for. */ function openInGraph(repoSlug: string, path: string) { const [owner, repo] = repoSlug.split('/'); window.dispatchEvent( new CustomEvent('aria-open-graph', { detail: { owner, repo, path, source: 'dead-code' }, }) ); } function openInChat(repoSlug: string, path: string, prompt: string) { const [owner, repo] = repoSlug.split('/'); window.dispatchEvent( new CustomEvent('aria-open-chat', { detail: { owner, repo, path, source: 'dead-code', prompt }, }) ); } const PATH_RE = /([a-zA-Z0-9_\-./]+\.[a-zA-Z0-9]+)/; /** * Splits a recommendation string into a title, an optional path and the * remaining explanation. Purely a display split of the backend string — the * casing is left exactly as the backend wrote it and the full original text is * preserved on the row via `title`. */ function splitRecommendation(text: string): { action: string; path: string | null; rest: string } { const colon = text.indexOf(':'); const action = colon > 0 ? text.slice(0, colon).trim() : text.trim(); const remainder = colon > 0 ? text.slice(colon + 1).trim() : ''; const match = PATH_RE.exec(remainder) || (colon > 0 ? null : PATH_RE.exec(text)); const path = match ? match[1] : null; const rest = path ? remainder.replace(path, '').replace(/^[\s·—-]+/, '').trim() : remainder; return { action, path, rest }; } /** * Bounded evidence registry: a preview, then a fixed-height scroll region. * * Bounded rather than growing so a repository with 1,000 findings does not turn * the page into an unnavigable column. The continuation control names what it * expands so it reads as "keep going", not as a button. */ const BoundedRegistry: React.FC<{ total: number; preview: number; noun: string; children: (limit: number | null) => React.ReactNode; }> = ({ total, preview, noun, children }) => { const [expanded, setExpanded] = useState(false); const overflow = total > preview; const shown = expanded ? total : Math.min(preview, total); return ( <>

SHOWING {shown.toLocaleString()} OF {total.toLocaleString()}

{children(expanded ? null : preview)}
{overflow && ( )} ); }; /** * Evidence row actions. Arrowed so they read as navigation into another * instrument rather than as another piece of metadata on the row. */ const RowActions: React.FC<{ repoSlug: string; path: string; question: string }> = ({ repoSlug, path, question, }) => ( ); /** A registry section title with a subordinate count. */ const RegistryHeading: React.FC<{ id: string; title: string; criterion: string; count?: string; }> = ({ id, title, criterion, count }) => (

{title}

{count && {count}} {criterion}
); /** One labelled field inside an orphan record. */ const RecordField: React.FC<{ label: string; children: React.ReactNode; className?: string }> = ({ label, children, className = '', }) => (
{label}
{children}
); export const DeadCodeAnalyzer: React.FC = ({ repoName }) => { const [activeRepo, setActiveRepo] = useState(() => resolveRepo(repoName)); const { healthStatus, hasPrerequisites, isRepairing, repair } = usePrerequisites(activeRepo); const [isLoading, setIsLoading] = useState(false); const [analyzerResult, setAnalyzerResult] = useState(null); const [errorMsg, setErrorMsg] = useState(''); // Sync activeRepo with repoName prop changes and clear stale results React.useEffect(() => { const nextRepo = resolveRepo(repoName); setActiveRepo(nextRepo); setAnalyzerResult(null); setErrorMsg(''); }, [repoName]); const handleRunAnalysis = useCallback(async () => { if (!activeRepo) { setErrorMsg('No active repository loaded.'); return; } const [owner, repo] = activeRepo.split('/'); if (!owner || !repo) { setErrorMsg('Invalid repository identifier.'); return; } setIsLoading(true); setErrorMsg(''); setAnalyzerResult(null); try { const res = await fetch(apiUrl('/api/v1/dead-code/analyze'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ owner, repo }), }); if (!res.ok) { const errorData = await res.json().catch(() => ({})); throw new Error(extractErrorMessage(errorData)); } setAnalyzerResult(await res.json()); } catch (err: any) { setErrorMsg(extractErrorMessage(err)); } finally { setIsLoading(false); } }, [activeRepo]); /** Reachability movement, stated only from what the payload reports. */ const scoreNote = useMemo(() => { if (!analyzerResult) return null; const { cleanup_score: now, previous_cleanup_score: prev } = analyzerResult; if (prev === undefined || prev === null) return 'NO HISTORICAL BASELINE'; if (now === prev) return 'NO REACHABILITY IMPROVEMENT DETECTED'; return now > prev ? 'REACHABILITY IMPROVED' : 'REACHABILITY REGRESSED'; }, [analyzerResult]); /** * The previous score is only worth a line when it actually differs — a * "PREVIOUS 00 → 00" caption above a "NO REACHABILITY IMPROVEMENT DETECTED" * note says the same thing twice. The data itself is untouched. */ const scoreDelta = useMemo(() => { if (!analyzerResult) return null; const { cleanup_score: now, previous_cleanup_score: prev } = analyzerResult; if (prev === undefined || prev === null || prev === now) return null; return `PREVIOUS ${String(prev).padStart(2, '0')} → ${String(now).padStart(2, '0')}`; }, [analyzerResult]); const runControl = ( ); return (
{/* ── 01 · Audit header ────────────────────────────────────────────── */}
DEAD CODE / REPOSITORY AUDIT

Find what the codebase no longer reaches.

Trace unreachable modules, isolated files, and dead dependency chains before they become maintenance weight.

{runControl}

DEPENDENCY GRAPH · REACHABILITY ANALYSIS · PATH FILTERS

{!hasPrerequisites && healthStatus && (
)}
{errorMsg && (
)} {/* ── Loading ──────────────────────────────────────────────────────── */} {isLoading && (
)} {/* ── Compact empty state, integrated with the audit ───────────────── */} {!analyzerResult && !isLoading && !errorMsg && hasPrerequisites && (
DEAD CODE ANALYSIS NOT RUN

The repository graph has not yet been scanned for unreachable modules, isolated files, or dead dependency chains.

)} {/* ── Results ──────────────────────────────────────────────────────── */} {analyzerResult && (
{/* ── 02 · Specification strip ─────────────────────────────────── */} {/* A real
: these are term/value pairs, so the grid lives on the definition list itself rather than on a wrapper div — `dt`/`dd` are only valid inside a `dl` (or a `div` grouping within one). Vertical hairlines make the four readings one instrument face instead of four cards. */}
{[ { k: 'REPOSITORY', v: ( {analyzerResult.repo} ), d: null as string | null, }, { k: 'ANALYZED', v: ( {formatAnalyzed(analyzerResult.analyzed_at)} ), d: null, }, { k: 'ESTIMATED EFFORT', v: ( // No `strip-value`: this reading carries a semantic colour, // which hover must not overwrite. {analyzerResult.estimated_cleanup_effort} ), d: null, }, { k: 'CLEANUP SCORE', v: ( {String(analyzerResult.cleanup_score).padStart(2, '0')} / 100 ), d: scoreDelta, }, ].map((cell) => (
{cell.k}
{cell.v} {cell.d && ( {cell.d} )}
))}
{scoreNote && (

{scoreNote}

)} {/* ── 03 · Prioritized recommendations ─────────────────────────── */}

PRIORITIZED RECOMMENDATIONS

{analyzerResult.cleanup_recommendations?.length ?? 0} findings
{analyzerResult.cleanup_recommendations?.length ? (
    {analyzerResult.cleanup_recommendations.map((recommendation, idx) => { const { action, path, rest } = splitRecommendation(recommendation); return (
  1. {String(idx + 1).padStart(2, '0')} {/* The title is the strongest element and keeps the backend's own casing — an audit finding is a sentence, not a status code. */} {action} {path && ( )} {rest && ( {rest} )}
  2. ); })}
) : (

No cleanup recommendations from this run — every module the graph reaches is accounted for.

)}
{/* ── 04 · Unused files: a column registry ─────────────────────── */}
{analyzerResult.unused_files?.length ? ( {(limit) => ( <> {/* Column captions, once — this is what makes the section read as a registry rather than another prose list. */} {/* `minmax(0, Nfr)` rather than a bare `Nfr`: an `fr` track keeps a min-content floor, and a one-word caption like CONFIDENCE would then push the registry wider than the column. The captions only appear from `lg` — below that the readings are labelled inline instead. */}
    {(limit === null ? analyzerResult.unused_files : analyzerResult.unused_files.slice(0, limit) ).map((file, idx) => (
  • {/* Below `lg` the readings stack in the same order but carry their own labels, since the column captions are hidden. */} CONFIDENCE {pct(file.confidence)} RISK {file.risk_level}

    {file.recommendation}

  • ))}
)}
) : (

Every top-level file in this repository is reachable from an entry point.

)}
{/* ── 05 · Orphan modules: labelled records ────────────────────── */}
{analyzerResult.orphan_modules?.length ? ( {(limit) => (
    {(limit === null ? analyzerResult.orphan_modules : analyzerResult.orphan_modules.slice(0, limit) ).map((mod, idx) => (
  • {/* Four labelled readings: the reasoning is scannable without reading the sentence underneath. */}
    {mod.last_reachable_parent ? ( ) : ( NONE · FULLY ISOLATED )} {pct(mod.confidence)} {mod.risk_level}

    {mod.recommendation}

  • ))}
)}
) : (

No isolated subgraphs detected — every module is reachable.

)}
{/* ── 06 · Dead dependency chains: directional trace ───────────── */}
{analyzerResult.dead_dependency_chains?.length ? ( {(limit) => (
    {(limit === null ? analyzerResult.dead_dependency_chains : analyzerResult.dead_dependency_chains.slice(0, limit) ).map((c, idx) => (
  • CHAIN {String(idx + 1).padStart(2, '0')} {c.total_nodes} NODES · {c.length} {c.length === 1 ? 'HOP' : 'HOPS'}
    {/* The trace is the point of the record: the source is the strongest element and every hop descends from it. */}
      {c.chain.map((node, nodeIdx) => (
    1. {nodeIdx < c.chain.length - 1 && (
    2. ))}

    CENTRALITY {c.max_centrality} · CONFIDENCE {pct(c.confidence)} ·{' '} {(c.risk_level || '').toUpperCase()}

    {c.recommendation}

  • ))}
)}
) : (

No unreachable dependency chains identified.

)}
{/* ── 07 · Run summary ────────────────────────────────────────────── Deliberately not a second "ANALYSIS COMPLETE" indicator: the dashboard already closes the workspace with one. This line reports what only this run knows — the reachability scope and its counts. */}
)}
); }; export default DeadCodeAnalyzer;