/** * ImpactAnalysisGraph — predictive impact instrument. * * Answers one question: what will this change touch, and where does the risk * propagate? The graph is the product surface; the readout beside it explains * what the graph means, and the inspector explains the selected node. * * SCENARIO → RISK → PROPAGATION → ARCHITECTURAL IMPACT * * Framing is computed from the measured canvas rather than left to `fitView`: * the layout is asked to balance its bounding box against the canvas aspect, and * the viewport is then set explicitly with a clamped zoom. Without that, a wide * short canvas had to zoom out to fit a roughly square graph, which is what made * the nodes render as specks with empty margins either side. * * Every figure comes from the `/api/v1/impact-analysis` payload unchanged. Node * degrees are counted from the edges of this view, as before. */ import React, { useState, useEffect, useMemo, useCallback, useRef } from 'react'; import ReactFlow, { MiniMap, Controls, Background, useNodesState, useEdgesState, useReactFlow, MarkerType, ReactFlowProvider, } from 'reactflow'; import { PanControls } from './graph/PanControls'; import { layoutImpactGraph, fitZoomFor, DEFAULT_TARGET_ASPECT, } from './graph/impactLayout'; import { X, AlertTriangle, ArrowRight, ExternalLink, MessageSquare, Layers } from 'lucide-react'; import { FilePath } from '../ui/FilePath'; import { LeaderRow } from './pr/instrument'; import 'reactflow/dist/style.css'; interface DependencyPath { path: string[]; } interface ImpactAnalysisData { repo: string; issue_text: string; directly_affected_files: string[]; indirectly_affected_files: string[]; affected_components: string[]; risk_level: string; estimated_file_count: number; dependency_paths: DependencyPath[]; confidence: number; } interface GraphProps { repoName: string; impactData: ImpactAnalysisData; onReset: () => void; } type NodeCategory = 'direct' | 'indirect' | 'component' | 'regular'; interface SelectedNodeData { id: string; label: string; category: NodeCategory; inDegree: number; outDegree: number; riskContribution: 'High' | 'Medium' | 'Low'; } interface HoverInfo { id: string; category: NodeCategory; degree: number; } /** * Node surfaces. Direct impact is the only bright surface, so the propagation * chain wins against the background topology; the rest are dark surfaces * separated by edge colour alone. */ const NODE_BASE = 'rounded-[3px] px-2.5 py-1.5 text-center text-[11px] font-mono leading-tight ' + 'break-words cursor-pointer transition-[color,border-color,opacity] duration-200'; const NODE_CLASS: Record = { direct: `${NODE_BASE} bg-[#1b0f12] border border-danger/70 text-white font-medium hover:border-danger`, indirect: `${NODE_BASE} bg-canvas border border-warn/55 text-warn hover:border-warn`, component: `${NODE_BASE} bg-canvas border border-primary/60 text-primary hover:border-primary`, regular: `${NODE_BASE} bg-canvas border border-white/[0.06] text-text-subtle hover:border-white/20 hover:text-text-muted`, }; /** Label length drives width, within bounds that keep the grid gutters intact. */ const NODE_STYLE: React.CSSProperties = { width: 'auto', minWidth: 118, maxWidth: 216, overflowWrap: 'anywhere', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden', }; function riskToneClass(risk: string): string { const r = (risk || '').toLowerCase(); if (r === 'high' || r === 'critical') return 'text-danger'; if (r === 'medium' || r === 'moderate') return 'text-warn'; if (r === 'low') return 'text-success'; return 'text-text-muted'; } function categoryTone(category: NodeCategory): string { if (category === 'direct') return 'text-danger'; if (category === 'indirect') return 'text-warn'; if (category === 'component') return 'text-primary'; return 'text-text-muted'; } /** Only relayout when the canvas shape has moved enough to matter. */ const ASPECT_EPSILON = 0.12; const ImpactAnalysisGraphInner: React.FC = ({ repoName, impactData, onReset }) => { const [nodes, setNodes, onNodesChange] = useNodesState([]); const [edges, setEdges, onEdgesChange] = useEdgesState([]); const [selectedNode, setSelectedNode] = useState(null); const [hover, setHover] = useState(null); const canvasRef = useRef(null); const { setViewport } = useReactFlow(); /** Canvas aspect, bucketed so a resize drag cannot thrash the layout. */ const [targetAspect, setTargetAspect] = useState(DEFAULT_TARGET_ASPECT); useEffect(() => { const el = canvasRef.current; if (!el || typeof ResizeObserver === 'undefined') return; const measure = () => { const { clientWidth: w, clientHeight: h } = el; if (w <= 0 || h <= 0) return; const next = w / h; setTargetAspect((prev) => Math.abs(Math.log(next / prev)) > ASPECT_EPSILON ? next : prev, ); }; measure(); const ro = new ResizeObserver(measure); ro.observe(el); return () => ro.disconnect(); }, []); // Parse raw impact data into React Flow nodes and edges useEffect(() => { const directSet = new Set(impactData.directly_affected_files); const indirectSet = new Set(impactData.indirectly_affected_files); const uniqueNodes = new Set(); const tempEdges: { source: string; target: string; isDotted?: boolean }[] = []; // 1. Process propagation paths impactData.dependency_paths.forEach((p) => { const path = p.path; for (let i = 0; i < path.length; i++) { uniqueNodes.add(path[i]); if (i < path.length - 1) { tempEdges.push({ source: path[i], target: path[i + 1] }); } } }); // 2. Add remaining isolated files impactData.directly_affected_files.forEach((f) => uniqueNodes.add(f)); impactData.indirectly_affected_files.forEach((f) => uniqueNodes.add(f)); // 3. Process component nodes impactData.affected_components.forEach((comp) => { const compId = `component-${comp}`; uniqueNodes.add(compId); // Heuristic connection: Link components to directly affected files that are related let connectedAny = false; const compLower = comp.toLowerCase(); impactData.directly_affected_files.forEach((file) => { const fileLower = file.toLowerCase(); // Simple matching logic const matches = (compLower.includes('api') && (fileLower.includes('api') || fileLower.includes('route'))) || (compLower.includes('auth') && (fileLower.includes('auth') || fileLower.includes('sec'))) || (compLower.includes('service') && fileLower.includes('service')) || (compLower.includes('db') && (fileLower.includes('db') || fileLower.includes('model'))) || fileLower.includes(compLower); if (matches) { tempEdges.push({ source: compId, target: file, isDotted: true }); connectedAny = true; } }); // Fallback: connect component node to the first directly affected file if no matches found if (!connectedAny && impactData.directly_affected_files.length > 0) { tempEdges.push({ source: compId, target: impactData.directly_affected_files[0], isDotted: true }); } }); const categoryOf = (id: string): NodeCategory => { if (id.startsWith('component-')) return 'component'; if (directSet.has(id)) return 'direct'; if (indirectSet.has(id)) return 'indirect'; return 'regular'; }; // Build React Flow Node objects const flowNodes = Array.from(uniqueNodes).map((id) => { const isComponent = id.startsWith('component-'); const cleanLabel = isComponent ? id.replace('component-', '') : id.split('/').pop() || id; const category = categoryOf(id); return { id, data: { label: cleanLabel, category, fullId: id }, className: NODE_CLASS[category], style: NODE_STYLE, type: 'default' }; }); /* Edge weight follows the classification of what it points at, so an amber node is reached by an amber edge. Derived from the existing sets — no new classification is introduced. */ const flowEdges = tempEdges.map((e, idx) => { const targetCategory = categoryOf(e.target); let stroke = '#ef4444'; let width = 2; let opacity = 0.9; if (e.isDotted) { stroke = '#5e6ad2'; width = 1.5; opacity = 0.68; } else if (targetCategory === 'indirect') { stroke = '#f59e0b'; width = 1.75; opacity = 0.7; } else if (targetCategory === 'regular') { stroke = '#ffffff'; width = 1; opacity = 0.16; } return { id: `edge-${idx}`, source: e.source, target: e.target, // No continuous animation: a permanently marching edge is noise. animated: false, style: e.isDotted ? { stroke, strokeWidth: width, opacity, strokeDasharray: '4,4' } : { stroke, strokeWidth: width, opacity }, markerEnd: { type: MarkerType.ArrowClosed, width: 11, height: 11, color: stroke, }, }; }); /* Isolated files get a grid whose column count balances the *whole* bounding box against the canvas aspect — see `impactLayout.ts`. The propagation chains keep their left-to-right ranking. */ const { nodes: layoutedNodes, edges: layoutedEdges, bounds } = layoutImpactGraph( flowNodes, flowEdges, { direction: 'LR', targetAspect }, ); setNodes(layoutedNodes as never); setEdges(layoutedEdges as never); setSelectedNode(null); setHover(null); // Explicit framing: clamped zoom, bounding box centred in the canvas. const el = canvasRef.current; if (el && bounds.width > 0 && bounds.height > 0) { const cw = el.clientWidth; const ch = el.clientHeight; const zoom = fitZoomFor(bounds, cw, ch); setViewport({ x: (cw - bounds.width * zoom) / 2 - bounds.x * zoom, y: (ch - bounds.height * zoom) / 2 - bounds.y * zoom, zoom, }); } }, [impactData, targetAspect, setNodes, setEdges, setViewport]); const degreeOf = useCallback( (id: string) => ({ inDegree: edges.filter((e) => e.target === id).length, outDegree: edges.filter((e) => e.source === id).length, }), [edges], ); /** Nodes adjacent to the selection, for the focus treatment. */ const focusSet = useMemo(() => { if (!selectedNode) return null; const set = new Set([selectedNode.id]); edges.forEach((e) => { if (e.source === selectedNode.id) set.add(e.target); if (e.target === selectedNode.id) set.add(e.source); }); return set; }, [selectedNode, edges]); /** * Focus is applied at render time rather than written back into node state, so * clearing the selection cannot leave stale styling behind. */ const displayNodes = useMemo(() => { if (!focusSet) return nodes; return nodes.map((n) => { const inFocus = focusSet.has(n.id); return { ...n, style: { ...(n.style as React.CSSProperties), opacity: inFocus ? 1 : 0.22, }, }; }); }, [nodes, focusSet]); const displayEdges = useMemo(() => { if (!focusSet) return edges; return edges.map((e) => { const onPath = focusSet.has(e.source) && focusSet.has(e.target); const base = (e.style ?? {}) as React.CSSProperties; const baseOpacity = typeof base.opacity === 'number' ? base.opacity : 1; return { ...e, style: { ...base, opacity: onPath ? Math.min(1, baseOpacity + 0.25) : baseOpacity * 0.25, }, }; }); }, [edges, focusSet]); // Handle node selection const onNodeClick = (_event: any, node: any) => { const id = node.id; const { inDegree, outDegree } = degreeOf(id); let riskContribution: 'High' | 'Medium' | 'Low' = 'Low'; if (node.data.category === 'direct') { riskContribution = outDegree > 2 ? 'High' : 'Medium'; } else if (node.data.category === 'indirect') { riskContribution = 'Medium'; } setSelectedNode({ id, label: node.data.label, category: node.data.category, inDegree, outDegree, riskContribution }); setHover(null); }; const onNodeMouseEnter = useCallback( (_event: React.MouseEvent, node: any) => { const { inDegree, outDegree } = degreeOf(node.id); setHover({ id: node.id, category: node.data?.category ?? 'regular', degree: inDegree + outDegree, }); }, [degreeOf], ); const onNodeMouseLeave = useCallback(() => setHover(null), []); const counts = useMemo( () => ({ direct: impactData.directly_affected_files.length, indirect: impactData.indirectly_affected_files.length, chains: impactData.dependency_paths.length, }), [impactData], ); const scenario = (impactData.issue_text || '').trim(); return (
{/* ── Scenario context strip ────────────────────────────────────────── */} {scenario && (
SCENARIO “{scenario}”
)}
{/* ── Risk intelligence ───────────────────────────────────────────── */}

RISK INTELLIGENCE

{/* Risk state — a band, not a filled card */}

Calculated risk of change propagation based on coupling and core components.

{/* One continuous diagnostic readout */}
{impactData.confidence} % {impactData.estimated_file_count} files
AFFECTED COMPONENTS {impactData.affected_components.length > 0 ? (

{impactData.affected_components.join(' · ')}

) : (

NOT AVAILABLE

)}
PROPAGATION
{counts.direct} {counts.indirect} {counts.chains}
{/* ── Impact propagation graph ────────────────────────────────────── */}

IMPACT PROPAGATION GRAPH

{/* Counts read brighter than the legend they sit beside. */} {nodes.length} NODES · {edges.length} EDGES
{ setHover(null); setSelectedNode(null); }} /* Framing is set explicitly from measured bounds, so `fitView` is not used — it would override the computed viewport. */ minZoom={0.15} maxZoom={2} > { const cat = node.data?.category; if (cat === 'direct') return '#ef4444'; if (cat === 'indirect') return '#f59e0b'; if (cat === 'component') return '#5e6ad2'; return '#26262b'; }} maskColor="rgba(2, 2, 4, 0.74)" style={{ backgroundColor: '#020204', border: '1px solid rgba(255,255,255,0.07)', width: 128, height: 88, }} /> {/* ── Hover micro-inspector ─────────────────────────────────── */} {hover && !selectedNode && (
{hover.category.toUpperCase()} DEGREE {hover.degree}
)} {/* Inspector: a side drawer on desktop, a bottom sheet at <=640px so the topology stays visible behind it. */} {selectedNode && (
DEPENDENCY CHAIN
FILE / NODE
{selectedNode.category} {selectedNode.inDegree} {selectedNode.outDegree} {selectedNode.riskContribution}
{/* Smart actions — not yet wired, and labelled as such. */}
SMART ACTIONS NOT AVAILABLE
    {[ { icon: ExternalLink, label: 'Open file' }, { icon: MessageSquare, label: 'Ask about impact' }, ].map(({ icon: Icon, label }) => (
  • ))}
)}
{/* ── Status line ───────────────────────────────────────────────── */}

{selectedNode ? ( <> FOCUSED: {selectedNode.label} · DEPENDENCY CHAIN ) : ( <>SCENARIO TOPOLOGY · {nodes.length} NODES · {edges.length} EDGES )}

{!selectedNode && ( SELECT A NODE TO INSPECT ITS IMPACT CHAIN )}
); }; const LegendDot: React.FC<{ tone: string; label: string }> = ({ tone, label }) => ( ); export const ImpactAnalysisGraph: React.FC = (props) => { return ( ); }; export default ImpactAnalysisGraph;