File size: 17,665 Bytes
bbe2211
adb7e74
bbe2211
adb7e74
cc6b2b9
adb7e74
 
 
 
 
 
 
bbe2211
adb7e74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc6b2b9
adb7e74
 
 
 
 
bbe2211
adb7e74
 
cc6b2b9
adb7e74
 
 
 
 
 
 
 
 
 
cc6b2b9
adb7e74
 
cc6b2b9
adb7e74
 
 
 
 
 
 
 
 
bbe2211
adb7e74
 
 
 
 
 
 
 
 
 
cc6b2b9
 
adb7e74
 
 
 
 
 
 
 
cc6b2b9
adb7e74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc6b2b9
 
adb7e74
 
 
 
 
 
 
cc6b2b9
 
adb7e74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc6b2b9
adb7e74
 
 
 
 
cc6b2b9
adb7e74
 
 
 
 
cc6b2b9
adb7e74
 
 
 
 
 
cc6b2b9
bbe2211
adb7e74
 
dddcb49
adb7e74
 
dddcb49
adb7e74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dddcb49
adb7e74
dddcb49
adb7e74
 
 
 
dddcb49
adb7e74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dddcb49
adb7e74
 
 
 
 
 
 
 
 
 
 
 
dddcb49
adb7e74
 
 
dddcb49
adb7e74
 
 
 
 
dddcb49
adb7e74
 
 
 
 
 
dddcb49
adb7e74
 
 
 
 
 
 
 
 
 
 
 
 
dddcb49
adb7e74
 
 
dddcb49
adb7e74
 
 
 
 
 
 
 
 
 
 
dddcb49
adb7e74
dddcb49
adb7e74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc6b2b9
adb7e74
 
 
 
 
 
 
 
 
 
 
 
cc6b2b9
adb7e74
 
 
 
 
cc6b2b9
adb7e74
a400436
adb7e74
 
 
 
 
 
 
 
 
 
 
 
 
a400436
adb7e74
 
 
 
 
 
 
cc6b2b9
adb7e74
 
 
 
 
cc6b2b9
adb7e74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc6b2b9
adb7e74
 
 
 
 
a400436
adb7e74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a400436
adb7e74
 
 
 
 
 
a400436
 
adb7e74
 
cc6b2b9
adb7e74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
"""
Enhanced components with real ARF integration
"""
import streamlit as st
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
from typing import List, Dict, Any, Optional
import time
import json

# Mock imports for ARF objects (in real app, import from actual packages)
class MockHealingIntent:
    """Mock HealingIntent for demo purposes"""
    def __init__(self, action, component, confidence, status, rag_similarity_score=None):
        self.action = action
        self.component = component
        self.confidence = confidence
        self.status = status
        self.rag_similarity_score = rag_similarity_score
        self.deterministic_id = f"intent_{int(time.time())}"
        self.created_at = time.time()
        
    def get_execution_summary(self):
        return {
            "intent_id": self.deterministic_id,
            "action": self.action,
            "component": self.component,
            "confidence": self.confidence,
            "status": self.status.value if hasattr(self.status, 'value') else self.status,
            "rag_similarity_score": self.rag_similarity_score
        }

def create_arf_enhanced_timeline(incident_data: Dict[str, Any], healing_intents: List[Dict[str, Any]] = None):
    """
    Create an enhanced incident timeline with real ARF integration
    """
    col1, col2 = st.columns([2, 1])
    
    with col1:
        st.markdown("### πŸ“ˆ ARF-Enhanced Incident Timeline")
        
        # Create timeline events based on ARF processing pipeline
        events = [
            {"time": "-5m", "event": "πŸ“‘ Alert Triggered", "phase": "detection", "color": "#FF6B6B"},
            {"time": "-4m", "event": "🧠 ARF Analysis Started", "phase": "analysis", "color": "#4ECDC4"},
            {"time": "-3.5m", "event": "πŸ” RAG Similarity Search", "phase": "rag", "color": "#1E90FF"},
            {"time": "-2.5m", "event": "🎯 Pattern Detection", "phase": "pattern", "color": "#9D4EDD"},
            {"time": "-1.5m", "event": "πŸ’‘ HealingIntent Generated", "phase": "intent", "color": "#FFD166"},
            {"time": "-1m", "event": "⚑ MCP Execution", "phase": "execution", "color": "#06D6A0"},
            {"time": "Now", "event": "βœ… Resolution Complete", "phase": "resolution", "color": "#118AB2"}
        ]
        
        # Create enhanced timeline with ARF phases
        fig = go.Figure()
        
        # Add ARF processing phases as background
        phases = [
            {"name": "Detection", "x_range": [0, 1], "color": "rgba(255, 107, 107, 0.1)"},
            {"name": "Analysis", "x_range": [1, 2.5], "color": "rgba(78, 205, 196, 0.1)"},
            {"name": "RAG Search", "x_range": [2.5, 3.5], "color": "rgba(30, 144, 255, 0.1)"},
            {"name": "Intent Gen", "x_range": [3.5, 4.5], "color": "rgba(157, 78, 221, 0.1)"},
            {"name": "Execution", "x_range": [4.5, 5.5], "color": "rgba(6, 214, 160, 0.1)"},
            {"name": "Resolution", "x_range": [5.5, 6], "color": "rgba(17, 138, 178, 0.1)"}
        ]
        
        for phase in phases:
            fig.add_shape(
                type="rect",
                x0=phase["x_range"][0] - 0.5,
                x1=phase["x_range"][1] - 0.5,
                y0=-0.3,
                y1=0.3,
                fillcolor=phase["color"],
                line=dict(width=0),
                layer="below"
            )
            
            # Add phase labels
            fig.add_annotation(
                x=(phase["x_range"][0] + phase["x_range"][1] - 1) / 2,
                y=0.4,
                text=phase["name"],
                showarrow=False,
                font=dict(size=9, color="#64748B"),
                yshift=10
            )
        
        # Add timeline line with markers
        fig.add_trace(go.Scatter(
            x=[i for i in range(len(events))],
            y=[0] * len(events),
            mode='lines+markers+text',
            line=dict(color='#334155', width=2, dash='solid'),
            marker=dict(
                size=18,
                color=[e['color'] for e in events],
                line=dict(width=2, color='white')
            ),
            text=[e['event'][0] for e in events],  # Use emoji as marker text
            textposition="middle center",
            textfont=dict(size=10, color='white'),
            hoverinfo='text',
            hovertext=[f"<b>{e['event']}</b><br>Phase: {e['phase'].title()}<br>Time: {e['time']}" for e in events],
            hovertemplate='%{hovertext}<extra></extra>'
        ))
        
        # Add event descriptions
        for i, event in enumerate(events):
            fig.add_annotation(
                x=i,
                y=-0.2,
                text=event['event'].split(' ')[1] if ' ' in event['event'] else event['event'][1:],
                showarrow=False,
                yshift=-30,
                font=dict(size=9, color=event['color'])
            )
            
            fig.add_annotation(
                x=i,
                y=0.1,
                text=event['time'],
                showarrow=False,
                yshift=25,
                font=dict(size=8, color="#94A3B8")
            )
        
        # Update layout
        fig.update_layout(
            height=250,
            showlegend=False,
            plot_bgcolor='rgba(0,0,0,0)',
            paper_bgcolor='rgba(0,0,0,0)',
            xaxis=dict(
                range=[-1, len(events)],
                showticklabels=False,
                showgrid=False,
                zeroline=False
            ),
            yaxis=dict(
                range=[-0.5, 0.5],
                showticklabels=False,
                showgrid=False,
                zeroline=False
            ),
            margin=dict(l=20, r=20, t=20, b=50)
        )
        
        st.plotly_chart(fig, use_container_width=True)
        
        # Add ARF processing metrics
        if healing_intents:
            cols = st.columns(4)
            with cols[0]:
                intent_conf = healing_intents[0].get('confidence', 0.7) if healing_intents else 0.7
                st.metric(
                    label="🧠 ARF Confidence",
                    value=f"{intent_conf*100:.1f}%",
                    delta="+15% with RAG"
                )
            with cols[1]:
                st.metric(
                    label="πŸ” Similar Incidents",
                    value=f"{len(healing_intents[0].get('similar_incidents', [])) if healing_intents else 0}",
                    delta="Pattern detected"
                )
            with cols[2]:
                st.metric(
                    label="⚑ Resolution Time",
                    value="8.2min",
                    delta="-85% vs OSS"
                )
            with cols[3]:
                cost_savings = incident_data.get('revenue_loss_per_hour', 8500) * 0.5  # 30min saved
                st.metric(
                    label="πŸ’° Cost Avoided",
                    value=f"${cost_savings:,.0f}",
                    delta_color="normal"
                )
    
    with col2:
        st.markdown("### 🎯 ARF Pattern Detection")
        
        # Pattern confidence from ARF RAG similarity
        rag_score = healing_intents[0].get('rag_similarity_score', 0.85) if healing_intents else 0.85
        
        # Confidence gauge using actual ARF confidence
        fig = go.Figure(go.Indicator(
            mode="gauge+number",
            value=rag_score * 100,
            domain={'x': [0, 1], 'y': [0, 1]},
            title={'text': "RAG Similarity Score", 'font': {'size': 14}},
            gauge={
                'axis': {'range': [0, 100], 'tickwidth': 1, 'tickcolor': "darkblue"},
                'bar': {'color': "#06D6A0" if rag_score > 0.85 else "#FFD166"},
                'steps': [
                    {'range': [0, 70], 'color': "rgba(255, 107, 107, 0.3)"},
                    {'range': [70, 85], 'color': "rgba(255, 209, 102, 0.3)"},
                    {'range': [85, 100], 'color': "rgba(6, 214, 160, 0.3)"}
                ],
                'threshold': {
                    'line': {'color': "red", 'width': 4},
                    'thickness': 0.75,
                    'value': 85
                }
            }
        ))
        
        fig.update_layout(
            height=200,
            margin=dict(l=30, r=30, t=50, b=20)
        )
        st.plotly_chart(fig, use_container_width=True)
        
        # Pattern details based on ARF analysis
        pattern_type = "cache_miss_storm"
        if incident_data.get('database_load', 0) > 90:
            pattern_type = "database_overload"
        
        st.info(f"""
        **Detected Pattern**: `{pattern_type}`
        **Confidence**: {rag_score*100:.1f}%
        **Auto-Heal Eligible**: {'βœ… Yes' if rag_score > 0.85 else '❌ Manual Review'}
        **Similar Incidents**: {len(healing_intents[0].get('similar_incidents', [])) if healing_intents else 0}
        """)

def create_healing_intent_visualizer(healing_intent: Dict[str, Any]):
    """
    Visualize a HealingIntent object from ARF
    """
    st.markdown("### πŸ’‘ ARF HealingIntent")
    
    # Create columns for intent visualization
    col1, col2 = st.columns([1, 2])
    
    with col1:
        # Confidence indicator
        confidence = healing_intent.get('confidence', 0.85)
        fig = go.Figure(go.Indicator(
            mode="gauge+number",
            value=confidence * 100,
            domain={'x': [0, 1], 'y': [0, 1]},
            title={'text': "Confidence"},
            gauge={
                'axis': {'range': [0, 100]},
                'bar': {'color': "#06D6A0" if confidence > 0.85 else "#FFD166"},
                'steps': [
                    {'range': [0, 70], 'color': "rgba(255, 107, 107, 0.3)"},
                    {'range': [70, 85], 'color': "rgba(255, 209, 102, 0.3)"},
                    {'range': [85, 100], 'color': "rgba(6, 214, 160, 0.3)"}
                ],
                'threshold': {
                    'line': {'color': "red", 'width': 4},
                    'thickness': 0.75,
                    'value': 85
                }
            }
        ))
        fig.update_layout(height=180)
        st.plotly_chart(fig, use_container_width=True)
        
        # Intent metadata
        st.caption("Intent Metadata")
        st.code(f"""
ID: {healing_intent.get('deterministic_id', 'N/A')}
Status: {healing_intent.get('status', 'created')}
Source: {healing_intent.get('source', 'oss_analysis')}
Created: {datetime.fromtimestamp(healing_intent.get('created_at', time.time())).strftime('%H:%M:%S')}
        """)
    
    with col2:
        # Intent details
        st.markdown("#### Action Details")
        
        # Action card
        action = healing_intent.get('action', 'scale_out')
        component = healing_intent.get('component', 'redis_cache')
        
        st.info(f"""
**Action**: `{action}`
**Component**: `{component}`
**Justification**: {healing_intent.get('justification', 'Based on historical pattern analysis')}
        """)
        
        # Parameters
        params = healing_intent.get('parameters', {})
        if params:
            st.markdown("#### Parameters")
            for key, value in params.items():
                st.metric(label=key, value=str(value))
        
        # Similar incidents
        similar = healing_intent.get('similar_incidents', [])
        if similar:
            st.markdown(f"#### Similar Incidents ({len(similar)})")
            for i, incident in enumerate(similar[:2]):  # Show top 2
                with st.expander(f"Similar Incident #{i+1}"):
                    st.json(incident)

def create_rag_similarity_panel(query: str, similar_incidents: List[Dict[str, Any]]):
    """
    Display RAG similarity search results
    """
    st.markdown("### πŸ” RAG Similarity Search")
    
    if not similar_incidents:
        st.info("No similar incidents found in memory")
        return
    
    # Create similarity results table
    df_data = []
    for i, incident in enumerate(similar_incidents):
        df_data.append({
            "Rank": i + 1,
            "Component": incident.get('component', 'unknown'),
            "Similarity": f"{incident.get('similarity_score', 0)*100:.1f}%",
            "Resolution": incident.get('resolution', 'Unknown'),
            "Success": "βœ…" if incident.get('success', False) else "❌",
            "Actions": len(incident.get('actions_taken', []))
        })
    
    df = pd.DataFrame(df_data)
    
    # Display as styled table
    st.dataframe(
        df,
        use_container_width=True,
        column_config={
            "Rank": st.column_config.NumberColumn(width="small"),
            "Similarity": st.column_config.ProgressColumn(
                width="medium",
                format="%f%%",
                min_value=0,
                max_value=100,
            ),
        },
        hide_index=True
    )
    
    # Similarity distribution chart
    if len(similar_incidents) > 1:
        fig = px.bar(
            df,
            x="Rank",
            y=df["Similarity"].str.rstrip('%').astype(float),
            color=df["Similarity"].str.rstrip('%').astype(float),
            color_continuous_scale=["#FF6B6B", "#FFD166", "#06D6A0"],
            title="Similarity Scores Distribution"
        )
        fig.update_layout(height=200, showlegend=False)
        st.plotly_chart(fig, use_container_width=True)

def create_learning_engine_panel(learning_stats: Dict[str, Any]):
    """
    Display ARF learning engine insights
    """
    st.markdown("### 🧠 ARF Learning Engine")
    
    cols = st.columns(2)
    
    with cols[0]:
        # Pattern detection stats
        st.metric(
            label="Patterns Detected",
            value=learning_stats.get('patterns_detected', 6),
            delta="+2 this week"
        )
        
        st.metric(
            label="Success Rate",
            value=f"{learning_stats.get('success_rate', '95.2%')}",
            delta="+5.2%"
        )
    
    with cols[1]:
        # Learning metrics
        st.metric(
            label="Auto-Heal Rate",
            value=f"{learning_stats.get('auto_heal_rate', '78.6%')}",
            delta="+12.4%"
        )
        
        st.metric(
            label="Confidence Threshold",
            value=f"{learning_stats.get('confidence_threshold', 0.85)}",
            delta="Optimized"
        )
    
    # Detected patterns
    patterns = learning_stats.get('detected_patterns', {})
    if patterns:
        st.markdown("#### Detected Patterns")
        
        pattern_data = []
        for pattern_name, pattern_info in patterns.items():
            pattern_data.append({
                "Pattern": pattern_name,
                "Occurrences": pattern_info.get('occurrences', 0),
                "Confidence": f"{pattern_info.get('confidence', 0)*100:.1f}%",
                "Auto-Heal": "βœ…" if pattern_info.get('auto_heal', False) else "❌"
            })
        
        pattern_df = pd.DataFrame(pattern_data)
        st.dataframe(pattern_df, use_container_width=True, hide_index=True)

def create_execution_mode_toggle(current_mode: str = "advisory"):
    """
    Show OSS vs Enterprise execution mode differences
    """
    st.markdown("### ⚑ ARF Execution Modes")
    
    # Mode selector
    modes = {
        "advisory": {
            "name": "OSS Advisory",
            "description": "Analysis only, no execution",
            "color": "#FF6B6B",
            "features": [
                "Incident analysis",
                "RAG similarity search",
                "HealingIntent creation",
                "Pattern detection"
            ]
        },
        "approval": {
            "name": "Enterprise (Approval)",
            "description": "Human-in-the-loop execution",
            "color": "#FFD166",
            "features": [
                "All OSS features",
                "Human approval workflow",
                "Audit trail",
                "Compliance reporting"
            ]
        },
        "autonomous": {
            "name": "Enterprise (Autonomous)",
            "description": "AI-driven auto-healing",
            "color": "#06D6A0",
            "features": [
                "All approval features",
                "Auto-execution",
                "Learning engine",
                "Predictive analytics"
            ]
        }
    }
    
    # Create mode selection
    selected_mode = st.selectbox(
        "Execution Mode",
        options=list(modes.keys()),
        format_func=lambda x: modes[x]["name"],
        index=list(modes.keys()).index(current_mode) if current_mode in modes else 0
    )
    
    # Display mode details
    mode = modes[selected_mode]
    
    # Mode indicator
    st.info(f"""
    **Current Mode**: {mode['name']}
    **Description**: {mode['description']}
    """)
    
    # Feature comparison
    st.markdown("#### Features Available")
    
    for feature in mode['features']:
        st.markdown(f"βœ… {feature}")
    
    # Mode differences
    st.markdown("#### Mode Differences")
    
    diff_data = {
        "Feature": ["Execution", "Human Review", "Audit Trail", "Learning", "Compliance"],
        "OSS Advisory": ["❌", "❌", "Basic", "❌", "❌"],
        "Enterprise (Approval)": ["βœ…", "βœ…", "Full", "Basic", "βœ…"],
        "Enterprise (Autonomous)": ["βœ…", "Optional", "Full", "Advanced", "βœ…"]
    }
    
    diff_df = pd.DataFrame(diff_data)
    st.dataframe(diff_df, use_container_width=True, hide_index=True)
    
    return selected_mode