Spaces:
Paused
Paused
Deploy Sensorflow Studio (part 2)
Browse filesFiles changed (22)
- src/components/retro/AuditTrail.tsxAdded+65
- src/components/retro/EvidenceChain.tsxAdded+194
- src/components/retro/HardwareCard.tsxAdded+73
- src/components/retro/ScorecardView.tsxAdded+137
- src/components/retro/StandardsPanel.tsxAdded+49
- src/components/retro/tierTheme.tsAdded+25
- src/content/glossary.ts+38-1
- src/content/pageHelp.ts+12
- src/context/LabelEvalContext.tsx+2
- src/pages/retro/RetroAnalyzerPage.tsxAdded+186
- src/services/retro.tsAdded+68
- src/types/retro.tsAdded+184
- tests/test_retro/__init__.pyAdded
- tests/test_retro/conftest.pyAdded+39
- tests/test_retro/test_agent.pyAdded+195
- tests/test_retro/test_api.pyAdded+111
- tests/test_retro/test_inference.pyAdded+120
- tests/test_retro/test_metrics.pyAdded+130
- tests/test_retro/test_optional_deps.pyAdded+50
- tests/test_retro/test_policy.pyAdded+142
- tests/test_retro/test_rag.pyAdded+125
- tests/test_retro/test_tools.pyAdded+130
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465/** Tool-call audit trail: args, result hash, timing, permission outcomes. */import Box from '@mui/material/Box';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 type { AuditRecord } from '../../types/retro';
const STATUS_COLORS: Record<string, string> = { ok: '#66bb6a', error: '#ef5350', timeout: '#ffb74d', denied: '#e65100',};
export default function AuditTrail({ records }: { records: AuditRecord[] }) { if (!records.length) { return <Typography sx={{ fontSize: 13, color: '#8a949e' }}>No audit records.</Typography>; } return ( <Box sx={{ overflowX: 'auto' }}> <Typography sx={{ fontSize: 11.5, color: '#8a949e', mb: 1 }}> Every tool call — including denials and failures — is appended with its arguments, a SHA-256 result hash, and a UTC timestamp. </Typography> <Table size="small"> <TableHead> <TableRow> {['time (UTC)', 'tool', 'status', 'ms', 'args', 'result hash', 'write?'].map((h) => ( <TableCell key={h} sx={{ color: '#8a949e', fontSize: 11, whiteSpace: 'nowrap' }}>{h}</TableCell> ))} </TableRow> </TableHead> <TableBody> {records.map((r) => ( <TableRow key={r.call_id} hover> <TableCell sx={{ fontFamily: 'monospace', fontSize: 11, whiteSpace: 'nowrap' }}> {r.timestamp.replace('T', ' ').slice(0, 19)} </TableCell> <TableCell sx={{ fontSize: 12, fontWeight: 600 }}>{r.tool}</TableCell> <TableCell> <Chip size="small" label={r.status} sx={{ bgcolor: `${STATUS_COLORS[r.status] ?? '#8a949e'}22`, color: STATUS_COLORS[r.status] ?? '#8a949e', fontWeight: 700, fontSize: 10 }} /> </TableCell> <TableCell sx={{ fontFamily: 'monospace', fontSize: 11 }}>{r.elapsed_ms.toFixed(1)}</TableCell> <TableCell sx={{ fontFamily: 'monospace', fontSize: 10.5, maxWidth: 320, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}> {JSON.stringify(r.args)} </TableCell> <TableCell sx={{ fontFamily: 'monospace', fontSize: 10.5 }}> {r.result_hash ? `${r.result_hash.slice(0, 12)}…` : r.error ? `⚠ ${r.error.slice(0, 60)}` : '—'} </TableCell> <TableCell sx={{ fontSize: 11 }}>{r.authorized_write ? 'AUTHORIZED' : ''}</TableCell> </TableRow> ))} </TableBody> </Table> </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194/** * The traceable-chain view: a vertical evidence flow from raw failure to * human decision, each stage expandable into tier-color-coded items. */import { useState } from 'react';import Accordion from '@mui/material/Accordion';import AccordionDetails from '@mui/material/AccordionDetails';import AccordionSummary from '@mui/material/AccordionSummary';import Box from '@mui/material/Box';import Chip from '@mui/material/Chip';import Typography from '@mui/material/Typography';import { ChevronDown } from 'lucide-react';import type { EvidenceItem, RetrospectiveScorecard } from '../../types/retro';import { DETERMINATION_COLOR, LAUNCH_COLORS, SEVERITY_COLORS, TIER_META } from './tierTheme';
interface StageDef { id: string; title: string; color: string; badge: string; items: { primary: string; secondary: string; color: string }[];}
function evidenceRow(e: EvidenceItem) { const meta = TIER_META[e.tier]; return { primary: `${e.key}${e.value !== null ? ` = ${e.value}` : ''}`, secondary: `${e.statement} — ${e.provenance}`, color: meta.color, };}
function buildStages(sc: RetrospectiveScorecard): StageDef[] { const byTier = (tier: EvidenceItem['tier']) => sc.evidence.filter((e) => e.tier === tier && !e.key.startsWith('policy_') && e.key !== 'severity_divergence'); const observed = byTier('TIER1_OBSERVED'); const derived = byTier('TIER2_DERIVED').filter((e) => e.key !== 'behavioral_impact'); const behavioral = sc.evidence.filter((e) => e.key === 'behavioral_impact'); const retrieved = byTier('TIER3_RETRIEVED'); const policyItems = sc.evidence.filter( (e) => e.key === 'policy_severity' || e.key === 'severity_divergence' );
return [ { id: 'raw', title: '1 · Raw failure artifact', color: '#8a949e', badge: sc.failure_type, items: [ { primary: sc.evaluation_id, secondary: `${String(sc.scenario?.description ?? 'evaluation log')} (weather: ${String( sc.scenario?.weather ?? '?' )}, ODD: ${String(sc.scenario?.odd_status ?? '?')})`, color: '#8a949e', }, ], }, { id: 'observed', title: `2 · Observed evidence — FACT (${observed.length})`, color: TIER_META.TIER1_OBSERVED.color, badge: 'TIER 1', items: observed.map(evidenceRow), }, { id: 'derived', title: `3 · Derived metrics — DERIVED FACT (${derived.length})`, color: TIER_META.TIER2_DERIVED.color, badge: 'TIER 2', items: derived.map(evidenceRow), }, { id: 'retrieved', title: `4 · Retrieved engineering evidence (${retrieved.length})`, color: TIER_META.TIER3_RETRIEVED.color, badge: 'TIER 3', items: retrieved.map(evidenceRow), }, { id: 'hypothesis', title: `5 · Agent hypotheses — INFERENCE (${sc.root_cause_hypotheses.length})`, color: TIER_META.TIER4_AI_HYPOTHESIS.color, badge: 'TIER 4', items: sc.root_cause_hypotheses.map((h) => ({ primary: `${Math.round(h.confidence * 100)}% confidence`, secondary: `${h.hypothesis} [supported by: ${h.supporting_evidence_keys.join(', ') || 'n/a'}; missing: ${ h.missing_evidence.join(', ') || 'none' }]`, color: TIER_META.TIER4_AI_HYPOTHESIS.color, })), }, { id: 'behavioral', title: '6 · Behavioral analysis', color: TIER_META.TIER2_DERIVED.color, badge: 'DERIVED', items: behavioral.length ? behavioral.map(evidenceRow) : [{ primary: 'behavioral consequence', secondary: sc.behavioral_consequence, color: TIER_META.TIER2_DERIVED.color }], }, { id: 'policy', title: '7 · Safety policy (deterministic)', color: DETERMINATION_COLOR, badge: sc.policy_version, items: [ ...policyItems.map(evidenceRow), ...sc.launch_rationale.map((r) => ({ primary: 'launch gate', secondary: r, color: DETERMINATION_COLOR, })), ], }, { id: 'scorecard', title: '8 · Retrospective scorecard → human decision', color: LAUNCH_COLORS[sc.launch_recommendation], badge: sc.launch_recommendation, items: [ { primary: `severity ${sc.severity} · launch ${sc.launch_recommendation}`, secondary: sc.human_review_required ? `HUMAN REVIEW REQUIRED: ${sc.human_review_reasons.join('; ')}` : 'no human review trigger fired — decision still rests with a human', color: SEVERITY_COLORS[sc.severity], }, ], }, ];}
export default function EvidenceChain({ scorecard }: { scorecard: RetrospectiveScorecard }) { const [expanded, setExpanded] = useState<string[]>(['observed', 'derived', 'policy', 'scorecard']); const stages = buildStages(scorecard);
const toggle = (id: string) => setExpanded((cur) => (cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id]));
return ( <Box> <Box sx={{ display: 'flex', gap: 1, mb: 1.5, flexWrap: 'wrap', alignItems: 'center' }}> <Typography variant="caption" sx={{ color: '#8a949e', fontWeight: 700 }}> EVIDENCE TIER LEGEND: </Typography> {Object.values(TIER_META).map((m) => ( <Chip key={m.label} size="small" label={m.label} sx={{ bgcolor: `${m.color}22`, color: m.color, fontWeight: 700, fontSize: 10 }} /> ))} <Chip size="small" label="DETERMINATION" sx={{ bgcolor: `${DETERMINATION_COLOR}22`, color: DETERMINATION_COLOR, fontWeight: 700, fontSize: 10 }} /> </Box>
{stages.map((stage, i) => ( <Box key={stage.id} sx={{ display: 'flex', gap: 1.5 }}> <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: 18, pt: 1 }}> <Box sx={{ width: 12, height: 12, borderRadius: '50%', bgcolor: stage.color, flexShrink: 0 }} /> {i < stages.length - 1 ? ( <Box sx={{ width: 2, flex: 1, bgcolor: '#232a31', minHeight: 18 }} /> ) : null} </Box> <Accordion disableGutters expanded={expanded.includes(stage.id)} onChange={() => toggle(stage.id)} sx={{ flex: 1, mb: 1, bgcolor: '#161c23', border: '1px solid #232a31', '&:before': { display: 'none' } }} > <AccordionSummary expandIcon={<ChevronDown size={16} />} sx={{ minHeight: 40 }}> <Typography sx={{ fontSize: 13.5, fontWeight: 700, flex: 1 }}>{stage.title}</Typography> <Chip size="small" label={stage.badge} sx={{ bgcolor: `${stage.color}22`, color: stage.color, fontWeight: 700, fontSize: 10, mr: 1 }} /> </AccordionSummary> <AccordionDetails sx={{ pt: 0 }}> {stage.items.length === 0 ? ( <Typography sx={{ fontSize: 12, color: '#8a949e' }}>no items</Typography> ) : ( stage.items.map((item, j) => ( <Box key={j} sx={{ borderLeft: `3px solid ${item.color}`, pl: 1.25, py: 0.5, mb: 0.5 }}> <Typography sx={{ fontSize: 12.5, fontFamily: 'monospace', color: item.color }}> {item.primary} </Typography> <Typography sx={{ fontSize: 12, color: '#aab4be' }}>{item.secondary}</Typography> </Box> )) )} </AccordionDetails> </Accordion> </Box> ))} </Box> );}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273/** Hardware / compatibility status card — honest platform reporting. */import { useEffect, useState } from 'react';import Box from '@mui/material/Box';import Chip from '@mui/material/Chip';import Paper from '@mui/material/Paper';import Typography from '@mui/material/Typography';import { Cpu } from 'lucide-react';import { getRetroCompat, getRetroEnv } from '../../services/retro';import type { CompatReport, EnvironmentReport } from '../../types/retro';
const CHECK_COLORS: Record<string, string> = { PASS: '#66bb6a', FAIL: '#ef5350', SKIPPED: '#8a949e',};
export default function HardwareCard() { const [env, setEnv] = useState<EnvironmentReport | null>(null); const [compat, setCompat] = useState<CompatReport | null>(null); const [error, setError] = useState<string | null>(null);
useEffect(() => { getRetroEnv().then((r) => setEnv(r.environment)).catch((e: Error) => setError(e.message)); getRetroCompat().then((r) => setCompat(r.report)).catch((e: Error) => setError(e.message)); }, []);
if (error) { return <Typography sx={{ fontSize: 12, color: '#ef5350' }}>hardware report unavailable: {error}</Typography>; } if (!env || !compat) { return <Typography sx={{ fontSize: 12, color: '#8a949e' }}>Detecting environment…</Typography>; }
return ( <Paper sx={{ p: 1.5, bgcolor: '#161c23', border: '1px solid #232a31' }}> <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}> <Cpu size={16} color="#4fc3f7" /> <Typography sx={{ fontSize: 13, fontWeight: 700 }}>Hardware & vLLM compatibility</Typography> <Chip size="small" label={compat.vllm_supported ? 'vLLM SUPPORTED' : 'vLLM UNSUPPORTED HERE'} sx={{ bgcolor: compat.vllm_supported ? '#66bb6a22' : '#ef535022', color: compat.vllm_supported ? '#66bb6a' : '#ef5350', fontWeight: 800, fontSize: 10 }} /> </Box> <Typography sx={{ fontSize: 12, color: '#aab4be', mb: 1 }}>{compat.platform_summary}</Typography> <Typography sx={{ fontSize: 11.5, fontFamily: 'monospace', color: '#8a949e', mb: 1 }}> {env.os_name} {env.os_version} · {env.machine_arch} {env.is_apple_silicon ? ' (Apple Silicon)' : ''} · Python {env.python_version} {env.gpus.length ? ` · ${env.gpus.map((g) => `${g.vendor} ${g.model}`).join(', ')}` : ' · no GPU detected'} </Typography> <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}> {compat.checks.map((c) => ( <Box key={c.link} sx={{ display: 'flex', gap: 1, alignItems: 'baseline' }}> <Chip size="small" label={c.status} sx={{ bgcolor: `${CHECK_COLORS[c.status]}22`, color: CHECK_COLORS[c.status], fontWeight: 700, fontSize: 9.5, width: 70 }} /> <Typography sx={{ fontSize: 11.5, fontFamily: 'monospace', minWidth: 110 }}>{c.link}</Typography> <Typography sx={{ fontSize: 11.5, color: '#8a949e' }}>{c.reason}</Typography> </Box> ))} </Box> {env.ollama_endpoint ? ( <Typography sx={{ fontSize: 11.5, color: '#66bb6a', mt: 1 }}> Ollama reachable at {env.ollama_endpoint} ({env.ollama_models.length} models) — real local inference available, labeled Ollama-on-CPU/Metal (not vLLM). </Typography> ) : ( <Typography sx={{ fontSize: 11.5, color: '#8a949e', mt: 1 }}> Ollama not reachable — deterministic mock backend is the only runnable option here. </Typography> )} </Paper> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137/** Scorecard rendering: severity + launch banner, kinematics, statistics. */import Box from '@mui/material/Box';import Chip from '@mui/material/Chip';import Grid from '@mui/material/Grid';import Paper from '@mui/material/Paper';import Typography from '@mui/material/Typography';import { AlertTriangle, UserCheck } from 'lucide-react';import type { RetrospectiveScorecard } from '../../types/retro';import { LAUNCH_COLORS, SEVERITY_COLORS } from './tierTheme';
function Stat({ label, value, mono = true }: { label: string; value: string; mono?: boolean }) { return ( <Box sx={{ minWidth: 130 }}> <Typography sx={{ fontSize: 10.5, color: '#8a949e', letterSpacing: 0.6 }}>{label}</Typography> <Typography sx={{ fontSize: 13.5, fontFamily: mono ? 'monospace' : undefined, fontWeight: 600 }}> {value} </Typography> </Box> );}
const fmt = (v: number | null | undefined, unit = '', digits = 2) => v === null || v === undefined ? 'UNKNOWN' : `${v.toFixed(digits)}${unit}`;
export default function ScorecardView({ scorecard: sc }: { scorecard: RetrospectiveScorecard }) { const sevColor = SEVERITY_COLORS[sc.severity]; const launchColor = LAUNCH_COLORS[sc.launch_recommendation];
return ( <Box> {/* severity + launch banner */} <Paper sx={{ p: 1.5, mb: 1.5, bgcolor: `${launchColor}14`, border: `1px solid ${launchColor}55`, display: 'flex', alignItems: 'center', gap: 2, flexWrap: 'wrap' }}> <Chip label={`SEVERITY: ${sc.severity}`} sx={{ bgcolor: sevColor, color: '#0b0e11', fontWeight: 800 }} /> <Chip label={`LAUNCH: ${sc.launch_recommendation}`} sx={{ bgcolor: launchColor, color: '#0b0e11', fontWeight: 800 }} /> {sc.severity_divergence && sc.ai_proposed_severity ? ( <Chip icon={<AlertTriangle size={14} />} label={`AI proposed ${sc.ai_proposed_severity} — policy override recorded`} sx={{ bgcolor: '#ffb74d22', color: '#ffb74d', fontWeight: 700 }} /> ) : null} {sc.human_review_required ? ( <Chip icon={<UserCheck size={14} />} label={`HUMAN REVIEW: ${sc.human_review_reasons.join(' · ')}`} sx={{ bgcolor: '#e6510022', color: '#ffab73', fontWeight: 700 }} /> ) : null} <Typography sx={{ fontSize: 11.5, color: '#8a949e', width: '100%' }}> {sc.launch_rationale.join(' ')} </Typography> </Paper>
<Paper sx={{ p: 1.5, mb: 1.5, bgcolor: '#161c23', border: '1px solid #232a31' }}> <Typography sx={{ fontSize: 11, color: '#8a949e', fontWeight: 700, mb: 1 }}> CONTEXT & KINEMATICS (UNKNOWN means absent telemetry — never guessed) </Typography> <Grid container spacing={1.5}> <Grid item><Stat label="FAILURE TYPE" value={sc.failure_type} /></Grid> <Grid item><Stat label="OBJECT (GT)" value={sc.object_class ?? 'UNKNOWN'} /></Grid> <Grid item><Stat label="CONFIDENCE" value={fmt(sc.confidence)} /></Grid> <Grid item><Stat label="EGO SPEED" value={fmt(sc.ego_speed_mps, ' m/s', 1)} /></Grid> <Grid item><Stat label="DISTANCE" value={fmt(sc.distance_to_object_m, ' m', 1)} /></Grid> <Grid item><Stat label="REL. VELOCITY" value={fmt(sc.relative_velocity_mps, ' m/s', 1)} /></Grid> <Grid item><Stat label="STOPPING DIST" value={fmt(sc.stopping_distance_m, ' m', 1)} /></Grid> <Grid item><Stat label="TTC" value={fmt(sc.ttc_s, ' s')} /></Grid> <Grid item><Stat label="DISENGAGE P" value={fmt(sc.disengagement_probability)} /></Grid> <Grid item><Stat label="SCR IMPACT" value={sc.safety_critical_recall_impact === null ? 'UNKNOWN' : sc.safety_critical_recall_impact.toFixed(5)} /></Grid> <Grid item><Stat label="BASELINE" value={sc.baseline_model ?? 'UNKNOWN'} /></Grid> <Grid item><Stat label="CANDIDATE" value={sc.candidate_model ?? 'UNKNOWN'} /></Grid> </Grid> {sc.ttc_validity.length ? ( <Typography sx={{ fontSize: 11, color: '#8a949e', mt: 1 }}> TTC validity: {sc.ttc_validity.join('; ')} </Typography> ) : null} </Paper>
<Paper sx={{ p: 1.5, mb: 1.5, bgcolor: '#161c23', border: '1px solid #232a31' }}> <Typography sx={{ fontSize: 11, color: '#8a949e', fontWeight: 700, mb: 0.5 }}> BEHAVIORAL CONSEQUENCE </Typography> <Typography sx={{ fontSize: 13 }}>{sc.behavioral_consequence}</Typography> {sc.planner_response ? ( <Typography sx={{ fontSize: 11.5, color: '#8a949e', mt: 0.5, fontFamily: 'monospace' }}> observed planner: {JSON.stringify(sc.planner_response)} </Typography> ) : null} </Paper>
<Paper sx={{ p: 1.5, mb: 1.5, bgcolor: '#161c23', border: '1px solid #232a31' }}> <Typography sx={{ fontSize: 11, color: '#8a949e', fontWeight: 700, mb: 0.5 }}> STATISTICS </Typography> <Typography sx={{ fontSize: 12.5, fontFamily: 'monospace' }}> metric_delta: {sc.metric_delta ? JSON.stringify(sc.metric_delta) : 'UNKNOWN'} </Typography> <Typography sx={{ fontSize: 12.5 }}> significance: {sc.statistical_significance ? `${sc.statistical_significance.method} → ${ sc.statistical_significance.significant === null ? 'not evaluable' : sc.statistical_significance.significant ? 'SIGNIFICANT' : 'not significant' } (${sc.statistical_significance.detail})` : 'UNKNOWN'} </Typography> {sc.distribution_shift ? ( <Typography sx={{ fontSize: 12.5, fontFamily: 'monospace' }}> distribution_shift: {JSON.stringify(sc.distribution_shift)} </Typography> ) : null} </Paper>
{sc.uncertainty.missing_fields.length || sc.uncertainty.unknown_metrics.length ? ( <Paper sx={{ p: 1.5, bgcolor: '#90a4ae14', border: '1px solid #90a4ae55' }}> <Typography sx={{ fontSize: 11, color: '#90a4ae', fontWeight: 700, mb: 0.5 }}> UNCERTAINTY / MISSING EVIDENCE </Typography> {sc.uncertainty.missing_fields.map((f) => ( <Typography key={f} sx={{ fontSize: 12, fontFamily: 'monospace' }}>missing field: {f} → UNKNOWN</Typography> ))} {sc.uncertainty.unknown_metrics.map((m) => ( <Typography key={m} sx={{ fontSize: 12, fontFamily: 'monospace' }}>metric not computable: {m} → UNKNOWN</Typography> ))} {sc.uncertainty.notes.map((n, i) => ( <Typography key={i} sx={{ fontSize: 12, color: '#aab4be' }}>{n}</Typography> ))} </Paper> ) : null}
<Typography sx={{ fontSize: 10.5, color: '#5c6770', mt: 1.5 }}> {sc.policy_version} · {sc.agent_version} · backend {sc.backend_used} · {sc.created_at} </Typography> </Box> );}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849/** Retrieved-standards citations with prominent SYNTHETIC_EXAMPLE badges. */import Box from '@mui/material/Box';import Chip from '@mui/material/Chip';import Paper from '@mui/material/Paper';import Typography from '@mui/material/Typography';import type { RetrievedStandard } from '../../types/retro';import { TIER_META } from './tierTheme';
export default function StandardsPanel({ standards }: { standards: RetrievedStandard[] }) { if (!standards.length) { return ( <Typography sx={{ fontSize: 13, color: '#8a949e' }}> No requirements retrieved — by the hard rule, nothing is cited. </Typography> ); } const color = TIER_META.TIER3_RETRIEVED.color; return ( <Box> <Typography sx={{ fontSize: 11.5, color: '#8a949e', mb: 1 }}> Every citation below is backed by an audited retrieval hit (no citation without retrieval). Synthetic demonstration rules are labeled; SOTIF entries are concept paraphrases, never standard text. </Typography> {standards.map((s) => ( <Paper key={s.chunk_id} sx={{ p: 1.5, mb: 1, bgcolor: '#161c23', border: `1px solid ${color}44` }}> <Box sx={{ display: 'flex', gap: 1, alignItems: 'center', flexWrap: 'wrap', mb: 0.5 }}> <Chip size="small" label={s.synthetic ? 'SYNTHETIC_EXAMPLE' : 'PARAPHRASE — NOT STANDARD TEXT'} sx={{ bgcolor: s.synthetic ? '#e6510022' : '#4fc3f722', color: s.synthetic ? '#ffab73' : '#4fc3f7', fontWeight: 800, fontSize: 10 }} /> <Typography sx={{ fontSize: 13, fontWeight: 700 }}> {s.document} v{s.version} </Typography> <Chip size="small" label={`§ ${s.section}`} sx={{ bgcolor: '#232a31', fontSize: 10 }} /> <Chip size="small" label={`relevance ${s.relevance_score.toFixed(2)}`} sx={{ bgcolor: `${color}22`, color, fontSize: 10, fontWeight: 700 }} /> </Box> <Typography sx={{ fontSize: 12.5, color: '#c3ccd4', fontStyle: 'italic' }}> “{s.retrieved_text.length > 380 ? `${s.retrieved_text.slice(0, 380)}…` : s.retrieved_text}” </Typography> <Typography sx={{ fontSize: 10.5, color: '#5c6770', mt: 0.5, fontFamily: 'monospace' }}> {s.doc_id} · {s.doc_type} · {s.source} · {s.jurisdiction} · effective {s.effective_date} · chunk {s.chunk_id} </Typography> </Paper> ))} </Box> );}12345678910111213141516171819202122232425/** Shared color/label mapping for the evidence hierarchy. */import type { EvidenceTier, LaunchRecommendation, RetroSeverity } from '../../types/retro';
export const TIER_META: Record<EvidenceTier, { label: string; color: string }> = { TIER1_OBSERVED: { label: 'FACT', color: '#66bb6a' }, TIER2_DERIVED: { label: 'DERIVED', color: '#4fc3f7' }, TIER3_RETRIEVED: { label: 'RETRIEVED', color: '#ba68c8' }, TIER4_AI_HYPOTHESIS: { label: 'AI HYPOTHESIS', color: '#ffb74d' },};
export const DETERMINATION_COLOR = '#ef5350';
export const SEVERITY_COLORS: Record<RetroSeverity, string> = { BENIGN: '#66bb6a', DISRUPTIVE: '#ffb74d', CRITICAL: '#ef5350', FATAL: '#b71c1c',};
export const LAUNCH_COLORS: Record<LaunchRecommendation, string> = { PASS: '#66bb6a', CONDITIONAL_PASS: '#ffb74d', FAIL: '#ef5350', INSUFFICIENT_EVIDENCE: '#90a4ae',};31 unmodified lines32333435363738749 unmodified lines78878979079179279369 unmodified lines86386486586631 unmodified lines| 'Ground truth'| 'Operations'| 'EM readiness'| 'Hardware acceleration';export const GLOSSARY: Record<string, GlossaryEntry> = {// ------------------------------------------------------------ detection metrics749 unmodified linesdetail: '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.',},};export type GlossaryKey = keyof typeof GLOSSARY;69 unmodified lines'Operations','EM readiness','Hardware acceleration',];31 unmodified lines3233343536373839749 unmodified lines78979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882969 unmodified lines89990090190290331 unmodified lines| 'Ground truth'| 'Operations'| 'EM readiness'| 'Hardware acceleration'| 'Retrospective safety';export const GLOSSARY: Record<string, GlossaryEntry> = {// ------------------------------------------------------------ detection metrics749 unmodified linesdetail: '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',short: 'Every claim in a retrospective is tagged by how it was produced: observed, derived, retrieved, or hypothesized.',detail: 'Tier 1 OBSERVED = a fact read directly from the failure log. Tier 2 DERIVED = deterministically computed from observed facts (stopping distance, TTC, SCR impact). Tier 3 RETRIEVED = text returned by the safety-case RAG with full citation. Tier 4 AI_HYPOTHESIS = an LLM inference, never treated as fact. The scorecard renders the distinction explicitly.',caveat: 'A hypothesis with high confidence is still Tier 4 — confidence never promotes an inference to a fact.',},retro_severity: {term: 'Retrospective severity',category: 'Retrospective safety',short: 'BENIGN / DISRUPTIVE / CRITICAL / FATAL — computed deterministically from contextual evidence, not by the LLM.',detail: 'An asymmetric cost model: false negatives are scored by VRU class × safety-relevant distance × relative motion × remaining reaction time; false positives by intervention magnitude × traffic disruption. The LLM may propose a severity, but the deterministic policy engine validates or overrides it, and any divergence is flagged for human review.',caveat: 'Not every miss outranks every phantom: a distant benign FN ranks below a hard-braking phantom FP with tailgating traffic.',},launch_gate_retro: {term: 'Launch recommendation gate',category: 'Retrospective safety',short: 'Deterministic, policy-versioned mapping from severity + evidence completeness to PASS / CONDITIONAL_PASS / FAIL / INSUFFICIENT_EVIDENCE.',detail: 'The gate is pure code with a versioned config: FATAL/CRITICAL fail, DISRUPTIVE passes conditionally, and missing critical telemetry yields INSUFFICIENT_EVIDENCE — which can never be upgraded to PASS. The recommendation is advice to a human decision-maker, never an automatic launch.',},synthetic_standard: {term: 'SYNTHETIC_EXAMPLE standard',category: 'Retrospective safety',short: 'Every document in the safety-case corpus is a labeled synthetic demonstration — never real standard text.',detail: 'Corpus documents (safety requirements, launch criteria, ODD definitions, historical retrospectives) carry SYNTHETIC_EXAMPLE / NOT_A_REAL_STANDARD in both content and metadata; SOTIF entries are concept-level paraphrases explicitly labeled as not standard text. The retriever surfaces these labels with every citation.',caveat: 'Hard rule: the system never cites a safety requirement without a retrieval hit backing it.',},tool_audit_trail: {term: 'Tool audit trail',category: 'Retrospective safety',short: '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',];
226 unmodified lines227228229230231232226 unmodified linesdataFlow:'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.',},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.',226 unmodified lines227228229230231232233234235236237238239240241242243244226 unmodified linesdataFlow:'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:'Agentic failure retrospectives: perception failures become a traceable evidence chain — observed facts, derived metrics, retrieved requirements, AI hypotheses — ending in a deterministic policy-gated launch recommendation.',purpose:'A false negative on a pedestrian and a phantom brake on a plastic bag need very different engineering responses. This page runs an evidence-tiered retrospective: deterministic code computes the safety metrics and owns the launch decision; the LLM only interprets, correlates and hypothesizes — and every claim carries its evidence tier.',reading:'The evidence chain flows top-to-bottom from raw failure to human decision; items are color-coded by tier (FACT / DERIVED / RETRIEVED / AI HYPOTHESIS / DETERMINATION). Retrieved standards are SYNTHETIC demonstration documents (badged) — never real standard text. UNKNOWN means the telemetry was absent, never guessed. The hardware card reports honestly whether vLLM can run on this machine.',actions:'Pick a failure fixture and inference backend (mock is deterministic and always available; Ollama when a local server is running; vLLM only on CUDA/ROCm hosts), run the analysis, inspect the chain / scorecard / citations / tool-call audit trail, and reload prior analyses.',dataFlow:'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.',
18 unmodified lines19202122232416 unmodified lines41424344454618 unmodified lines| 'rca'| 'raremine'| 'hillclimb'| 'vitis'| 'ssam'| 'legacy';16 unmodified lines'rca','raremine','hillclimb','vitis','ssam','legacy',18 unmodified lines1920212223242516 unmodified lines4243444546474818 unmodified lines| 'rca'| 'raremine'| 'hillclimb'| 'retro'| 'vitis'| 'ssam'| 'legacy';16 unmodified lines'rca','raremine','hillclimb','retro','vitis','ssam','legacy',
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186/** * Retrospective Analyzer — agentic failure retrospectives with a traceable * evidence chain, deterministic policy gate, and full tool-call audit trail. */import { useCallback, useEffect, useState } from 'react';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 Select from '@mui/material/Select';import Tab from '@mui/material/Tab';import Tabs from '@mui/material/Tabs';import Typography from '@mui/material/Typography';import { History, Play, ShieldCheck } from 'lucide-react';import AuditTrail from '../../components/retro/AuditTrail';import EvidenceChain from '../../components/retro/EvidenceChain';import HardwareCard from '../../components/retro/HardwareCard';import ScorecardView from '../../components/retro/ScorecardView';import StandardsPanel from '../../components/retro/StandardsPanel';import { analyzeFixture, getRetroAnalysis, getRetroAudit, getRetroBackends, getRetroFixtures, listRetroAnalyses,} from '../../services/retro';import type { AnalysisSummary, AuditRecord, BackendStatus, FixtureInfo, RetrospectiveScorecard,} from '../../types/retro';
export default function RetroAnalyzerPage() { const [fixtures, setFixtures] = useState<FixtureInfo[]>([]); const [backends, setBackends] = useState<BackendStatus[]>([]); const [history, setHistory] = useState<AnalysisSummary[]>([]); const [fixtureId, setFixtureId] = useState(''); const [backend, setBackend] = useState('mock'); const [running, setRunning] = useState(false); const [error, setError] = useState<string | null>(null); const [scorecard, setScorecard] = useState<RetrospectiveScorecard | null>(null); const [audit, setAudit] = useState<AuditRecord[]>([]); const [tab, setTab] = useState(0);
const refreshHistory = useCallback(() => { listRetroAnalyses().then((r) => setHistory(r.analyses)).catch(() => undefined); }, []);
useEffect(() => { getRetroFixtures() .then((r) => { setFixtures(r.fixtures); if (r.fixtures.length) setFixtureId(r.fixtures[0].fixture_id); }) .catch((e: Error) => setError(e.message)); getRetroBackends().then((r) => setBackends(r.backends)).catch(() => undefined); refreshHistory(); }, [refreshHistory]);
const runAnalysis = () => { if (!fixtureId) return; setRunning(true); setError(null); analyzeFixture(fixtureId, backend) .then((res) => { setScorecard(res.scorecard); setTab(0); refreshHistory(); return getRetroAudit(res.scorecard.evaluation_id).then((a) => setAudit(a.records)); }) .catch((e: Error) => setError(e.message)) .finally(() => setRunning(false)); };
const loadHistorical = (evaluationId: string) => { setError(null); getRetroAnalysis(evaluationId) .then((res) => { setScorecard(res.scorecard); setTab(0); return getRetroAudit(evaluationId).then((a) => setAudit(a.records)); }) .catch((e: Error) => setError(e.message)); };
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}> <ShieldCheck size={20} color="#4fc3f7" /> <Typography variant="h6" sx={{ fontWeight: 700 }}>Retrospective Analyzer</Typography> <Typography sx={{ fontSize: 12, color: '#8a949e' }}> LLM interprets & hypothesizes · deterministic code computes metrics & owns the safety boundary </Typography> </Box>
<HardwareCard />
{/* picker + analyze action */} <Paper sx={{ p: 1.5, bgcolor: '#161c23', border: '1px solid #232a31', display: 'flex', gap: 1.5, alignItems: 'center', flexWrap: 'wrap' }}> <Box> <Typography sx={{ fontSize: 10.5, color: '#8a949e' }}>FAILURE FIXTURE</Typography> <Select size="small" value={fixtureId} onChange={(e) => setFixtureId(e.target.value)} sx={{ minWidth: 340, fontSize: 13 }}> {fixtures.map((f) => ( <MenuItem key={f.fixture_id} value={f.fixture_id} sx={{ fontSize: 13 }}> {f.fixture_id} — {f.description.slice(0, 60)} </MenuItem> ))} </Select> </Box> <Box> <Typography sx={{ fontSize: 10.5, color: '#8a949e' }}>INFERENCE BACKEND</Typography> <Select size="small" value={backend} onChange={(e) => setBackend(e.target.value)} sx={{ minWidth: 260, fontSize: 13 }}> {backends.map((b) => ( <MenuItem key={b.backend} value={b.backend} disabled={!b.available} sx={{ fontSize: 13 }}> <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}> {b.backend} <Chip size="small" label={b.available ? 'AVAILABLE' : 'UNAVAILABLE'} sx={{ height: 16, fontSize: 9, fontWeight: 700, bgcolor: b.available ? '#66bb6a22' : '#ef535022', color: b.available ? '#66bb6a' : '#ef5350' }} /> <Typography sx={{ fontSize: 10.5, color: '#8a949e' }}>{b.detail.slice(0, 48)}</Typography> </Box> </MenuItem> ))} </Select> </Box> <Button variant="contained" onClick={runAnalysis} disabled={running || !fixtureId} startIcon={running ? <CircularProgress size={14} /> : <Play size={14} />} sx={{ mt: 1.5, fontWeight: 700 }}> {running ? 'Analyzing…' : 'Analyze failure'} </Button> {history.length ? ( <Box sx={{ ml: 'auto' }}> <Typography sx={{ fontSize: 10.5, color: '#8a949e', display: 'flex', alignItems: 'center', gap: 0.5 }}> <History size={12} /> PRIOR ANALYSES </Typography> <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap', maxWidth: 420 }}> {history.slice(0, 6).map((h) => ( <Chip key={h.evaluation_id} size="small" onClick={() => loadHistorical(h.evaluation_id)} label={`${h.evaluation_id.slice(0, 24)} · ${h.severity ?? '?'}`} sx={{ fontSize: 10, cursor: 'pointer', bgcolor: '#232a31' }} /> ))} </Box> </Box> ) : null} </Paper>
{error ? ( <Paper sx={{ p: 1.5, bgcolor: '#ef535014', border: '1px solid #ef535055' }}> <Typography sx={{ fontSize: 12.5, color: '#ef5350' }}>{error}</Typography> </Paper> ) : null}
{scorecard ? ( <Paper sx={{ p: 2, bgcolor: '#11161c', border: '1px solid #232a31' }}> <Tabs value={tab} onChange={(_, v: number) => setTab(v)} sx={{ mb: 2, minHeight: 36 }}> <Tab label="Evidence chain" sx={{ fontSize: 12, minHeight: 36 }} /> <Tab label="Scorecard" sx={{ fontSize: 12, minHeight: 36 }} /> <Tab label={`Retrieved standards (${scorecard.retrieved_standards.length})`} sx={{ fontSize: 12, minHeight: 36 }} /> <Tab label={`Audit trail (${audit.length})`} sx={{ fontSize: 12, minHeight: 36 }} /> </Tabs> {tab === 0 ? <EvidenceChain scorecard={scorecard} /> : null} {tab === 1 ? <ScorecardView scorecard={scorecard} /> : null} {tab === 2 ? <StandardsPanel standards={scorecard.retrieved_standards} /> : null} {tab === 3 ? <AuditTrail records={audit} /> : null} </Paper> ) : ( <Paper sx={{ p: 3, bgcolor: '#11161c', border: '1px dashed #232a31', textAlign: 'center' }}> <Typography sx={{ fontSize: 13, color: '#8a949e' }}> Pick a failure fixture and run an analysis. The result renders as a traceable chain: RAW FAILURE → OBSERVED → DERIVED → RETRIEVED → HYPOTHESIS → BEHAVIORAL → POLICY → SCORECARD → HUMAN DECISION. </Typography> </Paper> )} </Box> );}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768/** Typed fetch wrappers for the Retrospective Safety Analyzer API (/api/retro). */import type { AnalysisSummary, AnalyzeResponse, AuditRecord, BackendStatus, CompatReport, EnvironmentReport, FixtureInfo, RetrospectiveScorecard, ToolSpec,} from '../types/retro';
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 get = <T,>(url: string): Promise<T> => fetch(url).then((r) => handle<T>(r));
export const getRetroEnv = () => get<{ environment: EnvironmentReport }>('/api/retro/env');
export const getRetroCompat = () => get<{ report: CompatReport; formatted: string }>('/api/retro/compat');
export const getRetroBackends = () => get<{ backends: BackendStatus[] }>('/api/retro/backends');
export const getRetroFixtures = () => get<{ fixtures: FixtureInfo[] }>('/api/retro/fixtures');
export const analyzeFixture = (fixtureId: string, backend: string) => fetch(`/api/retro/analyze?fixture_id=${encodeURIComponent(fixtureId)}&backend=${backend}`, { method: 'POST', }).then((r) => handle<AnalyzeResponse>(r));
export const listRetroAnalyses = () => get<{ analyses: AnalysisSummary[] }>('/api/retro/analyses');
export const getRetroAnalysis = (evaluationId: string) => get<{ scorecard: RetrospectiveScorecard; markdown: string; audit_analysis_id: string }>( `/api/retro/analyses/${encodeURIComponent(evaluationId)}` );
export const getRetroAudit = (evaluationId: string) => get<{ audit_analysis_id: string; records: AuditRecord[] }>( `/api/retro/analyses/${encodeURIComponent(evaluationId)}/audit` );
export const getRetroTools = () => get<{ tools: ToolSpec[]; note: string }>('/api/retro/tools');
export const searchRetroRag = (q: string, k = 4) => get<{ store_backend: string; hits: import('../types/retro').RetrievedStandard[] }>( `/api/retro/rag/search?q=${encodeURIComponent(q)}&k=${k}` );123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184/** Types for the Agentic Retrospective Safety Analyzer (/api/retro). */
export type EvidenceTier = | 'TIER1_OBSERVED' | 'TIER2_DERIVED' | 'TIER3_RETRIEVED' | 'TIER4_AI_HYPOTHESIS';
export type RetroSeverity = 'BENIGN' | 'DISRUPTIVE' | 'CRITICAL' | 'FATAL';
export type LaunchRecommendation = | 'PASS' | 'CONDITIONAL_PASS' | 'FAIL' | 'INSUFFICIENT_EVIDENCE';
export interface EvidenceItem { tier: EvidenceTier; key: string; statement: string; value: string | null; provenance: string;}
export interface RetrievedStandard { source: string; document: string; version: string; section: string; retrieved_text: string; relevance_score: number; doc_id: string; doc_type: string; jurisdiction: string; effective_date: string; synthetic: boolean; label: string; chunk_id: string;}
export interface RootCauseHypothesis { hypothesis: string; confidence: number; supporting_evidence_keys: string[]; missing_evidence: string[]; tier: EvidenceTier;}
export interface StatSignificance { method: string; significant: boolean | null; detail: string;}
export interface UncertaintyReport { missing_fields: string[]; unknown_metrics: string[]; notes: string[];}
export interface RetrospectiveScorecard { evaluation_id: string; created_at: string; policy_version: string; agent_version: string; backend_used: string; failure_type: string; severity: RetroSeverity; ai_proposed_severity: RetroSeverity | null; severity_divergence: boolean; safety_critical_recall_impact: number | null; scr_impact_detail: string; behavioral_consequence: string; launch_recommendation: LaunchRecommendation; launch_rationale: string[]; baseline_model: string | null; candidate_model: string | null; scenario: Record<string, unknown>; object_class: string | null; ground_truth: Record<string, unknown> | null; prediction: Record<string, unknown> | null; confidence: number | null; ego_speed_mps: number | null; distance_to_object_m: number | null; relative_velocity_mps: number | null; stopping_distance_m: number | null; ttc_s: number | null; ttc_validity: string[]; planner_response: Record<string, unknown> | null; disengagement_probability: number | null; metric_delta: Record<string, number> | null; statistical_significance: StatSignificance | null; distribution_shift: Record<string, unknown> | null; root_cause_hypotheses: RootCauseHypothesis[]; evidence: EvidenceItem[]; retrieved_standards: RetrievedStandard[]; uncertainty: UncertaintyReport; human_review_required: boolean; human_review_reasons: string[];}
export interface AnalyzeResponse { status: string; scorecard: RetrospectiveScorecard; markdown: string;}
export interface FixtureInfo { fixture_id: string; evaluation_id: string; description: string; weather: string | null;}
export interface BackendStatus { backend: string; available: boolean; endpoint: string | null; model: string | null; detail: string; health_latency_ms: number | null;}
export interface CompatCheck { link: string; status: 'PASS' | 'FAIL' | 'SKIPPED'; reason: string; remediation: string | null;}
export interface CompatReport { vllm_supported: boolean; platform_summary: string; checks: CompatCheck[]; failed_link: string | null; notes: string[];}
export interface EnvironmentReport { os_name: string; os_version: string; machine_arch: string; is_macos: boolean; is_apple_silicon: boolean; python_version: string; gpus: { vendor: string; model: string; unified_memory: boolean; detail: string }[]; vllm_installed: boolean; ollama_endpoint: string | null; ollama_models: string[]; notes: string[];}
export interface AuditRecord { call_id: string; analysis_id: string; tool: string; timestamp: string; args: Record<string, unknown>; status: string; result_hash: string | null; elapsed_ms: number; error: string | null; authorized_write: boolean;}
export interface AnalysisSummary { evaluation_id: string; created_at: string | null; failure_type: string | null; severity: RetroSeverity | null; launch_recommendation: LaunchRecommendation | null; backend_used: string | null; human_review_required: boolean | null;}
export interface ToolSpec { name: string; description: string; input_schema: Record<string, unknown>; output_schema: Record<string, unknown>; read_only: boolean; timeout_s: number; error_behavior: string;}123456789101112131415161718192021222324252627282930313233343536373839"""Shared fixtures for the retro (Agentic Retrospective Safety Analyzer) suite.
- retro_root: function-scoped isolated runs/retro replacement (RETRO_RUNS_DIR).- fallback_index: forces the deterministic numpy/hashed-TF store so RAG tests never depend on chromadb's model download or ANN nondeterminism.- registry: audited tool registry bound to the isolated root."""
from __future__ import annotations
import pytest
import sensorflow.retro.rag.retriever as retriever_modfrom sensorflow.retro.rag.retriever import SafetyCaseIndexfrom sensorflow.retro.rag.store import NumpyCosineStorefrom sensorflow.retro.tools.builtin import build_registry
@pytest.fixture()def retro_root(tmp_path, monkeypatch): root = tmp_path / "retro" monkeypatch.setenv("RETRO_RUNS_DIR", str(root)) return root
@pytest.fixture(scope="session")def fallback_index(): return SafetyCaseIndex(store=NumpyCosineStore())
@pytest.fixture(autouse=True)def _pin_fallback_index(fallback_index, monkeypatch): """All retro tests retrieve through the deterministic fallback index.""" monkeypatch.setattr(retriever_mod, "_INDEX", fallback_index)
@pytest.fixture()def registry(retro_root): return build_registry(analysis_id="test-analysis")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195"""Agent pipeline tests: canonical fixtures, fact/inference separation,stripped-telemetry -> UNKNOWN, scorecard completeness and tier tagging."""
from __future__ import annotations
import json
import pytest
from sensorflow.retro import store as retro_storefrom sensorflow.retro.agent.orchestrator import analyze, analyze_fixturefrom sensorflow.retro.scorecard import (EvidenceTier, LaunchRecommendation, RetrospectiveScorecard, Severity)
@pytest.fixture()def phantom(retro_root) -> RetrospectiveScorecard: return analyze_fixture("phantom_brake_plastic_bag", backend="mock")
@pytest.fixture()def missed_ped(retro_root) -> RetrospectiveScorecard: return analyze_fixture("missed_pedestrian_rain", backend="mock")
# ----------------------------------------------------- canonical fixture A
def test_phantom_brake_fixture_analysis(phantom): sc = phantom assert sc.failure_type == "FALSE_POSITIVE" assert sc.severity == Severity.CRITICAL # hard brake + tailgater assert sc.launch_recommendation == LaunchRecommendation.FAIL assert sc.object_class == "plastic_bag" # causal hypotheses reference the actual evidence texts = " ".join(h.hypothesis.lower() for h in sc.root_cause_hypotheses) assert "deformable" in texts or "training-distribution" in texts assert any("velocity latch" in h.hypothesis.lower() for h in sc.root_cause_hypotheses) # phantom braking requirement was retrieved assert any(s.doc_id == "SFS-SAFE-001" for s in sc.retrieved_standards)
# ----------------------------------------------------- canonical fixture B
def test_missed_pedestrian_fixture_analysis(missed_ped): sc = missed_ped assert sc.failure_type == "FALSE_NEGATIVE" assert sc.severity == Severity.CRITICAL assert sc.launch_recommendation == LaunchRecommendation.FAIL assert sc.human_review_required # kinematics: pedestrian inside stopping distance assert sc.stopping_distance_m is not None assert sc.distance_to_object_m <= sc.stopping_distance_m * 1.05 assert sc.ttc_s is not None and sc.ttc_s < 2.5 # rain-conditioned hypothesis grounded in sensor evidence assert any("fusion" in h.hypothesis.lower() for h in sc.root_cause_hypotheses) # SCR regression computed and significant -> reflected in the gate assert sc.safety_critical_recall_impact == pytest.approx(-3 / 1240, abs=1e-6) assert sc.statistical_significance.significant is True assert any(s.doc_id in ("SFS-SAFE-001", "SFS-PERC-002") for s in sc.retrieved_standards)
# --------------------------------------------------- fact/inference separation
def test_fact_inference_separation(missed_ped): sc = missed_ped tiers = {e.tier for e in sc.evidence} assert {EvidenceTier.OBSERVED, EvidenceTier.DERIVED, EvidenceTier.RETRIEVED, EvidenceTier.AI_HYPOTHESIS} <= tiers # hypotheses never appear as observed/derived facts for e in sc.evidence: if e.tier == EvidenceTier.AI_HYPOTHESIS: assert "inference" in e.provenance for h in sc.root_cause_hypotheses: assert h.tier == EvidenceTier.AI_HYPOTHESIS assert h.supporting_evidence_keys, "hypotheses must cite evidence" # observed items carry artifact provenance observed = [e for e in sc.evidence if e.tier == EvidenceTier.OBSERVED] assert all("artifact" in e.provenance or "eval log field" in e.provenance for e in observed) # rendered scorecard keeps the five-way distinction md = sc.render_markdown() for heading in ("FACT", "DERIVED FACT", "RETRIEVED REQUIREMENT", "AI HYPOTHES", "SAFETY DETERMINATION"): assert heading in md
# ------------------------------------------------- stripped telemetry -> UNKNOWN
def test_stripped_telemetry_produces_unknown_not_guesses(retro_root): sc = analyze_fixture("missing_telemetry_variant", backend="mock") assert sc.failure_type == "FALSE_NEGATIVE" # stripped fields must be UNKNOWN, never guessed assert sc.ego_speed_mps is None assert sc.stopping_distance_m is None assert sc.ttc_s is None assert "ego.speed_mps" in sc.uncertainty.missing_fields assert "counterfactual_planner_response" in sc.uncertainty.missing_fields assert "stopping_distance" in sc.uncertainty.unknown_metrics assert "ttc" in sc.uncertainty.unknown_metrics # UNKNOWN markers surface in the evidence chain unknown_ev = [e for e in sc.evidence if e.value == "UNKNOWN"] assert unknown_ev # and the gate refuses to make a decision assert sc.launch_recommendation == LaunchRecommendation.INSUFFICIENT_EVIDENCE assert sc.human_review_required
def test_dynamically_stripped_field_becomes_unknown(retro_root): """Strip a field from fixture B at runtime -> the output marks it UNKNOWN.""" from sensorflow.retro.tools.builtin import FIXTURES_DIR log = json.loads((FIXTURES_DIR / "missed_pedestrian_rain.json").read_text()) del log["ego"]["speed_mps"] log["evaluation_id"] = "EVAL-STRIPPED-01" upload = retro_store.uploads_dir() / "stripped.json" upload.write_text(json.dumps(log))
sc = analyze(path=str(upload), backend="mock") assert sc.ego_speed_mps is None assert "ego.speed_mps" in sc.uncertainty.missing_fields assert sc.stopping_distance_m is None # not computable without speed assert sc.launch_recommendation == LaunchRecommendation.INSUFFICIENT_EVIDENCE
# ------------------------------------------------- severity divergence flow
def test_llm_severity_divergence_flagged(retro_root): """On the missing-telemetry variant the scripted 'LLM' proposes CRITICAL (near-miss heuristic) while policy computes DISRUPTIVE from the sparse evidence -> divergence recorded, policy wins, human review required.""" sc = analyze_fixture("missing_telemetry_variant", backend="mock") assert sc.ai_proposed_severity == Severity.CRITICAL assert sc.severity == Severity.DISRUPTIVE assert sc.severity_divergence assert any("diverged" in r for r in sc.human_review_reasons) assert any("severity adjudication" in n for n in sc.uncertainty.notes)
# ------------------------------------------------------ variants + persistence
def test_benign_variants_pass(retro_root): fp = analyze_fixture("benign_fp_static_sign", backend="mock") fn = analyze_fixture("noncritical_fn_parked_vehicle", backend="mock") assert fp.severity == Severity.BENIGN assert fp.launch_recommendation == LaunchRecommendation.PASS assert fn.severity == Severity.BENIGN assert fn.launch_recommendation == LaunchRecommendation.PASS assert not fn.human_review_required
def test_analysis_persisted_with_audit(retro_root): sc = analyze_fixture("phantom_brake_plastic_bag", backend="mock") stored = retro_store.load_analysis(sc.evaluation_id) assert stored and stored["scorecard"]["failure_type"] == "FALSE_POSITIVE" assert "# Retrospective Scorecard" in stored["markdown"] audit = retro_store.read_audit(stored["audit_analysis_id"]) tools_used = {r["tool"] for r in audit} assert {"log_reader", "metric_calculator", "safety_standard_rag", "historical_failure_search", "distribution_analysis"} <= tools_used # no write-tool call happened during analysis assert "create_evaluation_case" not in tools_used
def test_scorecard_completeness_spec_fields(missed_ped): """Every spec field exists and the strictly-typed model round-trips.""" sc = missed_ped dumped = json.loads(sc.model_dump_json()) for field in ["evaluation_id", "failure_type", "severity", "safety_critical_recall_impact", "behavioral_consequence", "launch_recommendation", "baseline_model", "candidate_model", "scenario", "object_class", "ground_truth", "prediction", "confidence", "ego_speed_mps", "distance_to_object_m", "stopping_distance_m", "ttc_s", "planner_response", "disengagement_probability", "metric_delta", "statistical_significance", "distribution_shift", "root_cause_hypotheses", "evidence", "retrieved_standards", "uncertainty", "human_review_required", "policy_version", "agent_version"]: assert field in dumped, f"missing spec field {field}" assert dumped["policy_version"].startswith("retro-policy/") assert dumped["agent_version"].startswith("retro-agent/") restored = RetrospectiveScorecard(**dumped) assert restored.severity == sc.severity
def test_historical_search_finds_prior_analyses(retro_root): analyze_fixture("missed_pedestrian_rain", backend="mock") from sensorflow.retro.tools.builtin import build_registry reg = build_registry(analysis_id="hist-test") res = reg.call("historical_failure_search", {"query_text": "pedestrian rain night missed detection", "k": 3}) assert res.result["corpus_size"] >= 1 assert any(m["evaluation_id"] == "EVAL-2026-0802-MP01" for m in res.result["matches"])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111"""API lifecycle tests for /api/retro via TestClient."""
from __future__ import annotations
import json
import pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient
from sensorflow.retro.api import router
@pytest.fixture()def client(retro_root): app = FastAPI() app.include_router(router) return TestClient(app)
def test_env_and_compat_endpoints(client): env = client.get("/api/retro/env").json()["environment"] assert "os_name" in env and "gpus" in env compat = client.get("/api/retro/compat").json() assert "vllm_supported" in compat["report"] assert "[" in compat["formatted"] # formatted chain output
def test_backends_endpoint(client): body = client.get("/api/retro/backends").json() names = {b["backend"] for b in body["backends"]} assert names == {"mock", "ollama", "vllm"}
def test_rag_search_and_eval_endpoints(client): hits = client.get("/api/retro/rag/search", params={"q": "phantom braking plastic bag", "k": 3}).json() assert hits["hits"] and all("retrieved_text" in h for h in hits["hits"]) ev = client.get("/api/retro/rag/eval", params={"k": 4}).json()["report"] assert ev["precision_at_k"] >= 0.85
def test_fixtures_listing(client): fixtures = client.get("/api/retro/fixtures").json()["fixtures"] ids = {f["fixture_id"] for f in fixtures} assert {"phantom_brake_plastic_bag", "missed_pedestrian_rain"} <= ids
def test_analyze_lifecycle(client): res = client.post("/api/retro/analyze", params={"fixture_id": "missed_pedestrian_rain", "backend": "mock"}) assert res.status_code == 200 body = res.json() sc = body["scorecard"] assert sc["failure_type"] == "FALSE_NEGATIVE" assert sc["launch_recommendation"] == "FAIL" assert "# Retrospective Scorecard" in body["markdown"]
eval_id = sc["evaluation_id"] listing = client.get("/api/retro/analyses").json()["analyses"] assert any(a["evaluation_id"] == eval_id for a in listing)
detail = client.get(f"/api/retro/analyses/{eval_id}").json() assert detail["scorecard"]["severity"] == "CRITICAL"
audit = client.get(f"/api/retro/analyses/{eval_id}/audit").json() assert audit["records"] assert all({"tool", "timestamp", "result_hash", "status"} <= set(r) for r in audit["records"])
def test_analyze_uploaded_log(client): from sensorflow.retro.tools.builtin import FIXTURES_DIR log = json.loads((FIXTURES_DIR / "benign_fp_static_sign.json").read_text()) log["evaluation_id"] = "EVAL-UPLOADED-77" res = client.post("/api/retro/analyze", params={"backend": "mock"}, json=log) assert res.status_code == 200 assert res.json()["scorecard"]["evaluation_id"] == "EVAL-UPLOADED-77"
def test_analyze_error_paths(client): assert client.post("/api/retro/analyze").status_code == 400 assert client.post("/api/retro/analyze", params={"fixture_id": "nope"}).status_code == 404 assert client.post("/api/retro/analyze", params={"fixture_id": "x", "backend": "gpt9"} ).status_code == 422 missing = client.get("/api/retro/analyses/NOPE") assert missing.status_code == 404
def test_tools_listing(client): tools = client.get("/api/retro/tools").json()["tools"] by_name = {t["name"]: t for t in tools} assert by_name["log_reader"]["read_only"] is True assert by_name["create_evaluation_case"]["read_only"] is False assert all("input_schema" in t and "output_schema" in t for t in tools)
def test_vllm_backend_honestly_unavailable_locally(client): """On this macOS machine an analysis with backend=vllm must fail with a clear 503 unless a remote CUDA/ROCm endpoint is configured.""" import platform if platform.system() != "Darwin": pytest.skip("assertion set is for the macOS dev host") res = client.post("/api/retro/analyze", params={"fixture_id": "benign_fp_static_sign", "backend": "vllm"}) assert res.status_code == 503 assert "unavailable" in res.json()["detail"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120"""Phase 1 tests: environment detection, compat chain, backend client."""
from __future__ import annotations
import platform
import pytest
from sensorflow.retro.inference.client import (MockBackend, VALIDATION_EXPECT, all_backend_statuses, get_backend)from sensorflow.retro.inference.compat import (FAIL, PASS, SKIPPED, check_vllm_compatibility, format_report)from sensorflow.retro.inference.env_detect import detect_environment
IS_MACOS = platform.system() == "Darwin"
# ------------------------------------------------------------ env detection
def test_env_detection_reports_this_machine_honestly(): env = detect_environment(probe_ollama=False) assert env.os_name == platform.system() assert env.machine_arch == platform.machine() assert env.python_version.count(".") == 2 if IS_MACOS: assert env.is_macos # No CUDA/ROCm stack exists on macOS — detection must say so. assert not env.nvidia_smi_present assert not env.rocm_smi_present assert not any(g.vendor in ("nvidia", "amd") for g in env.gpus) assert any("vLLM does not run on macOS" in n for n in env.notes)
def test_env_detection_never_fabricates_torch(): env = detect_environment(probe_ollama=False) try: import torch # noqa: F401 assert env.torch.installed except ImportError: assert not env.torch.installed assert "not importable" in env.torch.detail
# --------------------------------------------------------------- compat chain
@pytest.mark.skipif(not IS_MACOS, reason="assertion set is for the macOS dev host")def test_vllm_reported_unsupported_on_this_machine(): report = check_vllm_compatibility() assert report.vllm_supported is False assert report.failed_link == "gpu" assert "UNSUPPORTED" in report.platform_summary gpu = next(c for c in report.checks if c.link == "gpu") assert gpu.status == FAIL assert "vLLM requires NVIDIA CUDA or AMD ROCm" in gpu.reason assert gpu.remediation and "ollama" in gpu.remediation
def test_compat_chain_failure_clarity_blocked_links(): """Every link after the first failure is SKIPPED with a clear blocked-by message — the chain never pretends to evaluate unreachable links.""" report = check_vllm_compatibility() if report.vllm_supported: # only on a real GPU host assert all(c.status == PASS for c in report.checks) return seen_fail = False for check in report.checks: if check.status == FAIL and not seen_fail: seen_fail = True assert check.reason # human-readable continue if seen_fail: assert check.status == SKIPPED assert "blocked by failed" in check.reason text = format_report(report) assert "[FAIL]" in text and "remediation:" in text
def test_compat_chain_covers_all_links_in_order(): report = check_vllm_compatibility() assert [c.link for c in report.checks] == [ "gpu", "driver", "torch", "vllm", "model", "quantization"]
# ------------------------------------------------------------- client contract
def test_mock_backend_contract(): b = get_backend("mock") assert isinstance(b, MockBackend) st = b.health() assert st.available and st.backend == "mock"
v = b.validate() assert v.passed and v.got == VALIDATION_EXPECT assert v.prompt_tokens > 0 and v.completion_tokens > 0 assert v.latency_ms >= 0
# deterministic: identical prompt -> identical reply and token counts r1 = b.generate("what happened in scenario X?") r2 = b.generate("what happened in scenario X?") assert r1.text == r2.text assert r1.prompt_tokens == r2.prompt_tokens assert r1.completion_tokens == r2.completion_tokens
def test_unknown_backend_rejected(): with pytest.raises(ValueError, match="unknown backend"): get_backend("gpt-in-the-sky")
def test_all_backend_statuses_never_raise(): statuses = all_backend_statuses() assert {s.backend for s in statuses} == {"mock", "ollama", "vllm"} mock = next(s for s in statuses if s.backend == "mock") assert mock.available # ollama/vllm may or may not be reachable; whatever the answer, it must # carry a human-readable detail rather than an exception. for s in statuses: assert isinstance(s.detail, str)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130"""Deterministic metric tests: stopping-distance parameterization, TTCvalidity flags, SCR criticality, behavioral comparison."""
from __future__ import annotations
import pytest
from sensorflow.retro import metrics
# ---------------------------------------------------------- stopping distance
def test_stopping_distance_baseline_case(): r = metrics.stopping_distance(velocity_mps=20.0, reaction_time_s=1.0, friction=0.7, grade=0.0) # reaction 20m + braking 400/(2*6.8646) = 29.13m assert r.reaction_distance_m == pytest.approx(20.0) assert r.braking_distance_m == pytest.approx(29.13, abs=0.05) assert r.stopping_distance_m == pytest.approx(49.13, abs=0.1)
def test_stopping_distance_latency_charged_against_budget(): base = metrics.stopping_distance(velocity_mps=15.0, reaction_time_s=0.25) lat = metrics.stopping_distance(velocity_mps=15.0, reaction_time_s=0.25, system_latency_s=0.3, planner_latency_s=0.1) assert lat.total_reaction_time_s == pytest.approx(0.65) assert lat.stopping_distance_m - base.stopping_distance_m == pytest.approx( 15.0 * 0.4, abs=0.02)
def test_stopping_distance_grade_and_friction(): flat = metrics.stopping_distance(velocity_mps=20.0, friction=0.5, grade=0.0) downhill = metrics.stopping_distance(velocity_mps=20.0, friction=0.5, grade=-0.08) uphill = metrics.stopping_distance(velocity_mps=20.0, friction=0.5, grade=0.08) assert downhill.stopping_distance_m > flat.stopping_distance_m > uphill.stopping_distance_m wet = metrics.stopping_distance(velocity_mps=20.0, friction=0.3) dry = metrics.stopping_distance(velocity_mps=20.0, friction=0.9) assert wet.stopping_distance_m > dry.stopping_distance_m
def test_stopping_distance_explicit_decel_and_impossible_grade(): explicit = metrics.stopping_distance(velocity_mps=20.0, decel_mps2=5.0) assert explicit.effective_decel_mps2 == pytest.approx(5.0) impossible = metrics.stopping_distance(velocity_mps=20.0, friction=0.05, grade=-0.2) assert impossible.stopping_distance_m is None assert "undefined" in impossible.unknown_reason
def test_stopping_distance_missing_velocity_is_unknown(): r = metrics.stopping_distance(velocity_mps=None) assert r.stopping_distance_m is None assert "UNKNOWN" in r.unknown_reason
# ------------------------------------------------------------------------ TTC
def test_ttc_closing_matches_closed_form(): r = metrics.time_to_collision(distance_m=30.0, closing_velocity_mps=10.0, ego_length_m=4.5, obj_length_m=0.5) # gap = 30 - (4.5+0.5)/2 = 27.5 -> 2.75 s assert r.ttc_s == pytest.approx(2.75, abs=0.05) assert r.closed_form_ttc_s == pytest.approx(2.75, abs=0.01) assert any("constant-velocity" in f for f in r.validity_flags) assert any("ssam_ext" in f for f in r.validity_flags)
def test_ttc_not_closing_flagged_undefined(): r = metrics.time_to_collision(distance_m=30.0, closing_velocity_mps=-2.0) assert r.ttc_s is None assert any("not closing" in f for f in r.validity_flags) assert r.unknown_reason is None # defined situation, not missing data
def test_ttc_missing_telemetry_unknown(): r = metrics.time_to_collision(distance_m=None, closing_velocity_mps=5.0) assert r.ttc_s is None assert "UNKNOWN" in r.unknown_reason
def test_ttc_beyond_lookahead_flagged(): r = metrics.time_to_collision(distance_m=200.0, closing_velocity_mps=1.0, look_ahead_s=5.0) assert r.ttc_s is None assert any("look-ahead" in f for f in r.validity_flags)
# ------------------------------------------------------------------------ SCR
def test_scr_impact_computation(): r = metrics.scr_impact({"critical_object_count": 1000, "baseline_missed_critical": 2, "candidate_missed_critical": 5}) assert r.scr_baseline == pytest.approx(0.998) assert r.scr_candidate == pytest.approx(0.995) assert r.scr_impact == pytest.approx(-0.003) assert r.denominator == 1000 assert "stopping distance" in r.criticality_policy
def test_scr_impact_unknown_without_denominator(): r = metrics.scr_impact({"baseline_missed_critical": 2}) assert r.scr_impact is None assert "UNKNOWN" in r.unknown_reason assert metrics.scr_impact(None).scr_impact is None
# ---------------------------------------------------------- behavioral impact
def test_behavioral_impact_phantom_intervention(): r = metrics.behavioral_impact( {"action": "emergency_brake", "decel_mps2": 6.2, "response_time_s": 0.4}, {"action": "maintain_speed", "decel_mps2": 0.0, "response_time_s": 0.4}) assert r.action_changed and r.decel_delta_mps2 == pytest.approx(6.2) assert "unwarranted intervention" in r.consequence
def test_behavioral_impact_delayed_response(): r = metrics.behavioral_impact( {"action": "emergency_brake", "decel_mps2": 8.0, "response_time_s": 2.4}, {"action": "controlled_brake", "decel_mps2": 3.5, "response_time_s": 0.5}) assert r.response_delay_s == pytest.approx(1.9) assert "DELAYED" in r.consequence
def test_behavioral_impact_unknown_without_counterfactual(): r = metrics.behavioral_impact( {"action": "emergency_brake", "decel_mps2": 8.0}, None) assert r.consequence == "UNKNOWN" assert "counterfactual" in r.unknown_reason1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950"""Optional-dependency integrations: chromadb store and the MCP server bonus.
These skip honestly when the optional packages are absent — the fallbackpaths are covered by the rest of the suite either way."""
from __future__ import annotations
import pytest
from sensorflow.retro.rag.embedder import chromadb_available
@pytest.mark.skipif(not chromadb_available(), reason="chromadb not installed")def test_chroma_store_same_interface(): from sensorflow.retro.rag.store import ChromaStore store = ChromaStore(collection_name="retro_test_iface") store.add(["c1", "c2"], ["pedestrian crossing in heavy rain at night", "plastic bag drifting across a highway lane"], [{"doc_id": "D1", "synthetic": "true"}, {"doc_id": "D2", "synthetic": "true"}]) hits = store.query("missed pedestrian in rain", k=1) assert hits and hits[0].chunk_id == "c1" assert 0.0 <= hits[0].relevance_score <= 1.0 assert hits[0].metadata["doc_id"] == "D1"
@pytest.mark.skipif(not chromadb_available(), reason="chromadb not installed")def test_full_index_on_chroma_backend(): from sensorflow.retro.rag.retriever import SafetyCaseIndex from sensorflow.retro.rag.store import ChromaStore index = SafetyCaseIndex(store=ChromaStore(collection_name="retro_test_full")) hits = index.search("phantom braking caused by plastic bag", k=3) assert hits and any(h.doc_id in ("SFS-SAFE-001", "SFS-RETRO-HIST-01") for h in hits) assert all(h.label for h in hits) # synthetic labels survive chroma round-trip
def test_mcp_server_bonus_builds_if_installed(retro_root): try: import mcp # noqa: F401 except ImportError: pytest.skip("mcp not installed; registry remains the MCP-style boundary") from sensorflow.retro.tools.mcp_server import build_mcp_server server, registry = build_mcp_server() assert {s.name for s in registry.specs()} >= { "log_reader", "safety_standard_rag", "metric_calculator", "historical_failure_search", "distribution_analysis", "create_evaluation_case"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142"""Phase 4 tests: asymmetric severity model, adjudication, launch gate."""
from __future__ import annotations
from sensorflow.retro.policy import (POLICY_CONFIG, SEVERITY_ORDER, SeverityContext, adjudicate_severity, compute_severity, launch_gate)from sensorflow.retro.scorecard import LaunchRecommendation, Severity
def _rank(sev: Severity) -> int: return SEVERITY_ORDER.index(sev)
# --------------------------------------------------------- asymmetric costs
def test_benign_distant_fn_ranks_below_phantom_braking_fp(): """The spec's pinned ordering: NOT every FN outranks every FP.""" benign_fn = compute_severity(SeverityContext( failure_type="FALSE_NEGATIVE", object_class="vehicle", distance_m=87.0, stopping_distance_m=8.7, closing_velocity_mps=-0.2, ego_speed_mps=8.3)) phantom_fp = compute_severity(SeverityContext( failure_type="FALSE_POSITIVE", object_class="plastic_bag", intervention_decel_mps2=6.2, following_gap_s=0.9, ego_speed_mps=24.6)) assert benign_fn.severity == Severity.BENIGN assert phantom_fp.severity == Severity.CRITICAL assert _rank(benign_fn.severity) < _rank(phantom_fp.severity) assert benign_fn.score < phantom_fp.score
def test_fn_vru_inside_stopping_distance_is_critical(): r = compute_severity(SeverityContext( failure_type="FALSE_NEGATIVE", object_class="pedestrian", distance_m=26.0, stopping_distance_m=26.2, closing_velocity_mps=13.9, ttc_s=1.69, total_reaction_time_s=0.53, near_miss=True)) assert r.severity == Severity.CRITICAL assert any("stopping" in t for t in r.rule_trace)
def test_fn_collision_is_fatal(): r = compute_severity(SeverityContext( failure_type="FALSE_NEGATIVE", object_class="pedestrian", distance_m=10.0, stopping_distance_m=25.0, closing_velocity_mps=12.0, collision_occurred=True)) assert r.severity == Severity.FATAL
def test_fp_gentle_slowdown_without_traffic_is_benign(): r = compute_severity(SeverityContext( failure_type="FALSE_POSITIVE", object_class="traffic_sign", intervention_decel_mps2=1.2, following_gap_s=4.2, ego_speed_mps=12.0)) assert r.severity == Severity.BENIGN
def test_fp_hard_brake_rule_requires_tailgater(): tailgated = compute_severity(SeverityContext( failure_type="FALSE_POSITIVE", intervention_decel_mps2=4.5, following_gap_s=1.0, ego_speed_mps=20.0)) clear_road = compute_severity(SeverityContext( failure_type="FALSE_POSITIVE", intervention_decel_mps2=4.5, following_gap_s=4.0, ego_speed_mps=20.0)) assert tailgated.severity == Severity.CRITICAL assert _rank(clear_road.severity) < _rank(tailgated.severity)
def test_severity_is_deterministic(): ctx = SeverityContext(failure_type="FALSE_NEGATIVE", object_class="cyclist", distance_m=18.0, stopping_distance_m=20.0, closing_velocity_mps=9.0, ttc_s=1.8, total_reaction_time_s=0.6) results = {compute_severity(ctx).model_dump_json() for _ in range(5)} assert len(results) == 1
def test_rule_trace_is_explainable(): r = compute_severity(SeverityContext( failure_type="FALSE_POSITIVE", intervention_decel_mps2=6.0, following_gap_s=0.8, ego_speed_mps=25.0)) assert r.rule_trace[0].startswith("policy retro-policy/") assert len(r.rule_trace) >= 4
# ------------------------------------------------------------- adjudication
def test_ai_severity_divergence_recorded_and_policy_wins(): policy = compute_severity(SeverityContext( failure_type="FALSE_POSITIVE", intervention_decel_mps2=1.0, following_gap_s=5.0, ego_speed_mps=10.0)) adj = adjudicate_severity(policy, Severity.CRITICAL) assert adj.final_severity == policy.severity # policy always authoritative assert adj.divergence assert "overstated" in adj.divergence_note
agree = adjudicate_severity(policy, policy.severity) assert not agree.divergence no_proposal = adjudicate_severity(policy, None) assert not no_proposal.divergence
# --------------------------------------------------------------- launch gate
def test_gate_insufficient_evidence_never_pass(): d = launch_gate(Severity.BENIGN, has_evidence_gaps=True, scr_impact=0.001, scr_significant=False) assert d.recommendation == LaunchRecommendation.INSUFFICIENT_EVIDENCE assert any("never be converted to PASS" in r for r in d.rationale) # even a FATAL with gaps stays INSUFFICIENT_EVIDENCE (gaps block first, # and certainly never improve the outcome to PASS) d2 = launch_gate(Severity.FATAL, has_evidence_gaps=True, scr_impact=None, scr_significant=None) assert d2.recommendation != LaunchRecommendation.PASS
def test_gate_critical_fails(): d = launch_gate(Severity.CRITICAL, has_evidence_gaps=False, scr_impact=0.0, scr_significant=False) assert d.recommendation == LaunchRecommendation.FAIL
def test_gate_scr_regression_with_significance_fails(): tol = POLICY_CONFIG["scr_regression_tolerance"] d = launch_gate(Severity.BENIGN, has_evidence_gaps=False, scr_impact=-(tol * 2), scr_significant=True) assert d.recommendation == LaunchRecommendation.FAIL # same delta without established significance -> conditional, not fail d2 = launch_gate(Severity.BENIGN, has_evidence_gaps=False, scr_impact=-(tol * 2), scr_significant=None) assert d2.recommendation == LaunchRecommendation.CONDITIONAL_PASS
def test_gate_disruptive_conditional_and_benign_pass(): assert launch_gate(Severity.DISRUPTIVE, False, 0.0, False).recommendation \ == LaunchRecommendation.CONDITIONAL_PASS assert launch_gate(Severity.BENIGN, False, 0.001, False).recommendation \ == LaunchRecommendation.PASS
def test_gate_determinism(): outs = {launch_gate(Severity.DISRUPTIVE, False, -0.001, False).model_dump_json() for _ in range(5)} assert len(outs) == 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125"""Phase 2 tests: chunking, retrieval eval, synthetic labeling, and theno-citation-without-retrieval hard rule."""
from __future__ import annotations
import pytestfrom pydantic import ValidationError
from sensorflow.retro.rag.chunking import chunk_document, chunk_words, parse_sectionsfrom sensorflow.retro.rag.corpus import SEED_DOCUMENTSfrom sensorflow.retro.rag.evalharness import EVAL_QUERIES, run_retrieval_evalfrom sensorflow.retro.scorecard import RetrievedStandard
# ------------------------------------------------------------------ chunking
def test_parse_sections_and_word_chunking(): text = "preamble line\n## Alpha\n" + ("word " * 300) + "\n## Beta\nshort tail" secs = parse_sections(text) assert [s["section"] for s in secs] == ["preamble", "Alpha", "Beta"] chunks = chunk_words(secs[1]["text"], chunk_size=100, overlap=20) assert len(chunks) >= 3 # overlap: consecutive chunks share their boundary words first_words = chunks[0].split() second_words = chunks[1].split() assert first_words[-20:] == second_words[:20]
def test_chunk_config_validation(): with pytest.raises(ValueError): chunk_words("a b c", chunk_size=10, overlap=10) with pytest.raises(ValueError): chunk_words("a b c", chunk_size=0)
def test_chunk_document_propagates_metadata(): chunks = chunk_document("DOC-1", "## Sec A\nhello world content here", {"doc_id": "DOC-1", "source": "unit"}, chunk_size=50, overlap=10) assert chunks and chunks[0].metadata["section"] == "Sec A" assert chunks[0].metadata["source"] == "unit"
# ---------------------------------------------------------------- eval harness
def test_retrieval_eval_precision(fallback_index): report = run_retrieval_eval(index=fallback_index, k=4) assert report.num_queries == len(EVAL_QUERIES) >= 12 # deterministic fallback embedder must resolve at least 85% of the # expected-source assertions at k=4 assert report.precision_at_k >= 0.85, [ r.model_dump() for r in report.results if not r.hit_at_k]
def test_every_synthetic_hit_is_labeled(fallback_index): """Synthetic rules carry the SYNTHETIC label in content AND metadata; the SOTIF doc carries the paraphrase label. No unlabeled hit can exist.""" for item in EVAL_QUERIES: for hit in fallback_index.search(item["query"], k=4): if hit.synthetic: assert "SYNTHETIC_EXAMPLE" in hit.label assert ("SYNTHETIC_EXAMPLE" in hit.retrieved_text or "NOT_A_REAL_STANDARD" in hit.retrieved_text) else: assert hit.label == "PARAPHRASE_NOT_STANDARD_TEXT" assert "PARAPHRASE_NOT_STANDARD_TEXT" in hit.retrieved_text
def test_seed_corpus_covers_required_doc_types(): types = {d["doc_type"] for d in SEED_DOCUMENTS} assert {"safety_requirement", "launch_criteria", "perception_requirement", "odd_definition", "historical_retrospective", "evaluation_policy", "standard_concept_paraphrase"} <= types for doc in SEED_DOCUMENTS: # full metadata is mandatory for key in ("source", "version", "jurisdiction", "doc_type", "effective_date"): assert doc[key]
# ------------------------------------- no-citation-without-retrieval hard rule
def test_citation_impossible_without_retrieved_text(): """RetrievedStandard has no escape hatch: a citation cannot be built without real retrieved text and a relevance score.""" base = dict(source="s", document="d", version="1", section="x", doc_id="D-1", doc_type="t", jurisdiction="j", effective_date="2026-01-01", synthetic=True, label="L", chunk_id="c1") with pytest.raises(ValidationError): RetrievedStandard(**base) # no retrieved_text / relevance_score at all with pytest.raises(ValidationError): RetrievedStandard(**base, retrieved_text="too short", relevance_score=0.5) with pytest.raises(ValidationError): RetrievedStandard(**base, retrieved_text="long enough retrieved text body here", relevance_score=1.7)
def test_retriever_always_returns_full_citation_fields(fallback_index): hits = fallback_index.search("pedestrian stopping distance recall", k=4) assert hits for h in hits: assert h.source and h.document and h.version and h.section assert len(h.retrieved_text) >= 20 assert 0.0 <= h.relevance_score <= 1.0
def test_agent_citations_are_backed_by_retrieval(retro_root): """End-to-end: every citation on a scorecard corresponds to a retrieval hit recorded in the audited RAG tool calls.""" from sensorflow.retro.agent.orchestrator import analyze_fixture from sensorflow.retro.tools.builtin import build_registry from sensorflow.retro import store as retro_store
sc = analyze_fixture("missed_pedestrian_rain", backend="mock") assert sc.retrieved_standards, "canonical fixture must cite requirements" audit = retro_store.read_audit("missed_pedestrian_rain") rag_calls = [r for r in audit if r["tool"] == "safety_standard_rag" and r["status"] == "ok"] assert rag_calls, "citations exist but no audited retrieval call was made" for std in sc.retrieved_standards: assert std.retrieved_text and std.relevance_score >= 0.0 assert std.chunk_id # traceable to a stored chunk123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130"""Phase 3 tests: tool registry permissions, audit completeness, allowlist."""
from __future__ import annotations
import jsonimport time
import pytestfrom pydantic import BaseModel
from sensorflow.retro import store as retro_storefrom sensorflow.retro.tools.registry import ToolPermissionError, ToolRegistry
class _EchoIn(BaseModel): msg: str
class _EchoOut(BaseModel): echoed: str
def test_read_only_is_the_default(registry): specs = {s.name: s for s in registry.specs()} assert specs["log_reader"].read_only is True assert specs["safety_standard_rag"].read_only is True assert specs["metric_calculator"].read_only is True assert specs["historical_failure_search"].read_only is True assert specs["distribution_analysis"].read_only is True # exactly one write tool exists write_tools = [s for s in specs.values() if not s.read_only] assert [t.name for t in write_tools] == ["create_evaluation_case"]
def test_write_tool_requires_explicit_authorization(registry, retro_root): args = {"title": "Rain-night pedestrian case", "description": "derived from retrospective EVAL-2026-0802-MP01", "scenario_tags": ["rain", "night", "pedestrian"], "source_evaluation_id": "EVAL-2026-0802-MP01"} with pytest.raises(ToolPermissionError): registry.call("create_evaluation_case", args) denied = [r for r in registry.audit_log if r.status == "denied"] assert denied and denied[0].tool == "create_evaluation_case"
res = registry.call("create_evaluation_case", args, policy_authorization=True) assert res.ok case_path = res.result["path"] assert json.loads(open(case_path).read())["title"] == args["title"] authorized = [r for r in registry.audit_log if r.tool == "create_evaluation_case" and r.status == "ok"] assert authorized and authorized[0].authorized_write is True
def test_audit_completeness(registry, retro_root): registry.call("safety_standard_rag", {"query": "phantom braking", "k": 2}) with pytest.raises(Exception): registry.call("metric_calculator", {"operation": "nope", "params": {}}) with pytest.raises(KeyError): registry.call("not_a_tool", {})
# every call — ok, error, unknown — is audited with args + timestamp assert len(registry.audit_log) == 3 for rec in registry.audit_log: assert rec.timestamp and rec.args is not None and rec.call_id ok = registry.audit_log[0] assert ok.status == "ok" and len(ok.result_hash) == 64 assert registry.audit_log[1].status == "error" assert registry.audit_log[2].status == "error"
# persisted to the isolated runs root as jsonl persisted = retro_store.read_audit("test-analysis") assert len(persisted) == 3
def test_result_hash_is_deterministic(registry, retro_root): r1 = registry.call("metric_calculator", { "operation": "stopping_distance", "params": {"velocity_mps": 10.0}}) r2 = registry.call("metric_calculator", { "operation": "stopping_distance", "params": {"velocity_mps": 10.0}}) hashes = [rec.result_hash for rec in registry.audit_log if rec.status == "ok"] assert hashes[0] == hashes[1] assert r1.result == r2.result
def test_path_allowlist_enforced(registry, tmp_path): secret = tmp_path / "secret.json" secret.write_text("{}") with pytest.raises(PermissionError, match="allowlist"): registry.call("log_reader", {"path": str(secret)}) with pytest.raises(PermissionError): registry.call("log_reader", {"fixture_id": "../../../etc/passwd"}) # uploads dir IS allowed up = retro_store.uploads_dir() / "ok.json" up.write_text(json.dumps({"evaluation_id": "X", "ground_truth": {"class": "car"}})) res = registry.call("log_reader", {"path": str(up)}) assert res.ok and res.result["log"]["evaluation_id"] == "X"
def test_timeout_enforced(retro_root): reg = ToolRegistry(analysis_id="timeout-test")
def slow(_inp: _EchoIn) -> _EchoOut: time.sleep(1.0) return _EchoOut(echoed="late")
reg.register("slow_echo", slow, _EchoIn, _EchoOut, "slow", timeout_s=0.1) with pytest.raises(TimeoutError): reg.call("slow_echo", {"msg": "hi"}) assert reg.audit_log[-1].status == "timeout"
def test_error_behavior_return_error(retro_root): reg = ToolRegistry(analysis_id="errbehavior-test")
def boom(_inp: _EchoIn) -> _EchoOut: raise RuntimeError("kaput")
reg.register("boom", boom, _EchoIn, _EchoOut, "explodes", error_behavior="return_error") res = reg.call("boom", {"msg": "x"}) assert not res.ok and "kaput" in res.error assert reg.audit_log[-1].status == "error"
def test_tool_schemas_declared(registry): for spec in registry.specs(): assert spec.input_schema.get("properties") is not None assert spec.output_schema.get("properties") is not None assert spec.timeout_s > 0 assert spec.descriptionsrc/components/retro/AuditTrail.tsxAdded+65
src/components/retro/EvidenceChain.tsxAdded+194
src/components/retro/HardwareCard.tsxAdded+73
src/components/retro/ScorecardView.tsxAdded+137
src/components/retro/StandardsPanel.tsxAdded+49
src/components/retro/tierTheme.tsAdded+25
src/content/glossary.ts+38-1
src/content/pageHelp.ts+12
src/context/LabelEvalContext.tsx+2
src/pages/retro/RetroAnalyzerPage.tsxAdded+186
src/services/retro.tsAdded+68
src/types/retro.tsAdded+184
tests/test_retro/__init__.pyAdded
tests/test_retro/conftest.pyAdded+39
tests/test_retro/test_agent.pyAdded+195
tests/test_retro/test_api.pyAdded+111
tests/test_retro/test_inference.pyAdded+120
tests/test_retro/test_metrics.pyAdded+130
tests/test_retro/test_optional_deps.pyAdded+50
tests/test_retro/test_policy.pyAdded+142
tests/test_retro/test_rag.pyAdded+125
tests/test_retro/test_tools.pyAdded+130