diff --git a/app/analyze/page.tsx b/app/analyze/page.tsx index cc6ccc7..9dfaf13 100644 --- a/app/analyze/page.tsx +++ b/app/analyze/page.tsx @@ -219,6 +219,7 @@ const AnalyzeContent = memo(() => { mapView={mapView} onMapViewChange={setMapView} prChangedFiles={prChangedFiles} + betweennessScores={data.betweennessScores ?? {}} /> )} diff --git a/app/api/analyze/route.ts b/app/api/analyze/route.ts index 735919c..fe36206 100644 --- a/app/api/analyze/route.ts +++ b/app/api/analyze/route.ts @@ -17,7 +17,7 @@ import { } from "@/lib/pipeline/ast-pipeline"; import { GitHubAuthError } from "@/lib/github"; -const ANALYSIS_VERSION = 10; +const ANALYSIS_VERSION = 14; // ── SafeStream ──────────────────────────────────────────────────────────────── class SafeStream { diff --git a/app/api/v1/analyze/route.ts b/app/api/v1/analyze/route.ts index e2a5843..95a716d 100644 --- a/app/api/v1/analyze/route.ts +++ b/app/api/v1/analyze/route.ts @@ -8,7 +8,7 @@ import { ratelimitApiKey } from "@/lib/ratelimit"; import { parseRepoUrl, GitHubAuthError } from "@/lib/github"; import { runAstPipeline, PipelineError } from "@/lib/pipeline/ast-pipeline"; -const ANALYSIS_VERSION = 10; +const ANALYSIS_VERSION = 14; const PIPELINE_ERROR_STATUS: Record = { INVALID_REPO_URL: 400, diff --git a/components/ArchitectureMap.tsx b/components/ArchitectureMap.tsx index b9c8024..8c4da26 100644 --- a/components/ArchitectureMap.tsx +++ b/components/ArchitectureMap.tsx @@ -47,6 +47,28 @@ import { getRankedArticulationPoints, type RankedArticulationPoint, } from "@/lib/algorithms/articulationPoints"; +import { + betweennessToSeverity, + BETWEENNESS_SEVERITY_COLORS, +} from "@/lib/algorithms/betweenness"; +type BetweennessSeverity = keyof typeof BETWEENNESS_SEVERITY_COLORS; + +// ─── Betweenness severity → Tailwind classes ─────────────────────────────── +const BETWEENNESS_SEVERITY_TW: Record = { + critical: { bg: "bg-red-500" }, + high: { bg: "bg-orange-500" }, + medium: { bg: "bg-yellow-500" }, + low: { bg: "bg-blue-500" }, +}; + +const BETWEENNESS_RING_COLOR: Record = { + critical: "#ef4444", + high: "#f97316", + medium: "#eab308", + low: "transparent", +}; + +// ─── Pure helper functions (stable references, no closures) ─────────────── function detectCircularDependencies(graph: Record): { cycleNodes: Set; @@ -136,7 +158,6 @@ function computePrBlastRadius( return { modifiedNodes, blastNodes }; } -// ── NEW: Self-contained PageRank computation ────────────────────────────────── function computePageRank( graph: Record, iterations = 20, @@ -162,12 +183,10 @@ function computePageRank( Object.assign(scores, next); } - // Normalize to 0–100 const max = Math.max(...Object.values(scores), 1); nodes.forEach((n) => (scores[n] = Math.round((scores[n] / max) * 100))); return scores; } -// ───────────────────────────────────────────────────────────────────────────── type PageRankTier = 0 | 1 | 2 | 3; @@ -205,6 +224,8 @@ interface GlassNodeData { isArticulationPoint?: boolean; apDisconnects?: number; isBridge?: boolean; + betweennessScore?: number; + betweennessSeverity?: BetweennessSeverity; } const PR_TIER_STYLES: Record< @@ -265,7 +286,16 @@ const HEATMAP_STYLES: Record< }, }; -const GlassNode = ({ data }: { data: GlassNodeData }) => { +// ─── PERF FIX 1: Wrap GlassNode in React.memo ───────────────────────────── +// Without memo, all 85 nodes re-render on every state change (mode toggle, +// node click, etc.). With memo, only nodes whose `data` reference actually +// changed will re-render. ReactFlow preserves data identity via useNodesState, +// so unaffected nodes get skipped entirely. +const GlassNode = React.memo(function GlassNode({ + data, +}: { + data: GlassNodeData; +}) { const { isBlastRadius, isDimmed, @@ -277,8 +307,17 @@ const GlassNode = ({ data }: { data: GlassNodeData }) => { pageRankTier, pageRankActive, pageRankScore, + betweennessScore, + betweennessSeverity, } = data; + const betweennessRingStyle: React.CSSProperties = + betweennessSeverity && betweennessSeverity !== "low" + ? { + boxShadow: `0 0 0 2px ${BETWEENNESS_RING_COLOR[betweennessSeverity]}`, + } + : {}; + if ( pageRankActive && pageRankTier !== undefined && @@ -293,7 +332,8 @@ const GlassNode = ({ data }: { data: GlassNodeData }) => { return (
{ PR {pageRankScore}
)} + {betweennessSeverity && ( +
+ + + Betweenness:{" "} + + {betweennessSeverity.toUpperCase()} + {" "} + {betweennessScore !== undefined && + `(${(betweennessScore * 100).toFixed(1)}%)`} + +
+ )} { } return ( -
+
{ {data.apDisconnects} files affected
)} + {betweennessSeverity && ( +
+ + + Betweenness:{" "} + + {betweennessSeverity.toUpperCase()} + {" "} + {betweennessScore !== undefined && + `(${(betweennessScore * 100).toFixed(1)}%)`} + +
+ )}
{ /> ); -}; +}); +// ─── PERF FIX 2: nodeTypes at module level (not inside component) ────────── +// This was already correct in the original. Defined here as a stable constant +// so ReactFlow never sees a new object reference across renders. const nodeTypes = { glass: GlassNode }; interface ForceNode extends Node { @@ -584,6 +657,8 @@ function getForceLayoutedElements( }; } +// ─── Sidebar ─────────────────────────────────────────────────────────────── + interface SidebarProps { nodeCount: number; cycleCount: number; @@ -605,7 +680,11 @@ interface SidebarProps { pageRankTopFiles: Array<{ path: string; score: number }>; } -function AnalysisSidebar({ +// ─── PERF FIX 3: Wrap AnalysisSidebar in React.memo ────────────────────── +// Sidebar is a heavy component (~600 lines of JSX). Without memo it re-renders +// on every node click and mode change even though its own props haven't changed. +// With memo it only re-renders when sidebar-relevant props actually change. +const AnalysisSidebar = React.memo(function AnalysisSidebar({ nodeCount, cycleCount, cycleNodes, @@ -1485,7 +1564,9 @@ function AnalysisSidebar({ ); -} +}); + +// ─── Main Component ──────────────────────────────────────────────────────── export default function ArchitectureMap({ dependencyGraph = {}, @@ -1493,12 +1574,14 @@ export default function ArchitectureMap({ fileMetrics = [], prChangedFiles = [], pageRankScores = {}, + betweennessScores = {}, }: { dependencyGraph: Record; entryPoints: string[]; fileMetrics?: { path: string; size: number }[]; prChangedFiles?: string[]; pageRankScores?: Record; + betweennessScores?: Record; }) { const [selectedNode, setSelectedNode] = useState(null); const previousGraphRef = useRef(""); @@ -1508,6 +1591,8 @@ export default function ArchitectureMap({ const [heatmapEnabled, setHeatmapEnabled] = useState(false); const [selectedOrphan, setSelectedOrphan] = useState(null); + // ── Derived data from graph (stable per analysis session) ──────────────── + const { cycleNodes, cycleCount } = useMemo( () => detectCircularDependencies(dependencyGraph), [dependencyGraph], @@ -1523,6 +1608,8 @@ export default function ArchitectureMap({ [dependencyGraph], ); + const orphanSet = useMemo(() => new Set(orphans), [orphans]); + const adjacencyList = useMemo(() => { const rev: Record = {}; Object.keys(dependencyGraph).forEach((src) => { @@ -1547,12 +1634,10 @@ export default function ArchitectureMap({ return { prModifiedNodes: modifiedNodes, prBlastNodes: blastNodes }; }, [prChangedFiles, adjacencyList]); - // ── NEW: Compute PageRank internally if not passed in from parent ────────── const computedPageRankScores = useMemo(() => { if (Object.keys(pageRankScores).length > 0) return pageRankScores; return computePageRank(dependencyGraph); }, [dependencyGraph, pageRankScores]); - // ────────────────────────────────────────────────────────────────────────── const pageRankTopFiles = useMemo( () => @@ -1571,7 +1656,6 @@ export default function ArchitectureMap({ return map; }, [computedPageRankScores]); - // ── Articulation point computation ──────────────────────────────────────── const apResult = useMemo( () => computeArticulationPoints(dependencyGraph), [dependencyGraph], @@ -1589,17 +1673,23 @@ export default function ArchitectureMap({ [apResult], ); - const prevPrFilesRef = useRef(""); - useEffect(() => { - const key = prChangedFiles.join(","); - if (key && key !== prevPrFilesRef.current) { - prevPrFilesRef.current = key; - } - }, [prChangedFiles]); - - const { initialNodes, initialEdges, graphHash } = useMemo(() => { + // ── PERF FIX 4: Split layout memo from decoration memo ─────────────────── + // + // BEFORE: one memo ran the D3 force simulation (500 ticks, ~expensive) AND + // included betweennessScores + computedPageRankScores as deps. Whenever those + // score props changed, the entire simulation re-ran even though node positions + // don't depend on scores. + // + // AFTER: + // layoutMemo → runs force sim, depends only on graph structure + // initialNodes → decorates with scores (no sim), runs on score changes + // + // This means the 500-tick simulation only re-runs when the graph changes, + // not when analysis scores are delivered. + + const { layoutNodes, layoutEdges, graphHash } = useMemo(() => { if (!dependencyGraph || typeof dependencyGraph !== "object") - return { initialNodes: [], initialEdges: [], graphHash: "" }; + return { layoutNodes: [], layoutEdges: [], graphHash: "" }; const nodes: Node[] = []; const edges: Edge[] = []; @@ -1612,20 +1702,28 @@ export default function ArchitectureMap({ label: filePath.split("/").pop() || filePath, fullPath: filePath, isEntry: entryPoints.includes(filePath), + // Static graph-derived properties baked in here so they don't + // need a separate effect later. + isCircular: cycleNodes.has(filePath), + isOrphan: orphanSet.has(filePath), + // Highlighting props — reset to neutral defaults. The mode effect + // overrides these when the user activates a mode. isBlastRadius: false, isDimmed: false, - isCircular: false, - heatmap: undefined, - isOrphan: false, isOrphanHighlighted: false, isPrModified: false, isPrBlast: false, - pageRankScore: computedPageRankScores[filePath] ?? 0, - pageRankTier: getPageRankTier(computedPageRankScores[filePath] ?? 0), pageRankActive: false, isArticulationPoint: false, apDisconnects: 0, isBridge: false, + heatmap: undefined, + // Scores are NOT included here — they're added in initialNodes below + // so that score changes don't re-trigger the force simulation. + pageRankScore: 0, + pageRankTier: 0 as PageRankTier, + betweennessScore: 0, + betweennessSeverity: undefined, }, position: { x: 0, y: 0 }, }); @@ -1644,48 +1742,67 @@ export default function ArchitectureMap({ }); }); - const { nodes: layoutNodes, edges: layoutEdges } = getForceLayoutedElements( - nodes, - edges, - entryPoints, - ); + const { nodes: laidOutNodes, edges: laidOutEdges } = + getForceLayoutedElements(nodes, edges, entryPoints); - const graphHash = JSON.stringify({ + const hash = JSON.stringify({ graphKeys: Object.keys(dependencyGraph).sort(), edgesCount: edges.length, - entryPoints: entryPoints.sort(), + entryPoints: [...entryPoints].sort(), }); - return { initialNodes: layoutNodes, initialEdges: layoutEdges, graphHash }; - }, [dependencyGraph, entryPoints, computedPageRankScores]); + return { + layoutNodes: laidOutNodes, + layoutEdges: laidOutEdges, + graphHash: hash, + }; + // Note: cycleNodes and orphanSet are derived from dependencyGraph so they + // only change when dependencyGraph changes — no extra sim triggers. + }, [dependencyGraph, entryPoints, cycleNodes, orphanSet]); + + // Decorate layout nodes with scores — fast map, no force sim. + const initialNodes = useMemo(() => { + return layoutNodes.map((n) => { + const bScore = betweennessScores[n.id] ?? 0; + const bSeverity = betweennessToSeverity(bScore); + const showRing = bSeverity !== "low"; + return { + ...n, + data: { + ...n.data, + pageRankScore: computedPageRankScores[n.id] ?? 0, + pageRankTier: getPageRankTier(computedPageRankScores[n.id] ?? 0), + betweennessScore: bScore, + betweennessSeverity: showRing ? bSeverity : undefined, + }, + }; + }); + }, [layoutNodes, computedPageRankScores, betweennessScores]); const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes); - const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges); + const [edges, setEdges, onEdgesChange] = useEdgesState(layoutEdges); + // Sync ReactFlow state when graph structure changes (new analysis loaded). useEffect(() => { if (previousGraphRef.current !== graphHash) { setNodes(initialNodes); - setEdges(initialEdges); + setEdges(layoutEdges); previousGraphRef.current = graphHash; } - }, [initialNodes, initialEdges, graphHash, setNodes, setEdges]); - - useEffect(() => { - setNodes((nds) => - nds.map((n) => ({ - ...n, - data: { - ...n.data, - isCircular: cycleNodes.has(n.id), - heatmap: heatmapEnabled - ? (heatmapColors.get(n.id) ?? "green") - : undefined, - isOrphan: orphans.includes(n.id), - }, - })), - ); - }, [cycleNodes, heatmapColors, heatmapEnabled, orphans, setNodes]); - + }, [initialNodes, layoutEdges, graphHash, setNodes, setEdges]); + + // ── PERF FIX 5: Single unified effect for all visual state ─────────────── + // + // BEFORE: two separate effects both called setNodes, causing two render + // cycles on every mode change: + // Effect 1: set isCircular, heatmap, isOrphan + // Effect 2: set all mode-specific highlighting + // + // AFTER: one effect handles everything. isCircular and isOrphan are now + // baked into initialNodes (graph-derived, stable), so this effect only + // handles user-interaction state: mode highlighting + heatmap toggle. + // + // This eliminates one render cycle per interaction. useEffect(() => { if (!activeMode && !selectedNode) { setNodes((nds) => @@ -1701,6 +1818,9 @@ export default function ArchitectureMap({ pageRankActive: false, isArticulationPoint: false, apDisconnects: 0, + heatmap: heatmapEnabled + ? (heatmapColors.get(n.id) ?? "green") + : undefined, }, })), ); @@ -1729,6 +1849,7 @@ export default function ArchitectureMap({ isArticulationPoint: apSet.has(n.id), apDisconnects: apResult.componentSizes.get(n.id) ?? 0, isDimmed: !apSet.has(n.id), + heatmap: undefined, }, })), ); @@ -1771,6 +1892,7 @@ export default function ArchitectureMap({ isOrphanHighlighted: false, isArticulationPoint: false, isDimmed: tier === 0, + heatmap: undefined, }, }; }), @@ -1820,6 +1942,7 @@ export default function ArchitectureMap({ isPrModified: prModifiedNodes.has(n.id), isPrBlast: prBlastNodes.has(n.id), isDimmed: !prModifiedNodes.has(n.id) && !prBlastNodes.has(n.id), + heatmap: undefined, }, })), ); @@ -1873,6 +1996,7 @@ export default function ArchitectureMap({ isOrphanHighlighted: selectedOrphan ? n.id === selectedOrphan : false, + heatmap: undefined, }, })), ); @@ -1904,6 +2028,7 @@ export default function ArchitectureMap({ isArticulationPoint: false, isDimmed: !cycleNodes.has(n.id), isOrphanHighlighted: false, + heatmap: undefined, }, })), ); @@ -1956,6 +2081,7 @@ export default function ArchitectureMap({ isPrModified: false, isPrBlast: false, isArticulationPoint: false, + heatmap: undefined, }, })), ); @@ -1981,6 +2107,8 @@ export default function ArchitectureMap({ }, [ activeMode, selectedNode, + heatmapEnabled, + heatmapColors, cycleNodes, selectedOrphan, prModifiedNodes, @@ -1991,11 +2119,12 @@ export default function ArchitectureMap({ apSet, apResult, bridgeSet, - rankedAPs, setNodes, setEdges, ]); + // ── Event handlers (all stable via useCallback) ─────────────────────────── + const handleNodeClick = useCallback((_: React.MouseEvent, node: Node) => { setSelectedOrphan(null); setSelectedNode(node.id); diff --git a/components/DirectoryTreeVisualizer.tsx b/components/DirectoryTreeVisualizer.tsx index 165a181..c6adacd 100644 --- a/components/DirectoryTreeVisualizer.tsx +++ b/components/DirectoryTreeVisualizer.tsx @@ -140,6 +140,9 @@ const TreeNode = memo(({ data }: { data: TreeNodeData }) => { }); TreeNode.displayName = "TreeNode"; +// ─── PERF FIX: nodeTypes at module level (not inside component) ─────────── +const nodeTypes = { treeNode: TreeNode }; + export default function DirectoryTreeVisualizer({ metrics, }: { @@ -147,8 +150,6 @@ export default function DirectoryTreeVisualizer({ }) { const [selectedPath, setSelectedPath] = useState(null); - const nodeTypes = useMemo(() => ({ treeNode: TreeNode }), []); - const { initialNodes, initialEdges } = useMemo(() => { if (!metrics || metrics.length === 0) return { initialNodes: [], initialEdges: [] }; @@ -222,10 +223,9 @@ export default function DirectoryTreeVisualizer({ id: `e-${link.source.data.path}-${link.target.data.path}`, source: link.source.data.path, target: link.target.data.path, - type: "smoothstep", // Keep the structured layout + type: "smoothstep", animated: false, style: { stroke: "#334155", strokeWidth: 1.5, opacity: 0.3 }, - // Add this property to slightly round the sharp 90-degree corners! pathOptions: { borderRadius: 12 }, }); }); @@ -285,13 +285,12 @@ export default function DirectoryTreeVisualizer({ return { ...e, - // --- PRINCIPAL UPGRADE: Active flow animation on isolated paths --- animated: isActiveEdge, style: { ...e.style, opacity: isActiveEdge ? 1 : 0.05, strokeWidth: isActiveEdge ? 2.5 : 1, - stroke: isActiveEdge ? "#10b981" : "#1e293b", // Emerald glow for active flow + stroke: isActiveEdge ? "#10b981" : "#1e293b", }, }; }), diff --git a/components/analyze/VisualizerPanel.tsx b/components/analyze/VisualizerPanel.tsx index 2500cd8..06cc0e0 100644 --- a/components/analyze/VisualizerPanel.tsx +++ b/components/analyze/VisualizerPanel.tsx @@ -37,6 +37,7 @@ interface VisualizerPanelProps { mapView: MapViewType; onMapViewChange: (view: MapViewType) => void; prChangedFiles?: string[]; + betweennessScores?: Record; // NEW } export default function VisualizerPanel({ @@ -44,6 +45,7 @@ export default function VisualizerPanel({ mapView, onMapViewChange, prChangedFiles = [], + betweennessScores = {}, // NEW }: VisualizerPanelProps) { return ( Blueprint Map - - VISUAL LAYOUT - + {/* NEW: wrap subtitle + legend chip in a row */} +
+ + VISUAL LAYOUT + + {mapView === "graph" && + Object.keys(betweennessScores).length > 0 && ( + + 🔶 orange ring = high betweenness + + )} +
@@ -105,6 +116,7 @@ export default function VisualizerPanel({ fileMetrics={data.fileMetrics} prChangedFiles={prChangedFiles} pageRankScores={data.pageRankScores ?? {}} + betweennessScores={betweennessScores} // NEW /> ) : (
diff --git a/lib/__tests__/cfg-builder.test.ts b/lib/__tests__/cfg-builder.test.ts new file mode 100644 index 0000000..82e0092 --- /dev/null +++ b/lib/__tests__/cfg-builder.test.ts @@ -0,0 +1,146 @@ +// lib/__tests__/cfg-builder.test.ts + +import { analyzeCFG, analyzeCFGBatch, cfgResultsToLLMSummary } from "../cfg-builder"; + +describe("analyzeCFG", () => { + it("returns parseError for unparseable content", () => { + const result = analyzeCFG("test.ts", "const x = {{{{"); + // errorRecovery:true means it may still parse, but finding count = 0 + // Just assert it doesn't throw + expect(result.filePath).toBe("test.ts"); + }); + + it("detects unreachable code after return", () => { + const code = ` + function foo() { + return 1; + const x = 2; + } + `; + const result = analyzeCFG("foo.ts", code); + const unreachable = result.findings.filter( + (f) => f.type === "unreachable_code", + ); + expect(unreachable.length).toBeGreaterThan(0); + expect(unreachable[0].severity).toBe("error"); + }); + + it("does not flag reachable code", () => { + const code = ` + function bar() { + const x = 1; + const y = 2; + return x + y; + } + `; + const result = analyzeCFG("bar.ts", code); + expect( + result.findings.filter((f) => f.type === "unreachable_code").length, + ).toBe(0); + }); + + it("detects missing error handling in async function", () => { + const code = ` + async function fetchData() { + const res = await fetch('/api/data'); + return res.json(); + } + `; + const result = analyzeCFG("fetch.ts", code); + const missing = result.findings.filter( + (f) => f.type === "missing_error_handling", + ); + expect(missing.length).toBeGreaterThan(0); + expect(missing[0].severity).toBe("warning"); + }); + + it("does not flag async function with try/catch", () => { + const code = ` + async function safe() { + try { + const res = await fetch('/api'); + return res.json(); + } catch (e) { + console.error(e); + } + } + `; + const result = analyzeCFG("safe.ts", code); + expect( + result.findings.filter((f) => f.type === "missing_error_handling").length, + ).toBe(0); + }); + + it("detects while(true) without break", () => { + const code = ` + function poll() { + while (true) { + console.log('tick'); + } + } + `; + const result = analyzeCFG("poll.ts", code); + const loops = result.findings.filter( + (f) => f.type === "infinite_loop_candidate", + ); + expect(loops.length).toBeGreaterThan(0); + }); + + it("does not flag while(true) with break", () => { + const code = ` + function run() { + while (true) { + if (done) break; + } + } + `; + const result = analyzeCFG("run.ts", code); + expect( + result.findings.filter((f) => f.type === "infinite_loop_candidate").length, + ).toBe(0); + }); +}); + +describe("analyzeCFGBatch", () => { + it("only processes JS/TS files", () => { + const files = [ + { path: "lib/utils.ts", content: "function f() { return 1; }" }, + { path: "styles/main.css", content: ".foo { color: red; }" }, + { path: "data.json", content: '{"key": "value"}' }, + ]; + const results = analyzeCFGBatch(files, {}, 5); + expect(results.every((r) => r.filePath.endsWith(".ts"))).toBe(true); + }); + + it("respects topN limit", () => { + const files = Array.from({ length: 10 }, (_, i) => ({ + path: `lib/file${i}.ts`, + content: "export const x = 1;", + })); + const scores = Object.fromEntries(files.map((f, i) => [f.path, i * 10])); + const results = analyzeCFGBatch(files, scores, 3); + expect(results.length).toBeLessThanOrEqual(3); + }); +}); + +describe("cfgResultsToLLMSummary", () => { + it("returns empty string when no findings", () => { + const result = analyzeCFG("clean.ts", "export const x = 1;"); + expect(cfgResultsToLLMSummary([result])).toBe(""); + }); + + it("includes file path and finding description in output", () => { + const code = ` + function f() { + return 1; + const x = 2; + } + `; + const result = analyzeCFG("problem.ts", code); + const summary = cfgResultsToLLMSummary([result]); + if (result.findings.length > 0) { + expect(summary).toContain("problem.ts"); + expect(summary).toContain("ERROR"); + } + }); +}); \ No newline at end of file diff --git a/lib/__tests__/dependency-graph-depth.test.ts b/lib/__tests__/dependency-graph-depth.test.ts new file mode 100644 index 0000000..44407f6 --- /dev/null +++ b/lib/__tests__/dependency-graph-depth.test.ts @@ -0,0 +1,70 @@ +// lib/__tests__/dependency-graph-depth.test.ts +// +// Tests for the getFilesByDepth function added to lib/dependency-graph.ts. +// Import path assumes you've spliced getFilesByDepth into that file. + +import { getFilesByDepth } from "../dependency-graph"; + +describe("getFilesByDepth", () => { + const graph = { + "app/page.tsx": ["components/Nav.tsx", "lib/utils.ts"], + "components/Nav.tsx": ["lib/constants.ts"], + "lib/utils.ts": ["lib/helpers.ts"], + "lib/helpers.ts": [], + "lib/constants.ts": [], + "orphan.ts": [], + }; + + it("returns entry points at depth 0", () => { + const result = getFilesByDepth(graph, ["app/page.tsx"], 3, 60); + expect(result.depthMap["app/page.tsx"]).toBe(0); + }); + + it("returns direct deps at depth 1", () => { + const result = getFilesByDepth(graph, ["app/page.tsx"], 3, 60); + expect(result.depthMap["components/Nav.tsx"]).toBe(1); + expect(result.depthMap["lib/utils.ts"]).toBe(1); + }); + + it("returns transitive deps at depth 2", () => { + const result = getFilesByDepth(graph, ["app/page.tsx"], 3, 60); + expect(result.depthMap["lib/constants.ts"]).toBe(2); + expect(result.depthMap["lib/helpers.ts"]).toBe(2); + }); + + it("respects maxDepth — does not go deeper than specified", () => { + const result = getFilesByDepth(graph, ["app/page.tsx"], 1, 60); + // depth 2 nodes should not appear + expect(result.depthMap["lib/constants.ts"]).toBeUndefined(); + expect(result.depthMap["lib/helpers.ts"]).toBeUndefined(); + }); + + it("respects maxNodes hard cap", () => { + const result = getFilesByDepth(graph, ["app/page.tsx"], 3, 2); + expect(result.files.length).toBeLessThanOrEqual(2); + }); + + it("includes orphan nodes via fallbackRanked when BFS doesn't fill quota", () => { + const result = getFilesByDepth( + graph, + ["app/page.tsx"], + 3, + 60, + ["orphan.ts"], + ); + expect(result.files).toContain("orphan.ts"); + expect(result.depthMap["orphan.ts"]).toBe(4); // maxDepth + 1 = fallback tier + }); + + it("seeds from high-fanIn nodes when entryPoints is empty", () => { + const result = getFilesByDepth(graph, [], 3, 60); + // Should not throw and should return some files + expect(result.files.length).toBeGreaterThan(0); + }); + + it("does not include duplicate nodes", () => { + const result = getFilesByDepth(graph, ["app/page.tsx"], 3, 60); + const uniqueFiles = new Set(result.files); + expect(result.files.length).toBe(uniqueFiles.size); + }); +}); \ No newline at end of file diff --git a/lib/__tests__/file-filter.test.ts b/lib/__tests__/file-filter.test.ts new file mode 100644 index 0000000..5419900 --- /dev/null +++ b/lib/__tests__/file-filter.test.ts @@ -0,0 +1,67 @@ +// lib/__tests__/file-filter.test.ts + +import { shouldSkipFile, filterFiles } from "../file-filter"; + +describe("shouldSkipFile", () => { + // Directory-based skips + it("skips node_modules", () => + expect(shouldSkipFile("node_modules/lodash/index.js")).toBe(true)); + it("skips .next", () => + expect(shouldSkipFile(".next/server/app/page.js")).toBe(true)); + it("skips dist", () => + expect(shouldSkipFile("dist/index.js")).toBe(true)); + + // Extension-based skips + it("skips .min.js", () => + expect(shouldSkipFile("public/vendor.min.js")).toBe(true)); + it("skips .bundle.js", () => + expect(shouldSkipFile("public/app.bundle.js")).toBe(true)); + it("skips .d.ts", () => + expect(shouldSkipFile("types/global.d.ts")).toBe(true)); + it("skips .generated.ts", () => + expect(shouldSkipFile("lib/schema.generated.ts")).toBe(true)); + it("skips .map files", () => + expect(shouldSkipFile("public/main.js.map")).toBe(true)); + + // Filename pattern skips + it("skips .mock.ts", () => + expect(shouldSkipFile("lib/api.mock.ts")).toBe(true)); + it("skips .fixture.tsx", () => + expect(shouldSkipFile("components/Button.fixture.tsx")).toBe(true)); + it("skips __mocks__ directory", () => + expect(shouldSkipFile("lib/__mocks__/supabase.ts")).toBe(true)); + it("skips .stories.tsx", () => + expect(shouldSkipFile("components/Button.stories.tsx")).toBe(true)); + + // Size-based skip + it("skips files over maxSizeBytes", () => + expect(shouldSkipFile("lib/big.ts", 100_000)).toBe(true)); + it("allows files under maxSizeBytes", () => + expect(shouldSkipFile("lib/small.ts", 1_000)).toBe(false)); + + // Allowed files + it("allows normal source files", () => + expect(shouldSkipFile("lib/utils.ts")).toBe(false)); + it("allows React components", () => + expect(shouldSkipFile("components/Button.tsx")).toBe(false)); + it("allows API routes", () => + expect(shouldSkipFile("app/api/analyze/route.ts")).toBe(false)); + it("allows test files themselves", () => + expect(shouldSkipFile("lib/utils.test.ts")).toBe(false)); +}); + +describe("filterFiles", () => { + it("removes skipped files and keeps valid ones", () => { + const files = [ + { path: "lib/utils.ts", size: 1000 }, + { path: "dist/bundle.js", size: 5000 }, + { path: "lib/api.mock.ts", size: 500 }, + { path: "components/Nav.tsx", size: 2000 }, + ]; + const result = filterFiles(files); + expect(result.map((f) => f.path)).toEqual([ + "lib/utils.ts", + "components/Nav.tsx", + ]); + }); +}); \ No newline at end of file diff --git a/lib/algorithms/__tests__/betweenness.test.ts b/lib/algorithms/__tests__/betweenness.test.ts new file mode 100644 index 0000000..1b4e633 --- /dev/null +++ b/lib/algorithms/__tests__/betweenness.test.ts @@ -0,0 +1,79 @@ +// lib/algorithms/__tests__/betweenness.test.ts + +import { computeBetweenness, betweennessToSeverity } from "../betweenness"; + +describe("computeBetweenness", () => { + it("returns empty scores for empty graph", () => { + const result = computeBetweenness({}); + expect(result.scores.size).toBe(0); + expect(result.topK(5)).toEqual([]); + }); + + it("returns empty scores for graph with fewer than 3 nodes", () => { + const result = computeBetweenness({ a: ["b"], b: [] }); + expect(result.scores.size).toBe(0); + }); + + it("assigns high betweenness to a bridge node in a chain a→b→c→d", () => { + const graph = { a: ["b"], b: ["c"], c: ["d"], d: [] }; + const result = computeBetweenness(graph, true); + + // b and c sit on the only path from a to d — they must have betweenness > 0 + expect(result.scores.get("b")).toBeGreaterThan(0); + expect(result.scores.get("c")).toBeGreaterThan(0); + // a and d are endpoints — betweenness = 0 in a simple chain + expect(result.scores.get("a")).toBe(0); + expect(result.scores.get("d")).toBe(0); + }); + + it("assigns highest betweenness to the hub in a star graph", () => { + // hub imports all leaves; all paths between leaves go through hub + const graph = { + hub: ["l1", "l2", "l3", "l4"], + l1: [], + l2: [], + l3: [], + l4: [], + }; + const result = computeBetweenness(graph, true); + const top = result.topK(1); + expect(top[0][0]).toBe("hub"); + }); + + it("topK returns at most k results sorted descending", () => { + const graph = { + a: ["b", "c"], + b: ["d"], + c: ["d"], + d: ["e"], + e: [], + }; + const result = computeBetweenness(graph, true); + const top2 = result.topK(2); + expect(top2.length).toBeLessThanOrEqual(2); + if (top2.length === 2) { + expect(top2[0][1]).toBeGreaterThanOrEqual(top2[1][1]); + } + }); + + it("normalized scores are in [0, 1]", () => { + const graph = { + a: ["b", "c"], + b: ["d"], + c: ["d"], + d: [], + }; + const result = computeBetweenness(graph, true); + for (const score of result.scores.values()) { + expect(score).toBeGreaterThanOrEqual(0); + expect(score).toBeLessThanOrEqual(1); + } + }); +}); + +describe("betweennessToSeverity", () => { + it("maps 0 to low", () => expect(betweennessToSeverity(0)).toBe("low")); + it("maps 0.05 to medium", () => expect(betweennessToSeverity(0.05)).toBe("medium")); + it("maps 0.10 to high", () => expect(betweennessToSeverity(0.10)).toBe("high")); + it("maps 0.20 to critical", () => expect(betweennessToSeverity(0.20)).toBe("critical")); +}); \ No newline at end of file diff --git a/lib/algorithms/betweenness.ts b/lib/algorithms/betweenness.ts new file mode 100644 index 0000000..93a740a --- /dev/null +++ b/lib/algorithms/betweenness.ts @@ -0,0 +1,169 @@ +// lib/algorithms/betweenness.ts +// +// Brandes' algorithm for betweenness centrality on a directed graph. +// O(V * E) time, O(V + E) space — the best known exact algorithm for +// unweighted graphs. No external library required; matches the interface +// style of pagerank.ts and articulationPoints.ts already in this codebase. +// +// Betweenness centrality of node v = +// Σ (s ≠ v ≠ t) [ σ(s,t|v) / σ(s,t) ] +// where σ(s,t) is the number of shortest paths from s to t, +// and σ(s,t|v) is the subset of those paths passing through v. +// +// In CodeAutopsy terms: a file with high betweenness sits on many +// shortest import chains between other files. Removing or breaking it +// disrupts the maximum number of indirect dependency paths — making it +// a higher-priority refactor/review target than fan-in or PageRank alone +// can identify. + +export interface BetweennessResult { + scores: Map; + topK: (k: number) => Array<[string, number]>; + normalized: boolean; +} + +/** + * Compute betweenness centrality for every node in a directed dependency graph. + * + * @param graph Adjacency list: graph[A] = [B, C] means A imports B and C. + * @param normalize When true, divide each score by (N-1)(N-2) so all scores + * fall in [0, 1] regardless of graph size. Default: true. + */ +export function computeBetweenness( + graph: Record, + normalize = true, +): BetweennessResult { + // ── 0. Fast path ────────────────────────────────────────────────────────── + const nodeSet = new Set(); + for (const [src, targets] of Object.entries(graph)) { + nodeSet.add(src); + for (const t of targets) nodeSet.add(t); + } + + const nodes = Array.from(nodeSet); + const N = nodes.length; + + const empty: BetweennessResult = { + scores: new Map(), + topK: () => [], + normalized: normalize, + }; + + if (N < 3) return empty; + + const nodeIndex = new Map(nodes.map((n, i) => [n, i])); + + // Build numeric adjacency list for O(1) index lookups + const adj: number[][] = Array.from({ length: N }, () => []); + for (const [src, targets] of Object.entries(graph)) { + const u = nodeIndex.get(src); + if (u === undefined) continue; + for (const t of targets) { + const v = nodeIndex.get(t); + if (v !== undefined && v !== u) adj[u].push(v); + } + } + + // ── 1. Brandes' algorithm ───────────────────────────────────────────────── + const cb = new Float64Array(N); // accumulator for centrality + + // BFS queue and per-source arrays — allocated once and reused each source + const bfsQueue = new Int32Array(N); + const sigma = new Float64Array(N); // shortest-path counts from source s + const dist = new Int32Array(N); // shortest-path distances from s + const delta = new Float64Array(N); // dependency accumulator + + // Stack of nodes in order of non-increasing distance from s + // (used for back-propagation) + const stack: number[] = []; + + // Predecessor lists: pred[v] = nodes on shortest paths to v from s + const pred: number[][] = Array.from({ length: N }, () => []); + + for (let s = 0; s < N; s++) { + // Reset per-source state + stack.length = 0; + for (let i = 0; i < N; i++) { + pred[i].length = 0; + sigma[i] = 0; + dist[i] = -1; + delta[i] = 0; + } + sigma[s] = 1; + dist[s] = 0; + + // BFS from s + let head = 0; + let tail = 0; + bfsQueue[tail++] = s; + + while (head < tail) { + const v = bfsQueue[head++]; + stack.push(v); + + for (const w of adj[v]) { + // First discovery of w from s + if (dist[w] < 0) { + bfsQueue[tail++] = w; + dist[w] = dist[v] + 1; + } + // Shortest path to w via v + if (dist[w] === dist[v] + 1) { + sigma[w] += sigma[v]; + pred[w].push(v); + } + } + } + + // Back-propagation: accumulate pair dependencies + while (stack.length > 0) { + const w = stack.pop()!; + for (const v of pred[w]) { + delta[v] += (sigma[v] / sigma[w]) * (1 + delta[w]); + } + if (w !== s) cb[w] += delta[w]; + } + } + + // ── 2. Normalization ────────────────────────────────────────────────────── + const normFactor = normalize && N > 2 ? 1 / ((N - 1) * (N - 2)) : 1; + + const scores = new Map(); + for (let i = 0; i < N; i++) { + scores.set(nodes[i], cb[i] * normFactor); + } + + const topK = (k: number): Array<[string, number]> => + Array.from(scores.entries()) + .sort((a, b) => b[1] - a[1]) + .slice(0, k); + + return { scores, topK, normalized: normalize }; +} + +/** + * Maps a normalized betweenness score [0, 1] to a severity label. + * Used for badge rendering in ArchitectureMap node overlays. + */ +export function betweennessToSeverity( + score: number, +): "critical" | "high" | "medium" | "low" { + if (score >= 0.15) return "critical"; + if (score >= 0.07) return "high"; + if (score >= 0.01) return "medium"; + return "low"; +} + +/** + * Severity → Tailwind border color class for node highlighting. + * Consistent with the heatmap convention used in rankToOklch (pagerank.ts). + */ +export const BETWEENNESS_SEVERITY_COLORS: Record< + ReturnType, + string +> = { + critical: "#ef4444", // red-500 + high: "#f97316", // orange-500 + medium: "#eab308", // yellow-500 + low: "#3b82f6", // blue-500 +}; \ No newline at end of file diff --git a/lib/analysis-cache.ts b/lib/analysis-cache.ts new file mode 100644 index 0000000..b9574a3 --- /dev/null +++ b/lib/analysis-cache.ts @@ -0,0 +1,161 @@ +// lib/analysis-cache.ts +// +// Semantic caching layer for CodeAutopsy repo analyses. +// +// Cache key: analyses table row keyed on (repo_url, commit_sha, analysis_version, user_id). +// This table already exists in your Supabase schema (confirmed from screenshot). +// The pipeline already reads from it via the checkCache callback in runAstPipeline. +// This module adds the three missing pieces: +// 1. getLatestCommitSha — fetches the HEAD sha from GitHub API. +// 2. isCacheStale — compares stored commit_sha vs live HEAD. +// 3. invalidateUserCache — hard-deletes rows for a (repo_url, user_id) pair. +// 4. forceReanalyze — used by /api/reanalyze route to bust cache. +// +// TTL is enforced via a Postgres partial index or a where-clause filter on +// created_at. No cron needed — stale rows are just ignored on read, and +// the nightly Supabase pg_cron cleanup (if configured) handles GC. + +import { SupabaseClient } from "@supabase/supabase-js"; + +const CACHE_TTL_HOURS = 24; +const ANALYSIS_VERSION = 14; // keep in sync with app/api/analyze/route.ts + +// ── GitHub HEAD sha ────────────────────────────────────────────────────────A + +/** + * Fetches the HEAD commit SHA of the default branch for a repo. + * Uses the same token-passing pattern as the rest of the codebase. + * + * @returns SHA string, or null on any network / auth failure. + */ +export async function getLatestCommitSha( + owner: string, + repo: string, + githubToken: string, +): Promise { + try { + const res = await fetch( + `https://api.github.com/repos/${owner}/${repo}/commits/HEAD`, + { + headers: { + Authorization: `Bearer ${githubToken}`, + Accept: "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + }, + next: { revalidate: 60 }, // Next.js fetch cache: 1 min + }, + ); + + if (!res.ok) return null; + const data = await res.json(); + return typeof data?.sha === "string" ? data.sha : null; + } catch { + return null; + } +} + +// ── Cache staleness check ────────────────────────────────────────────────── + +export interface CacheStatusResult { + hit: boolean; + stale: boolean; + storedSha: string | null; + liveSha: string | null; + cachedAt: string | null; +} + +/** + * Checks if a valid, non-stale cache entry exists for the given repo + user. + * + * "Stale" means either: + * - The stored commit_sha differs from the current HEAD sha. + * - The cached row is older than CACHE_TTL_HOURS. + */ +export async function getCacheStatus( + supabase: SupabaseClient, + repoUrl: string, + userId: string | null, + owner: string, + repo: string, + githubToken: string, +): Promise { + const staleCutoff = new Date( + Date.now() - CACHE_TTL_HOURS * 60 * 60 * 1000, + ).toISOString(); + + const { data: row } = await supabase + .from("analyses") + .select("commit_sha, created_at") + .eq("repo_url", repoUrl) + .eq("analysis_version", ANALYSIS_VERSION) + .eq("user_id", userId ?? "") + .gte("created_at", staleCutoff) + .order("created_at", { ascending: false }) + .limit(1) + .maybeSingle(); + + if (!row) { + return { hit: false, stale: false, storedSha: null, liveSha: null, cachedAt: null }; + } + + const liveSha = await getLatestCommitSha(owner, repo, githubToken); + const stale = liveSha !== null && liveSha !== row.commit_sha; + + return { + hit: !stale, + stale, + storedSha: row.commit_sha, + liveSha, + cachedAt: row.created_at, + }; +} + +// ── Cache invalidation ───────────────────────────────────────────────────── + +/** + * Deletes all cached rows for (repoUrl, userId). + * Called by /api/reanalyze when the user forces a fresh run. + * + * Returns the number of rows deleted, or -1 on error. + */ +export async function invalidateUserCache( + supabase: SupabaseClient, + repoUrl: string, + userId: string, +): Promise { + const { data, error } = await supabase + .from("analyses") + .delete() + .eq("repo_url", repoUrl) + .eq("user_id", userId) + .select("id"); + + if (error) { + console.error("[analysis-cache] invalidateUserCache error:", error.message); + return -1; + } + + return data?.length ?? 0; +} + +/** + * Admin-level invalidation: deletes all cached rows for a repo regardless + * of user. Only call from server-side contexts with service-role key. + */ +export async function invalidateRepoCache( + supabase: SupabaseClient, + repoUrl: string, +): Promise { + const { data, error } = await supabase + .from("analyses") + .delete() + .eq("repo_url", repoUrl) + .select("id"); + + if (error) { + console.error("[analysis-cache] invalidateRepoCache error:", error.message); + return -1; + } + + return data?.length ?? 0; +} \ No newline at end of file diff --git a/lib/cfg-builder.ts b/lib/cfg-builder.ts new file mode 100644 index 0000000..48ccafc --- /dev/null +++ b/lib/cfg-builder.ts @@ -0,0 +1,328 @@ +// lib/cfg-builder.ts +// +// Control Flow Graph (CFG) builder for JS/TS files. +// +// Uses @babel/parser which is a dependency of Next.js itself and is always +// present in node_modules even without an explicit package.json entry. +// If you want to import it explicitly, run: npm install --save-dev @babel/parser @babel/types +// +// What this detects (static analysis only — no runtime execution): +// 1. Unreachable code — statements after return/throw/break/continue. +// 2. Missing error handling — async functions with await but no try/catch. +// 3. Infinite loop candidates — while(true) / for(;;) without a break. +// +// Intentional non-goals: +// - Full CFG edge construction (control flow edges between basic blocks). +// That would require a full compiler pass and blows the Groq token budget. +// Instead we return structured findings per function that the LLM can reason about. +// - Runtime type checking (needs execution context). + +import * as parser from "@babel/parser"; +import type { + File, + FunctionDeclaration, + ArrowFunctionExpression, + FunctionExpression, + BlockStatement, + Statement, + Node, +} from "@babel/types"; + +export interface CFGFinding { + type: "unreachable_code" | "missing_error_handling" | "infinite_loop_candidate"; + functionName: string | null; + line: number; + description: string; + severity: "warning" | "error"; +} + +export interface CFGResult { + filePath: string; + findings: CFGFinding[]; + functionsAnalyzed: number; + parseError: string | null; +} + +// ── Helpers ─────────────────────────────────────────────────────────────────── + +type FunctionNode = + | FunctionDeclaration + | ArrowFunctionExpression + | FunctionExpression; + +function getFunctionName(node: FunctionNode): string | null { + if (node.type === "FunctionDeclaration" && node.id) return node.id.name; + if (node.type === "FunctionExpression" && node.id) return node.id.name; + return null; +} + +function isTerminator(node: Statement): boolean { + return ( + node.type === "ReturnStatement" || + node.type === "ThrowStatement" || + node.type === "BreakStatement" || + node.type === "ContinueStatement" + ); +} + +function findUnreachableStatements( + body: Statement[], + functionName: string | null, +): CFGFinding[] { + const findings: CFGFinding[] = []; + + for (let i = 0; i < body.length - 1; i++) { + if (isTerminator(body[i])) { + const nextStmt = body[i + 1]; + findings.push({ + type: "unreachable_code", + functionName, + line: nextStmt.loc?.start.line ?? 0, + description: `Unreachable statement after ${body[i].type} at line ${body[i].loc?.start.line ?? "?"}`, + severity: "error", + }); + break; // Only report the first unreachable block per function + } + } + + return findings; +} + +function findMissingErrorHandling( + node: FunctionNode, + functionName: string | null, +): CFGFinding[] { + if (!node.async) return []; + + const body = node.body; + if (!body || body.type !== "BlockStatement") return []; + + let hasAwait = false; + let hasTryCatch = false; + + // Simple linear scan — not a full AST walk, intentionally shallow + for (const stmt of body.body) { + if (stmt.type === "TryStatement") { + hasTryCatch = true; + } + if (JSON.stringify(stmt).includes('"type":"AwaitExpression"')) { + hasAwait = true; + } + } + + if (hasAwait && !hasTryCatch) { + return [ + { + type: "missing_error_handling", + functionName, + line: node.loc?.start.line ?? 0, + description: `Async function '${functionName ?? "(anonymous)"}' uses await without try/catch`, + severity: "warning", + }, + ]; + } + + return []; +} + +function findInfiniteLoopCandidates( + body: Statement[], + functionName: string | null, +): CFGFinding[] { + const findings: CFGFinding[] = []; + + for (const stmt of body) { + // while (true) { ... } without a break + if (stmt.type === "WhileStatement") { + const test = stmt.test; + const isTrueLiteral = + test.type === "BooleanLiteral" && test.value === true; + const isNumericOne = + test.type === "NumericLiteral" && test.value === 1; + + if (isTrueLiteral || isNumericOne) { + const block = stmt.body; + const hasBreak = + block.type === "BlockStatement" && + block.body.some( + (s) => s.type === "BreakStatement" || s.type === "ReturnStatement", + ); + + if (!hasBreak) { + findings.push({ + type: "infinite_loop_candidate", + functionName, + line: stmt.loc?.start.line ?? 0, + description: `while(true) loop without break/return — potential infinite loop`, + severity: "warning", + }); + } + } + } + + // for (;;) { ... } without a break + if ( + stmt.type === "ForStatement" && + stmt.test == null && + stmt.init == null && + stmt.update == null + ) { + const block = stmt.body; + const hasBreak = + block.type === "BlockStatement" && + block.body.some( + (s) => s.type === "BreakStatement" || s.type === "ReturnStatement", + ); + + if (!hasBreak) { + findings.push({ + type: "infinite_loop_candidate", + functionName, + line: stmt.loc?.start.line ?? 0, + description: `for(;;) loop without break/return — potential infinite loop`, + severity: "warning", + }); + } + } + } + + return findings; +} + +function walkFunctions( + ast: File, + findings: CFGFinding[], +): number { + let count = 0; + + function visit(node: Node): void { + if ( + node.type === "FunctionDeclaration" || + node.type === "FunctionExpression" || + node.type === "ArrowFunctionExpression" + ) { + const fn = node as FunctionNode; + const name = getFunctionName(fn); + count++; + + const body = fn.body; + if (body && body.type === "BlockStatement") { + findings.push(...findUnreachableStatements(body.body, name)); + findings.push(...findInfiniteLoopCandidates(body.body, name)); + } + + findings.push(...findMissingErrorHandling(fn, name)); + } + + // Recurse into child nodes + for (const key of Object.keys(node)) { + const child = (node as unknown as Record)[key]; + if (Array.isArray(child)) { + for (const item of child) { + if (item && typeof item === "object" && "type" in item) { + visit(item as Node); + } + } + } else if (child && typeof child === "object" && "type" in child) { + visit(child as Node); + } + } + } + + visit(ast.program); + return count; +} + +// ── Public API ──────────────────────────────────────────────────────────────── + +/** + * Analyzes a single JS/TS file's content and returns CFG findings. + * Safe to call on any file — returns parseError if Babel can't parse it. + */ +export function analyzeCFG(filePath: string, content: string): CFGResult { + const isTypeScript = + filePath.endsWith(".ts") || filePath.endsWith(".tsx"); + const isJSX = + filePath.endsWith(".jsx") || filePath.endsWith(".tsx"); + + let ast: File; + try { + ast = parser.parse(content, { + sourceType: "module", + plugins: [ + ...(isTypeScript ? (["typescript"] as const) : []), + ...(isJSX ? (["jsx"] as const) : []), + "classProperties", + "classStaticBlock", + "dynamicImport", + "importAssertions", + "optionalChaining", + "nullishCoalescingOperator", + "decorators-legacy", + ], + errorRecovery: true, // don't throw on minor parse errors + strictMode: false, + }); + } catch (err) { + return { + filePath, + findings: [], + functionsAnalyzed: 0, + parseError: err instanceof Error ? err.message : "Parse failed", + }; + } + + const findings: CFGFinding[] = []; + const functionsAnalyzed = walkFunctions(ast, findings); + + return { filePath, findings, functionsAnalyzed, parseError: null }; +} + +/** + * Runs CFG analysis on the top N files by PageRank score. + * Only processes JS/TS files — skips JSON, CSS, HTML, etc. + */ +export function analyzeCFGBatch( + fileContents: Array<{ path: string; content: string }>, + pageRankScores: Record, + topN = 5, +): CFGResult[] { + const analysableExtensions = new Set([ + ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", + ]); + + const eligible = fileContents.filter((f) => { + const ext = "." + f.path.split(".").pop(); + return analysableExtensions.has(ext); + }); + + const ranked = eligible + .map((f) => ({ ...f, score: pageRankScores[f.path] ?? 0 })) + .sort((a, b) => b.score - a.score) + .slice(0, topN); + + return ranked.map((f) => analyzeCFG(f.path, f.content)); +} + +/** + * Flattens CFGResult[] into a summary string for LLM consumption. + * Fits within a 300-token budget — designed for the Groq 32K context. + */ +export function cfgResultsToLLMSummary(results: CFGResult[]): string { + const lines: string[] = []; + + for (const r of results) { + if (r.parseError) continue; + if (r.findings.length === 0) continue; + + lines.push(`[${r.filePath}]`); + for (const f of r.findings) { + const prefix = f.severity === "error" ? "ERROR" : "WARN"; + lines.push( + ` ${prefix} L${f.line}: ${f.description}`, + ); + } + } + + return lines.join("\n"); +} \ No newline at end of file diff --git a/lib/dependency-graph.ts b/lib/dependency-graph.ts index 6e82e55..7a0dedc 100644 --- a/lib/dependency-graph.ts +++ b/lib/dependency-graph.ts @@ -75,7 +75,7 @@ function extractImports(content: string, currentFile: string, aliases: Record = {}; - + for (const file of allFiles) { const dir = file.split("/").slice(0, -1).join("/") || "root"; if (!directories[dir]) directories[dir] = []; directories[dir].push(file); } - // FIXED: Changed to Object.values and removed 'dir' for (const filesInDir of Object.values(directories)) { const layout = filesInDir.find(f => f.match(/\/layout\.(tsx|ts|jsx|js)$/)); const page = filesInDir.find(f => f.match(/\/page\.(tsx|ts|jsx|js)$/)); @@ -139,7 +138,7 @@ export function injectNextJsHeuristics(graph: DependencyGraph, allFiles: string[ if (page) { if (!enhancedGraph[page]) enhancedGraph[page] = []; - + if (layout && !enhancedGraph[page].includes(layout)) { enhancedGraph[page].push(layout); } @@ -160,7 +159,7 @@ export function buildDependencyGraph( allFiles: string[] ): DependencyGraph { const graph: DependencyGraph = {}; - + const tsConfigFile = fileContents.find(f => f.path === "tsconfig.json"); const aliases = tsConfigFile ? extractAliasesFromTsConfig(tsConfigFile.content) : {}; @@ -210,7 +209,7 @@ export function graphToMermaid(graph: DependencyGraph, entryPoints: string[]): s const potentialEntries = Object.keys(graph).filter(file => { const isEntry = file.includes("index.") || file.includes("main.") || file.includes("page.") || file.includes("app."); const isHighFanIn = (fanIn[file] || 0) > 2; - return isEntry || isHighFanIn; + return isEntry || isHighFanIn; }); queue.push(...potentialEntries.slice(0, 3)); } @@ -337,7 +336,7 @@ export function traverseFromCrash( distance: 0, fan_in: fanIn[crashNode] || 0, relationship: "crash_site", - relevance_score: 1000, + relevance_score: 1000, }); visited.add(crashNode); @@ -374,22 +373,22 @@ export function calculateBlastRadius( for (const file of modifiedFiles) { const affected = new Set(); const queue = [file]; - + while (queue.length > 0) { const current = queue.shift()!; const dependents = reverseDependencyGraph[current] || []; - + for (const dep of dependents) { if (!affected.has(dep)) { affected.add(dep); - queue.push(dep); + queue.push(dep); } } } const affectedArray = Array.from(affected); let risk: BlastRadiusResult["riskScore"] = "LOW"; - + if (affectedArray.length > 20) risk = "CRITICAL"; else if (affectedArray.length > 10) risk = "HIGH"; else if (affectedArray.length > 3) risk = "MEDIUM"; @@ -402,4 +401,82 @@ export function calculateBlastRadius( } return results.sort((a, b) => b.affectedDownstream.length - a.affectedDownstream.length); +} + +// ───────────────────────────────────────────────────────────────────────────── +// DEPTH-BASED FILE SELECTION +// ───────────────────────────────────────────────────────────────────────────── + +export interface DepthBatchResult { + files: string[]; + depthMap: Record; + layerSizes: number[]; +} + +export function getFilesByDepth( + graph: DependencyGraph, + entryPoints: string[], + maxDepth = 3, + maxNodes = 60, + fallbackRanked: string[] = [], +): DepthBatchResult { + const depthMap: Record = {}; + const layerSizes: number[] = []; + + let seeds = entryPoints.filter((ep) => ep in graph); + + if (seeds.length === 0) { + const fanIn = computeFanIn(graph); + seeds = Object.entries(fanIn) + .sort(([, a], [, b]) => b - a) + .slice(0, 5) + .map(([f]) => f); + } + + const visited = new Set(); + let currentLayer = seeds.filter((s) => { + if (visited.has(s)) return false; + visited.add(s); + return true; + }); + + for (const seed of currentLayer) depthMap[seed] = 0; + + for (let depth = 1; depth <= maxDepth; depth++) { + if (currentLayer.length === 0) break; + + const nextLayer: string[] = []; + + for (const node of currentLayer) { + const deps = graph[node] ?? []; + for (const dep of deps) { + if (!visited.has(dep)) { + visited.add(dep); + depthMap[dep] = depth; + nextLayer.push(dep); + } + } + } + + layerSizes.push(nextLayer.length); + currentLayer = nextLayer; + } + + const files = Array.from(visited); + + if (files.length < maxNodes) { + for (const f of fallbackRanked) { + if (files.length >= maxNodes) break; + if (!visited.has(f)) { + files.push(f); + depthMap[f] = maxDepth + 1; + } + } + } + + return { + files: files.slice(0, maxNodes), + depthMap, + layerSizes, + }; } \ No newline at end of file diff --git a/lib/file-filter.ts b/lib/file-filter.ts new file mode 100644 index 0000000..08d7191 --- /dev/null +++ b/lib/file-filter.ts @@ -0,0 +1,417 @@ +// lib/file-filter.ts +// +// Upgraded file filter with repo-type detection and strict graph-node gating. +// Three layers of filtering: +// 1. shouldSkipFile — hard rejects (unchanged contract, stricter set) +// 2. isGraphNode — can this file have JS/TS import statements? +// 3. detectRepoType — what kind of repo is this? used for early-exit UX +// 4. assessGraphQuality — is the resulting graph worth visualizing? + +export interface FileFilterOptions { + maxSizeBytes?: number; +} + +// ─── Layer 1: Hard skips (never fetch, never process) ──────────────────────── + +const SKIP_DIRECTORIES = new Set([ + "node_modules", "dist", "build", ".next", ".git", "coverage", + "__pycache__", ".yarn", "vendor", ".turbo", ".cache", "out", + "storybook-static", ".output", ".vercel", ".netlify", "tmp", "temp", + "logs", "log", ".idea", ".vscode", ".vs", +]); + +const SKIP_EXTENSIONS = new Set([ + // Compiled / minified + ".min.js", ".min.css", ".bundle.js", ".chunk.js", + ".map", ".lock", + // Type stubs (no runtime imports) + ".d.ts", + // Generated + ".generated.ts", ".generated.tsx", + // Media + ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico", + ".woff", ".woff2", ".ttf", ".eot", ".otf", + ".mp4", ".mp3", ".wav", ".webp", ".avif", + // Archives + ".pdf", ".zip", ".tar", ".gz", ".bz2", ".7z", + // Data (large, not importable) + ".csv", ".parquet", ".arrow", ".npy", ".pkl", + // Binary / compiled outputs + ".exe", ".dll", ".so", ".dylib", ".class", ".pyc", ".pyo", + ".o", ".a", ".lib", ".wasm", + // Notebooks (not importable as modules) + ".ipynb", +]); + +const SKIP_FILENAME_PATTERNS = [ + /\.mock\.[jt]sx?$/i, + /\.fixture\.[jt]sx?$/i, + /\.stories\.[jt]sx?$/i, + /\.storybook/i, + /\.generated\./i, + /repomix-output/i, + /package-lock\.json$/i, + /yarn\.lock$/i, + /pnpm-lock\.yaml$/i, + /composer\.lock$/i, + /Gemfile\.lock$/i, + /poetry\.lock$/i, + // Auto-generated proto/grpc files + /\.pb\.go$/i, + /\.pb\.ts$/i, + /_pb2\.py$/i, + // Compiled CSS-in-JS artifacts + /styled-components\.d\.ts$/i, +]; + +const SKIP_DIR_PATTERNS = [ + /__mocks__/, + /__fixtures__/, + /\/__tests__\//, + /\/\.storybook\//, + /\/storybook\//, + /\/migrations\//, // DB migration files — not importable + /\/seeds?\//, // DB seed files + /\/snapshots?\//, // Jest snapshots + /\/\.github\//, // CI configs + /\/\.husky\//, + /\/scripts\/generated\//, +]; + +const DEFAULT_MAX_SIZE_BYTES = 50_000; + +export function shouldSkipFile( + path: string, + sizeBytes?: number, + options: FileFilterOptions = {}, +): boolean { + const maxSize = options.maxSizeBytes ?? DEFAULT_MAX_SIZE_BYTES; + const segments = path.split("/"); + + // Directory segment check + for (const seg of segments.slice(0, -1)) { + if (SKIP_DIRECTORIES.has(seg)) return true; + } + + // Dir pattern check + for (const pattern of SKIP_DIR_PATTERNS) { + if (pattern.test(path)) return true; + } + + // Extension check — compound extensions like .min.js, .d.ts + const filename = segments[segments.length - 1]; + for (const ext of SKIP_EXTENSIONS) { + if (filename.endsWith(ext)) return true; + } + + // Filename pattern check + for (const pattern of SKIP_FILENAME_PATTERNS) { + if (pattern.test(path)) return true; + } + + // Size check + if (sizeBytes !== undefined && sizeBytes > maxSize) return true; + + return false; +} + +// ─── Layer 2: Graph node gate ───────────────────────────────────────────────── +// Only files that can contain JS/TS import/require statements should enter +// the dependency graph. Everything else gets fetched for LLM context only +// (if relevant) but never becomes a node. + +const JS_TS_EXTENSIONS = new Set([ + ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".mts", ".cts", +]); + +// These can reference JS/TS files via