/**
* PRIntelligence — PR risk assessment.
*
* Answers one question: what could this pull request break? The surface reads in
* that order:
*
* PR → RISK → EVIDENCE → REVIEW FOCUS → FILE / SYMBOL IMPACT
*
* Every figure comes from `POST /api/v1/pr/analyze` unchanged — risk score,
* blast radius, size bucket, counts, symbols and propagation paths are all
* backend fields. Nothing here computes a new risk metric.
*
* Typography rule: uppercase monospace is reserved for labels, statuses, paths
* and telemetry. Risk explanations and review-focus titles keep readable casing.
*/
import React, { useState, useEffect, useMemo } from 'react';
import { apiUrl, extractErrorMessage } from '../../lib/api';
import { AlertTriangle, ArrowRight, Loader2 } from 'lucide-react';
import { PRReferenceForm } from './pr/PRReferenceForm';
import { RiskGauge } from './pr/RiskGauge';
import { PrerequisitesBanner } from './pr/PrerequisitesBanner';
import { DiagnosticsPanel } from './pr/DiagnosticsPanel';
import { usePrerequisites } from './pr/usePrerequisites';
import { riskTextClass, sizeTextClass, blastTextClass } from './pr/risk';
import {
CommandWorkspace, WaitingState, PRIdentity, SectionHead, InstrumentAction,
} from './pr/instrument';
import { SkeletonCard, SkeletonGroup } from '../ui/Skeleton';
import { FilePath } from '../ui/FilePath';
import { SectionSeam } from '../ui/SectionSeam';
interface ChangedFile {
filename: string;
status: string;
additions: number;
deletions: number;
changes: number;
}
interface SymbolChange {
name: string;
type: string;
file_path: string;
line_number: number;
language: string;
change_type: string;
parent_class?: string;
}
interface PropagationPath {
source: string;
target: string;
path: string[];
depth: number;
}
interface RiskBreakdown {
factor: string;
score: number;
detail: string;
}
interface ReviewFocusArea {
area: string;
reason: string;
files: string[];
priority: 'HIGH' | 'MEDIUM' | 'LOW';
}
interface PRAnalysisResult {
repo: string;
pr_number: number;
pr_url: string;
pr_title: string;
pr_state: string;
pr_size: 'XS' | 'S' | 'M' | 'L' | 'XL';
risk_score: number;
risk_level: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
risk_breakdown: RiskBreakdown[];
top_risks: string[];
changed_files: ChangedFile[];
total_additions: number;
total_deletions: number;
added_symbols: SymbolChange[];
modified_symbols: SymbolChange[];
removed_symbols: SymbolChange[];
affected_files: string[];
impact_radius: number;
blast_radius: 'LOW' | 'MEDIUM' | 'HIGH' | 'EXTREME';
max_depth: number;
propagation_paths: PropagationPath[];
affected_components: string[];
changed_entry_points: string[];
changed_core_files: string[];
changed_high_coupling_files: string[];
review_focus_areas: ReviewFocusArea[];
analyzed_at: string;
}
interface PRIntelligenceProps {
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 '';
}
/** Open PRs read as active work; anything else is quiet metadata. */
function prStateTone(state: string): string {
const s = (state || '').toLowerCase();
if (s === 'open') return 'text-success';
return 'text-text-muted';
}
function fileStatusTone(status: string): string {
const s = (status || '').toLowerCase();
if (s === 'added') return 'text-success';
if (s === 'removed' || s === 'deleted') return 'text-danger';
return 'text-primary';
}
function priorityTone(priority: string): string {
const p = (priority || '').toUpperCase();
if (p === 'HIGH') return 'text-danger';
if (p === 'MEDIUM') return 'text-warn';
return 'text-text-muted';
}
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;
}
}
/** One of the three architecture detection categories. */
const DetectionRow: React.FC<{
label: string;
files: string[];
tone: string;
quiet: string;
}> = ({ label, files, tone, quiet }) => {
const active = files.length > 0;
return (
{label}
{files.length}
{active ? (
) : (
{quiet}
)}
);
};
/** A bounded symbol registry column. */
const SymbolColumn: React.FC<{
title: string;
tone: string;
symbols: SymbolChange[];
empty: string;
}> = ({ title, tone, symbols, empty }) => (
{title}
{symbols.length}
{symbols.length > 0 ? (
{symbols.map((sym, idx) => (
{sym.name}
{sym.type}
{sym.file_path.split('/').pop()}:{sym.line_number}
))}
) : (
{empty}
)}
);
export const PRIntelligence: React.FC = ({ repoName }) => {
const [activeRepo, setActiveRepo] = useState(() => resolveRepo(repoName));
const { healthStatus, hasPrerequisites, isRepairing, repair } = usePrerequisites(activeRepo);
const [useUrl, setUseUrl] = useState(true);
const [prUrlInput, setPrUrlInput] = useState('');
const [ownerInput, setOwnerInput] = useState('');
const [repoInput, setRepoInput] = useState('');
const [prNumberInput, setPrNumberInput] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [analysisResult, setAnalysisResult] = useState(null);
const [errorMsg, setErrorMsg] = useState('');
// Sync activeRepo with repoName prop changes and clear stale results
useEffect(() => {
const nextRepo = resolveRepo(repoName);
setActiveRepo(nextRepo);
setAnalysisResult(null);
setErrorMsg('');
setPrUrlInput('');
setOwnerInput('');
setRepoInput('');
setPrNumberInput('');
}, [repoName]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsLoading(true);
setErrorMsg('');
setAnalysisResult(null);
const payload: any = {};
if (useUrl) {
if (!prUrlInput.trim()) { setErrorMsg('Please enter a GitHub Pull Request URL.'); setIsLoading(false); return; }
payload.pr_url = prUrlInput.trim();
} else {
if (!ownerInput.trim() || !repoInput.trim() || !prNumberInput.trim()) {
setErrorMsg('Please fill in Owner, Repo, and PR Number.'); setIsLoading(false); return;
}
payload.owner = ownerInput.trim();
payload.repo = repoInput.trim();
payload.pr_number = parseInt(prNumberInput.trim(), 10);
}
try {
const res = await fetch(apiUrl('/api/v1/pr/analyze'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
if (!res.ok) {
const errorData = await res.json().catch(() => ({}));
throw new Error(extractErrorMessage(errorData));
}
const data = await res.json();
setAnalysisResult(data);
if (data.repo) setActiveRepo(data.repo);
} catch (err: any) {
setErrorMsg(extractErrorMessage(err));
} finally {
setIsLoading(false);
}
};
/** The four readings in the metric strip, straight from the payload. */
const metricStrip = useMemo(() => {
if (!analysisResult) return [];
const r = analysisResult;
return [
{
k: 'PR SIZE',
v: (
{r.pr_size}
),
},
{
k: 'BLAST RADIUS',
v: (
{r.blast_radius}
{' '}· {r.impact_radius} downstream
),
},
{
k: 'FILES',
v: (
{r.changed_files.length}
),
},
{
k: 'DIFF',
v: (
+{r.total_additions}
/
-{r.total_deletions}
),
},
];
}, [analysisResult]);
return (
{/* ── 01 · Header ───────────────────────────────────────────────────── */}
PR INTELLIGENCE / RISK ASSESSMENT
Understand what this pull request puts at risk.
Trace changed files, architectural hotspots, dependency propagation, and review focus
before merging.
{activeRepo && (
REPOSITORY · {activeRepo}
)}
{/* ── 02 · Command workspace ────────────────────────────────────────── */}
PULL REQUEST
{errorMsg && (
PR ANALYSIS FAILED
{errorMsg}
)}
}
diagnostics={
}
/>
{/* ── Loading ───────────────────────────────────────────────────────── */}
{isLoading && (
)}
{/* ── Compact waiting state ─────────────────────────────────────────── */}
{!analysisResult && !isLoading && !errorMsg && (
Paste a GitHub PR URL or provide repository coordinates to begin risk analysis.
)}
{/* ── Results ───────────────────────────────────────────────────────── */}
{analysisResult && (
{analysisResult.pr_title}
}
metadata={
<>
{analysisResult.repo} · ANALYZED{' '}
{relativeTime(analysisResult.analyzed_at).toUpperCase()}
>
}
action={
VIEW ON GITHUB
}
/>
{/* ── 03 · Primary risk readout ─────────────────────────────────── */}
{analysisResult.top_risks.length > 0 ? (
{analysisResult.top_risks.map((risk, idx) => (
{risk}
))}
) : (
No critical risk signals were raised for this change payload.
)}
{/* ── 04 · Metric strip ─────────────────────────────────────────── */}
{metricStrip.map((cell, idx) => (
0 ? 'border-t border-white/[0.055] sm:border-t-0' : ''}
${idx % 2 === 1 ? 'sm:border-l sm:border-white/[0.055]' : ''}
${idx === 2 ? 'sm:border-t sm:border-white/[0.055] lg:border-t-0 lg:border-l' : ''}
${idx === 3 ? 'lg:border-l lg:border-white/[0.055]' : ''}`}
>
{cell.k}
{cell.v}
))}
{/* ── 05 · Architecture detections ──────────────────────────────── */}
{/* ── 06 · Prioritized review focus ─────────────────────────────── */}
{analysisResult.review_focus_areas.length} areas
}
/>
{analysisResult.review_focus_areas.length > 0 ? (
{analysisResult.review_focus_areas.map((area, idx) => (
{area.area}
{area.priority}
{area.reason}
{area.files.length > 0 && (
TARGET FILES
{area.files.map((file, fIdx) => (
))}
)}
))}
) : (
No review focus areas triggered — the standard review process is sufficient for
this PR.
)}
{/* ── 07 · Changed files ────────────────────────────────────────── */}
{/* Column captions from `lg`; below that each row labels its own readings. */}
FILE PATH
STATUS
+
−
Δ
{/* ── 08 · Symbol groups ────────────────────────────────────────── */}
{/* ── 09 · Dependency propagation ───────────────────────────────── */}
{analysisResult.propagation_paths.length} paths
}
/>
{analysisResult.propagation_paths.length > 0 ? (
) : (
No multi-level import cascades found.
)}
{/*
A neutral run summary, not a completion badge: the dashboard shell
owns the single authoritative ANALYSIS COMPLETE indicator, so a green
"READY" here would be a second one competing with it.
*/}
RISK ANALYSIS ·{' '}
{analysisResult.review_focus_areas.length}{' '}
{analysisResult.review_focus_areas.length === 1 ? 'FINDING' : 'FINDINGS'} ·{' '}
{analysisResult.changed_files.length} CHANGED{' '}
{analysisResult.changed_files.length === 1 ? 'FILE' : 'FILES'} · ANALYZED{' '}
{relativeTime(analysisResult.analyzed_at).toUpperCase()}
)}
);
};
export default PRIntelligence;