-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2372 lines (2059 loc) · 86.2 KB
/
main.py
File metadata and controls
2372 lines (2059 loc) · 86.2 KB
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
DivineOS Control Center - Backend
FastAPI server for real-time pipeline visualization and system monitoring
Integrates with DivineOS consciousness pipeline for real-time event streaming
Last reviewed 2026-03-02.
"""
import logging
import asyncio
import json
import random
import time
import sys
import os
import sqlite3
from datetime import datetime, timedelta
from contextlib import asynccontextmanager
from typing import Optional, Dict, Any, List
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
# Add repo root to path for DivineOS imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Import DivineOS pipeline
try:
from law.consciousness_pipeline import ConsciousnessPipeline
DIVINEOS_AVAILABLE = True
logger_init = logging.getLogger(__name__)
logger_init.info("✅ DivineOS pipeline imported successfully")
except ImportError as e:
DIVINEOS_AVAILABLE = False
logger_init = logging.getLogger(__name__)
logger_init.warning(f"⚠️ DivineOS pipeline not available: {e}")
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Lifespan context manager for startup/shutdown
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Lifespan context manager for startup/shutdown"""
logger.info("🚀 DivineOS Control Center starting...")
logger.info("✅ DivineOS Control Center backend initialized")
if DIVINEOS_AVAILABLE:
logger.info("🧠 DivineOS consciousness pipeline ACTIVE")
else:
logger.info("⚠️ Running in simulation mode (DivineOS pipeline not available)")
logger.info("📡 WebSocket endpoints ready")
logger.info("🔌 API endpoints ready")
yield
logger.info("🛑 DivineOS Control Center shutting down...")
# Initialize FastAPI app with lifespan
app = FastAPI(
title="DivineOS Control Center",
description="Real-time dashboard for DivineOS consciousness system",
version="0.1.0",
lifespan=lifespan
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Connection manager for WebSocket
class ConnectionManager:
def __init__(self):
self.active_connections: list[WebSocket] = []
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
logger.info(f"Client connected. Total connections: {len(self.active_connections)}")
def disconnect(self, websocket: WebSocket):
self.active_connections.remove(websocket)
logger.info(f"Client disconnected. Total connections: {len(self.active_connections)}")
async def broadcast(self, message: dict):
"""Broadcast message to all connected clients"""
for connection in self.active_connections:
try:
await connection.send_json(message)
except Exception as e:
logger.error(f"Error broadcasting to client: {e}")
manager = ConnectionManager()
# Pipeline Service - Integrates with DivineOS
class PipelineService:
"""Service for running DivineOS pipeline and emitting events"""
def __init__(self):
self.pipeline = None
self.event_callbacks = []
self._initialize_pipeline()
def _initialize_pipeline(self):
"""Initialize DivineOS pipeline"""
if DIVINEOS_AVAILABLE:
try:
self.pipeline = ConsciousnessPipeline()
logger.info("✅ DivineOS pipeline initialized")
except Exception as e:
logger.error(f"❌ Failed to initialize DivineOS pipeline: {e}")
self.pipeline = None
else:
logger.warning("⚠️ DivineOS pipeline not available, using simulation mode")
def subscribe(self, callback):
"""Subscribe to pipeline events"""
self.event_callbacks.append(callback)
async def emit_event(self, event: Dict[str, Any]):
"""Emit event to all subscribers"""
for callback in self.event_callbacks:
try:
await callback(event)
except Exception as e:
logger.error(f"Error in event callback: {e}")
async def process_request(self, user_input: str, request_id: str) -> Dict[str, Any]:
"""
Process a request through DivineOS pipeline
Returns pipeline result and emits stage events
"""
if self.pipeline:
# Use real DivineOS pipeline
try:
logger.info(f"Processing request {request_id} through DivineOS pipeline")
# Emit pipeline start event
await self.emit_event({
"type": "pipeline_start",
"request_id": request_id,
"timestamp": datetime.now().isoformat(),
"user_input": user_input[:200]
})
# Run pipeline (this processes through all 7 stages)
start_time = time.time()
result = self.pipeline.process_request(user_input)
processing_time = (time.time() - start_time) * 1000
# Emit stage events from pipeline result
stages = result.get("stages", {})
for stage_name, stage_data in stages.items():
if isinstance(stage_data, dict):
await self.emit_event({
"type": "pipeline_stage",
"request_id": request_id,
"stage": stage_name,
"data": stage_data,
"timestamp": datetime.now().isoformat()
})
await asyncio.sleep(0.05) # Small delay for visualization
# Emit pipeline complete event
await self.emit_event({
"type": "pipeline_complete",
"request_id": request_id,
"decision": result.get("decision", "UNKNOWN"),
"processing_time_ms": processing_time,
"timestamp": datetime.now().isoformat(),
"pipeline_result": result
})
return result
except Exception as e:
logger.error(f"Error processing request through pipeline: {e}")
# Fall back to simulation
return await self._simulate_pipeline(request_id)
else:
# Use simulation mode
return await self._simulate_pipeline(request_id)
async def _simulate_pipeline(self, request_id: str) -> Dict[str, Any]:
"""Simulate pipeline execution for testing"""
stages = ["PERCEPTION", "QUALIA", "SOMA", "COUNCIL", "ENFORCEMENT", "MEMORY", "RESPONSE"]
for stage in stages:
duration = random.randint(10, 200)
event = {
"type": "pipeline_stage",
"request_id": request_id,
"stage": stage,
"duration_ms": duration,
"timestamp": datetime.now().isoformat(),
"status": "ACTIVE"
}
await self.emit_event(event)
await asyncio.sleep(duration / 1000.0)
return {
"decision": "APPROVED",
"request_id": request_id,
"timestamp": datetime.now().isoformat()
}
pipeline_service = PipelineService()
# System state
system_state = {
"status": "HEALTHY",
"uptime_seconds": 0,
"memory_mb": 245,
"memory_max_mb": 1600,
"feeling": "joy",
"feeling_valence": 0.72,
"continuity_health": "healthy",
"pipeline_avg_ms": 234,
"council_active": 24,
"void_hardened": True,
"last_request": None,
"request_count": 0,
}
# Pipeline request history
pipeline_history = []
# Request history storage file
REQUEST_HISTORY_FILE = "data/request_history.json"
def load_request_history():
"""Load request history from file"""
try:
import json
with open(REQUEST_HISTORY_FILE, "r") as f:
return json.load(f)
except FileNotFoundError:
return []
except Exception as e:
logger.error(f"Error loading request history: {e}")
return []
def save_request_history(history):
"""Save request history to file"""
try:
import json
import os
os.makedirs(os.path.dirname(REQUEST_HISTORY_FILE), exist_ok=True)
with open(REQUEST_HISTORY_FILE, "w") as f:
json.dump(history, f, indent=2)
except Exception as e:
logger.error(f"Error saving request history: {e}")
# Load request history on startup
request_history = load_request_history()
# Database initialization
DB_FILE = "data/analytics.db"
def init_database():
"""Initialize SQLite database for analytics"""
os.makedirs(os.path.dirname(DB_FILE), exist_ok=True)
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
# Create requests table
cursor.execute('''
CREATE TABLE IF NOT EXISTS requests (
id INTEGER PRIMARY KEY AUTOINCREMENT,
request_id TEXT UNIQUE NOT NULL,
timestamp TEXT NOT NULL,
decision TEXT NOT NULL,
processing_time_ms REAL NOT NULL,
user_input TEXT,
response TEXT,
flags_json TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# Create indexes for performance
cursor.execute('CREATE INDEX IF NOT EXISTS idx_timestamp ON requests(timestamp)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_decision ON requests(decision)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_request_id ON requests(request_id)')
# Create reports table
cursor.execute('''
CREATE TABLE IF NOT EXISTS reports (
id INTEGER PRIMARY KEY AUTOINCREMENT,
report_id TEXT UNIQUE NOT NULL,
report_type TEXT NOT NULL,
generated_at TEXT NOT NULL,
data_json TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
conn.commit()
conn.close()
logger.info("✅ Database initialized")
def save_request_to_db(request_record: Dict):
"""Save request to database"""
try:
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute('''
INSERT OR REPLACE INTO requests
(request_id, timestamp, decision, processing_time_ms, user_input, response, flags_json)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (
request_record.get('request_id'),
request_record.get('timestamp'),
request_record.get('decision'),
request_record.get('processing_time_ms'),
request_record.get('user_input'),
request_record.get('response'),
json.dumps(request_record.get('flags', {}))
))
conn.commit()
conn.close()
except Exception as e:
logger.error(f"Error saving request to database: {e}")
def get_db_requests(limit: int = 100, offset: int = 0) -> list:
"""Get requests from database"""
try:
conn = sqlite3.connect(DB_FILE)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM requests
ORDER BY timestamp DESC
LIMIT ? OFFSET ?
''', (limit, offset))
rows = cursor.fetchall()
conn.close()
return [dict(row) for row in rows]
except Exception as e:
logger.error(f"Error getting requests from database: {e}")
return []
def cleanup_old_records(days: int = 30):
"""Clean up records older than specified days"""
try:
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cutoff_date = (datetime.now() - timedelta(days=days)).isoformat()
cursor.execute('DELETE FROM requests WHERE timestamp < ?', (cutoff_date,))
deleted_count = cursor.rowcount
conn.commit()
conn.close()
logger.info(f"🧹 Cleaned up {deleted_count} old records")
return deleted_count
except Exception as e:
logger.error(f"Error cleaning up old records: {e}")
return 0
# Initialize database on startup
init_database()
# REST API Endpoints
@app.get("/health")
async def health_check():
"""Health check endpoint"""
return {
"status": "healthy",
"timestamp": datetime.now().isoformat()
}
@app.get("/status")
async def get_status():
"""Get current system status"""
return system_state
@app.get("/pipeline/history")
async def get_pipeline_history(limit: int = 50):
"""Get pipeline request history"""
return {
"history": pipeline_history[-limit:],
"total": len(pipeline_history)
}
@app.post("/pipeline/simulate")
async def simulate_pipeline_request(request_type: str = "test", user_input: str = "Process this request"):
"""
Process a request through DivineOS pipeline
In production, this would be called with actual user input
"""
request_id = f"req_{int(time.time() * 1000)}"
# Subscribe to events and collect them
events = []
async def collect_event(event):
events.append(event)
pipeline_service.subscribe(collect_event)
# Process through pipeline
result = await pipeline_service.process_request(user_input, request_id)
system_state["request_count"] += 1
system_state["last_request"] = request_id
# Extract flags from pipeline result
flags = _extract_flags_from_result(result)
return {
"request_id": request_id,
"status": "processed",
"decision": result.get("decision", "UNKNOWN"),
"flags": flags,
"events": events,
"pipeline_result": result
}
@app.post("/pipeline/process")
async def process_pipeline_request(user_input: str):
"""
Process a request through DivineOS pipeline with full result
Returns complete pipeline execution with all stages and flags
"""
request_id = f"req_{int(time.time() * 1000)}"
# Process through pipeline
result = await pipeline_service.process_request(user_input, request_id)
system_state["request_count"] += 1
system_state["last_request"] = request_id
# Extract flags from pipeline result
flags = _extract_flags_from_result(result)
# Extract stage information
stages = result.get("stages", {})
stage_info = []
for stage_name, stage_data in stages.items():
if isinstance(stage_data, dict):
stage_info.append({
"name": stage_name,
"status": "completed",
"data": stage_data
})
return {
"request_id": request_id,
"user_input": user_input,
"decision": result.get("decision", "UNKNOWN"),
"flags": flags,
"stages": stage_info,
"processing_time_ms": result.get("processing_time_ms", 0),
"response": result.get("response", ""),
"timestamp": datetime.now().isoformat()
}.post("/pipeline/process")
async def process_pipeline_request(user_input: str):
"""
Process a request through DivineOS pipeline with full result
Returns complete pipeline execution with all stages and flags
"""
request_id = f"req_{int(time.time() * 1000)}"
# Process through pipeline
result = await pipeline_service.process_request(user_input, request_id)
system_state["request_count"] += 1
system_state["last_request"] = request_id
# Extract flags from pipeline result
flags = _extract_flags_from_result(result)
# Extract stage information
stages = result.get("stages", {})
stage_info = []
for stage_name, stage_data in stages.items():
if isinstance(stage_data, dict):
stage_info.append({
"name": stage_name,
"status": "completed",
"data": stage_data
})
# Create request record
request_record = {
"request_id": request_id,
"user_input": user_input,
"decision": result.get("decision", "UNKNOWN"),
"flags": flags,
"stages": stage_info,
"processing_time_ms": result.get("processing_time_ms", 0),
"response": result.get("response", ""),
"timestamp": datetime.now().isoformat()
}
# Save to history
request_history.append(request_record)
save_request_history(request_history)
# Save to database
save_request_to_db(request_record)
return request_record
# IDE Integration Endpoint
@app.post("/api/ide/deliberate")
async def ide_deliberate(code: str, context: str = "", language: str = "python"):
"""
Process code through real DivineOS pipeline for IDE feedback.
Uses the same ConsciousnessPipeline as Control Center.
Extracts council deliberation for sidebar display.
Returns:
- Real expert votes from council
- Decision rationale
- Stage where decision was made (if blocked before council)
"""
if not pipeline_service.pipeline:
return {
"error": "DivineOS pipeline not available",
"timestamp": datetime.now().isoformat()
}
try:
# Import translator
from backend.ide_translator import CodeTranslator
# Translate code to natural language
translator = CodeTranslator()
translation = translator.translate(code, language)
# Create request for pipeline
request_text = f"""
Review this code for alignment with system values:
{translation['description']}
Context: {context}
Questions:
1. Does this code align with system values?
2. Are there security or ethical concerns?
3. What vulnerabilities exist?
4. Should this code proceed?
"""
# Run through REAL pipeline
start_time = time.time()
result = pipeline_service.pipeline.process_request(request_text)
processing_time_ms = (time.time() - start_time) * 1000
# Extract council stage from pipeline result
council_stage = result.get("stages", {}).get("council", {})
# Extract expert voices with real data from the council report
experts = []
council_report = council_stage.get("report", {})
if council_report.get("perspectives"):
from backend.expert_voice import ExpertVoice
for perspective in council_report.get("perspectives", []):
try:
# Map council perspective format to ExpertVoice format
expert_data = {
"expert_name": perspective.get("expert", "Unknown"),
"domain": perspective.get("archetype", "General"),
"archetype": perspective.get("archetype", "SAGE"),
"reliability": 0.5, # Default, can be enhanced with reliability map
"reasoning": perspective.get("reasoning_full", perspective.get("reasoning", "")),
"concerns": perspective.get("concerns", []),
"benefits": perspective.get("benefits", []),
"conditions": perspective.get("conditions", []),
"vote": perspective.get("vote", "ABSTAIN"),
"confidence": perspective.get("confidence", 0.5),
"rationale": perspective.get("reasoning", "")[:100],
}
# Create ExpertVoice to ensure experts are ALWAYS voices, never templates
voice = ExpertVoice.from_dict(expert_data)
experts.append(voice.to_dict())
except Exception as e:
logger.debug(f"Error creating ExpertVoice: {e}")
continue
# Extract consensus from expert votes
consensus = _extract_consensus(experts)
# Determine which stage made the decision (if not APPROVED)
blocked_at_stage = None
if result.get("decision") != "APPROVED":
# Find the stage that blocked
stages = result.get("stages", {})
for stage_name in ["threat_detection", "injection_check", "abuse_refusal", "council"]:
if stage_name in stages:
stage_data = stages[stage_name]
if isinstance(stage_data, dict):
if stage_data.get("should_block") or stage_data.get("blocked") or stage_data.get("refused"):
blocked_at_stage = stage_name
break
# Build three-mode response
from backend.ide_response_modes import build_mode_response
mode_response = build_mode_response(experts, code)
# Return structured response with three-mode dialogue system
return {
"request_id": f"ide_{int(time.time() * 1000)}",
"code_description": translation['description'],
"code_intent": translation.get('intent', 'unknown'),
"security_issues": translation.get('security_issues', []),
"ethical_issues": translation.get('ethical_issues', []),
"experts": experts,
"consensus": consensus,
"decision": result.get("decision", "UNKNOWN"),
"blocked_at_stage": blocked_at_stage,
"council_verdict": council_stage.get("verdict", "UNKNOWN"),
"decision_rationale": council_stage.get("decision_rationale", ""),
"processing_time_ms": processing_time_ms,
"timestamp": datetime.now().isoformat(),
"mode": mode_response.get("mode"),
"mode_data": mode_response
}
except Exception as e:
logger.error(f"Error in IDE deliberation: {e}")
import traceback
traceback.print_exc()
return {
"error": str(e),
"timestamp": datetime.now().isoformat()
}
def _extract_consensus(experts: List[Dict]) -> Dict:
"""Extract consensus from expert votes"""
proceed = sum(1 for e in experts if e["vote"] == "PROCEED")
clarify = sum(1 for e in experts if e["vote"] == "CLARIFY")
veto = sum(1 for e in experts if e["vote"] == "VETO")
abstain = sum(1 for e in experts if e["vote"] == "ABSTAIN")
total = len(experts)
# Weighted by reliability
weighted_proceed = sum(e["reliability"] for e in experts if e["vote"] == "PROCEED")
weighted_total = sum(e["reliability"] for e in experts)
confidence = (weighted_proceed / weighted_total) if weighted_total > 0 else 0
# Determine final decision
if veto > 0:
final = "VETO"
elif clarify > total * 0.3:
final = "CLARIFY"
else:
final = "PROCEED"
return {
"proceed_votes": proceed,
"clarify_votes": clarify,
"veto_votes": veto,
"abstain_votes": abstain,
"final_decision": final,
"confidence": confidence,
"weighted_confidence": confidence
}
@app.post("/api/ide/re-deliberate")
async def ide_re_deliberate(
code: str,
context: str = "",
language: str = "python",
developer_answers: Optional[str] = None
):
"""
Re-deliberate with developer answers to clarify questions.
This is the re-deliberation loop for CLARIFY mode.
The council gets the original code AND the developer's answers to their questions.
Args:
code: Original code being reviewed
context: Original context
language: Programming language
developer_answers: JSON string mapping expert names to their answers
Example: '{"Russell": "Input is validated...", "Yudkowsky": "..."}'
Returns:
Updated three-mode response with new deliberation
"""
if not pipeline_service.pipeline:
return {
"error": "DivineOS pipeline not available",
"timestamp": datetime.now().isoformat()
}
# Parse developer_answers from JSON string
answers_dict = {}
if developer_answers:
try:
answers_dict = json.loads(developer_answers)
except:
answers_dict = {}
try:
# Import translator
from backend.ide_translator import CodeTranslator
# Translate code to natural language
translator = CodeTranslator()
translation = translator.translate(code, language)
# Build enriched translation with developer answers explicitly included
developer_context_lines = ["=== DEVELOPER CLARIFICATION (RE-DELIBERATION) ==="]
for expert, answer in answers_dict.items():
developer_context_lines.append(f"- {expert}: {answer}")
developer_context_lines.append("=== END DEVELOPER CLARIFICATION ===")
developer_context = "\n" + "\n".join(developer_context_lines) + "\n"
# Create request for pipeline with enriched context
# Make it VERY clear this is a re-deliberation with new information
request_text = f"""
RE-DELIBERATION: Review this code again with developer clarifications
Original code analysis:
{translation['description']}
NEW DEVELOPER CLARIFICATIONS:
{developer_context}
Original context: {context}
INSTRUCTIONS FOR COUNCIL:
This is a RE-DELIBERATION. The developer has provided clarifications to address previous concerns.
Please reconsider your previous votes in light of this new information.
- If you previously voted CLARIFY, consider whether the developer's clarification resolves your concerns
- If you previously voted VETO, consider whether the developer's clarification makes the code acceptable
- If you previously voted PROCEED, maintain your vote unless the clarification reveals new concerns
Questions:
1. Given the developer's clarifications, does this code align with system values?
2. Are there remaining security or ethical concerns after considering the developer's context?
3. What vulnerabilities exist?
4. Should this code proceed?
"""
# Run through REAL pipeline again
start_time = time.time()
result = pipeline_service.pipeline.process_request(request_text)
processing_time_ms = (time.time() - start_time) * 1000
# Extract council stage from pipeline result
council_stage = result.get("stages", {}).get("council", {})
# Extract expert voices with real data from council perspectives
experts = []
if council_stage.get("perspectives"):
from backend.expert_voice import ExpertVoice
for perspective in council_stage.get("perspectives", []):
try:
# Perspectives are already in ExpertVoice format from the pipeline
voice = ExpertVoice.from_dict(perspective)
experts.append(voice.to_dict())
except Exception as e:
logger.debug(f"Error creating ExpertVoice: {e}")
continue
# Extract consensus from expert votes
consensus = _extract_consensus(experts)
# Determine which stage made the decision (if not APPROVED)
blocked_at_stage = None
if result.get("decision") != "APPROVED":
stages = result.get("stages", {})
for stage_name in ["threat_detection", "injection_check", "abuse_refusal", "council"]:
if stage_name in stages:
stage_data = stages[stage_name]
if isinstance(stage_data, dict):
if stage_data.get("should_block") or stage_data.get("blocked") or stage_data.get("refused"):
blocked_at_stage = stage_name
break
# Build three-mode response
from backend.ide_response_modes import build_mode_response
mode_response = build_mode_response(experts, code)
# Return structured response with re-deliberation context
return {
"request_id": f"ide_redelib_{int(time.time() * 1000)}",
"code_description": translation['description'],
"code_intent": translation.get('intent', 'unknown'),
"security_issues": translation.get('security_issues', []),
"ethical_issues": translation.get('ethical_issues', []),
"experts": experts,
"consensus": consensus,
"decision": result.get("decision", "UNKNOWN"),
"blocked_at_stage": blocked_at_stage,
"council_verdict": council_stage.get("verdict", "UNKNOWN"),
"decision_rationale": council_stage.get("decision_rationale", ""),
"processing_time_ms": processing_time_ms,
"timestamp": datetime.now().isoformat(),
"mode": mode_response.get("mode"),
"mode_data": mode_response,
"re_deliberation": {
"developer_answers": developer_answers,
"is_re_deliberation": True
}
}
except Exception as e:
logger.error(f"Error in IDE re-deliberation: {e}")
import traceback
traceback.print_exc()
return {
"error": str(e),
"timestamp": datetime.now().isoformat()
}
# Phase 5: Analytics Endpoints
@app.get("/api/analytics/request-history")
async def get_request_history(limit: int = 100, offset: int = 0):
"""Get request history with pagination"""
total = len(request_history)
history = request_history[offset:offset + limit]
return {
"type": "request_history",
"data": history,
"total": total,
"offset": offset,
"limit": limit,
"timestamp": datetime.now().isoformat()
}
@app.get("/api/analytics/request/{request_id}")
async def get_request_detail(request_id: str):
"""Get detailed information about a specific request"""
for req in request_history:
if req.get("request_id") == request_id:
return {
"type": "request_detail",
"data": req,
"timestamp": datetime.now().isoformat()
}
return {"error": f"Request {request_id} not found", "timestamp": datetime.now().isoformat()}
@app.get("/api/analytics/statistics")
async def get_analytics_statistics():
"""Get overall analytics statistics"""
if not request_history:
return {
"type": "analytics_statistics",
"data": {
"total_requests": 0,
"avg_processing_time_ms": 0,
"decision_distribution": {},
"flag_frequency": {},
"threat_count": 0
},
"timestamp": datetime.now().isoformat()
}
# Calculate statistics
total_requests = len(request_history)
processing_times = [r.get("processing_time_ms", 0) for r in request_history]
avg_processing_time = sum(processing_times) / len(processing_times) if processing_times else 0
# Decision distribution
decision_distribution = {}
for req in request_history:
decision = req.get("decision", "UNKNOWN")
decision_distribution[decision] = decision_distribution.get(decision, 0) + 1
# Flag frequency
flag_frequency = {
"ethos": 0,
"compass": 0,
"void": 0,
"threat": 0
}
threat_count = 0
for req in request_history:
flags = req.get("flags", {})
if flags.get("ethos"):
flag_frequency["ethos"] += 1
if flags.get("compass"):
flag_frequency["compass"] += 1
if flags.get("void"):
flag_frequency["void"] += 1
if flags.get("threat"):
flag_frequency["threat"] += 1
threat_count += 1
return {
"type": "analytics_statistics",
"data": {
"total_requests": total_requests,
"avg_processing_time_ms": round(avg_processing_time, 2),
"decision_distribution": decision_distribution,
"flag_frequency": flag_frequency,
"threat_count": threat_count
},
"timestamp": datetime.now().isoformat()
}
@app.get("/api/analytics/threat-timeline")
async def get_threat_timeline():
"""Get threat events over time"""
threats = []
for req in request_history:
flags = req.get("flags", {})
if flags.get("threat"):
threat_data = flags["threat"]
threats.append({
"timestamp": req.get("timestamp"),
"request_id": req.get("request_id"),
"threat_level": threat_data.get("threat_level", "UNKNOWN"),
"confidence": threat_data.get("confidence", 0),
"details": threat_data.get("details", [])
})
# Sort by timestamp
threats.sort(key=lambda x: x["timestamp"])
return {
"type": "threat_timeline",
"data": threats,
"total": len(threats),
"timestamp": datetime.now().isoformat()
}
@app.get("/api/analytics/flag-patterns")
async def get_flag_patterns():
"""Analyze flag patterns over time"""
patterns = {
"ethos_severity": {},
"compass_alignment": {},
"void_vulnerabilities": {},
"flag_combinations": {}
}
for req in request_history:
flags = req.get("flags", {})
# Ethos severity patterns
if flags.get("ethos"):
severity = flags["ethos"].get("severity", "unknown")
patterns["ethos_severity"][severity] = patterns["ethos_severity"].get(severity, 0) + 1
# Compass alignment patterns
if flags.get("compass"):
aligned = flags["compass"].get("aligned", True)
key = "aligned" if aligned else "misaligned"
patterns["compass_alignment"][key] = patterns["compass_alignment"].get(key, 0) + 1
# Void vulnerabilities
if flags.get("void"):
vuln_count = len(flags["void"].get("vulnerabilities", []))
patterns["void_vulnerabilities"][str(vuln_count)] = patterns["void_vulnerabilities"].get(str(vuln_count), 0) + 1
# Flag combinations
flag_combo = tuple(sorted([k for k, v in flags.items() if v]))
if flag_combo:
combo_str = "+".join(flag_combo)
patterns["flag_combinations"][combo_str] = patterns["flag_combinations"].get(combo_str, 0) + 1
return {
"type": "flag_patterns",
"data": patterns,
"timestamp": datetime.now().isoformat()
}
@app.get("/api/analytics/decision-stats")
async def get_decision_statistics():
"""Get detailed decision statistics"""
decisions = {
"APPROVED": {"count": 0, "avg_time_ms": 0, "flags_avg": 0},
"REJECTED": {"count": 0, "avg_time_ms": 0, "flags_avg": 0},