Spaces:
Paused
Paused
Deploy Sensorflow Studio (part 2)
Browse filesFiles changed (25)
- src/pages/hillclimb/DashboardView.tsxAdded+187
- src/pages/hillclimb/DesignLabView.tsxAdded+248
- src/pages/hillclimb/DiagnosticView.tsxAdded+142
- src/pages/hillclimb/EvidenceView.tsxAdded+81
- src/pages/hillclimb/HillClimbSection.tsxAdded+91
- src/pages/hillclimb/InterviewView.tsxAdded+175
- src/pages/hillclimb/MatrixView.tsxAdded+151
- src/pages/hillclimb/PracticeView.tsxAdded+232
- src/pages/hillclimb/SimulationView.tsxAdded+247
- src/pages/hillclimb/StarView.tsxAdded+178
- src/services/hillclimb.tsAdded+139
- src/types/hillclimb.tsAdded+424
- tests/test_hillclimb/__init__.pyAdded
- tests/test_hillclimb/conftest.pyAdded+67
- tests/test_hillclimb/test_adaptive.pyAdded+50
- tests/test_hillclimb/test_api.pyAdded+142
- tests/test_hillclimb/test_blueprint.pyAdded+65
- tests/test_hillclimb/test_content.pyAdded+65
- tests/test_hillclimb/test_design_lab.pyAdded+107
- tests/test_hillclimb/test_evaluate.pyAdded+85
- tests/test_hillclimb/test_interviewer.pyAdded+71
- tests/test_hillclimb/test_journey.pyAdded+90
- tests/test_hillclimb/test_readiness.pyAdded+83
- tests/test_hillclimb/test_simulation.pyAdded+87
- tests/test_hillclimb/test_star.pyAdded+64
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187/** Dashboard: readiness bars, bottleneck callout, ONE next-best-action card, journey state. */
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 { ArrowRight, Compass, Mountain } from 'lucide-react';import { ErrorNote, HBar, LoadingBox, SectionCard } from '../../components/labeleval/shared';import { useAsync } from '../../components/hillclimb/shared';import { getJourney, getNextAction, getReadiness } from '../../services/hillclimb';import type { Exercise, JourneyStateId } from '../../types/hillclimb';import type { GoFn } from './HillClimbSection';
const JOURNEY_ORDER: JourneyStateId[] = [ 'NOT_STARTED', 'DIAGNOSTIC', 'LEARNING', 'PRACTICE', 'ASSESSMENT', 'REMEDIATION', 'REASSESS',];
const DIM_COLORS: Record<string, string> = { 'Technical Depth': '#4fc3f7', 'System Design': '#9575cd', Execution: '#ffb74d', Leadership: '#66bb6a', Communication: '#f06292', 'Safety/Risk': '#ef5350',};
export default function DashboardView({ go }: { go: GoFn }) { const readiness = useAsync(getReadiness); const nba = useAsync(getNextAction); const journey = useAsync(getJourney);
if (readiness.loading && !readiness.data) return <LoadingBox label="Computing readiness…" />; if (readiness.error && !readiness.data) return <ErrorNote error={readiness.error} />;
const bn = readiness.data?.bottleneck ?? null; const dims = readiness.data?.dimensions ?? []; const j = journey.data;
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> {j ? ( <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, flexWrap: 'wrap' }}> <Typography variant="caption" sx={{ color: '#8a949e', mr: 0.5 }}> JOURNEY </Typography> {JOURNEY_ORDER.map((s) => ( <Chip key={s} size="small" label={s.replace(/_/g, ' ')} sx={{ height: 20, fontSize: 10.5, fontWeight: j.state === s ? 800 : 500, bgcolor: j.state === s ? '#0d47a1' : '#1a2027', color: j.state === s ? '#90caf9' : '#5c6873', }} /> ))} {j.remediation_target ? ( <Chip size="small" label={`remediating: ${j.remediation_target}`} sx={{ height: 20, fontSize: 10.5, bgcolor: '#e65100', color: '#ffe0b2' }} /> ) : null} </Box> ) : null}
{bn ? ( <Alert severity="warning" variant="outlined" icon={<Mountain size={20} />} sx={{ '& .MuiAlert-message': { width: '100%' } }} > <Typography variant="subtitle2" sx={{ fontWeight: 800 }}> Current bottleneck: {bn.name}{' '} <Chip size="small" label={`phase ${bn.phase} · ${bn.dimension}`} sx={{ ml: 0.5, height: 18, fontSize: 10, bgcolor: '#232a31', color: '#aab4be' }} /> </Typography> <Typography variant="body2" sx={{ color: '#cfd8dc', mt: 0.5 }}> {bn.explanation} </Typography> </Alert> ) : readiness.data ? ( <Alert severity="success" variant="outlined"> No bottleneck: every competency is at COMPETENT or better. Keep polishing toward INTERVIEW_READY. </Alert> ) : null}
<Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}> <SectionCard title="Readiness by dimension" help="Aggregated readiness across the competency matrix, grouped into the six dimensions an EM interview loop actually probes. Bars show average score (1-5) over competencies with any signal; the fraction shows how many are COMPETENT or better." sx={{ flex: '2 1 420px' }} > {dims.map((d) => ( <HBar key={d.dimension} label={`${d.dimension} (${d.competent}/${d.total} competent)`} value={d.avg_score} max={5} color={DIM_COLORS[d.dimension] ?? '#4fc3f7'} valueLabel={d.avg_score > 0 ? `${d.avg_score.toFixed(1)}/5` : 'no signal'} /> ))} <Typography variant="caption" sx={{ color: '#5c6873' }}> Knowledge, application and evidence are tracked separately per competency — open the Competency Matrix for the full explainable breakdown. </Typography> </SectionCard>
<SectionCard title={ <Box component="span" sx={{ display: 'inline-flex', alignItems: 'center', gap: 0.75 }}> <Compass size={16} /> Next best action </Box> } help="Exactly one concept, one exercise, one assessment — chosen by bottleneck analysis (the prerequisite blocking the most downstream competencies, not merely your lowest score)." sx={{ flex: '1 1 340px' }} > {nba.loading && !nba.data ? <LoadingBox label="Choosing your next move…" /> : null} {nba.error && !nba.data ? <ErrorNote error={nba.error} /> : null} {nba.data ? ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.25 }}> <Box> <Typography variant="caption" sx={{ color: '#4fc3f7', fontWeight: 700 }}> 1 · CONCEPT </Typography> <Typography variant="body2" sx={{ fontWeight: 700 }}> {nba.data.concept.name} </Typography> <Typography variant="caption" sx={{ color: '#8a949e' }}> Study: {nba.data.concept.study.join(', ') || nba.data.concept.description} </Typography> </Box> <Box> <Typography variant="caption" sx={{ color: '#9ccc65', fontWeight: 700 }}> 2 · EXERCISE </Typography> <Typography variant="body2" sx={{ color: '#cfd8dc' }}> {nba.data.exercise.scenario.slice(0, 160)}… </Typography> </Box> <Box> <Typography variant="caption" sx={{ color: '#ffb74d', fontWeight: 700 }}> 3 · ASSESSMENT </Typography> <Typography variant="caption" sx={{ color: '#8a949e', display: 'block' }}> {nba.data.assessment.description} </Typography> </Box> <Button variant="contained" size="small" endIcon={<ArrowRight size={15} />} onClick={() => go('practice', nba.data!.exercise as Exercise)} > Start this exercise </Button> </Box> ) : null} </SectionCard> </Box>
{readiness.data && dims.every((d) => d.avg_score === 0) ? ( <Alert severity="info" variant="outlined" action={ <Button size="small" onClick={() => go('diagnostic')}> Run diagnostic </Button> } > No signal yet — run the adaptive diagnostic to seed your competency matrix. </Alert> ) : null} </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248/** Design Lab: challenge brief + pragmatic add-node/connect builder + rationale fields -> graded results. */
import { 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 IconButton from '@mui/material/IconButton';import MenuItem from '@mui/material/MenuItem';import TextField from '@mui/material/TextField';import Typography from '@mui/material/Typography';import { Plus, Trash2 } from 'lucide-react';import { ErrorNote, HBar, LoadingBox, SectionCard } from '../../components/labeleval/shared';import { PassChip, ScoreChip, useAsync } from '../../components/hillclimb/shared';import { getDesignChallenges, submitDesign } from '../../services/hillclimb';import type { DesignComponent, DesignEdge, DesignGrade } from '../../types/hillclimb';
const TYPE_COLORS: Record<string, string> = { source: '#8d6e63', ingestion: '#4fc3f7', stream: '#29b6f6', batch: '#0288d1', storage: '#9575cd', feature: '#7e57c2', training: '#ffb74d', inference: '#ffa726', eval: '#66bb6a', monitoring: '#26a69a', feedback: '#ec407a',};
export default function DesignLabView() { const catalog = useAsync(getDesignChallenges); const [challengeId, setChallengeId] = useState('petabyte_ingestion'); const [components, setComponents] = useState<DesignComponent[]>([]); const [edges, setEdges] = useState<DesignEdge[]>([]); const [rationales, setRationales] = useState<Record<string, string>>({}); const [newType, setNewType] = useState('source'); const [newName, setNewName] = useState(''); const [newNote, setNewNote] = useState(''); const [edgeFrom, setEdgeFrom] = useState(''); const [edgeTo, setEdgeTo] = useState(''); const [grade, setGrade] = useState<DesignGrade | null>(null); const [busy, setBusy] = useState(false); const [error, setError] = useState<string | null>(null);
const challenge = useMemo( () => catalog.data?.challenges.find((c) => c.challenge_id === challengeId) ?? null, [catalog.data, challengeId] );
const reset = (cid: string) => { setChallengeId(cid); setComponents([]); setEdges([]); setRationales({}); setGrade(null); };
const addComponent = () => { const id = `c${components.length + 1}`; setComponents([...components, { id, type: newType, name: newName || `${newType}-${id}`, note: newNote }]); setNewName(''); setNewNote(''); };
const removeComponent = (id: string) => { setComponents(components.filter((c) => c.id !== id)); setEdges(edges.filter((e) => e.source !== id && e.target !== id)); };
const addEdge = () => { if (!edgeFrom || !edgeTo || edgeFrom === edgeTo) return; if (edges.some((e) => e.source === edgeFrom && e.target === edgeTo)) return; setEdges([...edges, { source: edgeFrom, target: edgeTo }]); };
const submit = () => { setBusy(true); setError(null); submitDesign(challengeId, components, edges, rationales) .then(setGrade) .catch((e: Error) => setError(e.message)) .finally(() => setBusy(false)); };
if (catalog.loading && !catalog.data) return <LoadingBox label="Loading challenges…" />; if (catalog.error && !catalog.data) return <ErrorNote error={catalog.error} />;
const nameOf = (id: string) => components.find((c) => c.id === id)?.name ?? id;
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> <SectionCard title="Challenge" action={ <TextField select size="small" value={challengeId} onChange={(e) => reset(e.target.value)} sx={{ minWidth: 280 }}> {(catalog.data?.challenges ?? []).map((c) => ( <MenuItem key={c.challenge_id} value={c.challenge_id}> {c.title} </MenuItem> ))} </TextField> } help="Submit a typed component graph plus a written rationale per key decision. The rule-based grader checks required stages, orphans, feedback-loop closure, single points of failure, capacity math, and rationale coverage of scalability / reliability / latency / cost / observability / failure handling / tradeoffs." > {challenge ? ( <> <Typography variant="body2" sx={{ color: '#e6e9ec', lineHeight: 1.65, mb: 1 }}> {challenge.brief} </Typography> <Typography variant="caption" sx={{ color: '#8a949e' }}> Required stages:{' '} {challenge.required_stages.map((g) => g.join(' or ')).join(' · ')} {challenge.requires_feedback_loop ? ' · must close a feedback loop' : ''} </Typography> </> ) : null} </SectionCard>
<Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap', alignItems: 'flex-start' }}> <SectionCard title={`Components (${components.length})`} sx={{ flex: '1 1 340px' }}> <Box sx={{ display: 'flex', gap: 1, mb: 1.5, flexWrap: 'wrap' }}> <TextField select size="small" label="Type" value={newType} onChange={(e) => setNewType(e.target.value)} sx={{ width: 130 }}> {(catalog.data?.component_types ?? []).map((t) => ( <MenuItem key={t} value={t}>{t}</MenuItem> ))} </TextField> <TextField size="small" label="Name" value={newName} onChange={(e) => setNewName(e.target.value)} sx={{ width: 150 }} /> <TextField size="small" label="Capacity note (e.g. 2 PB/week)" value={newNote} onChange={(e) => setNewNote(e.target.value)} sx={{ flex: 1, minWidth: 170 }} /> <Button size="small" variant="outlined" startIcon={<Plus size={14} />} onClick={addComponent}> Add </Button> </Box> {components.map((c) => ( <Box key={c.id} sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5 }}> <Chip size="small" label={c.type} sx={{ bgcolor: TYPE_COLORS[c.type] ?? '#37474f', color: '#101418', fontWeight: 700, fontSize: 10.5, width: 88 }} /> <Typography variant="body2" sx={{ flex: 1 }}> {c.name} {c.note ? ( <Typography component="span" variant="caption" sx={{ color: '#8a949e', ml: 1 }}> {c.note} </Typography> ) : null} </Typography> <IconButton size="small" onClick={() => removeComponent(c.id)}> <Trash2 size={14} /> </IconButton> </Box> ))} </SectionCard>
<SectionCard title={`Connections (${edges.length})`} sx={{ flex: '1 1 300px' }}> <Box sx={{ display: 'flex', gap: 1, mb: 1.5 }}> <TextField select size="small" label="From" value={edgeFrom} onChange={(e) => setEdgeFrom(e.target.value)} sx={{ flex: 1 }}> {components.map((c) => ( <MenuItem key={c.id} value={c.id}>{c.name}</MenuItem> ))} </TextField> <TextField select size="small" label="To" value={edgeTo} onChange={(e) => setEdgeTo(e.target.value)} sx={{ flex: 1 }}> {components.map((c) => ( <MenuItem key={c.id} value={c.id}>{c.name}</MenuItem> ))} </TextField> <Button size="small" variant="outlined" onClick={addEdge}> Connect </Button> </Box> {edges.map((e, i) => ( <Box key={i} sx={{ display: 'flex', alignItems: 'center', gap: 0.5, mb: 0.4 }}> <Typography variant="caption" sx={{ fontFamily: 'monospace', color: '#aab4be', flex: 1 }}> {nameOf(e.source)} → {nameOf(e.target)} </Typography> <IconButton size="small" onClick={() => setEdges(edges.filter((_x, j) => j !== i))}> <Trash2 size={13} /> </IconButton> </Box> ))} </SectionCard> </Box>
<SectionCard title="Rationale per key decision" help="Each decision needs written reasoning. The grader scans for capacity math and coverage of the seven design dimensions — hand-waving scores zero."> {(challenge?.key_decisions ?? []).map((d) => ( <TextField key={d} label={d} multiline minRows={2} fullWidth sx={{ mb: 1.5 }} value={rationales[d] ?? ''} onChange={(e) => setRationales({ ...rationales, [d]: e.target.value })} /> ))} <Box sx={{ display: 'flex', justifyContent: 'flex-end' }}> <Button variant="contained" onClick={submit} disabled={busy || components.length === 0}> {busy ? 'Grading…' : 'Submit for grading'} </Button> </Box> {error ? <ErrorNote error={error} /> : null} </SectionCard>
{grade ? ( <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}> <SectionCard title={ <Box component="span" sx={{ display: 'inline-flex', alignItems: 'center', gap: 1 }}> Structural checks <ScoreChip score={grade.overall_score} label="Overall" /> </Box> } sx={{ flex: '1 1 320px' }} > <Box sx={{ display: 'flex', gap: 0.75, flexWrap: 'wrap', mb: 1.5 }}> <PassChip passed={grade.structural.missing_stages.length === 0} label="required stages" /> <PassChip passed={grade.structural.orphan_components.length === 0} label="no orphans" /> <PassChip passed={!grade.structural.feedback_loop_required || grade.structural.feedback_loop_closed} label="feedback loop" /> <PassChip passed={grade.structural.single_points_of_failure.length === 0} label="no SPOF" /> <PassChip passed={grade.structural.capacity_math_found} label="capacity math" /> </Box> {grade.gaps.map((g, i) => ( <Typography key={i} variant="caption" sx={{ color: '#ef9a9a', display: 'block', mb: 0.5 }}> • {g} </Typography> ))} {grade.gaps.length === 0 ? ( <Typography variant="body2" sx={{ color: '#9ccc65' }}> No structural gaps found. </Typography> ) : null} </SectionCard>
<SectionCard title="Per-dimension scores" sx={{ flex: '1 1 340px' }}> {grade.dimension_grades.map((d) => ( <HBar key={d.dimension} label={d.dimension.replace(/_/g, ' ')} value={d.score} max={5} color={d.score >= 3 ? '#66bb6a' : d.score >= 2 ? '#f9a825' : '#ef5350'} valueLabel={`${d.score}/5`} /> ))} {grade.evidence_id ? ( <Alert severity="success" variant="outlined" sx={{ mt: 1, py: 0.25 }}> Saved to your evidence library. </Alert> ) : null} </SectionCard> </Box> ) : null} </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142/** Adaptive diagnostic: a short question set that seeds the competency matrix. */
import { 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 LinearProgress from '@mui/material/LinearProgress';import TextField from '@mui/material/TextField';import Typography from '@mui/material/Typography';import { ErrorNote, SectionCard } from '../../components/labeleval/shared';import { ScoreChip } from '../../components/hillclimb/shared';import { answerDiagnostic, startDiagnostic } from '../../services/hillclimb';import type { DiagnosticSession } from '../../types/hillclimb';import type { GoFn } from './HillClimbSection';
export default function DiagnosticView({ go }: { go: GoFn }) { const [session, setSession] = useState<DiagnosticSession | null>(null); const [answer, setAnswer] = useState(''); const [busy, setBusy] = useState(false); const [error, setError] = useState<string | null>(null);
const start = () => { setBusy(true); setError(null); startDiagnostic(Math.floor(Math.random() * 100000)) .then(setSession) .catch((e: Error) => setError(e.message)) .finally(() => setBusy(false)); };
const submit = () => { if (!session || !answer.trim()) return; setBusy(true); setError(null); answerDiagnostic(session.diagnostic_id, answer) .then((s) => { setSession(s); setAnswer(''); }) .catch((e: Error) => setError(e.message)) .finally(() => setBusy(false)); };
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, maxWidth: 900 }}> {error ? <ErrorNote error={error} /> : null}
{!session ? ( <SectionCard title="Adaptive diagnostic" help="Six short scenario questions. The sequence adapts: a weak answer drills into prerequisites, a strong answer jumps ahead. Results seed your competency matrix and set the journey to LEARNING." > <Typography variant="body2" sx={{ color: '#aab4be', mb: 2 }}> Answer six scenario questions in your own words. There is no multiple choice and no memorizable answer key — each question is generated from a parameterized template, and your answers are scored against a concept rubric with quoted evidence. </Typography> <Button variant="contained" onClick={start} disabled={busy}> Start diagnostic </Button> </SectionCard> ) : null}
{session && session.status === 'active' && session.current_question ? ( <SectionCard title={`Question ${session.answered + 1} of ${session.total_questions}`} action={ <Chip size="small" label={session.current_question.competency_id} sx={{ bgcolor: '#232a31', fontFamily: 'monospace', fontSize: 11 }} /> } > <LinearProgress variant="determinate" value={(session.answered / session.total_questions) * 100} sx={{ mb: 2, height: 5, borderRadius: 2 }} /> <Typography variant="body2" sx={{ color: '#e6e9ec', mb: 2, lineHeight: 1.65 }}> {session.current_question.scenario} </Typography> <TextField multiline minRows={5} fullWidth placeholder="Answer in your own words — mechanisms, numbers, tradeoffs…" value={answer} onChange={(e) => setAnswer(e.target.value)} disabled={busy} /> <Box sx={{ display: 'flex', justifyContent: 'flex-end', mt: 1.5, gap: 1 }}> <Button variant="contained" onClick={submit} disabled={busy || !answer.trim()}> {busy ? 'Scoring…' : 'Submit answer'} </Button> </Box> {session.results.length > 0 ? ( <Box sx={{ display: 'flex', gap: 0.75, mt: 2, flexWrap: 'wrap' }}> {session.results.map((r, i) => ( <Chip key={i} size="small" label={`${r.competency_id}: ${r.score}/5`} sx={{ bgcolor: '#1a2027', color: '#8a949e', fontSize: 10.5, height: 20 }} /> ))} </Box> ) : null} </SectionCard> ) : null}
{session && session.status === 'complete' ? ( <SectionCard title="Diagnostic complete — matrix seeded"> <Alert severity="success" variant="outlined" sx={{ mb: 2 }}> Your competency matrix has been seeded from {session.results.length} scored answers and your journey advanced to LEARNING. </Alert> <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1, mb: 2 }}> {session.results.map((r, i) => ( <Box key={i} sx={{ display: 'flex', alignItems: 'center', gap: 1 }}> <ScoreChip score={r.score} label="" /> <Typography variant="body2" sx={{ fontFamily: 'monospace', fontSize: 12 }}> {r.competency_id} </Typography> <Typography variant="caption" sx={{ color: '#8a949e' }}> {r.evaluation.weaknesses[0] ?? r.evaluation.strengths[0] ?? ''} </Typography> </Box> ))} </Box> <Box sx={{ display: 'flex', gap: 1 }}> <Button variant="contained" onClick={() => go('dashboard')}> See dashboard & next best action </Button> <Button onClick={start}>Retake (new questions)</Button> </Box> </SectionCard> ) : null} </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081/** Evidence library: every artifact backing the readiness matrix. */
import { useState } from 'react';import Box from '@mui/material/Box';import Chip from '@mui/material/Chip';import ToggleButton from '@mui/material/ToggleButton';import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';import Typography from '@mui/material/Typography';import { EmptyState, ErrorNote, LoadingBox, SectionCard } from '../../components/labeleval/shared';import { ScoreChip, useAsync } from '../../components/hillclimb/shared';import { getEvidence } from '../../services/hillclimb';
const TYPE_LABELS: Record<string, string> = { exercise_attempt: 'Exercise', star_story: 'STAR story', design_submission: 'Design lab', simulation_debrief: 'Simulation', interview_transcript: 'Interview', diagnostic: 'Diagnostic',};
export default function EvidenceView({ competencyFilter }: { competencyFilter: string | null }) { const [typeFilter, setTypeFilter] = useState<string>('all'); const evidence = useAsync(() => getEvidence(competencyFilter ?? undefined), [competencyFilter]);
if (evidence.loading && !evidence.data) return <LoadingBox label="Loading evidence…" />; if (evidence.error && !evidence.data) return <ErrorNote error={evidence.error} />;
const items = (evidence.data?.evidence ?? []).filter( (e) => typeFilter === 'all' || e.artifact_type === typeFilter );
return ( <SectionCard title={`Evidence library (${items.length})`} action={ <ToggleButtonGroup size="small" exclusive value={typeFilter} onChange={(_e, v: string | null) => v && setTypeFilter(v)}> <ToggleButton value="all">All</ToggleButton> {Object.entries(TYPE_LABELS).map(([k, v]) => ( <ToggleButton key={k} value={k}> {v} </ToggleButton> ))} </ToggleButtonGroup> } help="Every score in the platform traces back to artifacts here: exercise attempts (with quoted answer evidence), diagnosed STAR stories, graded designs, simulation debriefs, and interview transcripts." > {items.length === 0 ? ( <EmptyState title="No evidence yet" message="Evidence accumulates as you practice: run the diagnostic, submit exercises, diagnose STAR stories, grade designs, finish simulations and interviews." /> ) : ( items.map((e) => ( <Box key={e.evidence_id} sx={{ py: 1.25, borderBottom: '1px solid #232a31' }}> <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, flexWrap: 'wrap' }}> <Chip size="small" label={TYPE_LABELS[e.artifact_type] ?? e.artifact_type} sx={{ bgcolor: '#232a31', color: '#aab4be', fontSize: 10.5, height: 20 }} /> {e.score > 0 ? <ScoreChip score={Math.round(e.score)} label="" /> : null} <Typography variant="caption" sx={{ color: '#5c6873' }}> {new Date(e.timestamp).toLocaleString()} · {e.source} </Typography> </Box> <Typography variant="body2" sx={{ color: '#e6e9ec', mt: 0.5 }}> {e.summary} </Typography> {e.quotes.slice(0, 2).map((q, i) => ( <Typography key={i} variant="caption" sx={{ display: 'block', fontStyle: 'italic', color: '#8a949e' }}> “{q}” </Typography> ))} <Box sx={{ display: 'flex', gap: 0.5, mt: 0.5, flexWrap: 'wrap' }}> {e.competency_ids.map((c) => ( <Chip key={c} size="small" label={c} sx={{ bgcolor: '#1a2027', color: '#5c6873', fontFamily: 'monospace', fontSize: 10, height: 18 }} /> ))} </Box> </Box> )) )} </SectionCard> );}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091/** * Hill Climbing EM — section shell with competency-first internal navigation: * Assess → Diagnose → Practice → Apply → Evaluate → Improve (not an LMS). */
import { useCallback, useState } from 'react';import Box from '@mui/material/Box';import Tab from '@mui/material/Tab';import Tabs from '@mui/material/Tabs';import type { Exercise } from '../../types/hillclimb';import DashboardView from './DashboardView';import DiagnosticView from './DiagnosticView';import PracticeView from './PracticeView';import StarView from './StarView';import DesignLabView from './DesignLabView';import SimulationView from './SimulationView';import InterviewView from './InterviewView';import EvidenceView from './EvidenceView';import MatrixView from './MatrixView';
export type HillClimbView = | 'dashboard' | 'diagnostic' | 'practice' | 'star' | 'design' | 'simulation' | 'interview' | 'matrix' | 'evidence';
const VIEWS: { id: HillClimbView; label: string }[] = [ { id: 'dashboard', label: 'Dashboard' }, { id: 'diagnostic', label: 'Diagnostic' }, { id: 'practice', label: 'Practice' }, { id: 'star', label: 'STAR Story Box' }, { id: 'design', label: 'Design Lab' }, { id: 'simulation', label: 'Simulation' }, { id: 'interview', label: 'Interview Room' }, { id: 'matrix', label: 'Competency Matrix' }, { id: 'evidence', label: 'Evidence Library' },];
export interface GoFn { (view: HillClimbView, exercise?: Exercise | null, competencyId?: string | null): void;}
export default function HillClimbSection({ initialView }: { initialView?: string | null }) { const initial = (VIEWS.some((v) => v.id === initialView) ? initialView : 'dashboard') as HillClimbView; const [view, setView] = useState<HillClimbView>(initial); const [seedExercise, setSeedExercise] = useState<Exercise | null>(null); const [seedCompetency, setSeedCompetency] = useState<string | null>(null);
const go: GoFn = useCallback((next, exercise = null, competencyId = null) => { setSeedExercise(exercise); setSeedCompetency(competencyId); setView(next); }, []);
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> <Tabs value={view} onChange={(_e, v: HillClimbView) => go(v)} variant="scrollable" scrollButtons="auto" sx={{ minHeight: 38, borderBottom: '1px solid #232a31', '& .MuiTab-root': { minHeight: 38, py: 0.5, fontSize: 13, textTransform: 'none' }, }} > {VIEWS.map((v) => ( <Tab key={v.id} value={v.id} label={v.label} /> ))} </Tabs>
{view === 'dashboard' ? <DashboardView go={go} /> : null} {view === 'diagnostic' ? <DiagnosticView go={go} /> : null} {view === 'practice' ? ( <PracticeView go={go} seedExercise={seedExercise} seedCompetency={seedCompetency} /> ) : null} {view === 'star' ? <StarView /> : null} {view === 'design' ? <DesignLabView /> : null} {view === 'simulation' ? <SimulationView /> : null} {view === 'interview' ? <InterviewView /> : null} {view === 'matrix' ? <MatrixView go={go} /> : null} {view === 'evidence' ? <EvidenceView competencyFilter={seedCompetency} /> : null} </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175/** Interview room: chat-style adaptive session with per-answer evaluation chips. */
import { 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 TextField from '@mui/material/TextField';import ToggleButton from '@mui/material/ToggleButton';import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';import Typography from '@mui/material/Typography';import { ErrorNote, SectionCard } from '../../components/labeleval/shared';import { ScoreChip, scoreColor } from '../../components/hillclimb/shared';import { answerInterview, endInterview, startInterview } from '../../services/hillclimb';import type { InterviewSession, InterviewTurn } from '../../types/hillclimb';
const TYPE_LABEL: Record<InterviewTurn['question_type'], { label: string; color: string }> = { opening: { label: 'opening', color: '#4fc3f7' }, probe: { label: 'weakness probe', color: '#ef5350' }, depth_probe: { label: 'depth probe', color: '#ffb74d' }, escalate: { label: 'escalation', color: '#66bb6a' }, advance: { label: 'new competency', color: '#9575cd' },};
export default function InterviewView() { const [mode, setMode] = useState('hybrid'); const [session, setSession] = useState<InterviewSession | null>(null); const [answer, setAnswer] = useState(''); const [busy, setBusy] = useState(false); const [error, setError] = useState<string | null>(null);
const start = () => { setBusy(true); setError(null); startInterview(mode, Math.floor(Math.random() * 100000)) .then(setSession) .catch((e: Error) => setError(e.message)) .finally(() => setBusy(false)); };
const submit = () => { if (!session || !answer.trim()) return; setBusy(true); setError(null); answerInterview(session.session_id, answer) .then((s) => { setSession(s); setAnswer(''); }) .catch((e: Error) => setError(e.message)) .finally(() => setBusy(false)); };
const finish = () => { if (!session) return; setBusy(true); endInterview(session.session_id) .then(setSession) .catch((e: Error) => setError(e.message)) .finally(() => setBusy(false)); };
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, maxWidth: 980 }}> {error ? <ErrorNote error={error} /> : null}
{!session ? ( <SectionCard title="AI interviewer" help="No fixed question list: the next question is chosen from your last evaluation — weakness → targeted probe, strong answer → escalation or dimension switch, polished-but-shallow → depth probe. The transcript is saved as evidence." > <Typography variant="body2" sx={{ color: '#aab4be', mb: 2 }}> Pick a mode and answer in your own words. The interviewer adapts after every answer. </Typography> <Box sx={{ display: 'flex', gap: 2, alignItems: 'center' }}> <ToggleButtonGroup size="small" exclusive value={mode} onChange={(_e, v: string | null) => v && setMode(v)}> <ToggleButton value="technical">Technical</ToggleButton> <ToggleButton value="management">Management</ToggleButton> <ToggleButton value="hybrid">Hybrid EM</ToggleButton> </ToggleButtonGroup> <Button variant="contained" onClick={start} disabled={busy}> Start interview </Button> </Box> </SectionCard> ) : null}
{session ? ( <SectionCard title={`Interview (${session.mode})`} action={ session.status === 'active' ? ( <Button size="small" color="warning" onClick={finish} disabled={busy}> End & save transcript </Button> ) : ( <Chip size="small" label="transcript saved as evidence" sx={{ bgcolor: '#00695c', color: '#80cbc4' }} /> ) } > <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}> {session.turns.map((t, i) => ( <Box key={i}> <Box sx={{ bgcolor: '#12171d', border: '1px solid #232a31', borderLeft: `3px solid ${TYPE_LABEL[t.question_type].color}`, borderRadius: 1, p: 1.25, maxWidth: '85%', }} > <Typography variant="caption" sx={{ color: TYPE_LABEL[t.question_type].color, fontWeight: 700 }}> INTERVIEWER · {TYPE_LABEL[t.question_type].label} · {t.competency_id} · difficulty {t.difficulty} </Typography> <Typography variant="body2" sx={{ color: '#e6e9ec', lineHeight: 1.6 }}> {t.question} </Typography> </Box> {t.answer ? ( <Box sx={{ display: 'flex', justifyContent: 'flex-end', mt: 1 }}> <Box sx={{ bgcolor: '#1a2733', borderRadius: 1, p: 1.25, maxWidth: '85%' }}> <Typography variant="body2" sx={{ color: '#cfd8dc' }}> {t.answer} </Typography> {t.evaluation ? ( <Box sx={{ display: 'flex', gap: 0.75, mt: 1, flexWrap: 'wrap', alignItems: 'center' }}> <ScoreChip score={t.evaluation.score} /> {t.evaluation.weaknesses.slice(0, 2).map((w, j) => ( <Chip key={j} size="small" label={`gap: ${w.slice(0, 44)}`} sx={{ bgcolor: '#232a31', color: '#ffcc80', fontSize: 10, height: 18 }} /> ))} {t.evaluation.evidence.length > 0 ? ( <Chip size="small" label={`${t.evaluation.evidence.length} evidence quote(s)`} sx={{ bgcolor: '#232a31', color: scoreColor(t.evaluation.score), fontSize: 10, height: 18 }} /> ) : null} </Box> ) : null} </Box> </Box> ) : null} </Box> ))} </Box>
{session.status === 'active' ? ( <Box sx={{ mt: 2 }}> <TextField multiline minRows={3} fullWidth placeholder="Your answer…" value={answer} onChange={(e) => setAnswer(e.target.value)} disabled={busy} /> <Box sx={{ display: 'flex', justifyContent: 'flex-end', mt: 1 }}> <Button variant="contained" onClick={submit} disabled={busy || !answer.trim()}> {busy ? 'Evaluating…' : 'Answer'} </Button> </Box> </Box> ) : ( <Alert severity="success" variant="outlined" sx={{ mt: 2 }}> Interview complete. Answers were folded into your readiness matrix and the transcript stored in the evidence library. <Button size="small" sx={{ ml: 1 }} onClick={start}> New interview </Button> </Alert> )} </SectionCard> ) : null} </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151/** Competency matrix: explainable scores — click a row to see the evidence behind it. */
import { useState } from 'react';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 DialogActions from '@mui/material/DialogActions';import DialogContent from '@mui/material/DialogContent';import DialogTitle from '@mui/material/DialogTitle';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 { ErrorNote, LoadingBox, SectionCard } from '../../components/labeleval/shared';import { ReadinessChip, useAsync } from '../../components/hillclimb/shared';import { getEvidence, getReadiness } from '../../services/hillclimb';import type { EvidenceItem, ReadinessRow } from '../../types/hillclimb';import type { GoFn } from './HillClimbSection';
function fmtScore(v: number): string { return v > 0 ? v.toFixed(1) : '—';}
export default function MatrixView({ go }: { go: GoFn }) { const readiness = useAsync(getReadiness); const [selected, setSelected] = useState<ReadinessRow | null>(null); const [evidence, setEvidence] = useState<EvidenceItem[] | null>(null);
const openRow = (row: ReadinessRow) => { setSelected(row); setEvidence(null); getEvidence(row.competency_id) .then((r) => setEvidence(r.evidence)) .catch(() => setEvidence([])); };
if (readiness.loading && !readiness.data) return <LoadingBox label="Loading matrix…" />; if (readiness.error && !readiness.data) return <ErrorNote error={readiness.error} />;
const rows = readiness.data?.matrix ?? []; const bottleneckId = readiness.data?.bottleneck?.competency_id;
return ( <SectionCard title={`Competency matrix (${rows.length})`} help="Knowledge / application / evidence are tracked separately per competency and never collapsed into one number. Click a row to see the evidence behind its scores. The flagged row is your current bottleneck." > <Table size="small"> <TableHead> <TableRow> <TableCell>Competency</TableCell> <TableCell>Phase</TableCell> <TableCell>Dimension</TableCell> <TableCell align="right">Knowledge</TableCell> <TableCell align="right">Application</TableCell> <TableCell align="right">Evidence</TableCell> <TableCell>State</TableCell> </TableRow> </TableHead> <TableBody> {rows.map((r) => ( <TableRow key={r.competency_id} hover sx={{ cursor: 'pointer', bgcolor: r.competency_id === bottleneckId ? 'rgba(230,81,0,0.12)' : undefined }} onClick={() => openRow(r)} > <TableCell> <Typography variant="body2" sx={{ fontWeight: 600 }}> {r.name} {r.competency_id === bottleneckId ? ( <Chip size="small" label="BOTTLENECK" sx={{ ml: 1, height: 16, fontSize: 9, bgcolor: '#e65100', color: '#ffe0b2', fontWeight: 800 }} /> ) : null} </Typography> <Typography variant="caption" sx={{ color: '#5c6873', fontFamily: 'monospace' }}> {r.competency_id} </Typography> </TableCell> <TableCell>{r.phase}</TableCell> <TableCell> <Typography variant="caption" sx={{ color: '#8a949e' }}> {r.dimension} </Typography> </TableCell> <TableCell align="right" sx={{ fontFamily: 'monospace', fontSize: 12 }}>{fmtScore(r.knowledge_score)}</TableCell> <TableCell align="right" sx={{ fontFamily: 'monospace', fontSize: 12 }}>{fmtScore(r.application_score)}</TableCell> <TableCell align="right" sx={{ fontFamily: 'monospace', fontSize: 12 }}>{fmtScore(r.evidence_score)}</TableCell> <TableCell> <ReadinessChip state={r.readiness_state} /> </TableCell> </TableRow> ))} </TableBody> </Table>
<Dialog open={selected !== null} onClose={() => setSelected(null)} maxWidth="sm" fullWidth> <DialogTitle> {selected?.name} <Typography variant="caption" sx={{ display: 'block', color: '#8a949e', fontFamily: 'monospace' }}> {selected?.competency_id} · prerequisites: {selected?.prerequisites.join(', ') || 'none'} </Typography> </DialogTitle> <DialogContent> {selected ? ( <> <Typography variant="body2" sx={{ mb: 1.5 }}> knowledge <b>{fmtScore(selected.knowledge_score)}</b> �� application{' '} <b>{fmtScore(selected.application_score)}</b> · evidence{' '} <b>{fmtScore(selected.evidence_score)}</b> — <ReadinessChip state={selected.readiness_state} /> </Typography> <Typography variant="caption" sx={{ color: '#4fc3f7', fontWeight: 700 }}> EVIDENCE BEHIND THIS SCORE </Typography> {evidence === null ? ( <LoadingBox label="Loading evidence…" /> ) : evidence.length === 0 ? ( <Typography variant="body2" sx={{ color: '#8a949e', mt: 1 }}> No evidence yet — every score requires evidence, which is why this competency is still {selected.readiness_state.replace(/_/g, ' ')}. </Typography> ) : ( evidence.map((e) => ( <Box key={e.evidence_id} sx={{ my: 1, p: 1, bgcolor: '#12171d', borderRadius: 1, border: '1px solid #232a31' }}> <Typography variant="caption" sx={{ color: '#aab4be', fontWeight: 700 }}> {e.artifact_type.replace(/_/g, ' ')} · score {e.score}/5 · {new Date(e.timestamp).toLocaleString()} </Typography> <Typography variant="body2" sx={{ color: '#cfd8dc' }}> {e.summary} </Typography> {e.quotes.slice(0, 2).map((q, i) => ( <Typography key={i} variant="caption" sx={{ display: 'block', fontStyle: 'italic', color: '#8a949e' }}> “{q}” </Typography> ))} </Box> )) )} </> ) : null} </DialogContent> <DialogActions> <Button onClick={() => go('practice', null, selected?.competency_id ?? null)}>Practice this</Button> <Button onClick={() => setSelected(null)}>Close</Button> </DialogActions> </Dialog> </SectionCard> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232/** Practice workspace: scenario + free-text answer -> structured coaching panel. */
import { useEffect, 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 FormControlLabel from '@mui/material/FormControlLabel';import MenuItem from '@mui/material/MenuItem';import Switch from '@mui/material/Switch';import TextField from '@mui/material/TextField';import Typography from '@mui/material/Typography';import { RefreshCw } from 'lucide-react';import { ErrorNote, SectionCard } from '../../components/labeleval/shared';import { EvaluationPanel, useAsync } from '../../components/hillclimb/shared';import { generateExercise, getBlueprint, submitExercise } from '../../services/hillclimb';import type { Exercise, SubmitExerciseResponse } from '../../types/hillclimb';import type { GoFn } from './HillClimbSection';
export default function PracticeView({ go, seedExercise, seedCompetency,}: { go: GoFn; seedExercise: Exercise | null; seedCompetency: string | null;}) { const blueprint = useAsync(getBlueprint); const [competencyId, setCompetencyId] = useState<string>( seedExercise?.competency_id ?? seedCompetency ?? 'p1.regression_detection' ); const [difficulty, setDifficulty] = useState(2); const [exercise, setExercise] = useState<Exercise | null>(seedExercise); const [answer, setAnswer] = useState(''); const [result, setResult] = useState<SubmitExerciseResponse | null>(null); const [asAssessment, setAsAssessment] = useState(false); const [busy, setBusy] = useState(false); const [error, setError] = useState<string | null>(null);
const fetchExercise = (cid: string, diff: number) => { setBusy(true); setError(null); setResult(null); setAnswer(''); generateExercise(cid, diff) .then(setExercise) .catch((e: Error) => setError(e.message)) .finally(() => setBusy(false)); };
useEffect(() => { if (!seedExercise) fetchExercise(competencyId, difficulty); // eslint-disable-next-line react-hooks/exhaustive-deps }, []);
const submit = () => { if (!exercise || !answer.trim()) return; setBusy(true); setError(null); submitExercise(exercise.exercise_id, answer, asAssessment) .then(setResult) .catch((e: Error) => setError(e.message)) .finally(() => setBusy(false)); };
const continueWithFollowUp = () => { if (!result || !exercise) return; const probe = result.evaluation.follow_up_question; setExercise({ ...exercise, scenario: probe, exercise_id: exercise.exercise_id }); setAnswer(''); setResult(null); };
return ( <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap', alignItems: 'flex-start' }}> <Box sx={{ flex: '3 1 480px', display: 'flex', flexDirection: 'column', gap: 2 }}> <SectionCard title="Exercise" action={ <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}> <TextField select size="small" label="Competency" value={competencyId} onChange={(e) => { setCompetencyId(e.target.value); fetchExercise(e.target.value, difficulty); }} sx={{ minWidth: 240 }} > {(blueprint.data?.competencies ?? []).map((c) => ( <MenuItem key={c.id} value={c.id}> P{c.phase} · {c.name} </MenuItem> ))} </TextField> <TextField select size="small" label="Difficulty" value={difficulty} onChange={(e) => { const d = Number(e.target.value); setDifficulty(d); fetchExercise(competencyId, d); }} sx={{ width: 110 }} > <MenuItem value={1}>Warmup</MenuItem> <MenuItem value={2}>Core</MenuItem> <MenuItem value={3}>Stretch</MenuItem> </TextField> <Button size="small" startIcon={<RefreshCw size={14} />} onClick={() => fetchExercise(competencyId, difficulty)} disabled={busy} > New variant </Button> </Box> } help="Every regeneration produces a structurally different scenario for the same competency (seeded template variation) — repetition can't be memorized. Answers are scored on concept coverage, tradeoffs, and quantified claims; never on length." > {error ? <ErrorNote error={error} /> : null} {exercise ? ( <> <Box sx={{ display: 'flex', gap: 0.75, mb: 1.5, flexWrap: 'wrap' }}> <Chip size="small" label={exercise.competency_id} sx={{ bgcolor: '#232a31', fontFamily: 'monospace', fontSize: 11 }} /> <Chip size="small" label={`family: ${exercise.family}`} sx={{ bgcolor: '#232a31', fontSize: 11 }} /> <Chip size="small" label={exercise.template_id} sx={{ bgcolor: '#232a31', fontFamily: 'monospace', fontSize: 11 }} /> </Box> <Typography variant="body2" sx={{ color: '#e6e9ec', lineHeight: 1.7, mb: 2 }}> {exercise.scenario} </Typography> {exercise.linked_tool ? ( <Alert severity="info" variant="outlined" sx={{ mb: 2, py: 0.25 }}> {exercise.linked_tool.label} — open the{' '} <a href={`#${exercise.linked_tool.page}`} style={{ color: '#4fc3f7' }}> RCA workbench </a>{' '} to run this diagnosis against live data. </Alert> ) : null} <TextField multiline minRows={6} fullWidth placeholder="Your answer — enumerate causes, mechanisms, numbers, tradeoffs, and a verification plan…" value={answer} onChange={(e) => setAnswer(e.target.value)} disabled={busy} /> <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mt: 1.5 }}> <FormControlLabel control={ <Switch size="small" checked={asAssessment} onChange={(e) => setAsAssessment(e.target.checked)} /> } label={ <Typography variant="caption" sx={{ color: '#8a949e' }}> Submit as assessment (4+/5 passes; failing routes remediation to the diagnosed prerequisite) </Typography> } /> <Button variant="contained" onClick={submit} disabled={busy || !answer.trim()}> {busy ? 'Evaluating…' : 'Submit for coaching'} </Button> </Box> </> ) : null} </SectionCard>
{result ? ( <SectionCard title="Coaching" action={ result.evaluation.follow_up_question ? ( <Button size="small" variant="outlined" onClick={continueWithFollowUp}> Continue with follow-up </Button> ) : undefined } > <EvaluationPanel evaluation={result.evaluation} coaching={result.coaching} /> {result.evaluation.follow_up_question ? ( <Alert severity="info" variant="outlined" sx={{ mt: 2, py: 0.25 }}> <b>Follow-up:</b> {result.evaluation.follow_up_question} </Alert> ) : null} {result.journey && result.journey.state === 'REMEDIATION' ? ( <Alert severity="warning" variant="outlined" sx={{ mt: 1.5, py: 0.25 }}> Assessment failed — remediation routed to prerequisite{' '} <b>{result.journey.remediation_target}</b>.{' '} <Button size="small" onClick={() => go('practice', null, result.journey!.remediation_target)}> Practice it now </Button> </Alert> ) : null} </SectionCard> ) : null} </Box>
<Box sx={{ flex: '1 1 260px', display: 'flex', flexDirection: 'column', gap: 2 }}> {result?.readiness_for_competency ? ( <SectionCard title="Competency readiness" help="Updated after every attempt. Knowledge, application and evidence are tracked separately."> <Typography variant="caption" sx={{ color: '#8a949e', display: 'block' }}> knowledge {result.readiness_for_competency.knowledge_score.toFixed(1)} · application{' '} {result.readiness_for_competency.application_score.toFixed(1)} · evidence{' '} {result.readiness_for_competency.evidence_score.toFixed(1)} </Typography> <Chip size="small" label={result.readiness_for_competency.readiness_state.replace(/_/g, ' ')} sx={{ mt: 1, bgcolor: '#232a31', color: '#aab4be', fontWeight: 700 }} /> </SectionCard> ) : null} {exercise ? ( <SectionCard title="Common failure modes" help="How answers to this exercise family typically go wrong."> {exercise.common_failure_modes.map((f, i) => ( <Typography key={i} variant="caption" sx={{ color: '#8a949e', display: 'block', mb: 0.75 }}> • {f} </Typography> ))} </SectionCard> ) : null} </Box> </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247/** Hill-climbing simulation: state gauges, hypothesis input, intervention picker, event log, debrief. */
import { useState } from 'react';import Alert from '@mui/material/Alert';import Box from '@mui/material/Box';import Button from '@mui/material/Button';import Checkbox from '@mui/material/Checkbox';import Chip from '@mui/material/Chip';import FormControlLabel from '@mui/material/FormControlLabel';import MenuItem from '@mui/material/MenuItem';import TextField from '@mui/material/TextField';import Typography from '@mui/material/Typography';import { ErrorNote, HBar, LoadingBox, SectionCard } from '../../components/labeleval/shared';import { useAsync } from '../../components/hillclimb/shared';import { getSimulationCatalog, startSimulation, stepSimulation } from '../../services/hillclimb';import type { SimulationState } from '../../types/hillclimb';
function metricColor(name: string, value: number, inverted: string[]): string { const effective = inverted.includes(name) ? 100 - value : value; if (effective >= 60) return '#66bb6a'; if (effective >= 40) return '#f9a825'; return '#ef5350';}
export default function SimulationView() { const catalog = useAsync(getSimulationCatalog); const [sim, setSim] = useState<SimulationState | null>(null); const [hypothesis, setHypothesis] = useState(''); const [interventionId, setInterventionId] = useState('add_monitoring'); const [revert, setRevert] = useState(false); const [busy, setBusy] = useState(false); const [error, setError] = useState<string | null>(null);
const start = () => { setBusy(true); setError(null); startSimulation(Math.floor(Math.random() * 100000), 8) .then(setSim) .catch((e: Error) => setError(e.message)) .finally(() => setBusy(false)); };
const step = () => { if (!sim || !hypothesis.trim()) return; setBusy(true); setError(null); stepSimulation(sim.sim_id, hypothesis, interventionId, revert) .then((s) => { setSim(s); setHypothesis(''); setRevert(false); }) .catch((e: Error) => setError(e.message)) .finally(() => setBusy(false)); };
if (catalog.loading && !catalog.data) return <LoadingBox label="Loading scenario…" />; if (catalog.error && !catalog.data) return <ErrorNote error={catalog.error} />;
const inverted = catalog.data?.inverted_metrics ?? []; const interventions = catalog.data?.interventions ?? []; const scenario = catalog.data?.scenarios[0]; const lastTurn = sim?.history[sim.history.length - 1] ?? null;
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> {error ? <ErrorNote error={error} /> : null}
{!sim ? ( <SectionCard title={scenario?.title ?? 'Scenario'} help="A stateful multi-objective exercise: each turn you write a falsifiable hypothesis, pick one intervention, measure the seeded (deterministic per seed) effect, and keep or reject. Safety has a hard floor — breach it and an incident fires."> <Typography variant="body2" sx={{ color: '#e6e9ec', lineHeight: 1.7, mb: 2 }}> {scenario?.narrative} </Typography> <Button variant="contained" onClick={start} disabled={busy}> Take over the team (8 turns) </Button> </SectionCard> ) : null}
{sim ? ( <> <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, flexWrap: 'wrap' }}> <Chip size="small" label={`turn ${sim.turn}/${sim.max_turns}`} sx={{ bgcolor: '#0d47a1', color: '#90caf9', fontWeight: 700 }} /> <Chip size="small" label={`balanced objective ${sim.objective_history[sim.objective_history.length - 1].toFixed(1)}`} sx={{ bgcolor: '#232a31', color: '#e6e9ec', fontFamily: 'monospace' }} /> {lastTurn ? ( <Chip size="small" label={`Δ ${lastTurn.objective_delta >= 0 ? '+' : ''}${lastTurn.objective_delta.toFixed(1)} → ${ lastTurn.verdict === 'keep_recommended' ? 'KEEP' : 'REJECT' }`} sx={{ bgcolor: lastTurn.objective_delta >= 0 ? '#1b5e20' : '#5d1414', color: lastTurn.objective_delta >= 0 ? '#a5d6a7' : '#ffcdd2', fontWeight: 700, }} /> ) : null} {sim.status === 'complete' ? ( <Chip size="small" label="COMPLETE — see debrief below" sx={{ bgcolor: '#00695c', color: '#80cbc4', fontWeight: 700 }} /> ) : null} </Box>
<Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap', alignItems: 'flex-start' }}> <SectionCard title="Competing objectives" help="All ten metrics matter; cost and risk are inverted (lower is better). Safety below the hard floor triggers an incident with second-order damage." sx={{ flex: '1 1 360px' }} > {(catalog.data?.metrics ?? []).map((m) => ( <HBar key={m} label={`${m.replace(/_/g, ' ')}${inverted.includes(m) ? ' (lower=better)' : ''}`} value={sim.metrics[m] ?? 0} max={100} color={metricColor(m, sim.metrics[m] ?? 0, inverted)} valueLabel={(sim.metrics[m] ?? 0).toFixed(0)} /> ))} </SectionCard>
<Box sx={{ flex: '1 1 380px', display: 'flex', flexDirection: 'column', gap: 2 }}> {sim.status === 'active' ? ( <SectionCard title={`Turn ${sim.turn + 1}: hypothesis → intervention`}> <TextField label="Hypothesis (falsifiable: metric + direction + magnitude)" placeholder="e.g. 'Adding monitoring will raise safety by ~5 within 2 turns'" multiline minRows={2} fullWidth value={hypothesis} onChange={(e) => setHypothesis(e.target.value)} sx={{ mb: 1.5 }} /> <TextField select fullWidth size="small" label="Intervention" value={interventionId} onChange={(e) => setInterventionId(e.target.value)} sx={{ mb: 1 }} > {interventions.map((i) => ( <MenuItem key={i.id} value={i.id}> {i.label} </MenuItem> ))} </TextField> <Typography variant="caption" sx={{ color: '#8a949e', display: 'block', mb: 1 }}> {interventions.find((i) => i.id === interventionId)?.description}{' '} <i>{interventions.find((i) => i.id === interventionId)?.second_order}</i> </Typography> {sim.history.length > 0 ? ( <FormControlLabel control={<Checkbox size="small" checked={revert} onChange={(e) => setRevert(e.target.checked)} />} label={ <Typography variant="caption" sx={{ color: '#ffb74d' }}> Reject previous intervention first (roll back its immediate effects) </Typography> } /> ) : null} <Box sx={{ display: 'flex', justifyContent: 'flex-end' }}> <Button variant="contained" onClick={step} disabled={busy || !hypothesis.trim()}> {busy ? 'Measuring…' : 'Intervene & measure'} </Button> </Box> </SectionCard> ) : null}
<SectionCard title="Event log" sx={{ maxHeight: 420, overflowY: 'auto' }}> {sim.history.length === 0 ? ( <Typography variant="body2" sx={{ color: '#8a949e' }}> No turns yet. </Typography> ) : null} {[...sim.history].reverse().map((t) => ( <Box key={t.turn} sx={{ mb: 1.5, pb: 1, borderBottom: '1px solid #232a31' }}> <Typography variant="caption" sx={{ color: '#4fc3f7', fontWeight: 700 }}> TURN {t.turn} · {t.intervention_id} · Δobj {t.objective_delta >= 0 ? '+' : ''} {t.objective_delta.toFixed(1)} {' '} <Chip size="small" label={`hypothesis: ${t.hypothesis_assessment.quality}`} sx={{ height: 16, fontSize: 9.5, ml: 0.5, bgcolor: t.hypothesis_assessment.quality === 'strong' ? '#1b5e20' : t.hypothesis_assessment.quality === 'directional' ? '#f9a825' : '#5d1414', color: t.hypothesis_assessment.quality === 'directional' ? '#212121' : '#e6e9ec', }} /> </Typography> <Typography variant="caption" sx={{ color: '#aab4be', display: 'block', fontStyle: 'italic' }}> “{t.hypothesis}” </Typography> {t.delayed_landed.map((d, i) => ( <Typography key={i} variant="caption" sx={{ color: '#9ccc65', display: 'block' }}> ⏲ {d} </Typography> ))} {t.events.map((e, i) => ( <Typography key={i} variant="caption" sx={{ color: '#ef9a9a', display: 'block' }}> ⚠ {e} </Typography> ))} </Box> ))} </SectionCard> </Box> </Box>
{sim.debrief ? ( <SectionCard title="Debrief — decisions mapped to competency evidence"> <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap', mb: 1.5 }}> <Chip size="small" label={`objective ${sim.debrief.objective_start} → ${sim.debrief.objective_end} (${sim.debrief.objective_delta >= 0 ? '+' : ''}${sim.debrief.objective_delta})`} sx={{ bgcolor: '#232a31', fontFamily: 'monospace' }} /> <Chip size="small" label={`${sim.debrief.incidents} incident(s)`} sx={{ bgcolor: sim.debrief.incidents ? '#5d1414' : '#1b5e20', color: sim.debrief.incidents ? '#ffcdd2' : '#a5d6a7' }} /> <Chip size="small" label={sim.debrief.balanced_finish ? 'balanced finish' : 'unbalanced finish'} sx={{ bgcolor: sim.debrief.balanced_finish ? '#1b5e20' : '#e65100', color: '#e6e9ec' }} /> </Box> {sim.debrief.competency_mappings.map((m) => ( <Alert key={m.competency_id} severity={m.verdict === 'evidenced' ? 'success' : 'warning'} variant="outlined" sx={{ mb: 1, py: 0.25 }} > <b>{m.competency_id}</b> — {m.reason} {m.quotes.map((q, i) => ( <Typography key={i} variant="caption" sx={{ display: 'block', fontStyle: 'italic', color: '#aab4be' }}> “{q}” </Typography> ))} </Alert> ))} <Button size="small" onClick={start}> Run again (new seed) </Button> </SectionCard> ) : null} </> ) : null} </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178/** STAR Story Box: paste a raw story -> diagnosed S/T/A/R with claim-vs-evidence flags. */
import { 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 FormControlLabel from '@mui/material/FormControlLabel';import Switch from '@mui/material/Switch';import TextField from '@mui/material/TextField';import Typography from '@mui/material/Typography';import { ErrorNote, SectionCard } from '../../components/labeleval/shared';import { PassChip, ScoreChip } from '../../components/hillclimb/shared';import { diagnoseStar } from '../../services/hillclimb';import type { StarDiagnosis } from '../../types/hillclimb';
const COMPONENT_COLORS: Record<string, string> = { S: '#4fc3f7', T: '#9575cd', A: '#ffb74d', R: '#66bb6a',};
export default function StarView() { const [text, setText] = useState(''); const [saveEvidence, setSaveEvidence] = useState(true); const [diagnosis, setDiagnosis] = useState<StarDiagnosis | null>(null); const [busy, setBusy] = useState(false); const [error, setError] = useState<string | null>(null);
const run = () => { if (!text.trim()) return; setBusy(true); setError(null); diagnoseStar(text, saveEvidence) .then(setDiagnosis) .catch((e: Error) => setError(e.message)) .finally(() => setBusy(false)); };
return ( <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> <SectionCard title="Your story, unstructured" help="Paste a real experience in any shape. The diagnoser (not a rewriter) segments it into Situation/Task/Action/Result, runs per-component checks, flags unquantified claims vs measurable evidence, and maps the story to the Phase-3 leadership competencies it actually evidences." > {error ? <ErrorNote error={error} /> : null} <TextField multiline minRows={6} fullWidth placeholder="e.g. 'When I joined, the team of 12 was missing every release date. I was asked to… I decided to… As a result, deploy failures dropped from 14% to 3%…'" value={text} onChange={(e) => setText(e.target.value)} disabled={busy} /> <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mt: 1.5 }}> <FormControlLabel control={<Switch size="small" checked={saveEvidence} onChange={(e) => setSaveEvidence(e.target.checked)} />} label={ <Typography variant="caption" sx={{ color: '#8a949e' }}> Save to evidence library on diagnose </Typography> } /> <Button variant="contained" onClick={run} disabled={busy || !text.trim()}> {busy ? 'Diagnosing…' : 'Diagnose story'} </Button> </Box> </SectionCard>
{diagnosis ? ( <> <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, flexWrap: 'wrap' }}> <ScoreChip score={diagnosis.overall_score} label="Story" /> {diagnosis.checks.map((c) => ( <PassChip key={c.check} passed={c.passed} label={c.label} /> ))} {diagnosis.evidence_id ? ( <Chip size="small" label="saved to evidence" sx={{ bgcolor: '#00695c', color: '#80cbc4', fontSize: 11 }} /> ) : null} </Box>
<Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}> {diagnosis.components.map((comp) => ( <SectionCard key={comp.component} title={ <Box component="span" sx={{ color: COMPONENT_COLORS[comp.component] }}> {comp.component} — {comp.label} </Box> } sx={{ flex: '1 1 260px', borderTop: `2px solid ${COMPONENT_COLORS[comp.component]}` }} > {comp.present ? ( comp.sentences.map((s, i) => ( <Typography key={i} variant="body2" sx={{ color: '#cfd8dc', mb: 0.5 }}> {s} </Typography> )) ) : ( <Typography variant="body2" sx={{ color: '#ef9a9a' }}> {comp.issues[0] ?? 'Not detected.'} </Typography> )} </SectionCard> ))} </Box>
<Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}> <SectionCard title="Claim vs evidence" help="Unquantified claims ('improved performance') are flagged; claims backed by numbers / before-after / named mechanisms count as measurable evidence. Unquantified claims cap the story score at 3." sx={{ flex: '2 1 380px' }} > {diagnosis.claim_flags.length === 0 ? ( <Typography variant="body2" sx={{ color: '#8a949e' }}> No outcome claims detected — a strong story should claim a measurable result. </Typography> ) : ( diagnosis.claim_flags.map((f, i) => ( <Alert key={i} severity={f.kind === 'measurable_evidence' ? 'success' : 'warning'} variant="outlined" sx={{ mb: 1, py: 0.25 }} > <Typography variant="caption" sx={{ display: 'block', fontStyle: 'italic' }}> “{f.sentence}” </Typography> <Typography variant="caption">{f.detail}</Typography> </Alert> )) )} </SectionCard>
<SectionCard title="Competencies evidenced" help="Phase-3 leadership competencies this story can serve as evidence for, with the matched cues." sx={{ flex: '1 1 280px' }} > {diagnosis.competencies.length === 0 ? ( <Typography variant="body2" sx={{ color: '#8a949e' }}> None detected yet — anchor the story to a leadership behavior. </Typography> ) : ( diagnosis.competencies.map((c) => ( <Box key={c.competency_id} sx={{ mb: 1 }}> <Chip size="small" label={c.competency_id} sx={{ bgcolor: '#232a31', fontFamily: 'monospace', fontSize: 11 }} /> <Typography variant="caption" sx={{ color: '#8a949e', display: 'block' }}> {c.reason} </Typography> </Box> )) )} {diagnosis.coaching.length > 0 ? ( <> <Typography variant="caption" sx={{ color: '#4fc3f7', fontWeight: 700, display: 'block', mt: 1 }}> STRENGTHEN </Typography> {diagnosis.coaching.map((c, i) => ( <Typography key={i} variant="caption" sx={{ color: '#aab4be', display: 'block', mb: 0.5 }}> • {c} </Typography> ))} </> ) : null} </SectionCard> </Box> </> ) : null} </Box> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139/** Typed fetch wrappers for the Hill Climbing EM API (/api/hillclimb). */
import type { Blueprint, DesignChallenge, DesignComponent, DesignEdge, DesignGrade, DiagnosticSession, EvidenceListResponse, Exercise, GraphResponse, InterviewSession, Journey, NextBestAction, ReadinessResponse, SimulationCatalog, SimulationState, StarDiagnosis, SubmitExerciseResponse, UserProfile,} from '../types/hillclimb';
const BASE = '/api/hillclimb';const JSON_HEADERS = { 'Content-Type': 'application/json' };
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>;}
function get<T>(url: string): Promise<T> { return fetch(`${BASE}${url}`).then((res) => handle<T>(res));}
function post<T>(url: string, body?: unknown): Promise<T> { return fetch(`${BASE}${url}`, { method: 'POST', headers: JSON_HEADERS, body: body === undefined ? undefined : JSON.stringify(body), }).then((res) => handle<T>(res));}
function put<T>(url: string, body: unknown): Promise<T> { return fetch(`${BASE}${url}`, { method: 'PUT', headers: JSON_HEADERS, body: JSON.stringify(body), }).then((res) => handle<T>(res));}
// ------------------------------------------------------------------- profile
export const getProfile = () => get<UserProfile>('/profile');export const saveProfile = (p: UserProfile) => put<UserProfile>('/profile', p);
// ----------------------------------------------------------------- blueprint
export const getBlueprint = () => get<Blueprint>('/blueprint');export const getGraph = () => get<GraphResponse>('/graph');
// ---------------------------------------------------------------- diagnostic
export const startDiagnostic = (seed = 11) => post<DiagnosticSession>('/diagnostic/start', { seed });export const answerDiagnostic = (diagnosticId: string, answer: string) => post<DiagnosticSession>(`/diagnostic/${encodeURIComponent(diagnosticId)}/answer`, { answer });
// ----------------------------------------------------------------- exercises
export const generateExercise = (competencyId: string, difficulty = 2, seed?: number) => post<Exercise>('/exercise/generate', { competency_id: competencyId, difficulty, seed });export const submitExercise = (exerciseId: string, answer: string, asAssessment = false) => post<SubmitExerciseResponse>('/exercise/submit', { exercise_id: exerciseId, answer, as_assessment: asAssessment, });
// ---------------------------------------------------------------------- STAR
export const diagnoseStar = (text: string, saveEvidence: boolean) => post<StarDiagnosis>('/star/diagnose', { text, save_evidence: saveEvidence });
// ----------------------------------------------------------------- design lab
export const getDesignChallenges = () => get<{ challenges: DesignChallenge[]; component_types: string[] }>('/design/challenges');export const submitDesign = ( challengeId: string, components: DesignComponent[], edges: DesignEdge[], rationales: Record<string, string>) => post<DesignGrade>('/design/submit', { challenge_id: challengeId, components, edges, rationales, });
// ----------------------------------------------------------------- simulation
export const getSimulationCatalog = () => get<SimulationCatalog>('/simulation/catalog');export const startSimulation = (seed = 42, maxTurns = 8) => post<SimulationState>('/simulation/start', { seed, max_turns: maxTurns });export const stepSimulation = ( simId: string, hypothesis: string, interventionId: string, revertPrevious = false) => post<SimulationState>(`/simulation/${encodeURIComponent(simId)}/step`, { hypothesis, intervention_id: interventionId, revert_previous: revertPrevious, });
// ------------------------------------------------------------------ interview
export const startInterview = (mode: string, seed?: number) => post<InterviewSession>('/interview/start', seed === undefined ? { mode } : { mode, seed });export const answerInterview = (sessionId: string, answer: string) => post<InterviewSession>(`/interview/${encodeURIComponent(sessionId)}/answer`, { answer });export const endInterview = (sessionId: string) => post<InterviewSession>(`/interview/${encodeURIComponent(sessionId)}/end`);
// ----------------------------------------------------- evidence / readiness
export const getEvidence = (competencyId?: string) => get<EvidenceListResponse>( competencyId ? `/evidence?competency_id=${encodeURIComponent(competencyId)}` : '/evidence' );export const getReadiness = () => get<ReadinessResponse>('/readiness');export const getNextAction = () => get<NextBestAction>('/next-action');export const getJourney = () => get<Journey>('/journey');123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424/** Types for the Hill Climbing EM API (/api/hillclimb). */
export type Dimension = 'Knowledge' | 'Technical Reasoning' | 'Leadership' | 'Execution';
export type ReadinessStateId = | 'NOT_STARTED' | 'LEARNING' | 'PRACTICING' | 'NEEDS_REVIEW' | 'COMPETENT' | 'STRONG' | 'INTERVIEW_READY';
export type JourneyStateId = | 'NOT_STARTED' | 'DIAGNOSTIC' | 'LEARNING' | 'PRACTICE' | 'ASSESSMENT' | 'REMEDIATION' | 'REASSESS';
export interface UserProfile { user_id: string; name: string; target_role: string; experience_years: number; focus_note: string; created_at: string; updated_at: string;}
// ------------------------------------------------------------------ blueprint
export interface Competency { id: string; name: string; phase: number; dimension: Dimension; description: string; prerequisites: string[]; topics: string[];}
export interface PhaseSpec { phase: number; title: string; objective: string; topics: string[]; skills: string[]; exercises: string[]; assessments: string[]; completion_criteria: string[];}
export interface Blueprint { version: number; source: string; note: string; phases: PhaseSpec[]; competencies: Competency[];}
export interface GraphResponse { nodes: Competency[]; edges: { source: string; target: string }[]; problems: string[];}
// ----------------------------------------------------------------- evaluation
export interface EvaluationResult { competency: string; score: number; confidence: number; evidence: string[]; strengths: string[]; weaknesses: string[]; missing_evidence: string[]; misconceptions: string[]; recommended_action: string; follow_up_question: string; evaluator: string;}
export interface RubricItem { criterion: string; check: string; keywords: string[]; weight: number;}
export interface LinkedTool { label: string; page: string; api: string;}
export interface Exercise { exercise_id: string; competency_id: string; difficulty: number; prerequisites: string[]; scenario: string; expected_reasoning: string[]; evaluation_rubric: RubricItem[]; common_failure_modes: string[]; follow_up_questions: string[]; template_id: string; seed: number; family: string; linked_tool: LinkedTool | null;}
export interface CompetencyReadiness { competency_id: string; knowledge_score: number; application_score: number; evidence_score: number; readiness_state: ReadinessStateId; evidence_ids: string[]; last_updated: string;}
export interface SubmitExerciseResponse { evaluation: EvaluationResult; coaching: string; attempt_id: string; evidence_id: string; linked_tool: LinkedTool | null; readiness_for_competency: CompetencyReadiness | null; journey: Journey | null;}
// ------------------------------------------------------------------ diagnostic
export interface DiagnosticQuestion { exercise_id: string; competency_id: string; scenario: string;}
export interface DiagnosticSession { diagnostic_id: string; user_id: string; seed: number; total_questions: number; answered: number; status: 'active' | 'complete'; current_exercise_id: string | null; current_competency: string | null; asked: string[]; results: { competency_id: string; score: number; evaluation: EvaluationResult }[]; current_question?: DiagnosticQuestion;}
// ------------------------------------------------------------------------ STAR
export interface StarComponent { component: 'S' | 'T' | 'A' | 'R'; label: string; sentences: string[]; present: boolean; issues: string[]; strengths: string[];}
export interface ClaimFlag { sentence: string; kind: 'unquantified_claim' | 'measurable_evidence'; detail: string;}
export interface StarCheck { check: string; label: string; passed: boolean; detail: string; evidence: string | null;}
export interface StarDiagnosis { components: StarComponent[]; checks: StarCheck[]; claim_flags: ClaimFlag[]; competencies: { competency_id: string; matched_cues: string[]; reason: string }[]; overall_score: number; coaching: string[]; evidence_id: string | null;}
// ------------------------------------------------------------------ design lab
export interface DesignChallenge { challenge_id: string; title: string; brief: string; required_stages: string[][]; key_decisions: string[]; competency_ids: string[]; requires_feedback_loop: boolean;}
export interface DesignComponent { id: string; type: string; name: string; note: string;}
export interface DesignEdge { source: string; target: string;}
export interface StructuralChecks { missing_stages: string[]; orphan_components: string[]; feedback_loop_closed: boolean; feedback_loop_required: boolean; single_points_of_failure: string[]; capacity_math_found: boolean; capacity_quotes: string[];}
export interface DimensionGrade { dimension: string; score: number; gaps: string[]; evidence: string[];}
export interface DesignGrade { grade_id: string; challenge_id: string; structural: StructuralChecks; dimension_grades: DimensionGrade[]; overall_score: number; gaps: string[]; evidence_id: string | null;}
// ------------------------------------------------------------------ simulation
export interface InterventionSpec { id: string; label: string; description: string; immediate: Record<string, number>; delayed: { delay: number; effects: Record<string, number>; note?: string }[]; second_order: string;}
export interface SimulationCatalog { scenarios: { scenario_id: string; title: string; narrative: string }[]; interventions: InterventionSpec[]; metrics: string[]; inverted_metrics: string[]; safety_floor: number; morale_floor: number;}
export interface SimTurnRecord { turn: number; hypothesis: string; hypothesis_assessment: { mentions_metrics: string[]; targets_intervention_effects: boolean; directional: boolean; falsifiable: boolean; quality: string; }; intervention_id: string; reverted_previous: boolean; applied_effects: Record<string, number>; delayed_landed: string[]; events: string[]; metrics_after: Record<string, number>; objective_after: number; objective_delta: number; verdict: string; timestamp: string;}
export interface SimCompetencyMapping { competency_id: string; verdict: 'evidenced' | 'gap'; reason: string; quotes: string[]; evidence_id?: string;}
export interface SimDebrief { objective_start: number; objective_end: number; objective_delta: number; incidents: number; turns: number; balanced_finish: boolean; competency_mappings: SimCompetencyMapping[];}
export interface SimulationState { sim_id: string; user_id: string; scenario_id: string; seed: number; max_turns: number; turn: number; status: 'active' | 'complete'; metrics: Record<string, number>; pending: { due_turn: number; effects: Record<string, number>; note: string }[]; history: SimTurnRecord[]; events: { turn: number; type: string; detail: string }[]; objective_history: number[]; debrief: SimDebrief | null;}
// -------------------------------------------------------------------- interview
export interface InterviewTurn { index: number; question: string; question_type: 'opening' | 'probe' | 'depth_probe' | 'escalate' | 'advance'; competency_id: string; exercise_id: string; difficulty: number; answer: string | null; evaluation: EvaluationResult | null; timestamp: string;}
export interface InterviewSession { session_id: string; user_id: string; mode: 'technical' | 'management' | 'hybrid'; seed: number; status: 'active' | 'complete'; turns: InterviewTurn[]; asked_competencies: string[]; probe_count_on_current: number; evidence_id: string | null;}
// -------------------------------------------------------- evidence / readiness
export interface EvidenceItem { evidence_id: string; user_id: string; competency_ids: string[]; artifact_type: string; source: string; summary: string; quotes: string[]; score: number; confidence: number; timestamp: string; payload: Record<string, unknown>;}
export interface EvidenceListResponse { evidence: EvidenceItem[]; count: number;}
export interface ReadinessRow extends CompetencyReadiness { name: string; phase: number; dimension: Dimension; prerequisites: string[];}
export interface DimensionSummary { dimension: string; avg_score: number; coverage: number; competent: number; total: number;}
export interface Bottleneck { competency_id: string; name: string; phase: number; dimension: Dimension; readiness: CompetencyReadiness; blocked_competencies: string[]; blocked_count: number; explanation: string;}
export interface ReadinessResponse { matrix: ReadinessRow[]; dimensions: DimensionSummary[]; bottleneck: Bottleneck | null;}
export interface NextBestAction { bottleneck: Bottleneck | null; explanation: string; concept: { competency_id: string; name: string; study: string[]; description: string; phase_objective: string; }; exercise: Exercise; assessment: { competency_id: string; kind: string; description: string; };}
export interface Journey { user_id: string; state: JourneyStateId; current_phase: number; current_competency: string | null; remediation_target: string | null; history: Record<string, unknown>[]; updated_at: string;}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import pytest
from sensorflow.hillclimb.models import reset_store
@pytest.fixture(autouse=True)def isolated_store(tmp_path, monkeypatch): """Every test runs against a fresh store and with the LLM disabled, so the deterministic rule-based paths are what is under test.""" monkeypatch.setenv("HILLCLIMB_DISABLE_LLM", "1") store = reset_store(tmp_path / "hillclimb") yield store reset_store(tmp_path / "hillclimb-teardown")
# ---------------------------------------------------------- shared answer text
# Covers nearly every rubric criterion of the offline/shadow exercise family,# with quantified claims and explicit tradeoffs.STRONG_TECH_ANSWER = ( "First I would check for a metric definition mismatch: offline eval and shadow monitoring may " "use a different IoU threshold or matching threshold, so the two numbers are not the same metric. " "Second, distribution shift: live traffic differs from the eval set, so the population changed. " "Third, sampling bias in how the eval set was built — it may not be representative. " "Fourth, training-serving skew: the feature pipeline can produce a feature mismatch at serving time. " "Fifth, a serving mismatch: preprocessing or quantization differences in the inference stack. " "I would also test statistical significance — the shadow delta may be noise, so I would compute a " "95% confidence interval given the sample size. A true regression remains possible, so I would " "slice metrics by scenario, run a matched A/B experiment, and re-score identical frames in both stacks. " "The tradeoff: this delays launch by 3 days, at the cost of schedule, but avoids shipping a " "genuinely worse model.")
# Long, polished-sounding, but covers no rubric concept and has no numbers.VERBOSE_WAFFLE = ( "This is truly an interesting and important challenge, and in situations like this one it is " "essential to take a holistic, thoughtful, and collaborative approach that considers the " "perspectives of all involved parties. I believe the most valuable thing a leader can do is to " "bring people together, encourage open communication, and ensure that everyone feels heard and " "aligned around a shared vision of success. It is also important to remember that great teams " "are built on trust, and trust is built through consistency, empathy, and transparency. " "I would begin by gathering the relevant people in a room and facilitating a constructive " "discussion about the situation, its causes, and the potential paths forward, always keeping an " "open mind and remaining flexible as new information emerges. Ultimately, what matters most is " "that we move forward together with confidence, clarity, and a renewed sense of purpose, and " "that we continue to learn and grow as an organization through every challenge we encounter. " "By staying positive, communicating openly, and supporting one another, I am confident that " "we will arrive at a good outcome for the business, for the team, and for our users, and that " "this challenge will make us stronger as a group going forward.")
CONCISE_PRECISE_ANSWER = ( "Likely causes: a metric definition mismatch between the two pipelines, distribution shift " "between eval data and live traffic, or sampling bias in the eval set. Before reacting I would " "check statistical significance of the shadow delta.")
STRONG_LEADERSHIP_ANSWER = ( "When our launch slipped I decided to pause the feature work. Instead of quietly absorbing the " "risk, I considered delaying the launch or cutting scope, and rejected the delay because it " "punished the wrong team. I held a 1:1 with the tech lead, gave direct feedback, and aligned " "the stakeholders on the new plan. We agreed to measure the result weekly, and the outcome was " "a 30% drop in escaped regressions within 2 months. The tradeoff: we gave up one roadmap item " "at the cost of short-term velocity.")
WEAK_ANSWER = "Honestly not sure. Probably fine either way."1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950"""Diagnostic flow adaptivity and next-best-action shape."""
from sensorflow.hillclimb import adaptivefrom sensorflow.hillclimb.blueprint import competency_index, load_blueprint
from .conftest import STRONG_TECH_ANSWER, WEAK_ANSWER
def test_diagnostic_seeds_matrix_and_completes(isolated_store): dx = adaptive.start_diagnostic(store=isolated_store) assert dx.status == "active" and dx.current_exercise_id answers = [WEAK_ANSWER, STRONG_TECH_ANSWER, WEAK_ANSWER, STRONG_TECH_ANSWER, WEAK_ANSWER, WEAK_ANSWER] for a in answers: dx = adaptive.answer_diagnostic(dx.diagnostic_id, a, use_llm=False, store=isolated_store) assert dx.status == "complete" assert dx.answered == 6 # attempts recorded -> matrix seeded attempts = isolated_store.all("attempts") assert len(attempts) == 6 assert all(a["kind"] == "diagnostic" for a in attempts) # journey advanced past diagnostic j = adaptive.get_journey(store=isolated_store) assert j.state.value == "LEARNING"
def test_diagnostic_adapts_weak_answer_drills_into_prerequisites(isolated_store): idx = competency_index(load_blueprint(isolated_store)) dx = adaptive.start_diagnostic(store=isolated_store) first = dx.current_competency dx = adaptive.answer_diagnostic(dx.diagnostic_id, WEAK_ANSWER, use_llm=False, store=isolated_store) second = dx.current_competency prereqs = idx[first].prerequisites if prereqs: # weak answer -> drill into a prerequisite assert second in prereqs else: # no prereqs -> continue the starter set assert second != first
def test_next_best_action_returns_exactly_one_of_each(isolated_store): nba = adaptive.next_best_action(store=isolated_store) assert set(nba) >= {"concept", "exercise", "assessment", "explanation", "bottleneck"} assert isinstance(nba["concept"], dict) and nba["concept"]["competency_id"] assert isinstance(nba["exercise"], dict) and nba["exercise"]["scenario"] assert isinstance(nba["assessment"], dict) and nba["assessment"]["description"] # all three target the same bottleneck competency target = nba["concept"]["competency_id"] assert nba["exercise"]["competency_id"] == target assert nba["assessment"]["competency_id"] == target123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142"""End-to-end API lifecycle through the FastAPI router (in-process TestClient)."""
import pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient
from sensorflow.hillclimb.api import router
from .conftest import STRONG_LEADERSHIP_ANSWER, STRONG_TECH_ANSWER, WEAK_ANSWER
@pytest.fixture()def client(isolated_store): app = FastAPI() app.include_router(router) return TestClient(app)
def test_full_lifecycle(client): # profile p = client.get("/api/hillclimb/profile").json() assert p["user_id"] == "default" p["target_role"] = "EM, ML Infrastructure" assert client.put("/api/hillclimb/profile", json=p).json()["target_role"] == "EM, ML Infrastructure"
# blueprint + graph bp = client.get("/api/hillclimb/blueprint").json() assert bp["source"] == "reconstructed-from-spec" assert len(bp["phases"]) == 4 graph = client.get("/api/hillclimb/graph").json() assert graph["problems"] == [] assert len(graph["nodes"]) >= 30 and graph["edges"]
# journey starts NOT_STARTED assert client.get("/api/hillclimb/journey").json()["state"] == "NOT_STARTED"
# diagnostic dx = client.post("/api/hillclimb/diagnostic/start", json={"seed": 11}).json() assert dx["current_question"]["scenario"] for _ in range(6): dx = client.post(f"/api/hillclimb/diagnostic/{dx['diagnostic_id']}/answer", json={"answer": STRONG_TECH_ANSWER}).json() assert dx["status"] == "complete" assert client.get("/api/hillclimb/journey").json()["state"] == "LEARNING"
# exercise generate + submit -> coached, evidence-backed evaluation ex = client.post("/api/hillclimb/exercise/generate", json={"competency_id": "p1.regression_detection", "seed": 77}).json() sub = client.post("/api/hillclimb/exercise/submit", json={"exercise_id": ex["exercise_id"], "answer": STRONG_TECH_ANSWER}).json() assert sub["evaluation"]["score"] >= 4 assert sub["evaluation"]["evidence"] assert sub["coaching"] assert sub["linked_tool"]["api"] == "/api/rca"
# STAR star = client.post("/api/hillclimb/star/diagnose", json={ "text": ("When I joined the team of 12 our deploys failed under a hard deadline. I was " "asked to fix it. I decided to build a gate and convinced the tech lead who " "disagreed. As a result failures dropped from 14% to 3% and we sustained it " "with weekly monitoring since then."), "save_evidence": True}).json() assert star["evidence_id"] assert len(star["components"]) == 4
# design lab challenges = client.get("/api/hillclimb/design/challenges").json() assert len(challenges["challenges"]) == 4 grade = client.post("/api/hillclimb/design/submit", json={ "challenge_id": "parallel_inference", "components": [ {"id": "s", "type": "source", "name": "traffic", "note": "20000 qps"}, {"id": "i1", "type": "inference", "name": "gpu pool a"}, {"id": "i2", "type": "inference", "name": "gpu pool b"}, {"id": "st", "type": "storage", "name": "results"}, {"id": "m", "type": "monitoring", "name": "slo monitor"}, ], "edges": [{"source": "s", "target": "i1"}, {"source": "s", "target": "i2"}, {"source": "i1", "target": "st"}, {"source": "i2", "target": "st"}, {"source": "st", "target": "m"}], "rationales": {"batching": "dynamic batching keeps p99 latency under 100 ms with 30% " "headroom; the tradeoff is cost, and replicated zones give " "reliability; monitoring alerts on scalability limits and " "failure handling uses degraded single-model fallback"}, }).json() assert grade["structural"]["missing_stages"] == [] assert grade["overall_score"] >= 2
# simulation: 3 turns sim = client.post("/api/hillclimb/simulation/start", json={"seed": 42, "max_turns": 3}).json() for hyp, iid in [("Monitoring will improve safety by 5", "add_monitoring"), ("Pausing launches raises safety by 8", "pause_launches"), ("1:1s will recover team morale by 5", "team_1on1s")]: sim = client.post(f"/api/hillclimb/simulation/{sim['sim_id']}/step", json={"hypothesis": hyp, "intervention_id": iid}).json() assert sim["status"] == "complete" assert sim["debrief"]["competency_mappings"] catalog = client.get("/api/hillclimb/simulation/catalog").json() assert catalog["interventions"] and catalog["scenarios"]
# interview: 2 questions iv = client.post("/api/hillclimb/interview/start", json={"mode": "management", "seed": 5}).json() iv = client.post(f"/api/hillclimb/interview/{iv['session_id']}/answer", json={"answer": WEAK_ANSWER}).json() assert iv["turns"][-1]["question_type"] == "probe" iv = client.post(f"/api/hillclimb/interview/{iv['session_id']}/answer", json={"answer": STRONG_LEADERSHIP_ANSWER}).json() iv = client.post(f"/api/hillclimb/interview/{iv['session_id']}/end").json() assert iv["status"] == "complete" and iv["evidence_id"]
# evidence library reflects everything above ev = client.get("/api/hillclimb/evidence").json() types = {e["artifact_type"] for e in ev["evidence"]} assert {"star_story", "design_submission", "interview_transcript", "exercise_attempt", "diagnostic"} <= types
# readiness matrix + bottleneck + next best action rd = client.get("/api/hillclimb/readiness").json() assert rd["matrix"] and rd["dimensions"] assert any(r["knowledge_score"] > 0 for r in rd["matrix"]) nba = client.get("/api/hillclimb/next-action").json() assert nba["concept"] and nba["exercise"] and nba["assessment"]
def test_error_paths(client): assert client.get("/api/hillclimb/exercise/nope").status_code == 404 assert client.post("/api/hillclimb/exercise/generate", json={"competency_id": "bogus"}).status_code == 400 assert client.post("/api/hillclimb/star/diagnose", json={"text": " "}).status_code == 400 assert client.get("/api/hillclimb/simulation/nope").status_code == 404 assert client.post("/api/hillclimb/interview/start", json={"mode": "bogus"}).status_code == 400 assert client.post("/api/hillclimb/journey/advance", json={"event": "assessment_result", "passed": True}).status_code == 400
def test_blueprint_edit_validation(client): bp = client.get("/api/hillclimb/blueprint").json() bp["competencies"][0]["prerequisites"] = ["does.not.exist"] res = client.put("/api/hillclimb/blueprint", json=bp) assert res.status_code == 400 assert "unknown prerequisite" in str(res.json())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465"""Blueprint & competency-graph integrity."""
from sensorflow.hillclimb.blueprint import (competency_index, downstream_map, display_dimensions_for, load_blueprint, seed_blueprint, validate_graph)from sensorflow.hillclimb.models import Dimension, get_store
def test_four_phases_with_full_structure(): bp = seed_blueprint() assert [p.phase for p in bp.phases] == [1, 2, 3, 4] for p in bp.phases: assert p.objective assert p.topics and p.skills and p.exercises and p.assessments assert p.completion_criteria
def test_marked_reconstructed_from_spec_and_seeded_editable(): store = get_store() bp = load_blueprint(store) assert bp.source == "reconstructed-from-spec" # persisted as an editable data structure, not hardcoded prose raw = store.get("blueprint", "active") assert raw is not None and raw["source"] == "reconstructed-from-spec" # editing the stored copy is what subsequent loads see raw["version"] = 2 store.put("blueprint", "active", raw) assert load_blueprint(store).version == 2
def test_no_prerequisite_cycles_and_no_dangling_ids(): bp = seed_blueprint() assert validate_graph(bp) == []
def test_every_competency_tagged_with_exactly_one_dimension(): bp = seed_blueprint() for c in bp.competencies: assert isinstance(c.dimension, Dimension) # all four dimensions are represented and tracked separately dims = {c.dimension for c in bp.competencies} assert dims == set(Dimension)
def test_key_prerequisite_edge_distributed_fundamentals_to_parallel_inference(): idx = competency_index(seed_blueprint()) assert "p2.distributed_fundamentals" in idx["p2.parallel_inference"].prerequisites
def test_downstream_map_transitive(): bp = seed_blueprint() down = downstream_map(bp) # distributed fundamentals transitively unlocks the phase-4 capstone assert "p4.hill_climbing" in down["p2.distributed_fundamentals"] # capstone unlocks nothing assert down["p4.hill_climbing"] == set()
def test_display_dimensions_cover_all_six(): bp = seed_blueprint() covered = set() for c in bp.competencies: covered |= set(display_dimensions_for(c)) assert covered == {"Technical Depth", "System Design", "Execution", "Leadership", "Communication", "Safety/Risk"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465"""Exercise generation: required shape, seeded structural variation, canonical family."""
import pytest
from sensorflow.hillclimb.content import generate_exercise, get_exercise
def test_exercise_has_required_shape(): ex = generate_exercise("p1.cusum", difficulty=2, seed=5, use_llm=False) assert ex.competency_id == "p1.cusum" assert ex.difficulty == 2 assert ex.prerequisites == ["p1.statistical_evaluation"] assert len(ex.scenario) > 50 assert ex.expected_reasoning assert ex.evaluation_rubric assert ex.common_failure_modes assert ex.follow_up_questions
def test_structurally_different_regeneration_for_same_competency(): a = generate_exercise("p1.regression_detection", seed=101, use_llm=False) b = generate_exercise("p1.regression_detection", seed=202, use_llm=False) assert a.exercise_id != b.exercise_id assert a.scenario != b.scenario # different slot values / variant assert a.template_id != b.template_id # seeded template stamp differs # same competency, same family — the rubric skeleton stays comparable assert a.competency_id == b.competency_id assert a.family == b.family == "offline_shadow"
def test_same_seed_is_deterministic(): a = generate_exercise("p2.parallel_inference", seed=7, use_llm=False) b = generate_exercise("p2.parallel_inference", seed=7, use_llm=False) assert a.scenario == b.scenario
def test_canonical_offline_shadow_family_rubric_distinguishes_seven_causes(): ex = generate_exercise("p1.regression_detection", seed=1, use_llm=False) criteria = " | ".join(i.criterion.lower() for i in ex.evaluation_rubric) for cause in ["metric definition", "distribution shift", "sampling bias", "feature", "serving", "noise", "true regression"]: assert cause in criteria, f"rubric missing cause: {cause}" # cross-linked to the live RCA workbench (read-only pointer) assert ex.linked_tool is not None assert ex.linked_tool["page"] == "rca" assert ex.linked_tool["api"] == "/api/rca"
def test_every_competency_can_generate(isolated_store): from sensorflow.hillclimb.blueprint import load_blueprint bp = load_blueprint(isolated_store) for comp in bp.competencies: ex = generate_exercise(comp.id, seed=3, use_llm=False) assert ex.evaluation_rubric and ex.scenario
def test_exercise_persisted_and_retrievable(): ex = generate_exercise("p3.hiring", seed=9, use_llm=False) again = get_exercise(ex.exercise_id) assert again is not None and again.scenario == ex.scenario
def test_unknown_competency_rejected(): with pytest.raises(ValueError): generate_exercise("p9.nope", use_llm=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107"""Design-lab grader: good vs broken architectures."""
from sensorflow.hillclimb.design_lab import (Component, DesignSubmission, Edge, grade_submission)
RATIONALES = { "Failure-mining trigger criteria": ( "Monitoring computes slice metrics and alerts when drift exceeds 2 sigma; scalability comes " "from partitioned stream consumers handling 20000 qps with 30% headroom."), "Label routing & quality control": ( "Redundant dual-region labeling queues (replicated, failover in under 5 minutes) with " "observability dashboards, logs and traces on every stage; cost is controlled by tiered " "storage and spot instances."), "Loop latency (failure → fixed model)": ( "End-to-end loop latency target is 7 days; p99 inference latency stays under 100 ms. " "The tradeoff: faster loops cost more compute, at the expense of budget."), "How you detect the loop itself breaking": ( "A dead letter queue plus a heartbeat monitor covers failure handling; if mining stalls we " "degrade gracefully to weekly batch replay and recover from checkpoints."),}
def _good_submission(): comps = [ Component(id="src", type="source", name="Fleet frames", note="2 PB/week"), Component(id="inf1", type="inference", name="Serving A", note="10000 qps"), Component(id="inf2", type="inference", name="Serving B", note="10000 qps"), Component(id="mon", type="monitoring", name="Slice monitor"), Component(id="fb", type="feedback", name="Failure miner"), Component(id="train", type="training", name="Retrain"), Component(id="ev", type="eval", name="Eval gate"), ] edges = [Edge(source="src", target="inf1"), Edge(source="src", target="inf2"), Edge(source="inf1", target="mon"), Edge(source="inf2", target="mon"), Edge(source="mon", target="fb"), Edge(source="fb", target="train"), Edge(source="train", target="ev"), Edge(source="ev", target="inf1"), Edge(source="ev", target="inf2")] return DesignSubmission(challenge_id="feedback_loop", components=comps, edges=edges, rationales=RATIONALES)
def _broken_submission(): comps = [ Component(id="src", type="source", name="Fleet frames"), Component(id="inf", type="inference", name="Serving"), Component(id="stor", type="storage", name="Orphan bucket"), # never connected ] edges = [Edge(source="src", target="inf")] return DesignSubmission(challenge_id="feedback_loop", components=comps, edges=edges, rationales={"why": "it works"})
def test_good_architecture_grades_well(): grade = grade_submission(_good_submission(), save_evidence=False) s = grade.structural assert s.missing_stages == [] assert s.orphan_components == [] assert s.feedback_loop_closed assert s.capacity_math_found and s.capacity_quotes assert grade.overall_score >= 3
def test_broken_architecture_reports_specific_gaps(): grade = grade_submission(_broken_submission(), save_evidence=False) s = grade.structural assert "monitoring" in " ".join(s.missing_stages) assert "Orphan bucket" in s.orphan_components assert not s.feedback_loop_closed assert not s.capacity_math_found joined = " ".join(grade.gaps).lower() assert "missing required stage" in joined assert "orphan" in joined assert "feedback loop is not closed" in joined assert "capacity" in joined assert grade.overall_score < grade_submission(_good_submission(), save_evidence=False).overall_score
def test_spof_detection(): # single inference node shared by everything upstream/downstream = articulation point comps = [ Component(id="src", type="source"), Component(id="inf", type="inference"), Component(id="mon", type="monitoring"), Component(id="fb", type="feedback"), Component(id="train", type="training"), Component(id="ev", type="eval"), ] edges = [Edge(source="src", target="inf"), Edge(source="inf", target="mon"), Edge(source="mon", target="fb"), Edge(source="fb", target="train"), Edge(source="train", target="ev"), Edge(source="ev", target="inf")] grade = grade_submission(DesignSubmission(challenge_id="feedback_loop", components=comps, edges=edges, rationales={}), save_evidence=False) assert "inf" in grade.structural.single_points_of_failure
def test_per_dimension_scores_with_rationale_evidence(): grade = grade_submission(_good_submission(), save_evidence=False) dims = {d.dimension: d for d in grade.dimension_grades} assert set(dims) == {"scalability", "reliability", "latency", "cost", "observability", "failure_handling", "tradeoffs"} assert dims["scalability"].score >= 3 and dims["scalability"].evidence assert dims["tradeoffs"].score >= 2
def test_grading_stores_evidence_artifact(isolated_store): grade = grade_submission(_good_submission(), store=isolated_store, save_evidence=True) assert grade.evidence_id raw = isolated_store.get("evidence", grade.evidence_id) assert raw["artifact_type"] == "design_submission" assert "p2.feedback_loops" in raw["competency_ids"]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""Evaluation contract, evidence-required rule, anti-gaming, coaching specificity."""
import pytestfrom pydantic import ValidationError
from sensorflow.hillclimb import coachfrom sensorflow.hillclimb.content import generate_exercisefrom sensorflow.hillclimb.evaluate import rule_based_evaluatefrom sensorflow.hillclimb.models import EvaluationResult
from .conftest import (CONCISE_PRECISE_ANSWER, STRONG_TECH_ANSWER, VERBOSE_WAFFLE, WEAK_ANSWER)
def _exercise(seed=1): return generate_exercise("p1.regression_detection", seed=seed, use_llm=False)
def test_contract_schema_enforced(): with pytest.raises(ValidationError): EvaluationResult(competency="x", score=0, confidence=0.5) with pytest.raises(ValidationError): EvaluationResult(competency="x", score=6, confidence=0.5) with pytest.raises(ValidationError): EvaluationResult(competency="x", score=3, confidence=1.5)
def test_strong_answer_scores_high_with_quoted_evidence(): result = rule_based_evaluate(_exercise(), STRONG_TECH_ANSWER) assert result.score >= 4 assert result.evidence, "no score without evidence" # evidence quotes the user's own statements for quote in result.evidence: assert quote.rstrip("…")[:40].lower() in STRONG_TECH_ANSWER.lower() assert result.follow_up_question in _exercise().follow_up_questions
def test_no_score_without_evidence(): result = rule_based_evaluate(_exercise(), WEAK_ANSWER) assert result.score == 1 assert result.evidence == [] empty = rule_based_evaluate(_exercise(), "") assert empty.score == 1 # the rule as an invariant: any score above 1 must carry evidence for answer in [STRONG_TECH_ANSWER, CONCISE_PRECISE_ANSWER, VERBOSE_WAFFLE, WEAK_ANSWER]: r = rule_based_evaluate(_exercise(), answer) if r.score > 1: assert r.evidence
def test_anti_gaming_verbose_waffle_scores_below_concise_precise(): ex = _exercise() waffle = rule_based_evaluate(ex, VERBOSE_WAFFLE) concise = rule_based_evaluate(ex, CONCISE_PRECISE_ANSWER) assert len(VERBOSE_WAFFLE) > 4 * len(CONCISE_PRECISE_ANSWER) assert waffle.score < concise.score, ( f"verbosity must not raise scores: waffle={waffle.score} concise={concise.score}")
def test_misconception_detection(): ex = _exercise() r = rule_based_evaluate(ex, "This is definitely a true regression, no need to test more. " "Offline eval is ground truth anyway.") assert r.misconceptions assert any("significance" in m.lower() or "premature" in m.lower() for m in r.misconceptions)
def test_missing_evidence_lists_specific_gaps(): ex = _exercise() r = rule_based_evaluate(ex, CONCISE_PRECISE_ANSWER) joined = " ".join(r.missing_evidence).lower() assert "quantified" in joined or "tradeoff" in joined
def test_coaching_is_specific_not_generic(): ex = _exercise() r = rule_based_evaluate(ex, CONCISE_PRECISE_ANSWER) feedback = coach.build_feedback(ex, r) # references what the answer DID establish... assert "establishes" in feedback # ...and points at concrete rubric gaps, not platitudes assert "Missing:" in feedback or "quantified" in feedback.lower() # recommended action mentions the competency / retry semantics assert r.recommended_action assert "p1.regression_detection" in r.recommended_action or "exercise" in r.recommended_action1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071"""Interviewer adaptivity: sequencing must depend on evaluations, no fixed list."""
from sensorflow.hillclimb.content import get_exercisefrom sensorflow.hillclimb.interviewer import (end_interview, start_interview, submit_answer)
from .conftest import STRONG_LEADERSHIP_ANSWER, WEAK_ANSWER
def test_weak_answer_triggers_targeted_probe(isolated_store): s = start_interview("management", seed=5, store=isolated_store) first = s.turns[0] s = submit_answer(s.session_id, WEAK_ANSWER, use_llm=False, store=isolated_store) nxt = s.turns[-1] assert s.turns[0].evaluation.score <= 2 assert nxt.question_type == "probe" # the probe comes from the exercise's own follow_up_questions ex = get_exercise(first.exercise_id, isolated_store) assert nxt.question in ex.follow_up_questions assert nxt.competency_id == first.competency_id
def test_strong_answer_escalates(isolated_store): s = start_interview("management", seed=5, store=isolated_store) s = submit_answer(s.session_id, STRONG_LEADERSHIP_ANSWER, use_llm=False, store=isolated_store) assert s.turns[0].evaluation.score >= 4 nxt = s.turns[-1] assert nxt.question_type == "escalate" assert nxt.difficulty == 3 # difficulty went up
def test_sequencing_depends_on_answer_quality(isolated_store): weak = start_interview("management", seed=5, store=isolated_store) strong = start_interview("management", seed=5, store=isolated_store) # identical opening question (same seed) ... assert weak.turns[0].question == strong.turns[0].question weak = submit_answer(weak.session_id, WEAK_ANSWER, use_llm=False, store=isolated_store) strong = submit_answer(strong.session_id, STRONG_LEADERSHIP_ANSWER, use_llm=False, store=isolated_store) # ... but different evaluations produce different next questions assert weak.turns[-1].question != strong.turns[-1].question assert weak.turns[-1].question_type != strong.turns[-1].question_type
def test_probe_limit_then_moves_on(isolated_store): s = start_interview("management", seed=5, store=isolated_store) s = submit_answer(s.session_id, WEAK_ANSWER, use_llm=False, store=isolated_store) s = submit_answer(s.session_id, WEAK_ANSWER, use_llm=False, store=isolated_store) assert s.turns[-1].question_type == "probe" s = submit_answer(s.session_id, WEAK_ANSWER, use_llm=False, store=isolated_store) assert s.turns[-1].question_type == "advance" # max 2 probes, then new competency
def test_transcript_saved_as_evidence(isolated_store): s = start_interview("technical", seed=8, store=isolated_store) s = submit_answer(s.session_id, "Because dynamic batching amortizes overhead it can fail " "under overload; I would keep 30% headroom as the tradeoff.", use_llm=False, store=isolated_store) s = end_interview(s.session_id, store=isolated_store) assert s.status == "complete" and s.evidence_id raw = isolated_store.get("evidence", s.evidence_id) assert raw["artifact_type"] == "interview_transcript" assert raw["payload"]["transcript"] assert raw["competency_ids"]
def test_modes_restrict_competency_pool(isolated_store): tech = start_interview("technical", seed=2, store=isolated_store) mgmt = start_interview("management", seed=2, store=isolated_store) assert tech.turns[0].competency_id.split(".")[0] in ("p1", "p2") assert mgmt.turns[0].competency_id.startswith("p3")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""Journey state machine incl. FAIL -> REMEDIATION routing to the diagnosed prerequisite."""
import pytest
from sensorflow.hillclimb import adaptive, readinessfrom sensorflow.hillclimb.models import Attempt, EvaluationResult, JourneyState
def _seed(store, cid, score): for kind in ("diagnostic", "exercise"): readiness.record_attempt( Attempt(user_id="default", competency_id=cid, kind=kind, exercise_id="x", responses={}, evaluation=EvaluationResult(competency=cid, score=score, confidence=0.8, evidence=["q"])), store)
def test_happy_path_transitions(isolated_store): j = adaptive.get_journey(store=isolated_store) assert j.state == JourneyState.NOT_STARTED j = adaptive.advance_journey("default", "start_diagnostic", store=isolated_store) assert j.state == JourneyState.DIAGNOSTIC j = adaptive.advance_journey("default", "diagnostic_complete", store=isolated_store) assert j.state == JourneyState.LEARNING j = adaptive.advance_journey("default", "begin_practice", competency_id="p1.precision_recall", store=isolated_store) assert j.state == JourneyState.PRACTICE j = adaptive.advance_journey("default", "request_assessment", store=isolated_store) assert j.state == JourneyState.ASSESSMENT j = adaptive.advance_journey("default", "assessment_result", passed=True, competency_id="p1.precision_recall", store=isolated_store) assert j.state == JourneyState.LEARNING # PASS -> next assert j.current_competency != "p1.precision_recall" assert j.history and j.history[-1]["passed"] is True
def test_invalid_transitions_rejected(isolated_store): with pytest.raises(ValueError): adaptive.advance_journey("default", "request_assessment", store=isolated_store) with pytest.raises(ValueError): adaptive.advance_journey("default", "assessment_result", passed=True, store=isolated_store)
def test_fail_routes_remediation_to_diagnosed_prerequisite(isolated_store): # weak prerequisite: distributed fundamentals; the advanced item fails _seed(isolated_store, "p2.distributed_fundamentals", 2) adaptive.advance_journey("default", "start_diagnostic", store=isolated_store) adaptive.advance_journey("default", "diagnostic_complete", store=isolated_store) adaptive.advance_journey("default", "begin_practice", competency_id="p2.parallel_inference", store=isolated_store) adaptive.advance_journey("default", "request_assessment", store=isolated_store) j = adaptive.advance_journey("default", "assessment_result", passed=False, competency_id="p2.parallel_inference", store=isolated_store) assert j.state == JourneyState.REMEDIATION # backward routing: the diagnosed MISSING PREREQUISITE, not the failed item assert j.remediation_target == "p2.distributed_fundamentals"
j = adaptive.advance_journey("default", "remediation_complete", store=isolated_store) assert j.state == JourneyState.REASSESS j = adaptive.advance_journey("default", "assessment_result", passed=True, competency_id="p2.parallel_inference", store=isolated_store) assert j.state == JourneyState.LEARNING assert j.remediation_target is None
def test_fail_without_prerequisites_remediates_in_place(isolated_store): adaptive.advance_journey("default", "start_diagnostic", store=isolated_store) adaptive.advance_journey("default", "diagnostic_complete", store=isolated_store) adaptive.advance_journey("default", "begin_practice", competency_id="p1.precision_recall", store=isolated_store) adaptive.advance_journey("default", "request_assessment", store=isolated_store) j = adaptive.advance_journey("default", "assessment_result", passed=False, competency_id="p1.precision_recall", store=isolated_store) assert j.state == JourneyState.REMEDIATION assert j.remediation_target == "p1.precision_recall"
def test_reassess_fail_loops_back_to_remediation(isolated_store): _seed(isolated_store, "p2.distributed_fundamentals", 2) adaptive.advance_journey("default", "start_diagnostic", store=isolated_store) adaptive.advance_journey("default", "diagnostic_complete", store=isolated_store) adaptive.advance_journey("default", "begin_practice", competency_id="p2.parallel_inference", store=isolated_store) adaptive.advance_journey("default", "request_assessment", store=isolated_store) adaptive.advance_journey("default", "assessment_result", passed=False, competency_id="p2.parallel_inference", store=isolated_store) adaptive.advance_journey("default", "remediation_complete", store=isolated_store) j = adaptive.advance_journey("default", "assessment_result", passed=False, competency_id="p2.parallel_inference", store=isolated_store) assert j.state == JourneyState.REMEDIATION1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""Readiness matrix, state derivation, and leverage-based bottleneck analysis."""
from sensorflow.hillclimb import readinessfrom sensorflow.hillclimb.blueprint import load_blueprintfrom sensorflow.hillclimb.models import Attempt, EvaluationResult, ReadinessState
def _attempt(cid, score, kind, user="default"): return Attempt(user_id=user, competency_id=cid, kind=kind, exercise_id="x", responses={}, evaluation=EvaluationResult(competency=cid, score=score, confidence=0.8, evidence=["quoted statement"]))
def _seed_scores(store, cid, score, user="default"): readiness.record_attempt(_attempt(cid, score, "diagnostic", user), store) readiness.record_attempt(_attempt(cid, score, "exercise", user), store)
def test_states_derive_from_scores(isolated_store): _seed_scores(isolated_store, "p1.precision_recall", 5) _seed_scores(isolated_store, "p1.iou", 3) _seed_scores(isolated_store, "p1.cusum", 2) matrix = readiness.compute_matrix(store=isolated_store) assert matrix["p1.precision_recall"].readiness_state == ReadinessState.STRONG assert matrix["p1.iou"].readiness_state == ReadinessState.COMPETENT assert matrix["p1.cusum"].readiness_state == ReadinessState.PRACTICING assert matrix["p1.ap_map"].readiness_state == ReadinessState.NOT_STARTED
def test_needs_review_on_knowledge_application_mismatch(isolated_store): readiness.record_attempt(_attempt("p1.iou", 5, "diagnostic"), isolated_store) readiness.record_attempt(_attempt("p1.iou", 2, "exercise"), isolated_store) matrix = readiness.compute_matrix(store=isolated_store) assert matrix["p1.iou"].readiness_state == ReadinessState.NEEDS_REVIEW
def test_scores_tracked_separately_never_collapsed(isolated_store): readiness.record_attempt(_attempt("p1.iou", 5, "diagnostic"), isolated_store) readiness.record_attempt(_attempt("p1.iou", 2, "exercise"), isolated_store) r = readiness.compute_matrix(store=isolated_store)["p1.iou"] assert r.knowledge_score == 5.0 assert r.application_score == 2.0
def test_bottleneck_is_blocking_prerequisite_not_min_score(isolated_store): bp = load_blueprint(isolated_store) weak_hub = "p2.distributed_fundamentals" # blocks much of phase 2 lowest = "p3.mentorship" # lowest raw score, blocks nothing untouched = {"p2.petabyte_ingestion", "p2.streaming_batch", "p2.parallel_inference"} for comp in bp.competencies: if comp.id == weak_hub: _seed_scores(isolated_store, comp.id, 2) elif comp.id == lowest: _seed_scores(isolated_store, comp.id, 1) elif comp.id not in untouched: _seed_scores(isolated_store, comp.id, 5)
bn = readiness.bottleneck_analysis(store=isolated_store) assert bn is not None assert bn["competency_id"] == weak_hub, ( f"bottleneck must be the blocking prerequisite, got {bn['competency_id']}") assert bn["blocked_count"] >= 3 assert set(bn["blocked_competencies"]) >= untouched # plain-language explanation names the leverage assert "limiting" in bn["explanation"]
def test_bottleneck_none_when_everything_competent(isolated_store): bp = load_blueprint(isolated_store) for comp in bp.competencies: _seed_scores(isolated_store, comp.id, 5) assert readiness.bottleneck_analysis(store=isolated_store) is None
def test_dimension_summary_covers_display_dimensions(isolated_store): _seed_scores(isolated_store, "p1.precision_recall", 4) dims = readiness.dimension_summary(store=isolated_store) names = {d["dimension"] for d in dims} assert names == {"Technical Depth", "System Design", "Execution", "Leadership", "Communication", "Safety/Risk"} tech = next(d for d in dims if d["dimension"] == "Technical Depth") assert tech["avg_score"] > 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687"""Simulation: determinism, safety-floor incidents, keep/reject, debrief mapping."""
from sensorflow.hillclimb.simulation import (create_simulation, get_simulation, step_simulation)
STRONG_HYP = "Investing in monitoring will improve safety by 5 points within two turns"
def _run(store, seed, moves): sim = create_simulation(seed=seed, max_turns=len(moves), store=store) for hyp, iid in moves: sim = step_simulation(sim.sim_id, hyp, iid, store=store) return sim
def test_deterministic_given_seed(isolated_store): moves = [(STRONG_HYP, "add_monitoring"), ("Pausing launches will raise safety", "pause_launches"), ("1:1s will recover team morale by 5", "team_1on1s")] a = _run(isolated_store, 42, moves) b = _run(isolated_store, 42, moves) assert a.objective_history == b.objective_history assert a.metrics == b.metrics c = _run(isolated_store, 43, moves) assert c.objective_history != a.objective_history
def test_safety_floor_triggers_incident_event(isolated_store): sim = create_simulation(seed=1, max_turns=6, store=isolated_store) for _ in range(5): sim = step_simulation(sim.sim_id, "Shipping fast will improve schedule", "ship_feature_fast", store=isolated_store) if any(e["type"] == "SAFETY_INCIDENT" for e in sim.events): break incidents = [e for e in sim.events if e["type"] == "SAFETY_INCIDENT"] assert incidents, "repeated corner-cutting must breach the safety floor" assert "regression escaped" in incidents[0]["detail"]
def test_keep_reject_reverts_previous_effects(isolated_store): sim = create_simulation(seed=9, max_turns=4, store=isolated_store) sim = step_simulation(sim.sim_id, "Shipping fast raises schedule", "ship_feature_fast", store=isolated_store) applied = sim.history[0].applied_effects sim = step_simulation(sim.sim_id, "Reverting; monitoring will improve safety", "add_monitoring", revert_previous=True, store=isolated_store) assert sim.history[1].reverted_previous assert any("Rejected previous intervention" in e for e in sim.history[1].events) assert applied # effects existed and were rolled back
def test_delayed_second_order_effects_land_later(isolated_store): sim = create_simulation(seed=3, max_turns=4, store=isolated_store) sim = step_simulation(sim.sim_id, "Test infra will raise reliability", "invest_test_infra", store=isolated_store) assert sim.pending, "delayed effects must be queued" sim = step_simulation(sim.sim_id, "Waiting for infra to land", "team_1on1s", store=isolated_store) sim = step_simulation(sim.sim_id, "Infra lands this turn", "team_1on1s", store=isolated_store) landed = [n for t in sim.history for n in t.delayed_landed] assert any("Test infra lands" in n for n in landed)
def test_debrief_maps_decisions_to_competency_evidence(isolated_store): moves = [(STRONG_HYP, "add_monitoring"), ("Pausing launches will raise safety above 55", "pause_launches"), ("Test infra will improve reliability by 7", "invest_test_infra"), ("Expectation reset will improve schedule by 6", "exec_expectation_reset")] sim = _run(isolated_store, 42, moves) assert sim.status == "complete" assert sim.debrief is not None mapped = {m["competency_id"]: m for m in sim.debrief["competency_mappings"]} assert "p4.hill_climbing" in mapped assert mapped["p4.hill_climbing"]["verdict"] == "evidenced" # falsifiable hypotheses assert "p2.reliability_tradeoffs" in mapped # evidenced mappings persist Evidence artifacts ev = isolated_store.where("evidence", artifact_type="simulation_debrief") assert ev, "debrief must store evidence" # state is retrievable assert get_simulation(sim.sim_id, isolated_store).status == "complete"
def test_vague_hypotheses_marked_as_gap(isolated_store): moves = [("do stuff", "add_monitoring"), ("things", "team_1on1s"), ("whatever", "cut_scope"), ("meh", "exec_expectation_reset")] sim = _run(isolated_store, 5, moves) mapped = {m["competency_id"]: m for m in sim.debrief["competency_mappings"]} assert mapped["p4.hill_climbing"]["verdict"] == "gap"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""STAR Story Box: diagnosis, claim-vs-evidence, competency mapping, evidence storage."""
from sensorflow.hillclimb.star import diagnose_story
GOOD_STORY = ( "When I joined, the team of 12 engineers owned a perception system whose release process was " "failing under a hard quarterly deadline. I was asked to fix the release pipeline. " "I decided to build a regression gate, and instead of pausing all launches I chose a staged " "rollout; the tech lead disagreed, and I convinced him with data from the last three incidents. " "As a result, deploy failures dropped from 14% to 3% within two quarters, and since then we " "have sustained the improvement with weekly monitoring.")
VAGUE_STORY = ( "My team had some problems with quality. We worked together on improving things and " "significantly improved performance. Everyone was happier and things got much better overall.")
def test_good_story_diagnosed_into_components(): d = diagnose_story(GOOD_STORY, save_evidence=False) by_label = {c.component: c for c in d.components} assert by_label["S"].present and by_label["A"].present and by_label["R"].present assert d.overall_score >= 4 passed = {c.check for c in d.checks if c.passed} assert {"personal_ownership", "measurable_outcome", "influence_disagreement", "constraints", "follow_through"} <= passed
def test_claim_vs_evidence_detector(): vague = diagnose_story(VAGUE_STORY, save_evidence=False) unquantified = [f for f in vague.claim_flags if f.kind == "unquantified_claim"] assert unquantified, "must flag 'significantly improved performance' style claims" assert any("metric" in f.detail or "before" in f.detail for f in unquantified)
good = diagnose_story(GOOD_STORY, save_evidence=False) measurable = [f for f in good.claim_flags if f.kind == "measurable_evidence"] assert measurable, "quantified before/after claims must be recognized as evidence"
def test_unquantified_claims_cap_score_and_produce_strengthen_prompts(): d = diagnose_story(VAGUE_STORY, save_evidence=False) assert d.overall_score <= 3 assert any("Strengthen evidence" in c for c in d.coaching) # weak ownership called out specifically ownership = next(c for c in d.checks if c.check == "personal_ownership") assert not ownership.passed
def test_story_maps_to_phase3_competencies(): d = diagnose_story(GOOD_STORY, save_evidence=False) ids = {c["competency_id"] for c in d.competencies} assert "p3.conflict_resolution" in ids # "disagreed" assert all(cid.startswith("p3.") for cid in ids) assert all(c["reason"] for c in d.competencies)
def test_saved_as_evidence_artifact(isolated_store): d = diagnose_story(GOOD_STORY, user_id="u1", save_evidence=True, store=isolated_store) assert d.evidence_id raw = isolated_store.get("evidence", d.evidence_id) assert raw["artifact_type"] == "star_story" assert raw["competency_ids"] assert raw["score"] == d.overall_scoresrc/pages/hillclimb/DashboardView.tsxAdded+187
src/pages/hillclimb/DesignLabView.tsxAdded+248
src/pages/hillclimb/DiagnosticView.tsxAdded+142
src/pages/hillclimb/EvidenceView.tsxAdded+81
src/pages/hillclimb/HillClimbSection.tsxAdded+91
src/pages/hillclimb/InterviewView.tsxAdded+175
src/pages/hillclimb/MatrixView.tsxAdded+151
src/pages/hillclimb/PracticeView.tsxAdded+232
src/pages/hillclimb/SimulationView.tsxAdded+247
src/pages/hillclimb/StarView.tsxAdded+178
src/services/hillclimb.tsAdded+139
src/types/hillclimb.tsAdded+424
tests/test_hillclimb/__init__.pyAdded
tests/test_hillclimb/conftest.pyAdded+67
tests/test_hillclimb/test_adaptive.pyAdded+50
tests/test_hillclimb/test_api.pyAdded+142
tests/test_hillclimb/test_blueprint.pyAdded+65
tests/test_hillclimb/test_content.pyAdded+65
tests/test_hillclimb/test_design_lab.pyAdded+107
tests/test_hillclimb/test_evaluate.pyAdded+85
tests/test_hillclimb/test_interviewer.pyAdded+71
tests/test_hillclimb/test_journey.pyAdded+90
tests/test_hillclimb/test_readiness.pyAdded+83
tests/test_hillclimb/test_simulation.pyAdded+87
tests/test_hillclimb/test_star.pyAdded+64