Spaces:
Paused
Paused
Deploy Sensorflow Studio
Browse filesFiles changed (21)
- app_backend.py+4
- sensorflow/hillclimb/__init__.pyAdded+5
- sensorflow/hillclimb/adaptive.pyAdded+276
- sensorflow/hillclimb/api.pyAdded+389
- sensorflow/hillclimb/blueprint.pyAdded+351
- sensorflow/hillclimb/coach.pyAdded+81
- sensorflow/hillclimb/content.pyAdded+441
- sensorflow/hillclimb/design_lab.pyAdded+331
- sensorflow/hillclimb/evaluate.pyAdded+196
- sensorflow/hillclimb/interviewer.pyAdded+210
- sensorflow/hillclimb/llm.pyAdded+86
- sensorflow/hillclimb/models.pyAdded+214
- sensorflow/hillclimb/readiness.pyAdded+156
- sensorflow/hillclimb/simulation.pyAdded+426
- sensorflow/hillclimb/star.pyAdded+270
- src/App.tsx+5
- src/components/help/HelpMenu.tsx+2
- src/components/hillclimb/shared.tsxAdded+227
- src/content/glossary.ts+54
- src/content/pageHelp.ts+12
- src/context/LabelEvalContext.tsx+2
1483 unmodified lines1484148514861487148814891483 unmodified linesfrom sensorflow.rca.api import router as rca_routerapp.include_router(rca_router)# Multimodal rare-event mining & perception QA (costumed-pedestrian miner).from sensorflow.raremine.api import router as raremine_routerapp.include_router(raremine_router)1483 unmodified lines14841485148614871488148914901491149214931483 unmodified linesfrom sensorflow.rca.api import router as rca_routerapp.include_router(rca_router)# Hill Climbing EM: adaptive EM development & interview-readiness platform.from sensorflow.hillclimb.api import router as hillclimb_routerapp.include_router(hillclimb_router)# Multimodal rare-event mining & perception QA (costumed-pedestrian miner).from sensorflow.raremine.api import router as raremine_routerapp.include_router(raremine_router)
12345"""Hill Climbing EM: adaptive Engineering-Manager development & interview-readiness platform.
Backend namespace for the "Hill Climbing EM" feature. All state persists underruns/hillclimb/ and the API is exposed under /api/hillclimb (see api.py)."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276"""Adaptive engine: journey state machine, diagnostic assessment, next-best-action.
Journey: NOT_STARTED → DIAGNOSTIC → LEARNING → PRACTICE → ASSESSMENT →(PASS → next competency | FAIL → REMEDIATION → REASSESS). Failing an advanceditem routes BACKWARD: the engine diagnoses the weakest prerequisite of thefailed competency and assigns remediation there.
Next-best-action always returns exactly {1 concept, 1 exercise, 1 assessment}aimed at the current bottleneck."""
from __future__ import annotations
import randomfrom typing import Dict, List, Optional
from pydantic import BaseModel, Field
from sensorflow.hillclimb import content, evaluate, readinessfrom sensorflow.hillclimb.blueprint import competency_index, load_blueprintfrom sensorflow.hillclimb.models import (Attempt, Evidence, Journey, JourneyState, Store, get_store, new_id, now_iso)
# ------------------------------------------------------------------ journey
def get_journey(user_id: str = "default", store: Optional[Store] = None) -> Journey: store = store or get_store() raw = store.get("journeys", user_id) if raw: return Journey(**raw) j = Journey(user_id=user_id) store.put("journeys", user_id, j) return j
def _save_journey(j: Journey, store: Store) -> None: j.updated_at = now_iso() store.put("journeys", j.user_id, j)
def diagnose_missing_prerequisite(competency_id: str, user_id: str = "default", store: Optional[Store] = None) -> str: """Failing an advanced item -> find the weakest prerequisite to remediate.
Returns the prerequisite (transitively closest) with the lowest combined readiness; if the competency has no prerequisites, remediation stays on the competency itself. """ store = store or get_store() bp = load_blueprint(store) idx = competency_index(bp) if competency_id not in idx or not idx[competency_id].prerequisites: return competency_id matrix = readiness.compute_matrix(user_id, store) prereqs = [p for p in idx[competency_id].prerequisites if p in matrix] weak = sorted(prereqs, key=lambda p: (readiness.combined_score(matrix[p]), p)) for p in weak: if matrix[p].readiness_state not in readiness.COMPETENT_STATES: return p return competency_id # all prereqs fine -> remediate the competency itself
TRANSITIONS = { (JourneyState.NOT_STARTED, "start_diagnostic"): JourneyState.DIAGNOSTIC, (JourneyState.DIAGNOSTIC, "diagnostic_complete"): JourneyState.LEARNING, (JourneyState.LEARNING, "begin_practice"): JourneyState.PRACTICE, (JourneyState.PRACTICE, "request_assessment"): JourneyState.ASSESSMENT, (JourneyState.REMEDIATION, "remediation_complete"): JourneyState.REASSESS,}
def advance_journey(user_id: str, event: str, competency_id: Optional[str] = None, passed: Optional[bool] = None, store: Optional[Store] = None) -> Journey: store = store or get_store() j = get_journey(user_id, store) prior = j.state
if event == "assessment_result": if j.state not in (JourneyState.ASSESSMENT, JourneyState.REASSESS): raise ValueError(f"assessment_result invalid in state {j.state}") target = competency_id or j.current_competency or "" if passed: j.state = JourneyState.LEARNING j.remediation_target = None j.current_competency = _next_competency(target, user_id, store) else: j.state = JourneyState.REMEDIATION j.remediation_target = diagnose_missing_prerequisite(target, user_id, store) else: key = (j.state, event) if key not in TRANSITIONS: raise ValueError(f"event '{event}' invalid in state {j.state}") j.state = TRANSITIONS[key] if competency_id: j.current_competency = competency_id
j.history.append({"from": prior, "event": event, "to": j.state, "competency": competency_id, "passed": passed, "remediation_target": j.remediation_target, "at": now_iso()}) _save_journey(j, store) return j
def _next_competency(after: str, user_id: str, store: Store) -> Optional[str]: """Next non-competent competency in blueprint order after the given one.""" bp = load_blueprint(store) matrix = readiness.compute_matrix(user_id, store) ordered = [c.id for c in bp.competencies] start = ordered.index(after) + 1 if after in ordered else 0 for cid in ordered[start:] + ordered[:start]: if cid != after and matrix[cid].readiness_state not in readiness.COMPETENT_STATES: return cid return None
# ------------------------------------------------------------------ diagnostic
class DiagnosticSession(BaseModel): diagnostic_id: str = Field(default_factory=lambda: new_id("dx")) user_id: str = "default" seed: int = 11 total_questions: int = 6 answered: int = 0 status: str = "active" # active | complete current_exercise_id: Optional[str] = None current_competency: Optional[str] = None asked: List[str] = Field(default_factory=list) results: List[Dict] = Field(default_factory=list)
DIAGNOSTIC_STARTERS = ["p1.precision_recall", "p2.distributed_fundamentals", "p3.roadmap_ambiguity", "p1.regression_detection", "p2.parallel_inference", "p3.prioritization_risk"]
def start_diagnostic(user_id: str = "default", seed: int = 11, store: Optional[Store] = None) -> DiagnosticSession: store = store or get_store() dx = DiagnosticSession(user_id=user_id, seed=seed) first = DIAGNOSTIC_STARTERS[0] ex = content.generate_exercise(first, difficulty=2, seed=seed, store=store, use_llm=False) dx.current_exercise_id = ex.exercise_id dx.current_competency = first dx.asked.append(first) store.put("diagnostics", dx.diagnostic_id, dx) try: advance_journey(user_id, "start_diagnostic", competency_id=first, store=store) except ValueError: pass # journey already past NOT_STARTED; diagnostic can be retaken return dx
def _adaptive_next(dx: DiagnosticSession, last_score: int, store: Store) -> Optional[str]: """Adaptive selection: weak answer drills into prerequisites, strong answer jumps ahead; otherwise walk the starter set.""" bp = load_blueprint(store) idx = competency_index(bp) if last_score <= 2 and dx.current_competency: for p in idx[dx.current_competency].prerequisites: if p not in dx.asked: return p if last_score >= 4 and dx.current_competency: dependents = [c.id for c in bp.competencies if dx.current_competency in c.prerequisites and c.id not in dx.asked] if dependents: rng = random.Random(dx.seed + dx.answered) return rng.choice(sorted(dependents)) for cid in DIAGNOSTIC_STARTERS: if cid not in dx.asked: return cid remaining = [c.id for c in bp.competencies if c.id not in dx.asked] return remaining[0] if remaining else None
def answer_diagnostic(diagnostic_id: str, answer: str, use_llm: bool = True, store: Optional[Store] = None) -> DiagnosticSession: store = store or get_store() raw = store.get("diagnostics", diagnostic_id) if raw is None: raise ValueError(f"unknown diagnostic '{diagnostic_id}'") dx = DiagnosticSession(**raw) if dx.status != "active": raise ValueError("diagnostic already complete")
ex = content.get_exercise(dx.current_exercise_id, store) result = evaluate.evaluate_response(ex, answer, use_llm=use_llm) dx.answered += 1 dx.results.append({"competency_id": dx.current_competency, "score": result.score, "evaluation": result.model_dump()})
attempt = Attempt(user_id=dx.user_id, exercise_id=ex.exercise_id, competency_id=dx.current_competency, kind="diagnostic", responses={"answer": answer}, evaluation=result) readiness.record_attempt(attempt, store)
if dx.answered >= dx.total_questions: dx.status = "complete" dx.current_exercise_id = None dx.current_competency = None ev = Evidence(user_id=dx.user_id, competency_ids=[r["competency_id"] for r in dx.results], artifact_type="diagnostic", source="Adaptive diagnostic", summary=f"Diagnostic across {len(dx.results)} competencies.", quotes=[], score=_avg_score(dx), confidence=0.5, payload={"diagnostic_id": dx.diagnostic_id}) store.put("evidence", ev.evidence_id, ev) readiness.compute_matrix(dx.user_id, store) try: advance_journey(dx.user_id, "diagnostic_complete", store=store) except ValueError: pass else: nxt = _adaptive_next(dx, result.score, store) ex2 = content.generate_exercise(nxt, difficulty=2, seed=dx.seed + dx.answered * 37, store=store, use_llm=False) dx.current_exercise_id = ex2.exercise_id dx.current_competency = nxt dx.asked.append(nxt)
store.put("diagnostics", dx.diagnostic_id, dx) return dx
def _avg_score(dx: DiagnosticSession) -> float: scores = [r["score"] for r in dx.results] return round(sum(scores) / len(scores), 2) if scores else 0.0
def get_diagnostic(diagnostic_id: str, store: Optional[Store] = None) -> Optional[DiagnosticSession]: raw = (store or get_store()).get("diagnostics", diagnostic_id) return DiagnosticSession(**raw) if raw else None
# ------------------------------------------------------------- next best action
def next_best_action(user_id: str = "default", store: Optional[Store] = None) -> Dict: """Exactly one concept + one exercise + one assessment, aimed at the bottleneck.""" store = store or get_store() bp = load_blueprint(store) idx = competency_index(bp) matrix = readiness.compute_matrix(user_id, store) bn = readiness.bottleneck_analysis(user_id, store, matrix)
if bn is None: # everything competent — polish the weakest STRONG item ranked = sorted(matrix.values(), key=readiness.combined_score) target = ranked[0].competency_id explanation = "All competencies are at COMPETENT or better; polishing the weakest one." else: target = bn["competency_id"] explanation = bn["explanation"]
comp = idx[target] phase = next(p for p in bp.phases if p.phase == comp.phase) exercise = content.generate_exercise(target, difficulty=2, store=store, use_llm=False)
return { "bottleneck": bn, "explanation": explanation, "concept": { "competency_id": target, "name": comp.name, "study": comp.topics, "description": comp.description, "phase_objective": phase.objective, }, "exercise": exercise.model_dump(), "assessment": { "competency_id": target, "kind": "scored_scenario", "description": (f"Timed assessment: answer a fresh {comp.name} scenario without notes; " f"target score 4+/5 to mark this competency COMPETENT."), }, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389"""FastAPI router for Hill Climbing EM (mounted at /api/hillclimb)."""
from __future__ import annotations
from typing import Dict, List, Optional
from fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModel, Field
from sensorflow.hillclimb import adaptive, coach, content, design_lab, evaluate, interviewerfrom sensorflow.hillclimb import readiness as readiness_modfrom sensorflow.hillclimb import simulation as sim_modfrom sensorflow.hillclimb import star as star_modfrom sensorflow.hillclimb.blueprint import (Blueprint, competency_index, load_blueprint, save_blueprint, validate_graph)from sensorflow.hillclimb.models import Attempt, Evidence, UserProfile, get_store, now_iso
router = APIRouter(prefix="/api/hillclimb", tags=["hillclimb"])
# --------------------------------------------------------------- request bodies
class GenerateExerciseRequest(BaseModel): competency_id: str difficulty: int = Field(default=2, ge=1, le=3) seed: Optional[int] = None
class SubmitExerciseRequest(BaseModel): exercise_id: str answer: str user_id: str = "default" as_assessment: bool = False
class StarRequest(BaseModel): text: str user_id: str = "default" save_evidence: bool = True
class DiagnosticStartRequest(BaseModel): user_id: str = "default" seed: int = 11
class DiagnosticAnswerRequest(BaseModel): answer: str
class SimulationStartRequest(BaseModel): user_id: str = "default" scenario_id: str = "inherited_perception_team" seed: int = 42 max_turns: int = 8
class SimulationStepRequest(BaseModel): hypothesis: str intervention_id: str revert_previous: bool = False
class InterviewStartRequest(BaseModel): mode: str = "hybrid" user_id: str = "default" seed: int = 7
class InterviewAnswerRequest(BaseModel): answer: str
class JourneyAdvanceRequest(BaseModel): user_id: str = "default" event: str competency_id: Optional[str] = None passed: Optional[bool] = None
# --------------------------------------------------------------------- profile
@router.get("/profile")def get_profile(user_id: str = "default"): store = get_store() raw = store.get("profiles", user_id) if raw is None: profile = UserProfile(user_id=user_id) store.put("profiles", user_id, profile) return profile return raw
@router.put("/profile")def put_profile(profile: UserProfile): store = get_store() profile.updated_at = now_iso() store.put("profiles", profile.user_id, profile) return profile
# -------------------------------------------------------------------- blueprint
@router.get("/blueprint")def get_blueprint(): return load_blueprint(get_store())
@router.put("/blueprint")def put_blueprint(bp: Blueprint): problems = validate_graph(bp) if problems: raise HTTPException(status_code=400, detail={"problems": problems}) save_blueprint(bp, get_store()) return bp
@router.get("/graph")def get_graph(): bp = load_blueprint(get_store()) return { "nodes": [c.model_dump() for c in bp.competencies], "edges": [{"source": p, "target": c.id} for c in bp.competencies for p in c.prerequisites], "problems": validate_graph(bp), }
# ------------------------------------------------------------------- diagnostic
@router.post("/diagnostic/start")def diagnostic_start(req: DiagnosticStartRequest): dx = adaptive.start_diagnostic(req.user_id, seed=req.seed, store=get_store()) return _diagnostic_view(dx)
@router.post("/diagnostic/{diagnostic_id}/answer")def diagnostic_answer(diagnostic_id: str, req: DiagnosticAnswerRequest): try: dx = adaptive.answer_diagnostic(diagnostic_id, req.answer, store=get_store()) except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) return _diagnostic_view(dx)
@router.get("/diagnostic/{diagnostic_id}")def diagnostic_get(diagnostic_id: str): dx = adaptive.get_diagnostic(diagnostic_id, get_store()) if dx is None: raise HTTPException(status_code=404, detail="diagnostic not found") return _diagnostic_view(dx)
def _diagnostic_view(dx) -> Dict: view = dx.model_dump() if dx.current_exercise_id: ex = content.get_exercise(dx.current_exercise_id, get_store()) view["current_question"] = {"exercise_id": ex.exercise_id, "competency_id": ex.competency_id, "scenario": ex.scenario} return view
# -------------------------------------------------------------------- exercises
@router.post("/exercise/generate")def exercise_generate(req: GenerateExerciseRequest): try: ex = content.generate_exercise(req.competency_id, difficulty=req.difficulty, seed=req.seed, store=get_store()) except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) return ex
@router.get("/exercise/{exercise_id}")def exercise_get(exercise_id: str): ex = content.get_exercise(exercise_id, get_store()) if ex is None: raise HTTPException(status_code=404, detail="exercise not found") return ex
@router.post("/exercise/submit")def exercise_submit(req: SubmitExerciseRequest): store = get_store() ex = content.get_exercise(req.exercise_id, store) if ex is None: raise HTTPException(status_code=404, detail="exercise not found") result = evaluate.evaluate_response(ex, req.answer) feedback = coach.build_feedback(ex, result)
attempt = Attempt(user_id=req.user_id, exercise_id=ex.exercise_id, competency_id=ex.competency_id, kind="exercise", responses={"answer": req.answer}, evaluation=result) readiness_mod.record_attempt(attempt, store)
ev = Evidence(user_id=req.user_id, competency_ids=[ex.competency_id], artifact_type="exercise_attempt", source=f"Exercise {ex.template_id} ({ex.competency_id})", summary=f"Scored {result.score}/5 on a {ex.family} exercise.", quotes=result.evidence[:3], score=float(result.score), confidence=result.confidence, payload={"attempt_id": attempt.attempt_id, "exercise_id": ex.exercise_id}) store.put("evidence", ev.evidence_id, ev)
journey = None if req.as_assessment: try: journey = adaptive.advance_journey(req.user_id, "assessment_result", competency_id=ex.competency_id, passed=result.score >= 4, store=store) except ValueError: journey = None
matrix = readiness_mod.compute_matrix(req.user_id, store) return { "evaluation": result.model_dump(), "coaching": feedback, "attempt_id": attempt.attempt_id, "evidence_id": ev.evidence_id, "linked_tool": ex.linked_tool, "readiness_for_competency": matrix[ex.competency_id].model_dump() if ex.competency_id in matrix else None, "journey": journey.model_dump() if journey else None, }
# ------------------------------------------------------------------------ STAR
@router.post("/star/diagnose")def star_diagnose(req: StarRequest): if not req.text.strip(): raise HTTPException(status_code=400, detail="empty story") return star_mod.diagnose_story(req.text, user_id=req.user_id, save_evidence=req.save_evidence, store=get_store())
# ------------------------------------------------------------------ design lab
@router.get("/design/challenges")def design_challenges(): return {"challenges": [c.model_dump() for c in design_lab.CHALLENGES], "component_types": design_lab.COMPONENT_TYPES}
@router.post("/design/submit")def design_submit(sub: design_lab.DesignSubmission): try: return design_lab.grade_submission(sub, store=get_store()) except ValueError as e: raise HTTPException(status_code=400, detail=str(e))
# ------------------------------------------------------------------ simulation
@router.get("/simulation/catalog")def simulation_catalog(): return {"scenarios": [s.model_dump() for s in sim_mod.SCENARIOS], "interventions": [i.model_dump() for i in sim_mod.INTERVENTIONS], "metrics": sim_mod.METRICS, "inverted_metrics": sorted(sim_mod.INVERTED), "safety_floor": sim_mod.SAFETY_FLOOR, "morale_floor": sim_mod.MORALE_FLOOR}
@router.post("/simulation/start")def simulation_start(req: SimulationStartRequest): return sim_mod.create_simulation(req.user_id, req.scenario_id, req.seed, req.max_turns, store=get_store())
@router.post("/simulation/{sim_id}/step")def simulation_step(sim_id: str, req: SimulationStepRequest): try: return sim_mod.step_simulation(sim_id, req.hypothesis, req.intervention_id, revert_previous=req.revert_previous, store=get_store()) except ValueError as e: raise HTTPException(status_code=400, detail=str(e))
@router.get("/simulation/{sim_id}")def simulation_get(sim_id: str): sim = sim_mod.get_simulation(sim_id, get_store()) if sim is None: raise HTTPException(status_code=404, detail="simulation not found") return sim
# -------------------------------------------------------------------- interview
@router.post("/interview/start")def interview_start(req: InterviewStartRequest): try: return interviewer.start_interview(req.mode, req.user_id, req.seed, store=get_store()) except ValueError as e: raise HTTPException(status_code=400, detail=str(e))
@router.post("/interview/{session_id}/answer")def interview_answer(session_id: str, req: InterviewAnswerRequest): store = get_store() try: session = interviewer.submit_answer(session_id, req.answer, store=store) except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) # answered turns also feed the readiness matrix as knowledge attempts answered = session.turns[-2] attempt = Attempt(user_id=session.user_id, exercise_id=answered.exercise_id, competency_id=answered.competency_id, kind="interview", responses={"answer": req.answer}, evaluation=answered.evaluation) readiness_mod.record_attempt(attempt, store) return session
@router.post("/interview/{session_id}/end")def interview_end(session_id: str): try: return interviewer.end_interview(session_id, store=get_store()) except ValueError as e: raise HTTPException(status_code=400, detail=str(e))
@router.get("/interview/{session_id}")def interview_get(session_id: str): session = interviewer.get_interview(session_id, get_store()) if session is None: raise HTTPException(status_code=404, detail="interview not found") return session
# ------------------------------------------------------- evidence / readiness
@router.get("/evidence")def evidence_list(user_id: str = "default", competency_id: Optional[str] = None): store = get_store() items = store.where("evidence", user_id=user_id) if competency_id: items = [e for e in items if competency_id in e.get("competency_ids", [])] items.sort(key=lambda e: e.get("timestamp", ""), reverse=True) return {"evidence": items, "count": len(items)}
@router.get("/readiness")def readiness_view(user_id: str = "default"): store = get_store() matrix = readiness_mod.compute_matrix(user_id, store) bp = load_blueprint(store) idx = competency_index(bp) rows: List[Dict] = [] for cid, r in matrix.items(): comp = idx[cid] rows.append({**r.model_dump(), "name": comp.name, "phase": comp.phase, "dimension": comp.dimension.value, "prerequisites": comp.prerequisites}) return { "matrix": rows, "dimensions": readiness_mod.dimension_summary(user_id, store, matrix), "bottleneck": readiness_mod.bottleneck_analysis(user_id, store, matrix), }
@router.get("/next-action")def next_action(user_id: str = "default"): return adaptive.next_best_action(user_id, get_store())
# ---------------------------------------------------------------------- journey
@router.get("/journey")def journey_get(user_id: str = "default"): return adaptive.get_journey(user_id, get_store())
@router.post("/journey/advance")def journey_advance(req: JourneyAdvanceRequest): try: return adaptive.advance_journey(req.user_id, req.event, req.competency_id, req.passed, store=get_store()) except ValueError as e: raise HTTPException(status_code=400, detail=str(e))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351"""Hill Climbing EM Blueprint: normalized 4-phase model + competency graph.
IMPORTANT PROVENANCE NOTE: the original blueprint image was not provided.This blueprint is RECONSTRUCTED FROM THE WRITTEN SPEC (source ="reconstructed-from-spec"). It is seeded once into runs/hillclimb/blueprint.jsonand is editable there / via the API — it is data, not hardcoded prose.
Model: Blueprint -> Phase -> {Objective, Topics, Skills, Exercises,Assessments, CompletionCriteria}, plus a flat competency list forming aprerequisite DAG. Every competency is tagged with exactly one dimension(Knowledge / Technical Reasoning / Leadership / Execution) which is trackedseparately and never collapsed into a single score."""
from __future__ import annotations
from typing import Dict, List, Optional, Set
from pydantic import BaseModel, Field
from sensorflow.hillclimb.models import Dimension, Store, get_store
class Competency(BaseModel): id: str name: str phase: int dimension: Dimension description: str = "" prerequisites: List[str] = Field(default_factory=list) topics: List[str] = Field(default_factory=list)
class PhaseSpec(BaseModel): phase: int title: str objective: str topics: List[str] = Field(default_factory=list) skills: List[str] = Field(default_factory=list) exercises: List[str] = Field(default_factory=list) assessments: List[str] = Field(default_factory=list) completion_criteria: List[str] = Field(default_factory=list)
class Blueprint(BaseModel): version: int = 1 source: str = "reconstructed-from-spec" note: str = ( "The original Hill Climbing EM blueprint image was not provided; this " "structure was derived from the written specification and is editable." ) phases: List[PhaseSpec] = Field(default_factory=list) competencies: List[Competency] = Field(default_factory=list)
def _c(cid: str, name: str, phase: int, dim: Dimension, desc: str, prereqs: Optional[List[str]] = None, topics: Optional[List[str]] = None) -> Competency: return Competency(id=cid, name=name, phase=phase, dimension=dim, description=desc, prerequisites=prereqs or [], topics=topics or [])
def seed_blueprint() -> Blueprint: K, T, L, E = (Dimension.KNOWLEDGE, Dimension.TECHNICAL_REASONING, Dimension.LEADERSHIP, Dimension.EXECUTION)
competencies: List[Competency] = [ # ----------------------------------------------------------- Phase 1 _c("p1.precision_recall", "Precision & Recall", 1, K, "Definitions, confusion-matrix intuition, threshold effects, PR curves.", topics=["confusion matrix", "thresholding", "PR curves", "class imbalance"]), _c("p1.iou", "IoU & Localization Quality", 1, K, "2D/3D IoU, localization vs classification errors, matching criteria.", topics=["IoU", "3D IoU", "matching thresholds", "localization error"]), _c("p1.ap_map", "AP / mAP", 1, K, "Average precision, mAP across classes and IoU thresholds, ranking metrics.", ["p1.precision_recall", "p1.iou"], ["AP", "mAP", "interpolated precision", "COCO-style evaluation"]), _c("p1.macro_micro", "Macro vs Micro Averaging", 1, K, "When macro vs micro averaging changes conclusions; per-class safety weighting.", ["p1.precision_recall"], ["macro averaging", "micro averaging", "class weighting"]), _c("p1.statistical_evaluation", "Statistical Evaluation", 1, K, "Confidence intervals, significance, sample-size effects, multiple comparisons.", topics=["confidence intervals", "bootstrap", "significance", "power"]), _c("p1.temporal_effects", "Temporal Effects", 1, T, "Track-level metrics, flicker, latency vs accuracy, temporal consistency.", ["p1.precision_recall"], ["track continuity", "flicker", "latency", "temporal IoU"]), _c("p1.regression_detection", "Regression Detection", 1, T, "Detecting model regressions across versions; offline vs online divergence.", ["p1.precision_recall", "p1.statistical_evaluation"], ["A/B deltas", "shadow mode", "release gates", "offline-online gap"]), _c("p1.cusum", "CUSUM & Drift Detection", 1, T, "Sequential change detection, CUSUM charts, alerting thresholds.", ["p1.statistical_evaluation"], ["CUSUM", "change points", "control charts"]), _c("p1.model_monitoring", "Model Monitoring", 1, T, "Production monitoring design: metrics, slicing, canaries, alert fatigue.", ["p1.regression_detection"], ["canary", "slicing", "data drift", "alerting"]), _c("p1.failure_analysis", "Failure Analysis", 1, T, "Systematic diagnosis of model failures; error taxonomies; root-causing metric gaps.", ["p1.precision_recall", "p1.iou"], ["error taxonomy", "root cause", "failure buckets"]), _c("p1.safety_metrics", "Safety Metrics", 1, K, "Safety-weighted evaluation: severity weighting, VRU recall, worst-case slices.", ["p1.precision_recall"], ["severity weighting", "VRU recall", "worst-case slices"]),
# ----------------------------------------------------------- Phase 2 _c("p2.distributed_fundamentals", "Distributed-Systems Fundamentals", 2, K, "Partitioning, replication, consistency, backpressure, queueing, failure domains.", topics=["partitioning", "replication", "consistency", "backpressure", "queueing theory"]), _c("p2.petabyte_ingestion", "Petabyte-Scale Ingestion", 2, T, "Sensor-data ingestion at PB scale: fan-in, schema, compression, ordering, backfill.", ["p2.distributed_fundamentals"], ["fan-in", "schema evolution", "backfill", "compaction"]), _c("p2.streaming_batch", "Streaming vs Batch Processing", 2, T, "Lambda/kappa tradeoffs, exactly-once semantics, watermarking, late data.", ["p2.distributed_fundamentals"], ["exactly-once", "watermarks", "late data", "kappa"]), _c("p2.storage_design", "Storage Design", 2, T, "Hot/warm/cold tiers, columnar formats, indexing, cost-aware retention.", ["p2.distributed_fundamentals"], ["tiering", "parquet", "indexing", "retention"]), _c("p2.feature_generation", "Feature Generation", 2, T, "Offline/online feature parity, materialization, point-in-time correctness.", ["p2.storage_design"], ["feature store", "point-in-time", "online-offline parity"]), _c("p2.training_infra", "Training Infrastructure", 2, T, "Distributed training, data loading bottlenecks, checkpointing, experiment tracking.", ["p2.distributed_fundamentals"], ["data parallel", "checkpointing", "throughput"]), _c("p2.parallel_inference", "Parallel ML Inference Design", 2, T, "High-throughput serving: batching, sharding, autoscaling, tail latency, GPU economics.", ["p2.distributed_fundamentals"], ["dynamic batching", "sharding", "tail latency", "autoscaling"]), _c("p2.eval_platform", "Evaluation Platform Design", 2, T, "Continuous evaluation at scale: metric cubes, slicing, human-in-the-loop sampling.", ["p1.ap_map", "p2.storage_design"], ["metric aggregation", "sampling", "HITL"]), _c("p2.monitoring_observability", "Monitoring & Observability", 2, T, "SLOs, golden signals, distributed tracing, model+system observability in one plane.", ["p1.model_monitoring", "p2.distributed_fundamentals"], ["SLO", "golden signals", "tracing"]), _c("p2.feedback_loops", "Data Feedback Loops", 2, T, "Closing the loop: mining production failures back into training/eval sets.", ["p2.monitoring_observability", "p2.eval_platform"], ["active learning", "auto-mining", "flywheel"]), _c("p2.reliability_tradeoffs", "Cost / Latency / Fault-Tolerance Tradeoffs", 2, T, "Explicit tradeoff reasoning: capacity math, redundancy cost, degradation modes.", ["p2.distributed_fundamentals"], ["capacity planning", "redundancy", "graceful degradation"]),
# ----------------------------------------------------------- Phase 3 _c("p3.roadmap_ambiguity", "Roadmap from Ambiguity", 3, E, "Turning ambiguous goals into a sequenced, measurable roadmap.", topics=["problem framing", "sequencing", "milestones", "success metrics"]), _c("p3.cross_functional", "Cross-Functional Leadership", 3, L, "Leading across PM, research, ops, safety; alignment without authority.", topics=["alignment", "stakeholders", "communication cadence"]), _c("p3.technical_strategy", "Technical Strategy", 3, E, "Multi-quarter technical bets, platform vs product tension, build/buy.", ["p3.roadmap_ambiguity"], ["technical bets", "platform investment", "build vs buy"]), _c("p3.org_influence", "Organizational Influence", 3, L, "Influencing beyond your team: writing, reviews, coalition building.", ["p3.cross_functional"], ["influence", "writing", "coalitions"]), _c("p3.performance_management", "Performance Management", 3, L, "Expectations, feedback, underperformance, promotion cases.", topics=["expectations", "feedback", "PIP", "promotion"]), _c("p3.mentorship", "Mentorship & Growth", 3, L, "Growing engineers and leads; delegation as a growth tool.", topics=["coaching", "delegation", "growth plans"]), _c("p3.hiring", "Hiring & Team Building", 3, L, "Sourcing, calibration, closing, onboarding, team shape.", topics=["calibration", "closing", "onboarding", "team topology"]), _c("p3.conflict_resolution", "Conflict Resolution", 3, L, "Surfacing and resolving disagreement; disagree-and-commit done honestly.", topics=["mediation", "escalation", "disagree and commit"]), _c("p3.prioritization_risk", "Prioritization & Risk", 3, E, "Ruthless prioritization under constraints; explicit risk registers.", topics=["prioritization", "risk register", "cut lines"]), _c("p3.safety_culture", "Safety Ownership", 3, E, "Safety as a first-class engineering constraint; incident culture.", ["p1.safety_metrics"], ["incident review", "safety cases", "blameless postmortems"]), _c("p3.closed_loop_execution", "Closed-Loop Execution", 3, E, "Plan → execute → measure → correct; commitments that land.", ["p3.prioritization_risk"], ["execution cadence", "measurement", "course correction"]), _c("p3.business_impact", "Business Impact", 3, E, "Connecting engineering work to business/customer outcomes with numbers.", topics=["impact quantification", "cost of delay", "customer outcomes"]),
# ----------------------------------------------------------- Phase 4 _c("p4.hill_climbing", "Multi-Objective Hill Climbing", 4, E, "Iteratively improving a system under competing objectives (performance, safety, " "cost, velocity, morale) with hypotheses, measurements, and keep/reject decisions.", ["p2.reliability_tradeoffs", "p3.prioritization_risk", "p3.closed_loop_execution", "p1.model_monitoring"], ["multi-objective optimization", "hypothesis testing", "local optima", "hard constraints"]), ]
phases = [ PhaseSpec( phase=1, title="Technical / ML Depth", objective="Rebuild deep, interview-grade fluency in ML evaluation, monitoring, and failure analysis for perception systems.", topics=["precision/recall", "IoU", "AP/mAP", "macro vs micro", "temporal effects", "regression detection", "CUSUM", "statistical evaluation", "model monitoring", "failure analysis", "safety metrics"], skills=["explain metric tradeoffs from first principles", "diagnose offline/online divergence", "design monitoring for a perception model", "quantify uncertainty in evaluations"], exercises=["metric-diagnosis scenarios (offline +5% / shadow −2%)", "CUSUM drift drills", "monitoring-design critiques", "failure-taxonomy construction"], assessments=["adaptive diagnostic", "scenario exercises scored 1-5 against rubrics"], completion_criteria=["all Phase-1 competencies at COMPETENT+", "at least one STRONG in regression detection or failure analysis"], ), PhaseSpec( phase=2, title="Large-Scale System Design", objective="Design petabyte-scale ML data/serving/evaluation systems with explicit capacity math and tradeoff reasoning.", topics=["petabyte ingestion", "streaming/batch", "storage", "feature generation", "training", "parallel inference", "evaluation platforms", "monitoring", "feedback loops", "reliability", "observability", "cost/latency/fault-tolerance tradeoffs"], skills=["propose an end-to-end architecture", "state capacity math", "identify SPOFs", "close data feedback loops", "argue tradeoffs quantitatively"], exercises=["design-lab challenges with typed component graphs + rationales"], assessments=["design-lab rubric grading per dimension"], completion_criteria=["two design-lab challenges at COMPETENT+", "no missing-stage or feedback-loop gaps on the final submission"], ), PhaseSpec( phase=3, title="Execution & People Management", objective="Evidence leadership and execution with quantified STAR stories mapped to EM competencies.", topics=["roadmap from ambiguity", "cross-functional leadership", "technical strategy", "org influence", "performance management", "mentorship", "hiring", "conflict resolution", "prioritization", "risk", "safety", "closed-loop execution", "business impact"], skills=["tell diagnosable STAR stories", "quantify outcomes", "show personal ownership", "demonstrate influence and disagreement handling"], exercises=["STAR Story Box diagnosis and strengthening loops"], assessments=["claim-vs-evidence checks", "per-component STAR diagnosis", "story-to-competency evidence mapping"], completion_criteria=["6+ stories saved as evidence covering 8+ Phase-3 competencies", "no unquantified-claim flags on the final story set"], ), PhaseSpec( phase=4, title="Simulation / Hill-Climbing Exercise", objective="Apply everything in a stateful multi-objective simulation: hypothesis → intervention → measure → keep/reject.", topics=["multi-objective optimization under competing constraints", "hard safety floors", "second-order consequences", "delayed effects"], skills=["form falsifiable hypotheses", "balance competing objectives", "respond to incidents", "debrief decisions into evidence"], exercises=["seeded scenario: inherited perception team, rising regression rate, exec pressure"], assessments=["simulation debrief mapping decisions to competency evidence"], completion_criteria=["complete a simulation with balanced score above threshold and no unresolved safety incident"], ), ]
return Blueprint(phases=phases, competencies=competencies)
# ------------------------------------------------------------------ storage
BLUEPRINT_KEY = "active"
def load_blueprint(store: Optional[Store] = None) -> Blueprint: store = store or get_store() raw = store.get("blueprint", BLUEPRINT_KEY) if raw: try: return Blueprint(**raw) except Exception: pass bp = seed_blueprint() store.put("blueprint", BLUEPRINT_KEY, bp) return bp
def save_blueprint(bp: Blueprint, store: Optional[Store] = None) -> None: (store or get_store()).put("blueprint", BLUEPRINT_KEY, bp)
# ------------------------------------------------------------------ graph ops
def competency_index(bp: Blueprint) -> Dict[str, Competency]: return {c.id: c for c in bp.competencies}
def validate_graph(bp: Blueprint) -> List[str]: """Return a list of integrity problems (empty = healthy).""" problems: List[str] = [] idx = competency_index(bp) for c in bp.competencies: for p in c.prerequisites: if p not in idx: problems.append(f"{c.id}: unknown prerequisite '{p}'") # cycle detection (DFS) WHITE, GRAY, BLACK = 0, 1, 2 color = {cid: WHITE for cid in idx}
def dfs(cid: str, stack: List[str]) -> None: color[cid] = GRAY for p in idx[cid].prerequisites: if p not in idx: continue if color[p] == GRAY: problems.append("prerequisite cycle: " + " -> ".join(stack + [cid, p])) elif color[p] == WHITE: dfs(p, stack + [cid]) color[cid] = BLACK
for cid in idx: if color[cid] == WHITE: dfs(cid, []) return problems
def downstream_map(bp: Blueprint) -> Dict[str, Set[str]]: """competency_id -> set of competencies that (transitively) depend on it.""" idx = competency_index(bp) direct: Dict[str, Set[str]] = {cid: set() for cid in idx} for c in bp.competencies: for p in c.prerequisites: if p in direct: direct[p].add(c.id)
result: Dict[str, Set[str]] = {}
def collect(cid: str) -> Set[str]: if cid in result: return result[cid] acc: Set[str] = set() for d in direct[cid]: acc.add(d) acc |= collect(d) result[cid] = acc return acc
for cid in idx: collect(cid) return result
# Display dimensions used by the dashboard readiness bars. Distinct from the# per-competency Dimension tag (which is never collapsed); this is a UX grouping.DISPLAY_DIMENSIONS = ["Technical Depth", "System Design", "Execution", "Leadership", "Communication", "Safety/Risk"]
SAFETY_COMPETENCIES = {"p1.safety_metrics", "p3.safety_culture"}
def display_dimensions_for(c: Competency) -> List[str]: dims: List[str] = [] if c.id in SAFETY_COMPETENCIES: dims.append("Safety/Risk") if c.phase == 1: dims.append("Technical Depth") elif c.phase == 2: dims.append("System Design") elif c.phase == 3: dims.append("Leadership" if c.dimension == Dimension.LEADERSHIP else "Execution") if c.id in ("p3.cross_functional", "p3.org_influence"): dims.append("Communication") elif c.phase == 4: dims.append("Execution") return dims123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""Coaching feedback generated from rubric gaps — specific, never generic.
Every feedback line points at a concrete gap between the answer and theexercise rubric ("your answer establishes the technical problem but notpersonal ownership; identify the decision you made..."), assembled from whatthe evaluation actually found."""
from __future__ import annotations
from typing import List
from sensorflow.hillclimb.content import Exercisefrom sensorflow.hillclimb.models import EvaluationResult
_GAP_TEMPLATES = { "quantified": ( "Nothing in your answer is quantified. Interviewers discount unmeasured claims — add the " "numbers you'd actually use: a threshold, a capacity figure, or a before/after comparison." ), "tradeoff": ( "You never state what your approach sacrifices. Name the explicit tradeoff (what gets worse, " "by how much, and why that's acceptable) — one honest tradeoff is worth three benefits." ),}
def _keyword_gap_line(criterion: str, keywords: List[str]) -> str: hint = ", ".join(f"'{k}'" for k in keywords[:3]) if keywords else criterion.lower() return (f"Missing: {criterion.lower()}. Work it in explicitly — an evaluator is scanning for " f"substance in the territory of {hint}.")
def build_feedback(exercise: Exercise, result: EvaluationResult) -> str: lines: List[str] = []
if result.strengths: established = "; ".join(s.split(" — ")[0].lower() for s in result.strengths[:3]) lines.append(f"What your answer establishes: {established}.") else: lines.append( "Your answer does not yet engage any rubric criterion for this exercise — the evaluator " "found no quotable evidence. Re-read the scenario and answer its specific question." )
covered_criteria = {s.split(" — ")[0] for s in result.strengths} for item in exercise.evaluation_rubric: if item.criterion in covered_criteria: continue if item.check in _GAP_TEMPLATES: lines.append(_GAP_TEMPLATES[item.check]) else: lines.append(_keyword_gap_line(item.criterion, item.keywords))
for m in result.misconceptions: lines.append(f"Watch out — likely misconception: {m}")
if result.score >= 4: lines.append("This is a strong answer; the remaining gaps above are what separates 'strong' from 'expert'.") return "\n".join(lines[:9])
def recommended_action(exercise: Exercise, result: EvaluationResult) -> str: comp = exercise.competency_id if result.score <= 2: return (f"Review the underlying concepts for {comp}, then retry a fresh variant of this " f"exercise (a structurally different scenario will be generated — memorizing this one won't help).") if result.score == 3: return (f"You have the shape of the answer. Practice one more {comp} exercise focusing on the " f"missing criteria listed above, then take the assessment.") return (f"Strong. Escalate: take a difficulty-{min(3, exercise.difficulty + 1)} exercise for {comp} " f"or move to the next competency in your path.")
def pick_follow_up(exercise: Exercise, result: EvaluationResult) -> str: if not exercise.follow_up_questions: return "" # Weak answers get the earlier (more fundamental) probes; strong answers # get the later (escalation) probes. idx = 0 if result.score <= 2 else min(len(exercise.follow_up_questions) - 1, result.score - 2) return exercise.follow_up_questions[idx]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441"""Exercise/content generation: parameterized, seeded scenario templates.
Every competency can generate exercises of the required shape:{competency_id, difficulty, prerequisites, scenario, expected_reasoning, evaluation_rubric, common_failure_modes, follow_up_questions}
Retry with a different seed produces a STRUCTURALLY DIFFERENT problem for thesame competency (different template variant and/or slot values) so users can'tmemorize by repetition. When an LLM is available it may enrich the scenariotext, but the rubric/reasoning skeleton is always the deterministic templateoutput (the rubric is what evaluation trusts)."""
from __future__ import annotations
import randomfrom typing import Dict, List, Optional
from pydantic import BaseModel, Field
from sensorflow.hillclimb import llmfrom sensorflow.hillclimb.blueprint import competency_index, load_blueprintfrom sensorflow.hillclimb.models import Store, get_store, new_id
class RubricItem(BaseModel): criterion: str # check: "keywords" (concept coverage), "quantified" (numeric evidence), # "tradeoff" (explicit tradeoff language). Non-keyword checks are scored # structurally by the evaluator. check: str = "keywords" keywords: List[str] = Field(default_factory=list) weight: float = 1.0
class Exercise(BaseModel): exercise_id: str = Field(default_factory=lambda: new_id("ex")) competency_id: str difficulty: int = 2 # 1=warmup 2=core 3=stretch prerequisites: List[str] = Field(default_factory=list) scenario: str expected_reasoning: List[str] = Field(default_factory=list) evaluation_rubric: List[RubricItem] = Field(default_factory=list) common_failure_modes: List[str] = Field(default_factory=list) follow_up_questions: List[str] = Field(default_factory=list) template_id: str = "generic" seed: int = 0 family: str = "generic" linked_tool: Optional[Dict] = None
QUANT_RUBRIC = RubricItem(criterion="Quantifies claims with numbers, thresholds, or before/after comparisons", check="quantified", weight=1.0)TRADEOFF_RUBRIC = RubricItem(criterion="States explicit tradeoffs and what is sacrificed by the chosen approach", check="tradeoff", weight=1.0)
# ------------------------------------------------------------- template bank
def _offline_shadow(rng: random.Random, difficulty: int) -> Dict: """Canonical Phase-1 family: offline metric up, shadow deployment down.""" offline_gain = rng.choice([3, 4, 5, 6, 7]) shadow_drop = rng.choice([1, 2, 3, 4]) metric = rng.choice(["mAP@0.5", "pedestrian recall", "3D IoU pass-rate", "F1 on cyclists"]) model = rng.choice(["perception-v12", "detector-nightly", "fusion-rc3", "tracker-v8"]) context = rng.choice([ "after a training-data refresh that added 40k night-time frames", "after switching the loss to a focal variant", "after a new auto-labeling vendor batch landed", "with no intentional model change (dependency bump only)", ]) variant = rng.choice([ (f"Your team ships {model}. Offline evaluation shows {metric} improved by +{offline_gain}% " f"{context}. But in a one-week shadow deployment against live traffic, the same metric " f"is DOWN {shadow_drop}% versus the current production model. Leadership asks whether to ship. " f"Diagnose the divergence: enumerate the possible causes, how you would distinguish them, " f"and what you would do before making a ship/no-ship call."), (f"A staff engineer reports: '{model} gained +{offline_gain}% {metric} offline {context}, " f"but shadow-mode monitoring shows a {shadow_drop}% regression.' The launch review is tomorrow. " f"Walk through your differential diagnosis of the offline/online gap and the concrete " f"experiments that would confirm or eliminate each hypothesis."), ]) return { "scenario": variant, "expected_reasoning": [ "Metric definition / computation mismatch between offline eval and shadow monitoring", "Distribution shift between the offline eval set and live traffic", "Sampling bias in how the offline set (or the shadow sample) was constructed", "Feature / training-serving skew in the input pipeline", "Serving-stack mismatch (preprocessing, quantization, version drift)", "Statistical noise — is the shadow delta even significant?", "A true regression the offline set cannot see", "A verification plan: slice analysis, matched-sample re-scoring, significance testing", ], "rubric": [ RubricItem(criterion="Considers metric definition / computation mismatch", keywords=["metric definition", "computed differently", "matching threshold", "iou threshold", "different metric", "definition mismatch", "metric error", "same metric", "measurement mismatch"]), RubricItem(criterion="Considers distribution shift between eval set and live traffic", keywords=["distribution shift", "domain shift", "drift", "live traffic differs", "population", "distribution change", "data shift"]), RubricItem(criterion="Considers sampling bias in eval or shadow sample", keywords=["sampling bias", "biased sample", "not representative", "selection bias", "sample size", "how the eval set was built", "oversampl", "undersampl"]), RubricItem(criterion="Considers feature / training-serving skew", keywords=["feature skew", "training-serving skew", "training serving skew", "feature pipeline", "feature mismatch", "stale feature"]), RubricItem(criterion="Considers serving-stack mismatch (preprocessing/quantization/versions)", keywords=["serving", "preprocessing", "quantization", "version mismatch", "deployment stack", "runtime", "inference stack", "model artifact"]), RubricItem(criterion="Questions statistical significance / noise before reacting", keywords=["noise", "significan", "confidence interval", "variance", "sample size", "error bars", "statistical"]), RubricItem(criterion="Keeps 'true regression' on the table and says how to confirm it", keywords=["true regression", "real regression", "genuine regression", "actually worse", "genuinely regressed"]), RubricItem(criterion="Proposes a concrete verification plan (slices, matched re-scoring, A/B)", keywords=["slice", "re-run", "rerun", "a/b", "matched", "re-score", "rescore", "experiment", "holdout", "ablat", "bisect"]), QUANT_RUBRIC, TRADEOFF_RUBRIC, ], "failure_modes": [ "Jumping straight to 'the model is worse' without checking the measurement itself", "Ignoring statistical significance of the shadow delta", "Treating offline eval as ground truth for live behavior", "No concrete verification experiment — only speculation", ], "follow_ups": [ "Your offline set is auto-labeled. How does that change your diagnosis ordering?", f"The {shadow_drop}% shadow drop is concentrated in night-time frames. What does that tell you?", "You have 48 hours before the launch review. Which single experiment do you run and why?", "How would you redesign the evaluation pipeline so this class of divergence is caught automatically?", ], "linked_tool": { "label": "Practice this diagnosis with the live RCA workbench", "page": "rca", "api": "/api/rca", }, }
def _cusum_drift(rng: random.Random, difficulty: int) -> Dict: window = rng.choice([7, 14, 30]) magnitude = rng.choice([0.5, 1.0, 2.0]) signal = rng.choice(["false-positive rate on static objects", "track fragmentation rate", "mean confidence on pedestrians", "per-frame latency p99"]) return { "scenario": (f"Production monitoring shows {signal} creeping up roughly {magnitude}% over the last " f"{window} days, but every daily comparison against the previous day looks 'within noise'. " f"Design a sequential change-detection approach (e.g. CUSUM) for this signal: how it works, " f"how you set thresholds, and how you avoid alert fatigue."), "expected_reasoning": [ "Why daily pairwise comparisons miss slow drift; cumulative evidence", "CUSUM mechanics: cumulative sum of deviations from a reference mean, decision interval h, slack k", "Threshold selection as a tradeoff between detection delay and false-alarm rate", "Baseline/reference maintenance and reset policy after confirmed changes", "Operational design: who gets paged, runbooks, alert budgets", ], "rubric": [ RubricItem(criterion="Explains why point-in-time comparisons miss slow drift", keywords=["slow drift", "cumulative", "accumulate", "small shifts", "gradual"]), RubricItem(criterion="Describes CUSUM mechanics (reference mean, slack, decision interval)", keywords=["cusum", "cumulative sum", "reference mean", "slack", "decision interval", "control chart", "change point"]), RubricItem(criterion="Treats threshold selection as detection-delay vs false-alarm tradeoff", keywords=["false alarm", "detection delay", "threshold", "arl", "sensitivity"]), RubricItem(criterion="Covers baseline maintenance / reset after confirmed change", keywords=["baseline", "reset", "re-baseline", "reference update", "recalibrat"]), RubricItem(criterion="Addresses alert fatigue and operational response", keywords=["alert fatigue", "pager", "runbook", "on-call", "alert budget", "triage"]), QUANT_RUBRIC, TRADEOFF_RUBRIC, ], "failure_modes": [ "Proposing a fixed threshold on the raw metric (misses slow drift entirely)", "No false-alarm analysis", "No plan for what happens after an alert fires", ], "follow_ups": [ "The signal is seasonal (weekday/weekend). How do you adapt the detector?", "How would you validate the detector before trusting it in production?", ], "linked_tool": None, }
def _parallel_inference(rng: random.Random, difficulty: int) -> Dict: qps = rng.choice([2000, 5000, 20000, 50000]) latency = rng.choice([50, 100, 200]) model_size = rng.choice(["300M-param detector", "1.2B-param fusion model", "ensemble of 3 detectors"]) return { "scenario": (f"Design the serving layer for a {model_size} that must handle {qps} inferences/sec " f"with a p99 latency budget of {latency}ms. GPUs are expensive and the fleet must survive " f"a zone outage. Walk through batching, sharding, autoscaling, and the capacity math."), "expected_reasoning": [ "Dynamic batching and its latency/throughput tradeoff", "Model/tensor sharding vs replica scaling", "Capacity math: per-GPU throughput → replica count → headroom", "Tail latency: queueing, hedged requests, timeouts, degradation modes", "Zone-redundant deployment and the cost of redundancy", ], "rubric": [ RubricItem(criterion="Uses dynamic batching with an explicit latency cost", keywords=["batch", "batching", "batch size", "queue delay"]), RubricItem(criterion="Distinguishes replica scaling from model sharding", keywords=["shard", "replica", "tensor parallel", "scale out", "horizontal"]), RubricItem(criterion="Shows capacity math (per-GPU throughput → fleet size → headroom)", keywords=["capacity", "headroom", "per-gpu", "throughput per", "utilization", "provision"]), RubricItem(criterion="Handles tail latency (queueing, hedging, timeouts, sheddable load)", keywords=["p99", "tail", "hedg", "timeout", "queue", "shed", "degrade"]), RubricItem(criterion="Designs for zone failure with explicit redundancy cost", keywords=["zone", "redundan", "failover", "outage", "multi-region", "n+1"]), QUANT_RUBRIC, TRADEOFF_RUBRIC, ], "failure_modes": [ "No numbers: hand-wavy 'we autoscale' without capacity math", "Ignoring tail latency, quoting only mean latency", "Redundancy without acknowledging its cost", ], "follow_ups": [ "Traffic doubles for 10 minutes every day at rush hour. Buy capacity or shed load — argue it.", "The model team wants to ship a 2x bigger model next quarter. What breaks first?", ], "linked_tool": None, }
def _leadership_scenario(rng: random.Random, difficulty: int, comp_name: str, topics: List[str]) -> Dict: tension = rng.choice([ "your strongest senior engineer openly disagrees with the plan in team channels", "the PM has promised the feature to a customer for a date engineering never agreed to", "two of your engineers each believe they own the same critical component", "a partner team's reorg just removed the people you depended on", "an underperforming engineer is well-liked and nobody has told them the truth", ]) stake = rng.choice(["a safety-critical launch", "the quarter's headline OKR", "a customer escalation with exec visibility", "your team's on-call health"]) return { "scenario": (f"You are the EM of a perception team. In the middle of {stake}, {tension}. " f"This exercise targets '{comp_name}'. Describe concretely how you handle it: the " f"decision you make, how you communicate it, and how you measure whether it worked. " f"Ground your answer in a real experience if you have one."), "expected_reasoning": [ "Names the actual decision and owns it personally (not 'we would')", "Considers and rejects at least one alternative", "Addresses the people dimension explicitly (conversations, expectations)", "Defines a measurable outcome and a follow-through check", "Manages risk to the in-flight commitment", ], "rubric": [ RubricItem(criterion="Personal ownership: states the decision THEY made", keywords=["i decided", "i chose", "my decision", "i told", "i set", "i asked", "i pushed", "i made the call", "i took"]), RubricItem(criterion="Considers alternatives and why they were rejected", keywords=["alternative", "instead of", "rejected", "considered", "option", "could have", "chose over"]), RubricItem(criterion="Handles the people/communication dimension explicitly", keywords=["1:1", "one-on-one", "conversation", "feedback", "expectations", "communicat", "listen", "align", "stakeholder"]), RubricItem(criterion="Defines a measurable outcome and follow-through", keywords=["measure", "outcome", "result", "metric", "follow up", "follow-up", "checked back", "retro"]), RubricItem(criterion=f"Engages the specific competency ({', '.join(topics[:3])})", keywords=[t.lower() for t in topics] or ["leadership"]), QUANT_RUBRIC, TRADEOFF_RUBRIC, ], "failure_modes": [ "Abstract 'best practices' answer with no personal decision", "No measurable result — the story ends at the action", "Avoiding the uncomfortable conversation entirely", ], "follow_ups": [ "What would you have done if your first approach failed?", "What did this cost you, and was it worth it?", "How did you know your intervention actually caused the improvement?", ], "linked_tool": None, }
def _hill_climb_concept(rng: random.Random, difficulty: int) -> Dict: objectives = rng.sample(["detection quality", "safety incident rate", "infra cost", "team velocity", "on-call health", "customer-visible latency"], 3) return { "scenario": (f"You inherit a system where {objectives[0]}, {objectives[1]}, and {objectives[2]} " f"are all trending the wrong way, and improving any one of them naively damages another. " f"Describe your hill-climbing approach: how you pick the next intervention, how you " f"measure it, when you keep vs revert, and how you avoid local optima and hard-constraint " f"violations (e.g. safety floors)."), "expected_reasoning": [ "Defines a balanced multi-objective view with hard constraints, not a single collapsed score", "One intervention at a time with a hypothesis and a measurement window", "Keep/revert discipline based on measured effect, not sunk cost", "Watches second-order and delayed consequences", "Escapes local optima with occasional larger structural bets", ], "rubric": [ RubricItem(criterion="Frames it as multi-objective with hard floors/constraints", keywords=["multi-objective", "hard constraint", "floor", "threshold", "guardrail", "never below", "competing objectives"]), RubricItem(criterion="Hypothesis-driven single-change iterations", keywords=["hypothesis", "one change", "single intervention", "iterate", "experiment"]), RubricItem(criterion="Keep/revert discipline from measurement", keywords=["revert", "keep", "roll back", "rollback", "measured effect", "kill"]), RubricItem(criterion="Considers delayed and second-order effects", keywords=["second-order", "delayed", "lag", "downstream effect", "unintended"]), RubricItem(criterion="Has a strategy for local optima", keywords=["local optim", "plateau", "bigger bet", "structural", "step change", "restart"]), QUANT_RUBRIC, TRADEOFF_RUBRIC, ], "failure_modes": [ "Optimizing a single collapsed score and violating a safety floor", "Changing many things at once — no attribution", "Never reverting anything", ], "follow_ups": [ "Your last three interventions all measured flat. What now?", "An exec demands you optimize velocity only for one quarter. How do you respond?", ], "linked_tool": None, }
def _generic_technical(rng: random.Random, difficulty: int, comp_name: str, topics: List[str]) -> Dict: scale = rng.choice(["a fleet of 500 test vehicles", "a petabyte-scale sensor lake", "a 40-engineer perception org", "a nightly retraining pipeline"]) angle = rng.choice(["design it from scratch", "critique and fix the current design", "explain it to a new senior hire, including the sharp edges", "defend it in an architecture review under hostile questioning"]) topic_str = ", ".join(topics[:4]) if topics else comp_name return { "scenario": (f"In the context of {scale}, {angle}: '{comp_name}' ({topic_str}). " f"Be specific about mechanisms, numbers, failure modes, and tradeoffs — " f"not just terminology."), "expected_reasoning": [ f"Correct working definitions of {topic_str}", "Mechanisms explained causally, not just named", "Concrete failure modes and how to detect them", "Quantified reasoning where applicable", "Explicit tradeoffs", ], "rubric": [ RubricItem(criterion=f"Covers the core concepts ({topic_str})", keywords=[t.lower() for t in topics] or [comp_name.lower()], weight=2.0), RubricItem(criterion="Explains mechanisms causally (because/therefore/so that)", keywords=["because", "therefore", "which means", "so that", "leads to", "causes"]), RubricItem(criterion="Names concrete failure modes and their detection", keywords=["fail", "failure mode", "breaks", "degrade", "detect", "edge case"]), QUANT_RUBRIC, TRADEOFF_RUBRIC, ], "failure_modes": [ "Terminology name-dropping without causal mechanism", "No failure modes considered", "No numbers anywhere", ], "follow_ups": [ f"Which part of {comp_name} do practitioners most often get wrong, and why?", "Give a concrete number or threshold you'd use, and defend it.", ], "linked_tool": None, }
FAMILY_BUILDERS = { "offline_shadow": _offline_shadow, "cusum_drift": _cusum_drift, "parallel_inference": _parallel_inference, "hill_climb": _hill_climb_concept,}
# Competency → template family. Anything unlisted uses the generic builder# (leadership competencies use the leadership scenario builder).COMPETENCY_FAMILY = { "p1.regression_detection": "offline_shadow", "p1.failure_analysis": "offline_shadow", "p1.cusum": "cusum_drift", "p1.model_monitoring": "cusum_drift", "p2.parallel_inference": "parallel_inference", "p4.hill_climbing": "hill_climb",}
def generate_exercise(competency_id: str, difficulty: int = 2, seed: Optional[int] = None, store: Optional[Store] = None, use_llm: bool = True) -> Exercise: store = store or get_store() bp = load_blueprint(store) idx = competency_index(bp) if competency_id not in idx: raise ValueError(f"unknown competency '{competency_id}'") comp = idx[competency_id] if seed is None: seed = random.SystemRandom().randrange(1, 10 ** 9) rng = random.Random(seed)
family = COMPETENCY_FAMILY.get(competency_id) if family: built = FAMILY_BUILDERS[family](rng, difficulty) elif comp.phase == 3: family = "leadership_scenario" built = _leadership_scenario(rng, difficulty, comp.name, comp.topics) else: family = "generic_technical" built = _generic_technical(rng, difficulty, comp.name, comp.topics)
scenario = built["scenario"] # Optional LLM enrichment of the scenario prose only — the rubric and # expected reasoning stay deterministic (they drive scoring). if use_llm and llm.llm_enabled(): enriched = llm.generate_text( "Rewrite this interview exercise scenario to be vivid and specific in <=120 words. " "Do not change any numbers, do not add new requirements, keep second person:\n\n" + scenario, timeout=10.0, ) if enriched and len(enriched) > 40: scenario = enriched.strip()
ex = Exercise( competency_id=competency_id, difficulty=difficulty, prerequisites=comp.prerequisites, scenario=scenario, expected_reasoning=built["expected_reasoning"], evaluation_rubric=built["rubric"], common_failure_modes=built["failure_modes"], follow_up_questions=built["follow_ups"], template_id=f"{family}#{seed % 1000}", seed=seed, family=family, linked_tool=built.get("linked_tool"), ) store.put("exercises", ex.exercise_id, ex) return ex
def get_exercise(exercise_id: str, store: Optional[Store] = None) -> Optional[Exercise]: raw = (store or get_store()).get("exercises", exercise_id) return Exercise(**raw) if raw else None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331"""System-design lab: typed component-graph challenges with a rule-based grader.
The user submits a graph of typed components (source/ingestion/stream/batch/storage/feature/training/inference/eval/monitoring/feedback) plus a writtenrationale per key decision. The grader checks: required stages present, noorphan components, feedback-loop closure, single-point-of-failure detection,stated capacity math, and rationale coverage of {scalability, reliability,latency, cost, observability, failure handling, tradeoffs}."""
from __future__ import annotations
from typing import Dict, List, Optional, Set
from pydantic import BaseModel, Field
from sensorflow.hillclimb.evaluate import QUANT_RE, TRADEOFF_MARKERSfrom sensorflow.hillclimb.models import Evidence, Store, get_store, new_id
COMPONENT_TYPES = ["source", "ingestion", "stream", "batch", "storage", "feature", "training", "inference", "eval", "monitoring", "feedback"]
class Component(BaseModel): id: str type: str name: str = "" note: str = "" # capacity/annotation text, counts toward capacity math
class Edge(BaseModel): source: str target: str
class DesignSubmission(BaseModel): challenge_id: str user_id: str = "default" components: List[Component] edges: List[Edge] rationales: Dict[str, str] = Field(default_factory=dict)
class Challenge(BaseModel): challenge_id: str title: str brief: str # any-of groups: each inner list is satisfied by one present type required_stages: List[List[str]] key_decisions: List[str] competency_ids: List[str] requires_feedback_loop: bool = False
CHALLENGES: List[Challenge] = [ Challenge( challenge_id="petabyte_ingestion", title="Petabyte-Scale Sensor Ingestion", brief=("Design ingestion for a fleet producing ~2 PB/week of camera+LiDAR data. " "Data must land queryable within 24h, survive a regional outage, and support " "backfill after schema changes. State your capacity math."), required_stages=[["source"], ["ingestion"], ["stream", "batch"], ["storage"], ["monitoring"]], key_decisions=["Partitioning & ordering strategy", "Hot/cold storage tiering", "Backfill / schema-evolution handling", "Failure & retry semantics"], competency_ids=["p2.petabyte_ingestion", "p2.storage_design", "p2.streaming_batch"], ), Challenge( challenge_id="parallel_inference", title="Parallel Inference Serving", brief=("Serve a perception model at 20k inferences/sec with a 100ms p99 budget on a " "GPU fleet that must survive a zone outage. Show batching, sharding, autoscaling " "and the capacity math behind your replica count."), required_stages=[["source"], ["inference"], ["monitoring"], ["storage", "feature"]], key_decisions=["Batching vs latency budget", "Replica/shard topology", "Autoscaling signal & headroom", "Degradation mode under overload"], competency_ids=["p2.parallel_inference", "p2.reliability_tradeoffs"], ), Challenge( challenge_id="eval_platform", title="Continuous Evaluation Platform", brief=("Design an evaluation platform that scores every model build against 500M frames, " "supports slice-level metrics, human-in-the-loop sampling, and blocks bad releases. " "Explain where metrics are aggregated and how results stay reproducible."), required_stages=[["source"], ["storage"], ["eval"], ["monitoring"], ["batch", "stream"]], key_decisions=["Metric aggregation & storage layout", "Sampling strategy for human review", "Release-gate policy", "Reproducibility / lineage"], competency_ids=["p2.eval_platform", "p1.statistical_evaluation"], ), Challenge( challenge_id="feedback_loop", title="Monitoring & Data Feedback Loop", brief=("Close the loop: production monitoring detects failure patterns, mines the " "corresponding frames, routes them through labeling into the next training set, " "and verifies the fix shipped. The loop must be a real cycle, with monitoring on " "the loop itself."), required_stages=[["source"], ["inference"], ["monitoring"], ["feedback"], ["training"], ["eval"]], key_decisions=["Failure-mining trigger criteria", "Label routing & quality control", "Loop latency (failure → fixed model)", "How you detect the loop itself breaking"], competency_ids=["p2.feedback_loops", "p2.monitoring_observability", "p1.model_monitoring"], requires_feedback_loop=True, ),]
RATIONALE_DIMENSIONS: Dict[str, List[str]] = { "scalability": ["scal", "shard", "partition", "horizontal", "throughput", "parallel", "fan-out", "fan-in"], "reliability": ["replic", "redundan", "failover", "retry", "durab", "availab", "quorum", "multi-region", "zone"], "latency": ["latency", "p99", "p95", "real-time", "ms", "tail", "deadline", "sla"], "cost": ["cost", "$", "budget", "cheap", "spend", "tier", "spot", "utilization", "expensive"], "observability": ["observ", "monitor", "metric", "trace", "log", "alert", "dashboard", "slo"], "failure_handling": ["failure", "fallback", "degrad", "dead letter", "backpressure", "circuit", "poison", "outage", "recover", "replay"], "tradeoffs": TRADEOFF_MARKERS,}
class DimensionGrade(BaseModel): dimension: str score: int = Field(ge=0, le=5) gaps: List[str] = Field(default_factory=list) evidence: List[str] = Field(default_factory=list)
class StructuralChecks(BaseModel): missing_stages: List[str] = Field(default_factory=list) orphan_components: List[str] = Field(default_factory=list) feedback_loop_closed: bool = False feedback_loop_required: bool = False single_points_of_failure: List[str] = Field(default_factory=list) capacity_math_found: bool = False capacity_quotes: List[str] = Field(default_factory=list)
class DesignGrade(BaseModel): grade_id: str = Field(default_factory=lambda: new_id("dg")) challenge_id: str structural: StructuralChecks dimension_grades: List[DimensionGrade] overall_score: int = Field(ge=0, le=5) gaps: List[str] = Field(default_factory=list) evidence_id: Optional[str] = None
def get_challenge(challenge_id: str) -> Optional[Challenge]: return next((c for c in CHALLENGES if c.challenge_id == challenge_id), None)
# ------------------------------------------------------------------- checks
def _adjacency(sub: DesignSubmission) -> Dict[str, Set[str]]: adj: Dict[str, Set[str]] = {c.id: set() for c in sub.components} for e in sub.edges: if e.source in adj and e.target in adj: adj[e.source].add(e.target) return adj
def _undirected(adj: Dict[str, Set[str]]) -> Dict[str, Set[str]]: und: Dict[str, Set[str]] = {k: set() for k in adj} for u, vs in adj.items(): for v in vs: und[u].add(v) und[v].add(u) return und
def _articulation_points(und: Dict[str, Set[str]]) -> Set[str]: """Classic Tarjan articulation points on the undirected component graph.""" disc: Dict[str, int] = {} low: Dict[str, int] = {} parent: Dict[str, Optional[str]] = {} points: Set[str] = set() timer = [0]
def dfs(u: str) -> None: disc[u] = low[u] = timer[0] timer[0] += 1 children = 0 for v in und[u]: if v not in disc: parent[v] = u children += 1 dfs(v) low[u] = min(low[u], low[v]) if parent.get(u) is None and children > 1: points.add(u) if parent.get(u) is not None and low[v] >= disc[u]: points.add(u) elif v != parent.get(u): low[u] = min(low[u], disc[v])
for node in und: if node not in disc: parent[node] = None dfs(node) return points
def _feedback_loop_closed(sub: DesignSubmission, adj: Dict[str, Set[str]]) -> bool: """A feedback/monitoring node participates in a directed cycle.""" loop_nodes = [c.id for c in sub.components if c.type in ("feedback", "monitoring")] for start in loop_nodes: # BFS from successors of start; loop closed if we can reach start again seen: Set[str] = set() frontier = list(adj.get(start, ())) while frontier: node = frontier.pop() if node == start: return True if node in seen: continue seen.add(node) frontier.extend(adj.get(node, ())) return False
def grade_submission(sub: DesignSubmission, store: Optional[Store] = None, save_evidence: bool = True) -> DesignGrade: store = store or get_store() challenge = get_challenge(sub.challenge_id) if challenge is None: raise ValueError(f"unknown challenge '{sub.challenge_id}'")
present_types = {c.type for c in sub.components} missing = ["/".join(group) for group in challenge.required_stages if not any(t in present_types for t in group)]
adj = _adjacency(sub) connected: Set[str] = set() for e in sub.edges: connected.add(e.source) connected.add(e.target) orphans = [c.name or c.id for c in sub.components if c.id not in connected]
loop_closed = _feedback_loop_closed(sub, adj)
und = _undirected(adj) art = _articulation_points(und) # Only interior nodes count as SPOFs (sources/sinks trivially "cut" the path). degree = {k: len(v) for k, v in und.items()} spof_ids = [a for a in art if degree.get(a, 0) >= 2] comp_by_id = {c.id: c for c in sub.components} spofs = [comp_by_id[i].name or i for i in spof_ids if i in comp_by_id]
all_text = " ".join(list(sub.rationales.values()) + [c.note for c in sub.components]) capacity_quotes = [m.group(0) for m in QUANT_RE.finditer(all_text)][:6] capacity_found = len(capacity_quotes) > 0
structural = StructuralChecks( missing_stages=missing, orphan_components=orphans, feedback_loop_closed=loop_closed, feedback_loop_required=challenge.requires_feedback_loop, single_points_of_failure=spofs, capacity_math_found=capacity_found, capacity_quotes=capacity_quotes, )
# ----------------------------------------------- rationale dimension grades text_lower = all_text.lower() dimension_grades: List[DimensionGrade] = [] for dim, cues in RATIONALE_DIMENSIONS.items(): matched = [c for c in cues if c in text_lower] base = 0 if not matched else (2 if len(matched) == 1 else 4) bonus = 0 gaps: List[str] = [] if dim == "scalability" and capacity_found: bonus = 1 elif dim == "scalability" and not capacity_found: gaps.append("No capacity math anywhere: state volumes, rates, and how they map to fleet size.") if dim == "reliability": if not spofs: bonus = 1 else: gaps.append(f"Single point(s) of failure: {', '.join(spofs)} — removal disconnects the pipeline.") if dim == "observability" and "monitoring" in present_types: bonus = 1 if dim == "failure_handling" and orphans: gaps.append(f"Orphan component(s) {', '.join(orphans)} — dead boxes suggest unfinished failure design.") if not matched: gaps.append(f"Rationales never address {dim.replace('_', ' ')}.") dimension_grades.append(DimensionGrade( dimension=dim, score=min(5, base + bonus), gaps=gaps, evidence=matched[:4]))
# ------------------------------------------------------------- aggregate gaps: List[str] = [] if missing: gaps.append(f"Missing required stage(s): {', '.join(missing)}.") if orphans: gaps.append(f"Orphan component(s): {', '.join(orphans)}.") if challenge.requires_feedback_loop and not loop_closed: gaps.append("The feedback loop is not closed: no directed cycle returns mined data to training.") if spofs: gaps.append(f"SPOF: {', '.join(spofs)}.") if not capacity_found: gaps.append("No stated capacity math.") for dg in dimension_grades: gaps.extend(dg.gaps)
structural_penalty = (len(missing) * 1.5 + (1 if orphans else 0) + (2 if challenge.requires_feedback_loop and not loop_closed else 0) + (1 if spofs else 0) + (1 if not capacity_found else 0)) dim_avg = sum(d.score for d in dimension_grades) / len(dimension_grades) overall = max(0, min(5, round(dim_avg - structural_penalty + 1))) if not missing and not orphans and loop_closed and capacity_found and dim_avg >= 3.5: overall = max(overall, 4)
grade = DesignGrade(challenge_id=sub.challenge_id, structural=structural, dimension_grades=dimension_grades, overall_score=overall, gaps=gaps[:12])
store.put("design_submissions", grade.grade_id, {"submission": sub.model_dump(), "grade": grade.model_dump()})
if save_evidence: ev = Evidence( user_id=sub.user_id, competency_ids=challenge.competency_ids, artifact_type="design_submission", source=f"Design Lab: {challenge.title}", summary=f"Scored {overall}/5 on '{challenge.title}' ({len(sub.components)} components).", quotes=capacity_quotes[:3], score=float(overall), confidence=0.7, payload={"grade_id": grade.grade_id, "challenge_id": sub.challenge_id}, ) store.put("evidence", ev.evidence_id, ev) grade.evidence_id = ev.evidence_id
return grade123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196"""Evaluation engine: rubric-driven, evidence-based scoring of free-text answers.
Rules enforced here:- NO SCORE WITHOUT EVIDENCE: every score above 1 must reference specific user statements (quotes extracted from the answer). No evidence => score 1.- ANTI-GAMING: score derives ONLY from concept coverage, tradeoff mentions and quantified results — never from answer length. A long waffle that covers no rubric concepts scores below a short precise answer.- LLM output (when available) must validate against the EvaluationResult contract AND its evidence quotes must actually appear in the user's answer; otherwise the deterministic rule-based result is used. An LLM may never raise the score more than one point above the rule-based floor."""
from __future__ import annotations
import jsonimport refrom typing import List, Optional, Tuple
from sensorflow.hillclimb import coach, llmfrom sensorflow.hillclimb.content import Exercise, RubricItemfrom sensorflow.hillclimb.models import EvaluationResult
QUANT_RE = re.compile( r"\d+(?:\.\d+)?\s*(?:%|percent|ms\b|s\b|x\b|qps\b|rps\b|fps\b|gb\b|tb\b|pb\b|" r"days?\b|hours?\b|weeks?\b|engineers?\b|gpus?\b|nodes?\b|replicas?\b|frames?\b)|" r"\bfrom\s+\d+(?:\.\d+)?\s+to\s+\d+(?:\.\d+)?|\bp9[059]\b|\d+(?:\.\d+)?\s*sigma", re.IGNORECASE,)
TRADEOFF_MARKERS = [ "trade-off", "tradeoff", "trade off", "at the cost of", "sacrific", "downside", "at the expense", " versus ", " vs ", "on the other hand", "the cost is", "we give up", "gives up", "in exchange", "instead of", "weighed against",]
MISCONCEPTION_PATTERNS: List[Tuple[str, str]] = [ (r"accuracy\s+is\s+the\s+best|just\s+use\s+accuracy", "Accuracy is a poor headline metric for imbalanced detection problems; prefer precision/recall/AP."), (r"average\s+latency\s+is\s+(fine|enough|what matters)", "Serving systems are judged by tail latency (p99), not the average."), (r"more\s+data\s+always\s+(helps|fixes|improves)", "More data does not fix distribution mismatch, label noise, or serving skew."), (r"offline\s+(metrics?|eval(uation)?)\s+(is|are)\s+ground\s+truth", "Offline evaluation is a proxy under its own sampling; it is not ground truth for live behavior."), (r"definitely\s+a\s+(true\s+)?regression|certainly\s+regressed", "Claiming certainty before significance testing / measurement validation is premature."),]
def split_sentences(text: str) -> List[str]: parts = re.split(r"(?<=[.!?])\s+|\n+", text.strip()) return [p.strip() for p in parts if p.strip()]
def _clip(sentence: str, limit: int = 220) -> str: return sentence if len(sentence) <= limit else sentence[:limit].rsplit(" ", 1)[0] + "…"
def _find_sentence(sentences: List[str], predicate) -> Optional[str]: for s in sentences: if predicate(s): return s return None
def _criterion_evidence(item: RubricItem, answer_lower: str, sentences: List[str]) -> Optional[str]: """Return an evidence quote (user's own sentence) if the criterion is met.""" if item.check == "quantified": hit = _find_sentence(sentences, lambda s: bool(QUANT_RE.search(s))) return hit if item.check == "tradeoff": return _find_sentence(sentences, lambda s: any(m in s.lower() for m in TRADEOFF_MARKERS)) for kw in item.keywords: if kw.lower() in answer_lower: hit = _find_sentence(sentences, lambda s: kw.lower() in s.lower()) if hit: return hit return None
def rule_based_evaluate(exercise: Exercise, answer: str) -> EvaluationResult: sentences = split_sentences(answer) answer_lower = answer.lower()
covered: List[Tuple[RubricItem, str]] = [] missed: List[RubricItem] = [] evidence: List[str] = [] for item in exercise.evaluation_rubric: quote = _criterion_evidence(item, answer_lower, sentences) if quote: covered.append((item, quote)) clipped = _clip(quote) if clipped not in evidence: evidence.append(clipped) else: missed.append(item)
total_weight = sum(i.weight for i in exercise.evaluation_rubric) or 1.0 covered_weight = sum(i.weight for i, _ in covered) coverage = covered_weight / total_weight
# Coverage → score. Deliberately independent of answer length. if coverage >= 0.85: score = 5 elif coverage >= 0.65: score = 4 elif coverage >= 0.45: score = 3 elif coverage >= 0.20: score = 2 else: score = 1
# No score without evidence. if not evidence: score = 1
misconceptions = [msg for pat, msg in MISCONCEPTION_PATTERNS if re.search(pat, answer_lower)]
strengths = [f"{i.criterion} — \"{_clip(q, 140)}\"" for i, q in covered[:5]] weaknesses = [i.criterion for i in missed if i.check == "keywords"][:5] missing_evidence = [] for i in missed: if i.check == "quantified": missing_evidence.append("No quantified claims: no numbers, thresholds, or before/after comparisons anywhere in the answer.") elif i.check == "tradeoff": missing_evidence.append("No explicit tradeoff stated: nothing about what your approach sacrifices.") else: missing_evidence.append(f"Not addressed: {i.criterion.lower()}.")
confidence = round(min(0.9, 0.35 + 0.07 * len(covered)), 2)
result = EvaluationResult( competency=exercise.competency_id, score=score, confidence=confidence, evidence=evidence, strengths=strengths, weaknesses=weaknesses, missing_evidence=missing_evidence[:6], misconceptions=misconceptions, evaluator="rule_based", ) result.recommended_action = coach.recommended_action(exercise, result) result.follow_up_question = coach.pick_follow_up(exercise, result) return result
def _normalize(s: str) -> str: return re.sub(r"\s+", " ", s.lower()).strip(" .\"'…")
def _llm_result_valid(candidate: EvaluationResult, answer: str) -> bool: """LLM evidence must quote the user's actual statements.""" if not candidate.evidence: return False normalized_answer = _normalize(answer) for quote in candidate.evidence: if _normalize(quote) not in normalized_answer: return False return True
def evaluate_response(exercise: Exercise, answer: str, use_llm: bool = True) -> EvaluationResult: rule_result = rule_based_evaluate(exercise, answer) if not (use_llm and llm.llm_enabled()): return rule_result
rubric_lines = "\n".join(f"- {i.criterion}" for i in exercise.evaluation_rubric) prompt = ( "You are grading an engineering-manager interview answer against a rubric.\n" f"SCENARIO:\n{exercise.scenario}\n\nRUBRIC:\n{rubric_lines}\n\n" f"ANSWER:\n{answer}\n\n" "Respond with ONLY a JSON object with keys: competency (string), score (int 1-5), " "confidence (0-1), evidence (array of EXACT quotes copied verbatim from the answer), " "strengths (array), weaknesses (array), missing_evidence (array), misconceptions (array), " "recommended_action (string), follow_up_question (string). " "Every point awarded must be justified by a quote in evidence. Do not reward verbosity." ) candidate = llm.generate_json(prompt, EvaluationResult, timeout=25.0) if candidate is None or not _llm_result_valid(candidate, answer): return rule_result
candidate.competency = exercise.competency_id candidate.evaluator = "llm" # Anti-gaming guard: the LLM may refine, but never inflate more than one # point above the deterministic evidence-based floor. if candidate.score > rule_result.score + 1: candidate.score = rule_result.score + 1 if not candidate.recommended_action: candidate.recommended_action = coach.recommended_action(exercise, candidate) if not candidate.follow_up_question: candidate.follow_up_question = coach.pick_follow_up(exercise, candidate) return candidate123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210"""AI interviewer: stateful adaptive sessions (technical / management / hybrid).
There is NO fixed question list. Questions come from the competency-keyedexercise generator; after every answer the evaluation contract drives thesequencing policy: - weakness detected (score <= 2) -> targeted follow-up probe from the exercise's follow_up_questions - strong answer (score >= 4) -> escalate difficulty, or switch dimension once difficulty is maxed - shallow-but-polished (score 3 with polish markers but thin concept coverage) -> depth probe on a missed criterion - otherwise -> advance to a new competency
The transcript is stored as an Evidence artifact."""
from __future__ import annotations
import randomfrom typing import Dict, List, Optional
from pydantic import BaseModel, Field
from sensorflow.hillclimb import content, evaluatefrom sensorflow.hillclimb.blueprint import competency_index, load_blueprintfrom sensorflow.hillclimb.models import (EvaluationResult, Evidence, Store, get_store, new_id, now_iso)
MODES = { "technical": [1, 2], "management": [3], "hybrid": [1, 2, 3, 4],}
POLISH_MARKERS = ["first", "second", "third", "in summary", "to summarize", "overall", "furthermore", "moreover", "in conclusion", "let me walk", "great question"]
class InterviewTurn(BaseModel): index: int question: str question_type: str # opening | probe | depth_probe | escalate | advance competency_id: str exercise_id: str difficulty: int answer: Optional[str] = None evaluation: Optional[EvaluationResult] = None timestamp: str = Field(default_factory=now_iso)
class InterviewSession(BaseModel): session_id: str = Field(default_factory=lambda: new_id("iv")) user_id: str = "default" mode: str = "hybrid" seed: int = 7 status: str = "active" # active | complete turns: List[InterviewTurn] = Field(default_factory=list) asked_competencies: List[str] = Field(default_factory=list) probe_count_on_current: int = 0 evidence_id: Optional[str] = None
def _pool(mode: str, store: Store) -> List[str]: bp = load_blueprint(store) phases = MODES.get(mode, MODES["hybrid"]) return [c.id for c in bp.competencies if c.phase in phases]
def _pick_competency(session: InterviewSession, store: Store, avoid_dimension_of: Optional[str] = None) -> str: bp = load_blueprint(store) idx = competency_index(bp) pool = [c for c in _pool(session.mode, store) if c not in session.asked_competencies] if not pool: pool = _pool(session.mode, store) if avoid_dimension_of and avoid_dimension_of in idx: dim = idx[avoid_dimension_of].dimension switched = [c for c in pool if idx[c].dimension != dim] if switched: pool = switched rng = random.Random(session.seed + len(session.turns) * 131) return rng.choice(sorted(pool))
def _new_exercise_turn(session: InterviewSession, competency_id: str, difficulty: int, question_type: str, store: Store) -> InterviewTurn: ex = content.generate_exercise(competency_id, difficulty=difficulty, seed=session.seed + len(session.turns) * 977, store=store, use_llm=False) session.asked_competencies.append(competency_id) session.probe_count_on_current = 0 return InterviewTurn(index=len(session.turns), question=ex.scenario, question_type=question_type, competency_id=competency_id, exercise_id=ex.exercise_id, difficulty=difficulty)
def start_interview(mode: str = "hybrid", user_id: str = "default", seed: int = 7, store: Optional[Store] = None) -> InterviewSession: store = store or get_store() if mode not in MODES: raise ValueError(f"unknown mode '{mode}' (technical|management|hybrid)") session = InterviewSession(user_id=user_id, mode=mode, seed=seed) first_comp = _pick_competency(session, store) session.turns.append(_new_exercise_turn(session, first_comp, difficulty=2, question_type="opening", store=store)) store.put("interviews", session.session_id, session) return session
def _is_polished_but_shallow(result: EvaluationResult, answer: str) -> bool: low = answer.lower() polish = sum(1 for m in POLISH_MARKERS if m in low) concept_strengths = [s for s in result.strengths if not s.lower().startswith(("quantifies", "states explicit tradeoff"))] return polish >= 2 and len(concept_strengths) <= 2
def submit_answer(session_id: str, answer: str, use_llm: bool = True, store: Optional[Store] = None) -> InterviewSession: store = store or get_store() raw = store.get("interviews", session_id) if raw is None: raise ValueError(f"unknown interview session '{session_id}'") session = InterviewSession(**raw) if session.status != "active": raise ValueError("interview already complete")
current = session.turns[-1] ex = content.get_exercise(current.exercise_id, store) result = evaluate.evaluate_response(ex, answer, use_llm=use_llm) current.answer = answer current.evaluation = result
# ------------------------------------------------------ sequencing policy next_turn: Optional[InterviewTurn] = None if result.score <= 2 and session.probe_count_on_current < 2 and ex.follow_up_questions: probe_idx = min(session.probe_count_on_current, len(ex.follow_up_questions) - 1) session.probe_count_on_current += 1 next_turn = InterviewTurn(index=len(session.turns), question=ex.follow_up_questions[probe_idx], question_type="probe", competency_id=current.competency_id, exercise_id=current.exercise_id, difficulty=current.difficulty) elif result.score >= 4: if current.difficulty < 3: next_turn = _new_exercise_turn(session, current.competency_id, difficulty=current.difficulty + 1, question_type="escalate", store=store) else: comp = _pick_competency(session, store, avoid_dimension_of=current.competency_id) next_turn = _new_exercise_turn(session, comp, difficulty=3, question_type="escalate", store=store) elif result.score == 3 and _is_polished_but_shallow(result, answer): missed = result.weaknesses[0] if result.weaknesses else "the mechanism behind your answer" next_turn = InterviewTurn( index=len(session.turns), question=(f"That was well structured, but let's go deeper. Specifically: " f"{missed.rstrip('.').lower()}. Explain the underlying mechanism with a " f"concrete example and real numbers."), question_type="depth_probe", competency_id=current.competency_id, exercise_id=current.exercise_id, difficulty=current.difficulty) else: comp = _pick_competency(session, store) next_turn = _new_exercise_turn(session, comp, difficulty=2, question_type="advance", store=store)
session.turns.append(next_turn) store.put("interviews", session.session_id, session) return session
def end_interview(session_id: str, store: Optional[Store] = None) -> InterviewSession: store = store or get_store() raw = store.get("interviews", session_id) if raw is None: raise ValueError(f"unknown interview session '{session_id}'") session = InterviewSession(**raw) if session.status == "complete": return session session.status = "complete"
answered = [t for t in session.turns if t.evaluation is not None] per_comp: Dict[str, List[int]] = {} for t in answered: per_comp.setdefault(t.competency_id, []).append(t.evaluation.score) avg = (sum(t.evaluation.score for t in answered) / len(answered)) if answered else 0.0
ev = Evidence( user_id=session.user_id, competency_ids=list(per_comp.keys()), artifact_type="interview_transcript", source=f"AI interview ({session.mode})", summary=(f"{len(answered)} answers across {len(per_comp)} competencies, " f"avg score {avg:.1f}/5."), quotes=[t.evaluation.evidence[0] for t in answered if t.evaluation.evidence][:4], score=round(avg, 2), confidence=min(0.85, 0.3 + 0.1 * len(answered)), payload={"session_id": session.session_id, "per_competency": {k: sum(v) / len(v) for k, v in per_comp.items()}, "transcript": [t.model_dump() for t in session.turns]}, ) store.put("evidence", ev.evidence_id, ev) session.evidence_id = ev.evidence_id store.put("interviews", session.session_id, session) return session
def get_interview(session_id: str, store: Optional[Store] = None) -> Optional[InterviewSession]: raw = (store or get_store()).get("interviews", session_id) return InterviewSession(**raw) if raw else None1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586"""LLM client wrapper with graceful degradation.
Follows the same pattern as sensorflow/evaluation/copilot.py: try local Ollamaendpoints, and if unreachable (or the response fails schema validation) thecaller falls back to the deterministic rule-based path. LLM output is NEVERallowed to mutate state as free-form text — callers must validate against apydantic schema via `generate_json`.
Set HILLCLIMB_DISABLE_LLM=1 to force offline behavior (used in tests)."""
from __future__ import annotations
import jsonimport osimport refrom typing import Optional, Type, TypeVar
import httpxfrom pydantic import BaseModel
OLLAMA_ENDPOINTS = [ {"url": "http://localhost:11434/api/chat", "model": "gemma3:latest"}, {"url": "http://dgx-spark.tail16d8d9.ts.net:11434/api/chat", "model": "gemma4:26b"},]
T = TypeVar("T", bound=BaseModel)
def llm_enabled() -> bool: return os.environ.get("HILLCLIMB_DISABLE_LLM", "") != "1"
def generate_text(prompt: str, timeout: float = 20.0) -> Optional[str]: """Return LLM text or None when no endpoint is reachable.""" if not llm_enabled(): return None for ep in OLLAMA_ENDPOINTS: try: res = httpx.post(ep["url"], json={ "model": ep["model"], "messages": [{"role": "user", "content": prompt}], "stream": False, }, timeout=timeout) if res.status_code == 200: text = res.json().get("message", {}).get("content", "") if text: return text except Exception: continue return None
def _extract_json(text: str) -> Optional[dict]: """Best-effort extraction of the first JSON object from LLM output.""" fence = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.DOTALL) candidates = [fence.group(1)] if fence else [] brace = text.find("{") if brace >= 0: candidates.append(text[brace:text.rfind("}") + 1]) for cand in candidates: try: obj = json.loads(cand) if isinstance(obj, dict): return obj except Exception: continue return None
def generate_json(prompt: str, schema: Type[T], timeout: float = 20.0) -> Optional[T]: """Ask the LLM for JSON and validate it against `schema`.
Returns None on any failure (unreachable, unparseable, schema-invalid) so the caller falls back to its deterministic rule-based path. """ text = generate_text(prompt, timeout=timeout) if not text: return None obj = _extract_json(text) if obj is None: return None try: return schema(**obj) except Exception: return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214"""Data model + JSON persistence for the Hill Climbing EM platform.
Everything persists as JSON documents under runs/hillclimb/ (one file percollection). The store is intentionally simple: this is a single-user,low-write-volume product surface, and file-backed JSON keeps the whole thinginspectable and dependency-free."""
from __future__ import annotations
import jsonimport osimport threadingimport uuidfrom datetime import datetime, timezonefrom enum import Enumfrom pathlib import Pathfrom typing import Dict, List, Optional
from pydantic import BaseModel, Field
def now_iso() -> str: return datetime.now(timezone.utc).isoformat()
def new_id(prefix: str) -> str: return f"{prefix}-{uuid.uuid4().hex[:10]}"
# --------------------------------------------------------------------- enums
class Dimension(str, Enum): KNOWLEDGE = "Knowledge" TECHNICAL_REASONING = "Technical Reasoning" LEADERSHIP = "Leadership" EXECUTION = "Execution"
class ReadinessState(str, Enum): NOT_STARTED = "NOT_STARTED" LEARNING = "LEARNING" PRACTICING = "PRACTICING" NEEDS_REVIEW = "NEEDS_REVIEW" COMPETENT = "COMPETENT" STRONG = "STRONG" INTERVIEW_READY = "INTERVIEW_READY"
class JourneyState(str, Enum): NOT_STARTED = "NOT_STARTED" DIAGNOSTIC = "DIAGNOSTIC" LEARNING = "LEARNING" PRACTICE = "PRACTICE" ASSESSMENT = "ASSESSMENT" REMEDIATION = "REMEDIATION" REASSESS = "REASSESS"
# --------------------------------------------------------------------- models
class UserProfile(BaseModel): user_id: str = "default" name: str = "You" target_role: str = "Engineering Manager, ML/Perception" experience_years: float = 8.0 focus_note: str = "" created_at: str = Field(default_factory=now_iso) updated_at: str = Field(default_factory=now_iso)
class EvaluationResult(BaseModel): """Structured AI-evaluation contract. Free-form LLM text NEVER mutates state directly — it must parse into this schema or the rule-based evaluator's result is used instead."""
competency: str score: int = Field(ge=1, le=5, description="1=Novice .. 5=Expert") confidence: float = Field(ge=0.0, le=1.0) evidence: List[str] = Field(default_factory=list, description="Quotes from the user's own statements") strengths: List[str] = Field(default_factory=list) weaknesses: List[str] = Field(default_factory=list) missing_evidence: List[str] = Field(default_factory=list) misconceptions: List[str] = Field(default_factory=list) recommended_action: str = "" follow_up_question: str = "" evaluator: str = "rule_based" # rule_based | llm
class Evidence(BaseModel): evidence_id: str = Field(default_factory=lambda: new_id("ev")) user_id: str = "default" competency_ids: List[str] = Field(default_factory=list) artifact_type: str = "exercise_attempt" # exercise_attempt | star_story | design_submission | simulation_debrief | interview_transcript | diagnostic source: str = "" summary: str = "" quotes: List[str] = Field(default_factory=list) score: float = 0.0 confidence: float = 0.0 timestamp: str = Field(default_factory=now_iso) payload: Dict = Field(default_factory=dict)
class Attempt(BaseModel): attempt_id: str = Field(default_factory=lambda: new_id("att")) user_id: str = "default" exercise_id: str = "" competency_id: str = "" kind: str = "exercise" # exercise | diagnostic | interview | design | simulation responses: Dict = Field(default_factory=dict) evaluation: Optional[EvaluationResult] = None timestamp: str = Field(default_factory=now_iso)
class CompetencyReadiness(BaseModel): competency_id: str knowledge_score: float = 0.0 application_score: float = 0.0 evidence_score: float = 0.0 readiness_state: ReadinessState = ReadinessState.NOT_STARTED evidence_ids: List[str] = Field(default_factory=list) last_updated: str = Field(default_factory=now_iso)
class Journey(BaseModel): user_id: str = "default" state: JourneyState = JourneyState.NOT_STARTED current_phase: int = 1 current_competency: Optional[str] = None remediation_target: Optional[str] = None history: List[Dict] = Field(default_factory=list) updated_at: str = Field(default_factory=now_iso)
# --------------------------------------------------------------------- store
class Store: """JSON-file collection store rooted at runs/hillclimb/ by default."""
def __init__(self, root: Optional[Path] = None): self.root = Path(root or os.environ.get("HILLCLIMB_DATA_DIR", "runs/hillclimb")) self.root.mkdir(parents=True, exist_ok=True) self._lock = threading.Lock() self._cache: Dict[str, Dict[str, Dict]] = {}
def _path(self, collection: str) -> Path: return self.root / f"{collection}.json"
def _load(self, collection: str) -> Dict[str, Dict]: if collection in self._cache: return self._cache[collection] path = self._path(collection) data: Dict[str, Dict] = {} if path.exists(): try: data = json.loads(path.read_text()) except Exception: data = {} self._cache[collection] = data return data
def _flush(self, collection: str) -> None: path = self._path(collection) tmp = path.with_suffix(".tmp") tmp.write_text(json.dumps(self._cache.get(collection, {}), indent=2, default=str)) tmp.replace(path)
def put(self, collection: str, key: str, value: Dict | BaseModel) -> None: if isinstance(value, BaseModel): value = value.model_dump(mode="json") with self._lock: data = self._load(collection) data[key] = value self._flush(collection)
def get(self, collection: str, key: str) -> Optional[Dict]: with self._lock: return self._load(collection).get(key)
def delete(self, collection: str, key: str) -> bool: with self._lock: data = self._load(collection) if key in data: del data[key] self._flush(collection) return True return False
def all(self, collection: str) -> List[Dict]: with self._lock: return list(self._load(collection).values())
def where(self, collection: str, **eq) -> List[Dict]: return [r for r in self.all(collection) if all(r.get(k) == v for k, v in eq.items())]
_store: Optional[Store] = None
def get_store() -> Store: global _store if _store is None: _store = Store() return _store
def reset_store(root: Optional[Path] = None) -> Store: """Replace the singleton (used by tests to isolate state).""" global _store _store = Store(root) return _store123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156"""Readiness matrix + bottleneck analysis.
Per competency we track knowledge_score, application_score and evidence_scoreseparately (never collapsed), derive a readiness state, and link the evidencebehind every number (explainable scores: click a score -> see its evidence).
Bottleneck = the highest-LEVERAGE weakness: the prerequisite blocking the mostdownstream competencies — explicitly NOT simply the lowest score."""
from __future__ import annotations
from typing import Dict, List, Optional
from sensorflow.hillclimb.blueprint import (competency_index, display_dimensions_for, downstream_map, load_blueprint, DISPLAY_DIMENSIONS)from sensorflow.hillclimb.models import (Attempt, CompetencyReadiness, ReadinessState, Store, get_store)
KNOWLEDGE_KINDS = {"diagnostic", "interview"}APPLICATION_KINDS = {"exercise", "design", "simulation"}
COMPETENT_STATES = {ReadinessState.COMPETENT, ReadinessState.STRONG, ReadinessState.INTERVIEW_READY}
def record_attempt(attempt: Attempt, store: Optional[Store] = None) -> None: (store or get_store()).put("attempts", attempt.attempt_id, attempt)
def _avg(scores: List[float]) -> float: return round(sum(scores) / len(scores), 2) if scores else 0.0
def _derive_state(k: float, a: float, e: float, evidence_count: int) -> ReadinessState: if k == 0 and a == 0 and evidence_count == 0: return ReadinessState.NOT_STARTED best = max(k, a) if k > 0 and a > 0 and abs(k - a) >= 2.0: return ReadinessState.NEEDS_REVIEW if best < 2.0: return ReadinessState.LEARNING if k >= 4.5 and a >= 4.0 and e >= 3.5 and evidence_count >= 2: return ReadinessState.INTERVIEW_READY if k >= 4.0 and a >= 4.0: return ReadinessState.STRONG if k >= 3.0 and a >= 3.0: return ReadinessState.COMPETENT return ReadinessState.PRACTICING
def compute_matrix(user_id: str = "default", store: Optional[Store] = None) -> Dict[str, CompetencyReadiness]: store = store or get_store() bp = load_blueprint(store) attempts = [Attempt(**a) for a in store.where("attempts", user_id=user_id)] evidence = store.where("evidence", user_id=user_id)
matrix: Dict[str, CompetencyReadiness] = {} for comp in bp.competencies: cid = comp.id k_scores = [a.evaluation.score for a in attempts if a.competency_id == cid and a.kind in KNOWLEDGE_KINDS and a.evaluation] a_scores = [a.evaluation.score for a in attempts if a.competency_id == cid and a.kind in APPLICATION_KINDS and a.evaluation] linked = [e for e in evidence if cid in e.get("competency_ids", [])] e_scores = [e.get("score", 0.0) for e in linked if e.get("score", 0.0) > 0]
k, a, e = _avg(k_scores), _avg(a_scores), _avg(e_scores) # interview/exercise evidence also informs application when direct # application attempts are absent if a == 0 and e > 0: a = round(e * 0.8, 2) state = _derive_state(k, a, e, len(linked)) matrix[cid] = CompetencyReadiness( competency_id=cid, knowledge_score=k, application_score=a, evidence_score=e, readiness_state=state, evidence_ids=[ev["evidence_id"] for ev in linked][:20], )
store.put("readiness", user_id, {cid: r.model_dump() for cid, r in matrix.items()}) return matrix
def combined_score(r: CompetencyReadiness) -> float: parts = [s for s in (r.knowledge_score, r.application_score) if s > 0] return round(sum(parts) / len(parts), 2) if parts else 0.0
def bottleneck_analysis(user_id: str = "default", store: Optional[Store] = None, matrix: Optional[Dict[str, CompetencyReadiness]] = None) -> Optional[Dict]: """Highest-leverage weakness: prerequisite blocking the most downstream work.""" store = store or get_store() bp = load_blueprint(store) idx = competency_index(bp) matrix = matrix or compute_matrix(user_id, store) downstream = downstream_map(bp)
candidates = [cid for cid, r in matrix.items() if r.readiness_state not in COMPETENT_STATES] if not candidates: return None
def blocked_count(cid: str) -> int: return sum(1 for d in downstream.get(cid, set()) if matrix[d].readiness_state not in COMPETENT_STATES)
ranked = sorted(candidates, key=lambda cid: (-blocked_count(cid), combined_score(matrix[cid]), cid)) best = ranked[0] blocked = sorted(d for d in downstream.get(best, set()) if matrix[d].readiness_state not in COMPETENT_STATES) comp = idx[best] blocked_names = [idx[b].name for b in blocked[:4]] if blocked_names: explanation = (f"{comp.name} is limiting {len(blocked)} downstream competencies " f"(e.g. {', '.join(blocked_names[:3])}). Strengthening it unblocks the most " f"of your remaining path — that makes it higher-leverage than your lowest raw score.") else: explanation = (f"{comp.name} is your weakest unblocked competency; nothing depends on it, " f"but it is required for the phase-{comp.phase} completion criteria.") return { "competency_id": best, "name": comp.name, "phase": comp.phase, "dimension": comp.dimension.value, "readiness": matrix[best].model_dump(), "blocked_competencies": blocked, "blocked_count": len(blocked), "explanation": explanation, }
def dimension_summary(user_id: str = "default", store: Optional[Store] = None, matrix: Optional[Dict[str, CompetencyReadiness]] = None) -> List[Dict]: """Aggregate readiness into the dashboard's display dimensions.""" store = store or get_store() bp = load_blueprint(store) matrix = matrix or compute_matrix(user_id, store) buckets: Dict[str, List[CompetencyReadiness]] = {d: [] for d in DISPLAY_DIMENSIONS} for comp in bp.competencies: for d in display_dimensions_for(comp): buckets[d].append(matrix[comp.id])
out: List[Dict] = [] for dim in DISPLAY_DIMENSIONS: rs = buckets[dim] scored = [combined_score(r) for r in rs] nonzero = [s for s in scored if s > 0] competent = sum(1 for r in rs if r.readiness_state in COMPETENT_STATES) out.append({ "dimension": dim, "avg_score": round(sum(nonzero) / len(nonzero), 2) if nonzero else 0.0, "coverage": round(len(nonzero) / len(rs), 2) if rs else 0.0, "competent": competent, "total": len(rs), }) return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426"""Stateful hill-climbing simulation: multi-objective EM decision exercise.
State vector: system_performance, safety, reliability, cost, velocity,maintainability, team_morale, customer_impact, risk, schedule (0-100; cost andrisk are "higher is worse"). A seeded scenario applies per-turn pressure; eachturn the user writes a hypothesis, picks an intervention (with probabilistic-but-seeded effects, delays and second-order consequences), measures the result,and keeps or rejects the change. The objective is a balanced multi-objectivescore with HARD FLOORS (safety below threshold triggers an incident event).Fully deterministic given the seed and the same choice sequence."""
from __future__ import annotations
import randomfrom typing import Dict, List, Optional
from pydantic import BaseModel, Field
from sensorflow.hillclimb.models import Evidence, Store, get_store, new_id, now_iso
METRICS = ["system_performance", "safety", "reliability", "cost", "velocity", "maintainability", "team_morale", "customer_impact", "risk", "schedule"]INVERTED = {"cost", "risk"} # higher is worse
OBJECTIVE_WEIGHTS = { "system_performance": 0.14, "safety": 0.20, "reliability": 0.10, "cost": 0.06, "velocity": 0.10, "maintainability": 0.08, "team_morale": 0.12, "customer_impact": 0.10, "risk": 0.05, "schedule": 0.05,}
SAFETY_FLOOR = 30.0MORALE_FLOOR = 25.0
class InterventionSpec(BaseModel): id: str label: str description: str immediate: Dict[str, float] # mean effect; jitter applied per-turn delayed: List[Dict] = Field(default_factory=list) # {delay: int, effects: {metric: delta}, note} second_order: str = ""
INTERVENTIONS: List[InterventionSpec] = [ InterventionSpec( id="add_regression_gate", label="Add a release regression gate", description="Block releases whose eval deltas regress safety-critical slices.", immediate={"safety": 7, "reliability": 4, "velocity": -6, "schedule": -4}, delayed=[{"delay": 2, "effects": {"system_performance": 5, "customer_impact": 3}, "note": "Gate catches a bad build before it ships"}], second_order="Slower releases short-term; fewer production regressions later."), InterventionSpec( id="pause_launches", label="Pause launches for stabilization", description="Freeze feature launches for a sprint; all hands on regressions.", immediate={"safety": 10, "reliability": 6, "schedule": -10, "customer_impact": -6, "risk": -8}, delayed=[{"delay": 1, "effects": {"team_morale": -4}, "note": "Exec pressure builds during the freeze"}], second_order="Buys stability at the price of roadmap credibility."), InterventionSpec( id="hire_senior", label="Hire a senior ML-infra engineer", description="Open and close a senior req to deepen the bench.", immediate={"cost": 8, "velocity": -2}, delayed=[{"delay": 3, "effects": {"velocity": 8, "system_performance": 5, "team_morale": 4}, "note": "New senior hire reaches productivity"}], second_order="Expensive and slow to pay off, then compounding."), InterventionSpec( id="invest_test_infra", label="Invest in test & eval infrastructure", description="Two engineers build slice-level eval + CI hardening for a sprint.", immediate={"velocity": -5, "schedule": -3, "cost": 3}, delayed=[{"delay": 2, "effects": {"reliability": 7, "maintainability": 8, "velocity": 6, "safety": 4}, "note": "Test infra lands: regressions caught pre-merge"}], second_order="Classic J-curve: worse before durably better."), InterventionSpec( id="ship_feature_fast", label="Ship the exec-requested feature now", description="Cut the corner: ship the feature leadership is pressing for.", immediate={"schedule": 10, "customer_impact": 7, "velocity": 3, "safety": -7, "maintainability": -6, "risk": 10}, delayed=[{"delay": 2, "effects": {"reliability": -6, "team_morale": -3}, "note": "Corner-cutting surfaces as flaky behavior"}], second_order="Relief now; debt and risk arrive on a delay."), InterventionSpec( id="team_1on1s", label="Deep-dive 1:1s across the team", description="Spend the week understanding people: load, friction, morale.", immediate={"team_morale": 7, "velocity": -2}, delayed=[{"delay": 1, "effects": {"velocity": 4, "risk": -3}, "note": "Friction removed after 1:1 follow-ups"}], second_order="Costs a week; surfaces problems before they explode."), InterventionSpec( id="exec_expectation_reset", label="Reset expectations with leadership", description="Present the regression data and renegotiate the ship date.", immediate={"schedule": 6, "team_morale": 5, "risk": -4, "customer_impact": -3}, delayed=[], second_order="Spends political capital to buy engineering room."), InterventionSpec( id="incident_review_process", label="Institute blameless incident reviews", description="Every escaped regression gets a review with tracked actions.", immediate={"velocity": -3, "maintainability": 3}, delayed=[{"delay": 2, "effects": {"safety": 6, "reliability": 5}, "note": "Incident-review actions close systemic holes"}], second_order="Culture change: slow, then decisive."), InterventionSpec( id="add_monitoring", label="Add production model monitoring", description="Slice-level drift + regression monitoring on live traffic.", immediate={"reliability": 5, "cost": 4, "velocity": -2}, delayed=[{"delay": 1, "effects": {"safety": 6, "system_performance": 4}, "note": "Monitoring catches a drift you didn't know about"}], second_order="Visibility first; fixes follow the visibility."), InterventionSpec( id="refactor_pipeline", label="Refactor the training/eval pipeline", description="Pay down the pipeline debt that makes every change slow.", immediate={"velocity": -7, "schedule": -5, "cost": 4}, delayed=[{"delay": 3, "effects": {"maintainability": 10, "velocity": 9, "system_performance": 4}, "note": "Refactor lands: iteration speed jumps"}], second_order="The biggest J-curve on the menu."), InterventionSpec( id="cut_scope", label="Cut scope to protect the date", description="Descope the release to the safety-critical core.", immediate={"schedule": 8, "risk": -5, "customer_impact": -5, "velocity": 2}, delayed=[], second_order="Trades breadth for certainty."),]
INTERVENTION_INDEX = {i.id: i for i in INTERVENTIONS}
class Scenario(BaseModel): scenario_id: str title: str narrative: str initial: Dict[str, float] drift: Dict[str, float] # per-turn pressure applied before interventions
SCENARIOS: List[Scenario] = [ Scenario( scenario_id="inherited_perception_team", title="Inherited Perception Team Under Pressure", narrative=("You just inherited a 14-engineer perception team. The regression rate on " "safety-critical slices has risen for three consecutive releases, on-call is " "burning people out, and an exec has publicly committed your team to shipping " "a major feature in 8 weeks. Every objective is in tension: climb carefully."), initial={"system_performance": 55, "safety": 48, "reliability": 50, "cost": 45, "velocity": 52, "maintainability": 40, "team_morale": 44, "customer_impact": 55, "risk": 55, "schedule": 50}, drift={"safety": -2.0, "team_morale": -1.5, "maintainability": -1.0, "risk": 1.5, "schedule": -1.0}, ),]
class TurnRecord(BaseModel): turn: int hypothesis: str hypothesis_assessment: Dict intervention_id: str reverted_previous: bool = False applied_effects: Dict[str, float] = Field(default_factory=dict) delayed_landed: List[str] = Field(default_factory=list) events: List[str] = Field(default_factory=list) metrics_after: Dict[str, float] = Field(default_factory=dict) objective_after: float = 0.0 objective_delta: float = 0.0 verdict: str = "" # keep_recommended | reject_recommended timestamp: str = Field(default_factory=now_iso)
class SimulationState(BaseModel): sim_id: str = Field(default_factory=lambda: new_id("sim")) user_id: str = "default" scenario_id: str = "inherited_perception_team" seed: int = 42 max_turns: int = 8 turn: int = 0 status: str = "active" # active | complete metrics: Dict[str, float] = Field(default_factory=dict) pending: List[Dict] = Field(default_factory=list) # {due_turn, effects, note} history: List[TurnRecord] = Field(default_factory=list) events: List[Dict] = Field(default_factory=list) objective_history: List[float] = Field(default_factory=list) debrief: Optional[Dict] = None
def objective_score(metrics: Dict[str, float]) -> float: total = 0.0 for m, w in OBJECTIVE_WEIGHTS.items(): v = metrics.get(m, 50.0) total += w * ((100.0 - v) if m in INVERTED else v) return round(total, 2)
def create_simulation(user_id: str = "default", scenario_id: str = "inherited_perception_team", seed: int = 42, max_turns: int = 8, store: Optional[Store] = None) -> SimulationState: store = store or get_store() scenario = next((s for s in SCENARIOS if s.scenario_id == scenario_id), SCENARIOS[0]) sim = SimulationState(user_id=user_id, scenario_id=scenario.scenario_id, seed=seed, max_turns=max_turns, metrics=dict(scenario.initial)) sim.objective_history.append(objective_score(sim.metrics)) store.put("simulations", sim.sim_id, sim) return sim
def _assess_hypothesis(hypothesis: str, spec: InterventionSpec) -> Dict: """Rule-based check: is the hypothesis falsifiable and targeted?""" low = hypothesis.lower() touched = set(spec.immediate) | {m for d in spec.delayed for m in d["effects"]} mentions_metric = [m for m in METRICS if m.replace("_", " ") in low or m in low] targeted = any(m in touched for m in mentions_metric) directional = bool(any(w in low for w in ["increase", "decrease", "improve", "reduce", "raise", "lower", "recover", "drop", "+", "-"])) falsifiable = directional and (bool(mentions_metric) or any(ch.isdigit() for ch in low)) quality = "strong" if (targeted and falsifiable) else ("directional" if directional else "vague") return {"mentions_metrics": mentions_metric, "targets_intervention_effects": targeted, "directional": directional, "falsifiable": falsifiable, "quality": quality}
def step_simulation(sim_id: str, hypothesis: str, intervention_id: str, revert_previous: bool = False, store: Optional[Store] = None) -> SimulationState: store = store or get_store() raw = store.get("simulations", sim_id) if raw is None: raise ValueError(f"unknown simulation '{sim_id}'") sim = SimulationState(**raw) if sim.status != "active": raise ValueError("simulation already complete") spec = INTERVENTION_INDEX.get(intervention_id) if spec is None: raise ValueError(f"unknown intervention '{intervention_id}'")
scenario = next(s for s in SCENARIOS if s.scenario_id == sim.scenario_id) sim.turn += 1 rng = random.Random(sim.seed * 1000 + sim.turn) record = TurnRecord(turn=sim.turn, hypothesis=hypothesis, hypothesis_assessment=_assess_hypothesis(hypothesis, spec), intervention_id=intervention_id)
# keep/reject mechanic: reject the previous turn's intervention (undo its # immediate effects) before applying the new one. if revert_previous and sim.history: prev = sim.history[-1] for m, dv in prev.applied_effects.items(): sim.metrics[m] = sim.metrics.get(m, 50.0) - dv record.reverted_previous = True record.events.append(f"Rejected previous intervention '{prev.intervention_id}' — its immediate effects were rolled back.")
# scenario pressure (drift) for m, dv in scenario.drift.items(): sim.metrics[m] = sim.metrics.get(m, 50.0) + dv
# intervention immediate effects with seeded jitter (±30%) applied: Dict[str, float] = {} for m, mean in spec.immediate.items(): jitter = 1.0 + (rng.random() - 0.5) * 0.6 dv = round(mean * jitter, 2) sim.metrics[m] = sim.metrics.get(m, 50.0) + dv applied[m] = dv record.applied_effects = applied
# enqueue delayed / second-order effects for d in spec.delayed: sim.pending.append({"due_turn": sim.turn + int(d["delay"]), "effects": d["effects"], "note": d.get("note", "")})
# deliver due delayed effects still_pending: List[Dict] = [] for p in sim.pending: if p["due_turn"] <= sim.turn: for m, dv in p["effects"].items(): jitter = 1.0 + (rng.random() - 0.5) * 0.4 sim.metrics[m] = sim.metrics.get(m, 50.0) + round(dv * jitter, 2) record.delayed_landed.append(p["note"] or "Delayed effect landed") else: still_pending.append(p) sim.pending = still_pending
# clamp for m in METRICS: sim.metrics[m] = round(max(0.0, min(100.0, sim.metrics.get(m, 50.0))), 2)
# hard floors → events if sim.metrics["safety"] < SAFETY_FLOOR: incident = { "turn": sim.turn, "type": "SAFETY_INCIDENT", "detail": (f"Safety fell to {sim.metrics['safety']:.0f} (< floor {SAFETY_FLOOR:.0f}): a " "regression escaped to the fleet. Forced remediation: launches frozen, " "customer trust and morale take the hit."), } sim.events.append(incident) record.events.append(incident["detail"]) sim.metrics["customer_impact"] = max(0.0, sim.metrics["customer_impact"] - 12) sim.metrics["team_morale"] = max(0.0, sim.metrics["team_morale"] - 8) sim.metrics["risk"] = min(100.0, sim.metrics["risk"] + 10) sim.metrics["safety"] = min(100.0, sim.metrics["safety"] + 12) # forced remediation if sim.metrics["team_morale"] < MORALE_FLOOR: attrition = { "turn": sim.turn, "type": "ATTRITION", "detail": (f"Morale fell to {sim.metrics['team_morale']:.0f} (< floor {MORALE_FLOOR:.0f}): " "a senior engineer resigns; velocity drops."), } sim.events.append(attrition) record.events.append(attrition["detail"]) sim.metrics["velocity"] = max(0.0, sim.metrics["velocity"] - 10) sim.metrics["team_morale"] = min(100.0, sim.metrics["team_morale"] + 6)
# measure & evaluate obj = objective_score(sim.metrics) prev_obj = sim.objective_history[-1] record.objective_after = obj record.objective_delta = round(obj - prev_obj, 2) record.verdict = "keep_recommended" if record.objective_delta >= 0 else "reject_recommended" record.metrics_after = dict(sim.metrics) sim.objective_history.append(obj) sim.history.append(record)
if sim.turn >= sim.max_turns: sim.status = "complete" sim.debrief = build_debrief(sim, store)
store.put("simulations", sim.sim_id, sim) return sim
def build_debrief(sim: SimulationState, store: Optional[Store] = None) -> Dict: """Map the decision history onto competency evidence.""" store = store or get_store() mappings: List[Dict] = []
strong_hyps = [t for t in sim.history if t.hypothesis_assessment.get("quality") == "strong"] if len(strong_hyps) >= max(1, len(sim.history) // 2): mappings.append({ "competency_id": "p4.hill_climbing", "verdict": "evidenced", "reason": (f"{len(strong_hyps)}/{len(sim.history)} turns used falsifiable, targeted " "hypotheses before intervening."), "quotes": [t.hypothesis for t in strong_hyps[:3]], }) else: mappings.append({ "competency_id": "p4.hill_climbing", "verdict": "gap", "reason": "Most hypotheses were vague (no metric, no direction) — hill climbing without a hypothesis is guessing.", "quotes": [t.hypothesis for t in sim.history[:2]], })
rejects = [t for t in sim.history if t.reverted_previous] negative_turns = [t for t in sim.history if t.objective_delta < 0] if rejects: mappings.append({ "competency_id": "p3.closed_loop_execution", "verdict": "evidenced", "reason": f"Rejected {len(rejects)} intervention(s) after measurement showed regression — real keep/reject discipline.", "quotes": [f"turn {t.turn}: rejected previous after Δobjective {sim.history[t.turn-2].objective_delta:+.1f}" for t in rejects[:2] if t.turn >= 2], }) elif len(negative_turns) >= 2: mappings.append({ "competency_id": "p3.closed_loop_execution", "verdict": "gap", "reason": f"{len(negative_turns)} turns measured negative but nothing was ever rejected/rolled back.", "quotes": [], })
incidents = [e for e in sim.events if e["type"] == "SAFETY_INCIDENT"] safety_interventions = {"add_regression_gate", "pause_launches", "incident_review_process", "add_monitoring"} used_safety = [t for t in sim.history if t.intervention_id in safety_interventions] if incidents and any(t.turn > incidents[0]["turn"] for t in used_safety): mappings.append({"competency_id": "p3.safety_culture", "verdict": "evidenced", "reason": "Responded to the safety incident with systemic safety interventions.", "quotes": [t.intervention_id for t in used_safety[:3]]}) elif incidents: mappings.append({"competency_id": "p3.safety_culture", "verdict": "gap", "reason": "A safety incident occurred and no safety-focused intervention followed.", "quotes": []}) elif used_safety: mappings.append({"competency_id": "p3.safety_culture", "verdict": "evidenced", "reason": "Kept safety above the floor all game via proactive safety investment.", "quotes": [t.intervention_id for t in used_safety[:3]]})
final = sim.metrics balanced = all((100 - final[m] if m in INVERTED else final[m]) >= 35 for m in METRICS) mappings.append({ "competency_id": "p2.reliability_tradeoffs", "verdict": "evidenced" if balanced else "gap", "reason": ("Ended with every objective above the balance threshold — no metric was sacrificed." if balanced else "At least one objective ended critically low — the climb over-optimized a subset."), "quotes": [], })
start_obj, end_obj = sim.objective_history[0], sim.objective_history[-1] summary = { "objective_start": start_obj, "objective_end": end_obj, "objective_delta": round(end_obj - start_obj, 2), "incidents": len(incidents), "turns": sim.turn, "balanced_finish": balanced, "competency_mappings": mappings, }
# persist evidence for the evidenced mappings for m in mappings: if m["verdict"] != "evidenced": continue ev = Evidence( user_id=sim.user_id, competency_ids=[m["competency_id"]], artifact_type="simulation_debrief", source=f"Simulation {sim.sim_id} ({sim.scenario_id})", summary=m["reason"], quotes=[q for q in m["quotes"] if isinstance(q, str)][:3], score=4.0 if balanced else 3.0, confidence=0.6, payload={"sim_id": sim.sim_id, "objective_delta": summary["objective_delta"]}, ) store.put("evidence", ev.evidence_id, ev) m["evidence_id"] = ev.evidence_id
return summary
def get_simulation(sim_id: str, store: Optional[Store] = None) -> Optional[SimulationState]: raw = (store or get_store()).get("simulations", sim_id) return SimulationState(**raw) if raw else None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270"""STAR Story Box: diagnose (not just rewrite) unstructured experience stories.
Segments raw text into Situation/Task/Action/Result, runs per-component checks(context clarity, personal ownership, constraints, tradeoffs, influence/disagreement handling, measurable outcome, follow-through), flags unquantifiedclaims vs measurable evidence, and maps the story onto the Phase-3 leadershipcompetencies it actually evidences. Saved stories become Evidence artifacts."""
from __future__ import annotations
import refrom typing import Dict, List, Optional
from pydantic import BaseModel, Field
from sensorflow.hillclimb.evaluate import QUANT_RE, TRADEOFF_MARKERS, split_sentencesfrom sensorflow.hillclimb.models import Evidence, Store, get_store
CLAIM_RE = re.compile( r"\b(improved?|increased?|reduced?|decreased?|dropped?|fell|declined?|doubled?|halved?|" r"optimi[sz]ed?|accelerated?|boosted?|cut|grew|saved?|streamlined?|enhanced?|" r"significantly|dramatically|much (better|faster)|" r"more (efficient|reliable|scalable))\b", re.IGNORECASE)
ACTION_VERBS = ["led", "built", "decided", "wrote", "organized", "met", "proposed", "implemented", "negotiated", "created", "ran", "set up", "drove", "presented", "designed", "restructured", "escalated", "coached", "hired", "paused", "refactored", "convinced", "prioritized", "delegated", "launched", "defined", "pushed"]
S_CUES = ["at the time", "we had", "the team", "our system", "when i joined", "was facing", "inherited", "the situation", "context", "back in", "my team of", "our org"]T_CUES = ["my goal", "i was asked", "needed to", "responsible for", "my task", "the goal was", "we needed", "i had to", "my job was", "the ask was", "was tasked"]R_CUES = ["as a result", "result", "outcome", "ultimately", "in the end", "shipped", "launched", "improved", "reduced", "increased", "ended up", "afterwards", "since then"]
class ComponentDiagnosis(BaseModel): component: str # S | T | A | R label: str sentences: List[str] = Field(default_factory=list) present: bool = False issues: List[str] = Field(default_factory=list) strengths: List[str] = Field(default_factory=list)
class ClaimFlag(BaseModel): sentence: str kind: str # unquantified_claim | measurable_evidence detail: str
class CheckResult(BaseModel): check: str label: str passed: bool detail: str evidence: Optional[str] = None
class StarDiagnosis(BaseModel): components: List[ComponentDiagnosis] checks: List[CheckResult] claim_flags: List[ClaimFlag] competencies: List[Dict] = Field(default_factory=list) overall_score: int = 1 coaching: List[str] = Field(default_factory=list) evidence_id: Optional[str] = None
def _classify_sentences(sentences: List[str]) -> Dict[str, List[str]]: """Assign each sentence to S/T/A/R via cue scoring with a positional prior.""" buckets: Dict[str, List[str]] = {"S": [], "T": [], "A": [], "R": []} n = max(1, len(sentences)) for i, s in enumerate(sentences): low = s.lower() pos = i / n scores = { "S": sum(2 for c in S_CUES if c in low) + (1.5 if pos < 0.25 else 0), "T": sum(2 for c in T_CUES if c in low) + (0.5 if pos < 0.4 else 0), "A": sum(2 for v in ACTION_VERBS if re.search(rf"\bi\s+(?:\w+\s+)?{v}\b|\bi {v}\b", low)) + (1 if re.search(r"\bi\b", low) and 0.2 <= pos <= 0.85 else 0), "R": sum(2 for c in R_CUES if c in low) + (2 if QUANT_RE.search(s) and pos > 0.4 else 0) + (1 if pos > 0.75 else 0), } best = max(scores, key=lambda k: scores[k]) if scores[best] == 0: best = "S" if pos < 0.3 else ("A" if pos < 0.7 else "R") buckets[best].append(s) return buckets
def _claim_analysis(sentences: List[str]) -> List[ClaimFlag]: flags: List[ClaimFlag] = [] for i, s in enumerate(sentences): if not CLAIM_RE.search(s): continue neighborhood = " ".join(sentences[max(0, i - 1):i + 2]) if QUANT_RE.search(neighborhood): flags.append(ClaimFlag(sentence=s, kind="measurable_evidence", detail="Claim is backed by a number/before-after nearby — good.")) else: claim_word = CLAIM_RE.search(s).group(0) flags.append(ClaimFlag( sentence=s, kind="unquantified_claim", detail=(f"'{claim_word}' is an unquantified claim. Strengthen it: what was the metric " f"before and after, and what named mechanism caused the change?"))) return flags
COMPETENCY_CUES = { "p3.conflict_resolution": ["disagree", "conflict", "pushback", "mediat", "tension", "clash"], "p3.hiring": ["hire", "hiring", "interview loop", "recruit", "offer", "onboard", "headcount"], "p3.mentorship": ["mentor", "coach", "junior", "grew into", "promotion", "growth plan"], "p3.performance_management": ["underperform", "pip", "performance review", "expectations", "difficult feedback", "low performer"], "p3.roadmap_ambiguity": ["roadmap", "ambigu", "unclear scope", "milestone", "no clear plan", "from scratch"], "p3.cross_functional": ["product manager", " pm ", "cross-functional", "partner team", "design team", "legal", "ops team", "research team"], "p3.org_influence": ["exec", "leadership review", "vp", "director", "rfc", "org-wide", "influence"], "p3.prioritization_risk": ["priorit", "risk", "cut scope", "deprioritiz", "deadline", "trade"], "p3.safety_culture": ["safety", "incident", "postmortem", "sev", "regression escaped"], "p3.closed_loop_execution": ["measured", "metric", "iterated", "course-correct", "weekly review", "tracked", "dashboards"], "p3.business_impact": ["revenue", "cost sav", "customer", "business", "churn", "$", "contract"], "p3.technical_strategy": ["strategy", "platform", "migration", "build vs buy", "technical bet", "rewrite"],}
def _map_competencies(text_lower: str) -> List[Dict]: hits: List[Dict] = [] for cid, cues in COMPETENCY_CUES.items(): matched = [c for c in cues if c in text_lower] if matched: hits.append({"competency_id": cid, "matched_cues": matched[:3], "reason": f"Story references {', '.join(matched[:3])}"}) return hits
def diagnose_story(text: str, user_id: str = "default", save_evidence: bool = False, store: Optional[Store] = None) -> StarDiagnosis: store = store or get_store() sentences = split_sentences(text) text_lower = text.lower() buckets = _classify_sentences(sentences)
labels = {"S": "Situation", "T": "Task", "A": "Action", "R": "Result"} components: List[ComponentDiagnosis] = [] for key in ["S", "T", "A", "R"]: sents = buckets[key] comp = ComponentDiagnosis(component=key, label=labels[key], sentences=sents, present=bool(sents)) if not sents: comp.issues.append(f"No {labels[key]} content detected — the story never establishes it.") components.append(comp) by_key = {c.component: c for c in components}
# ---------------------------------------------------------------- checks checks: List[CheckResult] = []
def add_check(check: str, label: str, passed: bool, detail: str, evidence: Optional[str] = None): checks.append(CheckResult(check=check, label=label, passed=passed, detail=detail, evidence=evidence))
s_text = " ".join(buckets["S"]).lower() context_tokens = bool(re.search(r"team|engineer|org|system|product|customer|quarter|year", s_text)) context_scale = bool(QUANT_RE.search(" ".join(buckets["S"]))) or bool(re.search(r"\d", s_text)) add_check("context_clarity", "Context clarity", bool(buckets["S"]) and context_tokens, "Situation should establish team, system, and scale so a stranger can follow." + ("" if context_scale else " Add scale (team size, data volume, timeline) as numbers."), buckets["S"][0] if buckets["S"] else None)
a_text = " ".join(buckets["A"]).lower() i_count = len(re.findall(r"\bi\b", a_text)) we_count = len(re.findall(r"\bwe\b", a_text)) ownership = i_count >= 2 and (we_count == 0 or i_count >= we_count) add_check("personal_ownership", "Personal ownership", ownership, (f"Actions use 'I' {i_count}x vs 'we' {we_count}x. " + ("Clear personal ownership." if ownership else "Mostly 'we' — identify the decision YOU made, the alternatives YOU rejected.")), buckets["A"][0] if buckets["A"] else None)
constraint_hit = re.search(r"deadline|constraint|limited|only had|budget|headcount|pressure|" r"within \d|couldn't|shortage|freeze", text_lower) add_check("constraints", "Constraints named", bool(constraint_hit), "Stories are credible when the constraints (time, people, budget) are explicit." if not constraint_hit else "Constraints are explicit — good.", _sentence_containing(sentences, constraint_hit.group(0)) if constraint_hit else None)
tradeoff_hit = next((m for m in TRADEOFF_MARKERS if m in text_lower), None) add_check("tradeoffs", "Tradeoffs / alternatives", bool(tradeoff_hit), "State what you chose NOT to do and why." if not tradeoff_hit else "Alternatives/tradeoffs are visible.", _sentence_containing(sentences, tradeoff_hit) if tradeoff_hit else None)
influence_hit = re.search(r"disagree|pushback|convinc|persuad|align|escalat|stakeholder|" r"object|resist|bought in|buy-in", text_lower) add_check("influence_disagreement", "Influence & disagreement handling", bool(influence_hit), "EM stories should show navigating disagreement or influencing without authority." if not influence_hit else "Disagreement/influence handling present.", _sentence_containing(sentences, influence_hit.group(0)) if influence_hit else None)
r_joined = " ".join(buckets["R"]) measurable = bool(QUANT_RE.search(r_joined)) add_check("measurable_outcome", "Measurable outcome", measurable, "The Result has no numbers. Add before/after values or a quantified business outcome." if not measurable else "Result is quantified.", next((s for s in buckets["R"] if QUANT_RE.search(s)), None))
follow_hit = re.search(r"monitor|sustain|long.term|retro|followed up|since then|kept|maintained|" r"checked back|still|a year later|months later", text_lower) add_check("follow_through", "Follow-through", bool(follow_hit), "Show the change stuck: monitoring, retros, or how it looked months later." if not follow_hit else "Follow-through demonstrated.", _sentence_containing(sentences, follow_hit.group(0)) if follow_hit else None)
# ------------------------------------------------------- claims & mapping claim_flags = _claim_analysis(sentences) unquantified = [f for f in claim_flags if f.kind == "unquantified_claim"] competencies = _map_competencies(text_lower)
passed = sum(1 for c in checks if c.passed) overall = max(1, min(5, 1 + round(passed * 4 / len(checks)))) if unquantified and overall > 3: overall = 3 # unquantified claims cap the story quality
coaching: List[str] = [] for c in checks: if not c.passed: coaching.append(f"{c.label}: {c.detail}") for f in unquantified[:3]: coaching.append(f"Strengthen evidence — \"{f.sentence[:90]}\": {f.detail}") if not competencies: coaching.append("This story doesn't clearly evidence any Phase-3 competency; " "anchor it to a leadership behavior (conflict, hiring, strategy, execution).")
diagnosis = StarDiagnosis(components=components, checks=checks, claim_flags=claim_flags, competencies=competencies, overall_score=overall, coaching=coaching)
if save_evidence: quotes = [f.sentence for f in claim_flags if f.kind == "measurable_evidence"][:4] if not quotes and buckets["A"]: quotes = buckets["A"][:2] ev = Evidence( user_id=user_id, competency_ids=[c["competency_id"] for c in competencies], artifact_type="star_story", source="STAR Story Box", summary=(buckets["S"][0] if buckets["S"] else sentences[0] if sentences else "")[:160], quotes=quotes, score=float(overall), confidence=round(0.4 + 0.08 * passed, 2), payload={"checks": [c.model_dump() for c in checks], "unquantified_claims": len(unquantified), "story_text": text}, ) store.put("evidence", ev.evidence_id, ev) diagnosis.evidence_id = ev.evidence_id
return diagnosis
def _sentence_containing(sentences: List[str], token: str) -> Optional[str]: tl = token.lower() for s in sentences: if tl in s.lower(): return s return None28 unmodified lines29303132333417 unmodified lines52535455565722 unmodified lines80818283848519 unmodified lines105106107108109110201 unmodified lines31231331431531631728 unmodified linesWorkflow,Map as MapIcon,AppWindow,CircuitBoard,} from 'lucide-react';import { LabelEvalContext, type PageId, ALL_PAGE_IDS } from './context/LabelEvalContext';17 unmodified linesimport RootCauseLabPage from './pages/rca/RootCauseLabPage';import RareMinePage from './pages/raremine/RareMinePage';import VitisPage from './pages/vitis/VitisPage';import PageIntro from './components/help/PageIntro';import HelpMenu from './components/help/HelpMenu';22 unmodified lines{ id: 'evaluation', label: 'Evaluation', icon: <ListChecks size={18} /> },{ id: 'audit', label: 'Audit', icon: <ScrollText size={18} /> },{ id: 'pipeline', label: 'Pipeline Architecture', icon: <Workflow size={18} /> },{ id: 'vitis', label: 'Hardware Acceleration', icon: <CircuitBoard size={18} /> },];19 unmodified linesevaluation: 'Evaluation Records',audit: 'Audit & Process Units',pipeline: 'Pipeline Architecture',vitis: 'Hardware Acceleration (Vitis Vision)',ssam: 'SSAM Safety Dashboard',legacy: 'Legacy Studio',201 unmodified lines{page === 'evaluation' ? <EvaluationPage /> : null}{page === 'audit' ? <AuditPage /> : null}{page === 'pipeline' ? <PipelineArchitecturePage /> : null}{page === 'vitis' ? <VitisPage /> : null}</Box>)}28 unmodified lines2930313233343517 unmodified lines5354555657585922 unmodified lines8283848586878819 unmodified lines108109110111112113114201 unmodified lines31631731831932032132228 unmodified linesWorkflow,Map as MapIcon,AppWindow,Mountain,CircuitBoard,} from 'lucide-react';import { LabelEvalContext, type PageId, ALL_PAGE_IDS } from './context/LabelEvalContext';17 unmodified linesimport RootCauseLabPage from './pages/rca/RootCauseLabPage';import RareMinePage from './pages/raremine/RareMinePage';import VitisPage from './pages/vitis/VitisPage';import HillClimbSection from './pages/hillclimb/HillClimbSection';import PageIntro from './components/help/PageIntro';import HelpMenu from './components/help/HelpMenu';22 unmodified lines{ id: 'evaluation', label: 'Evaluation', icon: <ListChecks size={18} /> },{ id: 'audit', label: 'Audit', icon: <ScrollText size={18} /> },{ id: 'pipeline', label: 'Pipeline Architecture', icon: <Workflow size={18} /> },{ id: 'hillclimb', label: 'Hill Climbing EM', icon: <Mountain size={18} /> },{ id: 'vitis', label: 'Hardware Acceleration', icon: <CircuitBoard size={18} /> },];19 unmodified linesevaluation: 'Evaluation Records',audit: 'Audit & Process Units',pipeline: 'Pipeline Architecture',hillclimb: 'Hill Climbing EM',vitis: 'Hardware Acceleration (Vitis Vision)',ssam: 'SSAM Safety Dashboard',legacy: 'Legacy Studio',201 unmodified lines{page === 'evaluation' ? <EvaluationPage /> : null}{page === 'audit' ? <AuditPage /> : null}{page === 'pipeline' ? <PipelineArchitecturePage /> : null}{page === 'hillclimb' ? <HillClimbSection initialView={entityId} /> : null}{page === 'vitis' ? <VitisPage /> : null}</Box>)}
183 unmodified lines18418518618718818916 unmodified lines206207208209210211183 unmodified lines'evaluation','audit','pipeline','vitis','ssam','legacy',16 unmodified linesevaluation: 'Evaluation Records',audit: 'Audit',pipeline: 'Pipeline Architecture',vitis: 'Hardware Acceleration',ssam: 'SSAM Safety',legacy: 'Legacy Studio',183 unmodified lines18418518618718818919016 unmodified lines207208209210211212213183 unmodified lines'evaluation','audit','pipeline','hillclimb','vitis','ssam','legacy',16 unmodified linesevaluation: 'Evaluation Records',audit: 'Audit',pipeline: 'Pipeline Architecture',hillclimb: 'Hill Climbing EM',vitis: 'Hardware Acceleration',ssam: 'SSAM Safety',legacy: 'Legacy Studio',
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227/** Shared UI pieces for the Hill Climbing EM section. */
import { useCallback, useEffect, useState } from 'react';import Box from '@mui/material/Box';import Chip from '@mui/material/Chip';import Typography from '@mui/material/Typography';import { CheckCircle2, XCircle } from 'lucide-react';import type { EvaluationResult, ReadinessStateId } from '../../types/hillclimb';
// ------------------------------------------------------------- async helper
export interface Async<T> { data: T | null; loading: boolean; error: string | null; reload: () => void;}
export function useAsync<T>(fn: () => Promise<T>, deps: unknown[] = []): Async<T> { const [data, setData] = useState<T | null>(null); const [loading, setLoading] = useState(true); const [error, setError] = useState<string | null>(null); const [tick, setTick] = useState(0); const reload = useCallback(() => setTick((t) => t + 1), []); useEffect(() => { let alive = true; setLoading(true); fn() .then((d) => { if (alive) { setData(d); setError(null); } }) .catch((e: Error) => { if (alive) setError(e.message); }) .finally(() => { if (alive) setLoading(false); }); return () => { alive = false; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [tick, ...deps]); return { data, loading, error, reload };}
// ------------------------------------------------------------- score display
export const SCORE_COLORS = ['#ef5350', '#ff7043', '#f9a825', '#9ccc65', '#66bb6a'];
export function scoreColor(score: number): string { return SCORE_COLORS[Math.max(0, Math.min(4, Math.round(score) - 1))];}
export function ScoreChip({ score, label }: { score: number; label?: string }) { return ( <Chip size="small" label={`${label ?? 'Score'} ${score}/5`} sx={{ bgcolor: scoreColor(score), color: '#101418', fontWeight: 800, fontSize: 12 }} /> );}
// -------------------------------------------------------------- state chips
export const READINESS_COLORS: Record<ReadinessStateId, { bg: string; fg: string }> = { NOT_STARTED: { bg: '#37474f', fg: '#cfd8dc' }, LEARNING: { bg: '#0d47a1', fg: '#90caf9' }, PRACTICING: { bg: '#4527a0', fg: '#d1c4e9' }, NEEDS_REVIEW: { bg: '#e65100', fg: '#ffe0b2' }, COMPETENT: { bg: '#2e7d32', fg: '#c8e6c9' }, STRONG: { bg: '#1b5e20', fg: '#a5d6a7' }, INTERVIEW_READY: { bg: '#00695c', fg: '#80cbc4' },};
export function ReadinessChip({ state }: { state: ReadinessStateId }) { const c = READINESS_COLORS[state] ?? READINESS_COLORS.NOT_STARTED; return ( <Chip size="small" label={state.replace(/_/g, ' ')} sx={{ bgcolor: c.bg, color: c.fg, fontWeight: 700, fontSize: 10.5, height: 20 }} /> );}
export function PassChip({ passed, label }: { passed: boolean; label: string }) { return ( <Chip size="small" icon={passed ? <CheckCircle2 size={13} /> : <XCircle size={13} />} label={label} sx={{ bgcolor: passed ? '#1b5e20' : '#5d1414', color: passed ? '#a5d6a7' : '#ffcdd2', fontWeight: 600, fontSize: 11, '& .MuiChip-icon': { color: 'inherit' }, }} /> );}
// ------------------------------------------------------------- bullet lists
export function BulletList({ items, color = '#aab4be' }: { items: string[]; color?: string }) { if (!items.length) return null; return ( <Box component="ul" sx={{ m: 0, pl: 2.25 }}> {items.map((s, i) => ( <Typography key={i} component="li" variant="body2" sx={{ color, mb: 0.25 }}> {s} </Typography> ))} </Box> );}
function LabeledBlock({ label, color, children }: { label: string; color: string; children: React.ReactNode }) { return ( <Box sx={{ mb: 1.25 }}> <Typography variant="caption" sx={{ color, textTransform: 'uppercase', letterSpacing: 0.6, fontWeight: 700 }} > {label} </Typography> {children} </Box> );}
// -------------------------------------------------------- evaluation panel
/** Structured coaching panel: score with evidence quotes, strengths / * weaknesses / missing evidence / misconceptions, and the follow-up probe. */export function EvaluationPanel({ evaluation, coaching,}: { evaluation: EvaluationResult; coaching?: string;}) { return ( <Box> <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1.25, flexWrap: 'wrap' }}> <ScoreChip score={evaluation.score} /> <Chip size="small" label={`confidence ${(evaluation.confidence * 100).toFixed(0)}%`} sx={{ bgcolor: '#232a31', color: '#aab4be', fontSize: 11 }} /> <Chip size="small" label={evaluation.evaluator === 'llm' ? 'LLM + rubric floor' : 'deterministic rubric'} sx={{ bgcolor: '#232a31', color: '#8a949e', fontSize: 11 }} /> </Box>
{evaluation.evidence.length > 0 ? ( <LabeledBlock label="Evidence — your own words" color="#4fc3f7"> {evaluation.evidence.map((q, i) => ( <Typography key={i} variant="body2" sx={{ borderLeft: '3px solid #4fc3f7', pl: 1.25, py: 0.4, my: 0.5, color: '#cfd8dc', fontStyle: 'italic', bgcolor: '#12171d', borderRadius: '0 4px 4px 0', }} > “{q}” </Typography> ))} </LabeledBlock> ) : ( <Typography variant="body2" sx={{ color: '#ef9a9a', mb: 1 }}> No quotable evidence found in your answer — scores above 1 require evidence, so this answer scores 1/5. </Typography> )}
{evaluation.strengths.length > 0 ? ( <LabeledBlock label="Strengths" color="#9ccc65"> <BulletList items={evaluation.strengths} color="#c5e1a5" /> </LabeledBlock> ) : null} {evaluation.weaknesses.length > 0 ? ( <LabeledBlock label="Weaknesses" color="#ffb74d"> <BulletList items={evaluation.weaknesses} color="#ffcc80" /> </LabeledBlock> ) : null} {evaluation.missing_evidence.length > 0 ? ( <LabeledBlock label="Missing evidence" color="#ef9a9a"> <BulletList items={evaluation.missing_evidence} color="#ef9a9a" /> </LabeledBlock> ) : null} {evaluation.misconceptions.length > 0 ? ( <LabeledBlock label="Likely misconceptions" color="#ce93d8"> <BulletList items={evaluation.misconceptions} color="#ce93d8" /> </LabeledBlock> ) : null}
{coaching ? ( <LabeledBlock label="Coaching" color="#4fc3f7"> <Typography variant="body2" sx={{ color: '#cfd8dc', whiteSpace: 'pre-line' }}> {coaching} </Typography> </LabeledBlock> ) : null}
{evaluation.recommended_action ? ( <Typography variant="body2" sx={{ color: '#8a949e', mt: 1 }}> <b>Next:</b> {evaluation.recommended_action} </Typography> ) : null} </Box> );}30 unmodified lines313233343536698 unmodified lines73573673773873974067 unmodified lines80880981081181230 unmodified lines| 'Failure reasons'| 'Ground truth'| 'Operations'| 'Hardware acceleration';export const GLOSSARY: Record<string, GlossaryEntry> = {698 unmodified linesshort: 'Synthetic stress variant barred from training by default: full lineage, protected eval destination.',detail: 'Every generated augmentation variant carries training_eligible: false, evaluation_only: true and destination REGRESSION_EVALUATION_SET, plus complete lineage (recipe with resolved parameters, seed, source frame, backend config). Mirrors the rare-event miner\u2019s protected-destination leakage guard: stress data that leaked into training would corrupt the very regression signal it exists to protect.',},};export type GlossaryKey = keyof typeof GLOSSARY;67 unmodified lines'Failure reasons','Ground truth','Operations','Hardware acceleration',];30 unmodified lines31323334353637698 unmodified lines73673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279367 unmodified lines86186286386486586630 unmodified lines| 'Failure reasons'| 'Ground truth'| 'Operations'| 'EM readiness'| 'Hardware acceleration';export const GLOSSARY: Record<string, GlossaryEntry> = {698 unmodified linesshort: 'Synthetic stress variant barred from training by default: full lineage, protected eval destination.',detail: 'Every generated augmentation variant carries training_eligible: false, evaluation_only: true and destination REGRESSION_EVALUATION_SET, plus complete lineage (recipe with resolved parameters, seed, source frame, backend config). Mirrors the rare-event miner\u2019s protected-destination leakage guard: stress data that leaked into training would corrupt the very regression signal it exists to protect.',},// ------------------------------------------------------------ EM readiness (Hill Climbing EM)hc_competency: {term: 'Competency',category: 'EM readiness',short: 'A single skill node in the 4-phase blueprint graph, with prerequisites and a dimension tag.',detail: 'Each competency belongs to a phase (ML depth / system design / execution & people / simulation), lists prerequisite competencies, and is tagged with one dimension (Knowledge, Technical Reasoning, Leadership, Execution). Scores are tracked per competency and per dimension — never collapsed into one number.',},hc_readiness_state: {term: 'Readiness state',category: 'EM readiness',short: 'Per-competency progression: NOT_STARTED → LEARNING → PRACTICING → NEEDS_REVIEW → COMPETENT → STRONG → INTERVIEW_READY.',detail: 'Derived from three separate scores: knowledge (diagnostic/interview answers), application (exercises, design lab, simulation) and evidence (STAR stories and other artifacts). NEEDS_REVIEW is entered when recent attempts contradict earlier strong scores.',caveat: 'States are only as trustworthy as the evidence backing them; with the LLM offline, scoring is rule-based concept coverage, which is stricter but coarser.',},hc_evidence_artifact: {term: 'Evidence artifact',category: 'EM readiness',short: 'A stored, quotable record (attempt, STAR story, design grade, simulation debrief, interview transcript) that justifies a score.',detail: 'The scoring rule is "no score without evidence": every evaluation must quote specific user statements. Artifacts persist under runs/hillclimb/ and are browsable in the Evidence Library; clicking any matrix score shows the artifacts behind it.',},hc_bottleneck: {term: 'Bottleneck competency',category: 'EM readiness',short: 'The weak prerequisite blocking the most downstream competencies — not merely the lowest score.',detail: 'Computed from the prerequisite graph: for each weak competency, count the downstream competencies transitively gated on it; the highest-leverage weakness wins. Fixing the bottleneck unblocks more of the graph than fixing the globally lowest score.',},hc_next_best_action: {term: 'Next best action',category: 'EM readiness',short: 'Exactly one concept to study, one exercise to attempt and one assessment to take, aimed at the current bottleneck.',detail: 'Regenerated whenever the readiness matrix changes. Deliberately singular: a ranked to-do list invites cherry-picking easy items; one action per category forces work on the highest-leverage weakness.',},hc_claim_vs_evidence: {term: 'Claim vs evidence',category: 'EM readiness',short: 'STAR Story Box flag: an unquantified claim ("improved performance") vs measurable evidence (numbers, before/after, named mechanism).',detail: 'Claim sentences are detected by improvement verbs without attached quantities. Each flag asks for the missing strengthening: the metric, the baseline, the delta, or the mechanism that caused it. Interviewers apply the same test — so the diagnoser applies it first.',},hc_anti_gaming: {term: 'Anti-gaming rule',category: 'EM readiness',short: 'Verbosity alone must not raise scores: concept coverage, tradeoffs and quantified results are scored, not length.',detail: 'The evaluator scores rubric-concept coverage, tradeoff discussion and quantified statements. Length is not a feature, and low information density is penalized — a long waffle scores below a short precise answer (enforced by test).',},hc_hill_climbing: {term: 'Hill climbing (simulation)',category: 'EM readiness',short: 'Iterative optimization loop: hypothesis → intervention → measure → keep/reject → repeat, under competing objectives.',detail: 'The Phase-4 simulation tracks ten competing state metrics (performance, safety, reliability, cost, velocity, maintainability, morale, customer impact, risk, schedule) with hard floors — dropping safety below its floor triggers an incident. The balanced multi-objective score rewards keeping all objectives healthy, not maximizing one.',caveat: 'Deterministic given the scenario seed: identical intervention sequences replay identically, which is what makes debriefs auditable.',},};export type GlossaryKey = keyof typeof GLOSSARY;67 unmodified lines'Failure reasons','Ground truth','Operations','EM readiness','Hardware acceleration',];
214 unmodified lines215216217218219220214 unmodified linesdataFlow:'Scenes and engines come read-only from the bevfusion package; sequential verdicts use seqeval\u2019s anytime-valid tests when importable (local paired-t fallback otherwise). Runs persist under runs/vitis/. Generated variants are evaluation-set supplements tagged evaluation-only (never training-eligible) and are offered to the raremine candidate flow when that package is available.',},ssam: {subtitle:'Surrogate-safety analysis of real intersections: conflicts ranked by TTC / PET / severity on an interactive map — the safety context the label platform feeds.',214 unmodified lines215216217218219220221222223224225226227228229230231232214 unmodified linesdataFlow:'Scenes and engines come read-only from the bevfusion package; sequential verdicts use seqeval\u2019s anytime-valid tests when importable (local paired-t fallback otherwise). Runs persist under runs/vitis/. Generated variants are evaluation-set supplements tagged evaluation-only (never training-eligible) and are offered to the raremine candidate flow when that package is available.',},hillclimb: {subtitle:'Adaptive Engineering-Manager development & interview-readiness platform: a 4-phase competency blueprint (ML depth → system design → execution & people → hill-climbing simulation) with evidence-based scoring, never self-reported progress.',purpose:'Interview readiness is a hill-climbing problem: find the competency whose weakness blocks the most downstream skills, fix it with deliberate practice, measure, repeat. This section runs that loop — Assess → Diagnose → Practice → Apply → Evaluate → Improve — over a prerequisite-linked competency graph reconstructed from the Hill Climbing EM blueprint spec.',reading:'Dashboard bars are per-dimension readiness (Knowledge / Technical Reasoning / Leadership / Execution — tracked separately, never collapsed). The bottleneck callout names the prerequisite blocking the most downstream competencies, not merely the lowest score. Every score in the matrix is explainable: click it to see the evidence artifacts (attempt quotes, STAR stories, design grades, simulation debriefs, interview transcripts) that produced it. Coaching panels quote your own statements as evidence — a score without evidence is never shown.',actions:'Run the adaptive diagnostic to seed your matrix. Practice generated exercises (structurally different on each retry) and get rubric-based coaching. Diagnose raw experience stories into STAR components with claim-vs-evidence flags. Build architectures in the Design Lab. Play the multi-objective hill-climbing simulation. Take an adaptive mock interview. Review your evidence library and competency matrix.',dataFlow:'All state persists under runs/hillclimb/. Exercise submissions, STAR stories, design grades, simulation debriefs and interview transcripts become Evidence artifacts that feed the readiness matrix; the matrix feeds bottleneck analysis and the Next Best Action. The Phase-1 "offline +5% / shadow −2%" exercise family cross-links to the Root Cause Lab as the live practice tool.',},ssam: {subtitle:'Surrogate-safety analysis of real intersections: conflicts ranked by TTC / PET / severity on an interactive map — the safety context the label platform feeds.',
17 unmodified lines18192021222315 unmodified lines39404142434417 unmodified lines| 'pipeline'| 'rca'| 'raremine'| 'vitis'| 'ssam'| 'legacy';15 unmodified lines'pipeline','rca','raremine','vitis','ssam','legacy',17 unmodified lines1819202122232415 unmodified lines4041424344454617 unmodified lines| 'pipeline'| 'rca'| 'raremine'| 'hillclimb'| 'vitis'| 'ssam'| 'legacy';15 unmodified lines'pipeline','rca','raremine','hillclimb','vitis','ssam','legacy',
app_backend.py+4
sensorflow/hillclimb/__init__.pyAdded+5
sensorflow/hillclimb/adaptive.pyAdded+276
sensorflow/hillclimb/api.pyAdded+389
sensorflow/hillclimb/blueprint.pyAdded+351
sensorflow/hillclimb/coach.pyAdded+81
sensorflow/hillclimb/content.pyAdded+441
sensorflow/hillclimb/design_lab.pyAdded+331
sensorflow/hillclimb/evaluate.pyAdded+196
sensorflow/hillclimb/interviewer.pyAdded+210
sensorflow/hillclimb/llm.pyAdded+86
sensorflow/hillclimb/models.pyAdded+214
sensorflow/hillclimb/readiness.pyAdded+156
sensorflow/hillclimb/simulation.pyAdded+426
sensorflow/hillclimb/star.pyAdded+270
src/App.tsx+5
src/components/help/HelpMenu.tsx+2
src/components/hillclimb/shared.tsxAdded+227
src/content/glossary.ts+54
src/content/pageHelp.ts+12
src/context/LabelEvalContext.tsx+2