Spaces:
Paused
Paused
Deploy Sensorflow Studio (part 3)
Browse filesFiles changed (44)
- src/components/megaeval/VisualQueryTab.tsxAdded+401
- src/components/safety/shared.tsxAdded+208
- src/components/visual/BrushChart.tsxAdded+243
- src/components/visual/DragList.tsxAdded+108
- src/components/visual/Feedback.tsxAdded+132
- src/components/visual/InspectorPanel.tsxAdded+161
- src/components/visual/NodeCanvas.tsxAdded+253
- src/components/visual/canvas.tsxAdded+212
- src/components/visual/charts.tsxAdded+368
- src/content/glossary.ts+245-51
- src/content/pageHelp.ts+180-12
- src/context/LabelEvalContext.tsx+30-2
- src/index.tsx+6-11
- src/pages/CommandCenterPage.tsx+4
- src/pages/agentic/LaunchReadinessPage.tsxAdded+349
- src/pages/engines/BevFusionPage.tsxAdded+413
- src/pages/engines/SeqevalPage.tsxAdded+553
- src/pages/safety/CalibrationPage.tsxAdded+281
- src/pages/safety/DiscrepancyPage.tsxAdded+215
- src/pages/safety/EvidencePage.tsxAdded+111
- src/pages/safety/OddCoveragePage.tsxAdded+385
- src/pages/safety/ReleaseGatesPage.tsxAdded+426
- src/pages/safety/ScenarioDbPage.tsxAdded+222
- src/pages/safety/SemanticSearchPage.tsxAdded+210
- src/pages/safety/SsamConflictPage.tsxAdded+271
- src/pages/studio/MyDashboardPage.tsxAdded+536
- src/pages/studio/PipelineBuilderPage.tsxAdded+367
- src/pages/studio/ScenarioComposerPage.tsxAdded+661
- src/services/agentic.tsAdded+120
- src/services/bevfusion.tsAdded+178
- src/services/safety.tsAdded+411
- src/services/seqeval.tsAdded+194
- src/services/studioux.tsAdded+116
- src/theme.tsAdded+115
- src/types/agentic.tsAdded+326
- tests/test_agentic/__init__.pyAdded
- tests/test_agentic/conftest.pyAdded+38
- tests/test_agentic/test_agents.pyAdded+189
- tests/test_agentic/test_api.pyAdded+157
- tests/test_agentic/test_evidence_snippets.pyAdded+68
- tests/test_agentic/test_flywheel.pyAdded+121
- tests/test_agentic/test_pipeline_worked_example.pyAdded+154
- tests/test_agentic/test_policy.pyAdded+223
- tests/test_retro/test_tools.py+60
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401/** * Visual Query Builder — an alternate, direct-manipulation front end for the * metric-cube query API (/api/evaluations/query). * * Drag dimension chips from the tray into the "Group by" and "Filter" wells, * pick filter values with visual chips, toggle metrics, and watch the live * result preview (table + bars) update as you build. The generated request * JSON is always visible, so the visual query stays auditable against the * manual API. */import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import Box from '@mui/material/Box';import Chip from '@mui/material/Chip';import Typography from '@mui/material/Typography';import { GripVertical, X } from 'lucide-react';import { DIM_NAMES, type DimName, type EvaluationQueryResponse, type MetricName } from '../../types/megaeval';import { getDimensions, queryEvaluations } from '../../services/megaeval';import { SectionCard, HBar, fmtPct, fmtInt } from '../../components/labeleval/shared';import { InfoDot } from '../help/InfoTip';import { PanelSkeleton, IllustratedEmpty } from '../visual/Feedback';import DragList from '../visual/DragList';import { tokens } from '../../theme';
const DIM_COLORS: Record<DimName, string> = { class: '#66bb6a', weather: '#4fc3f7', lighting: '#f9a825', road_type: '#ab47bc', scenario: '#ff7043', sensor: '#26c6da', distance_band: '#9ccc65', speed_band: '#ec407a', occlusion: '#8a949e',};
const METRIC_CHOICES: Array<{ name: MetricName; label: string; help: string; pct: boolean }> = [ { name: 'recall', label: 'recall', help: 'TP / (TP+FN) — fraction of real objects labeled.', pct: true }, { name: 'precision', label: 'precision', help: 'TP / (TP+FP) — fraction of produced labels that are correct.', pct: true }, { name: 'f1', label: 'f1', help: 'Harmonic mean of precision and recall.', pct: true }, { name: 'mean_iou', label: 'mean IoU', help: 'Mean 3D overlap of matched boxes.', pct: true }, { name: 'safety_recall', label: 'safety recall', help: 'Recall restricted to safety-critical objects.', pct: true }, { name: 'error_rate', label: 'error rate', help: '(FP+FN) / n.', pct: true }, { name: 'anomaly_rate', label: 'anomaly rate', help: 'Fraction of objects flagged by the anomaly ensemble.', pct: true }, { name: 'conf_mean', label: 'conf mean', help: 'Mean detection confidence.', pct: false },];
type Well = 'group' | 'filter';
interface FilterClause { dim: DimName; values: string[];}
interface VisualQueryTabProps { runId: string;}
export default function VisualQueryTab({ runId }: VisualQueryTabProps) { const [dimValues, setDimValues] = useState<Record<string, string[]> | null>(null); const [groupBy, setGroupBy] = useState<DimName[]>(['class']); const [filters, setFilters] = useState<FilterClause[]>([]); const [metrics, setMetrics] = useState<MetricName[]>(['recall', 'precision']); const [result, setResult] = useState<EvaluationQueryResponse | null>(null); const [loading, setLoading] = useState(false); const [error, setError] = useState<string | null>(null); const [dragOverWell, setDragOverWell] = useState<Well | null>(null); const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => { getDimensions() .then((d) => setDimValues(d.dimensions as Record<string, string[]>)) .catch((e) => setError(e instanceof Error ? e.message : String(e))); }, []);
const request = useMemo( () => ({ evaluation_id: runId, group_by: groupBy, filters: Object.fromEntries(filters.filter((f) => f.values.length).map((f) => [f.dim, f.values])), metrics, limit: 40, }), [runId, groupBy, filters, metrics] );
// live preview: debounce 350 ms after any change useEffect(() => { if (debounceRef.current) clearTimeout(debounceRef.current); setLoading(true); debounceRef.current = setTimeout(() => { queryEvaluations(request) .then((r) => { setResult(r); setError(null); }) .catch((e) => setError(e instanceof Error ? e.message : String(e))) .finally(() => setLoading(false)); }, 350); return () => { if (debounceRef.current) clearTimeout(debounceRef.current); }; }, [request]);
const dropDim = useCallback( (well: Well, dim: DimName) => { if (well === 'group') { setGroupBy((g) => (g.includes(dim) ? g : [...g, dim])); } else { setFilters((fs) => (fs.some((f) => f.dim === dim) ? fs : [...fs, { dim, values: [] }])); } setDragOverWell(null); }, [] );
const wellProps = (well: Well) => ({ onDragOver: (e: React.DragEvent) => { e.preventDefault(); setDragOverWell(well); }, onDragLeave: () => setDragOverWell(null), onDrop: (e: React.DragEvent) => { e.preventDefault(); const dim = e.dataTransfer.getData('application/x-dim') as DimName; if (dim && DIM_NAMES.includes(dim)) dropDim(well, dim); }, });
const firstMetric = metrics[0]; const firstMetricMeta = METRIC_CHOICES.find((m) => m.name === firstMetric); const rows = result?.rows ?? []; const barMax = useMemo(() => { if (!firstMetric) return 1; const vals = rows.map((r) => (typeof r[firstMetric] === 'number' ? (r[firstMetric] as number) : 0)); return firstMetricMeta?.pct ? 1 : Math.max(1e-9, ...vals); }, [rows, firstMetric, firstMetricMeta]);
const rowLabel = (r: Record<string, unknown>): string => groupBy.map((d) => String(r[d] ?? '—')).join(' · ') || 'all';
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> <SectionCard title={ <Box component="span" sx={{ display: 'inline-flex', alignItems: 'center' }}> Build the query visually <InfoDot title="Visual query builder" detail="Drag a dimension chip into the Group-by well to break results down by it, or into the Filter well to restrict the population (then pick the allowed values). Toggle metrics below. The preview runs the real /api/evaluations/query request — shown as JSON on the right — after every change." /> </Box> } > {/* dimension tray */} <Box sx={{ display: 'flex', gap: 0.75, flexWrap: 'wrap', mb: 1.5, alignItems: 'center' }}> <Typography variant="caption" sx={{ color: tokens.color.neutral }}> Dimensions — drag into a well: </Typography> {DIM_NAMES.map((d) => ( <Chip key={d} size="small" icon={<GripVertical size={12} />} label={d.replace(/_/g, ' ')} draggable onDragStart={(e) => { e.dataTransfer.setData('application/x-dim', d); e.dataTransfer.effectAllowed = 'copy'; }} onClick={() => dropDim('group', d)} sx={{ cursor: 'grab', bgcolor: `${DIM_COLORS[d]}1a`, color: DIM_COLORS[d], border: `1px solid ${DIM_COLORS[d]}55`, fontWeight: 700, '&:active': { cursor: 'grabbing' }, }} /> ))} </Box>
<Box sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap' }}> {/* group-by well */} <Box {...wellProps('group')} sx={{ flex: '1 1 260px', minHeight: 74, border: `2px dashed ${dragOverWell === 'group' ? tokens.color.info : tokens.color.borderStrong}`, borderRadius: 1.5, p: 1.25, bgcolor: dragOverWell === 'group' ? tokens.color.infoBg : tokens.color.surfaceSunken, transition: `border-color ${tokens.motion.fast}, background-color ${tokens.motion.fast}`, }} > <Typography variant="caption" sx={{ color: tokens.color.neutral, fontWeight: 700, letterSpacing: 0.5, display: 'block', mb: 0.75 }}> GROUP BY {groupBy.length ? `(${groupBy.length} — drag the handle to reorder)` : '— drop a dimension here'} </Typography> <DragList dense items={groupBy.map((d) => ({ id: d, content: ( <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}> <Chip size="small" label={d.replace(/_/g, ' ')} sx={{ bgcolor: `${DIM_COLORS[d]}26`, color: DIM_COLORS[d], fontWeight: 700, height: 22 }} /> <Box component="span" onClick={() => setGroupBy((g) => g.filter((x) => x !== d))} sx={{ display: 'inline-flex', cursor: 'pointer', color: tokens.color.textFaint, '&:hover': { color: tokens.color.danger } }} title="Remove from group-by" > <X size={13} /> </Box> </Box> ), }))} onReorder={(ids) => setGroupBy(ids as DimName[])} /> </Box>
{/* filter well */} <Box {...wellProps('filter')} sx={{ flex: '2 1 380px', minHeight: 74, border: `2px dashed ${dragOverWell === 'filter' ? tokens.color.warn : tokens.color.borderStrong}`, borderRadius: 1.5, p: 1.25, bgcolor: dragOverWell === 'filter' ? tokens.color.warnBg : tokens.color.surfaceSunken, transition: `border-color ${tokens.motion.fast}, background-color ${tokens.motion.fast}`, }} > <Typography variant="caption" sx={{ color: tokens.color.neutral, fontWeight: 700, letterSpacing: 0.5, display: 'block', mb: 0.75 }}> FILTERS {filters.length ? `(${filters.length})` : '— drop a dimension here, then pick values'} </Typography> <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.75 }}> {filters.map((f) => ( <Box key={f.dim} sx={{ display: 'flex', gap: 0.75, alignItems: 'center', flexWrap: 'wrap' }}> <Chip size="small" label={f.dim.replace(/_/g, ' ')} sx={{ bgcolor: `${DIM_COLORS[f.dim]}26`, color: DIM_COLORS[f.dim], fontWeight: 700 }} /> <Typography variant="caption" sx={{ color: tokens.color.textFaint, fontStyle: 'italic' }}> is any of </Typography> {(dimValues?.[f.dim] ?? []).map((v) => { const on = f.values.includes(v); return ( <Chip key={v} size="small" label={v} onClick={() => setFilters((fs) => fs.map((x) => (x.dim === f.dim ? { ...x, values: on ? x.values.filter((y) => y !== v) : [...x.values, v] } : x)) ) } sx={{ height: 21, fontSize: 10.5, cursor: 'pointer', bgcolor: on ? tokens.color.infoBg : 'transparent', color: on ? tokens.color.info : tokens.color.textFaint, border: `1px solid ${on ? tokens.color.info : tokens.color.border}`, transition: `all ${tokens.motion.fast}`, }} /> ); })} <Box component="span" onClick={() => setFilters((fs) => fs.filter((x) => x.dim !== f.dim))} sx={{ display: 'inline-flex', alignItems: 'center', cursor: 'pointer', color: tokens.color.textFaint, '&:hover': { color: tokens.color.danger } }} title="Remove this filter" > <X size={13} /> </Box> </Box> ))} </Box> </Box> </Box>
{/* metric toggles */} <Box sx={{ display: 'flex', gap: 0.75, flexWrap: 'wrap', mt: 1.5, alignItems: 'center' }}> <Typography variant="caption" sx={{ color: tokens.color.neutral }}> Metrics: </Typography> {METRIC_CHOICES.map((m) => { const on = metrics.includes(m.name); return ( <Chip key={m.name} size="small" label={m.label} title={m.help} onClick={() => setMetrics((ms) => (on ? ms.filter((x) => x !== m.name) : [...ms, m.name]))} sx={{ cursor: 'pointer', bgcolor: on ? tokens.color.successBg : 'transparent', color: on ? tokens.color.success : tokens.color.textFaint, border: `1px solid ${on ? tokens.color.success : tokens.color.border}`, fontWeight: on ? 700 : 400, transition: `all ${tokens.motion.fast}`, }} /> ); })} </Box> </SectionCard>
<Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap', alignItems: 'flex-start' }}> <SectionCard title="Live result preview" sx={{ flex: '3 1 460px' }} action={ result ? ( <Box sx={{ display: 'flex', gap: 0.5 }}> <Chip size="small" label={result.meta.source} sx={{ height: 20, fontSize: 10, bgcolor: tokens.color.surfaceRaised, fontFamily: 'monospace' }} title="Query provenance: answered from cache, the metric cube, or a raw scan" /> <Chip size="small" label={`${result.meta.latency_ms.toFixed(0)} ms`} sx={{ height: 20, fontSize: 10, bgcolor: tokens.color.surfaceRaised, fontFamily: 'monospace' }} /> <Chip size="small" label={result.meta.exact ? 'exact' : 'approx'} sx={{ height: 20, fontSize: 10, fontFamily: 'monospace', bgcolor: result.meta.exact ? tokens.color.successBg : tokens.color.warnBg, color: result.meta.exact ? tokens.color.success : tokens.color.warn }} /> </Box> ) : undefined } > {error ? ( <Typography variant="caption" sx={{ color: tokens.color.warn }}> {error} </Typography> ) : null} {loading && !result ? <PanelSkeleton rows={5} header={false} /> : null} {result && rows.length === 0 ? ( <IllustratedEmpty art="search" title="No matching population" message="The current filters exclude every object — loosen a filter value to see results." /> ) : null} {rows.length > 0 ? ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, opacity: loading ? 0.6 : 1, transition: `opacity ${tokens.motion.fast}` }}> {firstMetric ? ( <Box> <Typography variant="caption" sx={{ color: tokens.color.neutral, display: 'block', mb: 0.5 }}> {firstMetricMeta?.label ?? firstMetric} by {groupBy.map((d) => d.replace(/_/g, ' ')).join(' × ') || 'population'} </Typography> {rows.slice(0, 14).map((r, i) => { const v = typeof r[firstMetric] === 'number' ? (r[firstMetric] as number) : 0; return ( <HBar key={i} label={rowLabel(r)} value={v} max={barMax} color={tokens.color.info} valueLabel={firstMetricMeta?.pct ? fmtPct(v) : v.toFixed(3)} /> ); })} </Box> ) : null} <Box sx={{ overflowX: 'auto' }}> <Box component="table" sx={{ borderCollapse: 'collapse', width: '100%', '& td, & th': { border: `1px solid ${tokens.color.border}`, px: 1, py: 0.4, fontSize: 12, textAlign: 'right' }, '& th': { bgcolor: tokens.color.surfaceRaised, color: tokens.color.textDim }, '& td:first-of-type, & th:first-of-type': { textAlign: 'left' } }}> <thead> <tr> <th>group</th> <th>n</th> {metrics.map((m) => ( <th key={m}>{m.replace(/_/g, ' ')}</th> ))} </tr> </thead> <tbody> {rows.slice(0, 20).map((r, i) => ( <tr key={i}> <td style={{ fontFamily: 'monospace' }}>{rowLabel(r)}</td> <td style={{ fontFamily: 'monospace' }}>{fmtInt(r.n)}</td> {metrics.map((m) => { const v = r[m]; const meta = METRIC_CHOICES.find((x) => x.name === m); return ( <td key={m} style={{ fontFamily: 'monospace' }}> {typeof v === 'number' ? (meta?.pct ? fmtPct(v) : v.toFixed(3)) : '—'} </td> ); })} </tr> ))} </tbody> </Box> </Box> </Box> ) : null} </SectionCard>
<SectionCard title="Equivalent API request" sx={{ flex: '1 1 280px' }} help="The exact JSON body sent to POST /api/evaluations/query for the preview — build the same query manually and you will get the same rows." > <Box component="pre" sx={{ m: 0, p: 1, bgcolor: tokens.color.surfaceSunken, border: `1px solid ${tokens.color.border}`, borderRadius: 1, fontSize: 11, fontFamily: 'monospace', overflow: 'auto', maxHeight: 340, color: tokens.color.textDim }}> {JSON.stringify(request, null, 2)} </Box> </SectionCard> </Box> </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208/** * Shared building blocks for the Safety & Compliance pages: published-run * selection (safety analyses require published megaeval runs) and a compact * markdown renderer for evidence packages. */import { useEffect, useMemo, useState, type ReactNode } from 'react';import Box from '@mui/material/Box';import MenuItem from '@mui/material/MenuItem';import TextField from '@mui/material/TextField';import Typography from '@mui/material/Typography';import type { EvaluationRunInfo } from '../../types/megaeval';import { getRuns } from '../../services/megaeval';import { tokens } from '../../theme';
// ---------------------------------------------------------------- runs hook
export function usePublishedRuns() { const [runs, setRuns] = useState<EvaluationRunInfo[] | null>(null); const [error, setError] = useState<string | null>(null); useEffect(() => { let cancelled = false; getRuns() .then((r) => { if (cancelled) return; const published = r.runs .filter((x) => x.status === 'published') .sort((a, b) => (b.created_at ?? '').localeCompare(a.created_at ?? '')); setRuns(published); }) .catch((e) => { if (!cancelled) setError(e instanceof Error ? e.message : String(e)); }); return () => { cancelled = true; }; }, []); return { runs, error };}
export function RunSelect({ label, value, onChange, runs, exclude,}: { label: string; value: string | null; onChange: (id: string) => void; runs: EvaluationRunInfo[] | null; exclude?: string | null;}) { const options = useMemo(() => (runs ?? []).filter((r) => r.run_id !== exclude), [runs, exclude]); return ( <TextField select size="small" label={label} value={value ?? ''} onChange={(e) => onChange(e.target.value)} sx={{ minWidth: 260 }} > {options.map((r) => ( <MenuItem key={r.run_id} value={r.run_id}> <Box component="span" sx={{ fontFamily: 'monospace', fontSize: 12.5 }}> {r.run_id.slice(0, 14)} </Box> <Box component="span" sx={{ color: tokens.color.neutral, ml: 1, fontSize: 12 }}> {r.model_version} </Box> </MenuItem> ))} </TextField> );}
// ---------------------------------------------------------------- markdown-lite
/** Minimal markdown renderer (headings, bold, code, lists, tables, hr) — * enough for the generated Safety Evidence Package; no external deps. */export function MarkdownLite({ text }: { text: string }) { const blocks = useMemo(() => parseBlocks(text), [text]); return <Box sx={{ '& > *:first-of-type': { mt: 0 } }}>{blocks}</Box>;}
function inline(text: string): ReactNode[] { // **bold** and `code` const parts: ReactNode[] = []; const re = /(\*\*[^*]+\*\*|`[^`]+`)/g; let last = 0; let m: RegExpExecArray | null; let key = 0; while ((m = re.exec(text)) !== null) { if (m.index > last) parts.push(text.slice(last, m.index)); const tok = m[0]; if (tok.startsWith('**')) { parts.push(<strong key={key++}>{tok.slice(2, -2)}</strong>); } else { parts.push( <Box key={key++} component="code" sx={{ fontFamily: 'monospace', fontSize: '0.9em', bgcolor: tokens.color.surfaceRaised, px: 0.5, borderRadius: '3px' }}> {tok.slice(1, -1)} </Box> ); } last = m.index + tok.length; } if (last < text.length) parts.push(text.slice(last)); return parts;}
function parseBlocks(text: string): ReactNode[] { const lines = text.split('\n'); const out: ReactNode[] = []; let i = 0; let key = 0; while (i < lines.length) { const line = lines[i]; if (/^\s*$/.test(line)) { i += 1; continue; } const h = line.match(/^(#{1,4})\s+(.*)$/); if (h) { const level = h[1].length; out.push( <Typography key={key++} variant={level === 1 ? 'h5' : level === 2 ? 'h6' : 'subtitle1'} sx={{ fontWeight: 800, mt: level === 1 ? 2 : 2.5, mb: 0.75, color: level >= 3 ? tokens.color.info : undefined }} > {inline(h[2])} </Typography> ); i += 1; continue; } if (/^\s*(---|\*\*\*)\s*$/.test(line)) { out.push(<Box key={key++} sx={{ borderBottom: `1px solid ${tokens.color.border}`, my: 1.5 }} />); i += 1; continue; } if (/^\s*[-*]\s+/.test(line)) { const items: string[] = []; while (i < lines.length && /^\s*[-*]\s+/.test(lines[i])) { items.push(lines[i].replace(/^\s*[-*]\s+/, '')); i += 1; } out.push( <Box key={key++} component="ul" sx={{ my: 0.75, pl: 3 }}> {items.map((it, j) => ( <Typography key={j} component="li" variant="body2" sx={{ color: tokens.color.textDim, mb: 0.25 }}> {inline(it)} </Typography> ))} </Box> ); continue; } if (/^\s*\|.*\|\s*$/.test(line)) { const rows: string[][] = []; while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) { const cells = lines[i].trim().slice(1, -1).split('|').map((c) => c.trim()); if (!cells.every((c) => /^:?-+:?$/.test(c))) rows.push(cells); i += 1; } if (rows.length) { const [head, ...body] = rows; out.push( <Box key={key++} component="table" sx={{ borderCollapse: 'collapse', my: 1, '& td, & th': { border: `1px solid ${tokens.color.border}`, px: 1, py: 0.4, fontSize: 12.5 }, '& th': { bgcolor: tokens.color.surfaceRaised, textAlign: 'left' } }}> <thead> <tr>{head.map((c, j) => <th key={j}>{inline(c)}</th>)}</tr> </thead> <tbody> {body.map((r, ri) => ( <tr key={ri}>{r.map((c, j) => <td key={j}>{inline(c)}</td>)}</tr> ))} </tbody> </Box> ); } continue; } // paragraph: gather consecutive plain lines const para: string[] = [line]; i += 1; while (i < lines.length && !/^\s*$/.test(lines[i]) && !/^(#{1,4})\s|^\s*[-*]\s|^\s*\|/.test(lines[i])) { para.push(lines[i]); i += 1; } out.push( <Typography key={key++} variant="body2" sx={{ color: tokens.color.textDim, my: 0.75, lineHeight: 1.6 }}> {inline(para.join(' '))} </Typography> ); } return out;}
/** Trigger a client-side JSON download. */export function downloadJson(name: string, data: unknown) { const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = name; a.click(); URL.revokeObjectURL(url);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243/** * Brush-selectable scatter chart (direct-manipulation primitive). * * Drag a rectangle over the plot to select points — the selection is * reported via `onBrush` and highlighted in place. Click empty space to * clear. Used by the calibration residual scatter and the visual query * builder preview. */import { useMemo, useRef, useState } from 'react';import Box from '@mui/material/Box';import Typography from '@mui/material/Typography';import { tokens } from '../../theme';
export interface BrushPoint { id: string; x: number; y: number; color?: string; label?: string; r?: number;}
interface BrushChartProps { points: BrushPoint[]; width?: number | string; height?: number; xLabel: string; yLabel: string; onBrush?: (selectedIds: string[] | null) => void; /** Horizontal reference lines in y units, e.g. thresholds. */ refLinesY?: Array<{ y: number; label: string; color?: string }>; /** Vertical reference lines in x units. */ refLinesX?: Array<{ x: number; label: string; color?: string }>; xDomain?: [number, number]; yDomain?: [number, number];}
const PAD = { l: 46, r: 12, t: 10, b: 32 };const VIEW_W = 640;
function niceDomain(vals: number[], fixed?: [number, number]): [number, number] { if (fixed) return fixed; if (!vals.length) return [0, 1]; let lo = Math.min(...vals); let hi = Math.max(...vals); if (lo === hi) { lo -= 1; hi += 1; } const pad = (hi - lo) * 0.08; return [lo - pad, hi + pad];}
export default function BrushChart({ points, width = '100%', height = 260, xLabel, yLabel, onBrush, refLinesY = [], refLinesX = [], xDomain, yDomain,}: BrushChartProps) { const svgRef = useRef<SVGSVGElement | null>(null); const [brush, setBrush] = useState<{ x0: number; y0: number; x1: number; y1: number } | null>(null); const [selected, setSelected] = useState<Set<string> | null>(null); const [hover, setHover] = useState<BrushPoint | null>(null);
const viewH = height; const [xLo, xHi] = useMemo( () => niceDomain([...points.map((p) => p.x), ...refLinesX.map((r) => r.x)], xDomain), [points, refLinesX, xDomain] ); const [yLo, yHi] = useMemo( () => niceDomain([...points.map((p) => p.y), ...refLinesY.map((r) => r.y)], yDomain), [points, refLinesY, yDomain] );
const sx = (x: number) => PAD.l + ((x - xLo) / (xHi - xLo)) * (VIEW_W - PAD.l - PAD.r); const sy = (y: number) => viewH - PAD.b - ((y - yLo) / (yHi - yLo)) * (viewH - PAD.t - PAD.b);
const toLocal = (e: React.PointerEvent) => { const svg = svgRef.current; if (!svg) return { x: 0, y: 0 }; const rect = svg.getBoundingClientRect(); return { x: ((e.clientX - rect.left) / rect.width) * VIEW_W, y: ((e.clientY - rect.top) / rect.height) * viewH, }; };
const finishBrush = (b: { x0: number; y0: number; x1: number; y1: number }) => { const [bx0, bx1] = [Math.min(b.x0, b.x1), Math.max(b.x0, b.x1)]; const [by0, by1] = [Math.min(b.y0, b.y1), Math.max(b.y0, b.y1)]; if (bx1 - bx0 < 4 && by1 - by0 < 4) { setSelected(null); onBrush?.(null); return; } const ids = points.filter((p) => { const px = sx(p.x); const py = sy(p.y); return px >= bx0 && px <= bx1 && py >= by0 && py <= by1; }).map((p) => p.id); setSelected(new Set(ids)); onBrush?.(ids); };
const xTicks = useMemo(() => { const n = 5; return Array.from({ length: n + 1 }, (_, i) => xLo + ((xHi - xLo) * i) / n); }, [xLo, xHi]); const yTicks = useMemo(() => { const n = 4; return Array.from({ length: n + 1 }, (_, i) => yLo + ((yHi - yLo) * i) / n); }, [yLo, yHi]);
return ( <Box sx={{ width, position: 'relative' }}> <svg ref={svgRef} width="100%" viewBox={`0 0 ${VIEW_W} ${viewH}`} style={{ display: 'block', cursor: 'crosshair', touchAction: 'none' }} onPointerDown={(e) => { const p = toLocal(e); (e.target as Element).setPointerCapture(e.pointerId); setBrush({ x0: p.x, y0: p.y, x1: p.x, y1: p.y }); }} onPointerMove={(e) => { if (!brush || !(e.target as Element).hasPointerCapture?.(e.pointerId)) return; const p = toLocal(e); setBrush({ ...brush, x1: p.x, y1: p.y }); }} onPointerUp={(e) => { (e.target as Element).releasePointerCapture(e.pointerId); if (brush) finishBrush(brush); setBrush(null); }} > {/* axes */} <line x1={PAD.l} y1={viewH - PAD.b} x2={VIEW_W - PAD.r} y2={viewH - PAD.b} stroke={tokens.color.borderStrong} /> <line x1={PAD.l} y1={PAD.t} x2={PAD.l} y2={viewH - PAD.b} stroke={tokens.color.borderStrong} /> {xTicks.map((t) => ( <g key={`xt${t}`}> <line x1={sx(t)} y1={viewH - PAD.b} x2={sx(t)} y2={viewH - PAD.b + 4} stroke={tokens.color.borderStrong} /> <text x={sx(t)} y={viewH - PAD.b + 15} textAnchor="middle" fontSize={9.5} fill={tokens.color.neutral}> {Math.abs(t) >= 100 ? t.toFixed(0) : t.toFixed(2)} </text> </g> ))} {yTicks.map((t) => ( <g key={`yt${t}`}> <line x1={PAD.l} y1={sy(t)} x2={VIEW_W - PAD.r} y2={sy(t)} stroke={tokens.color.border} strokeDasharray="2 4" /> <text x={PAD.l - 6} y={sy(t) + 3} textAnchor="end" fontSize={9.5} fill={tokens.color.neutral}> {Math.abs(t) >= 100 ? t.toFixed(0) : t.toFixed(2)} </text> </g> ))} <text x={(PAD.l + VIEW_W - PAD.r) / 2} y={viewH - 4} textAnchor="middle" fontSize={10.5} fill={tokens.color.textDim}> {xLabel} </text> <text x={12} y={(PAD.t + viewH - PAD.b) / 2} textAnchor="middle" fontSize={10.5} fill={tokens.color.textDim} transform={`rotate(-90 12 ${(PAD.t + viewH - PAD.b) / 2})`}> {yLabel} </text>
{/* reference lines */} {refLinesY.map((r) => ( <g key={`ry${r.label}`}> <line x1={PAD.l} y1={sy(r.y)} x2={VIEW_W - PAD.r} y2={sy(r.y)} stroke={r.color ?? tokens.color.warn} strokeDasharray="6 4" strokeWidth={1.2} /> <text x={VIEW_W - PAD.r - 4} y={sy(r.y) - 4} textAnchor="end" fontSize={9.5} fill={r.color ?? tokens.color.warn}> {r.label} </text> </g> ))} {refLinesX.map((r) => ( <g key={`rx${r.label}`}> <line x1={sx(r.x)} y1={PAD.t} x2={sx(r.x)} y2={viewH - PAD.b} stroke={r.color ?? tokens.color.warn} strokeDasharray="6 4" strokeWidth={1.2} /> <text x={sx(r.x) + 4} y={PAD.t + 10} fontSize={9.5} fill={r.color ?? tokens.color.warn}> {r.label} </text> </g> ))}
{/* points */} {points.map((p) => { const dim = selected !== null && !selected.has(p.id); return ( <circle key={p.id} cx={sx(p.x)} cy={sy(p.y)} r={p.r ?? 4} fill={p.color ?? tokens.color.info} opacity={dim ? 0.18 : 0.85} stroke={hover?.id === p.id ? '#fff' : 'none'} strokeWidth={1.2} onPointerEnter={() => setHover(p)} onPointerLeave={() => setHover((h) => (h?.id === p.id ? null : h))} style={{ transition: `opacity ${tokens.motion.fast}` }} /> ); })}
{/* live brush rect */} {brush ? ( <rect x={Math.min(brush.x0, brush.x1)} y={Math.min(brush.y0, brush.y1)} width={Math.abs(brush.x1 - brush.x0)} height={Math.abs(brush.y1 - brush.y0)} fill="rgba(79,195,247,0.12)" stroke={tokens.color.info} strokeDasharray="4 3" pointerEvents="none" /> ) : null} </svg>
{hover ? ( <Box sx={{ position: 'absolute', top: 4, right: 8, px: 1, py: 0.5, bgcolor: '#1d242c', border: `1px solid ${tokens.color.borderStrong}`, borderRadius: 1, pointerEvents: 'none', }} > <Typography variant="caption" sx={{ fontFamily: 'monospace', fontSize: 11 }}> {hover.label ?? hover.id}: ({hover.x.toFixed(2)}, {hover.y.toFixed(2)}) </Typography> </Box> ) : null} </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108/** * Drag-handle list reordering (direct-manipulation primitive). * * Pointer-based (no DnD library): grab the handle, rows reorder live as you * drag, commit on release. Used for ordering query group-by chips, dashboard * widget stacking, and anywhere an ordered list needs rearranging. */import { useRef, useState, type ReactNode } from 'react';import Box from '@mui/material/Box';import { GripVertical } from 'lucide-react';import { tokens } from '../../theme';
export interface DragListItem { id: string; content: ReactNode;}
interface DragListProps { items: DragListItem[]; onReorder: (orderedIds: string[]) => void; dense?: boolean;}
export default function DragList({ items, onReorder, dense = false }: DragListProps) { const [order, setOrder] = useState<string[] | null>(null); // non-null while dragging const [dragId, setDragId] = useState<string | null>(null); const containerRef = useRef<HTMLDivElement | null>(null);
const ids = order ?? items.map((i) => i.id); const byId = new Map(items.map((i) => [i.id, i]));
const indexFromPointer = (clientY: number): number => { const container = containerRef.current; if (!container) return 0; const rows = Array.from(container.querySelectorAll<HTMLElement>('[data-dragrow]')); for (let i = 0; i < rows.length; i += 1) { const r = rows[i].getBoundingClientRect(); if (clientY < r.top + r.height / 2) return i; } return rows.length - 1; };
return ( <Box ref={containerRef} sx={{ display: 'flex', flexDirection: 'column', gap: dense ? 0.5 : 0.75 }}> {ids.map((id) => { const item = byId.get(id); if (!item) return null; const dragging = dragId === id; return ( <Box key={id} data-dragrow sx={{ display: 'flex', alignItems: 'center', gap: 1, px: 1, py: dense ? 0.5 : 0.75, borderRadius: 1, border: `1px solid ${dragging ? tokens.color.info : tokens.color.border}`, bgcolor: dragging ? tokens.color.surfaceRaised : tokens.color.surface, boxShadow: dragging ? tokens.elevation.raised : 'none', transition: `border-color ${tokens.motion.fast}, box-shadow ${tokens.motion.fast}`, userSelect: 'none', }} > <Box component="span" sx={{ display: 'inline-flex', color: tokens.color.textFaint, cursor: 'grab', touchAction: 'none', '&:hover': { color: tokens.color.info }, }} onPointerDown={(e) => { e.preventDefault(); (e.target as Element).setPointerCapture(e.pointerId); setDragId(id); setOrder(items.map((i) => i.id)); }} onPointerMove={(e) => { if (dragId !== id || order === null) return; const target = indexFromPointer(e.clientY); const current = order.indexOf(id); if (target !== current && target >= 0) { const next = [...order]; next.splice(current, 1); next.splice(target, 0, id); setOrder(next); } }} onPointerUp={(e) => { (e.target as Element).releasePointerCapture(e.pointerId); if (order) onReorder(order); setOrder(null); setDragId(null); }} > <GripVertical size={15} /> </Box> <Box sx={{ flex: 1, minWidth: 0 }}>{item.content}</Box> </Box> ); })} </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132/** * Loading / empty-state feedback components (Part 3 polish primitives). * * PanelSkeleton replaces spinner-style loading with content-shaped skeletons; * IllustratedEmpty renders a small inline-SVG illustration + a "how to * produce data" action so empty screens teach instead of dead-ending. */import type { ReactNode } from 'react';import Box from '@mui/material/Box';import Skeleton from '@mui/material/Skeleton';import Typography from '@mui/material/Typography';import { tokens } from '../../theme';
// ---------------------------------------------------------------- skeletons
export function PanelSkeleton({ rows = 4, height = 22, header = true }: { rows?: number; height?: number; header?: boolean }) { return ( <Box sx={{ p: 1 }} aria-busy="true" aria-label="Loading"> {header ? <Skeleton variant="text" width="35%" height={26} sx={{ mb: 1 }} /> : null} {Array.from({ length: rows }, (_, i) => ( <Skeleton key={i} variant="rounded" height={height} sx={{ mb: 0.75, opacity: 1 - i * 0.12 }} /> ))} </Box> );}
export function ChartSkeleton({ height = 240 }: { height?: number }) { return ( <Box sx={{ display: 'flex', alignItems: 'flex-end', gap: 1, height, p: 2 }} aria-busy="true" aria-label="Loading chart"> {[0.5, 0.8, 0.35, 0.65, 0.9, 0.45, 0.7, 0.55].map((f, i) => ( <Skeleton key={i} variant="rounded" width="100%" height={`${f * 100}%`} /> ))} </Box> );}
export function TileSkeleton({ n = 4 }: { n?: number }) { return ( <Box sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap' }} aria-busy="true"> {Array.from({ length: n }, (_, i) => ( <Skeleton key={i} variant="rounded" height={84} sx={{ flex: '1 1 150px' }} /> ))} </Box> );}
// ---------------------------------------------------------------- empty states
type EmptyArt = 'data' | 'search' | 'canvas' | 'gauge' | 'map';
function Art({ variant }: { variant: EmptyArt }) { const stroke = tokens.color.textFaint; const accent = tokens.color.info; const common = { fill: 'none', strokeWidth: 1.6, strokeLinecap: 'round' as const, strokeLinejoin: 'round' as const }; switch (variant) { case 'search': return ( <svg width="120" height="86" viewBox="0 0 120 86"> <rect x="14" y="12" width="72" height="10" rx="5" stroke={stroke} {...common} /> <rect x="14" y="30" width="52" height="10" rx="5" stroke={stroke} {...common} opacity={0.6} /> <rect x="14" y="48" width="62" height="10" rx="5" stroke={stroke} {...common} opacity={0.35} /> <circle cx="88" cy="52" r="16" stroke={accent} {...common} /> <line x1="100" y1="64" x2="110" y2="74" stroke={accent} {...common} /> </svg> ); case 'canvas': return ( <svg width="120" height="86" viewBox="0 0 120 86"> <rect x="10" y="10" width="100" height="66" rx="6" stroke={stroke} {...common} strokeDasharray="5 4" /> <rect x="26" y="26" width="26" height="16" rx="3" stroke={accent} {...common} /> <circle cx="82" cy="52" r="9" stroke={stroke} {...common} /> <path d="M 52 34 C 62 34, 66 52, 73 52" stroke={stroke} {...common} strokeDasharray="3 3" /> <path d="M 62 66 l 6 -6 m -6 6 l 8 -2 m -8 2 l 2 -8" stroke={accent} {...common} /> </svg> ); case 'gauge': return ( <svg width="120" height="86" viewBox="0 0 120 86"> <path d="M 24 70 A 40 40 0 0 1 96 70" stroke={stroke} {...common} /> <path d="M 24 70 A 40 40 0 0 1 52 33" stroke={accent} {...common} strokeWidth={3} /> <line x1="60" y1="70" x2="44" y2="46" stroke={accent} {...common} /> <circle cx="60" cy="70" r="4" fill={accent} stroke="none" /> </svg> ); case 'map': return ( <svg width="120" height="86" viewBox="0 0 120 86"> <path d="M 14 22 L 44 12 L 76 22 L 106 12 L 106 64 L 76 74 L 44 64 L 14 74 Z" stroke={stroke} {...common} /> <line x1="44" y1="12" x2="44" y2="64" stroke={stroke} {...common} opacity={0.4} /> <line x1="76" y1="22" x2="76" y2="74" stroke={stroke} {...common} opacity={0.4} /> <circle cx="60" cy="40" r="6" stroke={accent} {...common} /> <path d="M 60 46 L 60 56" stroke={accent} {...common} /> </svg> ); case 'data': default: return ( <svg width="120" height="86" viewBox="0 0 120 86"> <ellipse cx="60" cy="20" rx="34" ry="9" stroke={stroke} {...common} /> <path d="M 26 20 V 62 C 26 67, 41 71, 60 71 C 79 71, 94 67, 94 62 V 20" stroke={stroke} {...common} /> <path d="M 26 41 C 26 46, 41 50, 60 50 C 79 50, 94 46, 94 41" stroke={stroke} {...common} opacity={0.5} /> <circle cx="92" cy="62" r="13" {...common} fill={tokens.color.canvas} stroke={accent} /> <path d="M 92 56 v 12 m -6 -6 h 12" stroke={accent} {...common} /> </svg> ); }}
export function IllustratedEmpty({ art = 'data', title, message, action,}: { art?: EmptyArt; title: string; message: string; action?: ReactNode;}) { return ( <Box sx={{ textAlign: 'center', py: 5, px: 2, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 1 }}> <Art variant={art} /> <Typography variant="subtitle1" sx={{ fontWeight: 700 }}> {title} </Typography> <Typography variant="body2" sx={{ color: tokens.color.neutral, maxWidth: 520 }}> {message} </Typography> {action ? <Box sx={{ mt: 1 }}>{action}</Box> : null} </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161/** * Property inspector panel (direct-manipulation primitive). * * Click an object on any canvas → this panel shows its editable properties; * every change calls back immediately so the canvas re-renders live (WYSIWYG). * Field types: text, number, slider, select, toggle, readonly. */import type { ReactNode } from 'react';import Box from '@mui/material/Box';import MenuItem from '@mui/material/MenuItem';import Slider from '@mui/material/Slider';import Switch from '@mui/material/Switch';import TextField from '@mui/material/TextField';import Typography from '@mui/material/Typography';import { InfoDot } from '../help/InfoTip';import { tokens } from '../../theme';
export type InspectorField = | { type: 'text'; key: string; label: string; value: string; help?: string } | { type: 'number'; key: string; label: string; value: number; min?: number; max?: number; step?: number; help?: string } | { type: 'slider'; key: string; label: string; value: number; min: number; max: number; step?: number; unit?: string; help?: string } | { type: 'select'; key: string; label: string; value: string; options: Array<{ value: string; label: string }>; help?: string } | { type: 'toggle'; key: string; label: string; value: boolean; help?: string } | { type: 'readonly'; key: string; label: string; value: ReactNode; help?: string };
interface InspectorPanelProps { title: string; subtitle?: string; accent?: string; fields: InspectorField[]; onChange: (key: string, value: string | number | boolean) => void; footer?: ReactNode; emptyHint?: string;}
function FieldLabel({ label, help }: { label: string; help?: string }) { return ( <Typography variant="caption" sx={{ color: tokens.color.neutral, display: 'block', mb: 0.25 }}> {label} {help ? <InfoDot title={label} detail={help} size={11} /> : null} </Typography> );}
export default function InspectorPanel({ title, subtitle, accent, fields, onChange, footer, emptyHint }: InspectorPanelProps) { return ( <Box sx={{ border: `1px solid ${tokens.color.border}`, borderLeft: `3px solid ${accent ?? tokens.color.info}`, borderRadius: 1, bgcolor: tokens.color.surface, p: 1.5, display: 'flex', flexDirection: 'column', gap: 1.25, transition: `border-color ${tokens.motion.normal}`, }} > <Box> <Typography variant="subtitle2" sx={{ fontWeight: 700, lineHeight: 1.2 }}> {title} </Typography> {subtitle ? ( <Typography variant="caption" sx={{ color: tokens.color.neutral }}> {subtitle} </Typography> ) : null} </Box>
{fields.length === 0 && emptyHint ? ( <Typography variant="body2" sx={{ color: tokens.color.neutral, fontSize: 12.5 }}> {emptyHint} </Typography> ) : null}
{fields.map((f) => { switch (f.type) { case 'text': return ( <Box key={f.key}> <FieldLabel label={f.label} help={f.help} /> <TextField size="small" fullWidth value={f.value} onChange={(e) => onChange(f.key, e.target.value)} /> </Box> ); case 'number': return ( <Box key={f.key}> <FieldLabel label={f.label} help={f.help} /> <TextField size="small" fullWidth type="number" value={Number.isFinite(f.value) ? f.value : ''} inputProps={{ min: f.min, max: f.max, step: f.step ?? 'any' }} onChange={(e) => { const v = Number(e.target.value); if (!Number.isNaN(v)) onChange(f.key, v); }} /> </Box> ); case 'slider': return ( <Box key={f.key}> <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}> <FieldLabel label={f.label} help={f.help} /> <Typography variant="caption" sx={{ fontFamily: 'monospace', color: tokens.color.text }}> {f.value} {f.unit ?? ''} </Typography> </Box> <Slider size="small" value={f.value} min={f.min} max={f.max} step={f.step ?? 0.1} onChange={(_, v) => onChange(f.key, v as number)} sx={{ py: 0.5 }} /> </Box> ); case 'select': return ( <Box key={f.key}> <FieldLabel label={f.label} help={f.help} /> <TextField size="small" select fullWidth value={f.value} onChange={(e) => onChange(f.key, e.target.value)}> {f.options.map((o) => ( <MenuItem key={o.value} value={o.value}> {o.label} </MenuItem> ))} </TextField> </Box> ); case 'toggle': return ( <Box key={f.key} sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}> <FieldLabel label={f.label} help={f.help} /> <Switch size="small" checked={f.value} onChange={(e) => onChange(f.key, e.target.checked)} /> </Box> ); case 'readonly': return ( <Box key={f.key}> <FieldLabel label={f.label} help={f.help} /> <Typography variant="body2" sx={{ fontFamily: 'monospace', fontSize: 12, color: tokens.color.textDim }}> {f.value} </Typography> </Box> ); default: return null; } })}
{footer} </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253/** * Draggable node-graph canvas (direct-manipulation primitive). * * Generic over node payloads: the caller owns the graph state and receives * `onMoveNode` / `onConnect` / `onSelect` callbacks; this component renders * nodes (default card rendering or a custom `renderNode`), bezier edges with * arrowheads, drag with snap-to-grid, and interactive edge drawing from a * node's output port to another node's input port. * * Used by the Pipeline Builder; reusable for any stage/flow editor. */import { useState, type ReactNode } from 'react';import CanvasSurface, { snapTo, worldDrag, type CanvasApi } from './canvas';import { tokens } from '../../theme';
export interface GraphNode { id: string; x: number; y: number; label: string; sublabel?: string; color?: string; w?: number; h?: number; badge?: string;}
export interface GraphEdge { from: string; to: string; label?: string; color?: string; dashed?: boolean;}
interface NodeCanvasProps { nodes: GraphNode[]; edges: GraphEdge[]; selectedId?: string | null; onSelect?: (id: string | null) => void; onMoveNode?: (id: string, x: number, y: number) => void; /** When provided, dragging from a node's output port draws a new edge. */ onConnect?: (fromId: string, toId: string) => void; height?: number | string; world?: { x: number; y: number; w: number; h: number }; snap?: number; nodeW?: number; nodeH?: number; renderNode?: (node: GraphNode, selected: boolean) => ReactNode; ariaLabel?: string;}
const DEFAULT_W = 132;const DEFAULT_H = 56;
function edgePath(from: GraphNode, to: GraphNode, w: number, h: number): string { const fw = from.w ?? w; const tw = to.w ?? w; const sx = from.x + fw / 2; const sy = from.y; const ex = to.x - tw / 2 - 4; const ey = to.y; if (ex < sx - 20) { // feedback edge: loop under both nodes const fh = from.h ?? h; const drop = Math.max(from.y, to.y) + fh + 40; return `M ${from.x} ${from.y + fh / 2} C ${from.x} ${drop}, ${to.x} ${drop}, ${to.x} ${to.y + (to.h ?? h) / 2 + 4}`; } const mx = (sx + ex) / 2; return `M ${sx} ${sy} C ${mx} ${sy}, ${mx} ${ey}, ${ex} ${ey}`;}
export default function NodeCanvas({ nodes, edges, selectedId, onSelect, onMoveNode, onConnect, height = 480, world = { x: 0, y: 0, w: 1200, h: 520 }, snap = 20, nodeW = DEFAULT_W, nodeH = DEFAULT_H, renderNode, ariaLabel,}: NodeCanvasProps) { const byId = new Map(nodes.map((n) => [n.id, n])); const [dragOffset, setDragOffset] = useState<{ id: string; dx: number; dy: number } | null>(null); const [pendingEdge, setPendingEdge] = useState<{ fromId: string; x: number; y: number; overId: string | null } | null>(null);
const nodeAt = (x: number, y: number): GraphNode | null => nodes.find((n) => { const w2 = (n.w ?? nodeW) / 2; const h2 = (n.h ?? nodeH) / 2; return x >= n.x - w2 - 8 && x <= n.x + w2 + 8 && y >= n.y - h2 - 8 && y <= n.y + h2 + 8; }) ?? null;
return ( <CanvasSurface world={world} height={height} gridStep={snap * 2} onBackgroundClick={() => onSelect?.(null)} ariaLabel={ariaLabel ?? 'Node graph canvas'} > {(api: CanvasApi) => ( <> <defs> <marker id="nc-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"> <path d="M 0 0 L 10 5 L 0 10 z" fill="#4a5561" /> </marker> <marker id="nc-arrow-hot" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"> <path d="M 0 0 L 10 5 L 0 10 z" fill={tokens.color.info} /> </marker> </defs>
{edges.map((edge, i) => { const from = byId.get(edge.from); const to = byId.get(edge.to); if (!from || !to) return null; const hot = selectedId === edge.from || selectedId === edge.to; return ( <g key={`${edge.from}->${edge.to}-${i}`}> <path d={edgePath(from, to, nodeW, nodeH)} fill="none" stroke={hot ? tokens.color.info : edge.color ?? '#4a5561'} strokeWidth={hot ? 2 : 1.5} strokeDasharray={edge.dashed ? '5 4' : undefined} markerEnd={hot ? 'url(#nc-arrow-hot)' : 'url(#nc-arrow)'} style={{ transition: `stroke ${tokens.motion.fast}` }} /> {edge.label ? ( <text x={(from.x + to.x) / 2} y={(from.y + to.y) / 2 - 8} textAnchor="middle" fill={tokens.color.textDim} fontSize={10.5} > {edge.label} </text> ) : null} </g> ); })}
{/* edge being drawn */} {pendingEdge ? (() => { const from = byId.get(pendingEdge.fromId); if (!from) return null; return ( <path d={`M ${from.x + (from.w ?? nodeW) / 2} ${from.y} L ${pendingEdge.x} ${pendingEdge.y}`} fill="none" stroke={tokens.color.info} strokeWidth={2} strokeDasharray="6 4" markerEnd="url(#nc-arrow-hot)" pointerEvents="none" /> ); })() : null}
{nodes.map((node) => { const w = node.w ?? nodeW; const h = node.h ?? nodeH; const selected = selectedId === node.id; const targeted = pendingEdge?.overId === node.id && pendingEdge.fromId !== node.id; const drag = onMoveNode ? worldDrag(api, { onStart: (p) => { setDragOffset({ id: node.id, dx: node.x - p.x, dy: node.y - p.y }); onSelect?.(node.id); }, onMove: (p) => { const off = dragOffset && dragOffset.id === node.id ? dragOffset : { dx: 0, dy: 0 }; onMoveNode(node.id, snapTo(p.x + off.dx, snap), snapTo(p.y + off.dy, snap)); }, onEnd: () => setDragOffset(null), }) : { onPointerDown: (e: React.PointerEvent) => { e.stopPropagation(); onSelect?.(node.id); } }; return ( <g key={node.id} {...drag} style={{ cursor: onMoveNode ? 'grab' : 'pointer' }}> {renderNode ? ( renderNode(node, selected) ) : ( <> <rect x={node.x - w / 2} y={node.y - h / 2} width={w} height={h} rx={8} fill={selected ? tokens.color.surfaceRaised : tokens.color.surface} stroke={targeted ? tokens.color.success : selected ? tokens.color.info : node.color ?? tokens.color.borderStrong} strokeWidth={selected || targeted ? 2.5 : 2} style={{ transition: `stroke ${tokens.motion.fast}` }} /> <text x={node.x} y={node.y + (node.sublabel ? -2 : 4)} textAnchor="middle" fill={tokens.color.text} fontSize={12} fontWeight={700} pointerEvents="none"> {node.label} </text> {node.sublabel ? ( <text x={node.x} y={node.y + 14} textAnchor="middle" fill={node.color ?? tokens.color.textDim} fontSize={9.5} fontWeight={600} pointerEvents="none"> {node.sublabel} </text> ) : null} {node.badge ? ( <g pointerEvents="none"> <rect x={node.x + w / 2 - 26} y={node.y - h / 2 - 9} width={30} height={16} rx={8} fill={tokens.color.dangerStrong} /> <text x={node.x + w / 2 - 11} y={node.y - h / 2 + 3} textAnchor="middle" fill="#fff" fontSize={9.5} fontWeight={800}> {node.badge} </text> </g> ) : null} </> )}
{/* connection ports */} {onConnect ? ( <> {/* input port (left) */} <circle cx={node.x - w / 2} cy={node.y} r={5} fill={targeted ? tokens.color.success : '#4a5561'} stroke={tokens.color.surfaceSunken} strokeWidth={1.5} pointerEvents="none" /> {/* output port (right) — drag to draw an edge */} <circle cx={node.x + w / 2} cy={node.y} r={6} fill={pendingEdge?.fromId === node.id ? tokens.color.info : '#5c6873'} stroke={tokens.color.surfaceSunken} strokeWidth={1.5} style={{ cursor: 'crosshair' }} {...worldDrag(api, { onStart: (p) => setPendingEdge({ fromId: node.id, x: p.x, y: p.y, overId: null }), onMove: (p) => setPendingEdge({ fromId: node.id, x: p.x, y: p.y, overId: nodeAt(p.x, p.y)?.id ?? null }), onEnd: (p) => { const target = nodeAt(p.x, p.y); if (target && target.id !== node.id) onConnect(node.id, target.id); setPendingEdge(null); }, })} /> </> ) : null} </g> ); })} </> )} </CanvasSurface> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212/** * Direct-manipulation canvas foundation shared by the WYSIWYG surfaces * (Pipeline Builder node graph, Scenario Composer BEV editor, Perception * Engines BEV frame viewer). * * <CanvasSurface> renders an SVG with: * - wheel zoom centered on the cursor, * - background drag to pan, * - a `CanvasApi` (toWorld / scale) passed to children via render prop so * draggable elements can convert pointer events into world coordinates. * * `worldDrag(api, handlers)` returns pointer handlers implementing the * capture-move-release cycle in world coordinates — the single drag behavior * every draggable object on every canvas reuses. */import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';import Box from '@mui/material/Box';import { tokens } from '../../theme';
export interface CanvasApi { /** Convert a client (pointer event) position into world coordinates. */ toWorld: (clientX: number, clientY: number) => { x: number; y: number }; /** Current zoom scale (world unit -> px multiplier vs the initial fit). */ scale: number;}
export interface WorldDragHandlers { onStart?: (world: { x: number; y: number }, e: React.PointerEvent) => void; onMove: (world: { x: number; y: number }, e: React.PointerEvent) => void; onEnd?: (world: { x: number; y: number }, e: React.PointerEvent) => void;}
/** * Pointer handlers for dragging an element in world coordinates. * Attach the returned props to any SVG element inside a CanvasSurface. */export function worldDrag(api: CanvasApi, handlers: WorldDragHandlers) { return { onPointerDown: (e: React.PointerEvent) => { if (e.button !== 0) return; e.stopPropagation(); (e.target as Element).setPointerCapture(e.pointerId); handlers.onStart?.(api.toWorld(e.clientX, e.clientY), e); }, onPointerMove: (e: React.PointerEvent) => { if (!(e.target as Element).hasPointerCapture?.(e.pointerId)) return; handlers.onMove(api.toWorld(e.clientX, e.clientY), e); }, onPointerUp: (e: React.PointerEvent) => { if (!(e.target as Element).hasPointerCapture?.(e.pointerId)) return; (e.target as Element).releasePointerCapture(e.pointerId); handlers.onEnd?.(api.toWorld(e.clientX, e.clientY), e); }, };}
export function snapTo(v: number, step: number): number { return step > 0 ? Math.round(v / step) * step : v;}
interface CanvasSurfaceProps { /** World-space viewBox: the region visible at zoom 1. */ world: { x: number; y: number; w: number; h: number }; height: number | string; children: (api: CanvasApi) => ReactNode; /** Optional world-space grid rendering (line every `gridStep` units). */ gridStep?: number; /** Background click (not drag) in world coords — e.g. deselect / place. */ onBackgroundClick?: (world: { x: number; y: number }) => void; /** Native drop from an HTML drag source (palette) in world coords. */ onDropWorld?: (world: { x: number; y: number }, e: React.DragEvent) => void; disablePanZoom?: boolean; background?: string; cursor?: string; ariaLabel?: string;}
export default function CanvasSurface({ world, height, children, gridStep, onBackgroundClick, onDropWorld, disablePanZoom = false, background = tokens.color.surfaceSunken, cursor, ariaLabel,}: CanvasSurfaceProps) { const svgRef = useRef<SVGSVGElement | null>(null); // view = the world-space rectangle currently mapped onto the svg viewport. const [view, setView] = useState(world); const panRef = useRef<{ startClient: { x: number; y: number }; startView: typeof world; moved: boolean } | null>(null);
useEffect(() => { setView(world); // eslint-disable-next-line react-hooks/exhaustive-deps }, [world.x, world.y, world.w, world.h]);
const toWorld = useCallback( (clientX: number, clientY: number) => { const svg = svgRef.current; if (!svg) return { x: 0, y: 0 }; const rect = svg.getBoundingClientRect(); return { x: view.x + ((clientX - rect.left) / rect.width) * view.w, y: view.y + ((clientY - rect.top) / rect.height) * view.h, }; }, [view] );
const api: CanvasApi = { toWorld, scale: world.w / view.w };
const onWheel = useCallback( (e: React.WheelEvent) => { if (disablePanZoom) return; e.preventDefault(); const factor = e.deltaY > 0 ? 1.12 : 1 / 1.12; setView((v) => { const nw = Math.min(world.w * 4, Math.max(world.w / 12, v.w * factor)); const ratio = nw / v.w; const c = toWorld(e.clientX, e.clientY); return { x: c.x - (c.x - v.x) * ratio, y: c.y - (c.y - v.y) * ratio, w: nw, h: v.h * ratio, }; }); }, [disablePanZoom, toWorld, world.w] );
// Non-passive wheel listener so preventDefault actually stops page scroll. useEffect(() => { const svg = svgRef.current; if (!svg || disablePanZoom) return; const stop = (e: WheelEvent) => e.preventDefault(); svg.addEventListener('wheel', stop, { passive: false }); return () => svg.removeEventListener('wheel', stop); }, [disablePanZoom]);
const gridLines: ReactNode[] = []; if (gridStep && gridStep > 0) { const x0 = Math.floor(view.x / gridStep) * gridStep; const y0 = Math.floor(view.y / gridStep) * gridStep; for (let gx = x0; gx <= view.x + view.w; gx += gridStep) { gridLines.push( <line key={`v${gx}`} x1={gx} y1={view.y} x2={gx} y2={view.y + view.h} stroke={tokens.color.border} strokeWidth={view.w / 900} /> ); } for (let gy = y0; gy <= view.y + view.h; gy += gridStep) { gridLines.push( <line key={`h${gy}`} x1={view.x} y1={gy} x2={view.x + view.w} y2={gy} stroke={tokens.color.border} strokeWidth={view.w / 900} /> ); } }
return ( <Box sx={{ border: `1px solid ${tokens.color.border}`, borderRadius: 1, overflow: 'hidden', bgcolor: background, height, transition: `border-color ${tokens.motion.normal}`, '&:focus-within': { borderColor: tokens.color.borderStrong }, }} onDragOver={onDropWorld ? (e) => e.preventDefault() : undefined} onDrop={onDropWorld ? (e) => { e.preventDefault(); onDropWorld(toWorld(e.clientX, e.clientY), e); } : undefined} > <svg ref={svgRef} role="application" aria-label={ariaLabel} width="100%" height="100%" viewBox={`${view.x} ${view.y} ${view.w} ${view.h}`} style={{ display: 'block', cursor: cursor ?? (disablePanZoom ? 'default' : 'grab'), touchAction: 'none' }} onWheel={onWheel} onPointerDown={(e) => { if (e.button !== 0 || e.target !== svgRef.current) return; panRef.current = { startClient: { x: e.clientX, y: e.clientY }, startView: view, moved: false }; (e.target as Element).setPointerCapture(e.pointerId); }} onPointerMove={(e) => { const pan = panRef.current; if (!pan) return; const svg = svgRef.current; if (!svg) return; const rect = svg.getBoundingClientRect(); const dx = ((e.clientX - pan.startClient.x) / rect.width) * view.w; const dy = ((e.clientY - pan.startClient.y) / rect.height) * view.h; if (Math.abs(e.clientX - pan.startClient.x) + Math.abs(e.clientY - pan.startClient.y) > 3) pan.moved = true; if (!disablePanZoom && pan.moved) { setView({ ...view, x: pan.startView.x - dx, y: pan.startView.y - dy }); } }} onPointerUp={(e) => { const pan = panRef.current; panRef.current = null; if (pan && !pan.moved && onBackgroundClick) onBackgroundClick(toWorld(e.clientX, e.clientY)); }} > {gridLines} {children(api)} </svg> </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368/** * Shared lightweight SVG chart components used across the new visual pages: * HeatmapGrid (ODD coverage, regression map), Donut (composition), DeltaBars * (paired baseline/candidate deltas), and SeriesChart (multi-line with * reference boundaries — the base of the sequential-evidence chart). * No chart library: everything is plain SVG in theme colors. */import { useMemo, useState, type ReactNode } from 'react';import Box from '@mui/material/Box';import Tooltip from '@mui/material/Tooltip';import Typography from '@mui/material/Typography';import { tokens } from '../../theme';
// ---------------------------------------------------------------- HeatmapGrid
export interface HeatCell { row: string; col: string; value: number | null; /** Fully resolved fill color; the page owns the color semantics. */ color: string; label?: string; tooltip?: ReactNode;}
interface HeatmapGridProps { rows: string[]; cols: string[]; cells: HeatCell[]; onCellClick?: (cell: HeatCell) => void; selectedKey?: string | null; // `${row}|${col}` cellH?: number; minCellW?: number; rowLabelW?: number;}
export function HeatmapGrid({ rows, cols, cells, onCellClick, selectedKey, cellH = 34, minCellW = 56, rowLabelW = 120,}: HeatmapGridProps) { const byKey = useMemo(() => { const m = new Map<string, HeatCell>(); cells.forEach((c) => m.set(`${c.row}|${c.col}`, c)); return m; }, [cells]);
return ( <Box sx={{ overflowX: 'auto' }}> <Box sx={{ display: 'grid', gridTemplateColumns: `${rowLabelW}px repeat(${cols.length}, minmax(${minCellW}px, 1fr))`, gap: '3px', minWidth: rowLabelW + cols.length * minCellW }}> <Box /> {cols.map((c) => ( <Typography key={c} variant="caption" sx={{ color: tokens.color.textDim, textAlign: 'center', fontSize: 10.5, alignSelf: 'end', pb: 0.25, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}> {c} </Typography> ))} {rows.map((r) => ( <Box key={r} sx={{ display: 'contents' }}> <Typography variant="caption" sx={{ color: tokens.color.textDim, fontSize: 10.5, alignSelf: 'center', pr: 0.5, textAlign: 'right', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}> {r} </Typography> {cols.map((c) => { const cell = byKey.get(`${r}|${c}`); const selected = selectedKey === `${r}|${c}`; const body = ( <Box key={c} role={onCellClick ? 'button' : undefined} tabIndex={onCellClick && cell ? 0 : undefined} onClick={cell && onCellClick ? () => onCellClick(cell) : undefined} onKeyDown={cell && onCellClick ? (e) => { if (e.key === 'Enter' || e.key === ' ') onCellClick(cell); } : undefined} sx={{ height: cellH, borderRadius: '3px', bgcolor: cell ? cell.color : tokens.color.surfaceSunken, border: selected ? `2px solid #fff` : `1px solid rgba(0,0,0,0.35)`, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: cell && onCellClick ? 'pointer' : 'default', transition: `transform ${tokens.motion.fast}, border-color ${tokens.motion.fast}`, '&:hover': cell && onCellClick ? { transform: 'scale(1.06)', zIndex: 1 } : undefined, '&:focus-visible': { outline: `2px solid ${tokens.color.info}`, outlineOffset: 1 }, }} > <Typography variant="caption" sx={{ fontSize: 9.5, fontFamily: 'monospace', color: 'rgba(255,255,255,0.92)', fontWeight: 600 }}> {cell?.label ?? ''} </Typography> </Box> ); return cell?.tooltip ? ( <Tooltip key={c} title={cell.tooltip} enterDelay={150} slotProps={{ tooltip: { sx: { bgcolor: '#1d242c', border: `1px solid ${tokens.color.borderStrong}`, p: 1.25, maxWidth: 360 } } }}> {body} </Tooltip> ) : ( body ); })} </Box> ))} </Box> </Box> );}
// ---------------------------------------------------------------- Donut
export interface DonutSegment { label: string; value: number; color: string;}
export function Donut({ segments, size = 150, thickness = 22, centerLabel, centerSub }: { segments: DonutSegment[]; size?: number; thickness?: number; centerLabel?: string; centerSub?: string }) { const total = segments.reduce((s, x) => s + x.value, 0); const r = (size - thickness) / 2; const cx = size / 2; const circumference = 2 * Math.PI * r; let acc = 0; return ( <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, flexWrap: 'wrap' }}> <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}> <circle cx={cx} cy={cx} r={r} fill="none" stroke={tokens.color.border} strokeWidth={thickness} /> {total > 0 ? segments.map((s) => { const frac = s.value / total; const dash = frac * circumference; const el = ( <circle key={s.label} cx={cx} cy={cx} r={r} fill="none" stroke={s.color} strokeWidth={thickness} strokeDasharray={`${dash} ${circumference - dash}`} strokeDashoffset={-acc * circumference + circumference / 4} style={{ transition: `stroke-dasharray ${tokens.motion.slow}` }} /> ); acc += frac; return el; }) : null} {centerLabel ? ( <text x={cx} y={cx + (centerSub ? -2 : 5)} textAnchor="middle" fill={tokens.color.text} fontSize={18} fontWeight={800}> {centerLabel} </text> ) : null} {centerSub ? ( <text x={cx} y={cx + 15} textAnchor="middle" fill={tokens.color.neutral} fontSize={9.5}> {centerSub} </text> ) : null} </svg> <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}> {segments.map((s) => ( <Box key={s.label} sx={{ display: 'flex', alignItems: 'center', gap: 0.75 }}> <Box sx={{ width: 10, height: 10, borderRadius: '2px', bgcolor: s.color }} /> <Typography variant="caption" sx={{ color: tokens.color.textDim }}> {s.label} </Typography> <Typography variant="caption" sx={{ fontFamily: 'monospace', color: tokens.color.text }}> {s.value.toLocaleString()} {total > 0 ? ` (${((s.value / total) * 100).toFixed(1)}%)` : ''} </Typography> </Box> ))} </Box> </Box> );}
// ---------------------------------------------------------------- DeltaBars
export interface DeltaBarRow { label: string; baseline: number; candidate: number; delta: number; n?: number; improved: boolean; tooltip?: ReactNode;}
/** Paired horizontal bars (baseline vs candidate) with a signed delta chip. */export function DeltaBars({ rows, max = 1, fmt = (v: number) => v.toFixed(3) }: { rows: DeltaBarRow[]; max?: number; fmt?: (v: number) => string }) { return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}> {rows.map((r) => { const body = ( <Box key={r.label} sx={{ display: 'flex', alignItems: 'center', gap: 1 }}> <Typography variant="caption" sx={{ width: 130, flexShrink: 0, color: tokens.color.textDim, textAlign: 'right', pr: 0.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}> {r.label} {r.n !== undefined ? <span style={{ color: tokens.color.textFaint }}> · n={r.n.toLocaleString()}</span> : null} </Typography> <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', gap: '3px' }}> <Box sx={{ height: 7, bgcolor: tokens.color.border, borderRadius: 1, overflow: 'hidden' }}> <Box sx={{ height: '100%', width: `${Math.min(100, (r.baseline / max) * 100)}%`, bgcolor: tokens.color.textFaint, transition: `width ${tokens.motion.slow}` }} /> </Box> <Box sx={{ height: 7, bgcolor: tokens.color.border, borderRadius: 1, overflow: 'hidden' }}> <Box sx={{ height: '100%', width: `${Math.min(100, (r.candidate / max) * 100)}%`, bgcolor: r.improved ? tokens.color.success : tokens.color.danger, transition: `width ${tokens.motion.slow}` }} /> </Box> </Box> <Typography variant="caption" sx={{ width: 88, flexShrink: 0, fontFamily: 'monospace', fontWeight: 700, color: r.improved ? tokens.color.success : tokens.color.danger, }} > {r.delta >= 0 ? '+' : ''} {fmt(r.delta)} </Typography> </Box> ); return r.tooltip ? ( <Tooltip key={r.label} title={r.tooltip} enterDelay={150} placement="top" slotProps={{ tooltip: { sx: { bgcolor: '#1d242c', border: `1px solid ${tokens.color.borderStrong}`, p: 1.25, maxWidth: 380 } } }}> {body} </Tooltip> ) : ( body ); })} </Box> );}
// ---------------------------------------------------------------- SeriesChart
export interface Series { id: string; color: string; points: Array<{ x: number; y: number; meta?: unknown }>; width?: number; dashed?: boolean;}
interface SeriesChartProps { series: Series[]; height?: number; xLabel: string; yLabel: string; refLinesY?: Array<{ y: number; label: string; color?: string; dashed?: boolean }>; /** Vertical marker, e.g. "stopped here". */ markerX?: { x: number; label: string; color?: string } | null; onHoverPoint?: (seriesId: string | null, point: { x: number; y: number; meta?: unknown } | null) => void; yDomain?: [number, number]; xLog?: boolean;}
const SPAD = { l: 52, r: 14, t: 12, b: 34 };const SVIEW_W = 720;
export function SeriesChart({ series, height = 300, xLabel, yLabel, refLinesY = [], markerX = null, onHoverPoint, yDomain }: SeriesChartProps) { const [hover, setHover] = useState<{ sid: string; x: number; y: number } | null>(null);
const allX = series.flatMap((s) => s.points.map((p) => p.x)); const allY = [...series.flatMap((s) => s.points.map((p) => p.y)), ...refLinesY.map((r) => r.y)]; const xLo = allX.length ? Math.min(...allX) : 0; const xHi = allX.length ? Math.max(...allX, xLo + 1) : 1; let yLo: number; let yHi: number; if (yDomain) { [yLo, yHi] = yDomain; } else { yLo = allY.length ? Math.min(...allY) : 0; yHi = allY.length ? Math.max(...allY, yLo + 1) : 1; const pad = (yHi - yLo) * 0.1 || 1; yLo -= pad; yHi += pad; }
const sx = (x: number) => SPAD.l + ((x - xLo) / (xHi - xLo || 1)) * (SVIEW_W - SPAD.l - SPAD.r); const sy = (y: number) => height - SPAD.b - ((y - yLo) / (yHi - yLo || 1)) * (height - SPAD.t - SPAD.b);
const xTicks = Array.from({ length: 6 }, (_, i) => xLo + ((xHi - xLo) * i) / 5); const yTicks = Array.from({ length: 5 }, (_, i) => yLo + ((yHi - yLo) * i) / 4);
return ( <svg width="100%" viewBox={`0 0 ${SVIEW_W} ${height}`} style={{ display: 'block' }}> <line x1={SPAD.l} y1={height - SPAD.b} x2={SVIEW_W - SPAD.r} y2={height - SPAD.b} stroke={tokens.color.borderStrong} /> <line x1={SPAD.l} y1={SPAD.t} x2={SPAD.l} y2={height - SPAD.b} stroke={tokens.color.borderStrong} /> {xTicks.map((t) => ( <g key={`x${t}`}> <line x1={sx(t)} y1={height - SPAD.b} x2={sx(t)} y2={height - SPAD.b + 4} stroke={tokens.color.borderStrong} /> <text x={sx(t)} y={height - SPAD.b + 15} textAnchor="middle" fontSize={9.5} fill={tokens.color.neutral}> {Math.round(t).toLocaleString()} </text> </g> ))} {yTicks.map((t) => ( <g key={`y${t}`}> <line x1={SPAD.l} y1={sy(t)} x2={SVIEW_W - SPAD.r} y2={sy(t)} stroke={tokens.color.border} strokeDasharray="2 4" /> <text x={SPAD.l - 6} y={sy(t) + 3} textAnchor="end" fontSize={9.5} fill={tokens.color.neutral}> {Math.abs(t) >= 100 ? t.toFixed(0) : t.toFixed(1)} </text> </g> ))} <text x={(SPAD.l + SVIEW_W - SPAD.r) / 2} y={height - 5} textAnchor="middle" fontSize={11} fill={tokens.color.textDim}> {xLabel} </text> <text x={13} y={(SPAD.t + height - SPAD.b) / 2} textAnchor="middle" fontSize={11} fill={tokens.color.textDim} transform={`rotate(-90 13 ${(SPAD.t + height - SPAD.b) / 2})`}> {yLabel} </text>
{refLinesY.map((r) => ( <g key={`ref${r.label}`}> <line x1={SPAD.l} y1={sy(r.y)} x2={SVIEW_W - SPAD.r} y2={sy(r.y)} stroke={r.color ?? tokens.color.warn} strokeDasharray={r.dashed === false ? undefined : '7 4'} strokeWidth={1.4} /> <text x={SVIEW_W - SPAD.r - 4} y={sy(r.y) - 5} textAnchor="end" fontSize={10} fontWeight={700} fill={r.color ?? tokens.color.warn}> {r.label} </text> </g> ))}
{markerX ? ( <g> <line x1={sx(markerX.x)} y1={SPAD.t} x2={sx(markerX.x)} y2={height - SPAD.b} stroke={markerX.color ?? tokens.color.danger} strokeWidth={1.6} strokeDasharray="3 3" /> <text x={sx(markerX.x) + 5} y={SPAD.t + 11} fontSize={10} fontWeight={700} fill={markerX.color ?? tokens.color.danger}> {markerX.label} </text> </g> ) : null}
{series.map((s) => ( <g key={s.id}> <polyline points={s.points.map((p) => `${sx(p.x)},${sy(p.y)}`).join(' ')} fill="none" stroke={s.color} strokeWidth={s.width ?? 1.8} strokeDasharray={s.dashed ? '5 4' : undefined} opacity={hover && hover.sid !== s.id ? 0.25 : 1} style={{ transition: `opacity ${tokens.motion.fast}` }} /> {s.points.map((p, i) => ( <circle key={i} cx={sx(p.x)} cy={sy(p.y)} r={hover?.sid === s.id && hover.x === p.x ? 5 : 3} fill={s.color} opacity={hover && hover.sid !== s.id ? 0.25 : 1} onPointerEnter={() => { setHover({ sid: s.id, x: p.x, y: p.y }); onHoverPoint?.(s.id, p); }} onPointerLeave={() => { setHover(null); onHoverPoint?.(null, null); }} style={{ cursor: 'pointer', transition: `r ${tokens.motion.fast}` }} /> ))} </g> ))} </svg> );}32 unmodified lines33343536373839617 unmodified lines65765865966066166266366414 unmodified lines67968068168268368453 unmodified lines73873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579627 unmodified lines82482582682782882969 unmodified lines89990090190290332 unmodified lines| 'Operations'| 'EM readiness'| 'Hardware acceleration'| 'Retrospective safety';export const GLOSSARY: Record<string, GlossaryEntry> = {// ------------------------------------------------------------ detection metrics617 unmodified linesshort: 'Running a candidate model on live traffic without acting on its output.',detail: 'The candidate scores real production inputs in parallel with the incumbent; outcomes are compared post-hoc. Sensitive to sampling bias, serving-config differences and provisional labels — which is why the Root Cause Lab audits the shadow pipeline before trusting its number.',},// ------------------------------------------------- rare-event mining (raremine)costumed_pedestrian: {term: 'Costumed pedestrian',category: 'Anomaly & rarity',14 unmodified linesdetail: 'Candidates are binned by stated rare-event confidence; within each bin, the observed rate of true (planted) rare events is measured. A calibrated miner\u2019s 80% bin is right about 80% of the time — over-confident bins mean stated confidence cannot be trusted for triage ordering.',},// ------------------------------------------------------------ hardware acceleration (Vitis)vitis_emulated_backend: {term: 'Emulated Vitis backend',53 unmodified linesdetail: 'Every generated augmentation variant carries training_eligible: false, evaluation_only: true and destination REGRESSION_EVALUATION_SET, plus complete lineage (recipe with resolved parameters, seed, source frame, backend config). Mirrors the rare-event miner\u2019s protected-destination leakage guard: stress data that leaked into training would corrupt the very regression signal it exists to protect.',},// ------------------------------------------------------------ EM readiness (Hill Climbing EM)hc_competency: {term: 'Competency',category: 'EM readiness',short: 'A single skill node in the 4-phase blueprint graph, with prerequisites and a dimension tag.',detail: 'Each competency belongs to a phase (ML depth / system design / execution & people / simulation), lists prerequisite competencies, and is tagged with one dimension (Knowledge, Technical Reasoning, Leadership, Execution). Scores are tracked per competency and per dimension — never collapsed into one number.',},hc_readiness_state: {term: 'Readiness state',category: 'EM readiness',short: 'Per-competency progression: NOT_STARTED → LEARNING → PRACTICING → NEEDS_REVIEW → COMPETENT → STRONG → INTERVIEW_READY.',detail: 'Derived from three separate scores: knowledge (diagnostic/interview answers), application (exercises, design lab, simulation) and evidence (STAR stories and other artifacts). NEEDS_REVIEW is entered when recent attempts contradict earlier strong scores.',caveat: 'States are only as trustworthy as the evidence backing them; with the LLM offline, scoring is rule-based concept coverage, which is stricter but coarser.',},hc_evidence_artifact: {term: 'Evidence artifact',category: 'EM readiness',short: 'A stored, quotable record (attempt, STAR story, design grade, simulation debrief, interview transcript) that justifies a score.',detail: 'The scoring rule is "no score without evidence": every evaluation must quote specific user statements. Artifacts persist under runs/hillclimb/ and are browsable in the Evidence Library; clicking any matrix score shows the artifacts behind it.',},hc_bottleneck: {term: 'Bottleneck competency',category: 'EM readiness',short: 'The weak prerequisite blocking the most downstream competencies — not merely the lowest score.',detail: 'Computed from the prerequisite graph: for each weak competency, count the downstream competencies transitively gated on it; the highest-leverage weakness wins. Fixing the bottleneck unblocks more of the graph than fixing the globally lowest score.',},hc_next_best_action: {term: 'Next best action',category: 'EM readiness',short: 'Exactly one concept to study, one exercise to attempt and one assessment to take, aimed at the current bottleneck.',detail: 'Regenerated whenever the readiness matrix changes. Deliberately singular: a ranked to-do list invites cherry-picking easy items; one action per category forces work on the highest-leverage weakness.',},hc_claim_vs_evidence: {term: 'Claim vs evidence',category: 'EM readiness',short: 'STAR Story Box flag: an unquantified claim ("improved performance") vs measurable evidence (numbers, before/after, named mechanism).',detail: 'Claim sentences are detected by improvement verbs without attached quantities. Each flag asks for the missing strengthening: the metric, the baseline, the delta, or the mechanism that caused it. Interviewers apply the same test — so the diagnoser applies it first.',},hc_anti_gaming: {term: 'Anti-gaming rule',category: 'EM readiness',short: 'Verbosity alone must not raise scores: concept coverage, tradeoffs and quantified results are scored, not length.',detail: 'The evaluator scores rubric-concept coverage, tradeoff discussion and quantified statements. Length is not a feature, and low information density is penalized — a long waffle scores below a short precise answer (enforced by test).',},hc_hill_climbing: {term: 'Hill climbing (simulation)',category: 'EM readiness',short: 'Iterative optimization loop: hypothesis → intervention → measure → keep/reject → repeat, under competing objectives.',detail: 'The Phase-4 simulation tracks ten competing state metrics (performance, safety, reliability, cost, velocity, maintainability, morale, customer impact, risk, schedule) with hard floors — dropping safety below its floor triggers an incident. The balanced multi-objective score rewards keeping all objectives healthy, not maximizing one.',caveat: 'Deterministic given the scenario seed: identical intervention sequences replay identically, which is what makes debriefs auditable.',},// ------------------------------------------------------------ Retrospective safetyevidence_tier: {term: 'Evidence tier',category: 'Retrospective safety',27 unmodified linesshort: 'Every agent tool call — including denials — is appended to a per-analysis audit log with args, result hash, and timestamp.',detail: 'Tools are read-only by default; the single write tool (CreateEvaluationCase) requires an explicit policy authorization flag. The log reader is path-allowlisted to runs/ and the fixtures directory. The audit trail makes each scorecard reproducible and reviewable.',},};export type GlossaryKey = keyof typeof GLOSSARY;69 unmodified lines'Operations','EM readiness','Hardware acceleration','Retrospective safety',];32 unmodified lines3334353637383940414243617 unmodified lines66166266366466566614 unmodified lines68168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773853 unmodified lines79279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293327 unmodified lines9619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101969 unmodified lines10891090109110921093109410951096109732 unmodified lines| 'Operations'| 'EM readiness'| 'Hardware acceleration'| 'Safety & compliance'| 'Sequential testing'| 'Perception fusion'| 'Retrospective safety'| 'Launch readiness';export const GLOSSARY: Record<string, GlossaryEntry> = {// ------------------------------------------------------------ detection metrics617 unmodified linesshort: 'Running a candidate model on live traffic without acting on its output.',detail: 'The candidate scores real production inputs in parallel with the incumbent; outcomes are compared post-hoc. Sensitive to sampling bias, serving-config differences and provisional labels — which is why the Root Cause Lab audits the shadow pipeline before trusting its number.',},costumed_pedestrian: {term: 'Costumed pedestrian',category: 'Anomaly & rarity',14 unmodified linesdetail: 'Candidates are binned by stated rare-event confidence; within each bin, the observed rate of true (planted) rare events is measured. A calibrated miner\u2019s 80% bin is right about 80% of the time — over-confident bins mean stated confidence cannot be trusted for triage ordering.',},// ------------------------------------------------------------ EM readiness (Hill Climbing EM)hc_competency: {term: 'Competency',category: 'EM readiness',short: 'A single skill node in the 4-phase blueprint graph, with prerequisites and a dimension tag.',detail: 'Each competency belongs to a phase (ML depth / system design / execution & people / simulation), lists prerequisite competencies, and is tagged with one dimension (Knowledge, Technical Reasoning, Leadership, Execution). Scores are tracked per competency and per dimension — never collapsed into one number.',},hc_readiness_state: {term: 'Readiness state',category: 'EM readiness',short: 'Per-competency progression: NOT_STARTED → LEARNING → PRACTICING → NEEDS_REVIEW → COMPETENT → STRONG → INTERVIEW_READY.',detail: 'Derived from three separate scores: knowledge (diagnostic/interview answers), application (exercises, design lab, simulation) and evidence (STAR stories and other artifacts). NEEDS_REVIEW is entered when recent attempts contradict earlier strong scores.',caveat: 'States are only as trustworthy as the evidence backing them; with the LLM offline, scoring is rule-based concept coverage, which is stricter but coarser.',},hc_evidence_artifact: {term: 'Evidence artifact',category: 'EM readiness',short: 'A stored, quotable record (attempt, STAR story, design grade, simulation debrief, interview transcript) that justifies a score.',detail: 'The scoring rule is "no score without evidence": every evaluation must quote specific user statements. Artifacts persist under runs/hillclimb/ and are browsable in the Evidence Library; clicking any matrix score shows the artifacts behind it.',},hc_bottleneck: {term: 'Bottleneck competency',category: 'EM readiness',short: 'The weak prerequisite blocking the most downstream competencies — not merely the lowest score.',detail: 'Computed from the prerequisite graph: for each weak competency, count the downstream competencies transitively gated on it; the highest-leverage weakness wins. Fixing the bottleneck unblocks more of the graph than fixing the globally lowest score.',},hc_next_best_action: {term: 'Next best action',category: 'EM readiness',short: 'Exactly one concept to study, one exercise to attempt and one assessment to take, aimed at the current bottleneck.',detail: 'Regenerated whenever the readiness matrix changes. Deliberately singular: a ranked to-do list invites cherry-picking easy items; one action per category forces work on the highest-leverage weakness.',},hc_claim_vs_evidence: {term: 'Claim vs evidence',category: 'EM readiness',short: 'STAR Story Box flag: an unquantified claim ("improved performance") vs measurable evidence (numbers, before/after, named mechanism).',detail: 'Claim sentences are detected by improvement verbs without attached quantities. Each flag asks for the missing strengthening: the metric, the baseline, the delta, or the mechanism that caused it. Interviewers apply the same test — so the diagnoser applies it first.',},hc_anti_gaming: {term: 'Anti-gaming rule',category: 'EM readiness',short: 'Verbosity alone must not raise scores: concept coverage, tradeoffs and quantified results are scored, not length.',detail: 'The evaluator scores rubric-concept coverage, tradeoff discussion and quantified statements. Length is not a feature, and low information density is penalized — a long waffle scores below a short precise answer (enforced by test).',},hc_hill_climbing: {term: 'Hill climbing (simulation)',category: 'EM readiness',short: 'Iterative optimization loop: hypothesis → intervention → measure → keep/reject → repeat, under competing objectives.',detail: 'The Phase-4 simulation tracks ten competing state metrics (performance, safety, reliability, cost, velocity, maintainability, morale, customer impact, risk, schedule) with hard floors — dropping safety below its floor triggers an incident. The balanced multi-objective score rewards keeping all objectives healthy, not maximizing one.',caveat: 'Deterministic given the scenario seed: identical intervention sequences replay identically, which is what makes debriefs auditable.',},// ------------------------------------------------------------ hardware acceleration (Vitis)vitis_emulated_backend: {term: 'Emulated Vitis backend',53 unmodified linesdetail: 'Every generated augmentation variant carries training_eligible: false, evaluation_only: true and destination REGRESSION_EVALUATION_SET, plus complete lineage (recipe with resolved parameters, seed, source frame, backend config). Mirrors the rare-event miner\u2019s protected-destination leakage guard: stress data that leaked into training would corrupt the very regression signal it exists to protect.',},// ------------------------------------------------------------ safety & complianceodd: {term: 'ODD (Operational Design Domain)',category: 'Safety & compliance',short: 'The set of conditions the autonomy system is designed — and validated — to operate in.',detail: 'Formalized here as a taxonomy of dimensions (object class, weather, lighting, traffic density, road type). Every claim of safety only holds inside the ODD cells that have adequate evaluation evidence.',},odd_coverage: {term: 'ODD coverage',category: 'Safety & compliance',short: 'Fraction of ODD cells with enough evaluation samples and acceptable performance.',detail: 'A cell (class × condition) counts as covered when its evaluation sample count meets the per-cell requirement and its recall clears the policy floor. Production-weighted coverage weights each cell by its real-world exposure frequency, so covering a common cell counts more than an exotic one.',caveat: 'Coverage measures evidence quantity, not difficulty: a covered cell can still hide a hard sub-population.',},coverage_gap: {term: 'Coverage gap',category: 'Safety & compliance',short: 'An ODD cell with too little evaluation evidence (or too-low performance) to support a safety claim.',detail: 'Gaps are ranked by risk score = production exposure × class severity × statistical uncertainty. The top-ranked gap is the highest-value target for scenario generation or data collection.',},release_gate: {term: 'Release gate',category: 'Safety & compliance',short: 'A named safety criterion that must pass before a model can be promoted.',detail: 'Each gate bundles concrete checks (measured value vs policy threshold): overall quality, safety-critical recall, non-regression vs baseline, ODD coverage, and calibration health. One failing check blocks the gate; one blocked gate blocks the release.',},evidence_package: {term: 'Safety evidence package',category: 'Safety & compliance',short: 'A structured document assembling all evaluation evidence behind a release decision.',detail: 'Generated per candidate run: scope, gate results, coverage summary, calibration status, known limitations and sign-off placeholders, in the spirit of ISO 21448 (SOTIF) / UL 4600 argumentation.',caveat: 'The package generated in this demo is a synthetic demonstration artifact — not a real certification document.',},drac: {term: 'DRAC',category: 'Safety (SSAM)',short: 'Deceleration Rate to Avoid Crash — braking intensity required to prevent the collision.',detail: 'Computed from relative speed and gap at the conflict point: DRAC = Δv² / (2·distance). Values above ~3.35 m/s² conventionally mark an emergency-braking-level conflict.',},delta_s: {term: 'ΔS (speed differential)',category: 'Safety (SSAM)',short: 'Relative speed of the two road users at the conflict point.',detail: 'Higher ΔS means higher kinetic energy in a hypothetical collision — it scales the severity component of conflict indices.',},csi: {term: 'CSI (Conflict Severity Index)',category: 'Safety (SSAM)',short: 'Composite 0–1 severity score combining proximity (TTC/PET), required braking (DRAC) and speed differential.',detail: 'Blends the surrogate measures into a single ranking score so conflicts from different mechanisms (crossing, rear-end, merging) are comparable. Used to rank conflicts and compare scenarios.',caveat: 'The blend weights are a documented convention; always inspect the underlying TTC/PET/DRAC values before acting on a CSI ranking.',},extrinsic_calibration: {term: 'Extrinsic calibration',category: 'Safety & compliance',short: 'The rigid transform (rotation + translation) mapping one sensor\u2019s frame into another\u2019s.',detail: 'Validated cross-sensor: project LiDAR objects into the camera frame and measure residual offsets. A consistent directional residual across all objects indicates miscalibration; large residuals on a few objects indicate perception failures.',},residual: {term: 'Calibration residual',category: 'Safety & compliance',short: 'Per-object positional disagreement between camera and LiDAR after applying the calibration transform.',detail: 'Plotted as a 2D scatter (lateral × longitudinal offset). Healthy: tight cloud at origin. Miscalibrated: whole cloud shifted/rotated coherently. Perception failure: tight cloud plus isolated far outliers.',},discrepancy_mining: {term: 'Discrepancy mining',category: 'Safety & compliance',short: 'Systematically finding objects where auto-labels, human labels and model predictions disagree.',detail: 'Disagreements are typed (missing box, spurious box, class confusion, geometry drift) and aggregated per cohort. A cohort with a high discrepancy rate is where labeling quality is systematically weakest — without needing any new ground truth.',},semantic_search_stage: {term: 'Hybrid semantic search',category: 'Safety & compliance',short: 'Concept search = symbolic dimension filter → reasoning scorer → blended ranking, with per-stage explanations.',detail: 'The symbolic stage parses hard constraints from the query (e.g. lighting=night); the reasoning stage scores conceptual relevance; the blend combines them. Each result explains its score per stage, and a provider badge states whether an LLM or the deterministic fallback did the scoring.',},// ------------------------------------------------------------ sequential testingevalue: {term: 'E-value / e-process',category: 'Sequential testing',short: 'Betting-style evidence measure that stays valid under continuous monitoring — no peeking penalty.',detail: 'An e-process accumulates multiplicative evidence against a hypothesis; its running value can be checked after every sample, and rejecting when it crosses 1/α controls the error rate at α regardless of when you stop. The sequential-evidence chart plots log e-values, so the stopping boundary is a horizontal line.',},stopping_boundary: {term: 'Stopping boundary',category: 'Sequential testing',short: 'The evidence threshold that ends the sequential test the moment it is crossed.',detail: 'Crossing the upper (rejection) boundary = enough evidence of regression → BLOCK; crossing the lower boundary = enough evidence of safety → PASS. Running out of budget between the boundaries yields INSUFFICIENT_EVIDENCE.',},n_eff: {term: 'Effective n',category: 'Sequential testing',short: 'The information-equivalent sample count after accounting for correlation and weighting.',detail: 'Samples that are correlated (same scene, same track) carry less independent information than their raw count suggests. Decisions report both raw n used and effective n; a large gap flags heavy within-cluster correlation.',},safety_primary_node: {term: 'Safety-primary node',category: 'Sequential testing',short: 'A tested slice flagged as safety-critical and held to stricter sequential thresholds.',detail: 'Safety-primary nodes (e.g. pedestrian-at-night) get tighter regression tolerances and higher evidence requirements — a marginal regression that would pass on a comfort slice blocks on a safety-primary one.',},sample_budget: {term: 'Sample budget',category: 'Sequential testing',short: 'The maximum labeled samples the sequential run may spend before it must decide.',detail: 'The budget funnel shows planned budget vs actually used vs the full population size: the gap between used and population is the labeling cost the sequential design saved over a fixed-n evaluation.',},// ------------------------------------------------------------ perception fusionbev: {term: 'BEV (bird\u2019s-eye view)',category: 'Perception fusion',short: 'Top-down ego-centric view of the scene — the natural frame for fusing multi-sensor detections.',detail: 'All detections and boxes are expressed in the ego frame (x forward, y left, meters) and rasterized or drawn top-down. Distance rings and an ego marker anchor the geometry.',},along_ray_uncertainty: {term: 'Along-ray uncertainty',category: 'Perception fusion',short: 'Monocular camera depth error: large along the viewing ray, small across it.',detail: 'A camera fixes bearing precisely but estimates depth poorly, so its position covariance is an elongated ellipse pointing along the ray from the camera — exactly what the BEV canvas draws. Fusion with LiDAR (precise range) collapses that ellipse.',},masklet_propagation: {term: 'Masklet propagation',category: 'Perception fusion',short: 'Carrying a track through detection gaps using its motion model instead of dropping it.',detail: 'When a tracked object gets no detection this frame (occlusion, dropout), the tracker propagates the box along the track\u2019s estimated velocity for a bounded number of frames — drawn dashed on the canvas. Identity survives the gap, which is what improves IDF1 and cuts fragmentation.',caveat: 'Propagation is a prediction, not an observation: propagated boxes carry reduced confidence and expire if no detection re-associates.',},fused_track: {term: 'Fused track',category: 'Perception fusion',short: 'An object hypothesis maintained over time from camera + LiDAR detections fused in BEV.',detail: 'Camera and LiDAR detections are associated and merged per frame (covariance-weighted), then linked over time by the tracker. The canvas shows fused boxes filled, with the track ID label — click one to follow it across frames.',},// ------------------------------------------------------------ retrospective safetyevidence_tier: {term: 'Evidence tier',category: 'Retrospective safety',27 unmodified linesshort: 'Every agent tool call — including denials — is appended to a per-analysis audit log with args, result hash, and timestamp.',detail: 'Tools are read-only by default; the single write tool (CreateEvaluationCase) requires an explicit policy authorization flag. The log reader is path-allowlisted to runs/ and the fixtures directory. The audit trail makes each scorecard reproducible and reviewable.',},// ------------------------------------------------------------ launch readiness (agentic triage)policy_outcome: {term: 'Policy outcome (four-way)',category: 'Launch readiness',short: 'AUTOMATIC_STOP_SHIP / LAUNCH_REVIEW_REQUIRED / CONTINUE_INVESTIGATION / NO_LAUNCH_IMPACT — decided by the deterministic policy engine, never by an agent.',detail: 'The versioned stop-ship policy evaluates explicit conditions over severity × exposure × frequency × confidence × novelty × downstream consequence. Automatic stop-ship fires only on pre-authorized conditions; anything with missing ground truth, incomplete lineage, failed fusion verification or conflicting agents resolves to INDETERMINATE (a fail-safe escalation), never a pass.',caveat: 'All numeric thresholds in the shipped policy are example placeholders (flagged placeholder_values: true); a real deployment must set organization-approved values through the versioned policy API.',},severity_taxonomy: {term: 'Severity taxonomy (S0–S5)',category: 'Launch readiness',short: 'S0 cosmetic → S5 collision-in-replay, assigned by deterministic criteria over class criticality, containment and observed behavioral impact.',detail: 'S4 requires OBSERVED unsafe downstream behavior in replay evidence — a hypothesized consequence cannot reach S4. S3 is a safety-critical misclassification whose downstream effect is not shown to be contained.',},evidence_status_tag: {term: 'Evidence status (OBSERVED / DERIVED / HYPOTHESIS / UNAVAILABLE)',category: 'Launch readiness',short: 'Every node in the failure evidence graph carries an explicit epistemic status; missing evidence is shown as UNAVAILABLE rather than guessed.',detail: 'OBSERVED = measured from campaign data or replay; DERIVED = computed deterministically from observed data; HYPOTHESIS = produced by an advisory agent and requires confirmation; UNAVAILABLE = the evidence does not exist yet. Agents cannot upgrade their own hypotheses.',},option_c_reduced_odd: {term: 'Option C — reduced ODD',category: 'Launch readiness',short: 'Ship while excluding the concentrated failure region from the operational design domain — allowed only when the region is reliably detectable at runtime.',detail: 'Feasibility checks use the ODD taxonomy: the concentrating dimension must be an instrumented ODD dimension, the runtime detector recall must meet MIN_REQUIRED_SAFETY_RECALL, the post-exclusion residual rate must meet MAX_ACCEPTABLE_FAILURE_PROBABILITY, evidence confidence must reach the configured minimum, and the exclusion must not exceed MAX_ALLOWED_ODD_EXCLUSION.',caveat: 'A geographic bucket is not an instrumented ODD dimension, so geo-concentration alone can never justify Option C.',},hard_safety_constraint: {term: 'Safety as a hard constraint',category: 'Launch readiness',short: 'Expected loss is computed for every option, but options whose residual failure rate violates the policy limit are excluded from selection no matter how cheap they are.',detail: 'Business optimization happens only inside the safe feasible region: the option matrix skips a matched row whose option is safety-infeasible, and if no feasible row remains the engine fails safe to human safety review. Tested explicitly: a cheaper unsafe option is never selected.',},contamination_guard: {term: 'Contamination guard',category: 'Launch readiness',short: 'Members of flywheel evaluation suites are never training-eligible without an explicit recorded override (who + why).',detail: 'Prevents the learning flywheel from leaking its own evaluation examples into training data, which would silently invalidate future evaluations. Promotion without an actor and reason raises a leakage error (reusing the raremine lineage guard); overrides are recorded on the suite and in the audit trail.',},small_sample_instability: {term: 'Small-sample instability flag',category: 'Launch readiness',short: 'Raised when event counts are too small for the rate estimate to be stable (e.g. 25 events on a 240k denominator), capping evidence confidence.',detail: 'A ~0.01% rate estimated from a handful of events has a wide Wilson interval and an unstable relative risk. The statistical agent flags this, the evidence-quality level drops to LIKELY or below, and automatic stop-ship (which requires CONFIRMED) cannot fire on it — the case routes to human review instead.',},audit_hash_chain: {term: 'Hash-chained audit log',category: 'Launch readiness',short: 'Every stage transition, agent output, policy evaluation and human decision is appended to a per-failure JSONL log where each record hashes its predecessor.',detail: 'Records carry a monotonically increasing sequence number and a prev_hash → hash chain; any edit, deletion or reordering breaks recomputation and is reported as a broken chain. The log is append-only by construction.',},};export type GlossaryKey = keyof typeof GLOSSARY;69 unmodified lines'Operations','EM readiness','Hardware acceleration','Safety & compliance','Sequential testing','Perception fusion','Retrospective safety','Launch readiness',];
202 unmodified lines2032042052062072086 unmodified lines2152162172182192202212222232242252262272282292302317 unmodified lines239240241242243244245246247248249250251252253254202 unmodified linesdataFlow:'Investigations generate a paired offline + shadow evaluation dataset (persisted under runs/rca/). Every diagnostic is computed from that data — nothing is invented — and every board score traces to a recorded finding. Reports feed promotion decisions and the recommended follow-up experiments.',},vitis: {subtitle:'Optional AMD/Xilinx Vitis Vision acceleration layer: an emulated FPGA backend (honestly labeled — no hardware attached) powering HIL quantization-gap regression detection, accelerated ISP + synthetic edge-case generation, and temporal/stereo stability profiling.',6 unmodified linesdataFlow:'Scenes and engines come read-only from the bevfusion package; sequential verdicts use seqeval\u2019s anytime-valid tests when importable (local paired-t fallback otherwise). Runs persist under runs/vitis/. Generated variants are evaluation-set supplements tagged evaluation-only (never training-eligible) and are offered to the raremine candidate flow when that package is available.',},hillclimb: {subtitle:'Adaptive Engineering-Manager development & interview-readiness platform: a 4-phase competency blueprint (ML depth → system design → execution & people → hill-climbing simulation) with evidence-based scoring, never self-reported progress.',purpose:'Interview readiness is a hill-climbing problem: find the competency whose weakness blocks the most downstream skills, fix it with deliberate practice, measure, repeat. This section runs that loop — Assess → Diagnose → Practice → Apply → Evaluate → Improve — over a prerequisite-linked competency graph reconstructed from the Hill Climbing EM blueprint spec.',reading:'Dashboard bars are per-dimension readiness (Knowledge / Technical Reasoning / Leadership / Execution — tracked separately, never collapsed). The bottleneck callout names the prerequisite blocking the most downstream competencies, not merely the lowest score. Every score in the matrix is explainable: click it to see the evidence artifacts (attempt quotes, STAR stories, design grades, simulation debriefs, interview transcripts) that produced it. Coaching panels quote your own statements as evidence — a score without evidence is never shown.',actions:'Run the adaptive diagnostic to seed your matrix. Practice generated exercises (structurally different on each retry) and get rubric-based coaching. Diagnose raw experience stories into STAR components with claim-vs-evidence flags. Build architectures in the Design Lab. Play the multi-objective hill-climbing simulation. Take an adaptive mock interview. Review your evidence library and competency matrix.',dataFlow:'All state persists under runs/hillclimb/. Exercise submissions, STAR stories, design grades, simulation debriefs and interview transcripts become Evidence artifacts that feed the readiness matrix; the matrix feeds bottleneck analysis and the Next Best Action. The Phase-1 "offline +5% / shadow −2%" exercise family cross-links to the Root Cause Lab as the live practice tool.',},retro: {subtitle:7 unmodified linesdataFlow:'Fixtures live in sensorflow/retro/fixtures; analyses and audit trails persist under runs/retro/. Metric math reuses the SSAM safety extensions; distribution stats delegate to the mega-eval engine; the safety-case corpus is indexed at startup (chromadb or deterministic fallback).',},ssam: {subtitle:'Surrogate-safety analysis of real intersections: conflicts ranked by TTC / PET / severity on an interactive map — the safety context the label platform feeds.',purpose:'Identify dangerous intersections and conflict patterns from trajectory data using surrogate safety measures (no crashes required).',reading:'Map markers are intersections sized/colored by severity; the drawer ranks conflicts (critical / high / medium / low) with TTC, PET and speeds — hover the column headers for definitions. The grid lists individual conflict events.',actions: 'Filter by county / conflict type / severity, inspect intersections, drill into conflict events.',dataFlow:'Trajectories come from perception output upstream; hotspots identified here define the safety-critical scenarios that evaluation cohorts and rare-event mining prioritize.',},legacy: {subtitle:202 unmodified lines2032042052062072082092102112122132142152162172182192206 unmodified lines2272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973987 unmodified lines406407408409410411412413414415416417418419420421422202 unmodified linesdataFlow:'Investigations generate a paired offline + shadow evaluation dataset (persisted under runs/rca/). Every diagnostic is computed from that data — nothing is invented — and every board score traces to a recorded finding. Reports feed promotion decisions and the recommended follow-up experiments.',},hillclimb: {subtitle:'Adaptive Engineering-Manager development & interview-readiness platform: a 4-phase competency blueprint (ML depth → system design → execution & people → hill-climbing simulation) with evidence-based scoring, never self-reported progress.',purpose:'Interview readiness is a hill-climbing problem: find the competency whose weakness blocks the most downstream skills, fix it with deliberate practice, measure, repeat. This section runs that loop — Assess → Diagnose → Practice → Apply → Evaluate → Improve — over a prerequisite-linked competency graph reconstructed from the Hill Climbing EM blueprint spec.',reading:'Dashboard bars are per-dimension readiness (Knowledge / Technical Reasoning / Leadership / Execution — tracked separately, never collapsed). The bottleneck callout names the prerequisite blocking the most downstream competencies, not merely the lowest score. Every score in the matrix is explainable: click it to see the evidence artifacts (attempt quotes, STAR stories, design grades, simulation debriefs, interview transcripts) that produced it. Coaching panels quote your own statements as evidence — a score without evidence is never shown.',actions:'Run the adaptive diagnostic to seed your matrix. Practice generated exercises (structurally different on each retry) and get rubric-based coaching. Diagnose raw experience stories into STAR components with claim-vs-evidence flags. Build architectures in the Design Lab. Play the multi-objective hill-climbing simulation. Take an adaptive mock interview. Review your evidence library and competency matrix.',dataFlow:'All state persists under runs/hillclimb/. Exercise submissions, STAR stories, design grades, simulation debriefs and interview transcripts become Evidence artifacts that feed the readiness matrix; the matrix feeds bottleneck analysis and the Next Best Action. The Phase-1 "offline +5% / shadow −2%" exercise family cross-links to the Root Cause Lab as the live practice tool.',},vitis: {subtitle:'Optional AMD/Xilinx Vitis Vision acceleration layer: an emulated FPGA backend (honestly labeled — no hardware attached) powering HIL quantization-gap regression detection, accelerated ISP + synthetic edge-case generation, and temporal/stereo stability profiling.',6 unmodified linesdataFlow:'Scenes and engines come read-only from the bevfusion package; sequential verdicts use seqeval\u2019s anytime-valid tests when importable (local paired-t fallback otherwise). Runs persist under runs/vitis/. Generated variants are evaluation-set supplements tagged evaluation-only (never training-eligible) and are offered to the raremine candidate flow when that package is available.',},ssam: {subtitle:'Surrogate-safety analysis of real intersections: conflicts ranked by TTC / PET / severity on an interactive map — the safety context the label platform feeds.',purpose:'Identify dangerous intersections and conflict patterns from trajectory data using surrogate safety measures (no crashes required).',reading:'Map markers are intersections sized/colored by severity; the drawer ranks conflicts (critical / high / medium / low) with TTC, PET and speeds — hover the column headers for definitions. The grid lists individual conflict events.',actions: 'Filter by county / conflict type / severity, inspect intersections, drill into conflict events.',dataFlow:'Trajectories come from perception output upstream; hotspots identified here define the safety-critical scenarios that evaluation cohorts and rare-event mining prioritize.',},'safety-odd': {subtitle:'Interactive coverage map of the Operational Design Domain: which class × condition cells have enough evaluation evidence, and which gaps carry the most risk.',purpose:'An autonomy system is only validated inside the conditions it was actually evaluated in. This page grids the ODD taxonomy into cells (class × weather/lighting/density/road type), scores each cell\u2019s sample adequacy and performance, and ranks the uncovered cells by exposure-weighted risk so data collection goes where it matters.',reading:'The heatmap colors each cell by coverage adequacy: green = covered (enough samples, acceptable recall), amber = thin evidence, red = gap, gray = no data. Cell labels show sample counts; click a cell for its full detail (samples vs required, recall, production frequency weight). The gap table below is sorted by risk score = production exposure × severity × uncertainty — the top row is literally "the most dangerous thing we haven\u2019t tested enough".',actions:'Switch the condition dimension (weather / lighting / density / road type), click cells to inspect, and use "Fill gap" on a gap row to simulate targeted scenario generation for that cell — a before/after dialog shows how the coverage rate and the cell\u2019s adequacy would move.',dataFlow:'Coverage is computed from the published mega-eval run\u2019s per-cohort sample counts and recall, joined against the ODD taxonomy and production-fleet exposure weights. Fill-gap simulations call the scenario generator preview; actually collecting the data happens upstream in scenario generation / data acquisition.',},'safety-gates': {subtitle:'The release decision, made visible: five safety gates evaluated candidate-vs-baseline, each expanding into its actual-vs-threshold checks, with an editable gate policy.',purpose:'A model ships only if every safety gate passes. This page runs the full gate evaluation (overall quality, safety-critical recall, regression vs baseline, ODD coverage, calibration health) and shows exactly which check blocked a release — no more digging through logs to learn why promotion failed.',reading:'The verdict banner is the headline: RELEASE_READY (all gates green) or BLOCKED (any gate red). The pipeline strip shows the five gates as connected stages — click one to expand its checks: each row is measured value vs policy threshold with a pass/fail chip. The policy panel lists every threshold with its rationale.',actions:'Pick candidate and baseline runs, evaluate gates, expand gates to inspect checks, follow the link to the full Evidence Package, and edit gate thresholds in the policy editor (saved server-side; re-evaluate to apply).',dataFlow:'Gate inputs come from the published evaluation runs (metric cube aggregates, per-cohort recall, calibration diagnostics). The verdict + checks feed the Safety Evidence Package; threshold edits persist to the safety policy store and apply to subsequent evaluations.',},'safety-evidence': {subtitle:'The generated Safety Evidence Package for a candidate run: a structured, human-readable compliance document assembled from live evaluation data — clearly labeled as a demonstration artifact.',purpose:'Safety cases require documented evidence: what was evaluated, under which policy, with which results and known limitations. This page renders the generated evidence package (per ISO 21448 / UL 4600-style structure) so reviewers read one coherent document instead of a dozen dashboards.',reading:'The document is organized into sections — system description, evaluation scope, gate results, ODD coverage summary, calibration status, known limitations, sign-off placeholders. The prominent disclaimer matters: this is a synthetic demonstration package generated from demo data, not a real certification artifact.',actions:'Select the candidate run, read the rendered markdown, and download the underlying JSON for archival or external tooling.',dataFlow:'The package is assembled server-side from gate evaluations, coverage analysis and calibration results for the chosen run. The JSON download is the exact source of the rendered document.',},'safety-ssam': {subtitle:'Surrogate-safety conflict analysis for a simulated scenario: every near-miss scored with TTC / PET / DRAC / ΔS / CSI, plotted on a mini conflict map.',purpose:'Crashes are (thankfully) too rare to measure safety directly — surrogate measures score how close interactions came to conflict. This panel runs the SSAM-style analysis over a scenario\u2019s trajectories and ranks the conflicts it finds, so scenario risk is quantified, not guessed.',reading:'Aggregate tiles show total conflicts and the worst values (min TTC, min PET, max DRAC, aggregate CSI). Each conflict row carries chips for its measures — hover each chip for the definition (TTC = time-to-collision if paths continue; PET = gap between occupying the same space; DRAC = braking needed to avoid; CSI combines them into severity). The map plots conflict points at their location, colored by severity; the bars compare CSI across conflicts.',actions:'Choose scenario, random seed and reaction-delay assumption, run the analysis, inspect conflicts on the list and map.',dataFlow:'Trajectories are simulated deterministically from the scenario definition; conflicts and measures are computed by the safety backend. High-CSI scenario patterns are candidates for the Scenario DB and evaluation cohort design.',},'safety-calibration': {subtitle:'Camera–LiDAR extrinsic calibration validation: three scenario modes (clean / miscalibrated / perception failure), a residual scatter with brush-select, and a clear verdict badge.',purpose:'If the sensors disagree about where things are, every downstream label is suspect — and the failure can masquerade as a model problem. This panel validates cross-sensor geometric consistency and, critically, distinguishes systematic miscalibration (all residuals shifted the same way) from perception failures (a few objects wildly off).',reading:'The status badge is the verdict: CALIBRATED / MISCALIBRATED / PERCEPTION_FAILURE. Checks table shows each test (mean residual, residual direction consistency, outlier fraction) against thresholds. The scatter plots per-object residuals (camera-vs-LiDAR offset): a tight cloud at the origin = healthy; a shifted cloud = miscalibration; a tight cloud plus far outliers = perception failure. Drag on the chart to brush-select outlier objects and list them.',actions:'Pick a validation mode (clean baseline, planted rotation miscalibration with adjustable offset, planted perception failures with adjustable tamper fraction), run validation, brush the scatter to inspect object residuals.',dataFlow:'Object pair residuals are computed from synchronized camera and LiDAR detections in the synthetic scene bank. MISCALIBRATED verdicts should gate labeling runs upstream; the planted modes exist to prove the discriminator works.',},'safety-discrepancy': {subtitle:'Cross-source disagreement mining: where auto-labels, human labels and model predictions contradict each other, grouped by type and cohort.',purpose:'Disagreements between labeling sources are the cheapest quality signal that exists — no new ground truth required. Mining them reveals systematic auto-labeler blind spots, ambiguous classes and cohorts where human review is being wasted or missing.',reading:'Tiles count total mined discrepancies. The donut splits them by type (missing box, spurious box, class confusion, geometry drift…). The cohort table ranks cohorts by discrepancy rate — a high-rate cohort is where labeling quality is systematically weakest. Sample rows show concrete disagreements with both sides\u2019 values.',actions:'Run the miner, read the type mix and worst cohorts, drill into samples.',dataFlow:'The miner joins auto-label, human-review and model-prediction records for the same objects and emits typed discrepancies. High-discrepancy cohorts feed review-sampling plans and auto-labeler improvement work.',},'safety-scenarios': {subtitle:'The scenario database: every stored test scenario with severity / type / source filters, free-text search, rare-event import and filtered export.',purpose:'Scenario-based testing needs a governed library: what scenarios exist, where they came from (mined, synthetic, imported), how severe they are, and which subset a given evaluation should run. This browser is that library\u2019s front door.',reading:'Each row is a scenario with its type, severity chip, source and description. The count tile tracks the library size. Filters are conjunctive: severity × type × source × text query.',actions:'Filter and search scenarios, import mined rare events into the DB, export the current filtered set as a JSON bundle for external runners.',dataFlow:'Scenarios arrive from rare-event mining, SSAM conflict patterns and manual/synthetic authoring. Exported bundles feed simulation runners; scenario selections define evaluation cohorts.',},'safety-search': {subtitle:'Concept-level scenario search: type "pedestrian at night in rain" and get ranked scenario/container matches with per-stage scoring explanations and an honest provider badge.',purpose:'Finding evaluation data by concept — not by exact tag — is how engineers actually think. This search combines a symbolic dimension filter with a reasoning-based scorer and shows its work, so a match is never an unexplained black-box similarity number.',reading:'The stage breakdown shows the pipeline: symbolic filter (hard dimension constraints parsed from your query) → reasoning scorer (concept relevance) → hybrid blend. Each result card lists matched dimensions as chips, the blended score, and a per-stage explanation of why it ranked where it did. The provider badge states which scoring backend ran (LLM vs deterministic fallback) — results are comparable but the badge keeps provenance honest.',actions:'Enter a concept query, choose the target corpus (containers or scenarios), toggle LLM scoring, and inspect result explanations.',dataFlow:'Queries run against scenario/container metadata from the published runs and scenario DB. Selected results deep-link into their browsers; searches are read-only.',},seqeval: {subtitle:'Anytime-valid sequential regression testing: the run\u2019s verdict, the per-node decision tables, and the evidence chart showing exactly when — and why — the test stopped.',purpose:'Fixed-n evaluation wastes budget on obvious cases and under-samples subtle ones. Sequential testing accumulates evidence sample-by-sample and stops the moment a decision is statistically safe, with always-valid error control (no peeking penalty). This dashboard makes that decision process visible instead of burying it in a p-value.',reading:'The verdict banner states the decision (PROMOTE / BLOCK / INSUFFICIENT_EVIDENCE), which gate fired, and the plain-language reason. THE key visual is the sequential-evidence chart: each line is a node\u2019s log e-value trajectory vs samples used; crossing the upper boundary = evidence of regression (block), the lower = evidence of safety (pass); the vertical marker shows where the run stopped. Decision tables list every tested node with its recall delta + confidence sequence, n used vs effective n, decision chip and a badge on safety-primary nodes (they use stricter thresholds). The regression heatmap locates damage by class × condition. The budget funnel shows planned vs actually-used samples vs full population — the savings are the point.',actions:'Pick a run, read the verdict and its evidence, hover trajectories for per-step values, and launch new sequential runs (choose a preset planted effect or configure a custom one) from the launcher.',dataFlow:'Runs are configured and executed by the seqeval backend over paired baseline/candidate evaluations of the synthetic population. Verdicts are designed to gate promotion exactly like the Release Gates regression gate; attribution feeds the regression heatmap.',},bevfusion: {subtitle:'Camera-only vs camera+LiDAR BEV-fusion engine comparison — headline deltas, per-cohort explanations, and an interactive top-down canvas replaying one scene\u2019s every detection, fusion and track.',purpose:'Promoting a new perception engine needs both the statistics (is fused better, where, by how much) and the mechanism (WHY is it better). The comparison card gives the verdict; the BEV canvas shows the physics — depth-uncertain camera ellipses, tight LiDAR crosses, and the fused tracker carrying identity through occlusions.',reading:'The comparison card: green/red chips are candidate-minus-baseline deltas per metric (direction-aware — position error going down is green), the badge is the promotion policy verdict, and blockers list any gate the candidate failed. Cohort bars pair baseline (gray) vs candidate (colored), sorted by delta; hover for the causal explanation. On the canvas: white outlines = ground truth (dashed amber = camera-occluded), orange dots with ellipses = camera detections (the ellipse stretches along the viewing ray — monocular depth uncertainty), teal crosses = LiDAR, filled boxes = fused tracks (dashed purple = masklet-propagated through a detection gap), red outlines = what camera-only would have produced.',actions:'Run a comparison (sequences / frames / seed), toggle canvas layers, scrub or play frames, hover any object for details, click a fused box to follow its track across frames — watch the dashed purple propagation carry it through occlusion.',dataFlow:'Scenes are generated deterministically (seeded), both engines label every frame, and the evaluator scores them against ground truth. The canvas replays the same seeds through the same code path server-side, so what you see is exactly what was scored. Comparison reports persist under runs/bevfusion/.',},'scenario-composer': {subtitle:'WYSIWYG scenario editor: drag actors from a palette onto a top-down canvas, shape their trajectories, set the environment, and send the composed scene through evaluation.',purpose:'Authoring test scenarios by editing JSON is slow and error-prone. Here you place pedestrians, vehicles, cones and construction zones directly on a bird\u2019s-eye canvas, drag them (and their trajectory waypoints) until the scene is right, and the machine-readable recipe writes itself.',reading:'The canvas is ego-centric: the blue triangle is the ego vehicle, range rings mark distance. Each actor shows its footprint and, when selected, its trajectory waypoints. The environment toggles (day/night, clear/rain/fog) re-render the canvas look so lighting/weather context is visible, not abstract. The recipe panel on the right is the live JSON — it updates with every drag.',actions:'Drag actors from the palette onto the canvas; drag to reposition; select an actor to edit its properties (class, speed, heading) in the inspector and drag its waypoints; toggle environment; then "Run through evaluation" to send the recipe to the scene-consuming backend. Save/load compositions locally.',dataFlow:'Compositions persist in your browser (and via the studio-ux backend when available). The run action posts the recipe to the best available scene-consuming API — the capabilities probe hides the button when none is reachable.',},'pipeline-builder': {subtitle:'Direct-manipulation node-graph editor over the platform\u2019s pipeline architecture: drag stages, re-wire edges, inspect configs — a clearly-labeled what-if draft, not a deployment tool.',purpose:'The Pipeline Architecture page shows the pipeline as-built; this builder lets you manipulate a DRAFT copy of that graph — move stages, add or remove connections, toggle stages on/off — and read a live "what will run" summary of your draft. It is an explorer and design surface: the real pipeline is read-only and is never modified.',reading:'Nodes are pipeline stages (colored by role; live status from the real pipeline where available). Edges are data flows — drag from a node\u2019s output port to another node\u2019s input to connect. The summary panel recomputes the execution order (topological), flags orphaned stages and cycles, and diffs your draft against the as-built pipeline. The DRAFT banner is honest: nothing you do here executes.',actions:'Drag nodes to rearrange; draw edges port-to-port; click a node for its config in the inspector (enable/disable, notes); delete edges; reset to the as-built graph; export the draft as JSON.',dataFlow:'The initial graph loads read-only from the pipeline architecture API. Drafts live in your browser (and the studio-ux store when available); export produces a JSON description for humans or future tooling.',},'my-dashboard': {subtitle:'Your own composed dashboard: drag live widgets from every corner of the platform onto a grid, arrange and resize them, and the layout persists.',purpose:'Every role watches a different mix of signals. Instead of one fixed overview, this page lets you compose your own: pick widgets (seqeval verdict, ODD coverage mini-map, engine comparison, review queue, gate status…), place and size them on a grid, and keep that layout across sessions.',reading:'In view mode widgets are live — each one fetches its real data source and renders the same numbers as its home page, with a link to jump there. In edit mode, widgets get drag handles and resize grips; the palette lists available widgets grouped by source page.',actions:'Toggle edit mode, add widgets from the palette, drag to reposition, resize with the corner grip, remove with the ×, and reset to the starter layout. Layouts save automatically (locally, plus server-side when the studio-ux backend is up).',dataFlow:'Widget data comes live from the same APIs as the source pages (read-only). Layout state persists to localStorage and mirrors to /api/studio-ux/layout when available, so it can follow you across browsers.',},retro: {subtitle:7 unmodified linesdataFlow:'Fixtures live in sensorflow/retro/fixtures; analyses and audit trails persist under runs/retro/. Metric math reuses the SSAM safety extensions; distribution stats delegate to the mega-eval engine; the safety-case corpus is indexed at startup (chromadb or deterministic fallback).',},'launch-readiness': {subtitle:'Agentic launch readiness & misclassification triage: a five-layer pipeline (detection → evidence → analysis → decision → flywheel) where AI agents only recommend and a deterministic, versioned policy engine plus recorded human review own every launch decision.',purpose:'A pedestrian misclassified as a construction cone at "~0.01%" is not actionable until the denominator, confidence interval, significance, safety criticality, concentration and novelty are established. This page runs that triage end-to-end and shows exactly which claims are OBSERVED measurements versus AI hypotheses versus missing evidence.',reading:'The failure queue lists detected patterns with severity (S0–S5) and policy-outcome chips. Inside an investigation: the Evidence Graph colors each node by status (OBSERVED / DERIVED / HYPOTHESIS / UNAVAILABLE); the statistical panel shows Wilson CIs, exact-binomial significance and the seqeval anytime-valid decision with small-sample flags; the safety chain marks links without replay evidence as UNCERTAIN; the concentration heatmap colors strata by relative risk. Every panel is badged AI ANALYSIS (ADVISORY) or DETERMINISTIC. The decision tab shows the four-way policy outcome, the matrix row that fired, and option cards where safety-infeasible options are excluded no matter how cheap.',actions:'Scan for failures, run the seeded pedestrian→cone worked example, step the five pipeline stages, record human-review decisions (the only path to validation), export the leadership scorecard as JSON, and evaluate candidates against the flywheel-generated suites.',dataFlow:'Detection scans a seeded synthetic campaign (bevfusion scenes + a paired rate population). Statistics delegate to seqeval; safety replays reuse the SSAM extensions; Option C checks use the ODD taxonomy. Validated failures feed evaluation suites (contamination-guarded) under runs/agentic/, and every action lands in a hash-chained append-only audit log.',},legacy: {subtitle:
18 unmodified lines19202122232425262714 unmodified lines42434445464748495018 unmodified lines| 'rca'| 'raremine'| 'hillclimb'| 'retro'| 'vitis'| 'ssam'| 'legacy';export const ALL_PAGE_IDS: PageId[] = [14 unmodified lines'rca','raremine','hillclimb','retro','vitis','ssam','legacy',];18 unmodified lines192021222324252627282930313233343536373839404114 unmodified lines565758596061626364656667686970717273747576777818 unmodified lines| 'rca'| 'raremine'| 'hillclimb'| 'vitis'| 'ssam'| 'safety-odd'| 'safety-gates'| 'safety-evidence'| 'safety-ssam'| 'safety-calibration'| 'safety-discrepancy'| 'safety-scenarios'| 'safety-search'| 'seqeval'| 'bevfusion'| 'scenario-composer'| 'pipeline-builder'| 'my-dashboard'| 'retro'| 'launch-readiness'| 'legacy';export const ALL_PAGE_IDS: PageId[] = [14 unmodified lines'rca','raremine','hillclimb','vitis','ssam','safety-odd','safety-gates','safety-evidence','safety-ssam','safety-calibration','safety-discrepancy','safety-scenarios','safety-search','seqeval','bevfusion','scenario-composer','pipeline-builder','my-dashboard','retro','launch-readiness','legacy',];
1234567891011121314151617181920import React from 'react';import { createRoot } from 'react-dom/client';import CssBaseline from '@mui/material/CssBaseline';import { ThemeProvider, createTheme } from '@mui/material/styles';import App from './App';import './styles/globals.css';const theme = createTheme({palette: {mode: 'dark',background: { default: '#101418', paper: '#161b21' },primary: { main: '#4fc3f7' },},typography: {fontFamily: "'Inter', 'Helvetica Neue', Arial, sans-serif",},});const container = document.getElementById('root');if (!container) throw new Error('Root element missing');123456789101112131415import React from 'react';import { createRoot } from 'react-dom/client';import CssBaseline from '@mui/material/CssBaseline';import { ThemeProvider } from '@mui/material/styles';import App from './App';import './styles/globals.css';// Shared design tokens + theme factory (src/theme.ts): same palette values as// before, plus semantic tokens, motion durations, skeleton defaults and// keyboard-focus visibility.import { buildTheme } from './theme';const theme = buildTheme();const container = document.getElementById('root');if (!container) throw new Error('Root element missing');
39 unmodified lines4041424344454647484950235 unmodified lines2862872882892902916 unmodified lines29829930030130230339 unmodified linesimport ReviewTab from '../components/megaeval/ReviewTab';import ShiftTab from '../components/megaeval/ShiftTab';import LineageCard from '../components/megaeval/LineageCard';const ACTIVE_STATUSES: RunStatus[] = ['created', 'queued', 'running', 'reducing', 'materializing'];type TabId =| 'quality'| 'cohorts'| 'containers'| 'investigation'235 unmodified lines}}><Tab label="Quality" value="quality" title="Per-class quality, error distribution, quality funnel, run trend and sketch distributions" /><Tab label="Cohorts" value="cohorts" title="Drill the population by dimension (class, weather, lighting…) and run Why? decompositions" /><Tab label="Containers" value="containers" title="Per-scene quality table with risk sort presets; drill into the forensic object table" /><Tab label="Investigation" value="investigation" title="Multi-criteria search over the error index: worst containers and top examples" />6 unmodified lines{tab === 'quality' ? (<QualityTab runId={selectedRun.run_id} runs={runs} refreshKey={publishTick} />) : null}{tab === 'cohorts' ? <CohortTab runId={selectedRun.run_id} refreshKey={publishTick} /> : null}{tab === 'containers' ? (<ContainersTab39 unmodified lines40414243444546474849505152235 unmodified lines2882892902912922932946 unmodified lines30130230330430530630739 unmodified linesimport ReviewTab from '../components/megaeval/ReviewTab';import ShiftTab from '../components/megaeval/ShiftTab';import LineageCard from '../components/megaeval/LineageCard';import VisualQueryTab from '../components/megaeval/VisualQueryTab';const ACTIVE_STATUSES: RunStatus[] = ['created', 'queued', 'running', 'reducing', 'materializing'];type TabId =| 'quality'| 'visual-query'| 'cohorts'| 'containers'| 'investigation'235 unmodified lines}}><Tab label="Quality" value="quality" title="Per-class quality, error distribution, quality funnel, run trend and sketch distributions" /><Tab label="Query Builder" value="visual-query" title="Build metric-cube queries visually: drag dimensions into group-by / filter wells with a live result preview" /><Tab label="Cohorts" value="cohorts" title="Drill the population by dimension (class, weather, lighting…) and run Why? decompositions" /><Tab label="Containers" value="containers" title="Per-scene quality table with risk sort presets; drill into the forensic object table" /><Tab label="Investigation" value="investigation" title="Multi-criteria search over the error index: worst containers and top examples" />6 unmodified lines{tab === 'quality' ? (<QualityTab runId={selectedRun.run_id} runs={runs} refreshKey={publishTick} />) : null}{tab === 'visual-query' ? <VisualQueryTab runId={selectedRun.run_id} /> : null}{tab === 'cohorts' ? <CohortTab runId={selectedRun.run_id} refreshKey={publishTick} /> : null}{tab === 'containers' ? (<ContainersTab
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349/** Launch Readiness — agentic misclassification triage. * * Failure queue → five-layer investigation (evidence graph, agent analyses, * statistics, safety chain, concentration) → deterministic launch decision + * human review → scorecard → learning flywheel. */import { useCallback, useEffect, useMemo, useState } from 'react';import Alert from '@mui/material/Alert';import Box from '@mui/material/Box';import Button from '@mui/material/Button';import Chip from '@mui/material/Chip';import CircularProgress from '@mui/material/CircularProgress';import MenuItem from '@mui/material/MenuItem';import Paper from '@mui/material/Paper';import Tab from '@mui/material/Tab';import Table from '@mui/material/Table';import TableBody from '@mui/material/TableBody';import TableCell from '@mui/material/TableCell';import TableHead from '@mui/material/TableHead';import TableRow from '@mui/material/TableRow';import Tabs from '@mui/material/Tabs';import TextField from '@mui/material/TextField';import Typography from '@mui/material/Typography';import { PlayCircle, Radar } from 'lucide-react';import type { AuditRecord, EvaluationSuite, EvidenceGraph, FailureEvent, HumanReviewDecision, PipelineState, Scorecard, Stage,} from '../../types/agentic';import { STAGES } from '../../types/agentic';import { detectFailures, getAudit, getEvidence, getFailureQueue, getHumanReviews, getScorecard, getState, getWorkedExample, listSuites, runStage,} from '../../services/agentic';import AgentOutputsPanel from '../../components/agentic/AgentOutputsPanel';import ConcentrationHeatmap from '../../components/agentic/ConcentrationHeatmap';import DecisionPanel from '../../components/agentic/DecisionPanel';import EvidenceGraphPanel from '../../components/agentic/EvidenceGraphPanel';import FlywheelPanel from '../../components/agentic/FlywheelPanel';import SafetyChainPanel from '../../components/agentic/SafetyChainPanel';import ScorecardView from '../../components/agentic/ScorecardView';import StatisticalPanel from '../../components/agentic/StatisticalPanel';import { OutcomeChip, SeverityChip } from '../../components/agentic/common';
const STAGE_LABELS: Record<Stage, string> = { FAILURE_DETECTION: '1 · Detection', EVIDENCE_AGGREGATION: '2 · Evidence', FAILURE_ANALYSIS: '3 · Analysis', LAUNCH_DECISION: '4 · Decision', LEARNING_FLYWHEEL: '5 · Flywheel',};
const STAGE_STATUS_COLORS: Record<string, string> = { pending: '#37474f', running: '#0d47a1', complete: '#1b5e20', failed: '#b71c1c', blocked: '#4e342e',};
export default function LaunchReadinessPage() { const [topTab, setTopTab] = useState<'queue' | 'flywheel'>('queue'); const [failures, setFailures] = useState<FailureEvent[]>([]); const [suites, setSuites] = useState<EvaluationSuite[]>([]); const [selectedId, setSelectedId] = useState<string | null>(null); const [state, setState] = useState<PipelineState | null>(null); const [graph, setGraph] = useState<EvidenceGraph | null>(null); const [decisions, setDecisions] = useState<HumanReviewDecision[]>([]); const [audit, setAudit] = useState<AuditRecord[]>([]); const [auditValid, setAuditValid] = useState<boolean | null>(null); const [scorecard, setScorecard] = useState<Scorecard | null>(null); const [detailTab, setDetailTab] = useState<'investigation' | 'decision' | 'scorecard'>('investigation'); const [busy, setBusy] = useState<string | null>(null); const [error, setError] = useState<string | null>(null); const [filterSeverity, setFilterSeverity] = useState('all'); const [filterOutcome, setFilterOutcome] = useState('all'); const [filterStage, setFilterStage] = useState('all');
const refreshQueue = useCallback(async () => { const res = await getFailureQueue(); setFailures(res.failures); }, []);
const refreshSuites = useCallback(async () => { const res = await listSuites(); setSuites(res.suites); }, []);
const refreshSelected = useCallback(async (id: string) => { const st = await getState(id).then((r) => r.state).catch(() => null); setState(st); setGraph(await getEvidence(id).then((r) => r.graph).catch(() => null)); setDecisions(await getHumanReviews(id).then((r) => r.decisions).catch(() => [])); const auditRes = await getAudit(id).catch(() => null); setAudit(auditRes?.records ?? []); setAuditValid(auditRes?.chain.valid ?? null); if (st?.scorecard_id) { setScorecard(await getScorecard(st.scorecard_id).then((r) => r.scorecard).catch(() => null)); } else { setScorecard(null); } }, []);
useEffect(() => { refreshQueue().catch((e) => setError((e as Error).message)); refreshSuites().catch(() => undefined); }, [refreshQueue, refreshSuites]);
useEffect(() => { if (selectedId) refreshSelected(selectedId).catch((e) => setError((e as Error).message)); }, [selectedId, refreshSelected]);
const withBusy = async (label: string, fn: () => Promise<void>) => { setBusy(label); setError(null); try { await fn(); } catch (e) { setError((e as Error).message); } finally { setBusy(null); } };
const scan = () => withBusy('scan', async () => { await detectFailures(); await refreshQueue(); });
const workedExample = () => withBusy('worked-example', async () => { const res = await getWorkedExample(); await refreshQueue(); await refreshSuites(); setSelectedId(res.walkthrough.failure_id); setDetailTab('decision'); });
const advance = (stage?: Stage) => withBusy(stage ?? 'next', async () => { if (!selectedId) return; await runStage(selectedId, stage); await refreshSelected(selectedId); await refreshQueue(); await refreshSuites(); });
const filtered = useMemo( () => failures.filter((f) => { if (filterSeverity !== 'all' && f.severity !== filterSeverity) return false; if (filterOutcome !== 'all' && f.policy_outcome !== filterOutcome) return false; if (filterStage !== 'all' && f.status !== filterStage) return false; return true; }), [failures, filterSeverity, filterOutcome, filterStage] );
const selected = failures.find((f) => f.failure_id === selectedId) ?? null; const agents = state ? Object.values(state.agent_results) : []; const safety = state?.agent_results['safety_impact']; const nextStage = state?.stages.find((s) => s.status === 'pending')?.stage;
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}> {/* header actions */} <Box sx={{ display: 'flex', gap: 1, alignItems: 'center', flexWrap: 'wrap' }}> <Tabs value={topTab} onChange={(_, v) => setTopTab(v)} sx={{ minHeight: 34, flex: 1 }}> <Tab value="queue" label="Failure Queue & Investigation" sx={{ minHeight: 34, py: 0 }} /> <Tab value="flywheel" label={`Evaluation Flywheel (${suites.length})`} sx={{ minHeight: 34, py: 0 }} /> </Tabs> <Button size="small" variant="outlined" startIcon={<Radar size={15} />} disabled={busy !== null} onClick={scan}> Scan for failures </Button> <Button size="small" variant="contained" startIcon={<PlayCircle size={15} />} disabled={busy !== null} onClick={workedExample}> Run the pedestrian→cone walkthrough </Button> {busy ? <CircularProgress size={18} /> : null} </Box> {error ? ( <Alert severity="error" variant="outlined" onClose={() => setError(null)}> {error} </Alert> ) : null}
{topTab === 'flywheel' ? ( <FlywheelPanel suites={suites} /> ) : ( <> {/* filters + queue */} <Paper variant="outlined" sx={{ p: 1.5, bgcolor: '#161b22' }}> <Box sx={{ display: 'flex', gap: 1, mb: 1, alignItems: 'center' }}> <Typography variant="subtitle2" sx={{ fontWeight: 800, flex: 1 }}> Detected Failure Events ({filtered.length}) </Typography> <TextField size="small" select label="Severity" value={filterSeverity} onChange={(e) => setFilterSeverity(e.target.value)} sx={{ width: 120 }}> <MenuItem value="all">all</MenuItem> {['S0', 'S1', 'S2', 'S3', 'S4', 'S5'].map((s) => ( <MenuItem key={s} value={s}>{s}</MenuItem> ))} </TextField> <TextField size="small" select label="Policy outcome" value={filterOutcome} onChange={(e) => setFilterOutcome(e.target.value)} sx={{ width: 210 }}> <MenuItem value="all">all</MenuItem> {['AUTOMATIC_STOP_SHIP', 'LAUNCH_REVIEW_REQUIRED', 'CONTINUE_INVESTIGATION', 'NO_LAUNCH_IMPACT', 'INDETERMINATE'].map((o) => ( <MenuItem key={o} value={o}>{o}</MenuItem> ))} </TextField> <TextField size="small" select label="Status" value={filterStage} onChange={(e) => setFilterStage(e.target.value)} sx={{ width: 150 }}> <MenuItem value="all">all</MenuItem> {['detected', 'investigating', 'decided', 'closed'].map((s) => ( <MenuItem key={s} value={s}>{s}</MenuItem> ))} </TextField> </Box> {failures.length === 0 ? ( <Typography variant="caption" sx={{ color: '#8a949e' }}> No failures detected yet — run a scan or launch the worked example. </Typography> ) : ( <Table size="small"> <TableHead> <TableRow> {['Failure', 'Kind', 'Candidate rate', 'Severity', 'Policy outcome', 'Status', 'Validated'].map((h) => ( <TableCell key={h} sx={{ fontSize: 11, fontWeight: 800, color: '#8a949e' }}>{h}</TableCell> ))} </TableRow> </TableHead> <TableBody> {filtered.map((f) => ( <TableRow key={f.failure_id} hover selected={f.failure_id === selectedId} onClick={() => setSelectedId(f.failure_id)} sx={{ cursor: 'pointer' }} > <TableCell sx={{ fontSize: 12 }}>{f.title}</TableCell> <TableCell sx={{ fontSize: 11.5, fontFamily: 'monospace' }}>{f.kind}</TableCell> <TableCell sx={{ fontSize: 11.5, fontFamily: 'monospace' }}> {f.detection_basis.candidate_events}/{f.detection_basis.denominator.toLocaleString()} ({(f.detection_basis.candidate_rate * 100).toFixed(4)}%) </TableCell> <TableCell><SeverityChip severity={f.severity} /></TableCell> <TableCell><OutcomeChip outcome={f.policy_outcome} /></TableCell> <TableCell sx={{ fontSize: 11.5 }}>{f.status}</TableCell> <TableCell sx={{ fontSize: 11.5 }}>{f.validated ? '✓ human-validated' : '—'}</TableCell> </TableRow> ))} </TableBody> </Table> )} </Paper>
{/* investigation */} {selected && state ? ( <Paper variant="outlined" sx={{ p: 1.5, bgcolor: '#161b22' }}> <Typography variant="subtitle2" sx={{ fontWeight: 800, mb: 1 }}> {selected.title}{' '} <span style={{ color: '#5c6770', fontFamily: 'monospace', fontSize: 11 }}>{selected.failure_id}</span> </Typography>
{/* five-layer stage progress */} <Box sx={{ display: 'flex', gap: 0.5, alignItems: 'center', flexWrap: 'wrap', mb: 1.5 }}> {STAGES.map((s, i) => { const rec = state.stages.find((r) => r.stage === s); return ( <Box key={s} sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}> <Chip size="small" label={`${STAGE_LABELS[s]} · ${rec?.status ?? '?'}`} title={rec?.detail} sx={{ height: 22, fontSize: 10.5, fontWeight: 700, bgcolor: STAGE_STATUS_COLORS[rec?.status ?? 'pending'], color: '#fff', }} /> {i < STAGES.length - 1 ? <Typography sx={{ color: '#5c6770' }}>→</Typography> : null} </Box> ); })} {nextStage ? ( <Button size="small" variant="outlined" disabled={busy !== null} onClick={() => advance(nextStage)} sx={{ ml: 1 }}> Run {STAGE_LABELS[nextStage]} </Button> ) : null} </Box>
<Tabs value={detailTab} onChange={(_, v) => setDetailTab(v)} sx={{ minHeight: 34, mb: 1.5 }}> <Tab value="investigation" label="Investigation" sx={{ minHeight: 34, py: 0 }} /> <Tab value="decision" label="Launch Decision" sx={{ minHeight: 34, py: 0 }} disabled={!state.policy_evaluation} /> <Tab value="scorecard" label="Scorecard" sx={{ minHeight: 34, py: 0 }} disabled={!scorecard} /> </Tabs>
{detailTab === 'investigation' ? ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}> {graph ? ( <EvidenceGraphPanel graph={graph} /> ) : ( <Alert severity="info" variant="outlined"> Evidence graph not built yet — run the EVIDENCE AGGREGATION stage. </Alert> )} {state.statistical ? <StatisticalPanel stat={state.statistical} /> : null} {safety ? <SafetyChainPanel safety={safety} /> : null} {state.concentration ? <ConcentrationHeatmap conc={state.concentration} /> : null} {agents.length > 0 ? <AgentOutputsPanel agents={agents} /> : null} </Box> ) : null}
{detailTab === 'decision' && state.policy_evaluation ? ( <DecisionPanel failureId={selected.failure_id} evaluation={state.policy_evaluation} decisions={decisions} audit={audit} auditValid={auditValid} onReviewed={() => refreshSelected(selected.failure_id).then(refreshQueue)} /> ) : null}
{detailTab === 'scorecard' && scorecard ? <ScorecardView card={scorecard} /> : null} </Paper> ) : ( <Alert severity="info" variant="outlined"> Select a failure from the queue to open its five-layer investigation, or run the worked example for the full pedestrian→cone walkthrough. </Alert> )} </> )} </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413/** * Perception Engines (BEV fusion) — engine comparison card (headline delta * chips, PROMOTE badge, blockers), per-cohort paired delta bars with * explanation tooltips, run form, and the interactive top-down BEV canvas of * one frame with a frame scrubber and track following. */import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import Alert from '@mui/material/Alert';import Box from '@mui/material/Box';import Button from '@mui/material/Button';import Chip from '@mui/material/Chip';import IconButton from '@mui/material/IconButton';import MenuItem from '@mui/material/MenuItem';import Slider from '@mui/material/Slider';import TextField from '@mui/material/TextField';import Typography from '@mui/material/Typography';import { Pause, Play, PlayCircle } from 'lucide-react';import { getBevReplay, getBevReport, runBevComparison, type BevReplayResponse, type BevReport,} from '../../services/bevfusion';import BevFrameCanvas, { CanvasLegend, type HoverInfo, type LayerId } from '../../components/engines/BevFrameCanvas';import { DeltaBars, type DeltaBarRow } from '../../components/visual/charts';import { ChartSkeleton, IllustratedEmpty, PanelSkeleton, TileSkeleton } from '../../components/visual/Feedback';import { ErrorNote, SectionCard, fmtPct } from '../../components/labeleval/shared';import { InfoDot } from '../../components/help/InfoTip';import { deltaColor, tokens, verdictColor } from '../../theme';
const LOWER_IS_BETTER = new Set(['position_error_m', 'id_switch_rate', 'fragmentation_rate']);
const METRIC_HELP: Record<string, string> = { precision: 'Fraction of produced labels that match a GT object.', recall: 'Fraction of GT objects that got a label — the headline miss rate.', f1: 'Harmonic mean of precision and recall.', mean_iou: 'Mean BEV overlap of matched boxes — geometric quality.', position_error_m: 'Mean center distance of matched boxes (meters, lower is better).', class_accuracy: 'Fraction of matched boxes with the correct class.', safety_recall: 'Recall over pedestrians/cyclists/motorcycles only.', id_switch_rate: 'Track identity switches per GT track (lower is better).', fragmentation_rate: 'How often GT tracks break into pieces (lower is better).', idf1: 'Identity-F1: how consistently the same object keeps the same track id.',};
function DeltaChip({ metric, baseline, candidate, delta, improved }: { metric: string; baseline: number; candidate: number; delta: number; improved: boolean }) { const color = improved ? tokens.color.success : tokens.color.danger; const pct = !LOWER_IS_BETTER.has(metric) && Math.abs(baseline) <= 1; const fmt = (v: number) => (pct ? fmtPct(v) : v.toFixed(3)); return ( <Box title={METRIC_HELP[metric] ?? metric} sx={{ px: 1.25, py: 0.75, borderRadius: 1, border: `1px solid ${color}55`, bgcolor: `${color}12`, minWidth: 118, cursor: 'help', transition: `transform ${tokens.motion.fast}`, '&:hover': { transform: 'translateY(-2px)' }, }} > <Typography variant="caption" sx={{ color: tokens.color.neutral, display: 'block', fontSize: 10.5 }}> {metric.replace(/_/g, ' ')} </Typography> <Typography variant="body2" sx={{ fontFamily: 'monospace', fontWeight: 800, color }}> {delta >= 0 ? '+' : ''} {fmt(delta)} </Typography> <Typography variant="caption" sx={{ color: tokens.color.textFaint, fontFamily: 'monospace', fontSize: 10 }}> {fmt(baseline)} → {fmt(candidate)} </Typography> </Box> );}
export default function BevFusionPage() { const [report, setReport] = useState<BevReport | null>(null); const [loading, setLoading] = useState(true); const [running, setRunning] = useState(false); const [error, setError] = useState<string | null>(null);
// run form const [nSeq, setNSeq] = useState(6); const [framesPerSeq, setFramesPerSeq] = useState(24); const [seed, setSeed] = useState(7);
// canvas state const [replay, setReplay] = useState<BevReplayResponse | null>(null); const [replayError, setReplayError] = useState<string | null>(null); const [sequence, setSequence] = useState(0); const [frameIdx, setFrameIdx] = useState(0); const [playing, setPlaying] = useState(false); const [layers, setLayers] = useState<Record<LayerId, boolean>>({ gt: true, camera: true, lidar: true, fused: true, masklet: true, baseline: false }); const [selectedTrack, setSelectedTrack] = useState<number | string | null>(null); const [hover, setHover] = useState<HoverInfo | null>(null); const playRef = useRef<ReturnType<typeof setInterval> | null>(null);
useEffect(() => { getBevReport() .then(setReport) .catch(() => setReport(null)) .finally(() => setLoading(false)); }, []);
// replay follows the report params + chosen sequence useEffect(() => { if (!report) return; let cancelled = false; setReplay(null); setReplayError(null); setSelectedTrack(null); setFrameIdx(0); getBevReplay(report.params, sequence) .then((r) => { if (!cancelled) setReplay(r); }) .catch((e) => { if (!cancelled) setReplayError(e instanceof Error ? e.message : String(e)); }); return () => { cancelled = true; }; }, [report, sequence]);
// playback useEffect(() => { if (playRef.current) clearInterval(playRef.current); if (playing && replay) { playRef.current = setInterval(() => { setFrameIdx((i) => (i + 1) % replay.frames.length); }, 220); } return () => { if (playRef.current) clearInterval(playRef.current); }; }, [playing, replay]);
const run = useCallback(() => { setRunning(true); setError(null); runBevComparison({ n_sequences: nSeq, frames_per_sequence: framesPerSeq, seed }) .then((r) => { setReport(r); setSequence(0); }) .catch((e) => setError(e instanceof Error ? e.message : String(e))) .finally(() => setRunning(false)); }, [nSeq, framesPerSeq, seed]);
const cohortRows: DeltaBarRow[] = useMemo( () => (report?.per_cohort ?? []).map((c) => ({ label: c.cohort, baseline: c.recall_baseline, candidate: c.recall_candidate, delta: c.recall_delta, n: c.n_gt, improved: c.recall_delta >= 0, tooltip: ( <Box> <Typography variant="caption" sx={{ fontWeight: 700, color: tokens.color.info, display: 'block' }}> Why the {c.cohort} cohort moved </Typography> <Typography variant="caption" sx={{ display: 'block', color: '#e6e9ec' }}>{c.explanation}</Typography> <Typography variant="caption" sx={{ display: 'block', color: tokens.color.textDim, mt: 0.5 }}> recall {fmtPct(c.recall_baseline)} → {fmtPct(c.recall_candidate)} · position error{' '} {c.position_error_baseline_m.toFixed(2)} → {c.position_error_candidate_m.toFixed(2)} m · IoU{' '} {c.mean_iou_baseline.toFixed(2)} → {c.mean_iou_candidate.toFixed(2)} </Typography> </Box> ), })), [report] );
const classRows: DeltaBarRow[] = useMemo( () => (report?.per_class ?? []).map((c) => ({ label: c.class, baseline: c.recall_baseline, candidate: c.recall_candidate, delta: c.recall_delta, n: c.n_gt, improved: c.recall_delta >= 0, })), [report] );
const frame = replay?.frames[Math.min(frameIdx, (replay?.frames.length ?? 1) - 1)] ?? null;
const trail = useMemo(() => { if (!replay || selectedTrack === null) return []; const pts: Array<{ x: number; y: number }> = []; for (let i = 0; i <= frameIdx && i < replay.frames.length; i += 1) { const b = replay.frames[i].fused.find((f) => f.track_id === selectedTrack); if (b) pts.push({ x: b.bbox_3d[0], y: b.bbox_3d[1] }); } return pts; }, [replay, selectedTrack, frameIdx]);
const recoColor = verdictColor(report?.recommendation);
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> {error ? <ErrorNote error={error} /> : null} {loading ? <TileSkeleton n={5} /> : null}
{!loading && !report ? ( <SectionCard title="Engine comparison"> <IllustratedEmpty art="canvas" title="No BEV-fusion comparison yet" message="Run one: deterministic multi-sensor scenes are generated, both engines label every frame (camera-only baseline vs camera+LiDAR BEV fusion with masklet tracking), and the evaluation compares them per cohort." action={ <Button variant="contained" startIcon={<PlayCircle size={16} />} disabled={running} onClick={run}> {running ? 'Running…' : 'Run comparison'} </Button> } /> </SectionCard> ) : null}
{report ? ( <> <SectionCard title={ <Box component="span" sx={{ display: 'inline-flex', alignItems: 'center', gap: 1 }}> {report.engines.baseline} <span style={{ color: tokens.color.neutral }}>vs</span> {report.engines.candidate} <Chip size="small" label={report.recommendation.replace(/_/g, ' ')} sx={{ fontWeight: 900, bgcolor: `${recoColor}22`, color: recoColor, border: `2px solid ${recoColor}` }} /> </Box> } help="Headline metric deltas, candidate minus baseline (green = improved, red = regressed — direction-aware for error metrics). The promotion recommendation applies the policy: bounded drops on recall/precision/safety-recall and per-cohort recall. Hover a chip for the metric definition." action={ <Typography variant="caption" sx={{ color: tokens.color.neutral, fontFamily: 'monospace' }}> {report.run_id} · {report.scale.frames} frames · {report.scale.gt_boxes.toLocaleString()} GT boxes </Typography> } > <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}> {report.headline_deltas.map((d) => ( <DeltaChip key={d.metric} {...d} /> ))} </Box> {report.blockers.length ? ( <Alert severity="error" variant="outlined" sx={{ mt: 1.5 }}> <strong>Blockers:</strong> {report.blockers.join(' · ')} </Alert> ) : ( <Typography variant="caption" sx={{ color: tokens.color.success, display: 'block', mt: 1.5 }}> No policy blockers — every gated metric is within tolerance. </Typography> )} <Typography variant="caption" sx={{ color: tokens.color.textFaint, display: 'block', mt: 0.5 }}> {report.notes} </Typography> </SectionCard>
<Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}> <SectionCard title="Per-cohort recall — where the fusion wins and why" sx={{ flex: '3 1 460px' }} help="Paired bars: gray = camera baseline, colored = fused candidate, sorted by delta. Hover a row for the causal explanation — each cohort's gain traces to a specific sensor-physics mechanism (occlusion, darkness, range, rain), not a tuning constant." > <DeltaBars rows={cohortRows} max={1} fmt={(v) => `${(v * 100).toFixed(1)}pp`} /> </SectionCard> <SectionCard title="Per-class recall" sx={{ flex: '2 1 340px' }} help="Same paired-delta view per object class. Small vulnerable classes (pedestrian, cyclist, motorcycle) matter most — they drive safety recall."> <DeltaBars rows={classRows} max={1} fmt={(v) => `${(v * 100).toFixed(1)}pp`} /> </SectionCard> </Box>
<SectionCard title={ <Box component="span" sx={{ display: 'inline-flex', alignItems: 'center' }}> Top-down BEV canvas — one frame, every hypothesis <InfoDot title="BEV canvas" detail="A deterministic replay of the selected scene sequence through both engines (same seeds as the scored run). White outlines = ground truth (dashed amber = camera-occluded this frame). Orange dots + ellipses = camera detections with their along-ray depth uncertainty. Teal crosses = LiDAR detections. Filled boxes = fused+tracked output (dashed purple = masklet-propagated through a detection gap). Red outlines = the camera-only baseline for contrast." /> </Box> } action={ replay ? ( <Chip size="small" label={`${replay.time_of_day} · ${replay.weather}`} sx={{ bgcolor: replay.time_of_day === 'night' ? '#1a237e' : tokens.color.surfaceRaised, fontWeight: 700 }} /> ) : undefined } > {replayError ? ( <Alert severity="warning" variant="outlined"> Frame replay unavailable: {replayError} — the /api/studio-ux router may not be loaded on the backend. </Alert> ) : null} {!replay && !replayError ? <ChartSkeleton height={380} /> : null} {replay && frame ? ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}> <Box sx={{ display: 'flex', gap: 1.5, alignItems: 'center', flexWrap: 'wrap' }}> <TextField select size="small" label="Sequence" value={sequence} onChange={(e) => setSequence(Number(e.target.value))} sx={{ width: 200 }}> {Array.from({ length: report.params.n_sequences }, (_, i) => { const tod = i % 3 === 1 ? 'night' : 'day'; const wthr = i % 3 === 2 ? 'rain' : 'clear'; return ( <MenuItem key={i} value={i}> seq {i} · {tod}/{wthr} </MenuItem> ); })} </TextField> <IconButton size="small" onClick={() => setPlaying((p) => !p)} sx={{ border: `1px solid ${tokens.color.border}` }} aria-label={playing ? 'Pause playback' : 'Play frames'}> {playing ? <Pause size={16} /> : <Play size={16} />} </IconButton> <Box sx={{ flex: 1, minWidth: 220, display: 'flex', alignItems: 'center', gap: 1.5 }}> <Slider size="small" value={frameIdx} min={0} max={replay.frames.length - 1} onChange={(_, v) => { setPlaying(false); setFrameIdx(v as number); }} aria-label="Frame scrubber" /> <Typography variant="caption" sx={{ fontFamily: 'monospace', width: 72, flexShrink: 0 }}> frame {frame.index + 1}/{replay.frames.length} </Typography> </Box> {selectedTrack !== null ? ( <Chip size="small" label={`following track #${selectedTrack}`} onDelete={() => setSelectedTrack(null)} sx={{ bgcolor: tokens.color.infoBg, color: tokens.color.info }} /> ) : null} </Box> <CanvasLegend layers={layers} onToggle={(l) => setLayers((s) => ({ ...s, [l]: !s[l] }))} /> <Box sx={{ display: 'flex', gap: 1.5, alignItems: 'stretch', flexWrap: 'wrap' }}> <Box sx={{ flex: '3 1 520px', minWidth: 0 }}> <BevFrameCanvas frame={frame} layers={layers} selectedTrackId={selectedTrack} onSelectTrack={setSelectedTrack} trail={trail} onHover={setHover} /> </Box> <Box sx={{ flex: '1 1 220px', border: `1px solid ${tokens.color.border}`, borderRadius: 1, p: 1.5, bgcolor: tokens.color.surfaceSunken, minHeight: 120 }}> {hover ? ( <> <Typography variant="subtitle2" sx={{ fontWeight: 800, mb: 0.5 }}>{hover.title}</Typography> {hover.lines.map((l, i) => ( <Typography key={i} variant="caption" sx={{ display: 'block', color: tokens.color.textDim, mb: 0.25 }}> {l} </Typography> ))} </> ) : ( <> <Typography variant="subtitle2" sx={{ fontWeight: 800, mb: 0.5, color: tokens.color.neutral }}> Object details </Typography> <Typography variant="caption" sx={{ color: tokens.color.textFaint }}> Hover any box, ellipse or cross on the canvas. Click a fused box to follow its track — scrub the frames to watch masklet propagation carry identity through occlusion gaps (dashed purple boxes). </Typography> </> )} {frame ? ( <Box sx={{ mt: 1.5, pt: 1, borderTop: `1px solid ${tokens.color.border}` }}> <Typography variant="caption" sx={{ display: 'block', color: tokens.color.neutral, fontFamily: 'monospace', fontSize: 10.5 }}> GT {frame.gt.length} · cam {frame.camera.length} · lidar {frame.lidar.length} · fused {frame.fused.length} {frame.fused.some((b) => b.propagated) ? ` (${frame.fused.filter((b) => b.propagated).length} propagated)` : ''} </Typography> {frame.gt.some((g) => g.occluded) ? ( <Typography variant="caption" sx={{ color: tokens.color.warn, fontSize: 10.5 }}> ⚠ {frame.gt.filter((g) => g.occluded).length} object(s) camera-occluded this frame </Typography> ) : null} </Box> ) : null} </Box> </Box> </Box> ) : null} </SectionCard> </> ) : null}
{report || !loading ? ( <SectionCard title="Run a new comparison" help="Generates fresh deterministic scenes (seed-controlled), runs both engines on every frame, evaluates and persists the report. Sequences cycle day/clear → night/clear → day/rain so all cohorts are represented." > <Box sx={{ display: 'flex', gap: 1.5, alignItems: 'center', flexWrap: 'wrap' }}> <TextField size="small" label="Sequences" type="number" value={nSeq} inputProps={{ min: 1, max: 24 }} onChange={(e) => setNSeq(Math.max(1, Math.min(24, Number(e.target.value) || 6)))} sx={{ width: 110 }} /> <TextField size="small" label="Frames / sequence" type="number" value={framesPerSeq} inputProps={{ min: 8, max: 60 }} onChange={(e) => setFramesPerSeq(Math.max(8, Math.min(60, Number(e.target.value) || 24)))} sx={{ width: 140 }} /> <TextField size="small" label="Seed" type="number" value={seed} onChange={(e) => setSeed(Number(e.target.value) || 7)} sx={{ width: 90 }} /> <Button variant="contained" startIcon={<PlayCircle size={16} />} disabled={running} onClick={run}> {running ? 'Running engines…' : 'Run comparison'} </Button> {running ? <PanelSkeleton rows={1} header={false} /> : null} </Box> </SectionCard> ) : null}
{report ? ( <Typography variant="caption" sx={{ color: tokens.color.textFaint }}> Deltas colored by {`direction-aware improvement (`} <span style={{ color: deltaColor(1) }}>green</span> {` = better, `} <span style={{ color: deltaColor(-1) }}>red</span> {` = worse). Engine comparison recorded at ${new Date(report.created_at).toLocaleString()}.`} </Typography> ) : null} </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553/** * Sequential Regression dashboard (/api/seqeval) — decision-first: * verdict banner, per-node decision tables (delta + CI, n vs n_eff, decision * chips, safety-primary badges), the regression-map heatmap * (class × condition), the sequential-evidence chart (log e-value vs n * against stopping boundaries — showing exactly when and why the run * stopped), the budget funnel, and a run launcher. */import { useCallback, useEffect, useMemo, useState } from 'react';import Alert from '@mui/material/Alert';import Box from '@mui/material/Box';import Button from '@mui/material/Button';import Chip from '@mui/material/Chip';import Collapse from '@mui/material/Collapse';import MenuItem from '@mui/material/MenuItem';import Table from '@mui/material/Table';import TableBody from '@mui/material/TableBody';import TableCell from '@mui/material/TableCell';import TableHead from '@mui/material/TableHead';import TableRow from '@mui/material/TableRow';import TextField from '@mui/material/TextField';import Typography from '@mui/material/Typography';import { ChevronDown, ChevronUp, PlayCircle, ShieldAlert } from 'lucide-react';import { getSeqAttribution, getSeqRun, listSeqRuns, startSeqRun, type SeqAttribution, type SeqNode, type SeqRunState,} from '../../services/seqeval';import { getPopulations } from '../../services/megaeval';import type { PopulationMeta } from '../../types/megaeval';import { HeatmapGrid, SeriesChart, type HeatCell, type Series } from '../../components/visual/charts';import { IllustratedEmpty, PanelSkeleton, TileSkeleton } from '../../components/visual/Feedback';import { ErrorNote, MetricCard, SectionCard, fmtPct } from '../../components/labeleval/shared';import { HeadCell, InfoDot, Term } from '../../components/help/InfoTip';import { tokens, verdictColor } from '../../theme';
const DECISION_HELP: Record<string, string> = { REGRESSION: 'Anytime-valid evidence of a drop beyond the practical margin in at least one tested node — the gate blocks.', PASS: 'Overall + all pre-registered safety primaries proven within the margin (equivalence-style claim) — the gate allows.', INSUFFICIENT_EVIDENCE: 'NOT proven equivalent. Expand the budget or report — never treated as a pass.',};
const EFFECT_PRESETS: Array<{ label: string; effects: Record<string, number> }> = [ { label: 'clean candidate (no planted effect)', effects: {} }, { label: 'pedestrian@night −8% (safety primary)', effects: { 'pedestrian|night': -0.08 } }, { label: 'global −1% (subtle broad drop)', effects: { __global__: -0.01 } }, { label: 'cyclist@night −5% + global +0.5%', effects: { 'cyclist|night': -0.05, __global__: 0.005 } },];
function nodeGroup(key: string): string { if (key === 'overall') return 'overall'; const prefix = key.split(':')[0]; return prefix;}
function prettyNode(key: string): string { return key.replace(/^(class|stratum|difficulty|safety):/, '');}
// ------------------------------------------------------------ evidence chart
function EvidenceChart({ run, nodeKey }: { run: SeqRunState; nodeKey: string }) { const traj = run.trajectories?.[nodeKey]; if (!traj || !traj.points.length) { return ( <Typography variant="body2" sx={{ color: tokens.color.neutral, p: 2 }}> No trajectory recorded for this node (it may have had no samples). </Typography> ); } const pts = traj.points; const last = pts[pts.length - 1]; const stopped = last.decision !== 'INSUFFICIENT_EVIDENCE';
const series: Series[] = [ { id: 'regression evidence', color: tokens.color.danger, width: 2.2, points: pts.map((p) => ({ x: p.n, y: p.log_e_regression, meta: p })), }, { id: 'pass evidence', color: tokens.color.success, width: 2.2, points: pts.map((p) => ({ x: p.n, y: p.log_e_pass, meta: p })), }, ];
return ( <Box> <SeriesChart series={series} height={320} xLabel="samples analyzed (n)" yLabel="log e-value (accumulated evidence)" refLinesY={[ { y: traj.boundaries.log_e_regression, label: `REGRESSION boundary (${traj.boundaries.log_e_regression.toFixed(2)})`, color: tokens.color.danger }, { y: traj.boundaries.log_e_pass, label: `PASS boundary (${traj.boundaries.log_e_pass.toFixed(2)})`, color: tokens.color.success }, { y: 0, label: '', color: tokens.color.borderStrong, dashed: false }, ]} markerX={stopped ? { x: last.n, label: `stopped @ n=${last.n} → ${last.decision}`, color: verdictColor(last.decision) } : null} /> <Box sx={{ display: 'flex', gap: 2, alignItems: 'center', flexWrap: 'wrap', mt: 0.5 }}> <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}> <Box sx={{ width: 16, height: 3, bgcolor: tokens.color.danger }} /> <Typography variant="caption" sx={{ color: tokens.color.textDim }}>evidence FOR a regression (log e)</Typography> </Box> <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}> <Box sx={{ width: 16, height: 3, bgcolor: tokens.color.success }} /> <Typography variant="caption" sx={{ color: tokens.color.textDim }}>evidence FOR equivalence (pass)</Typography> </Box> <Typography variant="caption" sx={{ color: tokens.color.neutral }}> Whichever line crosses its boundary first ends the test for this node — crossing red blocks, crossing green proves equivalence, and running out of budget with neither = insufficient evidence. </Typography> </Box> </Box> );}
// ------------------------------------------------------------ budget funnel
function BudgetFunnel({ run }: { run: SeqRunState }) { const b = run.budget; if (!b) return null; const stages = [ { label: 'Full population', value: b.full_population, color: tokens.color.textFaint, note: 'every inference unit available' }, { label: 'Frozen sampling plan', value: b.planned_total, color: tokens.color.info, note: 'allocated before any candidate outcome was seen (hashed)' }, { label: 'Actually consumed', value: b.samples_used, color: verdictColor(run.decision), note: `stopped early: ${run.stopping_reason ?? '—'}` }, ]; if (b.escalation_used > 0) { stages.push({ label: 'Escalation', value: b.escalation_used, color: tokens.color.warn, note: 'extra targeted samples for suspect strata' }); } const max = Math.max(...stages.map((s) => s.value), 1); return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}> {stages.map((s) => ( <Box key={s.label}> <Box sx={{ display: 'flex', justifyContent: 'space-between' }}> <Typography variant="caption" sx={{ color: tokens.color.textDim }}>{s.label}</Typography> <Typography variant="caption" sx={{ fontFamily: 'monospace', color: tokens.color.text }}> {s.value.toLocaleString()} <span style={{ color: tokens.color.neutral }}>({fmtPct(s.value / max)})</span> </Typography> </Box> <Box sx={{ height: 14, bgcolor: tokens.color.border, borderRadius: 1, overflow: 'hidden' }}> <Box sx={{ height: '100%', width: `${Math.max(1.5, (s.value / max) * 100)}%`, bgcolor: s.color, transition: `width ${tokens.motion.slow}` }} /> </Box> <Typography variant="caption" sx={{ color: tokens.color.textFaint, fontSize: 10.5 }}>{s.note}</Typography> </Box> ))} <Typography variant="caption" sx={{ color: tokens.color.neutral, mt: 0.5 }}> The run answered with <strong>{fmtPct(b.samples_used / Math.max(b.full_population, 1))}</strong> of the population — that saving is the point of sequential testing. </Typography> </Box> );}
// ------------------------------------------------------------ decision table
function DecisionTable({ nodes, title, help }: { nodes: SeqNode[]; title: string; help: string }) { if (!nodes.length) return null; return ( <SectionCard title={title} help={help}> <Table size="small"> <TableHead> <TableRow> <TableCell>Node</TableCell> <TableCell align="right"><HeadCell label="Δ recall" title="Delta estimate" detail="Candidate minus baseline recall in this node, estimated from paired outcomes on identical samples." /></TableCell> <TableCell><HeadCell label="95% CS" title="Confidence sequence" detail="Anytime-valid confidence interval — valid at every look, not just the final one. Wide intervals mean the node is under-sampled." /></TableCell> <TableCell align="right"><HeadCell label="n / clusters" title="Samples vs effective clusters" detail="Objects analyzed vs container clusters they came from — inference runs on clusters, so n_eff (clusters) is the honest sample size." /></TableCell> <TableCell align="right"><HeadCell label="e-value (reg / pass)" title="Evidence values" detail="Accumulated betting-style evidence for regression and for equivalence, each against its stopping threshold." /></TableCell> <TableCell align="center">Decision</TableCell> </TableRow> </TableHead> <TableBody> {nodes.map((n) => { const color = verdictColor(n.decision); return ( <TableRow key={n.node} sx={{ bgcolor: n.decision === 'REGRESSION' ? tokens.color.dangerBg : undefined }}> <TableCell sx={{ fontFamily: 'monospace', fontSize: 11.5 }}> {prettyNode(n.node)} {n.safety_primary ? ( <Chip size="small" icon={<ShieldAlert size={11} />} label="safety primary" sx={{ ml: 0.75, height: 17, fontSize: 9.5, bgcolor: 'rgba(239,83,80,0.15)', color: '#ff8a80', fontWeight: 700 }} /> ) : null} {n.suspect ? ( <Chip size="small" label="suspect" title="Screening flagged this node as suspicious — it received escalated attention." sx={{ ml: 0.5, height: 17, fontSize: 9.5, bgcolor: tokens.color.warnBg, color: tokens.color.warn }} /> ) : null} </TableCell> <TableCell align="right" sx={{ fontFamily: 'monospace', fontSize: 12, fontWeight: 700, color: n.delta_estimate < 0 ? tokens.color.danger : tokens.color.success }}> {n.delta_estimate >= 0 ? '+' : ''}{(n.delta_estimate * 100).toFixed(2)}% </TableCell> <TableCell sx={{ fontFamily: 'monospace', fontSize: 11.5, color: tokens.color.textDim, minWidth: 130 }}> [{(n.delta_ci[0] * 100).toFixed(1)}%, {(n.delta_ci[1] * 100).toFixed(1)}%] </TableCell> <TableCell align="right" sx={{ fontFamily: 'monospace', fontSize: 12 }}> {n.n.toLocaleString()} / {n.n_clusters.toLocaleString()} </TableCell> <TableCell align="right" sx={{ fontFamily: 'monospace', fontSize: 11.5, color: tokens.color.textDim }}> {n.e_regression.toFixed(2)}<span style={{ color: tokens.color.textFaint }}>/{n.e_threshold_regression.toFixed(0)}</span> {' · '} {n.e_pass.toFixed(2)}<span style={{ color: tokens.color.textFaint }}>/{n.e_threshold_pass.toFixed(0)}</span> </TableCell> <TableCell align="center"> <Chip size="small" label={n.decision.replace(/_/g, ' ')} title={DECISION_HELP[n.decision]} sx={{ height: 20, fontSize: 10, fontWeight: 800, bgcolor: `${color}22`, color, border: `1px solid ${color}` }} /> </TableCell> </TableRow> ); })} </TableBody> </Table> </SectionCard> );}
// ------------------------------------------------------------ run launcher
function RunLauncher({ onStarted }: { onStarted: (run: SeqRunState) => void }) { const [open, setOpen] = useState(false); const [populations, setPopulations] = useState<PopulationMeta[]>([]); const [populationId, setPopulationId] = useState(''); const [preset, setPreset] = useState(1); const [targetN, setTargetN] = useState(3000); const [starting, setStarting] = useState(false); const [error, setError] = useState<string | null>(null);
useEffect(() => { getPopulations() .then((r) => { const sorted = [...r.populations].sort((a, b) => (b.created_at ?? '').localeCompare(a.created_at ?? '')); setPopulations(sorted); if (sorted.length) setPopulationId((p) => p || sorted[0].population_id); }) .catch(() => undefined); }, []);
const start = () => { setStarting(true); setError(null); startSeqRun({ population_id: populationId, baseline: { model_version: 'baseline-v1', effects: {} }, candidate: { model_version: `candidate-${EFFECT_PRESETS[preset].effects && Object.keys(EFFECT_PRESETS[preset].effects).length ? 'planted' : 'clean'}`, effects: EFFECT_PRESETS[preset].effects }, policy: { target_n: targetN }, sync: true, }) .then(onStarted) .catch((e) => setError(e instanceof Error ? e.message : String(e))) .finally(() => setStarting(false)); };
return ( <SectionCard title="Run launcher" help="Starts a new sequential evaluation: a sampling plan is frozen (hashed) over the population, then baseline and candidate are compared on identical samples batch by batch until the evidence crosses a boundary or the budget runs out. The synthetic candidate harness lets you plant a known per-stratum effect to watch the engine find it." action={ <Button size="small" endIcon={open ? <ChevronUp size={14} /> : <ChevronDown size={14} />} onClick={() => setOpen((o) => !o)}> {open ? 'Hide' : 'New run'} </Button> } > <Collapse in={open} unmountOnExit> {error ? <ErrorNote error={error} /> : null} <Box sx={{ display: 'flex', gap: 1.5, alignItems: 'center', flexWrap: 'wrap' }}> <TextField select size="small" label="Population" value={populationId} onChange={(e) => setPopulationId(e.target.value)} sx={{ minWidth: 240 }}> {populations.map((p) => ( <MenuItem key={p.population_id} value={p.population_id}> <span style={{ fontFamily: 'monospace', fontSize: 12.5 }}>{p.population_id.slice(0, 14)}</span> <span style={{ color: tokens.color.neutral, marginLeft: 8, fontSize: 12 }}>{p.num_objects.toLocaleString()} objects</span> </MenuItem> ))} </TextField> <TextField select size="small" label="Planted candidate effect" value={preset} onChange={(e) => setPreset(Number(e.target.value))} sx={{ minWidth: 280 }}> {EFFECT_PRESETS.map((p, i) => ( <MenuItem key={p.label} value={i}>{p.label}</MenuItem> ))} </TextField> <TextField size="small" label="Target n" type="number" value={targetN} onChange={(e) => setTargetN(Math.max(500, Number(e.target.value) || 3000))} sx={{ width: 110 }} /> <Button variant="contained" startIcon={<PlayCircle size={16} />} disabled={!populationId || starting} onClick={start}> {starting ? 'Running (sequential)…' : 'Start run'} </Button> </Box> <Typography variant="caption" sx={{ color: tokens.color.neutral, display: 'block', mt: 1 }}> Runs synchronously and typically finishes in a few seconds — early stopping is the whole point. </Typography> </Collapse> {!open ? ( <Typography variant="caption" sx={{ color: tokens.color.neutral }}> Launch a new sequential comparison against a megaeval population, optionally planting a known regression to see the engine catch it. </Typography> ) : null} </SectionCard> );}
// ------------------------------------------------------------ page
export default function SeqevalPage() { const [runsList, setRunsList] = useState<SeqRunState[] | null>(null); const [runId, setRunId] = useState<string | null>(null); const [run, setRun] = useState<SeqRunState | null>(null); const [attribution, setAttribution] = useState<SeqAttribution | null>(null); const [loading, setLoading] = useState(true); const [error, setError] = useState<string | null>(null); const [chartNode, setChartNode] = useState('overall');
const refreshList = useCallback(() => { listSeqRuns() .then((r) => { const sorted = [...r.runs].sort((a, b) => (b.created_at ?? '').localeCompare(a.created_at ?? '')); setRunsList(sorted); setRunId((id) => id ?? sorted[0]?.run_id ?? null); }) .catch((e) => setError(e instanceof Error ? e.message : String(e))) .finally(() => setLoading(false)); }, []);
useEffect(refreshList, [refreshList]);
useEffect(() => { if (!runId) return; let cancelled = false; setRun(null); setAttribution(null); getSeqRun(runId) .then((r) => { if (!cancelled) { setRun(r); setChartNode('overall'); } }) .catch((e) => { if (!cancelled) setError(e instanceof Error ? e.message : String(e)); }); getSeqAttribution(runId) .then((a) => { if (!cancelled) setAttribution(a); }) .catch(() => undefined); // 409 when no attribution — heatmap falls back to nodes return () => { cancelled = true; }; }, [runId]);
const onStarted = useCallback((r: SeqRunState) => { setRunId(r.run_id); refreshList(); }, [refreshList]);
// ---------------- regression map (class × condition) const heatmap = useMemo(() => { const rows: Array<{ cls: string; cond: string; delta: number | null; decision: string; safety: boolean; n: number }> = []; const attRows = (attribution?.all_nodes ?? []) as Array<Record<string, unknown>>; const source = attRows.length ? attRows.map((r) => ({ node: String(r.node), delta: (r.abs_delta as number | null), decision: String(r.decision), safety: Boolean(r.safety_primary), n: Number(r.n ?? 0) })) : (run?.nodes ?? []).map((n) => ({ node: n.node, delta: n.delta_estimate, decision: n.decision, safety: n.safety_primary, n: n.n })); source.forEach((r) => { const m = r.node.match(/^stratum:([^|]+)\|(.+)$/); if (!m) return; rows.push({ cls: m[1], cond: m[2], delta: r.delta, decision: r.decision, safety: r.safety, n: r.n }); }); if (!rows.length) return null; const classes = [...new Set(rows.map((r) => r.cls))]; const conds = [...new Set(rows.map((r) => r.cond))]; const cells: HeatCell[] = rows.map((r) => { const d = r.delta ?? 0; const mag = Math.min(1, Math.abs(d) / 0.08); const color = r.decision === 'REGRESSION' ? '#a02824' : d < -0.002 ? `rgba(239,83,80,${0.18 + mag * 0.5})` : d > 0.002 ? `rgba(102,187,106,${0.18 + mag * 0.45})` : 'rgba(138,148,158,0.15)'; return { row: r.cls, col: r.cond, value: d, color, label: r.delta === null ? '—' : `${d >= 0 ? '+' : ''}${(d * 100).toFixed(1)}${r.decision === 'REGRESSION' ? ' ✕' : ''}`, tooltip: ( <Box> <Typography variant="caption" sx={{ fontWeight: 700, color: tokens.color.info, display: 'block' }}> {r.cls} × {r.cond} {r.safety ? '· safety primary' : ''} </Typography> <Typography variant="caption" sx={{ display: 'block' }}> Δ recall {r.delta === null ? '—' : `${(d * 100).toFixed(2)}%`} · n={r.n.toLocaleString()} · decision: {r.decision} </Typography> </Box> ), }; }); return { classes, conds, cells }; }, [attribution, run]);
const trajNodes = useMemo(() => Object.keys(run?.trajectories ?? {}), [run]); const nodes = run?.nodes ?? []; const grouped = useMemo(() => { const overall = nodes.filter((n) => nodeGroup(n.node) === 'overall'); const classes = nodes.filter((n) => nodeGroup(n.node) === 'class'); const strata = [...nodes.filter((n) => nodeGroup(n.node) === 'stratum')].sort( (a, b) => Number(b.safety_primary) - Number(a.safety_primary) || a.delta_estimate - b.delta_estimate ); const other = nodes.filter((n) => !['overall', 'class', 'stratum'].includes(nodeGroup(n.node))); return { overall, classes, strata, other }; }, [nodes]);
const decisionColor = verdictColor(run?.decision);
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> {error ? <ErrorNote error={error} /> : null}
<Box sx={{ display: 'flex', gap: 1.5, alignItems: 'center', flexWrap: 'wrap' }}> <TextField select size="small" label="Run" value={runId ?? ''} onChange={(e) => setRunId(e.target.value)} sx={{ minWidth: 300 }}> {(runsList ?? []).map((r) => ( <MenuItem key={r.run_id} value={r.run_id}> <span style={{ fontFamily: 'monospace', fontSize: 12.5 }}>{r.run_id}</span> <Chip size="small" label={r.decision ?? r.status} sx={{ ml: 1, height: 17, fontSize: 9.5, bgcolor: `${verdictColor(r.decision ?? r.status)}22`, color: verdictColor(r.decision ?? r.status) }} /> </MenuItem> ))} </TextField> {run ? ( <Typography variant="caption" sx={{ color: tokens.color.neutral, fontFamily: 'monospace' }}> {run.baseline.model_version} → {run.candidate.model_version} · pop {run.population_id.slice(0, 12)} · metric {run.policy.metric} · margin ±{(run.policy.delta_margin * 100).toFixed(1)}% </Typography> ) : null} </Box>
{loading ? <TileSkeleton n={3} /> : null}
{runsList !== null && runsList.length === 0 && !loading ? ( <SectionCard title="Sequential regression detection"> <IllustratedEmpty art="gauge" title="No sequential runs yet" message="Launch one below: the engine freezes a stratified sampling plan over a megaeval population, then compares candidate vs baseline on identical samples until anytime-valid evidence settles the question — usually with a fraction of the population." /> </SectionCard> ) : null}
{run ? ( <> {/* verdict banner */} <Alert severity={run.decision === 'PASS' ? 'success' : run.decision === 'REGRESSION' ? 'error' : 'warning'} variant="outlined" sx={{ borderWidth: 2, '& .MuiAlert-message': { width: '100%' } }} > <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, flexWrap: 'wrap' }}> <Typography variant="h6" sx={{ fontWeight: 900, color: decisionColor }}> {(run.decision ?? run.status).replace(/_/g, ' ')} </Typography> <Chip size="small" label={`gate: ${run.gate ?? '—'}`} sx={{ fontWeight: 700, bgcolor: tokens.color.surfaceRaised }} /> <Typography variant="body2" sx={{ color: tokens.color.textDim }}> {run.message ?? ''} {run.stopping_reason ? `(stopping reason: ${run.stopping_reason.replace(/_/g, ' ')})` : ''} </Typography> <InfoDot title={run.decision ?? 'decision'} detail={DECISION_HELP[run.decision ?? ''] ?? 'Run still in progress.'} /> </Box> </Alert>
<Box sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap' }}> <MetricCard label="Samples used" value={run.budget?.samples_used.toLocaleString() ?? '—'} sub={`of ${run.budget?.planned_total.toLocaleString()} planned`} accent={tokens.color.info} info="Objects actually consumed before the evidence crossed a stopping boundary." /> <MetricCard label="Population fraction" value={run.budget ? fmtPct(run.budget.fraction_of_population) : '—'} sub={`${run.budget?.full_population.toLocaleString()} total`} info="How little of the full population the sequential design needed to reach its decision." /> <MetricCard label="Plan hash" value={<span style={{ fontSize: 15, fontFamily: 'monospace' }}>{run.plan?.plan_hash.slice(0, 12) ?? '—'}</span>} sub="frozen before outcomes" info="The sampling plan is hashed before any candidate outcome is observed, so allocations cannot chase noise." /> <MetricCard label="Safety primaries" value={run.policy.safety_primaries.length} sub={run.policy.safety_primaries.join(', ')} info="Pre-registered strata that must individually prove equivalence for a PASS — a global average cannot hide them." /> </Box>
{/* THE key visual */} <SectionCard title={ <Box component="span" sx={{ display: 'inline-flex', alignItems: 'center' }}> Sequential evidence — when and why the run stopped <InfoDot title="Sequential evidence chart" detail="Each point is one analysis batch. The red line accumulates evidence FOR a regression (log e-value), the green line FOR equivalence. Dashed horizontal lines are the pre-committed stopping boundaries (derived from the alpha allocated to this node). The moment a line crosses its boundary, the decision for this node is final — valid despite the repeated looks (anytime-valid inference)." /> </Box> } > <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap', mb: 1 }}> {trajNodes.map((k) => ( <Chip key={k} size="small" label={prettyNode(k)} onClick={() => setChartNode(k)} sx={{ height: 22, fontSize: 11, cursor: 'pointer', fontFamily: 'monospace', bgcolor: chartNode === k ? tokens.color.infoBg : tokens.color.surfaceRaised, color: chartNode === k ? tokens.color.info : tokens.color.textDim, border: `1px solid ${chartNode === k ? tokens.color.info : tokens.color.border}`, }} /> ))} </Box> <EvidenceChart run={run} nodeKey={chartNode} /> </SectionCard>
<Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}> <SectionCard title="Regression map — class × condition" sx={{ flex: '2 1 480px' }} help="Per-stratum recall delta (candidate − baseline). Red = drop, green = gain; ✕ marks strata with a confirmed anytime-valid regression. This is where 'the model regressed' becomes 'pedestrians at night regressed 8%'." > {heatmap ? ( <HeatmapGrid rows={heatmap.classes} cols={heatmap.conds} cells={heatmap.cells} cellH={38} /> ) : ( <Typography variant="body2" sx={{ color: tokens.color.neutral }}> No per-stratum attribution available for this run. </Typography> )} </SectionCard>
<SectionCard title="Budget funnel" sx={{ flex: '1 1 320px' }} help="Planned vs consumed sampling budget against the full population. The frozen plan bounds worst-case cost; early stopping usually spends far less." > <BudgetFunnel run={run} /> </SectionCard> </Box>
<DecisionTable nodes={[...grouped.overall, ...grouped.classes]} title="Decisions — overall & per class" help="Level-1 (overall) and level-2 (class) nodes with their paired delta estimates, anytime-valid confidence sequences, and e-value evidence against thresholds. Alpha is split across the hierarchy so all claims hold simultaneously." /> <DecisionTable nodes={grouped.strata} title="Decisions — strata (class × condition)" help="The finest tested granularity. Safety primaries are pre-registered and must individually prove equivalence for the run to PASS; they are sorted first." /> {run.sanity ? ( <Typography variant="caption" sx={{ color: tokens.color.textFaint, fontFamily: 'monospace' }}> sanity: plan {String((run.sanity as Record<string, unknown>).plan_hash ?? '').slice(0, 12)} · dataset {String((run.sanity as Record<string, unknown>).dataset_fingerprint ?? '')} · smoke discordance {String((run.sanity as Record<string, unknown>).smoke_discordance ?? '—')} · <Term k="seqeval_anytime_valid">anytime-valid</Term> inference on container clusters </Typography> ) : null} </> ) : null}
{runId && !run && !loading ? <PanelSkeleton rows={6} /> : null}
<RunLauncher onStarted={onStarted} /> </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281/** * Calibration Panel — multi-sensor calibration validation (Deepen-style): * three validation modes, a brush-selectable residual scatter, per-check * table and a status badge. */import { useCallback, useEffect, useMemo, useState } from 'react';import Box from '@mui/material/Box';import Button from '@mui/material/Button';import Chip from '@mui/material/Chip';import Slider from '@mui/material/Slider';import Table from '@mui/material/Table';import TableBody from '@mui/material/TableBody';import TableCell from '@mui/material/TableCell';import TableHead from '@mui/material/TableHead';import TableRow from '@mui/material/TableRow';import Typography from '@mui/material/Typography';import { CheckCircle2, PlayCircle, XCircle } from 'lucide-react';import { getCalibrationStatus, validateCalibration, type CalibrationMode, type CalibrationResult,} from '../../services/safety';import BrushChart, { type BrushPoint } from '../../components/visual/BrushChart';import { PanelSkeleton } from '../../components/visual/Feedback';import { ErrorNote, MetricCard, SectionCard } from '../../components/labeleval/shared';import { InfoDot } from '../../components/help/InfoTip';import { tokens, verdictColor } from '../../theme';
const MODES: Array<{ id: CalibrationMode; label: string; desc: string }> = [ { id: 'clean', label: 'Clean sensors', desc: 'Well-calibrated rig: residuals should be small, unbiased and isotropic — the healthy baseline.', }, { id: 'miscalibrated', label: 'Miscalibration', desc: 'Injects a rotation/translation extrinsic offset: residuals become systematically biased in one direction — the classic drifted-mount signature.', }, { id: 'perception_failure', label: 'Perception failure', desc: 'Tampers a fraction of objects: most residuals stay clean but a subset are wild outliers — distinguishable from miscalibration by the outlier fraction, not the bias.', },];
export default function CalibrationPage() { const [mode, setMode] = useState<CalibrationMode>('clean'); const [rotation, setRotation] = useState(2.0); const [tamper, setTamper] = useState(0.25); const [result, setResult] = useState<CalibrationResult | null>(null); const [loading, setLoading] = useState(false); const [error, setError] = useState<string | null>(null); const [selectedIds, setSelectedIds] = useState<string[] | null>(null);
useEffect(() => { getCalibrationStatus() .then((s) => { if (s.status !== 'NEVER_RUN') setResult(s); }) .catch(() => undefined); }, []);
const run = useCallback(() => { setLoading(true); setError(null); setSelectedIds(null); validateCalibration({ mode, rotation_offset_deg: rotation, tamper_fraction: tamper }) .then(setResult) .catch((e) => setError(e instanceof Error ? e.message : String(e))) .finally(() => setLoading(false)); }, [mode, rotation, tamper]);
const points: BrushPoint[] = useMemo( () => (result?.per_object ?? []).map((o) => ({ id: o.object_id, x: o.residual_px[0], y: o.residual_px[1], color: o.flagged ? tokens.color.danger : tokens.color.success, label: `${o.class_name} ${o.object_id}`, r: o.flagged ? 5 : 4, })), [result] );
const visibleObjects = useMemo(() => { const all = result?.per_object ?? []; if (!selectedIds) return all; const set = new Set(selectedIds); return all.filter((o) => set.has(o.object_id)); }, [result, selectedIds]);
const statusColor = verdictColor(result?.status);
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> {error ? <ErrorNote error={error} /> : null}
<SectionCard title="Validation mode" help="The validator projects LiDAR box centers into the camera and measures pixel residuals against camera detections. The three modes simulate the three states a real rig can be in — the point is that the checks can TELL THEM APART from residual statistics alone (bias vs scatter vs outlier fraction)." > <Box sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap' }}> {MODES.map((m) => ( <Box key={m.id} onClick={() => setMode(m.id)} role="button" tabIndex={0} onKeyDown={(e) => { if (e.key === 'Enter') setMode(m.id); }} sx={{ flex: '1 1 240px', p: 1.5, borderRadius: 1, border: `2px solid ${mode === m.id ? tokens.color.info : tokens.color.border}`, bgcolor: mode === m.id ? tokens.color.infoBg : tokens.color.surfaceSunken, cursor: 'pointer', transition: `border-color ${tokens.motion.fast}, background-color ${tokens.motion.fast}`, '&:focus-visible': { outline: `2px solid ${tokens.color.info}` }, }} > <Typography variant="subtitle2" sx={{ fontWeight: 700 }}>{m.label}</Typography> <Typography variant="caption" sx={{ color: tokens.color.neutral }}>{m.desc}</Typography> </Box> ))} </Box> <Box sx={{ display: 'flex', gap: 3, alignItems: 'center', mt: 1.5, flexWrap: 'wrap' }}> {mode === 'miscalibrated' ? ( <Box sx={{ width: 240 }}> <Typography variant="caption" sx={{ color: tokens.color.neutral }}> Injected rotation offset: {rotation.toFixed(1)}° </Typography> <Slider size="small" value={rotation} min={0.5} max={10} step={0.5} onChange={(_, v) => setRotation(v as number)} sx={{ py: 0.5 }} /> </Box> ) : null} {mode === 'perception_failure' ? ( <Box sx={{ width: 240 }}> <Typography variant="caption" sx={{ color: tokens.color.neutral }}> Tampered fraction: {(tamper * 100).toFixed(0)}% </Typography> <Slider size="small" value={tamper} min={0.05} max={0.8} step={0.05} onChange={(_, v) => setTamper(v as number)} sx={{ py: 0.5 }} /> </Box> ) : null} <Button variant="contained" startIcon={<PlayCircle size={16} />} disabled={loading} onClick={run}> {loading ? 'Validating…' : 'Run validation'} </Button> </Box> </SectionCard>
{loading && !result ? <PanelSkeleton rows={5} /> : null}
{result && result.status !== 'NEVER_RUN' ? ( <> <Box sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap', alignItems: 'stretch' }}> <Box sx={{ flex: '0 0 auto', display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', px: 3, borderRadius: 1, border: `2px solid ${statusColor}`, bgcolor: `${statusColor}18`, }} > <Typography variant="h5" sx={{ fontWeight: 900, color: statusColor, letterSpacing: 0.5 }}> {result.status} </Typography> <Typography variant="caption" sx={{ color: tokens.color.textDim, maxWidth: 220, textAlign: 'center' }}> {result.diagnosis} </Typography> {result.simulated ? ( <Chip size="small" label="simulated scene" sx={{ mt: 0.5, height: 18, fontSize: 10, bgcolor: tokens.color.warnBg, color: tokens.color.warn }} /> ) : null} </Box> {result.metrics ? ( <> <MetricCard label="Bias" value={`${result.metrics.bias_px.toFixed(2)} px`} sub={`vector (${result.metrics.bias_vector_px[0]}, ${result.metrics.bias_vector_px[1]})`} info="Mean residual vector magnitude — systematic bias is the miscalibration signature." accent={result.metrics.bias_px > (result.thresholds?.bias_px ?? 6) ? tokens.color.danger : tokens.color.success} /> <MetricCard label="Scatter" value={`${result.metrics.scatter_px.toFixed(2)} px`} info="Residual standard deviation around the bias — noise level of the projection." /> <MetricCard label="Outlier fraction" value={`${(result.metrics.outlier_fraction * 100).toFixed(0)}%`} info="Share of objects with residuals past the outlier threshold — high fraction with low bias indicates perception failure, not miscalibration." accent={result.metrics.outlier_fraction > 0.1 ? tokens.color.danger : tokens.color.success} /> <MetricCard label="Est. rotation offset" value={`${result.metrics.estimated_rotation_offset_deg.toFixed(2)}°`} sub={result.injected ? `injected: ${result.injected.rotation_offset_deg}°` : undefined} info="Rotation offset back-estimated from the residual field — compare against the injected value to see the estimator working." /> </> ) : null} </Box>
<Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}> <SectionCard title="Residual scatter" sx={{ flex: '2 1 460px' }} help="Each point is one object's camera-projection residual (pixels). A healthy rig clusters at the origin; miscalibration shifts the whole cloud off-center; perception failure keeps the cluster centered but sprays outliers. Drag a box to select points — the table filters to your selection." > <BrushChart points={points} height={280} xLabel="residual x (px)" yLabel="residual y (px)" onBrush={setSelectedIds} refLinesX={[{ x: 0, label: '', color: tokens.color.borderStrong }]} refLinesY={[{ y: 0, label: '', color: tokens.color.borderStrong }]} /> <Typography variant="caption" sx={{ color: tokens.color.neutral }}> {selectedIds ? `${selectedIds.length} objects selected — click empty space to clear.` : 'Drag to brush-select objects; green = inlier, red = flagged.'} </Typography> </SectionCard>
<SectionCard title="Checks" sx={{ flex: '1 1 340px' }} help="Deterministic checks with their thresholds. The combination of which checks fail is what separates CALIBRATED / MISCALIBRATED / PERCEPTION_FAILURE."> <Table size="small"> <TableHead> <TableRow> <TableCell>Check</TableCell> <TableCell align="right">Actual</TableCell> <TableCell align="right">Threshold</TableCell> <TableCell align="center">OK</TableCell> </TableRow> </TableHead> <TableBody> {(result.checks ?? []).map((c) => ( <TableRow key={c.name}> <TableCell sx={{ fontFamily: 'monospace', fontSize: 11.5 }}>{c.name}</TableCell> <TableCell align="right" sx={{ fontFamily: 'monospace', fontSize: 12 }}>{c.actual.toFixed(3)}</TableCell> <TableCell align="right" sx={{ fontFamily: 'monospace', fontSize: 12, color: tokens.color.neutral }}>{c.threshold}</TableCell> <TableCell align="center"> {c.passed ? <CheckCircle2 size={15} color={tokens.color.success} /> : <XCircle size={15} color={tokens.color.danger} />} </TableCell> </TableRow> ))} </TableBody> </Table> </SectionCard> </Box>
<SectionCard title={ <Box component="span" sx={{ display: 'inline-flex', alignItems: 'center' }}> Per-object residuals {selectedIds ? `(${visibleObjects.length} selected)` : `(${visibleObjects.length})`} <InfoDot title="Per-object residuals" detail="One row per validation object. Flagged objects exceed the outlier threshold; their failure reason distinguishes projection outliers from inlier-ratio failures." /> </Box> } > <Table size="small"> <TableHead> <TableRow> <TableCell>Object</TableCell> <TableCell>Class</TableCell> <TableCell align="right">Residual (px)</TableCell> <TableCell align="right">|r|</TableCell> <TableCell align="right">Inlier ratio</TableCell> <TableCell>Status</TableCell> </TableRow> </TableHead> <TableBody> {visibleObjects.map((o) => ( <TableRow key={o.object_id} sx={{ bgcolor: o.flagged ? tokens.color.dangerBg : undefined }}> <TableCell sx={{ fontFamily: 'monospace', fontSize: 11.5 }}>{o.object_id}</TableCell> <TableCell>{o.class_name}</TableCell> <TableCell align="right" sx={{ fontFamily: 'monospace', fontSize: 12 }}> ({o.residual_px[0].toFixed(1)}, {o.residual_px[1].toFixed(1)}) </TableCell> <TableCell align="right" sx={{ fontFamily: 'monospace', fontSize: 12 }}>{o.residual_magnitude_px.toFixed(2)}</TableCell> <TableCell align="right" sx={{ fontFamily: 'monospace', fontSize: 12 }}>{o.inlier_ratio.toFixed(2)}</TableCell> <TableCell> {o.flagged ? ( <Chip size="small" label={o.failure_reason ?? 'flagged'} sx={{ height: 18, fontSize: 10, bgcolor: tokens.color.dangerBg, color: tokens.color.danger }} /> ) : ( <Chip size="small" label="inlier" sx={{ height: 18, fontSize: 10, bgcolor: tokens.color.successBg, color: tokens.color.success }} /> )} </TableCell> </TableRow> ))} </TableBody> </Table> </SectionCard> </> ) : null} </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215/** * Discrepancy Dashboard — auto-label discrepancy mining: diff a simulated * online perception pass against the stored offline auto-labels. Mine * action, by-type donut, cohort table, sample discrepancy list. */import { useCallback, useEffect, useMemo, useState } from 'react';import Box from '@mui/material/Box';import Button from '@mui/material/Button';import Chip from '@mui/material/Chip';import Table from '@mui/material/Table';import TableBody from '@mui/material/TableBody';import TableCell from '@mui/material/TableCell';import TableHead from '@mui/material/TableHead';import TableRow from '@mui/material/TableRow';import Typography from '@mui/material/Typography';import { Pickaxe } from 'lucide-react';import { getDiscrepancySummary, mineDiscrepancies, type DiscrepancyReport } from '../../services/safety';import { Donut } from '../../components/visual/charts';import { IllustratedEmpty, TileSkeleton } from '../../components/visual/Feedback';import { ErrorNote, MetricCard, SectionCard, StatusChip, fmtPct } from '../../components/labeleval/shared';import { HeadCell } from '../../components/help/InfoTip';import { useLabelEval } from '../../context/LabelEvalContext';import { tokens } from '../../theme';
const TYPE_COLORS: Record<string, string> = { online_miss: '#ef5350', class_flip: '#ffa726', position_drift: '#4fc3f7', online_phantom: '#ab47bc',};
interface Totals { objects: number; online_detections: number; offline_annotations: number; discrepancies: number; discrepancy_rate: number;}
interface CohortRow { cohort: string; class: string; weather: string; time_of_day: string; objects: number; discrepancies: number; discrepancy_rate: number;}
interface DiscRow { discrepancy_id: string; type: string; class_name: string; weather: string; time_of_day: string; safety_critical: boolean; severity: string; details: Record<string, unknown>;}
export default function DiscrepancyPage() { const { activeDatasetId } = useLabelEval(); const [report, setReport] = useState<DiscrepancyReport | null>(null); const [mining, setMining] = useState(false); const [loading, setLoading] = useState(true); const [error, setError] = useState<string | null>(null);
useEffect(() => { getDiscrepancySummary() .then((r) => { const multi = r as { datasets?: DiscrepancyReport[] }; if (multi.datasets?.length) setReport(multi.datasets[multi.datasets.length - 1]); else if ((r as DiscrepancyReport).dataset_id) setReport(r as DiscrepancyReport); }) .catch(() => undefined) .finally(() => setLoading(false)); }, []);
const mine = useCallback(() => { setMining(true); setError(null); mineDiscrepancies(activeDatasetId ?? undefined) .then(setReport) .catch((e) => setError(e instanceof Error ? e.message : String(e))) .finally(() => setMining(false)); }, [activeDatasetId]);
const totals = (report?.totals ?? null) as Totals | null; const byType = (report?.by_type ?? {}) as Record<string, number>; const cohorts = ((report?.cohorts ?? []) as unknown as CohortRow[]).slice(0, 20); const samples = ((report?.discrepancies ?? []) as unknown as DiscRow[]).slice(0, 15); const maxRate = useMemo(() => Math.max(...cohorts.map((c) => c.discrepancy_rate), 0.001), [cohorts]);
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> {error ? <ErrorNote error={error} /> : null}
<Box sx={{ display: 'flex', gap: 1.5, alignItems: 'center', flexWrap: 'wrap' }}> <Button variant="contained" startIcon={<Pickaxe size={16} />} disabled={mining} onClick={mine}> {mining ? 'Mining…' : 'Mine discrepancies'} </Button> <Typography variant="caption" sx={{ color: tokens.color.neutral, maxWidth: 620 }}> Runs a deterministic <strong>simulated online pass</strong> over{' '} {activeDatasetId ? <code>{activeDatasetId}</code> : 'the newest dataset'} and diffs it against the stored offline auto-labels over shared ground-truth ids. Critical discrepancies feed the rare-event store and the scenario database automatically. </Typography> {report ? ( <Chip size="small" label={`dataset: ${report.dataset_id}`} sx={{ fontFamily: 'monospace', fontSize: 10.5, bgcolor: tokens.color.surfaceRaised }} /> ) : null} </Box>
{loading || mining ? <TileSkeleton n={4} /> : null}
{!report && !loading && !mining ? ( <SectionCard title="Discrepancy mining"> <IllustratedEmpty art="search" title="No discrepancy report yet" message="Mine the newest dataset to compare the simulated online perception pass against the offline auto-labels — the disagreements are the continuous-learning loop's best training candidates." action={ <Button variant="contained" size="small" startIcon={<Pickaxe size={15} />} onClick={mine}> Mine discrepancies </Button> } /> </SectionCard> ) : null}
{totals ? ( <Box sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap' }}> <MetricCard label="Objects compared" value={totals.objects.toLocaleString()} sub={`${totals.online_detections.toLocaleString()} online · ${totals.offline_annotations.toLocaleString()} offline`} info="Ground-truth objects present in both the offline auto-label pass and the simulated online pass." /> <MetricCard label="Discrepancies" value={totals.discrepancies.toLocaleString()} accent={tokens.color.warn} info="Disagreements between the two passes: online misses, class flips, position drifts and online phantoms." /> <MetricCard label="Discrepancy rate" value={fmtPct(totals.discrepancy_rate)} accent={totals.discrepancy_rate > 0.15 ? tokens.color.danger : tokens.color.warn} info="Discrepancies / objects compared. The online profile deliberately degrades at night and in rain — see the cohort table." /> </Box> ) : null}
{report ? ( <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}> <SectionCard title="Discrepancies by type" sx={{ flex: '1 1 320px' }} help="online_miss = online failed to detect an object the offline pass labeled (the dangerous one); class_flip = same object, different class; position_drift = localization disagreement; online_phantom = online detection with no offline counterpart."> <Donut segments={Object.entries(byType).map(([t, n]) => ({ label: t, value: n, color: TYPE_COLORS[t] ?? tokens.color.neutral }))} centerLabel={totals ? totals.discrepancies.toLocaleString() : ''} centerSub="total" /> </SectionCard>
<SectionCard title="Worst cohorts" sx={{ flex: '2 1 480px' }} help="Cohort = class / weather / time-of-day. Sorted by discrepancy rate — the top rows tell you exactly where the online stack diverges from offline labeling (typically VRU classes at night and in rain)."> <Table size="small"> <TableHead> <TableRow> <TableCell>Cohort</TableCell> <TableCell align="right"><HeadCell label="Objects" title="Objects" detail="Ground-truth objects in this cohort." /></TableCell> <TableCell align="right">Discrepancies</TableCell> <TableCell sx={{ width: '35%' }}>Rate</TableCell> </TableRow> </TableHead> <TableBody> {cohorts.map((c) => ( <TableRow key={c.cohort}> <TableCell sx={{ fontFamily: 'monospace', fontSize: 11.5 }}>{c.cohort}</TableCell> <TableCell align="right" sx={{ fontFamily: 'monospace' }}>{c.objects.toLocaleString()}</TableCell> <TableCell align="right" sx={{ fontFamily: 'monospace' }}>{c.discrepancies.toLocaleString()}</TableCell> <TableCell> <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}> <Box sx={{ flex: 1, height: 7, bgcolor: tokens.color.border, borderRadius: 1, overflow: 'hidden' }}> <Box sx={{ height: '100%', width: `${(c.discrepancy_rate / maxRate) * 100}%`, bgcolor: c.discrepancy_rate > 0.25 ? tokens.color.danger : c.discrepancy_rate > 0.12 ? '#ffa726' : tokens.color.warn, transition: `width ${tokens.motion.slow}` }} /> </Box> <Typography variant="caption" sx={{ fontFamily: 'monospace', width: 48 }}>{fmtPct(c.discrepancy_rate)}</Typography> </Box> </TableCell> </TableRow> ))} </TableBody> </Table> </SectionCard> </Box> ) : null}
{samples.length ? ( <SectionCard title={`Sample discrepancies (first ${samples.length})`} help="Individual disagreements with their evidence. Safety-critical + critical-severity discrepancies are automatically pushed to the rare-event store for review prioritization."> <Table size="small"> <TableHead> <TableRow> <TableCell>Type</TableCell> <TableCell>Class</TableCell> <TableCell>Conditions</TableCell> <TableCell>Severity</TableCell> <TableCell>Details</TableCell> </TableRow> </TableHead> <TableBody> {samples.map((d) => ( <TableRow key={d.discrepancy_id}> <TableCell> <Chip size="small" label={d.type} sx={{ height: 18, fontSize: 10, fontWeight: 700, bgcolor: `${TYPE_COLORS[d.type] ?? tokens.color.neutral}22`, color: TYPE_COLORS[d.type] ?? tokens.color.neutral, border: `1px solid ${TYPE_COLORS[d.type] ?? tokens.color.neutral}` }} /> </TableCell> <TableCell> {d.class_name} {d.safety_critical ? <Chip size="small" label="safety" sx={{ ml: 0.5, height: 16, fontSize: 9, bgcolor: tokens.color.dangerBg, color: tokens.color.danger }} /> : null} </TableCell> <TableCell sx={{ fontFamily: 'monospace', fontSize: 11.5 }}>{d.weather}/{d.time_of_day}</TableCell> <TableCell><StatusChip status={d.severity} /></TableCell> <TableCell sx={{ fontFamily: 'monospace', fontSize: 11 }}> {Object.entries(d.details ?? {}).map(([k, v]) => `${k}=${typeof v === 'number' ? v : String(v)}`).join(' · ')} </TableCell> </TableRow> ))} </TableBody> </Table> </SectionCard> ) : null} </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111/** * Safety Evidence Package viewer — rendered markdown from * /api/safety/evidence/{run}?format=markdown, JSON download, and a prominent * disclaimer about the simulated provenance of the underlying data. */import { useEffect, useState } from 'react';import Alert from '@mui/material/Alert';import AlertTitle from '@mui/material/AlertTitle';import Box from '@mui/material/Box';import Button from '@mui/material/Button';import Typography from '@mui/material/Typography';import { Download, ShieldCheck } from 'lucide-react';import { getEvidenceJson, getEvidenceMarkdown } from '../../services/safety';import { MarkdownLite, RunSelect, downloadJson, usePublishedRuns } from '../../components/safety/shared';import { IllustratedEmpty, PanelSkeleton } from '../../components/visual/Feedback';import { ErrorNote, SectionCard } from '../../components/labeleval/shared';import { useLabelEval } from '../../context/LabelEvalContext';import { tokens } from '../../theme';
export default function EvidencePage() { const { entityId, navigate } = useLabelEval(); const { runs, error: runsError } = usePublishedRuns(); const [runId, setRunId] = useState<string | null>(entityId); const [markdown, setMarkdown] = useState<string | null>(null); const [loading, setLoading] = useState(false); const [missing, setMissing] = useState(false); const [error, setError] = useState<string | null>(null);
useEffect(() => { if (!runId && runs?.length) setRunId(entityId ?? runs[0].run_id); }, [runs, runId, entityId]);
useEffect(() => { if (!runId) return; let cancelled = false; setLoading(true); setMissing(false); setError(null); setMarkdown(null); getEvidenceMarkdown(runId) .then((r) => { if (!cancelled) setMarkdown(r.markdown); }) .catch((e) => { if (cancelled) return; const msg = e instanceof Error ? e.message : String(e); if (msg.startsWith('API 404')) setMissing(true); else setError(msg); }) .finally(() => { if (!cancelled) setLoading(false); }); return () => { cancelled = true; }; }, [runId]);
const download = () => { if (!runId) return; getEvidenceJson(runId) .then((pkg) => downloadJson(`safety-evidence-${runId}.json`, pkg)) .catch((e) => setError(e instanceof Error ? e.message : String(e))); };
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> {runsError ? <ErrorNote error={runsError} /> : null} {error ? <ErrorNote error={error} /> : null}
<Alert severity="warning" variant="outlined" icon={<ShieldCheck size={20} />} sx={{ borderWidth: 2 }}> <AlertTitle sx={{ fontWeight: 800 }}>Demonstration artifact — not a certification document</AlertTitle> This Safety Evidence Package is generated from <strong>synthetic evaluation data</strong> inside Sensorflow Studio. Its structure follows UL 4600 / ISO 26262-style evidence practices (claims backed by measurements, versioned policy, reproducible lineage), but nothing here has been reviewed by an assessor and it must not be used to support a real deployment decision. </Alert>
<Box sx={{ display: 'flex', gap: 1.5, alignItems: 'center', flexWrap: 'wrap' }}> <RunSelect label="Candidate run" value={runId} onChange={(id) => setRunId(id)} runs={runs} /> <Button variant="outlined" size="small" startIcon={<Download size={15} />} disabled={!markdown} onClick={download}> Download JSON </Button> <Typography variant="caption" sx={{ color: tokens.color.neutral }}> Packages are produced by the Release Gates evaluation; the markdown below is rendered from the same data as the JSON. </Typography> </Box>
<SectionCard title="Safety Evidence Package"> {loading ? <PanelSkeleton rows={8} /> : null} {missing && !loading ? ( <IllustratedEmpty art="search" title="No evidence package for this run" message="Evidence packages are created when the release gates are evaluated for a candidate run. Run the gate evaluation first, then the package appears here." action={ <Button variant="contained" size="small" onClick={() => navigate('safety-gates')}> Go to Release Gates </Button> } /> ) : null} {markdown ? ( <Box sx={{ maxWidth: 980, px: 1 }}> <MarkdownLite text={markdown} /> </Box> ) : null} </SectionCard> </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385/** * ODD Coverage — interactive combinatorial coverage heatmap over the ODD * taxonomy (ISO 34503-inspired) with adequacy coloring, a risk-sorted gap * table, and a wired "Fill gap" action showing before/after cell metrics. */import { useCallback, useEffect, useMemo, useState } from 'react';import Alert from '@mui/material/Alert';import Box from '@mui/material/Box';import Button from '@mui/material/Button';import Chip from '@mui/material/Chip';import Dialog from '@mui/material/Dialog';import DialogContent from '@mui/material/DialogContent';import DialogTitle from '@mui/material/DialogTitle';import MenuItem from '@mui/material/MenuItem';import Table from '@mui/material/Table';import TableBody from '@mui/material/TableBody';import TableCell from '@mui/material/TableCell';import TableHead from '@mui/material/TableHead';import TableRow from '@mui/material/TableRow';import TextField from '@mui/material/TextField';import Typography from '@mui/material/Typography';import { ArrowRight, Wand2 } from 'lucide-react';import { fillOddGap, getOddCoverage, getOddTaxonomy, type OddCell, type OddCoverageResponse, type OddFillRequest, type OddTaxonomy,} from '../../services/safety';import { RunSelect, usePublishedRuns } from '../../components/safety/shared';import { HeatmapGrid, type HeatCell } from '../../components/visual/charts';import { PanelSkeleton, TileSkeleton, IllustratedEmpty } from '../../components/visual/Feedback';import { ErrorNote, MetricCard, SectionCard, fmtPct } from '../../components/labeleval/shared';import { HeadCell, InfoDot } from '../../components/help/InfoTip';import { tokens } from '../../theme';
// Coverage-adequacy palette: green adequate, amber = statistical gap, red = performance gap.function cellColor(cell: OddCell): string { if (cell.n === 0) return '#20262d'; if (cell.adequate) { const r = cell.recall ?? 0; return r >= 0.9 ? '#1e5c28' : r >= 0.8 ? '#2e6b33' : '#3f7a3f'; } if (cell.gap_reasons.includes('recall_below_target') || cell.performance_deficit > 0.1) return '#8e2f2b'; return '#8a6215';}
function GapReasonChips({ reasons }: { reasons: string[] }) { const meta: Record<string, { label: string; color: string; help: string }> = { insufficient_samples: { label: 'too few samples', color: tokens.color.warn, help: 'The cell has fewer evaluated objects than the min-samples threshold — its metrics are statistically unreliable.' }, wide_ci: { label: 'wide CI', color: tokens.color.warn, help: 'The Wilson confidence interval on recall is wider than the max-CI-width threshold.' }, recall_below_target: { label: 'recall below target', color: tokens.color.danger, help: 'Even with enough data, recall in this cell is below the target — a performance gap, not a data gap.' }, }; return ( <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap' }}> {reasons.map((r) => { const m = meta[r] ?? { label: r, color: tokens.color.neutral, help: '' }; return ( <Chip key={r} size="small" label={m.label} title={m.help} sx={{ height: 18, fontSize: 10, bgcolor: 'transparent', border: `1px solid ${m.color}`, color: m.color }} /> ); })} </Box> );}
function CellStats({ cell, title }: { cell: OddCell; title: string }) { return ( <Box sx={{ flex: 1, p: 1.5, border: `1px solid ${tokens.color.border}`, borderRadius: 1, bgcolor: tokens.color.surfaceSunken }}> <Typography variant="caption" sx={{ color: tokens.color.neutral, fontWeight: 700, textTransform: 'uppercase' }}> {title} </Typography> <Box sx={{ display: 'grid', gridTemplateColumns: 'auto 1fr', columnGap: 1.5, rowGap: 0.25, mt: 0.5 }}> <Typography variant="caption" sx={{ color: tokens.color.neutral }}>n</Typography> <Typography variant="caption" sx={{ fontFamily: 'monospace' }}>{cell.n.toLocaleString()}</Typography> <Typography variant="caption" sx={{ color: tokens.color.neutral }}>recall</Typography> <Typography variant="caption" sx={{ fontFamily: 'monospace' }}> {cell.recall !== null ? fmtPct(cell.recall) : '—'} {cell.wilson_ci ? ` (${fmtPct(cell.wilson_ci[0])} – ${fmtPct(cell.wilson_ci[1])})` : ''} </Typography> <Typography variant="caption" sx={{ color: tokens.color.neutral }}>CI width</Typography> <Typography variant="caption" sx={{ fontFamily: 'monospace' }}>{cell.ci_width?.toFixed(4) ?? '—'}</Typography> <Typography variant="caption" sx={{ color: tokens.color.neutral }}>adequate</Typography> <Typography variant="caption" sx={{ fontFamily: 'monospace', color: cell.adequate ? tokens.color.success : tokens.color.danger, fontWeight: 700 }}> {cell.adequate ? 'YES' : 'NO'} </Typography> </Box> {!cell.adequate ? <Box sx={{ mt: 0.75 }}><GapReasonChips reasons={cell.gap_reasons} /></Box> : null} </Box> );}
export default function OddCoveragePage() { const { runs, error: runsError } = usePublishedRuns(); const [runId, setRunId] = useState<string | null>(null); const [taxonomy, setTaxonomy] = useState<OddTaxonomy | null>(null); const [rowDim, setRowDim] = useState('class'); const [colDim, setColDim] = useState('weather'); const [coverage, setCoverage] = useState<OddCoverageResponse | null>(null); const [loading, setLoading] = useState(false); const [error, setError] = useState<string | null>(null); const [selectedCell, setSelectedCell] = useState<OddCell | null>(null); const [filling, setFilling] = useState<string | null>(null); // cell_id in flight const [fillResult, setFillResult] = useState<{ before: OddCell; after: OddCell; added: number; dataset: string } | null>(null);
useEffect(() => { getOddTaxonomy().then(setTaxonomy).catch(() => undefined); }, []);
useEffect(() => { if (!runId && runs?.length) setRunId(runs[0].run_id); }, [runs, runId]);
const refresh = useCallback(() => { if (!runId) return; setLoading(true); setError(null); setSelectedCell(null); getOddCoverage(runId, [rowDim, colDim], true) .then((c) => setCoverage(c)) .catch((e) => setError(e instanceof Error ? e.message : String(e))) .finally(() => setLoading(false)); }, [runId, rowDim, colDim]);
useEffect(refresh, [refresh]);
const dimNames = useMemo(() => Object.keys(taxonomy?.dimensions ?? { class: 0, weather: 0, lighting: 0, road_type: 0 }), [taxonomy]);
const heat = useMemo(() => { if (!coverage?.cells) return null; const rows = taxonomy?.dimensions[rowDim]?.values ?? [...new Set(coverage.cells.map((c) => c.cell[rowDim]))]; const cols = taxonomy?.dimensions[colDim]?.values ?? [...new Set(coverage.cells.map((c) => c.cell[colDim]))]; const cells: HeatCell[] = coverage.cells.map((c) => ({ row: c.cell[rowDim], col: c.cell[colDim], value: c.recall, color: cellColor(c), label: c.n === 0 ? '·' : c.recall !== null ? `${(c.recall * 100).toFixed(0)}%` : '—', tooltip: ( <Box> <Typography variant="caption" sx={{ fontWeight: 700, color: tokens.color.info, display: 'block' }}> {c.cell_id} </Typography> <Typography variant="caption" sx={{ display: 'block' }}> n={c.n.toLocaleString()} · recall {c.recall !== null ? fmtPct(c.recall) : '—'} {c.wilson_ci ? ` [${fmtPct(c.wilson_ci[0])}–${fmtPct(c.wilson_ci[1])}]` : ''} </Typography> <Typography variant="caption" sx={{ display: 'block', color: tokens.color.textDim }}> production share {fmtPct(c.production_share)} · {c.adequate ? 'adequate' : `gap: ${c.gap_reasons.join(', ')}`} </Typography> <Typography variant="caption" sx={{ color: tokens.color.neutral }}>click for details & fill action</Typography> </Box> ), })); return { rows, cols, cells }; }, [coverage, rowDim, colDim, taxonomy]);
const cellByKey = useMemo(() => { const m = new Map<string, OddCell>(); coverage?.cells?.forEach((c) => m.set(`${c.cell[rowDim]}|${c.cell[colDim]}`, c)); return m; }, [coverage, rowDim, colDim]);
const riskByCellId = useMemo(() => { const m = new Map<string, OddFillRequest>(); coverage?.fill_requests.forEach((f) => m.set(f.cell_id, f)); return m; }, [coverage]);
const sortedGaps = useMemo(() => { if (!coverage) return []; return [...coverage.gaps].sort((a, b) => { const ra = riskByCellId.get(a.cell_id)?.risk ?? a.production_share * Math.max(a.performance_deficit, 0.01); const rb = riskByCellId.get(b.cell_id)?.risk ?? b.production_share * Math.max(b.performance_deficit, 0.01); return rb - ra; }); }, [coverage, riskByCellId]);
const doFill = useCallback( (cell: OddCell) => { if (!runId) return; setFilling(cell.cell_id); setFillResult(null); fillOddGap(runId, cell.cell) .then((res) => { const r = res as unknown as { cell_before: OddCell; cell_after: OddCell; objects_added: number; generated_dataset_id: string }; setFillResult({ before: r.cell_before, after: r.cell_after, added: r.objects_added, dataset: r.generated_dataset_id }); refresh(); }) .catch((e) => setError(e instanceof Error ? e.message : String(e))) .finally(() => setFilling(null)); }, [runId, refresh] );
const s = coverage?.summary;
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> {runsError ? <ErrorNote error={runsError} /> : null} {error ? <ErrorNote error={error} /> : null}
<Box sx={{ display: 'flex', gap: 1.5, alignItems: 'center', flexWrap: 'wrap' }}> <RunSelect label="Evaluation run" value={runId} onChange={setRunId} runs={runs} /> <TextField select size="small" label="Rows" value={rowDim} onChange={(e) => setRowDim(e.target.value)} sx={{ minWidth: 140 }}> {dimNames.filter((d) => d !== colDim).map((d) => ( <MenuItem key={d} value={d}>{d}</MenuItem> ))} </TextField> <TextField select size="small" label="Columns" value={colDim} onChange={(e) => setColDim(e.target.value)} sx={{ minWidth: 140 }}> {dimNames.filter((d) => d !== rowDim).map((d) => ( <MenuItem key={d} value={d}>{d}</MenuItem> ))} </TextField> {taxonomy ? ( <Typography variant="caption" sx={{ color: tokens.color.neutral, maxWidth: 420 }}> {taxonomy.standard_basis} </Typography> ) : null} </Box>
{runs !== null && runs.length === 0 ? ( <SectionCard title="ODD coverage needs a published evaluation run"> <IllustratedEmpty art="gauge" title="No published evaluation runs" message="Coverage is computed from the metric cube of a published mega-scale evaluation run. Generate a population and launch a run from the Command Center, then come back here." /> </SectionCard> ) : null}
{loading && !coverage ? <TileSkeleton n={5} /> : null}
{s ? ( <Box sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap' }}> <MetricCard label="Coverage rate" value={fmtPct(s.coverage_rate)} sub={`${s.adequate_cells}/${s.total_cells} cells adequate`} accent={s.coverage_rate >= 0.9 ? tokens.color.success : s.coverage_rate >= 0.7 ? tokens.color.warn : tokens.color.danger} term="odd_coverage" /> <MetricCard label="Production-weighted" value={fmtPct(s.production_weighted_coverage)} sub="weighted by exposure share" accent={tokens.color.info} info="Coverage where each cell counts proportionally to its production exposure share — a gap in a common condition hurts more than one in a rare condition." /> <MetricCard label="Gap cells" value={s.gap_cells} sub={`${s.empty_cells} empty`} accent={s.gap_cells > 0 ? tokens.color.warn : tokens.color.success} info="Cells that fail the adequacy criteria (min samples, max CI width, recall target)." /> <MetricCard label="Overall recall" value={fmtPct(s.overall_recall)} term="recall" /> </Box> ) : null}
{heat && coverage ? ( <SectionCard title={`Coverage heatmap — ${rowDim} × ${colDim}`} help={`Each cell is one ODD combination. Green = adequate (enough samples, tight CI, recall at target — darker green is higher recall). Amber = statistical gap (too little data / wide CI). Red = performance gap (recall below the ${fmtPct(coverage.thresholds.target_recall)} target). Click a cell for details and the fill-gap action.`} action={ <Typography variant="caption" sx={{ color: tokens.color.neutral }}> thresholds: n ≥ {coverage.thresholds.min_samples}, CI width ≤ {coverage.thresholds.max_ci_width}, recall target {fmtPct(coverage.thresholds.target_recall)} </Typography> } > <HeatmapGrid rows={heat.rows} cols={heat.cols} cells={heat.cells} selectedKey={selectedCell ? `${selectedCell.cell[rowDim]}|${selectedCell.cell[colDim]}` : null} onCellClick={(hc) => setSelectedCell(cellByKey.get(`${hc.row}|${hc.col}`) ?? null)} /> {selectedCell ? ( <Box sx={{ mt: 1.5, display: 'flex', gap: 1.5, alignItems: 'stretch', flexWrap: 'wrap' }}> <CellStats cell={selectedCell} title={selectedCell.cell_id} /> <Box sx={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 1 }}> {selectedCell.is_gap ? ( <Button variant="contained" size="small" startIcon={<Wand2 size={15} />} disabled={filling !== null} onClick={() => doFill(selectedCell)} > {filling === selectedCell.cell_id ? 'Generating…' : 'Fill gap'} </Button> ) : ( <Chip size="small" label="adequate — no action needed" sx={{ bgcolor: tokens.color.successBg, color: tokens.color.success }} /> )} <Typography variant="caption" sx={{ color: tokens.color.neutral, maxWidth: 220 }}> Fill gap generates targeted synthetic sequences for this cell via the platform generator and re-computes coverage. </Typography> </Box> </Box> ) : null} </SectionCard> ) : null}
{coverage && loading ? <PanelSkeleton rows={3} header={false} /> : null}
{sortedGaps.length ? ( <SectionCard title="Coverage gaps, risk-sorted" help="Risk = production exposure share × performance deficit: how much real-world harm the gap could cause. The Fill gap action generates targeted synthetic data for the cell and shows the before/after effect." > <Table size="small"> <TableHead> <TableRow> <TableCell><HeadCell label="Cell" title="ODD cell" detail="The combination of ODD dimension values defining this coverage cell." /></TableCell> <TableCell align="right"><HeadCell label="n" title="Samples" detail="Evaluated objects in this cell." /></TableCell> <TableCell align="right"><HeadCell label="Recall (95% CI)" term="wilson_ci" /></TableCell> <TableCell align="right"><HeadCell label="Prod. share" title="Production share" detail="Estimated fraction of real-world exposure falling in this cell." /></TableCell> <TableCell align="right"><HeadCell label="Risk" title="Gap risk" detail="Production share × performance deficit — the sort key of this table." /></TableCell> <TableCell><HeadCell label="Why it's a gap" title="Gap reasons" detail="Which adequacy criteria the cell fails." /></TableCell> <TableCell align="center">Action</TableCell> </TableRow> </TableHead> <TableBody> {sortedGaps.map((g) => ( <TableRow key={g.cell_id} hover selected={selectedCell?.cell_id === g.cell_id} onClick={() => setSelectedCell(g)} sx={{ cursor: 'pointer' }}> <TableCell sx={{ fontFamily: 'monospace', fontSize: 11.5 }}> {Object.entries(g.cell).map(([k, v]) => ( <Chip key={k} size="small" label={`${k}=${v}`} sx={{ height: 18, fontSize: 10, mr: 0.5, bgcolor: tokens.color.surfaceRaised }} /> ))} </TableCell> <TableCell align="right" sx={{ fontFamily: 'monospace' }}>{g.n.toLocaleString()}</TableCell> <TableCell align="right" sx={{ fontFamily: 'monospace' }}> {g.recall !== null ? fmtPct(g.recall) : '—'} {g.wilson_ci ? ( <Typography component="span" variant="caption" sx={{ color: tokens.color.neutral }}> {' '}[{fmtPct(g.wilson_ci[0])}–{fmtPct(g.wilson_ci[1])}] </Typography> ) : null} </TableCell> <TableCell align="right" sx={{ fontFamily: 'monospace' }}>{fmtPct(g.production_share)}</TableCell> <TableCell align="right" sx={{ fontFamily: 'monospace' }}> {(riskByCellId.get(g.cell_id)?.risk ?? g.production_share * Math.max(g.performance_deficit, 0.01)).toExponential(2)} </TableCell> <TableCell><GapReasonChips reasons={g.gap_reasons} /></TableCell> <TableCell align="center"> <Button size="small" variant="outlined" startIcon={<Wand2 size={13} />} disabled={filling !== null} onClick={(e) => { e.stopPropagation(); doFill(g); }} > {filling === g.cell_id ? 'Generating…' : 'Fill gap'} </Button> </TableCell> </TableRow> ))} </TableBody> </Table> </SectionCard> ) : null}
{coverage && !sortedGaps.length && !loading ? ( <Alert severity="success" variant="outlined"> No coverage gaps at the current thresholds — every populated ODD cell is adequate. </Alert> ) : null}
<Dialog open={fillResult !== null} onClose={() => setFillResult(null)} maxWidth="md" fullWidth> <DialogTitle sx={{ fontWeight: 800 }}> Gap filled — before / after <InfoDot title="What happened" detail="Targeted synthetic sequences were generated for the gap cell (conditions retargeted to the cell), labeled by the current model, persisted as a supplement, and coverage was recomputed." /> </DialogTitle> <DialogContent> {fillResult ? ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}> <Typography variant="body2" sx={{ color: tokens.color.textDim }}> Added <strong>{fillResult.added}</strong> objects via synthetic dataset{' '} <Box component="code" sx={{ fontFamily: 'monospace' }}>{fillResult.dataset}</Box>. Supplements are tracked separately from the immutable evaluation population. </Typography> <Box sx={{ display: 'flex', gap: 1.5, alignItems: 'center' }}> <CellStats cell={fillResult.before} title="Before" /> <ArrowRight size={28} color={tokens.color.info} style={{ flexShrink: 0 }} /> <CellStats cell={fillResult.after} title="After" /> </Box> </Box> ) : null} </DialogContent> </Dialog> </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426/** * Release Gates — candidate/baseline pickers, a visual gate pipeline * (5 connected stages with PASS/BLOCK states, expandable actual-vs-threshold * checks), and the persisted release-policy editor. */import { useCallback, useEffect, useMemo, useState } from 'react';import Alert from '@mui/material/Alert';import Box from '@mui/material/Box';import Button from '@mui/material/Button';import Chip from '@mui/material/Chip';import Collapse from '@mui/material/Collapse';import Switch from '@mui/material/Switch';import Table from '@mui/material/Table';import TableBody from '@mui/material/TableBody';import TableCell from '@mui/material/TableCell';import TableHead from '@mui/material/TableHead';import TableRow from '@mui/material/TableRow';import TextField from '@mui/material/TextField';import Typography from '@mui/material/Typography';import { CheckCircle2, ChevronDown, ChevronUp, FileText, MinusCircle, PlayCircle, XCircle } from 'lucide-react';import { evaluateGates, getGatePolicy, getGateResult, setGatePolicy, type GateEvaluation, type GateResult,} from '../../services/safety';import { RunSelect, usePublishedRuns } from '../../components/safety/shared';import { IllustratedEmpty, PanelSkeleton } from '../../components/visual/Feedback';import { ErrorNote, SectionCard } from '../../components/labeleval/shared';import { InfoDot } from '../../components/help/InfoTip';import { useLabelEval } from '../../context/LabelEvalContext';import { tokens, verdictColor } from '../../theme';
const GATE_ORDER = ['scenario_quality', 'coverage', 'regression', 'safety', 'evidence'];const GATE_SHORT: Record<string, string> = { scenario_quality: 'Scenario Quality', coverage: 'ODD Coverage', regression: 'Regression', safety: 'Surrogate Safety', evidence: 'Evidence Package',};
function gateStatusIcon(status: string, size = 16) { if (status === 'PASS') return <CheckCircle2 size={size} color={tokens.color.success} />; if (status === 'BLOCK') return <XCircle size={size} color={tokens.color.danger} />; return <MinusCircle size={size} color={tokens.color.neutral} />;}
// ------------------------------------------------------------ gate pipeline
function GatePipeline({ gates, expanded, onToggle }: { gates: GateResult[]; expanded: string | null; onToggle: (g: string) => void }) { const ordered = useMemo(() => { const byGate = new Map(gates.map((g) => [g.gate, g])); const known = GATE_ORDER.filter((g) => byGate.has(g)).map((g) => byGate.get(g)!); const rest = gates.filter((g) => !GATE_ORDER.includes(g.gate)); return [...known, ...rest]; }, [gates]);
const W = 168; const H = 74; const GAPX = 42; const total = ordered.length * W + (ordered.length - 1) * GAPX + 20;
return ( <Box sx={{ overflowX: 'auto' }}> <svg width="100%" viewBox={`0 0 ${total} 110`} style={{ minWidth: Math.min(total, 900), display: 'block' }}> <defs> <marker id="gate-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"> <path d="M 0 0 L 10 5 L 0 10 z" fill="#4a5561" /> </marker> </defs> {ordered.map((g, i) => { const x = 10 + i * (W + GAPX); const color = verdictColor(g.status); const failing = g.checks.filter((c) => !c.passed).length; const isOpen = expanded === g.gate; return ( <g key={g.gate}> {i < ordered.length - 1 ? ( <line x1={x + W} y1={55} x2={x + W + GAPX - 6} y2={55} stroke="#4a5561" strokeWidth={2} markerEnd="url(#gate-arrow)" /> ) : null} <g onClick={() => onToggle(g.gate)} style={{ cursor: 'pointer' }}> <rect x={x} y={18} width={W} height={H} rx={10} fill={isOpen ? tokens.color.surfaceRaised : tokens.color.surface} stroke={color} strokeWidth={isOpen ? 3 : 2} style={{ transition: `stroke-width 120ms` }} /> <text x={x + W / 2} y={40} textAnchor="middle" fill={tokens.color.text} fontSize={12.5} fontWeight={700}> {GATE_SHORT[g.gate] ?? g.name} </text> <text x={x + W / 2} y={58} textAnchor="middle" fill={color} fontSize={12} fontWeight={800}> {g.status} </text> <text x={x + W / 2} y={74} textAnchor="middle" fill={tokens.color.neutral} fontSize={9.5}> {g.checks.length} checks{failing ? ` · ${failing} failing` : ''} · click to expand </text> <text x={x + W / 2} y={104} textAnchor="middle" fill={tokens.color.textFaint} fontSize={8.5}> {(g.standard_refs[0] ?? '').slice(0, 34)} </text> </g> </g> ); })} </svg> </Box> );}
function fmtVal(v: number | string | boolean | null): string { if (v === null || v === undefined) return '—'; if (typeof v === 'number') return v.toLocaleString(undefined, { maximumFractionDigits: 4 }); return String(v);}
function GateDetail({ gate }: { gate: GateResult }) { return ( <Box sx={{ p: 1.5, border: `1px solid ${tokens.color.border}`, borderLeft: `3px solid ${verdictColor(gate.status)}`, borderRadius: 1, bgcolor: tokens.color.surfaceSunken }}> <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5 }}> {gateStatusIcon(gate.status, 18)} <Typography variant="subtitle2" sx={{ fontWeight: 700 }}> {gate.name} </Typography> <Typography variant="caption" sx={{ color: tokens.color.neutral }}> {gate.standard_refs.join(' · ')} </Typography> </Box> <Table size="small"> <TableHead> <TableRow> <TableCell>Check</TableCell> <TableCell align="right">Actual</TableCell> <TableCell align="center">vs</TableCell> <TableCell align="left">Threshold</TableCell> <TableCell align="center">Result</TableCell> </TableRow> </TableHead> <TableBody> {gate.checks.map((c, i) => ( <TableRow key={`${c.check}-${i}`}> <TableCell sx={{ fontFamily: 'monospace', fontSize: 12 }}>{c.check}</TableCell> <TableCell align="right" sx={{ fontFamily: 'monospace', fontSize: 12, fontWeight: 700, color: c.passed ? tokens.color.text : tokens.color.danger }}> {fmtVal(c.actual)} </TableCell> <TableCell align="center" sx={{ fontFamily: 'monospace', fontSize: 12, color: tokens.color.neutral }}>{c.direction}</TableCell> <TableCell align="left" sx={{ fontFamily: 'monospace', fontSize: 12 }}>{fmtVal(c.threshold)}</TableCell> <TableCell align="center">{c.passed ? <CheckCircle2 size={15} color={tokens.color.success} /> : <XCircle size={15} color={tokens.color.danger} />}</TableCell> </TableRow> ))} </TableBody> </Table> {gate.notes ? ( <Typography variant="caption" sx={{ color: tokens.color.neutral, display: 'block', mt: 1 }}> {gate.notes} </Typography> ) : null} </Box> );}
// ------------------------------------------------------------ policy editor
function PolicyEditor({ onSaved }: { onSaved: () => void }) { const [policy, setPolicy] = useState<Record<string, Record<string, unknown>> | null>(null); const [draft, setDraft] = useState<Record<string, Record<string, unknown>> | null>(null); const [saving, setSaving] = useState(false); const [error, setError] = useState<string | null>(null); const [saved, setSaved] = useState(false);
useEffect(() => { getGatePolicy() .then((p) => { setPolicy(p.policy); setDraft(JSON.parse(JSON.stringify(p.policy))); }) .catch((e) => setError(e instanceof Error ? e.message : String(e))); }, []);
const dirty = useMemo(() => JSON.stringify(policy) !== JSON.stringify(draft), [policy, draft]);
const setField = (section: string, key: string, value: unknown) => { setDraft((d) => (d ? { ...d, [section]: { ...d[section], [key]: value } } : d)); setSaved(false); };
const save = () => { if (!draft) return; setSaving(true); setError(null); setGatePolicy(draft) .then((p) => { setPolicy(p.policy); setDraft(JSON.parse(JSON.stringify(p.policy))); setSaved(true); onSaved(); }) .catch((e) => setError(e instanceof Error ? e.message : String(e))) .finally(() => setSaving(false)); };
if (error) return <ErrorNote error={error} />; if (!draft) return <PanelSkeleton rows={3} />;
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}> <Box sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap' }}> {Object.entries(draft).map(([section, fields]) => ( <Box key={section} sx={{ flex: '1 1 260px', border: `1px solid ${tokens.color.border}`, borderRadius: 1, p: 1.5, bgcolor: tokens.color.surfaceSunken }}> <Typography variant="caption" sx={{ fontWeight: 800, color: tokens.color.info, textTransform: 'uppercase', letterSpacing: 0.6 }}> {GATE_SHORT[section] ?? section} </Typography> <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1, mt: 1 }}> {Object.entries(fields).map(([k, v]) => { if (typeof v === 'boolean') { return ( <Box key={k} sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}> <Typography variant="caption" sx={{ color: tokens.color.textDim, fontFamily: 'monospace' }}>{k}</Typography> <Switch size="small" checked={v} onChange={(e) => setField(section, k, e.target.checked)} /> </Box> ); } if (typeof v === 'number' || v === null) { return ( <TextField key={k} size="small" label={k} type="number" value={v ?? ''} inputProps={{ step: 'any' }} onChange={(e) => setField(section, k, e.target.value === '' ? null : Number(e.target.value))} /> ); } if (Array.isArray(v)) { return ( <TextField key={k} size="small" label={`${k} (comma-separated)`} value={(v as unknown[]).join(',')} onChange={(e) => setField(section, k, e.target.value.split(',').map((s) => s.trim()).filter(Boolean))} /> ); } if (typeof v === 'object') { return ( <Typography key={k} variant="caption" sx={{ color: tokens.color.textFaint, fontFamily: 'monospace' }}> {k}: {JSON.stringify(v)} </Typography> ); } return ( <TextField key={k} size="small" label={k} value={String(v)} onChange={(e) => setField(section, k, e.target.value)} /> ); })} </Box> </Box> ))} </Box> <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}> <Button variant="contained" size="small" disabled={!dirty || saving} onClick={save}> {saving ? 'Saving…' : 'Save policy'} </Button> <Button size="small" disabled={!dirty} onClick={() => setDraft(JSON.parse(JSON.stringify(policy)))}> Discard changes </Button> {saved ? <Chip size="small" label="saved — applies to the next evaluation" sx={{ bgcolor: tokens.color.successBg, color: tokens.color.success }} /> : null} <Typography variant="caption" sx={{ color: tokens.color.neutral }}> The policy is persisted server-side and versioned into every evidence package. </Typography> </Box> </Box> );}
// ------------------------------------------------------------ page
export default function ReleaseGatesPage() { const { navigate } = useLabelEval(); const { runs, error: runsError } = usePublishedRuns(); const [candidate, setCandidate] = useState<string | null>(null); const [baseline, setBaseline] = useState<string | null>(null); const [evaluation, setEvaluation] = useState<GateEvaluation | null>(null); const [running, setRunning] = useState(false); const [error, setError] = useState<string | null>(null); const [expanded, setExpanded] = useState<string | null>(null); const [showPolicy, setShowPolicy] = useState(false);
useEffect(() => { if (runs?.length && !candidate) { setCandidate(runs[0].run_id); if (runs.length > 1) setBaseline(runs[1].run_id); } }, [runs, candidate]);
// Show the last recorded result for the selected candidate, if any. useEffect(() => { if (!candidate) return; let cancelled = false; getGateResult(candidate) .then((r) => { if (!cancelled) { setEvaluation(r); if (r.baseline_run_id) setBaseline((b) => b ?? r.baseline_run_id); } }) .catch(() => { if (!cancelled) setEvaluation(null); }); return () => { cancelled = true; }; }, [candidate]);
const run = useCallback(() => { if (!candidate || !baseline) return; setRunning(true); setError(null); evaluateGates(candidate, baseline) .then((r) => { setEvaluation(r); setExpanded(r.blocking_gates[0] ?? null); }) .catch((e) => setError(e instanceof Error ? e.message : String(e))) .finally(() => setRunning(false)); }, [candidate, baseline]);
const decisionColor = verdictColor(evaluation?.decision);
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> {runsError ? <ErrorNote error={runsError} /> : null} {error ? <ErrorNote error={error} /> : null}
<Box sx={{ display: 'flex', gap: 1.5, alignItems: 'center', flexWrap: 'wrap' }}> <RunSelect label="Candidate run" value={candidate} onChange={setCandidate} runs={runs} /> <RunSelect label="Baseline run" value={baseline} onChange={setBaseline} runs={runs} exclude={candidate} /> <Button variant="contained" startIcon={<PlayCircle size={16} />} disabled={!candidate || !baseline || running} onClick={run}> {running ? 'Evaluating gates…' : 'Evaluate gates'} </Button> <Button size="small" startIcon={<FileText size={14} />} disabled={!evaluation} onClick={() => navigate('safety-evidence', evaluation?.candidate_run_id)}> Open evidence package </Button> </Box>
{evaluation ? ( <Alert severity={evaluation.decision === 'RELEASE_READY' ? 'success' : 'error'} variant="outlined" sx={{ borderWidth: 2, '& .MuiAlert-message': { width: '100%' } }} > <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, flexWrap: 'wrap' }}> <Typography variant="h6" sx={{ fontWeight: 800, color: decisionColor }}> {evaluation.decision.replace(/_/g, ' ')} </Typography> <Typography variant="body2" sx={{ color: tokens.color.textDim }}> candidate <code>{evaluation.candidate_run_id.slice(0, 14)}</code> vs baseline{' '} <code>{evaluation.baseline_run_id.slice(0, 14)}</code> {evaluation.blocking_gates.length ? ` — blocked by: ${evaluation.blocking_gates.join(', ')}` : ' — all gates passed'} </Typography> <Chip size="small" label={`evidence: ${evaluation.evidence_package_id}`} sx={{ fontFamily: 'monospace', fontSize: 10.5, bgcolor: tokens.color.surfaceRaised }} /> </Box> </Alert> ) : null}
{evaluation ? ( <SectionCard title="Gate pipeline" help="A release decision is the conjunction of five deterministic gates, each grounded in a safety-standard practice (ISO 26262 verification, ISO 34503 ODD coverage, regression policy, FHWA SSAM surrogate safety, UL 4600-style evidence). A single BLOCK anywhere blocks the release. Click a stage to expand its actual-vs-threshold checks." > <GatePipeline gates={evaluation.gates} expanded={expanded} onToggle={(g) => setExpanded((e) => (e === g ? null : g))} /> <Collapse in={expanded !== null} unmountOnExit> {expanded ? (() => { const g = evaluation.gates.find((x) => x.gate === expanded); return g ? <GateDetail gate={g} /> : null; })() : null} </Collapse> </SectionCard> ) : ( <SectionCard title="Gate pipeline"> <IllustratedEmpty art="gauge" title="No gate evaluation yet" message="Pick a candidate and baseline run above and evaluate the gates. The pipeline (scenario quality → ODD coverage → regression → surrogate safety → evidence) renders here with per-check pass/fail detail." action={ <Button variant="contained" size="small" startIcon={<PlayCircle size={15} />} disabled={!candidate || !baseline || running} onClick={run}> {running ? 'Evaluating…' : 'Evaluate gates'} </Button> } /> </SectionCard> )}
<SectionCard title={ <Box component="span" sx={{ display: 'inline-flex', alignItems: 'center', gap: 0.5 }}> Release policy <InfoDot title="Release policy" detail="The thresholds every gate checks against. Edits persist server-side and are stamped (with values) into each Safety Evidence Package, so a decision is always reproducible against the exact policy used." /> </Box> } action={ <Button size="small" endIcon={showPolicy ? <ChevronUp size={14} /> : <ChevronDown size={14} />} onClick={() => setShowPolicy((s) => !s)}> {showPolicy ? 'Hide editor' : 'Edit policy'} </Button> } > <Collapse in={showPolicy} unmountOnExit> <PolicyEditor onSaved={() => undefined} /> </Collapse> {!showPolicy ? ( <Typography variant="caption" sx={{ color: tokens.color.neutral }}> Thresholds for all five gates (geometric pass rate, coverage rate, regression margins, CSI increase ratio…). Open the editor to tune them; changes apply to the next evaluation. </Typography> ) : null} </SectionCard> </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222/** * Scenario Database browser — Safety Pool-inspired local scenario library: * toggleable filter chips + text search + export bundle, populated from rare * events, discrepancy mining and ODD gap fills. */import { useCallback, useEffect, useMemo, useState } from 'react';import Box from '@mui/material/Box';import Button from '@mui/material/Button';import Chip from '@mui/material/Chip';import Table from '@mui/material/Table';import TableBody from '@mui/material/TableBody';import TableCell from '@mui/material/TableCell';import TableHead from '@mui/material/TableHead';import TableRow from '@mui/material/TableRow';import TextField from '@mui/material/TextField';import Typography from '@mui/material/Typography';import { Download, FolderInput, Search } from 'lucide-react';import { exportScenarios, populateScenarios, searchScenarios, type ScenarioCounts, type ScenarioRecord,} from '../../services/safety';import { downloadJson } from '../../components/safety/shared';import { IllustratedEmpty, PanelSkeleton } from '../../components/visual/Feedback';import { ErrorNote, MetricCard, SectionCard, StatusChip } from '../../components/labeleval/shared';import { tokens } from '../../theme';
function FilterChipRow({ label, options, active, onToggle,}: { label: string; options: Array<{ value: string; count: number }>; active: string | null; onToggle: (v: string | null) => void;}) { if (!options.length) return null; return ( <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, flexWrap: 'wrap' }}> <Typography variant="caption" sx={{ color: tokens.color.neutral, width: 74, flexShrink: 0 }}> {label} </Typography> {options.map((o) => ( <Chip key={o.value} size="small" label={`${o.value} (${o.count})`} onClick={() => onToggle(active === o.value ? null : o.value)} sx={{ height: 22, fontSize: 11, cursor: 'pointer', bgcolor: active === o.value ? tokens.color.infoBg : tokens.color.surfaceRaised, color: active === o.value ? tokens.color.info : tokens.color.textDim, border: `1px solid ${active === o.value ? tokens.color.info : tokens.color.border}`, transition: `all ${tokens.motion.fast}`, }} /> ))} </Box> );}
export default function ScenarioDbPage() { const [counts, setCounts] = useState<ScenarioCounts | null>(null); const [scenarios, setScenarios] = useState<ScenarioRecord[] | null>(null); const [severity, setSeverity] = useState<string | null>(null); const [type, setType] = useState<string | null>(null); const [source, setSource] = useState<string | null>(null); const [text, setText] = useState(''); const [query, setQuery] = useState(''); const [loading, setLoading] = useState(true); const [busy, setBusy] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const refresh = useCallback(() => { setLoading(true); setError(null); searchScenarios({ severity: severity ?? undefined, scenario_type: type ?? undefined, source: source ?? undefined, text: query || undefined, limit: 200, }) .then((r) => { setCounts(r.counts); setScenarios(r.scenarios); }) .catch((e) => setError(e instanceof Error ? e.message : String(e))) .finally(() => setLoading(false)); }, [severity, type, source, query]);
useEffect(refresh, [refresh]);
const populate = () => { setBusy('populate'); populateScenarios() .then(() => refresh()) .catch((e) => setError(e instanceof Error ? e.message : String(e))) .finally(() => setBusy(null)); };
const doExport = () => { setBusy('export'); exportScenarios({ severity: severity ?? undefined, scenario_type: type ?? undefined, source: source ?? undefined, text: query || undefined }) .then((bundle) => downloadJson('scenario-db-export.json', bundle)) .catch((e) => setError(e instanceof Error ? e.message : String(e))) .finally(() => setBusy(null)); };
const opts = useMemo( () => ({ severity: Object.entries(counts?.by_severity ?? {}).map(([value, count]) => ({ value, count })), type: Object.entries(counts?.by_type ?? {}).map(([value, count]) => ({ value, count })), source: Object.entries(counts?.by_source ?? {}).map(([value, count]) => ({ value, count })), }), [counts] );
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> {error ? <ErrorNote error={error} /> : null}
<Box sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap', alignItems: 'center' }}> <MetricCard label="Scenarios" value={counts?.total ?? '—'} info="All scenario records in the local database, across sources (rare-event mining, discrepancy mining, ODD gap fills)." /> <Box sx={{ flex: 1 }} /> <Button variant="outlined" size="small" startIcon={<FolderInput size={15} />} disabled={busy !== null} onClick={populate}> {busy === 'populate' ? 'Importing…' : 'Import rare events'} </Button> <Button variant="outlined" size="small" startIcon={<Download size={15} />} disabled={busy !== null || !scenarios?.length} onClick={doExport}> {busy === 'export' ? 'Exporting…' : 'Export filtered bundle'} </Button> </Box>
<SectionCard title="Filters" help="Chips toggle exact filters over the scenario index; the text box searches descriptions and tags. Filters combine (AND). Export downloads exactly the filtered set as a JSON bundle with provenance." > <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}> <FilterChipRow label="severity" options={opts.severity} active={severity} onToggle={setSeverity} /> <FilterChipRow label="type" options={opts.type} active={type} onToggle={setType} /> <FilterChipRow label="source" options={opts.source} active={source} onToggle={setSource} /> <Box sx={{ display: 'flex', gap: 1, alignItems: 'center', mt: 0.5 }}> <TextField size="small" placeholder="Search descriptions and tags…" value={text} onChange={(e) => setText(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') setQuery(text); }} sx={{ width: 340 }} /> <Button size="small" variant="contained" startIcon={<Search size={14} />} onClick={() => setQuery(text)}> Search </Button> {query ? ( <Chip size="small" label={`text: "${query}"`} onDelete={() => { setQuery(''); setText(''); }} sx={{ height: 22, fontSize: 11 }} /> ) : null} </Box> </Box> </SectionCard>
<SectionCard title={`Scenarios ${scenarios ? `(${scenarios.length}${scenarios.length === 200 ? '+' : ''})` : ''}`}> {loading ? <PanelSkeleton rows={6} header={false} /> : null} {!loading && scenarios && !scenarios.length ? ( <IllustratedEmpty art="data" title={counts && counts.total > 0 ? 'No scenarios match the filters' : 'Scenario database is empty'} message={ counts && counts.total > 0 ? 'Relax a filter chip or clear the text search.' : 'Populate it by importing mined rare events, running discrepancy mining (Safety → Discrepancy), or filling ODD coverage gaps — each source registers scenarios here automatically.' } action={ counts && counts.total === 0 ? ( <Button variant="contained" size="small" startIcon={<FolderInput size={15} />} onClick={populate}> Import rare events </Button> ) : undefined } /> ) : null} {!loading && scenarios?.length ? ( <Table size="small"> <TableHead> <TableRow> <TableCell>ID</TableCell> <TableCell>Type</TableCell> <TableCell>Severity</TableCell> <TableCell>Source</TableCell> <TableCell>ODD tags</TableCell> <TableCell>Description</TableCell> </TableRow> </TableHead> <TableBody> {scenarios.map((s) => ( <TableRow key={s.scenario_id} hover> <TableCell sx={{ fontFamily: 'monospace', fontSize: 11 }}>{s.scenario_id.slice(0, 14)}</TableCell> <TableCell sx={{ fontSize: 12 }}>{s.scenario_type}</TableCell> <TableCell><StatusChip status={s.severity} /></TableCell> <TableCell sx={{ fontSize: 12, color: tokens.color.textDim }}>{s.source}</TableCell> <TableCell> {Object.entries(s.odd_tags ?? {}).map(([k, v]) => ( <Chip key={k} size="small" label={`${k}=${v}`} sx={{ height: 17, fontSize: 9.5, mr: 0.5, bgcolor: tokens.color.surfaceRaised }} /> ))} </TableCell> <TableCell sx={{ fontSize: 12, color: tokens.color.textDim, maxWidth: 420 }}>{s.description}</TableCell> </TableRow> ))} </TableBody> </Table> ) : null} </SectionCard> </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210/** * Semantic Search — neuro-symbolic concept mining over containers or the * scenario DB: concept input, per-stage pipeline explanation, provider * badge, and result cards with per-stage explanations. */import { useCallback, useEffect, useMemo, useState } from 'react';import Box from '@mui/material/Box';import Button from '@mui/material/Button';import Chip from '@mui/material/Chip';import MenuItem from '@mui/material/MenuItem';import TextField from '@mui/material/TextField';import ToggleButton from '@mui/material/ToggleButton';import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';import Typography from '@mui/material/Typography';import { BrainCircuit, Search } from 'lucide-react';import { semanticSearch, type SemanticSearchResponse } from '../../services/safety';import { RunSelect, usePublishedRuns } from '../../components/safety/shared';import { IllustratedEmpty, PanelSkeleton } from '../../components/visual/Feedback';import { ErrorNote, SectionCard } from '../../components/labeleval/shared';import { InfoDot } from '../../components/help/InfoTip';import { useLabelEval } from '../../context/LabelEvalContext';import { tokens } from '../../theme';
const EXAMPLES = [ 'pedestrians at night in the rain', 'occluded cyclists on the highway', 'construction zones with anomalies', 'high-risk intersections at dusk',];
interface ContainerResult { container_id: number; weather?: string; lighting?: string; road_type?: string; scenario?: string; n_objects?: number; fn?: number; fp?: number; anomalies?: number; safety_n?: number; risk_score?: number; score: number; rule_score?: number; embedding_similarity?: number | null; explanations?: { stage1_symbolic?: string; stage2_reasoning?: Array<Record<string, unknown>> }; [k: string]: unknown;}
export default function SemanticSearchPage() { const { navigate } = useLabelEval(); const { runs, error: runsError } = usePublishedRuns(); const [runId, setRunId] = useState<string | null>(null); const [target, setTarget] = useState<'containers' | 'scenarios'>('containers'); const [concept, setConcept] = useState(EXAMPLES[0]); const [llmMode, setLlmMode] = useState<'auto' | 'on' | 'off'>('auto'); const [response, setResponse] = useState<SemanticSearchResponse | null>(null); const [loading, setLoading] = useState(false); const [error, setError] = useState<string | null>(null);
useEffect(() => { if (!runId && runs?.length) setRunId(runs[0].run_id); }, [runs, runId]);
const run = useCallback(() => { if (!concept.trim()) return; setLoading(true); setError(null); semanticSearch({ concept: concept.trim(), target, run: target === 'containers' ? runId ?? undefined : undefined, k: 12, use_llm: llmMode === 'auto' ? null : llmMode === 'on', }) .then(setResponse) .catch((e) => setError(e instanceof Error ? e.message : String(e))) .finally(() => setLoading(false)); }, [concept, target, runId, llmMode]);
const stage1 = response?.stage1 as { applied_filters?: Record<string, unknown>; candidates_before?: number; candidates_after?: number } | undefined; const stage2 = response?.stage2 as { provider?: string; note?: string } | undefined; const hybrid = response?.hybrid as { rule_weight?: number; embedding_weight?: number; embedding_source?: string } | undefined; const llm = response?.llm as { provider?: string; rationale?: string } | null | undefined; const results = (response?.results ?? []) as ContainerResult[]; const maxScore = useMemo(() => Math.max(...results.map((r) => r.score), 0.001), [results]); const providerLabel = llm?.provider ?? stage2?.provider ?? 'offline_deterministic'; const isLlm = providerLabel !== 'offline_deterministic';
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> {runsError ? <ErrorNote error={runsError} /> : null} {error ? <ErrorNote error={error} /> : null}
<SectionCard title="Concept" help="Describe what you want to find in plain language. Stage 1 applies any structured filters symbolically; stage 2 scores candidates with a deterministic reasoning lexicon over their structured evidence, blended with embedding similarity. An LLM (local Ollama), when reachable, adds rationale text but never reorders results — rankings stay reproducible." > <Box sx={{ display: 'flex', gap: 1.5, alignItems: 'center', flexWrap: 'wrap' }}> <TextField size="small" value={concept} onChange={(e) => setConcept(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') run(); }} placeholder="e.g. pedestrians at night in the rain" sx={{ minWidth: 360, flex: '1 1 360px', maxWidth: 560 }} /> <ToggleButtonGroup size="small" exclusive value={target} onChange={(_, v) => v && setTarget(v)}> <ToggleButton value="containers" sx={{ textTransform: 'none', py: 0.4 }}>Containers</ToggleButton> <ToggleButton value="scenarios" sx={{ textTransform: 'none', py: 0.4 }}>Scenario DB</ToggleButton> </ToggleButtonGroup> {target === 'containers' ? <RunSelect label="Run" value={runId} onChange={setRunId} runs={runs} /> : null} <TextField select size="small" label="LLM rationale" value={llmMode} onChange={(e) => setLlmMode(e.target.value as 'auto' | 'on' | 'off')} sx={{ width: 130 }}> <MenuItem value="auto">auto</MenuItem> <MenuItem value="on">force on</MenuItem> <MenuItem value="off">off</MenuItem> </TextField> <Button variant="contained" startIcon={<Search size={15} />} disabled={loading || !concept.trim()} onClick={run}> {loading ? 'Searching…' : 'Search'} </Button> </Box> <Box sx={{ display: 'flex', gap: 0.75, mt: 1, flexWrap: 'wrap' }}> {EXAMPLES.map((ex) => ( <Chip key={ex} size="small" label={ex} onClick={() => setConcept(ex)} sx={{ height: 22, fontSize: 11, cursor: 'pointer', bgcolor: tokens.color.surfaceRaised }} /> ))} </Box> </SectionCard>
{loading ? <PanelSkeleton rows={5} /> : null}
{response && !loading ? ( <> <Box sx={{ display: 'flex', gap: 1, alignItems: 'center', flexWrap: 'wrap' }}> <Chip size="small" label={`stage 1 · symbolic filter: ${stage1?.candidates_before ?? '—'} → ${stage1?.candidates_after ?? '—'} candidates`} sx={{ bgcolor: tokens.color.surfaceRaised, fontFamily: 'monospace', fontSize: 11 }} /> <Chip size="small" icon={<BrainCircuit size={13} />} label={`stage 2 · ${isLlm ? `LLM rationale: ${providerLabel}` : 'deterministic reasoning scorer'}`} sx={{ bgcolor: isLlm ? tokens.color.infoBg : tokens.color.surfaceRaised, color: isLlm ? tokens.color.info : tokens.color.textDim, fontFamily: 'monospace', fontSize: 11 }} /> {hybrid ? ( <Chip size="small" label={`hybrid: ${hybrid.rule_weight} rules + ${hybrid.embedding_weight} embeddings`} sx={{ bgcolor: tokens.color.surfaceRaised, fontFamily: 'monospace', fontSize: 11 }} /> ) : null} <InfoDot title="Provider badge" detail={stage2?.note ?? 'The reasoning stage is deterministic; an LLM only decorates results with rationale text and never changes the ranking.'} /> </Box>
{llm?.rationale ? ( <SectionCard title="LLM rationale" help="Free-text rationale from the local LLM about why these results match the concept. Advisory only — the ranking above it is deterministic."> <Typography variant="body2" sx={{ color: tokens.color.textDim, whiteSpace: 'pre-wrap' }}>{llm.rationale}</Typography> </SectionCard> ) : null}
{!results.length ? ( <IllustratedEmpty art="search" title="No matches" message="Nothing scored above zero for this concept. Try different words (the lexicon knows weather, lighting, road types, classes, risk and anomaly vocabulary) or drop filters." /> ) : ( <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 1.5 }}> {results.map((r, i) => { const dims = [r.weather, r.lighting, r.road_type, r.scenario].filter(Boolean) as string[]; const matched = (r.explanations?.stage2_reasoning ?? []) as Array<{ term?: string; matched?: string; reason?: string; weight?: number; [k: string]: unknown }>; return ( <Box key={`${r.container_id ?? r.scenario_id ?? i}`} sx={{ border: `1px solid ${tokens.color.border}`, borderRadius: 1, p: 1.5, bgcolor: tokens.color.surface, display: 'flex', flexDirection: 'column', gap: 0.75, transition: `border-color ${tokens.motion.fast}`, '&:hover': { borderColor: tokens.color.borderStrong } }}> <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}> <Typography variant="subtitle2" sx={{ fontWeight: 800, fontFamily: 'monospace' }}> {r.container_id !== undefined ? `container #${r.container_id}` : String(r.scenario_id ?? `result ${i + 1}`)} </Typography> <Box sx={{ flex: 1 }} /> <Typography variant="caption" sx={{ fontFamily: 'monospace', color: tokens.color.info, fontWeight: 700 }}> score {r.score.toFixed(3)} </Typography> </Box> <Box sx={{ height: 5, bgcolor: tokens.color.border, borderRadius: 1, overflow: 'hidden' }}> <Box sx={{ height: '100%', width: `${(r.score / maxScore) * 100}%`, bgcolor: tokens.color.info }} /> </Box> <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap' }}> {dims.map((d) => ( <Chip key={d} size="small" label={d} sx={{ height: 18, fontSize: 10, bgcolor: tokens.color.surfaceRaised }} /> ))} {typeof r.n_objects === 'number' ? <Chip size="small" label={`${r.n_objects} objects`} sx={{ height: 18, fontSize: 10, bgcolor: tokens.color.surfaceRaised }} /> : null} {typeof r.fn === 'number' && r.fn > 0 ? <Chip size="small" label={`${r.fn} FN`} sx={{ height: 18, fontSize: 10, bgcolor: tokens.color.dangerBg, color: tokens.color.danger }} /> : null} {typeof r.anomalies === 'number' && r.anomalies > 0 ? <Chip size="small" label={`${r.anomalies} anomalies`} sx={{ height: 18, fontSize: 10, bgcolor: tokens.color.warnBg, color: tokens.color.warn }} /> : null} </Box> <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.25 }}> <Typography variant="caption" sx={{ color: tokens.color.neutral }}> <strong>stage 1:</strong> {r.explanations?.stage1_symbolic ?? '—'} </Typography> <Typography variant="caption" sx={{ color: tokens.color.neutral }}> <strong>stage 2:</strong>{' '} {matched.length ? matched.map((m) => String(m.reason ?? m.matched ?? m.term ?? '')).filter(Boolean).join('; ') : 'embedding similarity only'} </Typography> <Typography variant="caption" sx={{ color: tokens.color.textFaint, fontFamily: 'monospace' }}> rules {r.rule_score?.toFixed(3) ?? '—'} · embedding {r.embedding_similarity != null ? r.embedding_similarity.toFixed(3) : '—'} </Typography> </Box> {r.container_id !== undefined ? ( <Button size="small" sx={{ alignSelf: 'flex-start', textTransform: 'none', fontSize: 11.5, p: 0.25 }} onClick={() => navigate('command', runId)}> Investigate in Command Center → </Button> ) : null} </Box> ); })} </Box> )} </> ) : null} </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271/** * SSAM Conflict Panel — extended surrogate-safety analysis: scenario * selector, conflict list with TTC/PET/DRAC/ΔS/CSI chips, a mini * conflict-point map, and CSI comparison bars. */import { useCallback, useEffect, useMemo, useState } from 'react';import Box from '@mui/material/Box';import Button from '@mui/material/Button';import Chip from '@mui/material/Chip';import MenuItem from '@mui/material/MenuItem';import Slider from '@mui/material/Slider';import TextField from '@mui/material/TextField';import Typography from '@mui/material/Typography';import { PlayCircle } from 'lucide-react';import { analyzeSsam, type SsamAnalysis, type SsamConflict } from '../../services/safety';import { ChartSkeleton, IllustratedEmpty } from '../../components/visual/Feedback';import { ErrorNote, HBar, MetricCard, SectionCard } from '../../components/labeleval/shared';import { InfoDot } from '../../components/help/InfoTip';import { tokens } from '../../theme';
const SCENARIOS = [ { value: 'mixed', label: 'Mixed traffic (all conflict types)' }, { value: 'crossing', label: 'Crossing conflict (intersection)' }, { value: 'rear_end', label: 'Rear-end conflict (car following)' }, { value: 'lane_change', label: 'Lane change conflict' },];
const TYPE_COLORS: Record<string, string> = { crossing: '#ef5350', rear_end: '#ffa726', lane_change: '#4fc3f7',};
function severityColor(c: SsamConflict): string { if (c.csi >= 2 || (c.min_ttc_s !== null && c.min_ttc_s < 0.5)) return tokens.color.danger; if (c.csi >= 0.75 || (c.min_ttc_s !== null && c.min_ttc_s < 1.0)) return '#ffa726'; return tokens.color.warn;}
function MeasureChip({ label, value, unit, term, danger }: { label: string; value: number | null; unit: string; term: string; danger?: boolean }) { return ( <Chip size="small" label={ <span> {label} <strong>{value === null ? '—' : value.toFixed(2)}</strong> {value === null ? '' : unit} </span> } title={term} sx={{ height: 20, fontSize: 10.5, fontFamily: 'monospace', bgcolor: danger ? tokens.color.dangerBg : tokens.color.surfaceRaised, color: danger ? tokens.color.danger : tokens.color.textDim, border: `1px solid ${danger ? tokens.color.danger : tokens.color.border}`, }} /> );}
// ------------------------------------------------------------ conflict map
function ConflictMap({ conflicts, selected, onSelect }: { conflicts: SsamConflict[]; selected: number | null; onSelect: (i: number) => void }) { const pts = conflicts.filter((c) => c.conflict_point); const xs = pts.map((c) => c.conflict_point![0]); const ys = pts.map((c) => c.conflict_point![1]); const pad = 8; const xLo = Math.min(...xs, -10) - pad; const xHi = Math.max(...xs, 10) + pad; const yLo = Math.min(...ys, -10) - pad; const yHi = Math.max(...ys, 10) + pad; const W = 320; const H = 240; const sx = (x: number) => ((x - xLo) / (xHi - xLo)) * (W - 20) + 10; const sy = (y: number) => H - (((y - yLo) / (yHi - yLo)) * (H - 20) + 10);
return ( <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{ maxWidth: 380, display: 'block' }}> <rect x={0} y={0} width={W} height={H} rx={6} fill={tokens.color.surfaceSunken} stroke={tokens.color.border} /> {/* road cross reference */} <line x1={sx(xLo + pad)} y1={sy(0)} x2={sx(xHi - pad)} y2={sy(0)} stroke={tokens.color.borderStrong} strokeDasharray="4 4" /> <line x1={sx(0)} y1={sy(yLo + pad)} x2={sx(0)} y2={sy(yHi - pad)} stroke={tokens.color.borderStrong} strokeDasharray="4 4" /> <text x={sx(xHi - pad) - 2} y={sy(0) - 4} textAnchor="end" fontSize={8.5} fill={tokens.color.textFaint}>x (m)</text> <text x={sx(0) + 4} y={sy(yHi - pad) + 10} fontSize={8.5} fill={tokens.color.textFaint}>y (m)</text> {conflicts.map((c, i) => { if (!c.conflict_point) return null; const r = 4 + Math.min(10, c.csi * 3); const isSel = selected === i; return ( <g key={i} onClick={() => onSelect(i)} style={{ cursor: 'pointer' }}> <circle cx={sx(c.conflict_point[0])} cy={sy(c.conflict_point[1])} r={r} fill={TYPE_COLORS[c.conflict_type] ?? tokens.color.neutral} opacity={isSel ? 0.95 : 0.55} stroke={isSel ? '#fff' : 'none'} strokeWidth={1.5} > <title>{`${c.conflict_type}: ${c.vehicle_a} vs ${c.vehicle_b} · CSI ${c.csi.toFixed(2)}`}</title> </circle> {isSel ? ( <text x={sx(c.conflict_point[0])} y={sy(c.conflict_point[1]) - r - 4} textAnchor="middle" fontSize={9} fontWeight={700} fill="#fff"> CSI {c.csi.toFixed(2)} </text> ) : null} </g> ); })} </svg> );}
// ------------------------------------------------------------ page
export default function SsamConflictPage() { const [scenario, setScenario] = useState('mixed'); const [seed, setSeed] = useState(0); const [reaction, setReaction] = useState(0.6); const [analysis, setAnalysis] = useState<SsamAnalysis | null>(null); const [loading, setLoading] = useState(false); const [error, setError] = useState<string | null>(null); const [selected, setSelected] = useState<number | null>(null);
const run = useCallback(() => { setLoading(true); setError(null); analyzeSsam({ scenario, seed, reaction_delay_s: reaction }) .then((a) => { setAnalysis(a); setSelected(a.conflicts.length ? 0 : null); }) .catch((e) => setError(e instanceof Error ? e.message : String(e))) .finally(() => setLoading(false)); }, [scenario, seed, reaction]);
useEffect(run, []); // eslint-disable-line react-hooks/exhaustive-deps
const sortedByCsi = useMemo( () => (analysis ? [...analysis.conflicts].map((c, i) => ({ c, i })).sort((a, b) => b.c.csi - a.c.csi) : []), [analysis] ); const agg = analysis?.aggregate; const glossary = analysis?.measures_glossary ?? {};
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> {error ? <ErrorNote error={error} /> : null}
<Box sx={{ display: 'flex', gap: 2, alignItems: 'center', flexWrap: 'wrap' }}> <TextField select size="small" label="Scenario" value={scenario} onChange={(e) => setScenario(e.target.value)} sx={{ minWidth: 260 }}> {SCENARIOS.map((s) => ( <MenuItem key={s.value} value={s.value}>{s.label}</MenuItem> ))} </TextField> <TextField size="small" label="Seed" type="number" value={seed} onChange={(e) => setSeed(Number(e.target.value) || 0)} sx={{ width: 90 }} /> <Box sx={{ width: 200 }}> <Typography variant="caption" sx={{ color: tokens.color.neutral }}> Reaction delay: {reaction.toFixed(1)}s <InfoDot title="Reaction delay" detail="Simulated driver/AV reaction latency injected into the generated trajectories — longer delays produce more severe conflicts." size={11} /> </Typography> <Slider size="small" value={reaction} min={0} max={2} step={0.1} onChange={(_, v) => setReaction(v as number)} sx={{ py: 0.5 }} /> </Box> <Button variant="contained" startIcon={<PlayCircle size={16} />} disabled={loading} onClick={run}> {loading ? 'Analyzing…' : 'Analyze'} </Button> {analysis?.generated ? ( <Chip size="small" label="simulated trajectories" sx={{ bgcolor: tokens.color.warnBg, color: tokens.color.warn, fontSize: 10.5 }} /> ) : null} </Box>
{loading && !analysis ? <ChartSkeleton height={200} /> : null}
{agg ? ( <Box sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap' }}> <MetricCard label="Conflicts" value={agg.num_conflicts} sub={Object.entries(agg.by_type).map(([t, n]) => `${t}: ${n}`).join(' · ')} info="Vehicle-pair interactions crossing the surrogate-safety thresholds (TTC/PET) during the observed window." /> <MetricCard label="Aggregate CSI" value={agg.aggregate_csi.toFixed(2)} sub={`mean ${agg.mean_csi_per_conflict.toFixed(2)} per conflict`} accent={agg.aggregate_csi > 3 ? tokens.color.danger : tokens.color.warn} info={glossary.CSI ?? 'Conflict Severity Index'} /> <MetricCard label="Min TTC" value={agg.min_ttc_s !== null ? `${agg.min_ttc_s.toFixed(2)}s` : '—'} accent={agg.min_ttc_s !== null && agg.min_ttc_s < 1 ? tokens.color.danger : undefined} info={glossary.TTC ?? 'Time-to-collision'} /> <MetricCard label="Min PET" value={agg.min_pet_s !== null ? `${agg.min_pet_s.toFixed(2)}s` : '—'} info={glossary.PET ?? 'Post-encroachment time'} /> <MetricCard label="Max DRAC" value={agg.max_drac_mps2 !== null ? `${agg.max_drac_mps2.toFixed(1)} m/s²` : '—'} info={glossary.DRAC ?? 'Deceleration rate to avoid crash'} /> </Box> ) : null}
{analysis && !analysis.conflicts.length ? ( <SectionCard title="Conflicts"> <IllustratedEmpty art="map" title="No conflicts detected" message="The generated trajectories never crossed the TTC/PET thresholds. Try a different scenario, seed, or a longer reaction delay." /> </SectionCard> ) : null}
{analysis && analysis.conflicts.length ? ( <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}> <SectionCard title="Conflict list" sx={{ flex: '2 1 480px' }} help="Each row is one vehicle-pair conflict with its surrogate measures. Red chips mark values past critical thresholds (TTC < 1.5s is the conflict definition; < 1s is severe). Click a row to highlight it on the map." > <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}> {analysis.conflicts.map((c, i) => ( <Box key={i} onClick={() => setSelected(i)} sx={{ p: 1.25, border: `1px solid ${selected === i ? tokens.color.info : tokens.color.border}`, borderLeft: `3px solid ${severityColor(c)}`, borderRadius: 1, cursor: 'pointer', bgcolor: selected === i ? tokens.color.surfaceRaised : 'transparent', transition: `border-color ${tokens.motion.fast}, background-color ${tokens.motion.fast}`, }} > <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5, flexWrap: 'wrap' }}> <Chip size="small" label={c.conflict_type} sx={{ height: 18, fontSize: 10, fontWeight: 700, bgcolor: TYPE_COLORS[c.conflict_type] ?? tokens.color.neutral, color: '#0e1114' }} /> <Typography variant="caption" sx={{ fontFamily: 'monospace', color: tokens.color.textDim }}> {c.vehicle_a} × {c.vehicle_b} </Typography> <Typography variant="caption" sx={{ color: tokens.color.neutral }}> t = {c.t_start_s.toFixed(1)}–{c.t_end_s.toFixed(1)}s · P(collision) {(c.collision_probability * 100).toFixed(0)}% </Typography> </Box> <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap' }}> <MeasureChip label="TTC" value={c.min_ttc_s} unit="s" term={glossary.TTC ?? ''} danger={c.min_ttc_s !== null && c.min_ttc_s < 1.0} /> <MeasureChip label="PET" value={c.pet_s} unit="s" term={glossary.PET ?? ''} danger={c.pet_s !== null && c.pet_s < 1.0} /> <MeasureChip label="DRAC" value={c.max_drac_mps2} unit="m/s²" term={glossary.DRAC ?? ''} danger={c.max_drac_mps2 !== null && c.max_drac_mps2 > 6} /> <MeasureChip label="ΔS" value={c.delta_s_mps} unit="m/s" term={glossary.DeltaS ?? ''} /> <MeasureChip label="CSI" value={c.csi} unit="" term={glossary.CSI ?? ''} danger={c.csi >= 2} /> </Box> </Box> ))} </Box> </SectionCard>
<Box sx={{ flex: '1 1 340px', display: 'flex', flexDirection: 'column', gap: 2 }}> <SectionCard title="Conflict-point map" help="Where each conflict happens in the scene (meters). Marker color = conflict type, size = CSI severity. Click a marker to select the conflict." > <ConflictMap conflicts={analysis.conflicts} selected={selected} onSelect={setSelected} /> <Box sx={{ display: 'flex', gap: 1, mt: 1 }}> {Object.entries(TYPE_COLORS).map(([t, color]) => ( <Box key={t} sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}> <Box sx={{ width: 9, height: 9, borderRadius: '50%', bgcolor: color }} /> <Typography variant="caption" sx={{ color: tokens.color.neutral, fontSize: 10.5 }}>{t}</Typography> </Box> ))} </Box> </SectionCard>
<SectionCard title="CSI comparison" help="Conflict Severity Index per conflict, sorted — CSI integrates relative speed, collision probability and exposure time, so it ranks conflicts more faithfully than TTC alone." > {sortedByCsi.map(({ c, i }) => ( <HBar key={i} label={`${c.conflict_type} · ${c.vehicle_b.split(':').pop()}`} value={c.csi} max={Math.max(...analysis.conflicts.map((x) => x.csi), 0.001)} color={selected === i ? tokens.color.info : severityColor(c)} valueLabel={c.csi.toFixed(3)} /> ))} </SectionCard> </Box> </Box> ) : null} </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536/** * My Dashboard — WYSIWYG dashboard composer. * * Users drag live widgets (seqeval verdict, ODD coverage mini-map, engine * comparison, review queue, pipeline counters, scenario DB, calibration * status) onto a 12-column grid: drag to move, grip to resize, × to remove, * with an edit/view mode toggle. The layout persists via localStorage plus * the optional /api/studio-ux backend (see services/studioux.ts). */import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';import Box from '@mui/material/Box';import Button from '@mui/material/Button';import Chip from '@mui/material/Chip';import IconButton from '@mui/material/IconButton';import Switch from '@mui/material/Switch';import Typography from '@mui/material/Typography';import { ArrowUpRight, GripVertical, Plus, RotateCcw, X } from 'lucide-react';import { useLabelEval, type PageId } from '../../context/LabelEvalContext';import { loadLayout, saveLayout } from '../../services/studioux';import { listSeqRuns, type SeqRunState } from '../../services/seqeval';import { getBevReport, type BevReport } from '../../services/bevfusion';import { getCalibrationStatus, getOddCoverage, searchScenarios, type CalibrationResult, type OddCoverageResponse, type ScenariosResponse,} from '../../services/safety';import { getRuns } from '../../services/megaeval';import { PanelSkeleton, IllustratedEmpty } from '../../components/visual/Feedback';import { fmtInt, fmtPct } from '../../components/labeleval/shared';import { tokens, verdictColor } from '../../theme';
// ---------------------------------------------------------------- layout model
interface WidgetLayout { uid: string; type: WidgetType; x: number; // column 0..11 y: number; // row w: number; // columns h: number; // rows}
type WidgetType = | 'seqeval-verdict' | 'odd-mini' | 'engine-compare' | 'review-queue' | 'pipeline-counters' | 'scenario-db' | 'calibration-status';
const COLS = 12;const ROW_H = 84;const GAP = 10;const LAYOUT_KEY = 'my-dashboard-layout';
interface WidgetMeta { title: string; source: PageId; sourceLabel: string; defaultW: number; defaultH: number; description: string;}
const WIDGETS: Record<WidgetType, WidgetMeta> = { 'seqeval-verdict': { title: 'Sequential regression verdict', source: 'seqeval', sourceLabel: 'Sequential Regression', defaultW: 4, defaultH: 2, description: 'Latest sequential run: decision, gate and stopping reason.' }, 'odd-mini': { title: 'ODD coverage', source: 'safety-odd', sourceLabel: 'ODD Coverage', defaultW: 4, defaultH: 3, description: 'Coverage rate + mini heatmap of class × condition cells.' }, 'engine-compare': { title: 'Perception engine comparison', source: 'bevfusion', sourceLabel: 'Perception Engines', defaultW: 4, defaultH: 2, description: 'BEV-fusion vs camera baseline: recommendation + headline deltas.' }, 'review-queue': { title: 'Review queue', source: 'review', sourceLabel: 'Human Review', defaultW: 2, defaultH: 2, description: 'Live human-review queue depth and alert count.' }, 'pipeline-counters': { title: 'Pipeline counters', source: 'overview', sourceLabel: 'Overview', defaultW: 4, defaultH: 2, description: 'Live processed / auto-labeled / verified counters.' }, 'scenario-db': { title: 'Scenario database', source: 'safety-scenarios', sourceLabel: 'Scenario DB', defaultW: 2, defaultH: 2, description: 'Stored test scenarios by severity.' }, 'calibration-status': { title: 'Calibration status', source: 'safety-calibration', sourceLabel: 'Calibration', defaultW: 3, defaultH: 2, description: 'Latest camera–LiDAR extrinsic validation verdict.' },};
const STARTER_LAYOUT: WidgetLayout[] = [ { uid: 'w1', type: 'seqeval-verdict', x: 0, y: 0, w: 4, h: 2 }, { uid: 'w2', type: 'engine-compare', x: 4, y: 0, w: 4, h: 2 }, { uid: 'w3', type: 'review-queue', x: 8, y: 0, w: 2, h: 2 }, { uid: 'w4', type: 'odd-mini', x: 0, y: 2, w: 4, h: 3 }, { uid: 'w5', type: 'pipeline-counters', x: 4, y: 2, w: 4, h: 2 },];
let uidSeq = 0;function newUid(): string { uidSeq += 1; return `w-${Date.now().toString(36)}-${uidSeq}`;}
// ---------------------------------------------------------------- widgets
function Stat({ label, value, color }: { label: string; value: ReactNode; color?: string }) { return ( <Box sx={{ minWidth: 76 }}> <Typography variant="caption" sx={{ color: tokens.color.neutral, display: 'block', fontSize: 10.5 }}> {label} </Typography> <Typography variant="h6" sx={{ fontWeight: 800, fontFamily: 'monospace', fontSize: 18, color: color ?? tokens.color.text }}> {value} </Typography> </Box> );}
function useAsync<T>(fn: () => Promise<T>): { data: T | null; error: string | null } { const [data, setData] = useState<T | null>(null); const [error, setError] = useState<string | null>(null); const ref = useRef(fn); ref.current = fn; useEffect(() => { let cancelled = false; ref .current() .then((d) => { if (!cancelled) setData(d); }) .catch((e) => { if (!cancelled) setError(e instanceof Error ? e.message : String(e)); }); return () => { cancelled = true; }; }, []); return { data, error };}
function WidgetError({ error }: { error: string }) { return ( <Typography variant="caption" sx={{ color: tokens.color.warn }}> Data unavailable: {error.slice(0, 120)} </Typography> );}
function SeqevalWidget() { const { data, error } = useAsync(async () => { const { runs } = await listSeqRuns(); const done = runs.filter((r) => r.status === 'done').sort((a, b) => (b.created_at ?? '').localeCompare(a.created_at ?? '')); return (done[0] ?? runs[0] ?? null) as SeqRunState | null; }); if (error) return <WidgetError error={error} />; if (data === null) return <PanelSkeleton rows={2} header={false} />; if (!data) return <Typography variant="caption" sx={{ color: tokens.color.neutral }}>No sequential runs yet — launch one from the Sequential Regression page.</Typography>; const color = verdictColor(data.decision); return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.75 }}> <Box sx={{ display: 'flex', gap: 0.75, alignItems: 'center', flexWrap: 'wrap' }}> <Chip size="small" label={(data.decision ?? data.status).toUpperCase()} sx={{ fontWeight: 900, bgcolor: `${color}22`, color, border: `1.5px solid ${color}` }} /> {data.gate ? <Chip size="small" label={`gate: ${data.gate}`} sx={{ height: 20, fontSize: 10.5 }} /> : null} </Box> <Typography variant="caption" sx={{ color: tokens.color.textDim }}> {data.message ?? data.stopping_reason ?? `run ${data.run_id}`} </Typography> {data.budget ? ( <Typography variant="caption" sx={{ color: tokens.color.neutral, fontFamily: 'monospace', fontSize: 10.5 }}> {fmtInt((data.budget as { used?: number }).used ?? 0)} samples used </Typography> ) : null} </Box> );}
function OddMiniWidget() { const { data, error } = useAsync(async () => { const { runs } = await getRuns(); const pub = runs.filter((r) => r.status === 'published').sort((a, b) => (b.created_at ?? '').localeCompare(a.created_at ?? '')); if (!pub.length) return null; return getOddCoverage(pub[0].run_id, null, true); }); if (error) return <WidgetError error={error} />; if (data === null) return <PanelSkeleton rows={3} header={false} />; if (!data) return <Typography variant="caption" sx={{ color: tokens.color.neutral }}>No published evaluation run yet.</Typography>; const d = data as OddCoverageResponse; const cells = d.cells ?? []; return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}> <Box sx={{ display: 'flex', gap: 2 }}> <Stat label="coverage" value={fmtPct(d.summary.coverage_rate)} color={d.summary.coverage_rate >= 0.8 ? tokens.color.success : tokens.color.warn} /> <Stat label="gaps" value={d.summary.gap_cells} color={d.summary.gap_cells > 0 ? tokens.color.danger : tokens.color.success} /> <Stat label="recall" value={fmtPct(d.summary.overall_recall)} /> </Box> <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(14px, 1fr))', gap: '2px' }}> {cells.slice(0, 96).map((c) => ( <Box key={c.cell_id} title={`${Object.values(c.cell).join(' × ')} — ${c.n} samples${c.recall !== null ? `, recall ${fmtPct(c.recall)}` : ''}`} sx={{ height: 14, borderRadius: '2px', bgcolor: c.n === 0 ? tokens.color.surfaceRaised : c.is_gap ? tokens.color.danger : c.adequate ? tokens.color.success : tokens.color.warn, opacity: c.n === 0 ? 0.45 : 0.85, }} /> ))} </Box> </Box> );}
function EngineCompareWidget() { const { data, error } = useAsync(() => getBevReport().catch(() => null as BevReport | null)); if (error) return <WidgetError error={error} />; if (data === null) return <PanelSkeleton rows={2} header={false} />; if (!data) return <Typography variant="caption" sx={{ color: tokens.color.neutral }}>No comparison yet — run one on the Perception Engines page.</Typography>; const color = verdictColor(data.recommendation); const top = data.headline_deltas.filter((h) => ['recall', 'safety_recall', 'position_error_m'].includes(h.metric)); return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.75 }}> <Chip size="small" label={data.recommendation.replace(/_/g, ' ')} sx={{ alignSelf: 'flex-start', fontWeight: 900, bgcolor: `${color}22`, color, border: `1.5px solid ${color}` }} /> <Box sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap' }}> {top.map((h) => ( <Stat key={h.metric} label={h.metric.replace(/_/g, ' ')} value={`${h.delta >= 0 ? '+' : ''}${Math.abs(h.baseline) <= 1 && h.metric !== 'position_error_m' ? `${(h.delta * 100).toFixed(1)}pp` : h.delta.toFixed(2)}`} color={h.improved ? tokens.color.success : tokens.color.danger} /> ))} </Box> </Box> );}
function ReviewQueueWidget() { const { stream } = useLabelEval(); const review = stream?.pipeline.review_queue_count ?? null; const alerts = stream?.alerts_count ?? null; if (review === null) return <PanelSkeleton rows={1} header={false} />; return ( <Box sx={{ display: 'flex', gap: 2 }}> <Stat label="in queue" value={fmtInt(review)} color={review > 0 ? '#e65100' : tokens.color.success} /> <Stat label="alerts" value={fmtInt(alerts ?? 0)} color={(alerts ?? 0) > 0 ? tokens.color.danger : tokens.color.success} /> </Box> );}
function PipelineCountersWidget() { const { stream } = useLabelEval(); const c = stream?.pipeline.counters ?? null; if (!c) return <PanelSkeleton rows={1} header={false} />; return ( <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}> <Stat label="processed" value={fmtInt(c.frames_processed ?? 0)} /> <Stat label="auto-labeled" value={fmtInt(c.auto_labeled ?? 0)} /> <Stat label="verified" value={fmtInt(c.verified ?? 0)} color={tokens.color.success} /> <Stat label="flagged" value={fmtInt(c.flagged ?? 0)} color={(c.flagged ?? 0) > 0 ? tokens.color.warn : undefined} /> </Box> );}
function ScenarioDbWidget() { const { data, error } = useAsync(() => searchScenarios({}) as Promise<ScenariosResponse>); if (error) return <WidgetError error={error} />; if (data === null) return <PanelSkeleton rows={1} header={false} />; const bySev = data.counts?.by_severity ?? {}; return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}> <Stat label="scenarios" value={fmtInt(data.counts.total)} /> <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap' }}> {Object.entries(bySev).map(([sev, n]) => ( <Chip key={sev} size="small" label={`${sev} ${n}`} sx={{ height: 18, fontSize: 9.5, bgcolor: tokens.color.surfaceRaised }} /> ))} </Box> </Box> );}
function CalibrationWidget() { const { data, error } = useAsync(() => getCalibrationStatus().catch(() => null as CalibrationResult | null)); if (error) return <WidgetError error={error} />; if (data === null) return <PanelSkeleton rows={1} header={false} />; if (!data || !data.status) return <Typography variant="caption" sx={{ color: tokens.color.neutral }}>No validation run yet.</Typography>; const color = verdictColor(data.status); return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.75 }}> <Chip size="small" label={data.status} sx={{ alignSelf: 'flex-start', fontWeight: 900, bgcolor: `${color}22`, color, border: `1.5px solid ${color}` }} /> <Typography variant="caption" sx={{ color: tokens.color.textDim }}> {(data.checks ?? []).filter((c) => c.passed).length}/{(data.checks ?? []).length} checks passing </Typography> </Box> );}
function WidgetBody({ type }: { type: WidgetType }) { switch (type) { case 'seqeval-verdict': return <SeqevalWidget />; case 'odd-mini': return <OddMiniWidget />; case 'engine-compare': return <EngineCompareWidget />; case 'review-queue': return <ReviewQueueWidget />; case 'pipeline-counters': return <PipelineCountersWidget />; case 'scenario-db': return <ScenarioDbWidget />; case 'calibration-status': return <CalibrationWidget />; default: return null; }}
// ---------------------------------------------------------------- grid frame
interface DragState { uid: string; mode: 'move' | 'resize'; startX: number; startY: number; orig: WidgetLayout;}
export default function MyDashboardPage() { const { navigate } = useLabelEval(); const [layout, setLayout] = useState<WidgetLayout[] | null>(null); const [edit, setEdit] = useState(false); const [drag, setDrag] = useState<DragState | null>(null); const gridRef = useRef<HTMLDivElement | null>(null); const loaded = useRef(false);
useEffect(() => { loadLayout<WidgetLayout[]>(LAYOUT_KEY).then((saved) => { setLayout(saved && Array.isArray(saved) && saved.length ? saved : STARTER_LAYOUT); loaded.current = true; }); }, []);
useEffect(() => { if (loaded.current && layout) saveLayout(LAYOUT_KEY, layout); }, [layout]);
const colW = useCallback((): number => { const el = gridRef.current; if (!el) return 90; return (el.clientWidth - GAP * (COLS - 1)) / COLS; }, []);
const onPointerMove = useCallback( (e: React.PointerEvent) => { if (!drag) return; const cw = colW(); const dxCols = Math.round((e.clientX - drag.startX) / (cw + GAP)); const dyRows = Math.round((e.clientY - drag.startY) / (ROW_H + GAP)); setLayout((ls) => (ls ?? []).map((wl) => { if (wl.uid !== drag.uid) return wl; if (drag.mode === 'move') { return { ...wl, x: Math.max(0, Math.min(COLS - wl.w, drag.orig.x + dxCols)), y: Math.max(0, drag.orig.y + dyRows), }; } return { ...wl, w: Math.max(2, Math.min(COLS - wl.x, drag.orig.w + dxCols)), h: Math.max(1, drag.orig.h + dyRows), }; }) ); }, [drag, colW] );
const startDrag = (e: React.PointerEvent, wl: WidgetLayout, mode: 'move' | 'resize') => { e.preventDefault(); (e.currentTarget as Element).setPointerCapture(e.pointerId); setDrag({ uid: wl.uid, mode, startX: e.clientX, startY: e.clientY, orig: wl }); };
const addWidget = (type: WidgetType) => { const meta = WIDGETS[type]; const maxY = (layout ?? []).reduce((m, wl) => Math.max(m, wl.y + wl.h), 0); setLayout((ls) => [...(ls ?? []), { uid: newUid(), type, x: 0, y: maxY, w: meta.defaultW, h: meta.defaultH }]); };
const inUse = useMemo(() => new Set((layout ?? []).map((wl) => wl.type)), [layout]);
if (!layout) return <PanelSkeleton rows={5} />;
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}> <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, flexWrap: 'wrap' }}> <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}> <Switch size="small" checked={edit} onChange={(e) => setEdit(e.target.checked)} inputProps={{ 'aria-label': 'Edit mode' }} /> <Typography variant="body2" sx={{ fontWeight: 700, color: edit ? tokens.color.info : tokens.color.textDim }}> {edit ? 'Edit mode — drag, resize, remove' : 'View mode'} </Typography> </Box> {edit ? ( <Button size="small" startIcon={<RotateCcw size={14} />} onClick={() => setLayout(STARTER_LAYOUT)}> Reset to starter layout </Button> ) : null} <Typography variant="caption" sx={{ color: tokens.color.neutral, ml: 'auto' }}> {layout.length} widget{layout.length === 1 ? '' : 's'} · layout saved automatically </Typography> </Box>
{edit ? ( <Box sx={{ display: 'flex', gap: 0.75, flexWrap: 'wrap', p: 1.25, border: `1px dashed ${tokens.color.borderStrong}`, borderRadius: 1, bgcolor: tokens.color.surfaceSunken, alignItems: 'center' }}> <Typography variant="caption" sx={{ color: tokens.color.neutral, mr: 0.5 }}> Widget palette: </Typography> {(Object.keys(WIDGETS) as WidgetType[]).map((t) => ( <Chip key={t} size="small" icon={<Plus size={13} />} label={WIDGETS[t].title} onClick={() => addWidget(t)} title={WIDGETS[t].description} sx={{ cursor: 'pointer', bgcolor: inUse.has(t) ? tokens.color.surfaceRaised : tokens.color.infoBg, color: inUse.has(t) ? tokens.color.textDim : tokens.color.info, border: `1px solid ${inUse.has(t) ? tokens.color.border : tokens.color.info}`, }} /> ))} </Box> ) : null}
{layout.length === 0 ? ( <IllustratedEmpty art="canvas" title="An empty dashboard" message="Switch to edit mode and add widgets from the palette — every widget shows live data from its source page." action={ <Button variant="outlined" size="small" onClick={() => setEdit(true)}> Enter edit mode </Button> } /> ) : null}
<Box ref={gridRef} onPointerMove={onPointerMove} onPointerUp={() => setDrag(null)} sx={{ display: 'grid', gridTemplateColumns: `repeat(${COLS}, 1fr)`, gridAutoRows: `${ROW_H}px`, gap: `${GAP}px`, touchAction: drag ? 'none' : undefined, }} > {layout.map((wl) => { const meta = WIDGETS[wl.type]; const dragging = drag?.uid === wl.uid; return ( <Box key={wl.uid} sx={{ gridColumn: `${wl.x + 1} / span ${wl.w}`, gridRow: `${wl.y + 1} / span ${wl.h}`, border: `1px solid ${dragging ? tokens.color.info : edit ? tokens.color.borderStrong : tokens.color.border}`, borderRadius: 1.5, bgcolor: tokens.color.surface, display: 'flex', flexDirection: 'column', overflow: 'hidden', position: 'relative', boxShadow: dragging ? tokens.elevation.overlay : undefined, transition: dragging ? 'none' : `border-color ${tokens.motion.fast}, box-shadow ${tokens.motion.fast}`, }} > <Box onPointerDown={edit ? (e) => startDrag(e, wl, 'move') : undefined} sx={{ display: 'flex', alignItems: 'center', gap: 0.5, px: 1, py: 0.5, borderBottom: `1px solid ${tokens.color.border}`, bgcolor: tokens.color.surfaceSunken, cursor: edit ? 'grab' : 'default', userSelect: 'none', flexShrink: 0, }} > {edit ? <GripVertical size={13} color={tokens.color.textFaint} /> : null} <Typography variant="caption" sx={{ fontWeight: 700, color: tokens.color.textDim, flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}> {meta.title} </Typography> {!edit ? ( <IconButton size="small" onClick={() => navigate(meta.source)} title={`Open ${meta.sourceLabel}`} sx={{ p: 0.25 }}> <ArrowUpRight size={13} /> </IconButton> ) : ( <IconButton size="small" onClick={() => setLayout((ls) => (ls ?? []).filter((x) => x.uid !== wl.uid))} title="Remove widget" sx={{ p: 0.25, '&:hover': { color: tokens.color.danger } }}> <X size={13} /> </IconButton> )} </Box> <Box sx={{ p: 1.25, flex: 1, minHeight: 0, overflow: 'auto' }}> <WidgetBody type={wl.type} /> </Box> {edit ? ( <Box onPointerDown={(e) => startDrag(e, wl, 'resize')} sx={{ position: 'absolute', right: 0, bottom: 0, width: 18, height: 18, cursor: 'nwse-resize', borderRight: `3px solid ${tokens.color.info}`, borderBottom: `3px solid ${tokens.color.info}`, borderBottomRightRadius: 6, opacity: 0.7, '&:hover': { opacity: 1 }, }} /> ) : null} </Box> ); })} </Box> {edit ? ( <Typography variant="caption" sx={{ color: tokens.color.neutral }}> Drag a widget by its header to move it on the grid; drag the blue corner grip to resize; × removes. Widgets show live data in both modes. </Typography> ) : null} </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367/** * Pipeline Builder — direct-manipulation node-graph editor over the platform's * pipeline architecture. The as-built pipeline loads read-only (with live * service status where available); the user edits a clearly-labeled DRAFT: * drag stages, draw/remove edges, enable/disable stages, and read a live * "what will run" summary (topological order, orphans, cycles, diff vs * as-built). Nothing here executes — it is an explorer + what-if composer. */import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import Alert from '@mui/material/Alert';import Box from '@mui/material/Box';import Button from '@mui/material/Button';import Chip from '@mui/material/Chip';import Typography from '@mui/material/Typography';import { Download, RotateCcw, Unlink } from 'lucide-react';import NodeCanvas, { type GraphEdge, type GraphNode } from '../../components/visual/NodeCanvas';import InspectorPanel, { type InspectorField } from '../../components/visual/InspectorPanel';import { getPipeline } from '../../services/labeleval';import type { PipelineStateResponse } from '../../types/labeleval';import { loadLayout, saveLayout } from '../../services/studioux';import { SectionCard } from '../../components/labeleval/shared';import { useLabelEval } from '../../context/LabelEvalContext';import { tokens } from '../../theme';
// ------------------------------------------------------- as-built definition// Mirrors the read-only Pipeline Architecture page's graph (kept local so this// page never touches that file).
interface StageDef { id: string; label: string; x: number; y: number; role: string; aliases: string[];}
const AS_BUILT_STAGES: StageDef[] = [ { id: 'input', label: 'Input', x: 90, y: 240, role: 'Ingests raw sensor data: camera frames, LiDAR sweeps, radar, ego-pose.', aliases: ['input', 'ingest', 'sensor'] }, { id: 'autolabels', label: 'Auto Labels', x: 250, y: 240, role: 'The current model auto-labels each frame — candidates, not truth.', aliases: ['auto_label', 'autolabel', 'labeler'] }, { id: 'queue', label: 'Queue', x: 410, y: 240, role: 'Message queue distributing labeled frames to the evaluation engines.', aliases: ['queue', 'broker'] }, { id: 'anomaly', label: 'Anomaly Detection', x: 570, y: 100, role: 'Ensemble anomaly scoring: geometric plausibility, point statistics, temporal consistency.', aliases: ['anomaly'] }, { id: 'regression', label: 'Regression', x: 570, y: 240, role: 'Compares the labeling model against its registered baseline.', aliases: ['regression'] }, { id: 'grader', label: 'Grader', x: 570, y: 380, role: 'Independent grader models score each label; consensus is a confidence signal.', aliases: ['grader', 'consensus'] }, { id: 'validation', label: 'Quality Validation', x: 740, y: 240, role: 'The quality gate: combines engine evidence, applies policy thresholds, produces triage decisions.', aliases: ['validation', 'quality', 'gate'] }, { id: 'rare', label: 'Rare Events', x: 910, y: 100, role: 'Mines the long tail: high-rarity, high-severity events surfaced for review and training.', aliases: ['rare'] }, { id: 'autograded', label: 'Auto-Graded', x: 910, y: 240, role: 'Labels that passed every gate with margin — verified without human involvement.', aliases: ['auto_grad', 'triage'] }, { id: 'review', label: 'Review (HITL)', x: 910, y: 380, role: 'Human-in-the-loop queue: flagged labels wait for a reviewer verdict.', aliases: ['review', 'hitl'] }, { id: 'relabel', label: 'Re-Label', x: 1070, y: 380, role: 'Reviewer corrections re-enter Quality Validation — never trusted without re-passing gates.', aliases: ['relabel'] }, { id: 'training', label: 'Training', x: 1230, y: 240, role: 'Verified labels become training data for the next model version — the flywheel.', aliases: ['train'] },];
const AS_BUILT_EDGES: Array<[string, string]> = [ ['input', 'autolabels'], ['autolabels', 'queue'], ['queue', 'anomaly'], ['queue', 'regression'], ['queue', 'grader'], ['anomaly', 'validation'], ['regression', 'validation'], ['grader', 'validation'], ['validation', 'rare'], ['validation', 'autograded'], ['validation', 'review'], ['review', 'relabel'], ['relabel', 'validation'], ['rare', 'review'], ['autograded', 'training'],];
const ROLE_COLORS: Record<string, string> = { input: '#4fc3f7', autolabels: '#4fc3f7', queue: '#8a949e', anomaly: '#ab47bc', regression: '#ab47bc', grader: '#ab47bc', validation: '#f9a825', rare: '#ff7043', autograded: '#66bb6a', review: '#ff7043', relabel: '#ff7043', training: '#66bb6a',};
// ------------------------------------------------------------- draft state
interface DraftStage { id: string; x: number; y: number; enabled: boolean; note: string;}
interface Draft { stages: DraftStage[]; edges: Array<[string, string]>;}
const LAYOUT_KEY = 'pipeline-builder-draft';
function asBuiltDraft(): Draft { return { stages: AS_BUILT_STAGES.map((s) => ({ id: s.id, x: s.x, y: s.y, enabled: true, note: '' })), edges: AS_BUILT_EDGES.map((e) => [...e] as [string, string]), };}
/** Kahn topological sort over enabled stages; returns order + cycle members. */function analyze(draft: Draft): { order: string[]; cycle: string[]; orphans: string[] } { const enabled = new Set(draft.stages.filter((s) => s.enabled).map((s) => s.id)); const edges = draft.edges.filter(([f, t]) => enabled.has(f) && enabled.has(t)); const indeg = new Map<string, number>(); enabled.forEach((id) => indeg.set(id, 0)); edges.forEach(([, t]) => indeg.set(t, (indeg.get(t) ?? 0) + 1)); const queue = [...enabled].filter((id) => (indeg.get(id) ?? 0) === 0); const order: string[] = []; const deg = new Map(indeg); const q = [...queue]; while (q.length) { const id = q.shift() as string; order.push(id); edges.filter(([f]) => f === id).forEach(([, t]) => { deg.set(t, (deg.get(t) ?? 0) - 1); if ((deg.get(t) ?? 0) === 0) q.push(t); }); } const cycle = [...enabled].filter((id) => !order.includes(id)); const touched = new Set(edges.flat()); const orphans = [...enabled].filter((id) => !touched.has(id)); return { order, cycle, orphans };}
function diffVsAsBuilt(draft: Draft): string[] { const changes: string[] = []; const asKey = new Set(AS_BUILT_EDGES.map(([f, t]) => `${f}→${t}`)); const drKey = new Set(draft.edges.map(([f, t]) => `${f}→${t}`)); draft.stages.filter((s) => !s.enabled).forEach((s) => changes.push(`stage "${s.id}" disabled`)); [...drKey].filter((k) => !asKey.has(k)).forEach((k) => changes.push(`edge ${k} added`)); [...asKey].filter((k) => !drKey.has(k)).forEach((k) => changes.push(`edge ${k} removed`)); return changes;}
// ---------------------------------------------------------------- page
export default function PipelineBuilderPage() { const { stream, navigate } = useLabelEval(); const [draft, setDraft] = useState<Draft>(asBuiltDraft); const [selectedId, setSelectedId] = useState<string | null>(null); const [pipeline, setPipeline] = useState<PipelineStateResponse | null>(null); const loaded = useRef(false);
useEffect(() => { loadLayout<Draft>(LAYOUT_KEY).then((saved) => { if (saved && Array.isArray(saved.stages) && saved.stages.length) setDraft(saved); loaded.current = true; }); getPipeline().then(setPipeline).catch(() => undefined); }, []);
useEffect(() => { if (loaded.current) saveLayout(LAYOUT_KEY, draft); }, [draft]);
const live = stream?.pipeline ?? pipeline;
const stageDef = useCallback((id: string) => AS_BUILT_STAGES.find((s) => s.id === id), []);
const liveState = useCallback( (id: string): string | null => { const def = stageDef(id); if (!def || !live) return null; const svc = live.services.find((s) => def.aliases.some((a) => s.service.toLowerCase().includes(a))); return svc?.state ?? null; }, [live, stageDef] );
const nodes: GraphNode[] = useMemo( () => draft.stages.map((s) => { const def = stageDef(s.id); const state = liveState(s.id); return { id: s.id, x: s.x, y: s.y, label: def?.label ?? s.id, sublabel: s.enabled ? state ?? 'stage' : 'DISABLED', color: s.enabled ? ROLE_COLORS[s.id] ?? tokens.color.borderStrong : tokens.color.textFaint, }; }), [draft.stages, stageDef, liveState] );
const edges: GraphEdge[] = useMemo(() => { const enabled = new Set(draft.stages.filter((s) => s.enabled).map((s) => s.id)); return draft.edges.map(([from, to]) => ({ from, to, dashed: !enabled.has(from) || !enabled.has(to), color: !enabled.has(from) || !enabled.has(to) ? tokens.color.textFaint : undefined, })); }, [draft]);
const summary = useMemo(() => analyze(draft), [draft]); const changes = useMemo(() => diffVsAsBuilt(draft), [draft]);
const selected = draft.stages.find((s) => s.id === selectedId) ?? null; const selectedDef = selectedId ? stageDef(selectedId) : undefined; const selectedEdges = draft.edges.filter(([f, t]) => f === selectedId || t === selectedId);
const inspectorFields: InspectorField[] = selected ? [ { type: 'readonly', key: 'role', label: 'Role in the pipeline', value: selectedDef?.role ?? '' }, ...(liveState(selected.id) ? [{ type: 'readonly', key: 'live', label: 'Live service state (as-built pipeline)', value: liveState(selected.id) } as InspectorField] : []), { type: 'toggle', key: 'enabled', label: 'Enabled in draft', value: selected.enabled, help: 'Disabled stages are excluded from the what-will-run order; edges through them go inert (dashed).' }, { type: 'text', key: 'note', label: 'Draft note', value: selected.note, help: 'Free-form what-if annotation, stored with the draft.' }, ] : [];
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> <Alert severity="info" variant="outlined" sx={{ py: 0.25 }}> <strong>DRAFT — nothing here executes.</strong> The real pipeline is read-only (see{' '} <Box component="span" onClick={() => navigate('pipeline')} sx={{ color: tokens.color.info, cursor: 'pointer', textDecoration: 'underline' }}> Pipeline Architecture </Box> {' '}for the as-built map). This is a visual explorer and what-if composer: your changes live in a local draft you can export. </Alert>
<SectionCard title="Draft pipeline graph" help="Drag stages to rearrange. Drag from a stage's right-hand port onto another stage to draw a new edge. Click a stage to inspect and edit it (enable/disable, note). Live service states from the running pipeline are shown on nodes where available." action={ <Box sx={{ display: 'flex', gap: 0.75 }}> <Button size="small" startIcon={<RotateCcw size={14} />} onClick={() => { setDraft(asBuiltDraft()); setSelectedId(null); }}> Reset to as-built </Button> <Button size="small" startIcon={<Download size={14} />} onClick={() => { const payload = { schema: 'sensorflow.pipeline-draft/v1', draft, analysis: summary, changes }; const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' }); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'pipeline-draft.json'; a.click(); URL.revokeObjectURL(a.href); }} > Export draft </Button> </Box> } > <NodeCanvas nodes={nodes} edges={edges} selectedId={selectedId} onSelect={setSelectedId} onMoveNode={(id, x, y) => setDraft((d) => ({ ...d, stages: d.stages.map((s) => (s.id === id ? { ...s, x, y } : s)) }))} onConnect={(from, to) => setDraft((d) => d.edges.some(([f, t]) => f === from && t === to) ? d : { ...d, edges: [...d.edges, [from, to]] } ) } world={{ x: 0, y: 0, w: 1340, h: 500 }} height={430} ariaLabel="Pipeline draft node graph" /> </SectionCard>
<Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap', alignItems: 'flex-start' }}> <Box sx={{ flex: '1 1 300px', minWidth: 280 }}> <InspectorPanel title={selectedDef?.label ?? 'Stage inspector'} subtitle={selected ? `stage id: ${selected.id}` : undefined} accent={selected ? ROLE_COLORS[selected.id] : undefined} fields={inspectorFields} emptyHint="Click a stage on the canvas to inspect its role, live status and draft settings." onChange={(key, value) => { if (!selectedId) return; setDraft((d) => ({ ...d, stages: d.stages.map((s) => (s.id === selectedId ? { ...s, [key]: value } : s)), })); }} footer={ selected && selectedEdges.length ? ( <Box> <Typography variant="caption" sx={{ color: tokens.color.neutral, display: 'block', mb: 0.5 }}> Connections — click to remove from the draft: </Typography> <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap' }}> {selectedEdges.map(([f, t]) => ( <Chip key={`${f}->${t}`} size="small" icon={<Unlink size={12} />} label={`${f} → ${t}`} onClick={() => setDraft((d) => ({ ...d, edges: d.edges.filter(([ef, et]) => !(ef === f && et === t)) }))} sx={{ height: 22, fontSize: 10.5, fontFamily: 'monospace', cursor: 'pointer', '&:hover': { bgcolor: tokens.color.dangerBg, color: tokens.color.danger } }} /> ))} </Box> </Box> ) : null } /> </Box>
<SectionCard title="What will run (live summary of the draft)" sx={{ flex: '2 1 420px' }} help="Recomputed on every edit: the topological execution order of enabled stages, any cycles (which would deadlock a real scheduler — the as-built re-label loop is broken by the review gate, so removing that edge and adding a direct loop shows up here), orphaned stages, and the diff against the as-built pipeline." > <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.25 }}> <Box> <Typography variant="caption" sx={{ color: tokens.color.neutral, display: 'block', mb: 0.5 }}> Execution order (topological) </Typography> <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap', alignItems: 'center' }}> {summary.order.map((id, i) => ( <Box key={id} sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}> <Chip size="small" label={stageDef(id)?.label ?? id} sx={{ height: 22, fontSize: 11, bgcolor: `${ROLE_COLORS[id] ?? tokens.color.neutral}1c`, color: ROLE_COLORS[id] ?? tokens.color.text, fontWeight: 700 }} /> {i < summary.order.length - 1 ? <Typography variant="caption" sx={{ color: tokens.color.textFaint }}>→</Typography> : null} </Box> ))} {summary.order.length === 0 ? <Typography variant="caption" sx={{ color: tokens.color.textFaint }}>nothing runnable</Typography> : null} </Box> </Box>
{summary.cycle.length ? ( <Alert severity="warning" variant="outlined" sx={{ py: 0 }}> Cycle detected involving: {summary.cycle.map((id) => stageDef(id)?.label ?? id).join(', ')} — these stages can never be scheduled in a strict order. (The as-built re-label feedback loop is the legitimate exception; a real scheduler breaks it at the review gate.) </Alert> ) : null}
{summary.orphans.length ? ( <Typography variant="caption" sx={{ color: tokens.color.warn }}> Orphaned (enabled but unconnected): {summary.orphans.map((id) => stageDef(id)?.label ?? id).join(', ')} </Typography> ) : null}
<Box> <Typography variant="caption" sx={{ color: tokens.color.neutral, display: 'block', mb: 0.5 }}> Draft vs as-built {changes.length === 0 ? '— identical' : `— ${changes.length} change${changes.length === 1 ? '' : 's'}`} </Typography> {changes.map((c) => ( <Typography key={c} variant="caption" sx={{ display: 'block', fontFamily: 'monospace', color: tokens.color.info }}> · {c} </Typography> ))} </Box> </Box> </SectionCard> </Box> </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661/** * Scenario Composer — WYSIWYG BEV scenario editor. * * Drag actors from the palette onto the top-down canvas, drag them (and their * trajectory waypoints) to shape the scene, set the environment with visual * toggles (the canvas re-renders the look), watch the JSON recipe write * itself, and run the composition through the surrogate-safety evaluation * (SSAM /api/safety/ssam/analyze accepts custom trajectories). */import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import Alert from '@mui/material/Alert';import Box from '@mui/material/Box';import Button from '@mui/material/Button';import Chip from '@mui/material/Chip';import Typography from '@mui/material/Typography';import { CloudFog, CloudRain, Moon, Play, RotateCcw, Sun, Trash2 } from 'lucide-react';import CanvasSurface, { snapTo, worldDrag, type CanvasApi } from '../../components/visual/canvas';import InspectorPanel, { type InspectorField } from '../../components/visual/InspectorPanel';import { analyzeSsam, type SsamAnalysis, type SsamTrajectory } from '../../services/safety';import { getCapabilities, loadLayout, saveLayout } from '../../services/studioux';import { SectionCard, fmtNum } from '../../components/labeleval/shared';import { InfoDot } from '../../components/help/InfoTip';import { tokens, verdictColor } from '../../theme';import { useLabelEval } from '../../context/LabelEvalContext';
// ---------------------------------------------------------------- model
type ActorKind = 'vehicle' | 'truck' | 'pedestrian' | 'cyclist' | 'cone' | 'construction';
interface Waypoint { x: number; y: number;}
interface Actor { id: string; kind: ActorKind; x: number; y: number; /** degrees, 0 = +x (ego forward) */ heading: number; /** m/s along the waypoint path */ speed: number; waypoints: Waypoint[];}
interface Environment { timeOfDay: 'day' | 'night'; weather: 'clear' | 'rain' | 'fog';}
interface Composition { name: string; env: Environment; actors: Actor[];}
const ACTOR_META: Record<ActorKind, { label: string; color: string; l: number; w: number; defaultSpeed: number; movable: boolean }> = { vehicle: { label: 'Vehicle', color: '#66bb6a', l: 4.5, w: 1.9, defaultSpeed: 8, movable: true }, truck: { label: 'Truck', color: '#9ccc65', l: 8.5, w: 2.5, defaultSpeed: 6, movable: true }, pedestrian: { label: 'Pedestrian', color: '#ff7043', l: 0.6, w: 0.6, defaultSpeed: 1.4, movable: true }, cyclist: { label: 'Cyclist', color: '#ffca28', l: 1.8, w: 0.7, defaultSpeed: 4, movable: true }, cone: { label: 'Cone', color: '#ffa726', l: 0.4, w: 0.4, defaultSpeed: 0, movable: false }, construction: { label: 'Construction zone', color: '#ab47bc', l: 8, w: 4, defaultSpeed: 0, movable: false },};
const WORLD = { x: -12, y: -28, w: 104, h: 56 };const LAYOUT_KEY = 'scenario-composer';
const DEFAULT_COMPOSITION: Composition = { name: 'my-scenario', env: { timeOfDay: 'day', weather: 'clear' }, actors: [],};
let actorSeq = 0;function newActorId(kind: ActorKind): string { actorSeq += 1; return `${kind}-${Date.now().toString(36)}-${actorSeq}`;}
// ------------------------------------------------- recipe + trajectory compile
/** Machine-readable recipe — the live JSON preview and the export format. */function toRecipe(c: Composition) { return { schema: 'sensorflow.scenario/v1', name: c.name, environment: { time_of_day: c.env.timeOfDay, weather: c.env.weather }, ego: { x: 0, y: 0, heading_deg: 0 }, actors: c.actors.map((a) => ({ id: a.id, kind: a.kind, position: { x: round2(a.x), y: round2(a.y) }, heading_deg: Math.round(a.heading), speed_mps: round2(a.speed), trajectory_waypoints: a.waypoints.map((w) => ({ x: round2(w.x), y: round2(w.y) })), })), };}
function round2(v: number): number { return Math.round(v * 100) / 100;}
/** * Compile the composition into SSAM trajectories: each actor walks its * waypoint path at its speed (dt = 0.5 s); static props stand still. The ego * vehicle drives straight ahead at 8 m/s so every scene has the AV in it. */function compileTrajectories(c: Composition, durationS = 12): SsamTrajectory[] { const dt = 0.5; const steps = Math.round(durationS / dt); const out: SsamTrajectory[] = [];
const ego: SsamTrajectory = { vehicle_id: 'ego', vehicle_type: 'car', length: 4.5, width: 1.9, states: Array.from({ length: steps + 1 }, (_, i) => ({ t: i * dt, x: 8 * i * dt, y: 0, speed: 8, heading: 0 })), }; out.push(ego);
c.actors.forEach((a) => { const meta = ACTOR_META[a.kind]; const path: Waypoint[] = [{ x: a.x, y: a.y }, ...a.waypoints]; const states: SsamTrajectory['states'] = []; if (!meta.movable || a.speed <= 0 || path.length < 2) { const heading = (a.heading * Math.PI) / 180; for (let i = 0; i <= steps; i += 1) states.push({ t: i * dt, x: a.x, y: a.y, speed: 0, heading }); } else { // cumulative arc lengths const segLen: number[] = []; for (let i = 1; i < path.length; i += 1) segLen.push(Math.hypot(path[i].x - path[i - 1].x, path[i].y - path[i - 1].y)); const total = segLen.reduce((s, v) => s + v, 0); for (let i = 0; i <= steps; i += 1) { const dist = Math.min(a.speed * i * dt, total); let acc = 0; let seg = 0; while (seg < segLen.length - 1 && acc + segLen[seg] < dist) { acc += segLen[seg]; seg += 1; } const p0 = path[seg]; const p1 = path[seg + 1]; const f = segLen[seg] > 0 ? (dist - acc) / segLen[seg] : 0; const x = p0.x + (p1.x - p0.x) * f; const y = p0.y + (p1.y - p0.y) * f; const heading = Math.atan2(p1.y - p0.y, p1.x - p0.x); const done = dist >= total; states.push({ t: i * dt, x, y, speed: done ? 0 : a.speed, heading }); } } out.push({ vehicle_id: a.id, vehicle_type: a.kind === 'vehicle' ? 'car' : a.kind, length: meta.l, width: meta.w, states, }); }); return out;}
// ---------------------------------------------------------------- rendering
function ActorGlyph({ actor, selected, api, onSelect, onMove }: { actor: Actor; selected: boolean; api: CanvasApi; onSelect: () => void; onMove: (x: number, y: number) => void;}) { const meta = ACTOR_META[actor.kind]; const stroke = selected ? '#ffffff' : meta.color; const drag = worldDrag(api, { onStart: () => onSelect(), onMove: (w) => onMove(snapTo(w.x, 0.5), snapTo(w.y, 0.5)), });
const common = { ...drag, style: { cursor: 'grab' as const } }; const label = selected ? ( <text x={0} y={-meta.w / 2 - 0.8} fontSize={1.6} fill="#fff" textAnchor="middle" fontWeight={700} pointerEvents="none"> {meta.label} </text> ) : null;
switch (actor.kind) { case 'pedestrian': return ( <g transform={`translate(${actor.x}, ${-actor.y})`} {...common}> <circle r={0.5} fill={`${meta.color}55`} stroke={stroke} strokeWidth={selected ? 0.25 : 0.15} /> <circle r={0.18} fill={stroke} /> {label} </g> ); case 'cone': return ( <g transform={`translate(${actor.x}, ${-actor.y})`} {...common}> <polygon points="0,-0.55 0.45,0.45 -0.45,0.45" fill={`${meta.color}66`} stroke={stroke} strokeWidth={selected ? 0.2 : 0.12} /> {label} </g> ); case 'construction': return ( <g transform={`translate(${actor.x}, ${-actor.y}) rotate(${-actor.heading})`} {...common}> <rect x={-meta.l / 2} y={-meta.w / 2} width={meta.l} height={meta.w} fill={`${meta.color}22`} stroke={stroke} strokeWidth={selected ? 0.28 : 0.18} strokeDasharray="0.8 0.5" rx={0.3} /> <text x={0} y={0.35} fontSize={1.1} fill={stroke} textAnchor="middle" fontWeight={700} pointerEvents="none">WORK ZONE</text> {label} </g> ); default: // vehicle / truck / cyclist: oriented box + heading tick return ( <g transform={`translate(${actor.x}, ${-actor.y}) rotate(${-actor.heading})`} {...common}> <rect x={-meta.l / 2} y={-meta.w / 2} width={meta.l} height={meta.w} fill={`${meta.color}33`} stroke={stroke} strokeWidth={selected ? 0.28 : 0.18} rx={0.25} /> <line x1={meta.l / 2} y1={0} x2={meta.l / 2 + 1} y2={0} stroke={stroke} strokeWidth={0.2} /> {label} </g> ); }}
function EnvironmentDecor({ env, view }: { env: Environment; view: { x: number; y: number; w: number; h: number } }) { const items: React.ReactNode[] = []; if (env.weather === 'rain') { // deterministic rain streaks for (let i = 0; i < 60; i += 1) { const x = view.x + ((i * 37) % 100) / 100 * view.w; const y = view.y + ((i * 61) % 100) / 100 * view.h; items.push(<line key={`r${i}`} x1={x} y1={y} x2={x - 0.5} y2={y + 1.4} stroke="rgba(120,160,220,0.35)" strokeWidth={0.1} pointerEvents="none" />); } } if (env.weather === 'fog') { items.push(<rect key="fog" x={view.x} y={view.y} width={view.w} height={view.h} fill="rgba(200,210,220,0.13)" pointerEvents="none" />); } if (env.timeOfDay === 'night') { items.push(<rect key="night" x={view.x} y={view.y} width={view.w} height={view.h} fill="rgba(8,12,40,0.35)" pointerEvents="none" />); } return <>{items}</>;}
// ---------------------------------------------------------------- page
export default function ScenarioComposerPage() { const { navigate } = useLabelEval(); const [comp, setComp] = useState<Composition>(DEFAULT_COMPOSITION); const [selectedId, setSelectedId] = useState<string | null>(null); const [canRun, setCanRun] = useState(false); const [running, setRunning] = useState(false); const [result, setResult] = useState<SsamAnalysis | null>(null); const [runError, setRunError] = useState<string | null>(null); const loaded = useRef(false);
useEffect(() => { loadLayout<Composition>(LAYOUT_KEY).then((saved) => { if (saved && Array.isArray(saved.actors)) setComp(saved); loaded.current = true; }); getCapabilities().then((caps) => setCanRun(caps.ssamAnalyze)); }, []);
// autosave (skip until the initial load resolved to avoid clobbering) useEffect(() => { if (loaded.current) saveLayout(LAYOUT_KEY, comp); }, [comp]);
const selected = comp.actors.find((a) => a.id === selectedId) ?? null;
const updateActor = useCallback((id: string, patch: Partial<Actor>) => { setComp((c) => ({ ...c, actors: c.actors.map((a) => (a.id === id ? { ...a, ...patch } : a)) })); }, []);
const addActor = useCallback((kind: ActorKind, x: number, y: number) => { const meta = ACTOR_META[kind]; const actor: Actor = { id: newActorId(kind), kind, x: snapTo(x, 0.5), y: snapTo(y, 0.5), heading: 180, speed: meta.defaultSpeed, waypoints: [], }; setComp((c) => ({ ...c, actors: [...c.actors, actor] })); setSelectedId(actor.id); }, []);
const removeActor = useCallback((id: string) => { setComp((c) => ({ ...c, actors: c.actors.filter((a) => a.id !== id) })); setSelectedId((s) => (s === id ? null : s)); }, []);
const addWaypoint = useCallback((id: string) => { setComp((c) => ({ ...c, actors: c.actors.map((a) => { if (a.id !== id) return a; const last = a.waypoints[a.waypoints.length - 1] ?? { x: a.x, y: a.y }; const prev = a.waypoints.length > 1 ? a.waypoints[a.waypoints.length - 2] : { x: a.x, y: a.y }; const dx = last.x - prev.x; const dy = last.y - prev.y; const n = Math.hypot(dx, dy) || 1; // extend along the current direction (or along heading for the first) const dir = a.waypoints.length === 0 ? { x: Math.cos((a.heading * Math.PI) / 180), y: Math.sin((a.heading * Math.PI) / 180) } : { x: dx / n, y: dy / n }; return { ...a, waypoints: [...a.waypoints, { x: snapTo(last.x + dir.x * 8, 0.5), y: snapTo(last.y + dir.y * 8, 0.5) }] }; }), })); }, []);
const recipe = useMemo(() => toRecipe(comp), [comp]); const recipeJson = useMemo(() => JSON.stringify(recipe, null, 2), [recipe]);
const run = useCallback(() => { setRunning(true); setRunError(null); setResult(null); analyzeSsam({ trajectories: compileTrajectories(comp) }) .then(setResult) .catch((e) => setRunError(e instanceof Error ? e.message : String(e))) .finally(() => setRunning(false)); }, [comp]);
const inspectorFields: InspectorField[] = selected ? [ { type: 'readonly', key: 'id', label: 'Actor ID', value: selected.id }, { type: 'select', key: 'kind', label: 'Kind', value: selected.kind, options: (Object.keys(ACTOR_META) as ActorKind[]).map((k) => ({ value: k, label: ACTOR_META[k].label })), help: 'Changing the kind swaps footprint and default dynamics; position and waypoints are kept.', }, { type: 'readonly', key: 'pos', label: 'Position (ego frame)', value: `(${selected.x.toFixed(1)}, ${selected.y.toFixed(1)}) m` }, { type: 'slider', key: 'heading', label: 'Heading', value: Math.round(selected.heading), min: -180, max: 180, step: 5, unit: '°', help: '0° faces the same way as the ego vehicle (+x).' }, ...(ACTOR_META[selected.kind].movable ? [{ type: 'slider', key: 'speed', label: 'Speed', value: selected.speed, min: 0, max: 20, step: 0.5, unit: ' m/s', help: 'Speed along the waypoint path when the scenario runs.' } as InspectorField] : []), { type: 'readonly', key: 'wp', label: 'Trajectory waypoints', value: `${selected.waypoints.length} — drag the small circles on the canvas` }, ] : [];
const envBg = comp.env.timeOfDay === 'night' ? '#0a0e1c' : tokens.color.surfaceSunken;
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> <SectionCard title={ <Box component="span" sx={{ display: 'inline-flex', alignItems: 'center' }}> Compose the scene <InfoDot title="How to compose" detail="Drag an actor chip from the palette and drop it anywhere on the canvas. Drag actors to reposition. Select an actor to edit its heading/speed and add trajectory waypoints (small circles — drag them too). The ego vehicle (blue triangle) always drives straight at 8 m/s. Environment toggles change the canvas look and are recorded in the recipe." /> </Box> } action={ <Box sx={{ display: 'flex', gap: 0.75, alignItems: 'center' }}> <Chip size="small" icon={comp.env.timeOfDay === 'day' ? <Sun size={13} /> : <Moon size={13} />} label={comp.env.timeOfDay} onClick={() => setComp((c) => ({ ...c, env: { ...c.env, timeOfDay: c.env.timeOfDay === 'day' ? 'night' : 'day' } }))} sx={{ cursor: 'pointer', bgcolor: comp.env.timeOfDay === 'night' ? '#1a237e' : 'rgba(249,168,37,0.18)', fontWeight: 700 }} /> {(['clear', 'rain', 'fog'] as const).map((w) => ( <Chip key={w} size="small" icon={w === 'rain' ? <CloudRain size={13} /> : w === 'fog' ? <CloudFog size={13} /> : <Sun size={13} />} label={w} onClick={() => setComp((c) => ({ ...c, env: { ...c.env, weather: w } }))} sx={{ cursor: 'pointer', fontWeight: comp.env.weather === w ? 800 : 400, bgcolor: comp.env.weather === w ? tokens.color.infoBg : 'transparent', color: comp.env.weather === w ? tokens.color.info : tokens.color.textDim, border: `1px solid ${comp.env.weather === w ? tokens.color.info : tokens.color.border}`, }} /> ))} <Button size="small" startIcon={<RotateCcw size={14} />} onClick={() => { setComp(DEFAULT_COMPOSITION); setSelectedId(null); setResult(null); }} > Clear </Button> </Box> } > {/* palette */} <Box sx={{ display: 'flex', gap: 0.75, flexWrap: 'wrap', mb: 1, alignItems: 'center' }}> <Typography variant="caption" sx={{ color: tokens.color.neutral, mr: 0.5 }}> Palette — drag onto the canvas: </Typography> {(Object.keys(ACTOR_META) as ActorKind[]).map((k) => ( <Chip key={k} size="small" label={ACTOR_META[k].label} draggable onDragStart={(e) => { e.dataTransfer.setData('application/x-actor-kind', k); e.dataTransfer.effectAllowed = 'copy'; }} sx={{ cursor: 'grab', bgcolor: `${ACTOR_META[k].color}1f`, color: ACTOR_META[k].color, border: `1px solid ${ACTOR_META[k].color}66`, fontWeight: 700, '&:active': { cursor: 'grabbing' }, }} /> ))} <Typography variant="caption" sx={{ color: tokens.color.textFaint }}> {comp.actors.length} actor{comp.actors.length === 1 ? '' : 's'} placed </Typography> </Box>
<Box sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap', alignItems: 'stretch' }}> <Box sx={{ flex: '3 1 560px', minWidth: 0 }}> <CanvasSurface world={WORLD} height={440} gridStep={10} background={envBg} ariaLabel="Scenario composition canvas" onBackgroundClick={() => setSelectedId(null)} onDropWorld={(w, e) => { const kind = e.dataTransfer.getData('application/x-actor-kind') as ActorKind; if (kind && ACTOR_META[kind]) addActor(kind, w.x, -w.y); }} > {(api) => ( <> <EnvironmentDecor env={comp.env} view={WORLD} /> {/* road hint: ego lane */} <rect x={-12} y={-3.5} width={104} height={7} fill="rgba(255,255,255,0.03)" pointerEvents="none" /> <line x1={-12} y1={0} x2={92} y2={0} stroke="rgba(255,255,255,0.14)" strokeWidth={0.12} strokeDasharray="2.5 2.5" pointerEvents="none" /> {[20, 40, 60, 80].map((r) => ( <circle key={r} cx={0} cy={0} r={r} fill="none" stroke={tokens.color.border} strokeWidth={0.1} strokeDasharray="1 1.2" pointerEvents="none" /> ))} {/* ego */} <g pointerEvents="none"> <polygon points="2.4,0 -1.4,1.1 -1.4,-1.1" fill={tokens.color.info} stroke="#fff" strokeWidth={0.12} /> <text x={0} y={2.6} fontSize={1.5} fill={tokens.color.info} textAnchor="middle" fontWeight={700}>EGO → 8 m/s</text> </g>
{/* trajectory paths + waypoints of the selected actor */} {comp.actors.map((a) => { if (a.waypoints.length === 0) return null; const isSel = a.id === selectedId; const pts = [{ x: a.x, y: a.y }, ...a.waypoints]; return ( <g key={`traj-${a.id}`}> <polyline points={pts.map((p) => `${p.x},${-p.y}`).join(' ')} fill="none" stroke={isSel ? '#fff' : `${ACTOR_META[a.kind].color}88`} strokeWidth={isSel ? 0.18 : 0.12} strokeDasharray="0.9 0.6" pointerEvents="none" /> {isSel ? a.waypoints.map((wp, i) => ( <circle key={i} cx={wp.x} cy={-wp.y} r={0.8} fill="rgba(255,255,255,0.25)" stroke="#fff" strokeWidth={0.15} style={{ cursor: 'grab' }} {...worldDrag(api, { onMove: (w) => updateActor(a.id, { waypoints: a.waypoints.map((p, j) => (j === i ? { x: snapTo(w.x, 0.5), y: snapTo(-w.y, 0.5) } : p)), }), })} /> )) : null} </g> ); })}
{comp.actors.map((a) => ( <ActorGlyph key={a.id} actor={a} selected={a.id === selectedId} api={api} onSelect={() => setSelectedId(a.id)} onMove={(x, y) => updateActor(a.id, { x, y: -y })} /> ))} </> )} </CanvasSurface> <Typography variant="caption" sx={{ color: tokens.color.neutral, display: 'block', mt: 0.5 }}> Ego frame: x forward (right), y left (up). Scroll to zoom, drag the background to pan, drop palette chips to place actors. </Typography> </Box>
<Box sx={{ flex: '1 1 250px', display: 'flex', flexDirection: 'column', gap: 1.5, minWidth: 240 }}> <InspectorPanel title={selected ? ACTOR_META[selected.kind].label : 'Inspector'} subtitle={selected ? 'Live edits re-render the canvas' : undefined} accent={selected ? ACTOR_META[selected.kind].color : undefined} fields={inspectorFields} emptyHint="Select an actor on the canvas (or drop a new one from the palette) to edit its properties here." onChange={(key, value) => { if (!selected) return; if (key === 'kind') updateActor(selected.id, { kind: value as ActorKind, speed: ACTOR_META[value as ActorKind].defaultSpeed }); else if (key === 'heading') updateActor(selected.id, { heading: value as number }); else if (key === 'speed') updateActor(selected.id, { speed: value as number }); }} footer={ selected ? ( <Box sx={{ display: 'flex', gap: 0.75, flexWrap: 'wrap' }}> {ACTOR_META[selected.kind].movable ? ( <Button size="small" variant="outlined" onClick={() => addWaypoint(selected.id)}> + Waypoint </Button> ) : null} {selected.waypoints.length > 0 ? ( <Button size="small" onClick={() => updateActor(selected.id, { waypoints: selected.waypoints.slice(0, -1) })}> − Waypoint </Button> ) : null} <Button size="small" color="error" startIcon={<Trash2 size={14} />} onClick={() => removeActor(selected.id)}> Remove </Button> </Box> ) : null } /> </Box> </Box> </SectionCard>
<Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}> <SectionCard title="Live recipe (JSON)" sx={{ flex: '1 1 380px' }} help="The machine-readable scenario recipe, regenerated on every edit. This exact object is what gets compiled into trajectories for the evaluation run." action={ <Button size="small" onClick={() => { const blob = new Blob([recipeJson], { type: 'application/json' }); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = `${comp.name || 'scenario'}.json`; a.click(); URL.revokeObjectURL(a.href); }} > Download </Button> } > <Box component="pre" sx={{ m: 0, p: 1.25, bgcolor: tokens.color.surfaceSunken, border: `1px solid ${tokens.color.border}`, borderRadius: 1, fontSize: 11, fontFamily: 'monospace', maxHeight: 320, overflow: 'auto', color: tokens.color.textDim, }} > {recipeJson} </Box> </SectionCard>
<SectionCard title="Run through evaluation" sx={{ flex: '1 1 380px' }} help="Compiles the composed actors into trajectories (each actor walks its waypoint path at its speed; the ego drives straight at 8 m/s) and runs the surrogate-safety (SSAM) analysis over them. Conflicts are scored with TTC / PET / DRAC / CSI — the same measures as the SSAM Conflicts page." > {!canRun ? ( <Alert severity="info" variant="outlined"> No scene-consuming evaluation API is reachable right now — the run action is hidden. Composition and recipe export still work. </Alert> ) : ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}> <Box sx={{ display: 'flex', gap: 1, alignItems: 'center', flexWrap: 'wrap' }}> <Button variant="contained" startIcon={<Play size={15} />} disabled={running || comp.actors.length === 0} onClick={run}> {running ? 'Analyzing…' : 'Run surrogate-safety analysis'} </Button> <Typography variant="caption" sx={{ color: tokens.color.neutral }}> {comp.actors.length === 0 ? 'Place at least one actor first.' : `ego + ${comp.actors.length} actors · 12 s @ 2 Hz`} </Typography> </Box> {runError ? <Alert severity="warning" variant="outlined">{runError}</Alert> : null} {result ? ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}> <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}> <Chip size="small" label={`${result.aggregate.num_conflicts} conflict${result.aggregate.num_conflicts === 1 ? '' : 's'}`} sx={{ fontWeight: 900, bgcolor: result.aggregate.num_conflicts > 0 ? tokens.color.dangerBg : tokens.color.successBg, color: result.aggregate.num_conflicts > 0 ? tokens.color.danger : tokens.color.success, }} /> {result.aggregate.min_ttc_s !== null ? ( <Chip size="small" label={`min TTC ${fmtNum(result.aggregate.min_ttc_s, 2)} s`} sx={{ fontFamily: 'monospace' }} /> ) : null} {result.aggregate.max_drac_mps2 !== null ? ( <Chip size="small" label={`max DRAC ${fmtNum(result.aggregate.max_drac_mps2, 2)} m/s²`} sx={{ fontFamily: 'monospace' }} /> ) : null} <Chip size="small" label={`aggregate CSI ${fmtNum(result.aggregate.aggregate_csi, 3)}`} sx={{ fontFamily: 'monospace' }} /> </Box> {result.conflicts.slice(0, 6).map((c, i) => ( <Box key={i} sx={{ display: 'flex', gap: 1, alignItems: 'center', p: 0.75, border: `1px solid ${tokens.color.border}`, borderRadius: 1, bgcolor: tokens.color.surfaceSunken }}> <Chip size="small" label={c.conflict_type} sx={{ height: 20, fontSize: 10.5, bgcolor: `${verdictColor('WARN')}22`, color: verdictColor('WARN') }} /> <Typography variant="caption" sx={{ fontFamily: 'monospace', color: tokens.color.textDim }}> {c.vehicle_a} × {c.vehicle_b} · t {c.t_start_s.toFixed(1)}–{c.t_end_s.toFixed(1)} s {c.min_ttc_s !== null ? ` · TTC ${c.min_ttc_s.toFixed(2)} s` : ''} · CSI {c.csi.toFixed(3)} </Typography> </Box> ))} {result.aggregate.num_conflicts === 0 ? ( <Typography variant="caption" sx={{ color: tokens.color.success }}> No surrogate-safety conflicts detected in this composition — actors never got dangerously close to the ego or each other. </Typography> ) : ( <Button size="small" onClick={() => navigate('safety-ssam')} sx={{ alignSelf: 'flex-start' }}> Open the SSAM Conflicts page for the full toolkit → </Button> )} </Box> ) : null} </Box> )} </SectionCard> </Box> </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120/** Typed fetch wrappers for the Agentic Launch Readiness API (/api/agentic). */import type { AuditRecord, EvaluationSuite, EvidenceGraph, FailureEvent, HumanReviewDecision, PipelineState, PolicyEvaluation, RegressionSuiteResult, Scorecard, Walkthrough,} from '../types/agentic';
async function handle<T>(res: Response): Promise<T> { if (!res.ok) { let detail = ''; try { const body = await res.json(); detail = typeof body?.detail === 'string' ? body.detail : JSON.stringify(body); } catch { detail = await res.text().catch(() => ''); } const err = new Error(detail || res.statusText) as Error & { status?: number }; err.status = res.status; throw err; } return res.json() as Promise<T>;}
const JSON_HEADERS = { 'Content-Type': 'application/json' };const get = <T,>(url: string): Promise<T> => fetch(url).then((r) => handle<T>(r));const post = <T,>(url: string, body?: unknown): Promise<T> => fetch(url, { method: 'POST', headers: JSON_HEADERS, body: JSON.stringify(body ?? {}), }).then((r) => handle<T>(r));
const BASE = '/api/agentic';
// ------------------------------------------------------------- failures
export const detectFailures = () => post<{ detected: number; failures: { failure_id: string; title: string }[] }>( `${BASE}/failures/detect` );
export const getFailureQueue = () => get<{ failures: FailureEvent[]; stages: string[] }>(`${BASE}/failures`);
export const getFailure = (id: string) => get<{ failure: FailureEvent }>(`${BASE}/failures/${id}`);
export const getState = (id: string) => get<{ state: PipelineState }>(`${BASE}/failures/${id}/state`);
export const runStage = (id: string, stage?: string) => post<{ state: PipelineState }>( `${BASE}/failures/${id}/analyze${stage ? `?stage=${encodeURIComponent(stage)}` : ''}` );
export const getEvidence = (id: string) => get<{ graph: EvidenceGraph }>(`${BASE}/failures/${id}/evidence`);
export const getSnippets = (id: string) => get<{ snippets: Record<string, unknown>[] }>(`${BASE}/failures/${id}/snippets`);
export const runLaunchAssessment = (id: string) => post<{ policy_evaluation: PolicyEvaluation; scorecard_id: string | null }>( `${BASE}/failures/${id}/launch-assessment` );
// ------------------------------------------------------------- human review
export interface HumanReviewRequest { reviewer: string; decision: string; rationale: string; approved_option?: string | null; evidence_reviewed?: string[]; override_reason?: string | null;}
export const submitHumanReview = (id: string, req: HumanReviewRequest) => post<{ review: HumanReviewDecision; decisions: HumanReviewDecision[] }>( `${BASE}/failures/${id}/human-review`, req );
export const getHumanReviews = (id: string) => get<{ decisions: HumanReviewDecision[] }>(`${BASE}/failures/${id}/human-review`);
// ------------------------------------------------------------- policy / audit
export const getPolicy = () => get<{ policy: Record<string, unknown> }>(`${BASE}/policy`);
export const getAudit = (id: string) => get<{ records: AuditRecord[]; chain: { valid: boolean; records: number } }>( `${BASE}/audit/${id}` );
// ------------------------------------------------------------- scorecards
export const getScorecard = (id: string) => get<{ scorecard: Scorecard }>(`${BASE}/scorecards/${id}`);
// ------------------------------------------------------------- flywheel
export const listSuites = () => get<{ suites: EvaluationSuite[] }>(`${BASE}/evaluation-suites`);
export const runRegression = () => post<{ suites: RegressionSuiteResult[]; note: string }>(`${BASE}/regression/evaluate`);
// ------------------------------------------------------------- worked example
export const getWorkedExample = (refresh = false) => get<{ walkthrough: Walkthrough; cached: boolean }>( `${BASE}/worked-example${refresh ? '?refresh=true' : ''}` );123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178/** * Typed fetch wrappers + contracts for the BEV-Fusion perception engine * comparison (/api/bevfusion/*) and the studio-ux frame replay used by the * interactive top-down BEV canvas. */
async function handle<T>(res: Response): Promise<T> { if (!res.ok) { const body = await res.text().catch(() => ''); throw new Error(`API ${res.status}: ${body || res.statusText}`); } return res.json() as Promise<T>;}
const JSON_HEADERS = { 'Content-Type': 'application/json' };
function get<T>(url: string): Promise<T> { return fetch(url).then((res) => handle<T>(res));}
function post<T>(url: string, body?: unknown): Promise<T> { return fetch(url, { method: 'POST', headers: JSON_HEADERS, body: body === undefined ? undefined : JSON.stringify(body), }).then((res) => handle<T>(res));}
// ---------------------------------------------------------------- contracts
export interface BevHeadline { precision: number; recall: number; f1: number; mean_iou: number; position_error_m: number; class_accuracy: number; safety_recall: number; id_switch_rate: number; fragmentation_rate: number; idf1: number;}
export interface BevCohortStats { n_gt: number; recall: number; position_error_m: number; mean_iou: number; false_positives: number;}
export interface BevEngineEval { headline: BevHeadline; counts: { tp: number; fp: number; fn: number; pred_tracks: number; gt_tracks: number }; cohorts: Record<string, BevCohortStats>; per_class: Record<string, { n_gt: number; recall: number }>;}
export interface BevHeadlineDelta { metric: string; baseline: number; candidate: number; delta: number; improved: boolean;}
export interface BevCohortDelta { cohort: string; n_gt: number; recall_baseline: number; recall_candidate: number; recall_delta: number; position_error_baseline_m: number; position_error_candidate_m: number; mean_iou_baseline: number; mean_iou_candidate: number; explanation: string;}
export interface BevClassDelta { class: string; n_gt: number; recall_baseline: number; recall_candidate: number; recall_delta: number;}
export interface BevReport { run_id: string; created_at: string; params: { n_sequences: number; frames_per_sequence: number; seed: number }; engines: { baseline: string; candidate: string }; scale: { frames: number; gt_boxes: number; camera_detections: number; lidar_detections: number; fused_boxes: number }; baseline: BevEngineEval; candidate: BevEngineEval; headline_deltas: BevHeadlineDelta[]; per_cohort: BevCohortDelta[]; per_class: BevClassDelta[]; policy: Record<string, number>; blockers: string[]; improvements: string[]; recommendation: 'PROMOTE' | 'DO_NOT_PROMOTE'; process_units: Record<string, unknown>; notes: string;}
export interface BevStatus { engines: { baseline: string; candidate: string }; n_runs: number; runs: Array<{ run_id: string; created_at: string; params: BevReport['params']; recommendation: string | null }>; latest: { run_id: string; created_at: string; params: BevReport['params']; recommendation: string | null } | null; ready: boolean;}
export const getBevStatus = () => get<BevStatus>('/api/bevfusion/status');
export const getBevReport = () => get<BevReport>('/api/bevfusion/report');
export const runBevComparison = (body: { n_sequences?: number; frames_per_sequence?: number; seed?: number }) => post<BevReport>('/api/bevfusion/run', body);
// ---------------------------------------------------------------- frame replay (studio-ux)
/** [x, y, z, l, w, h, yaw] in ego frame. */export type Bbox3D = [number, number, number, number, number, number, number];
export interface BevGtBox { instance_id: string; class_name: string; bbox_3d: Bbox3D; occluded: boolean; distance: number;}
export interface BevDetection { modality: 'camera' | 'lidar'; x: number; y: number; cov: [[number, number], [number, number]]; dims: [number, number, number]; yaw: number; class_name: string; confidence: number;}
export interface BevFusedBox { bbox_3d: Bbox3D; class_name: string; confidence: number; track_id: number | string; propagated: boolean;}
export interface BevReplayFrame { frame_id: string; index: number; gt: BevGtBox[]; camera: BevDetection[]; lidar: BevDetection[]; fused: BevFusedBox[]; baseline: BevFusedBox[];}
export interface BevReplayResponse { sequence_id: string; sequence_index: number; n_sequences: number; time_of_day: string; weather: string; params: BevReport['params']; frames: BevReplayFrame[];}
export const getBevReplay = (params: { seed: number; n_sequences: number; frames_per_sequence: number }, sequence: number) => get<BevReplayResponse>( `/api/studio-ux/bev/replay?seed=${params.seed}&n_sequences=${params.n_sequences}` + `&frames_per_sequence=${params.frames_per_sequence}&sequence=${sequence}` );123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411/** * Typed fetch wrappers + contracts for the Safety & Compliance layer * (/api/safety/*). Mirrors the style of services/megaeval.ts. * * Sub-systems: ODD coverage, release gates + evidence packages, extended * SSAM surrogate safety, calibration validation, discrepancy mining, * scenario database, semantic search, consensus evidence. */
async function handle<T>(res: Response): Promise<T> { if (!res.ok) { const body = await res.text().catch(() => ''); throw new Error(`API ${res.status}: ${body || res.statusText}`); } return res.json() as Promise<T>;}
const JSON_HEADERS = { 'Content-Type': 'application/json' };
function get<T>(url: string): Promise<T> { return fetch(url).then((res) => handle<T>(res));}
function post<T>(url: string, body?: unknown): Promise<T> { return fetch(url, { method: 'POST', headers: JSON_HEADERS, body: body === undefined ? undefined : JSON.stringify(body), }).then((res) => handle<T>(res));}
// ---------------------------------------------------------------- ODD coverage
export interface OddDimensionInfo { values: string[]; iso34503_category: string; instrumented: boolean; source: string;}
export interface OddTaxonomy { standard_basis: string; dimensions: Record<string, OddDimensionInfo>; [k: string]: unknown;}
export interface OddCell { cell_id: string; cell: Record<string, string>; n: number; tp: number; fn: number; recall: number | null; mean_iou: number | null; wilson_ci: [number, number] | null; ci_width: number | null; production_share: number; adequate: boolean; is_gap: boolean; gap_reasons: string[]; performance_deficit: number;}
export interface OddFillRequest { cell_id: string; cell: Record<string, string>; needed_samples: number; risk: number; generator: string; request: Record<string, unknown>;}
export interface OddCoverageResponse { dims: string[]; thresholds: { min_samples: number; max_ci_width: number; target_recall: number }; summary: { total_cells: number; populated_cells: number; empty_cells: number; adequate_cells: number; gap_cells: number; coverage_rate: number; production_weighted_coverage: number; overall_recall: number; }; gaps: OddCell[]; fill_requests: OddFillRequest[]; cells?: OddCell[]; method: string; run_id: string; population_id: string; model_version: string;}
export const getOddTaxonomy = () => get<OddTaxonomy>('/api/safety/odd/taxonomy');
export const getOddCoverage = (run: string, dims: string[] | null, includeCells: boolean) => { const p = new URLSearchParams({ run, include_cells: String(includeCells), max_gaps: '100' }); if (dims && dims.length) p.set('dims', dims.join(',')); return get<OddCoverageResponse>(`/api/safety/odd/coverage?${p.toString()}`);};
export interface FillGapResult { [k: string]: unknown;}
export const fillOddGap = (run: string, cell: Record<string, string>, numSequences = 2) => post<FillGapResult>('/api/safety/odd/fill-gap', { run, cell, num_sequences: numSequences });
// ---------------------------------------------------------------- release gates
export interface GateCheck { check: string; actual: number | string | boolean | null; threshold: number | string | boolean | null; direction: string; passed: boolean;}
export interface GateResult { gate: string; name: string; status: 'PASS' | 'BLOCK' | 'SKIPPED' | string; standard_refs: string[]; checks: GateCheck[]; evidence: Record<string, unknown>; notes: string; evaluated_at: string;}
export interface GateEvaluation { candidate_run_id: string; baseline_run_id: string; decision: 'RELEASE_READY' | 'BLOCKED' | string; blocking_gates: string[]; gates: GateResult[]; policy: Record<string, Record<string, unknown>>; evidence_package_id: string; evaluated_at: string;}
export const evaluateGates = (candidateRun: string, baselineRun: string, policyOverrides?: Record<string, unknown>) => post<GateEvaluation>('/api/safety/gates/evaluate', { candidate_run: candidateRun, baseline_run: baselineRun, policy_overrides: policyOverrides, });
export const getGatePolicy = () => get<{ policy: Record<string, Record<string, unknown>>; defaults: Record<string, Record<string, unknown>> }>( '/api/safety/gates/policy' );
export const setGatePolicy = (overrides: Record<string, unknown>) => post<{ policy: Record<string, Record<string, unknown>> }>('/api/safety/gates/policy', { overrides });
export const getGateResult = (runId: string) => get<GateEvaluation>(`/api/safety/gates/result/${encodeURIComponent(runId)}`);
export interface EvidenceMarkdown { run_id: string; format: 'markdown'; markdown: string;}
export const getEvidenceMarkdown = (runId: string) => get<EvidenceMarkdown>(`/api/safety/evidence/${encodeURIComponent(runId)}?format=markdown`);
export const getEvidenceJson = (runId: string) => get<Record<string, unknown>>(`/api/safety/evidence/${encodeURIComponent(runId)}?format=json`);
// ---------------------------------------------------------------- SSAM
export interface SsamConflict { vehicle_a: string; vehicle_b: string; conflict_type: string; t_start_s: number; t_end_s: number; duration_s: number; min_ttc_s: number | null; pet_s: number | null; max_drac_mps2: number | null; delta_s_mps: number | null; max_s_mps: number | null; collision_probability: number; probability_exposure_s: number; csi: number; mass_proxy_reduced: number; conflict_point: [number, number] | null;}
export interface SsamAnalysis { params: Record<string, number>; conflicts: SsamConflict[]; aggregate: { num_conflicts: number; by_type: Record<string, number>; min_ttc_s: number | null; min_pet_s: number | null; max_drac_mps2: number | null; max_delta_s_mps: number | null; max_s_mps: number | null; max_collision_probability: number | null; aggregate_csi: number; mean_csi_per_conflict: number; observed_duration_s: number; }; measures_glossary: Record<string, string>; generated?: { scenario: string; seed: number; reaction_delay_s: number; simulated: boolean };}
export interface SsamTrajectoryState { t: number; x: number; y: number; speed: number; heading: number;}
export interface SsamTrajectory { vehicle_id: string; vehicle_type?: string; length?: number; width?: number; states: SsamTrajectoryState[];}
export const analyzeSsam = (body: { scenario?: string; seed?: number; reaction_delay_s?: number; trajectories?: SsamTrajectory[]; params?: Record<string, number>;}) => post<SsamAnalysis>('/api/safety/ssam/analyze', body);
export interface SsamRunSummary { [k: string]: unknown;}
export const getSsamSummary = (run: string) => get<SsamRunSummary>(`/api/safety/ssam/summary?run=${encodeURIComponent(run)}`);
// ---------------------------------------------------------------- calibration
export type CalibrationMode = 'clean' | 'miscalibrated' | 'perception_failure';
export interface CalibrationCheck { name: string; actual: number; threshold: number; passed: boolean;}
export interface CalibrationObject { object_id: string; class_name: string; residual_px: [number, number]; residual_magnitude_px: number; inlier_ratio: number; flagged: boolean; failure_reason: string | null;}
export interface CalibrationResult { status: 'CALIBRATED' | 'MISCALIBRATED' | 'PERCEPTION_FAILURE' | 'NEVER_RUN' | string; passed?: boolean; sensor_pair?: string; checks?: CalibrationCheck[]; metrics?: { bias_px: number; bias_vector_px: [number, number]; scatter_px: number; mean_inlier_ratio: number; outlier_fraction: number; estimated_rotation_offset_deg: number; num_objects: number; }; per_object?: CalibrationObject[]; thresholds?: Record<string, number>; diagnosis?: string; simulated?: boolean; mode?: string; injected?: Record<string, number>; seed?: number; created_at?: string; note?: string;}
export const validateCalibration = (body: { mode: CalibrationMode; rotation_offset_deg?: number; translation_offset_m?: number; tamper_fraction?: number; num_objects?: number; seed?: number;}) => post<CalibrationResult>('/api/safety/calibration/validate', body);
export const getCalibrationStatus = () => get<CalibrationResult>('/api/safety/calibration/status');
// ---------------------------------------------------------------- discrepancy mining
export interface DiscrepancyItem { [k: string]: unknown;}
export interface DiscrepancyReport { dataset_id: string; total_labels?: number; num_discrepancies?: number; discrepancy_rate?: number; by_type?: Record<string, number>; by_class?: Record<string, number>; by_cohort?: Array<Record<string, unknown>>; cohorts?: Array<Record<string, unknown>>; discrepancies?: DiscrepancyItem[]; discrepancies_truncated?: boolean; [k: string]: unknown;}
export const mineDiscrepancies = (datasetId?: string) => post<DiscrepancyReport>('/api/safety/discrepancy/mine', datasetId ? { dataset_id: datasetId } : {});
export const getDiscrepancySummary = (datasetId?: string) => get<DiscrepancyReport | { datasets: DiscrepancyReport[] }>( datasetId ? `/api/safety/discrepancy/summary?dataset_id=${encodeURIComponent(datasetId)}` : '/api/safety/discrepancy/summary' );
// ---------------------------------------------------------------- scenario DB
export interface ScenarioRecord { scenario_id: string; source: string; scenario_type: string; severity: string; description: string; odd_tags: Record<string, string>; tags?: string[]; created_at?: string; [k: string]: unknown;}
export interface ScenarioCounts { total: number; by_source: Record<string, number>; by_severity: Record<string, number>; by_type: Record<string, number>;}
export interface ScenariosResponse { counts: ScenarioCounts; scenarios: ScenarioRecord[];}
export const searchScenarios = (filters: { scenario_type?: string; source?: string; severity?: string; weather?: string; lighting?: string; text?: string; limit?: number;}) => { const p = new URLSearchParams(); Object.entries(filters).forEach(([k, v]) => { if (v !== undefined && v !== null && v !== '') p.set(k, String(v)); }); return get<ScenariosResponse>(`/api/safety/scenarios?${p.toString()}`);};
export const populateScenarios = () => post<{ imported_rare_events: number; counts: ScenarioCounts }>('/api/safety/scenarios/populate');
export const exportScenarios = (filters: { scenario_type?: string; source?: string; severity?: string; text?: string;}) => post<Record<string, unknown>>('/api/safety/scenarios/export', filters);
// ---------------------------------------------------------------- semantic search
export interface SemanticStage { stage?: string; [k: string]: unknown;}
export interface SemanticResult { [k: string]: unknown;}
export interface SemanticSearchResponse { concept?: string; provider?: string; llm_used?: boolean; interpretation?: Record<string, unknown>; results: SemanticResult[]; stages?: SemanticStage[]; [k: string]: unknown;}
export const semanticSearch = (body: { concept: string; target: 'containers' | 'scenarios'; run?: string; k?: number; use_llm?: boolean | null; filters?: Record<string, unknown>;}) => post<SemanticSearchResponse>('/api/safety/semantic-search', body);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194/** * Typed fetch wrappers + contracts for the anytime-valid sequential * regression-detection engine (/api/seqeval/*). * * Decision semantics (from GET /policy): * REGRESSION → block (evidence of a drop beyond the margin) * PASS → allow (equivalence proven within the margin) * INSUFFICIENT_EVIDENCE → not proven equivalent; never treated as a pass */
async function handle<T>(res: Response): Promise<T> { if (!res.ok) { const body = await res.text().catch(() => ''); throw new Error(`API ${res.status}: ${body || res.statusText}`); } return res.json() as Promise<T>;}
const JSON_HEADERS = { 'Content-Type': 'application/json' };
function get<T>(url: string): Promise<T> { return fetch(url).then((res) => handle<T>(res));}
function post<T>(url: string, body?: unknown): Promise<T> { return fetch(url, { method: 'POST', headers: JSON_HEADERS, body: body === undefined ? undefined : JSON.stringify(body), }).then((res) => handle<T>(res));}
// ---------------------------------------------------------------- contracts
export type SeqDecision = 'REGRESSION' | 'PASS' | 'INSUFFICIENT_EVIDENCE';
export interface SeqModelSpec { model_version: string; effects: Record<string, number>; fingerprint?: string;}
export interface SeqNode { node: string; // "overall" | "class:vehicle" | "stratum:pedestrian|night" | ... level: number; n: number; n_clusters: number; delta_estimate: number; delta_ci: [number, number]; e_regression: number; e_pass: number; p_analogue: number | null; bayes_p_regression: number | null; decision: SeqDecision; safety_primary: boolean; suspect: boolean; alpha_allocated: number; e_threshold_regression: number; e_threshold_pass: number;}
export interface TrajectoryPoint { n: number; n_clusters: number; delta_estimate: number; delta_lower: number; delta_upper: number; log_e_regression: number; log_e_pass: number; decision: SeqDecision;}
export interface NodeTrajectory { points: TrajectoryPoint[]; boundaries: { log_e_regression: number; log_e_pass: number; delta_margin: number };}
export interface SeqBudget { planned_total: number; samples_used: number; escalation_used: number; full_population: number; fraction_of_population: number;}
export interface SeqStratumPlan { key: string; class: string; condition: string; N: number; allocated: number; clusters: number; reserve: number; weight: number; safety_primary: boolean;}
export interface SeqPlan { plan_id: string; plan_hash: string; population_id: string; dataset_fingerprint: string; seed: number; created_at: string; config: Record<string, unknown>; population_objects: number; total_allocated: number; strata: Record<string, SeqStratumPlan>; frozen_before_candidate_outcomes: boolean;}
export interface SeqRunState { run_id: string; population_id: string; baseline: SeqModelSpec; candidate: SeqModelSpec; status: 'running' | 'done' | 'failed' | string; stage: string; decision: SeqDecision | null; gate: 'block' | 'allow' | 'expand_budget_or_report' | string | null; message: string | null; stopping_reason: string | null; error: string | null; seed: number; policy: { metric: string; delta_margin: number; alpha: number; alpha_pass: number; alpha_shares: Record<string, number>; condition_dim: string; safety_primaries: string[]; target_n: number; [k: string]: unknown; }; sanity: Record<string, unknown> | null; budget: SeqBudget | null; plan: SeqPlan | null; nodes: SeqNode[]; attribution?: SeqAttribution | null; trajectories?: Record<string, NodeTrajectory>; created_at: string; finished_at: string | null;}
export interface SeqAttribution { run_id?: string; decision?: SeqDecision | null; gate?: string | null; classes?: string[]; conditions?: string[]; cells?: Array<{ class: string; condition: string; delta: number | null; n?: number; flagged?: boolean; [k: string]: unknown; }>; [k: string]: unknown;}
export interface SeqPolicyInfo { default_policy: Record<string, unknown>; decision_semantics: Record<string, string>; test_method: string; multiple_testing_method: string; notes: string[];}
// ---------------------------------------------------------------- endpoints
export const listSeqRuns = () => get<{ runs: SeqRunState[] }>('/api/seqeval/runs');
export const getSeqRun = (runId: string) => get<SeqRunState>(`/api/seqeval/runs/${encodeURIComponent(runId)}`);
export const getSeqAttribution = (runId: string) => get<SeqAttribution>(`/api/seqeval/runs/${encodeURIComponent(runId)}/attribution`);
export const getSeqEvidence = (runId: string) => get<{ run_id: string; records: Array<Record<string, unknown>>; lineage: Record<string, unknown>; required_fields: string[] }>( `/api/seqeval/runs/${encodeURIComponent(runId)}/evidence` );
export const getSeqPolicy = () => get<SeqPolicyInfo>('/api/seqeval/policy');
export const startSeqRun = (body: { population_id: string; baseline: { model_version: string; effects: Record<string, number> }; candidate: { model_version: string; effects: Record<string, number> }; policy?: Record<string, unknown>; seed?: number; sync?: boolean;}) => post<SeqRunState>('/api/seqeval/runs', body);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116/** * Studio-UX helper service: dashboard layout persistence and capability * probing for optional backends. * * Layout persistence is dual-path: localStorage always (works offline / * without the optional router), plus best-effort sync to the small * /api/studio-ux backend when it is mounted, so layouts survive browser * storage resets and follow the backend store. */
const LS_PREFIX = 'sf-studio-ux:';
async function handle<T>(res: Response): Promise<T> { if (!res.ok) { const body = await res.text().catch(() => ''); throw new Error(`API ${res.status}: ${body || res.statusText}`); } return res.json() as Promise<T>;}
// ---------------------------------------------------------------- layouts
export function loadLayoutLocal<T>(key: string): T | null { try { const raw = localStorage.getItem(LS_PREFIX + key); return raw ? (JSON.parse(raw) as T) : null; } catch { return null; }}
export function saveLayoutLocal<T>(key: string, value: T): void { try { localStorage.setItem(LS_PREFIX + key, JSON.stringify(value)); } catch { /* storage full / private mode — backend sync still applies */ }}
export async function loadLayoutRemote<T>(key: string): Promise<T | null> { try { const res = await fetch(`/api/studio-ux/layouts/${encodeURIComponent(key)}`); if (!res.ok) return null; const body = (await res.json()) as { key: string; value: T | null }; return body.value ?? null; } catch { return null; }}
export function saveLayoutRemote<T>(key: string, value: T): void { // fire-and-forget; localStorage is the guaranteed path fetch(`/api/studio-ux/layouts/${encodeURIComponent(key)}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value }), }).catch(() => undefined);}
/** Load a layout preferring the backend copy, falling back to localStorage. */export async function loadLayout<T>(key: string): Promise<T | null> { const remote = await loadLayoutRemote<T>(key); if (remote !== null) return remote; return loadLayoutLocal<T>(key);}
export function saveLayout<T>(key: string, value: T): void { saveLayoutLocal(key, value); saveLayoutRemote(key, value);}
// ---------------------------------------------------------------- capability probe
export interface Capabilities { ssamAnalyze: boolean; bevfusion: boolean; nextgenCounterfactual: boolean; studioUx: boolean;}
let capCache: Capabilities | null = null;
async function probe(url: string, init?: RequestInit): Promise<boolean> { try { const res = await fetch(url, init); // Any non-404 answer means the router is mounted (405/422 count as present). return res.status !== 404; } catch { return false; }}
/** * Feature-detect the optional scene-consuming / persistence APIs once per * session. Pages hide actions whose backing endpoint is absent. */export async function getCapabilities(force = false): Promise<Capabilities> { if (capCache && !force) return capCache; const [ssamAnalyze, bevfusion, nextgenCounterfactual, studioUx] = await Promise.all([ probe('/api/safety/ssam/analyze', { method: 'OPTIONS' }), probe('/api/bevfusion/status'), probe('/api/nextgen/counterfactual', { method: 'OPTIONS' }), probe('/api/studio-ux/layouts/__probe__'), ]); capCache = { ssamAnalyze, bevfusion, nextgenCounterfactual, studioUx }; return capCache;}
export async function fetchJson<T>(url: string, body?: unknown): Promise<T> { const res = await fetch(url, { method: body === undefined ? 'GET' : 'POST', headers: body === undefined ? undefined : { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body), }); return handle<T>(res);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115/** * Shared design tokens + theme factory for Sensorflow Studio. * * Semantic color tokens (success / warn / danger / info / neutral) are the * single source of truth for state coloring across pages — use these instead * of ad-hoc hex values in new code. Existing pages keep their local palettes; * the values here intentionally match the established dark-theme colors so * adoption is a no-op visually. */import { createTheme, type Theme } from '@mui/material/styles';
export const tokens = { color: { success: '#66bb6a', successBg: 'rgba(102,187,106,0.12)', successStrong: '#1b5e20', warn: '#f9a825', warnBg: 'rgba(249,168,37,0.12)', danger: '#ef5350', dangerBg: 'rgba(239,83,80,0.14)', dangerStrong: '#b71c1c', info: '#4fc3f7', infoBg: 'rgba(79,195,247,0.12)', neutral: '#8a949e', neutralBg: 'rgba(138,148,158,0.12)', text: '#e6e9ec', textDim: '#aab4be', textFaint: '#5c6873', surface: '#161b21', surfaceRaised: '#1b222a', surfaceSunken: '#12171d', canvas: '#101418', border: '#232a31', borderStrong: '#2f3944', }, motion: { fast: '120ms cubic-bezier(0.4, 0, 0.2, 1)', normal: '200ms cubic-bezier(0.4, 0, 0.2, 1)', slow: '320ms cubic-bezier(0.4, 0, 0.2, 1)', }, radius: { sm: 4, md: 8, lg: 12 }, elevation: { raised: '0 2px 10px rgba(0,0,0,0.35)', overlay: '0 6px 24px rgba(0,0,0,0.5)', },} as const;
/** Color for a signed delta where positive = good (e.g. recall delta). */export function deltaColor(delta: number, higherIsBetter = true, eps = 1e-9): string { if (Math.abs(delta) < eps) return tokens.color.neutral; const improved = higherIsBetter ? delta > 0 : delta < 0; return improved ? tokens.color.success : tokens.color.danger;}
/** Traffic-light color for pass/block/unknown-style verdicts. */export function verdictColor(v: string | null | undefined): string { const s = (v ?? '').toUpperCase(); if (['PASS', 'PROMOTE', 'RELEASE_READY', 'CALIBRATED', 'ALLOW', 'OK'].includes(s)) return tokens.color.success; if (['BLOCK', 'BLOCKED', 'FAIL', 'REGRESSION', 'MISCALIBRATED', 'DO_NOT_PROMOTE', 'PERCEPTION_FAILURE'].includes(s)) return tokens.color.danger; if (['WARN', 'INSUFFICIENT_EVIDENCE', 'DEGRADED', 'NEVER_RUN'].includes(s)) return tokens.color.warn; return tokens.color.neutral;}
export function buildTheme(): Theme { return createTheme({ palette: { mode: 'dark', background: { default: tokens.color.canvas, paper: tokens.color.surface }, primary: { main: tokens.color.info }, success: { main: tokens.color.success }, warning: { main: tokens.color.warn }, error: { main: tokens.color.danger }, info: { main: tokens.color.info }, divider: tokens.color.border, }, typography: { fontFamily: "'Inter', 'Helvetica Neue', Arial, sans-serif", }, components: { MuiButtonBase: { styleOverrides: { root: { // Keyboard-focus visibility: a clear outline that never shows on mouse click. '&.Mui-focusVisible': { outline: `2px solid ${tokens.color.info}`, outlineOffset: 1, }, }, }, }, MuiButton: { styleOverrides: { root: { transition: `background-color ${tokens.motion.fast}, border-color ${tokens.motion.fast}, color ${tokens.motion.fast}` }, }, }, MuiCard: { styleOverrides: { root: { transition: `border-color ${tokens.motion.normal}, box-shadow ${tokens.motion.normal}` }, }, }, MuiChip: { styleOverrides: { root: { transition: `background-color ${tokens.motion.fast}` }, }, }, MuiSkeleton: { defaultProps: { animation: 'wave' }, styleOverrides: { root: { backgroundColor: 'rgba(138,148,158,0.09)' }, }, }, }, });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326/** Types for the Agentic Launch Readiness subsystem (/api/agentic). */
export type EvidenceStatus = 'OBSERVED' | 'DERIVED' | 'HYPOTHESIS' | 'UNAVAILABLE';export type EvidenceQuality = 'CONFIRMED' | 'LIKELY' | 'POSSIBLE' | 'INSUFFICIENT_EVIDENCE';export type Severity = 'S0' | 'S1' | 'S2' | 'S3' | 'S4' | 'S5';export type PolicyOutcome = | 'AUTOMATIC_STOP_SHIP' | 'LAUNCH_REVIEW_REQUIRED' | 'CONTINUE_INVESTIGATION' | 'NO_LAUNCH_IMPACT' | 'INDETERMINATE';export type OptionCode = | 'STOP_SHIP' | 'OPTION_A_DELAY' | 'OPTION_B_MITIGATION' | 'OPTION_C_REDUCED_ODD' | 'EXPAND_EVALUATION' | 'HUMAN_SAFETY_REVIEW' | 'PROCEED';export type StageStatus = 'pending' | 'running' | 'complete' | 'failed' | 'blocked';
export const STAGES = [ 'FAILURE_DETECTION', 'EVIDENCE_AGGREGATION', 'FAILURE_ANALYSIS', 'LAUNCH_DECISION', 'LEARNING_FLYWHEEL',] as const;export type Stage = (typeof STAGES)[number];
export interface FailureInstance { instance_id: string; sequence_id: string; frame_id: string; frame_index: number; object_instance_id: string; gt_class: string; predicted_class: string; confidence: number; distance_m: number; construction_zone: boolean; time_of_day: string; weather: string; geo_bucket: string; occluded: boolean; has_planner_trace: boolean;}
export interface DetectionBasis { method: string; candidate_events: number; baseline_events: number; denominator: number; candidate_rate: number; baseline_rate: number; metric_deltas: Record<string, number>; notes: string[];}
export interface FailureEvent { failure_id: string; kind: string; title: string; description: string; gt_class: string | null; predicted_class: string | null; detection_basis: DetectionBasis; instances: FailureInstance[]; baseline_model: string; candidate_model: string; status: string; severity: Severity | null; policy_outcome: PolicyOutcome | null; validated: boolean; created_at: string;}
export interface AgentEscalation { required: boolean; reasons: string[]; human_review_triggers: string[];}
export interface AgentResult { agent: string; agent_version: string; failure_id: string; status: 'ok' | 'failed' | 'escalated'; authority: 'ADVISORY_ONLY'; output: Record<string, unknown>; confidence: number; confidence_basis: string; epistemic_status: EvidenceStatus; escalation: AgentEscalation; llm_used: boolean; llm_rationale: string | null;}
export interface EvidenceNode { node_id: string; node_type: string; status: EvidenceStatus; summary: string; fields: Record<string, unknown>; source: string; caveats: string[];}
export interface EvidenceGraph { failure_id: string; nodes: EvidenceNode[]; edges: { src: string; dst: string; relation: string }[]; built_at: string;}
export interface RateEstimate { events: number; denominator: number; rate: number; wilson_ci: number[]; ci_method: string;}
export interface StatisticalAssessment { baseline: RateEstimate; candidate: RateEstimate; absolute_delta: number; relative_delta: number | null; significant: boolean; significance_method: string; exact_binomial_p: number | null; seqeval: { delegated_to: string; test_method: string; delta_margin: number; alpha: number; decision: string; snapshot: Record<string, unknown>; clusters_fed: number; note: string; }; power_mde: { mde_abs: number | null; observed_abs_delta: number; assessment: string; method: string }; small_sample_flags: string[]; rare_event_handling: string;}
export interface StratumRisk { dimension: string; stratum: string; exposure: number; exposure_share: number; events: number; stratum_rate: number; baseline_rate: number; relative_risk: number | null; odds_ratio: number | null; risk_difference: number; rate_wilson_ci: number[]; small_sample_flag: boolean;}
export interface ConcentrationAnalysis { failure_id: string; determination: 'concentrated' | 'uniform' | 'insufficient_data'; concentrated_dimensions: string[]; strata: StratumRisk[]; method: string;}
export interface ExpectedLossRow { option: OptionCode; business_cost: number; residual_failure_rate: number; expected_incidents_per_release: number; expected_loss: number; feasible: boolean; infeasible_reason: string | null;}
export interface PolicyEvaluation { outcome: PolicyOutcome; severity: Severity; severity_assignment?: { taxonomy_description?: string; criteria_fired?: string[] }; policy_version: string; recommended_option: OptionCode; matrix_row_fired: { row: number; condition: string; option: OptionCode; description: string } | null; automatic_stop_ship_condition: { condition_id: string; description?: string } | null; option_c_evaluation: { feasible: boolean; checks: { check: string; passed: boolean; detail?: string }[] } | null; expected_loss_table: ExpectedLossRow[]; mandatory_review_triggers?: { trigger: string; description: string; fired: boolean }[]; indeterminate_reasons?: string[]; input?: Record<string, unknown>; note?: string;}
export interface StageRecord { stage: Stage; status: StageStatus; started_at: string | null; finished_at: string | null; detail: string;}
export interface PipelineState { failure_id: string; stages: StageRecord[]; agent_results: Record<string, AgentResult>; statistical: StatisticalAssessment | null; concentration: ConcentrationAnalysis | null; policy_evaluation: PolicyEvaluation | null; scorecard_id: string | null; suite_ids: string[]; updated_at: string;}
export interface ScorecardField { value: unknown; tag: 'OBSERVED' | 'PREDICTED' | 'HYPOTHETICAL' | 'REQUIRED_EVIDENCE'; evidence_ref: string;}
export interface Scorecard { scorecard_id: string; failure_id: string; title: string; failure_summary: ScorecardField; frequency: ScorecardField; exposure: ScorecardField; severity: ScorecardField; confidence: ScorecardField; novelty: ScorecardField; concentration: ScorecardField; downstream_impact: ScorecardField; mitigations: ScorecardField; residual_risk: ScorecardField; evidence_quality: EvidenceQuality; policy_outcome: PolicyOutcome | null; recommended_option: OptionCode | null; policy_version: string; generated_at: string; notes: string[];}
export interface HumanReviewDecision { review_id: string; failure_id: string; reviewer: string; decision: string; approved_option: OptionCode | null; evidence_reviewed: string[]; policy_version: string; rationale: string; override_reason: string | null; timestamp: string;}
export interface SuiteMember { member_id: string; sequence_id: string; frame_id: string; object_instance_id: string; source_failure_id: string; training_eligible: boolean;}
export interface EvaluationSuite { suite_id: string; name: string; version: number; creation_reason: string; source_failures: string[]; taxonomy_tags: string[]; sampling_policy: string; coverage: Record<string, unknown>; known_limitations: string[]; approval_status: 'draft' | 'approved' | 'retired'; members: SuiteMember[]; contamination_guard: string; governance_overrides: { member_id: string; actor: string; reason: string; timestamp: string }[]; created_at: string; updated_at: string;}
export interface RegressionSuiteResult { suite: string; suite_id?: string | null; n: number; n_clusters?: number; baseline_rate?: number; candidate_rate?: number; delta?: number; delta_ci?: number[]; decision: string; note?: string; stats_delegated_to?: string;}
export interface AuditRecord { seq: number; event_type: string; failure_id: string | null; actor: string; detail: string; payload: Record<string, unknown>; timestamp: string; prev_hash: string; hash: string;}
export interface LabeledValue<T = unknown> { label: 'OBSERVED' | 'HYPOTHETICAL' | 'REQUIRED-EVIDENCE' | 'DERIVED'; value: T;}
export interface Walkthrough { methodology_provenance: string; seed: number; deterministic: boolean; failure_id: string; title: string; layers: Record<string, Record<string, LabeledValue>>; scorecard_id: string | null; audit_records: LabeledValue<number>; audit_chain_valid: LabeledValue<boolean>; separation_of_powers: string;}1234567891011121314151617181920212223242526272829303132333435363738"""Shared fixtures: isolated agentic storage root + one worked-example runreused by every test module (the pipeline is deterministic, so sharing issafe and keeps the suite fast)."""
from __future__ import annotations
import pytest
from sensorflow.agentic import data as data_modfrom sensorflow.agentic import store as store_mod
@pytest.fixture(scope="session", autouse=True)def agentic_env(tmp_path_factory): root = tmp_path_factory.mktemp("agentic_env") store_mod.set_agentic_root(str(root)) data_mod.reset_data_cache() yield {"root": root} store_mod.set_agentic_root("runs/agentic") data_mod.reset_data_cache()
@pytest.fixture(scope="session")def walkthrough(agentic_env): from sensorflow.agentic import worked_example as we_mod return we_mod.run_worked_example()
@pytest.fixture(scope="session")def ped_cone_failure(walkthrough): from sensorflow.agentic import pipeline as pipeline_mod return pipeline_mod.get_failure(walkthrough["failure_id"])
@pytest.fixture(scope="session")def ped_cone_state(walkthrough): from sensorflow.agentic import pipeline as pipeline_mod return pipeline_mod.get_state(walkthrough["failure_id"])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189"""Agents: seqeval delegation, small-sample flags, fusion-conflict escalation,hypothesis labeling, safety UNCERTAIN handling, advisory-only authority."""
from __future__ import annotations
from sensorflow.agentic import data as data_modfrom sensorflow.agentic import review as review_modfrom sensorflow.agentic.agents import (SafetyImpactAgent, SensorFusionVerificationAgent, StatisticalRegressionAgent, VLMSceneAnalysisAgent)from sensorflow.agentic.agents import statistical as stat_modfrom sensorflow.agentic.models import (DetectionBasis, FailureEvent, FailureInstance, new_id)
def _instance(**overrides) -> FailureInstance: kwargs = dict( instance_id=new_id("inst"), sequence_id="bev-seq-101-0", frame_id="bev-seq-101-0-f0006", frame_index=6, object_instance_id="bev-seq-101-0-obj-1", gt_class="pedestrian", predicted_class="construction_cone", confidence=0.62, distance_m=22.0, construction_zone=True, time_of_day="day", weather="clear", geo_bucket="bay_area_urban", occluded=False, has_planner_trace=False) kwargs.update(overrides) return FailureInstance(**kwargs)
def _failure(instances) -> FailureEvent: return FailureEvent( failure_id=new_id("fail"), kind="classification_flip", title="pedestrian misclassified as construction_cone", gt_class="pedestrian", predicted_class="construction_cone", detection_basis=DetectionBasis( method="test", candidate_events=25, baseline_events=5, denominator=240_000, candidate_rate=25 / 240_000, baseline_rate=5 / 240_000), instances=instances, dataset_fingerprint="fp-test", population_id="rate-pop-test")
# ------------------------------------------------------------------ statistical
def test_statistical_agent_delegates_to_seqeval_and_flags_small_samples(monkeypatch): constructed = [] real_cls = stat_mod.PairedSequentialTest
class SpyTest(real_cls): def __init__(self, *a, **kw): constructed.append((a, kw)) super().__init__(*a, **kw)
monkeypatch.setattr(stat_mod, "PairedSequentialTest", SpyTest) agent = StatisticalRegressionAgent() assessment = agent.assess(seed=data_mod.DEFAULT_SEED)
# the anytime-valid machinery really is seqeval's, not a reimplementation assert constructed, "PairedSequentialTest (seqeval) was not instantiated" assert assessment.seqeval["delegated_to"] == \ "sensorflow.seqeval.sequential.PairedSequentialTest" assert assessment.seqeval["decision"] in ( "REGRESSION", "PASS", "INSUFFICIENT_EVIDENCE") assert assessment.power_mde["method"] == \ "sensorflow.seqeval.sequential.approx_mde"
# rare-event handling: exact binomial drives the significance claim assert "binomial" in assessment.significance_method assert assessment.exact_binomial_p is not None assert assessment.significant is True
# small-sample instability is flagged (few dozen events on 240k denom) assert assessment.small_sample_flags assert any("event count" in f for f in assessment.small_sample_flags)
# Wilson CIs present and contain the point estimates lo, hi = assessment.candidate.wilson_ci assert lo <= assessment.candidate.rate <= hi
def test_statistical_agent_reports_measurements_not_hypotheses(): result = StatisticalRegressionAgent().run("fail-x", seed=data_mod.DEFAULT_SEED) assert result.authority == "ADVISORY_ONLY" assert result.epistemic_status == "OBSERVED" assert result.status == "ok"
# ------------------------------------------------------------------ fusion
class _FakeDet: def __init__(self, inst_id, cls, dims, x, y): self.source_instance_id = inst_id self.class_name = cls self.confidence = 0.9 self.dims = list(dims) self.x, self.y = x, y
def test_fusion_conflict_triggers_mandatory_human_review(ped_cone_failure, monkeypatch): """Force camera/LiDAR disagreement: camera says 'car' (non-VRU), LiDAR shape matches the GT pedestrian template -> modality_conflict, which must escalate to mandatory human review.""" from sensorflow.agentic.agents import fusion_verification as fv
inst = ped_cone_failure.instances[0] gt_dims = fv.scenes_mod.CLASS_DIMS.get(inst.gt_class, (0.8, 0.8, 1.8))
monkeypatch.setattr( fv.sensors_mod, "simulate_camera", lambda frame, seq, rng: [_FakeDet(inst.object_instance_id, "car", gt_dims, 10.0, 5.0)]) monkeypatch.setattr( fv.sensors_mod, "simulate_lidar", lambda frame, seq, rng: [_FakeDet(inst.object_instance_id, inst.gt_class, gt_dims, 10.0, 5.0)])
result = SensorFusionVerificationAgent().run( ped_cone_failure.failure_id, failure=ped_cone_failure) assert result.output["overall_verdict"] == "modality_conflict" assert result.escalation.required assert "modality_disagreement" in result.escalation.human_review_triggers
# and the governance layer fires the mandatory trigger on the verdict triggers = review_mod.mandatory_review_triggers( {"severity": "S1", "outcome": "CONTINUE_INVESTIGATION", "recommended_option": "EXPAND_EVALUATION"}, fusion_verdict="modality_conflict", gt_available=True, small_sample=False, behavioral_evidence="none") fired = {t["trigger"] for t in triggers if t["fired"]} assert "modality_disagreement" in fired
def test_fusion_agent_runs_deterministically(ped_cone_failure): r1 = SensorFusionVerificationAgent().run( ped_cone_failure.failure_id, failure=ped_cone_failure) r2 = SensorFusionVerificationAgent().run( ped_cone_failure.failure_id, failure=ped_cone_failure) assert r1.output["overall_verdict"] == r2.output["overall_verdict"] assert r1.output["per_instance"] == r2.output["per_instance"] assert r1.output["overall_verdict"] != "verification_failed"
# ------------------------------------------------------------------ VLM + safety
def test_vlm_output_is_always_labeled_hypothesis(): failure = _failure([_instance(), _instance(time_of_day="night")]) result = VLMSceneAnalysisAgent().run(failure.failure_id, failure=failure) assert result.epistemic_status == "HYPOTHESIS" assert "HYPOTHESIS" in result.output["epistemic_label"] assert all(h["label"] == "HYPOTHESIS" for h in result.output["hypotheses"]) # confidence capped: hypotheses can never look like confirmed evidence assert result.confidence <= 0.6
def test_safety_agent_uncertain_without_replay_evidence(): failure = _failure([_instance(has_planner_trace=False)]) result = SafetyImpactAgent().run(failure.failure_id, failure=failure) assert result.output["behavioral_evidence"] == "none" assert result.output["assessment"] == \ "safety assessment UNCERTAIN — no behavioral evidence" chain = {c["link"]: c["status"] for c in result.output["chain"]} assert chain["planner"] == "UNAVAILABLE" assert chain["behavior"] == "UNAVAILABLE" assert result.escalation.required # uncertainty escalates, never passes
def test_safety_agent_uses_replay_evidence_and_ssam_kinematics(): failure = _failure([_instance(has_planner_trace=True)]) result = SafetyImpactAgent().run(failure.failure_id, failure=failure) assert result.output["behavioral_evidence"] == "observed" assert result.output["replayed_instances"] == 1 kin = result.output["kinematics"] assert "ssam_ext" in kin["method"] # delayed reaction must cost stopping distance assert kin["stopping_distance_delayed_m"] > kin["stopping_distance_nominal_m"] chain = {c["link"]: c["status"] for c in result.output["chain"]} assert chain["planner"] == "OBSERVED" assert chain["behavior"] == "OBSERVED"
def test_agent_failure_is_captured_not_raised(): result = SafetyImpactAgent().run("fail-x", failure=None) # assert trips assert result.status == "failed" assert result.escalation.required assert "agent_failure" in result.escalation.human_review_triggers123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157"""API lifecycle over the /api/agentic router via TestClient."""
from __future__ import annotations
import copy
import pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient
from sensorflow.agentic.api import router
@pytest.fixture(scope="module")def client(agentic_env): app = FastAPI() app.include_router(router) return TestClient(app)
@pytest.fixture(scope="module")def ped_cone_id(client): res = client.post("/api/agentic/failures/detect", json={}) assert res.status_code == 200 events = res.json()["failures"] assert events flip = next(e for e in events if e["kind"] == "classification_flip" and "pedestrian" in e["title"] and "construction_cone" in e["title"]) return flip["failure_id"]
def test_detect_and_queue(client, ped_cone_id): res = client.get("/api/agentic/failures") assert res.status_code == 200 queue = res.json()["failures"] assert any(f["failure_id"] == ped_cone_id for f in queue) res = client.get(f"/api/agentic/failures/{ped_cone_id}") basis = res.json()["failure"]["detection_basis"] assert basis["denominator"] > 0 and basis["candidate_events"] > 0
def test_staged_analysis_and_evidence(client, ped_cone_id): # step stage by stage; stage order is enforced by the orchestrator for stage in ("EVIDENCE_AGGREGATION", "FAILURE_ANALYSIS", "LAUNCH_DECISION"): res = client.post( f"/api/agentic/failures/{ped_cone_id}/analyze?stage={stage}", json={}) assert res.status_code == 200, res.text state = res.json()["state"] rec = next(s for s in state["stages"] if s["stage"] == stage) assert rec["status"] == "complete"
res = client.get(f"/api/agentic/failures/{ped_cone_id}/evidence") graph = res.json()["graph"] assert {n["node_type"] for n in graph["nodes"]} >= {"Object", "GroundTruth", "Frequency"} res = client.get(f"/api/agentic/failures/{ped_cone_id}/snippets") assert res.json()["snippets"]
res = client.post(f"/api/agentic/failures/{ped_cone_id}/cluster", json={}) assert res.status_code == 200 res = client.post( f"/api/agentic/failures/{ped_cone_id}/safety-assessment", json={}) assert res.status_code == 200
res = client.post( f"/api/agentic/failures/{ped_cone_id}/launch-assessment", json={}) body = res.json() assert body["policy_evaluation"]["outcome"] in ( "AUTOMATIC_STOP_SHIP", "LAUNCH_REVIEW_REQUIRED", "CONTINUE_INVESTIGATION", "NO_LAUNCH_IMPACT", "INDETERMINATE") assert body["policy_evaluation"]["policy_version"]
def test_human_review_and_flywheel(client, ped_cone_id): res = client.post( f"/api/agentic/failures/{ped_cone_id}/human-review", json={"reviewer": "api-test-reviewer", "decision": "confirm_failure", "rationale": "GT verified against synthetic vendor labels", "evidence_reviewed": ["evidence_graph", "snippets"]}) assert res.status_code == 200 res = client.get(f"/api/agentic/failures/{ped_cone_id}/human-review") assert any(d["reviewer"] == "api-test-reviewer" for d in res.json()["decisions"])
# LEARNING_FLYWHEEL now permitted (failure validated by the human) res = client.post( f"/api/agentic/failures/{ped_cone_id}/analyze?stage=LEARNING_FLYWHEEL", json={}) assert res.status_code == 200
res = client.get("/api/agentic/evaluation-suites") suites = res.json()["suites"] assert suites suite = suites[0] res = client.get(f"/api/agentic/evaluation-suites/{suite['suite_id']}") assert res.status_code == 200
# contamination guard over the API: promotion without override -> 4xx member_id = suite["members"][0]["member_id"] res = client.post( f"/api/agentic/evaluation-suites/{suite['suite_id']}/promote-member", json={"member_id": member_id}) assert res.status_code in (400, 403, 409, 422)
def test_policy_endpoints(client): res = client.get("/api/agentic/policy") assert res.status_code == 200 doc = res.json()["policy"] assert doc["policy_version"] mutated = copy.deepcopy(doc) mutated["expected_loss"]["delay_cost"] = 123.0 res = client.post("/api/agentic/policy", json={"policy": mutated, "actor": "api-test"}) assert res.status_code == 200 new_version = res.json()["policy_version"] assert new_version != doc["policy_version"] res = client.get(f"/api/agentic/policy?version={doc['policy_version']}") assert res.status_code == 200 res = client.get("/api/agentic/policy/versions") assert len(res.json()["versions"]) >= 2 # restore the original as active for other tests res = client.post("/api/agentic/policy", json={"policy": doc, "actor": "api-test"}) assert res.status_code == 200
def test_regression_scorecard_audit_and_worked_example(client, ped_cone_id): res = client.post("/api/agentic/regression/evaluate", json={}) assert res.status_code == 200 assert res.json()["suites"]
res = client.get(f"/api/agentic/audit/{ped_cone_id}") body = res.json() assert body["records"] assert body["chain"]["valid"] is True
res = client.get("/api/agentic/worked-example") assert res.status_code == 200 we = res.json()["walkthrough"] assert we["layers"]["4_launch_decision"]["outcome"]["value"] card_id = we["scorecard_id"] res = client.get(f"/api/agentic/scorecards/{card_id}") assert res.status_code == 200 card = res.json()["scorecard"] for field in ("frequency", "exposure", "severity", "confidence", "novelty", "concentration", "downstream_impact", "mitigations", "residual_risk"): f = card[field] assert f["tag"] in ("OBSERVED", "PREDICTED", "HYPOTHETICAL", "REQUIRED_EVIDENCE") assert f["evidence_ref"]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""Evidence graph structure + snippet completeness and temporal context."""
from __future__ import annotations
from sensorflow.agentic import pipeline as pipeline_mod
REQUIRED_NODE_TYPES = { "Object", "Environment", "Sensors", "Prediction", "GroundTruth", "Tracking", "Planner", "HistoricalSimilarity", "Frequency", "SafetyConsequence",}
SNIPPET_REQUIRED_FIELDS = [ "scene_id", "sequence_id", "timestamp_us", "frame_index", "model_version_candidate", "model_version_baseline", "prediction", "ground_truth", "confidence", "tracking_state", "planner_state", "environment", "geo_bucket", "software_config", "hardware_config", "feature_pipeline_version", "temporal_context",]
def test_evidence_graph_has_all_spec_node_types(walkthrough): graph = pipeline_mod.get_evidence_graph(walkthrough["failure_id"]) assert graph is not None types = {n.node_type for n in graph.nodes} assert REQUIRED_NODE_TYPES <= types, REQUIRED_NODE_TYPES - types
def test_evidence_statuses_are_typed_and_honest(walkthrough): graph = pipeline_mod.get_evidence_graph(walkthrough["failure_id"]) allowed = {"OBSERVED", "DERIVED", "HYPOTHESIS", "UNAVAILABLE"} by_type = {n.node_type: n for n in graph.nodes} for n in graph.nodes: assert n.status in allowed assert n.summary # every node explains itself # GT comes from the synthetic vendor annotations -> OBSERVED assert by_type["GroundTruth"].status == "OBSERVED" # scene-context reasoning is a hypothesis, never ground truth assert by_type["Environment"].status in ("HYPOTHESIS", "OBSERVED") # every edge references real nodes ids = {n.node_id for n in graph.nodes} for e in graph.edges: assert e.src in ids and e.dst in ids
def test_snippet_completeness(walkthrough): snippets = pipeline_mod.get_snippets(walkthrough["failure_id"]) assert snippets, "no snippets were built" for snip in snippets: for field in SNIPPET_REQUIRED_FIELDS: assert snip.get(field) not in (None, "", [], {}), \ f"snippet missing {field}" assert snip["prediction"]["class"] == "construction_cone" assert snip["ground_truth"]["class"] == "pedestrian"
def test_snippets_carry_temporal_context_not_single_frames(walkthrough): snippets = pipeline_mod.get_snippets(walkthrough["failure_id"]) for snip in snippets: ctx = snip["temporal_context"] roles = {c["role"] for c in ctx} assert "failure" in roles # never single-frame when temporal context exists in the data assert len(ctx) > 1, "single-frame snippet emitted" assert roles & {"before", "after"} # frames ordered by index and centered on the failure idxs = [c["frame_index"] for c in ctx] assert idxs == sorted(idxs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121"""Flywheel: suite governance fields, diversity sampling, contaminationguard, and the seqeval-delegated regression hook."""
from __future__ import annotations
import pytest
from sensorflow.agentic import flywheel as flywheel_modfrom sensorflow.agentic.models import (DetectionBasis, FailureEvent, FailureInstance, new_id)
GOVERNANCE_FIELDS = ["suite_id", "version", "creation_reason", "source_failures", "sampling_policy", "coverage", "known_limitations", "approval_status"]
def _validated_failure(n_instances=6) -> FailureEvent: instances = [] for k in range(n_instances): # two objects, three frames each -> diversity sampling must cap at 2 obj = f"obj-{k % 2}" instances.append(FailureInstance( instance_id=new_id("inst"), sequence_id="seq-1", frame_id=f"seq-1-f{k:04d}", frame_index=k, object_instance_id=obj, gt_class="pedestrian", predicted_class="construction_cone", confidence=0.6, distance_m=20.0, construction_zone=True)) return FailureEvent( failure_id=new_id("fail"), kind="classification_flip", title="test flip", gt_class="pedestrian", predicted_class="construction_cone", detection_basis=DetectionBasis( method="test", candidate_events=n_instances, baseline_events=0, denominator=1000, candidate_rate=n_instances / 1000, baseline_rate=0.0), instances=instances, validated=True)
def test_suite_refused_for_unvalidated_failure(): failure = _validated_failure() failure.validated = False with pytest.raises(flywheel_mod.LeakageError): flywheel_mod.create_or_update_suite( failure, {"suite_name": "x", "creation_reason": "y"})
def test_suite_governance_fields_and_diversity_sampling(): failure = _validated_failure(n_instances=6) suite = flywheel_mod.create_or_update_suite( failure, {"suite_name": f"suite-{failure.failure_id}", "creation_reason": "validated test failure", "taxonomy_tags": ["pedestrian->construction_cone"], "sampling_policy": "diversity-aware", "known_limitations": ["synthetic"]}) doc = suite.model_dump() for field in GOVERNANCE_FIELDS: assert doc.get(field) not in (None, "", []), f"missing {field}" assert doc["approval_status"] == "draft" # 6 instances over 2 objects -> at most 2 frames per object kept assert len(suite.members) == 4 per_object = {} for m in suite.members: per_object[m.object_instance_id] = per_object.get(m.object_instance_id, 0) + 1 assert all(v <= flywheel_mod.MAX_FRAMES_PER_OBJECT for v in per_object.values()) # version bump on re-ingest, no duplicate members suite2 = flywheel_mod.create_or_update_suite( failure, {"suite_name": suite.name, "creation_reason": "re-ingest"}) assert suite2.suite_id == suite.suite_id assert suite2.version == suite.version + 1 assert len(suite2.members) == len(suite.members)
def test_contamination_guard_blocks_training_promotion(): failure = _validated_failure() suite = flywheel_mod.create_or_update_suite( failure, {"suite_name": f"guard-{failure.failure_id}", "creation_reason": "guard test"}) member = suite.members[0] assert member.training_eligible is False # unconditional default
with pytest.raises(flywheel_mod.LeakageError): flywheel_mod.promote_member_to_training(suite.suite_id, member.member_id) with pytest.raises(flywheel_mod.LeakageError): flywheel_mod.promote_member_to_training( suite.suite_id, member.member_id, actor="someone") # no reason
# explicit override (who + why) succeeds and is recorded result = flywheel_mod.promote_member_to_training( suite.suite_id, member.member_id, actor="data-lead", override_reason="approved augmentation experiment #42") assert result["training_eligible"] is True reloaded = flywheel_mod.get_suite(suite.suite_id) assert reloaded.governance_overrides assert reloaded.governance_overrides[-1]["actor"] == "data-lead"
def test_construction_zone_suite_auto_created_by_worked_example(walkthrough): layer5 = walkthrough["layers"]["5_learning_flywheel"] suite_ids = layer5["suites_created"]["value"] assert suite_ids suite = flywheel_mod.get_suite(suite_ids[0]) assert suite is not None assert "construction-zone" in suite.name assert suite.coverage["construction_zone_share"] > 0 assert all(m.training_eligible is False for m in suite.members)
def test_regression_hook_delegates_to_seqeval(): report = flywheel_mod.regression_evaluate() names = {r["suite"] for r in report["suites"]} assert {"general", "historical-regression", "rare-event", "safety-critical"} <= names evaluated = [r for r in report["suites"] if r["n"] > 0] assert evaluated for r in evaluated: assert r["stats_delegated_to"] == \ "sensorflow.seqeval.sequential.PairedSequentialTest" assert r["decision"] in ("PASS", "REGRESSION", "INSUFFICIENT_EVIDENCE") assert "delta_ci" in r and "delta" in r123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154"""Five-layer pipeline, worked-example determinism, epistemic labeling andaudit completeness (hash-chained, append-only)."""
from __future__ import annotations
import copyimport json
from sensorflow.agentic import store as store_modfrom sensorflow.agentic import worked_example as we_mod
STAGES = ["FAILURE_DETECTION", "EVIDENCE_AGGREGATION", "FAILURE_ANALYSIS", "LAUNCH_DECISION", "LEARNING_FLYWHEEL"]
def _strip_ids(obj): """Remove run-specific identifiers so two runs can be compared on substance.""" if isinstance(obj, dict): return {k: _strip_ids(v) for k, v in obj.items() if not (k.endswith("_id") or k.endswith("_at") or k in ("timestamp", "hash", "prev_hash", "evidence_ref", "narrative"))} if isinstance(obj, list): return [_strip_ids(v) for v in obj] if isinstance(obj, str): # ids are embedded in some prose fields; normalize them away for prefix in ("fail-", "snip-", "suite-", "inst-", "rev-", "card-"): if prefix in obj: return "<contains-id>" return obj return obj
def test_worked_example_completes_all_five_layers(walkthrough): assert set(walkthrough["layers"]) == { "1_failure_detection", "2_evidence_aggregation", "3_failure_analysis", "4_launch_decision", "5_learning_flywheel"} from sensorflow.agentic import pipeline as pipeline_mod state = pipeline_mod.get_state(walkthrough["failure_id"]) for stage in STAGES: assert state.stage_record(stage).status == "complete", stage # the methodology provenance disclosure is part of the artifact assert "was not provided" in walkthrough["methodology_provenance"]
def test_worked_example_values_are_epistemically_labeled(walkthrough): labels = set()
def collect(obj): if isinstance(obj, dict): if "label" in obj and "value" in obj: labels.add(obj["label"]) for v in obj.values(): collect(v) elif isinstance(obj, list): for v in obj: collect(v)
collect(walkthrough) assert labels <= {"OBSERVED", "HYPOTHETICAL", "REQUIRED-EVIDENCE", "DERIVED"} # all three spec labels actually occur assert {"OBSERVED", "HYPOTHETICAL", "REQUIRED-EVIDENCE"} <= labels
def test_worked_example_headline_numbers(walkthrough): l1 = walkthrough["layers"]["1_failure_detection"] assert l1["denominator"]["value"] == 240_000 assert l1["candidate_events"]["value"] == 25 rate = l1["observed_rate"]["value"] assert abs(rate - 1.0e-4) < 3.0e-5 # the motivating ~0.01%
l4 = walkthrough["layers"]["4_launch_decision"] assert l4["outcome"]["value"] == "LAUNCH_REVIEW_REQUIRED" assert l4["severity"]["value"] == "S4" assert l4["recommended_option"]["value"] == "OPTION_A_DELAY" # the final authorization is human, recorded, and references the policy decisions = l4["human_review"]["value"] assert decisions assert decisions[0]["decision"] == "confirm_failure" assert decisions[0]["policy_version"] assert decisions[0]["reviewer"] == "safety-reviewer-demo"
def test_scorecard_downstream_impact_observed_with_replay(walkthrough): """The safety agent escalates (unsafe replay behavior) but still produced OBSERVED replay evidence — the scorecard must not degrade that to REQUIRED_EVIDENCE just because the agent status is 'escalated'.""" from sensorflow.agentic import scorecard as scorecard_mod card = scorecard_mod.load_scorecard(walkthrough["scorecard_id"]) assert card["downstream_impact"]["tag"] == "OBSERVED" assert card["downstream_impact"]["value"]["behavioral_evidence"] == "observed" assert card["novelty"]["tag"] == "OBSERVED"
def test_worked_example_is_deterministic(tmp_path): """Two runs from two pristine storage roots must agree on every substantive value (only ids/timestamps may differ).""" original_root = store_mod.agentic_root() try: store_mod.set_agentic_root(str(tmp_path / "run_a")) run_a = we_mod.run_worked_example() store_mod.set_agentic_root(str(tmp_path / "run_b")) run_b = we_mod.run_worked_example() finally: store_mod.set_agentic_root(original_root) a, b = _strip_ids(run_a), _strip_ids(run_b) assert json.dumps(a, sort_keys=True, default=str) == \ json.dumps(b, sort_keys=True, default=str)
def test_audit_trail_is_complete_and_chained(walkthrough): fid = walkthrough["failure_id"] trail = store_mod.audit_trail(fid) events = {r["event_type"] for r in trail} # every stage transition, agent output, policy evaluation, human decision assert {"stage_transition", "agent_output", "policy_evaluated", "human_review_decision", "scorecard_generated", "suite_created_or_updated", "failure_validated"} <= events stage_details = " ".join(r["detail"] for r in trail if r["event_type"] == "stage_transition") for stage in STAGES[1:]: # detection transitions live in the global trail assert stage in stage_details agents_seen = {r["actor"] for r in trail if r["event_type"] == "agent_output"} assert {"vlm_scene_analysis", "sensor_fusion_verification", "scenario_mining", "statistical_regression", "safety_impact", "launch_decision", "eval_flywheel"} <= agents_seen # hash chain is intact and sequenced check = store_mod.verify_audit_chain(fid) assert check["valid"] is True assert check["records"] == len(trail)
def test_audit_tampering_is_detected(walkthrough): fid = walkthrough["failure_id"] trail = store_mod.audit_trail(fid) tampered = copy.deepcopy(trail) tampered[2]["detail"] = "history rewritten" import os path = os.path.join(store_mod.agentic_root(), "audit", f"{fid}.jsonl") with open(path) as f: original = f.read() try: with open(path, "w") as f: for rec in tampered: f.write(json.dumps(rec, default=str) + "\n") check = store_mod.verify_audit_chain(fid) assert check["valid"] is False assert check["broken_at_seq"] == 2 finally: with open(path, "w") as f: f.write(original) assert store_mod.verify_audit_chain(fid)["valid"] is True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223"""Policy engine: determinism, version hashing, pre-authorized stop-ship,INDETERMINATE fail-safe, severity taxonomy, the full option matrix and thesafety-as-hard-constraint guarantee."""
from __future__ import annotations
import copy
from sensorflow.agentic import policy as policy_modfrom sensorflow.agentic.policy import PolicyInput
def _base_input(**overrides) -> PolicyInput: kwargs = dict( failure_id="fail-test", safety_critical_class=True, behavioral_evidence="observed_unsafe", downstream_contained=False, rate=1.0e-4, rate_ci=[7.0e-5, 1.6e-4], denominator=240_000, significant=True, small_sample=False, novelty="novel", evidence_confidence="CONFIRMED", downstream_consequence="observed_critical", gt_available=True, lineage_complete=True, telemetry_available=True, fusion_verdict="multi_modal_supported", agent_conflict=False, ) kwargs.update(overrides) return PolicyInput(**kwargs)
# ------------------------------------------------------------------ versioning
def test_policy_hash_versioning_and_determinism(): doc = policy_mod.save_policy(copy.deepcopy(policy_mod.DEFAULT_POLICY)) assert doc["policy_version"] == policy_mod.policy_hash(doc) # identical content -> identical hash; changed content -> new hash again = policy_mod.policy_hash(copy.deepcopy(policy_mod.DEFAULT_POLICY)) assert again == doc["policy_version"] mutated = copy.deepcopy(policy_mod.DEFAULT_POLICY) mutated["expected_loss"]["delay_cost"] = 999.0 assert policy_mod.policy_hash(mutated) != doc["policy_version"] # persisted + retrievable by version fetched = policy_mod.get_policy(doc["policy_version"]) assert fetched["policy_name"] == doc["policy_name"] # example thresholds must be flagged as placeholders assert doc["placeholder_values"] is True
def test_policy_evaluation_is_deterministic(): inp = _base_input() r1 = policy_mod.evaluate(inp) r2 = policy_mod.evaluate(inp) for key in ("outcome", "severity", "recommended_option", "policy_version"): assert r1[key] == r2[key] assert r1["expected_loss_table"] == r2["expected_loss_table"]
# ------------------------------------------------------------------ stop-ship
def test_automatic_stop_ship_fires_only_on_preauthorized_conditions(): # ASS-1: S4 + CONFIRMED + significant -> fires r = policy_mod.evaluate(_base_input()) assert r["severity"] == "S4" assert r["outcome"] == "AUTOMATIC_STOP_SHIP" assert r["automatic_stop_ship_condition"]["condition_id"] == "ASS-1" assert r["recommended_option"] == "STOP_SHIP"
# same facts but only LIKELY confidence -> NOT pre-authorized r2 = policy_mod.evaluate(_base_input(evidence_confidence="LIKELY")) assert r2["outcome"] != "AUTOMATIC_STOP_SHIP"
# not significant -> NOT pre-authorized r3 = policy_mod.evaluate(_base_input(significant=False)) assert r3["outcome"] != "AUTOMATIC_STOP_SHIP"
# ------------------------------------------------------------------ INDETERMINATE
def test_indeterminate_on_missing_gt_lineage_telemetry_and_conflict(): cases = [ {"gt_available": False}, {"lineage_complete": False}, {"telemetry_available": False, "denominator": None}, {"fusion_verdict": "verification_failed"}, {"agent_conflict": True, "conflict_details": ["vlm vs fusion"]}, ] for overrides in cases: r = policy_mod.evaluate(_base_input(**overrides)) assert r["outcome"] == "INDETERMINATE", overrides # never a pass, always escalates to a human assert r["outcome"] != "NO_LAUNCH_IMPACT" assert r["recommended_option"] == "HUMAN_SAFETY_REVIEW" assert r["indeterminate_reasons"]
# ------------------------------------------------------------------ severity
def test_severity_taxonomy_criteria(): doc = policy_mod.get_policy() assert set(doc["severity_taxonomy"]) == {"S0", "S1", "S2", "S3", "S4", "S5"}
def sev(**kw): return policy_mod.assign_severity(doc, _base_input(**kw))["severity"]
assert sev(collision_observed=True) == "S5" assert sev(behavioral_evidence="observed_unsafe") == "S4" assert sev(behavioral_evidence="none", downstream_contained=False) == "S3" assert sev(behavioral_evidence="none", downstream_contained=True) == "S2" assert sev(safety_critical_class=False, behavioral_evidence="none", functional_impact=True) == "S1" assert sev(safety_critical_class=False, behavioral_evidence="none", functional_impact=False) == "S0"
# ------------------------------------------------------------------ option matrix
def test_option_matrix_all_seven_rows(): # row 1: gate violated -> STOP_SHIP r = policy_mod.evaluate(_base_input(gate_violated=True, evidence_confidence="LIKELY")) assert r["matrix_row_fired"]["row"] == 1 assert r["recommended_option"] == "STOP_SHIP"
# row 2: high-confidence uncontained critical -> OPTION_A_DELAY r = policy_mod.evaluate(_base_input(evidence_confidence="LIKELY")) assert r["matrix_row_fired"]["row"] == 2 assert r["recommended_option"] == "OPTION_A_DELAY"
# row 3: validated mitigation -> OPTION_B_MITIGATION r = policy_mod.evaluate(_base_input(evidence_confidence="LIKELY", mitigation_validated=True, mitigation_description="class-gate patch")) assert r["matrix_row_fired"]["row"] == 3 assert r["recommended_option"] == "OPTION_B_MITIGATION"
# row 4: reliably detectable ODD concentration -> OPTION_C_REDUCED_ODD r = policy_mod.evaluate(_base_input( behavioral_evidence="observed_contained", downstream_contained=True, downstream_consequence="observed_degraded", evidence_confidence="LIKELY", concentrated=True, concentration_dimension="lighting", odd_detector_recall=0.999, odd_exclusion_share=0.10, residual_rate_outside_odd=4.0e-6)) assert r["matrix_row_fired"]["row"] == 4 assert r["recommended_option"] == "OPTION_C_REDUCED_ODD" assert r["option_c_evaluation"]["feasible"] is True
# row 4 must NOT fire when the dimension is not instrumented in the ODD # taxonomy (geography), even with perfect detector numbers r_geo = policy_mod.evaluate(_base_input( behavioral_evidence="observed_contained", downstream_contained=True, downstream_consequence="observed_degraded", evidence_confidence="LIKELY", concentrated=True, concentration_dimension="geo_bucket", odd_detector_recall=0.999, odd_exclusion_share=0.10, residual_rate_outside_odd=4.0e-6)) assert r_geo["option_c_evaluation"]["feasible"] is False assert r_geo["recommended_option"] != "OPTION_C_REDUCED_ODD"
# row 5: insufficient evidence -> EXPAND_EVALUATION r = policy_mod.evaluate(_base_input( behavioral_evidence="none", downstream_contained=True, significant=False, small_sample=True, evidence_confidence="INSUFFICIENT_EVIDENCE", downstream_consequence="uncertain")) assert r["matrix_row_fired"]["row"] == 5 assert r["recommended_option"] == "EXPAND_EVALUATION"
# row 6: modality conflict -> HUMAN_SAFETY_REVIEW r = policy_mod.evaluate(_base_input( safety_critical_class=False, behavioral_evidence="none", evidence_confidence="LIKELY", rate=1.0e-6, fusion_verdict="modality_conflict", downstream_consequence="uncertain")) assert r["matrix_row_fired"]["row"] == 6 assert r["recommended_option"] == "HUMAN_SAFETY_REVIEW"
# row 7: no safety impact -> PROCEED r = policy_mod.evaluate(_base_input( safety_critical_class=False, behavioral_evidence="none", significant=False, rate=1.0e-6, novelty="known_stable", evidence_confidence="LIKELY", downstream_consequence="none_observed")) assert r["matrix_row_fired"]["row"] == 7 assert r["recommended_option"] == "PROCEED"
# ------------------------------------------------------------------ hard constraint
def test_cheaper_unsafe_option_never_selected(): # Craft a policy where PROCEED is by far the cheapest option. doc = copy.deepcopy(policy_mod.DEFAULT_POLICY) doc["expected_loss"]["incident_cost"] = 0.0 doc["expected_loss"]["delay_cost"] = 10_000.0 doc = policy_mod.save_policy(doc)
# S3 severity, POSSIBLE confidence: rows 1-6 all miss, row 7 (PROCEED) # matches — but PROCEED is infeasible under the hard constraint because # the residual rate exceeds MAX_ACCEPTABLE_RESIDUAL_RISK at S3+. # (odd_exclusion_share gives every alternative a nonzero business cost, # so PROCEED is STRICTLY cheapest.) inp = _base_input(behavioral_evidence="none", downstream_contained=False, evidence_confidence="POSSIBLE", significant=True, small_sample=False, rate=1.0e-4, odd_exclusion_share=0.5, downstream_consequence="uncertain") r = policy_mod.evaluate(inp, policy=doc) table = {row["option"]: row for row in r["expected_loss_table"]} # PROCEED is the cheapest option in the table... cheapest = min(r["expected_loss_table"], key=lambda x: x["expected_loss"]) assert cheapest["option"] == "PROCEED" # ...but it is infeasible and therefore NOT selected. assert table["PROCEED"]["feasible"] is False assert r["recommended_option"] != "PROCEED" assert r["recommended_option"] == "HUMAN_SAFETY_REVIEW" # fail-safe
# restore the default active policy for the rest of the suite policy_mod.save_policy(copy.deepcopy(policy_mod.DEFAULT_POLICY))127 unmodified lines128129130127 unmodified linesassert spec.output_schema.get("properties") is not Noneassert spec.timeout_s > 0assert spec.description127 unmodified lines128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190127 unmodified linesassert spec.output_schema.get("properties") is not Noneassert spec.timeout_s > 0assert spec.description# ---------------------------------------------- megaeval delegation (real data)@pytest.fixture(scope="module")def mega_run(tmp_path_factory):"""A real, published megaeval run in an isolated store (public API only)."""from sensorflow.megaeval import population as pop_modfrom sensorflow.megaeval.runs import get_mega_store, reset_mega_storeroot = tmp_path_factory.mktemp("retro-megaeval")pop_mod.set_mega_root(str(root))reset_mega_store()# 20k objects: large enough that skewed cohorts clear distribution_shift's# default min_eval_count=300 / rel_threshold=0.35 (8k leaves zero eligible)meta = pop_mod.generate_population("retro-delegation-pop",num_objects=20_000, seed=23)store = get_mega_store()run = store.create_run(population_id=meta["population_id"],model_version="retro-delegation-model",worker_delay_s=0.0)store.execute_sync(run)assert run.status == "published", run.erroryield runpop_mod.set_mega_root("runs/megaeval")reset_mega_store()def test_distribution_analysis_delegates_to_megaeval(registry, mega_run):"""The SUCCESS path: import + call chain into megaeval actually works."""res = registry.call("distribution_analysis", {"run_id": mega_run.run_id})assert res.okout = res.result# delegation succeeded — not the graceful-degradation branchassert out["source"] == "sensorflow.megaeval.analysis.distribution_shift"assert out["shift"]["run_id"] == mega_run.run_idassert "train mix vs eval mix" in out["shift"]["method"]# the synthetic training mix is deliberately skewed (night/rain cohorts),# so a real run surfaces genuine shifted cohortsshifts = out["shift"]["shifts"]assert len(shifts) > 0for s in shifts:assert {"cohort", "train_share", "eval_share","relative_change"} <= set(s)assert any("cohort" in f for f in out["findings"])# the call is audited like any other tool callaudited = [r for r in registry.audit_logif r.tool == "distribution_analysis" and r.status == "ok"]assert audited and len(audited[0].result_hash) == 64def test_distribution_analysis_degrades_for_unknown_run(registry, mega_run):"""Graceful degradation is reserved for genuinely missing data."""res = registry.call("distribution_analysis", {"run_id": "eval-nonexistent"})assert res.okassert res.result["source"] == "megaeval-delegation-failed"assert res.result["shift"] is Noneassert "no distribution claim is made" in res.result["findings"][0]
src/components/megaeval/VisualQueryTab.tsxAdded+401
src/components/safety/shared.tsxAdded+208
src/components/visual/BrushChart.tsxAdded+243
src/components/visual/DragList.tsxAdded+108
src/components/visual/Feedback.tsxAdded+132
src/components/visual/InspectorPanel.tsxAdded+161
src/components/visual/NodeCanvas.tsxAdded+253
src/components/visual/canvas.tsxAdded+212
src/components/visual/charts.tsxAdded+368
src/content/glossary.ts+245-51
src/content/pageHelp.ts+180-12
src/context/LabelEvalContext.tsx+30-2
src/index.tsx+6-11
src/pages/CommandCenterPage.tsx+4
src/pages/agentic/LaunchReadinessPage.tsxAdded+349
src/pages/engines/BevFusionPage.tsxAdded+413
src/pages/engines/SeqevalPage.tsxAdded+553
src/pages/safety/CalibrationPage.tsxAdded+281
src/pages/safety/DiscrepancyPage.tsxAdded+215
src/pages/safety/EvidencePage.tsxAdded+111
src/pages/safety/OddCoveragePage.tsxAdded+385
src/pages/safety/ReleaseGatesPage.tsxAdded+426
src/pages/safety/ScenarioDbPage.tsxAdded+222
src/pages/safety/SemanticSearchPage.tsxAdded+210
src/pages/safety/SsamConflictPage.tsxAdded+271
src/pages/studio/MyDashboardPage.tsxAdded+536
src/pages/studio/PipelineBuilderPage.tsxAdded+367
src/pages/studio/ScenarioComposerPage.tsxAdded+661
src/services/agentic.tsAdded+120
src/services/bevfusion.tsAdded+178
src/services/safety.tsAdded+411
src/services/seqeval.tsAdded+194
src/services/studioux.tsAdded+116
src/theme.tsAdded+115
src/types/agentic.tsAdded+326
tests/test_agentic/__init__.pyAdded
tests/test_agentic/conftest.pyAdded+38
tests/test_agentic/test_agents.pyAdded+189
tests/test_agentic/test_api.pyAdded+157
tests/test_agentic/test_evidence_snippets.pyAdded+68
tests/test_agentic/test_flywheel.pyAdded+121
tests/test_agentic/test_pipeline_worked_example.pyAdded+154
tests/test_agentic/test_policy.pyAdded+223
tests/test_retro/test_tools.py+60