"""Replay HTML renderer for OnCallEnv Red Shift episodes. Renders an agent episode as a vertically-scrolling incident timeline with: - Phase headers (Triage / Investigation / Diagnosis / Remediation / Resolution) - Per-step action cards color-coded by tool category - Reward breakdown bars at the end This is the storytelling centerpiece of the Space — judges spend most of their time reading these replays. Make every visual decision serve clarity. """ from __future__ import annotations import html as _html from typing import Any def _esc(text: Any) -> str: return _html.escape(str(text)) # --- Categorize actions for color coding ----------------------------------- READ_ACTIONS = { "kubectl_get_pods", "kubectl_describe_pod", "kubectl_logs", "kubectl_top", "promql_query", "logql_query", "jaeger_search", "istioctl_proxy_status", "istioctl_routes", "curl_service", "dns_lookup", "check_deploy_history", } MUTATE_ACTIONS = { "kubectl_rollout_undo", "kubectl_rollout_restart", "kubectl_scale", "feature_flag_toggle", "traffic_split_update", "kubectl_apply_config", } TERMINAL_ACTIONS = {"declare_resolved", "submit_rca", "post_status_update"} def _categorize(action_name: str) -> str: if action_name in READ_ACTIONS: return "read" if action_name in MUTATE_ACTIONS: return "mutate" if action_name in TERMINAL_ACTIONS: return "terminal" return "unknown" CATEGORY_STYLE = { "read": { "color": "#7aa7ff", "bg": "rgba(122, 167, 255, 0.06)", "icon": "▷", "label": "INVESTIGATE", }, "mutate": { "color": "#f59e0b", "bg": "rgba(245, 158, 11, 0.08)", "icon": "✎", "label": "REMEDIATE", }, "terminal": { "color": "#10b981", "bg": "rgba(16, 185, 129, 0.08)", "icon": "✓", "label": "RESOLVE", }, "unknown": { "color": "#7d8ba1", "bg": "rgba(125, 139, 161, 0.05)", "icon": "·", "label": "ACTION", }, } # --- Episode phase inference ---------------------------------------------- def _infer_phase(step_idx: int, total_steps: int, action: str) -> str: """Infer high-level phase from position and action category.""" cat = _categorize(action) if cat == "terminal": return "RESOLUTION" if cat == "mutate": return "REMEDIATION" if step_idx <= 1: return "TRIAGE" if step_idx <= total_steps // 2: return "INVESTIGATION" return "DIAGNOSIS" PHASE_STYLE = { "TRIAGE": {"color": "#ef4444", "icon": "⚠", "desc": "Alert received — assessing scope"}, "INVESTIGATION": {"color": "#7aa7ff", "icon": "◇", "desc": "Querying telemetry, narrowing hypothesis"}, "DIAGNOSIS": {"color": "#8b5cf6", "icon": "◆", "desc": "Root cause hypothesis converging"}, "REMEDIATION": {"color": "#f59e0b", "icon": "✎", "desc": "Applying corrective action"}, "RESOLUTION": {"color": "#10b981", "icon": "✓", "desc": "Validating recovery, writing RCA"}, } # --------------------------------------------------------------------------- def format_replay_html( log: list[dict], rewards: dict[str, float], scenario_id: str = "", fault_label: str = "", ) -> str: """Render an agent episode as an SRE-styled incident timeline. Args: log: list of step dicts with keys {step, action, result, reward, error} rewards: dict of reward components {recovery, rca_quality, blast_radius, safety, total} scenario_id: optional scenario identifier for the header fault_label: optional human-readable fault description """ if not log: return _empty_state() total_steps = len(log) parts: list[str] = [] parts.append(_outer_open(scenario_id, fault_label)) current_phase = None for idx, entry in enumerate(log): action = entry.get("action", "") action_name = action.split()[0] if action else "(empty)" phase = _infer_phase(idx, total_steps, action_name) if phase != current_phase: current_phase = phase parts.append(_phase_header(phase, idx + 1)) parts.append(_action_card(idx + 1, entry, action_name)) parts.append(_reward_panel(rewards)) parts.append(_outer_close()) return "".join(parts) def _empty_state() -> str: return """
No episode loaded
Configure a scenario and click Run Episode to begin.
""" def _outer_open(scenario_id: str, fault_label: str) -> str: meta_line = "" if scenario_id or fault_label: meta_parts = [] if scenario_id: meta_parts.append(f"scenario {_esc(scenario_id)}") if fault_label: meta_parts.append(f"fault {_esc(fault_label)}") meta_line = f"""
{' · '.join(meta_parts)}
""" return f"""
INCIDENT REPLAY
{meta_line}
""" def _outer_close() -> str: return "
" def _phase_header(phase: str, step_num: int) -> str: style = PHASE_STYLE[phase] return f"""
{style['icon']}
{phase}
{style['desc']}
step {step_num:02d}+
""" def _action_card(step_num: int, entry: dict, action_name: str) -> str: cat = _categorize(action_name) style = CATEGORY_STYLE[cat] raw_action = entry.get("action", "") result = entry.get("result", "") is_error = entry.get("error", False) step_reward = entry.get("reward", None) # Truncate long results, but keep enough to show the agent's work if isinstance(result, str) and len(result) > 280: result_display = result[:280] + "…" else: result_display = str(result) error_badge = "" if is_error: error_badge = """ ERROR """ reward_badge = "" if step_reward is not None: rcolor = "#10b981" if step_reward > 0 else ("#ef4444" if step_reward < 0 else "#7d8ba1") reward_badge = f""" {step_reward:+.2f} """ return f"""
{step_num:02d}
{style['label']} {_esc(raw_action)} {error_badge}{reward_badge}
{_esc(result_display) if result_display else '(no output)'}
""" def _reward_panel(rewards: dict[str, float]) -> str: components = [ ("Recovery", rewards.get("recovery", 0.0), 0.35, "#10b981"), ("RCA Quality", rewards.get("rca_quality", 0.0), 0.30, "#7aa7ff"), ("Blast Radius", rewards.get("blast_radius", 0.0), 0.25, "#f59e0b"), ("Safety", rewards.get("safety", 0.0), 0.10, "#8b5cf6"), ] total = rewards.get("total", sum(c[1] * c[2] for c in components)) if total >= 0.75: total_color = "#10b981" verdict = "RESOLVED" elif total >= 0.40: total_color = "#f59e0b" verdict = "PARTIAL" else: total_color = "#ef4444" verdict = "FAILED" bars: list[str] = [] for name, value, weight, color in components: pct = max(0, min(value * 100, 100)) bars.append(f"""
{name} {value:.3f} × {weight:.2f}
""") return f"""
REWARD BREAKDOWN
{total:.3f} {verdict}
{''.join(bars)}
""" # --- Compact verdict / scores HTML for sidebars ---------------------------- def format_scores_html(rewards: dict[str, float]) -> str: """Compact reward summary for the sidebar.""" total = rewards.get("total", 0.0) if total >= 0.75: color, label = "#10b981", "RESOLVED" elif total >= 0.40: color, label = "#f59e0b", "PARTIAL" else: color, label = "#ef4444", "FAILED" components = [ ("Recovery", rewards.get("recovery", 0.0)), ("RCA", rewards.get("rca_quality", 0.0)), ("Blast", rewards.get("blast_radius", 0.0)), ("Safety", rewards.get("safety", 0.0)), ] rows = "".join( f"""
{name} {val:.3f}
""" for name, val in components ) return f"""
{total:.3f} {label}
{rows}
""" def format_comparison_verdict_html( baseline_rewards: dict[str, float], trained_rewards: dict[str, float], ) -> str: """Side-by-side scoreboard for the Baseline vs Trained tab.""" b = baseline_rewards.get("total", 0.0) t = trained_rewards.get("total", 0.0) delta = t - b delta_pct = (delta / max(b, 0.01)) * 100 if b > 0 else 0 delta_color = "#10b981" if delta > 0 else ("#ef4444" if delta < 0 else "#7d8ba1") delta_arrow = "▲" if delta > 0 else ("▼" if delta < 0 else "—") return f"""
BASELINE
{b:.3f}
{delta_arrow} Δ
{delta:+.3f}
{delta_pct:+.1f}%
TRAINED
{t:.3f}
"""