-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevolve.py
More file actions
1748 lines (1516 loc) · 68.9 KB
/
evolve.py
File metadata and controls
1748 lines (1516 loc) · 68.9 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
#!/usr/bin/env python3
"""
RE_ware Interactive Agent - Web Dashboard & CLI Interface
========================================================
Multi-mode RE_ware interface supporting both CLI and web-based interaction.
Web mode provides interactive Psi graph visualization with real-time updates.
Usage:
python evolve.py # Interactive CLI mode (default)
python evolve.py --web # Launch with web dashboard
python evolve.py --web --port 8080 # Web dashboard on custom port
Interactive commands:
re_ware> status # Show consciousness state
re_ware> advice # Get project reasoning
re_ware> tick # Execute evolution cycle
re_ware> auto 5 # Enable autonomous mode (5min intervals)
re_ware> save # Save current state
re_ware> quit # Exit system
"""
import sys
import argparse
import asyncio
import json
from pathlib import Path
from typing import Dict, Any, List
# Add the re_ware package to path
sys.path.insert(0, str(Path(__file__).parent))
from re_ware.evolution import REWareInteractive, REWareEvolver
from re_ware.ontology import list_available_gene_templates
from re_ware.sensors import GitSensor, FsSensor, CliSensor, GhSensor
# from re_ware.ci_sensors import GitHubActionsSensor, JUnitTestSensor, PytestCoverageSensor, TestResultSensor
# Web server imports
try:
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
import uvicorn
WEB_DEPENDENCIES_AVAILABLE = True
except ImportError:
WEB_DEPENDENCIES_AVAILABLE = False
class REWareWebServer:
"""Web-based RE_ware dashboard with interactive graph visualization"""
def __init__(self, project_root: Path, schema_name: str = "project_manager", port: int = 8000, enable_web_ui: bool = False):
self.project_root = project_root
self.schema_name = schema_name
self.port = port
self.enable_web_ui = enable_web_ui
self.agent = None
# Configure FastAPI based on mode
if enable_web_ui:
self.app = FastAPI(title="RE_ware Dashboard", description="Interactive Psi Graph Visualization")
else:
self.app = FastAPI(title="RE_ware API", description="REware Core API")
self.active_connections: List[WebSocket] = []
self.auto_tick_interval = 0 # 0 = manual, >0 = auto interval in minutes
self.auto_tick_task = None
self.setup_routes()
def setup_routes(self):
"""Setup FastAPI routes and static files"""
# Root route that dynamically serves dashboard or API info
@self.app.get("/", response_class=HTMLResponse)
async def root_handler(request: Request):
"""Dynamic root handler - dashboard if web UI enabled, API info otherwise"""
if self.enable_web_ui:
return HTMLResponse(content=self.get_dashboard_html(), status_code=200)
else:
# Return API info as JSON but handle HTML response type
from fastapi.responses import JSONResponse
return JSONResponse({
"name": "RE_ware Core API",
"version": "1.0.0",
"endpoints": {
"/api/status": "System status",
"/api/graph": "Ontology graph",
"/api/tick": "Evolution tick",
"/api/advice": "Get advice",
"/api/actions": "List actions"
},
"note": "Use 'ui' command in CLI to enable web dashboard"
})
@self.app.get("/api/status")
async def get_status():
"""Get current system status"""
return await self.get_status_data()
@self.app.get("/api/graph")
async def get_graph():
"""Get current graph data for visualization"""
return await self.get_graph_data()
@self.app.post("/api/tick")
async def manual_tick():
"""Trigger manual evolution tick"""
if not self.agent:
return {"error": "Agent not initialized"}
await self.agent._cmd_tick()
# Broadcast update to connected clients
await self.broadcast_update()
return {"status": "Tick completed"}
@self.app.post("/api/advice")
async def get_advice():
"""Generate project advice with caching"""
if not self.agent:
return {"error": "Agent not initialized"}
# Use the new caching method
return await self.agent.get_advice_with_caching()
@self.app.get("/api/actions")
async def get_actions():
"""Get current idempotent actions from last advice frame"""
if not self.agent:
return {"error": "Agent not initialized"}
try:
phi_signals = self.agent.ontology.phi_signals()
advice_frame = await self.agent.re_agent.generate_advice_frame(
species_id="project_manager_v1",
instance_id=getattr(self.agent.ontology, 'instance_id', 'unknown'),
phi_state=phi_signals
)
actions = advice_frame.get('actions', [])
# Process actions for UI display
processed_actions = []
for action in actions:
processed_actions.append({
"id": action.get('idempotency_key', 'no-key'),
"kind": action.get('kind', 'unknown'),
"title": action.get('title', 'No title'),
"body": action.get('body', ''),
"targets": action.get('targets', []),
"params": action.get('params', {}),
"idempotency_key": action.get('idempotency_key', 'no-key'),
"status": "pending" # Could be "pending", "executed", "failed"
})
return {
"actions": processed_actions,
"total": len(processed_actions),
"phi_state": phi_signals
}
except Exception as e:
return {"error": f"Action retrieval failed: {e}"}
@self.app.post("/api/execute")
async def execute_actions():
"""Execute actions from most recent advice"""
if not self.agent or not self.agent.action_dispatcher:
return {"error": "Agent or action dispatcher not initialized"}
try:
# Find the most recent advice with actions
from re_ware.ontology import NodeType
advice_nodes = [n for n in self.agent.ontology.nodes.values() if n.type == NodeType.ADVICE]
if not advice_nodes:
return {"error": "No advice found. Generate advice first."}
# Sort by creation time (most recent first)
advice_nodes.sort(key=lambda n: n.content.get('generated_at', 0), reverse=True)
most_recent = advice_nodes[0]
actions = most_recent.content.get('actions', [])
if not actions:
return {"message": "No actions to execute in most recent advice", "executed": 0}
# Execute actions
results = await self.agent.action_dispatcher.dispatch_actions(actions)
# Gather external references
external_refs = []
for result in results:
if result.external_refs:
external_refs.extend(result.external_refs)
successful = sum(1 for r in results if r.success)
failed = len(results) - successful
return {
"message": f"Executed {len(actions)} actions",
"executed": len(actions),
"successful": successful,
"failed": failed,
"external_refs": external_refs,
"results": [
{
"kind": r.kind,
"success": r.success,
"message": r.message,
"idempotency_key": r.idempotency_key
} for r in results
]
}
except Exception as e:
return {"error": f"Execution failed: {e}"}
@self.app.post("/api/save")
async def save_snapshot():
"""Save current Ψ snapshot"""
if not self.agent:
return {"error": "Agent not initialized"}
try:
# Get current phi signals for snapshot
phi_signals = self.agent.ontology.phi_signals()
# Use the existing snapshot path or create default
snapshot_path = self.agent.ontology.warm_snapshot_path
if not snapshot_path:
from pathlib import Path
from re_ware.core import SNAPSHOT_FILENAME
snapshot_path = Path(SNAPSHOT_FILENAME)
# Save the snapshot
success = self.agent.ontology.save_snapshot(snapshot_path, phi_data={
"phi0": 0.0, # Will be computed by system
"coverage": phi_signals.get("coverage_ratio", 0.0),
"counters": {
"nodes": len(self.agent.ontology.nodes),
"edges": len(self.agent.ontology.edges),
"changed": len(self.agent.ontology.hot_state.changed_nodes)
},
"computed_at": __import__('time').time()
})
if success:
return {
"status": "Snapshot saved successfully",
"path": str(snapshot_path),
"nodes": len(self.agent.ontology.nodes),
"edges": len(self.agent.ontology.edges)
}
else:
return {"error": "Failed to save snapshot"}
except Exception as e:
return {"error": f"Save failed: {e}"}
@self.app.post("/api/expand-group/{group_id}")
async def expand_group(group_id: str):
"""Expand a group to show its individual files"""
if not self.agent:
return {"error": "Agent not initialized"}
try:
# Get detailed graph data for the specific group
detailed_graph = self._get_expanded_group_data(group_id)
return detailed_graph
except Exception as e:
return {"error": f"Group expansion failed: {e}"}
@self.app.post("/api/auto-tick/{interval}")
async def set_auto_tick(interval: int):
"""Set automatic tick interval in minutes (0 = disabled)"""
self.auto_tick_interval = max(0, interval)
# Cancel existing auto-tick task
if self.auto_tick_task and not self.auto_tick_task.done():
self.auto_tick_task.cancel()
# Start new auto-tick task if interval > 0
if self.auto_tick_interval > 0:
self.auto_tick_task = asyncio.create_task(self.auto_tick_loop())
return {"status": f"Auto-tick set to {self.auto_tick_interval}m"}
@self.app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
"""WebSocket for real-time updates"""
await websocket.accept()
self.active_connections.append(websocket)
try:
while True:
await websocket.receive_text() # Keep connection alive
except WebSocketDisconnect:
# Safe removal - only remove if present
if websocket in self.active_connections:
self.active_connections.remove(websocket)
except Exception as e:
# Handle any other websocket errors
print(f"WebSocket error: {e}")
if websocket in self.active_connections:
self.active_connections.remove(websocket)
async def auto_tick_loop(self):
"""Background task for automatic ticking"""
try:
while self.auto_tick_interval > 0:
# Convert minutes to seconds
await asyncio.sleep(self.auto_tick_interval * 60)
if self.agent:
await self.agent._cmd_tick()
await self.broadcast_update()
except asyncio.CancelledError:
pass
async def broadcast_update(self):
"""Broadcast graph updates to all connected WebSocket clients"""
if not self.active_connections:
return
# Get current graph and status data directly
graph_data = await self.get_graph_data()
status_data = await self.get_status_data()
update_data = {
"type": "graph_update",
"graph": graph_data,
"status": status_data
}
# Send to all connected clients
disconnected = []
for connection in self.active_connections:
try:
await connection.send_text(json.dumps(update_data))
except Exception:
disconnected.append(connection)
# Remove disconnected clients
for conn in disconnected:
self.active_connections.remove(conn)
async def get_status_data(self):
"""Get current system status data"""
if not self.agent:
return {
"phi_metrics": {
"phi0": 0.0,
"coherence": 0.0,
"stability": False,
"cycles": 0
},
"ontology_state": {
"total_nodes": 0,
"total_edges": 0,
"changed_nodes": 0,
"coverage_ratio": 0.0,
"entropy_hint": 0.0
},
"auto_tick_interval": self.auto_tick_interval,
"status": "initializing"
}
try:
phi_signals = self.agent.ontology.phi_signals()
return {
"phi_metrics": {
"phi0": self.agent.state.phi0,
"coherence": self.agent.state.phi_coherence,
"stability": self.agent.state.stability_check,
"cycles": self.agent.state.cycles_completed
},
"ontology_state": {
"total_nodes": len(self.agent.ontology.nodes),
"total_edges": len(self.agent.ontology.edges),
"changed_nodes": len(self.agent.ontology.hot_state.changed_nodes),
"coverage_ratio": phi_signals.get('coverage_ratio', 0.0),
"entropy_hint": phi_signals.get('entropy_hint', 0.0)
},
"auto_tick_interval": self.auto_tick_interval,
"status": "active"
}
except Exception as e:
return {
"phi_metrics": {
"phi0": 0.0,
"coherence": 0.0,
"stability": False,
"cycles": 0
},
"ontology_state": {
"total_nodes": 0,
"total_edges": 0,
"changed_nodes": 0,
"coverage_ratio": 0.0,
"entropy_hint": 0.0
},
"auto_tick_interval": self.auto_tick_interval,
"status": "error",
"error": str(e)
}
async def get_graph_data(self):
"""Get hierarchical graph data for visualization"""
if not self.agent:
# Return a placeholder while agent is initializing
return {
"nodes": [{
"id": "initializing",
"label": "🧠 RE_ware Initializing...",
"type": "SYSTEM",
"status": "initializing",
"criticality": "P1",
"version": "1.0",
"changed": True,
"full_title": "RE_ware System Initializing",
"level": "system"
}],
"edges": []
}
try:
return self._create_hierarchical_graph()
except Exception as e:
# Return error state if graph creation fails
return {
"nodes": [{
"id": "error",
"label": f"❌ Graph Error: {str(e)[:50]}...",
"type": "ERROR",
"status": "error",
"criticality": "P0",
"version": "1.0",
"changed": True,
"full_title": f"Graph generation error: {e}",
"level": "system"
}],
"edges": []
}
def _create_hierarchical_graph(self):
"""Create hierarchical graph with major components and expandable groups"""
nodes = []
edges = []
changed_nodes = set(self.agent.ontology.hot_state.changed_nodes)
# Get all ontology nodes
ontology_nodes = self.agent.ontology.nodes
# Group nodes by type for hierarchical display
node_groups = {
"CODE": [],
"TESTS": [],
"DOCS": [],
"CONFIG": [],
"OTHER": []
}
# Categorize nodes
for node_id, node in ontology_nodes.items():
node_type = node.type.name
if node_type == "PROJECT":
# PROJECT node is always shown at top level
nodes.append({
"id": node_id,
"label": node.title,
"type": node_type,
"status": node.state.status.name if hasattr(node.state.status, 'name') else str(node.state.status),
"criticality": node.state.criticality,
"version": node.state.version,
"changed": node_id in changed_nodes,
"full_title": node.title,
"level": "project",
"expanded": False
})
elif node_type in ["CODEMODULE"]:
node_groups["CODE"].append((node_id, node))
elif node_type in ["TEST", "TESTSUITE"]:
node_groups["TESTS"].append((node_id, node))
elif node_type in ["TECHNICALDOC", "USERDOC", "APIDOC"]:
node_groups["DOCS"].append((node_id, node))
elif node_type in ["DEPENDENCY_SPEC", "CONFIGURATION"]:
node_groups["CONFIG"].append((node_id, node))
else:
node_groups["OTHER"].append((node_id, node))
# Create group nodes for major categories
for group_name, group_nodes in node_groups.items():
if not group_nodes:
continue
# Count changes in this group
group_changed = sum(1 for node_id, _ in group_nodes if node_id in changed_nodes)
total_in_group = len(group_nodes)
# Create group node
group_id = f"GROUP_{group_name}"
group_label = f"{group_name} ({total_in_group})"
if group_changed > 0:
group_label += f" • {group_changed} changed"
nodes.append({
"id": group_id,
"label": group_label,
"type": f"GROUP_{group_name}",
"status": "active",
"criticality": "P1",
"version": "1.0",
"changed": group_changed > 0,
"full_title": f"{group_name} Component Group",
"level": "group",
"expanded": False,
"child_count": total_in_group,
"changed_count": group_changed,
"children": [node_id for node_id, _ in group_nodes]
})
# Create edge from PROJECT to group
project_nodes = [n for n in nodes if n.get("level") == "project"]
if project_nodes:
edges.append({
"id": f"project_to_{group_name}",
"from": project_nodes[0]["id"],
"to": group_id,
"type": "CONTAINS",
"label": "contains"
})
return {"nodes": nodes, "edges": edges}
def _get_expanded_group_data(self, group_id: str):
"""Get detailed graph data when a group is expanded"""
# First get the hierarchical graph
base_graph = self._create_hierarchical_graph()
if not group_id.startswith("GROUP_"):
return base_graph
group_type = group_id.replace("GROUP_", "")
# Find the group node
group_node = None
for node in base_graph["nodes"]:
if node["id"] == group_id:
group_node = node
break
if not group_node or not group_node.get("children"):
return base_graph
# Get the ontology nodes for this group
ontology_nodes = self.agent.ontology.nodes
changed_nodes = set(self.agent.ontology.hot_state.changed_nodes)
# Add individual file nodes for this group
expanded_nodes = list(base_graph["nodes"]) # Start with existing nodes
expanded_edges = list(base_graph["edges"])
for child_id in group_node["children"]:
if child_id in ontology_nodes:
node = ontology_nodes[child_id]
expanded_nodes.append({
"id": child_id,
"label": node.title[:30] + ("..." if len(node.title) > 30 else ""),
"type": node.type.name,
"status": node.state.status.name if hasattr(node.state.status, 'name') else str(node.state.status),
"criticality": node.state.criticality,
"version": node.state.version,
"changed": child_id in changed_nodes,
"full_title": node.title,
"level": "file",
"parent_group": group_id
})
# Create edge from group to child
expanded_edges.append({
"id": f"{group_id}_to_{child_id}",
"from": group_id,
"to": child_id,
"type": "CONTAINS",
"label": ""
})
# Mark the group as expanded
for node in expanded_nodes:
if node["id"] == group_id:
node["expanded"] = True
node["label"] = node["label"].replace(f" ({group_node['child_count']})", f" [EXPANDED]")
break
return {"nodes": expanded_nodes, "edges": expanded_edges}
def get_dashboard_html(self) -> str:
"""Generate dashboard HTML with embedded JavaScript"""
return """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RE_ware Dashboard - Ψ Graph Visualization</title>
<script src="https://unpkg.com/vis-network@9.1.6/standalone/umd/vis-network.min.js"></script>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
margin: 0;
padding: 0;
background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
color: white;
}
.header {
background: rgba(0,0,0,0.2);
padding: 1rem;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid rgba(255,255,255,0.1);
}
.title {
font-size: 1.5rem;
font-weight: bold;
}
.controls {
display: flex;
gap: 1rem;
align-items: center;
}
.btn {
background: rgba(255,255,255,0.1);
border: 1px solid rgba(255,255,255,0.3);
color: white;
padding: 0.5rem 1rem;
border-radius: 4px;
cursor: pointer;
transition: all 0.3s;
}
.btn:hover {
background: rgba(255,255,255,0.2);
transform: translateY(-1px);
}
.btn.active {
background: #4CAF50;
border-color: #45a049;
}
.main-content {
display: flex;
height: calc(100vh - 80px);
}
.graph-panel {
flex: 1;
position: relative;
background: rgba(255,255,255,0.05);
margin: 1rem;
border-radius: 8px;
overflow: hidden;
}
#psi-graph {
width: 100%;
height: 100%;
background: rgba(0,0,0,0.1);
}
.sidebar {
width: 300px;
background: rgba(0,0,0,0.2);
padding: 1rem;
overflow-y: auto;
}
.panel {
background: rgba(255,255,255,0.1);
border-radius: 8px;
padding: 1rem;
margin-bottom: 1rem;
}
.panel h3 {
margin-top: 0;
color: #4CAF50;
}
.metric {
display: flex;
justify-content: space-between;
margin: 0.5rem 0;
}
.metric-value {
font-weight: bold;
}
.status-indicator {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
margin-left: 0.5rem;
}
.status-pass { background: #4CAF50; }
.status-fail { background: #f44336; }
.status-warn { background: #ff9800; }
.advice-content {
max-height: 200px;
overflow-y: auto;
background: rgba(0,0,0,0.2);
padding: 0.5rem;
border-radius: 4px;
margin-top: 0.5rem;
}
.node-info {
background: rgba(0,0,0,0.3);
border-radius: 4px;
padding: 0.5rem;
margin-top: 0.5rem;
font-size: 0.9rem;
}
input[type="range"] {
width: 100%;
margin: 0.5rem 0;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 1rem;
margin: 1rem;
font-size: 0.9rem;
}
.legend-item {
display: flex;
align-items: center;
gap: 0.5rem;
}
.legend-color {
width: 16px;
height: 16px;
border-radius: 50%;
}
</style>
</head>
<body>
<div class="header">
<div class="title">🧠 RE_ware Dashboard - Ψ Graph</div>
<div class="controls">
<button class="btn" onclick="manualTick()">Manual Tick ⚡</button>
<button class="btn" onclick="getAdvice()">Get Advice 🤖</button>
<button class="btn" onclick="executeActions()">Execute Actions 🚀</button>
<button class="btn" onclick="resetGraph()">Reset View 🔄</button>
<span>Auto: <input type="range" min="0" max="10" value="0" id="autoSlider" oninput="setAutoTick(this.value)"> <span id="autoValue">Manual</span></span>
</div>
</div>
<div class="legend">
<div class="legend-item">
<div class="legend-color" style="background: linear-gradient(45deg, #FFD700, #FFA500); border-radius: 50%; width: 20px; height: 20px;"></div>
<span><strong>Project Hub ⭐</strong></span>
</div>
<div class="legend-item">
<div class="legend-color" style="background: #4CAF50; width: 20px; height: 20px; border-radius: 3px;"></div>
<span><strong>CODE Group</strong> (double-click to expand)</span>
</div>
<div class="legend-item">
<div class="legend-color" style="background: #FF9800; width: 20px; height: 20px; border-radius: 3px;"></div>
<span><strong>TESTS Group</strong> (double-click to expand)</span>
</div>
<div class="legend-item">
<div class="legend-color" style="background: #2196F3; width: 20px; height: 20px; border-radius: 3px;"></div>
<span><strong>DOCS Group</strong> (double-click to expand)</span>
</div>
<div class="legend-item">
<div class="legend-color" style="background: #9C27B0; width: 20px; height: 20px; border-radius: 3px;"></div>
<span><strong>CONFIG Group</strong> (double-click to expand)</span>
</div>
<div class="legend-item">
<div class="legend-color" style="background: #f44336;"></div>
<span>Changed/New Files</span>
</div>
</div>
<div class="main-content">
<div class="graph-panel">
<div id="psi-graph"></div>
</div>
<div class="sidebar">
<div class="panel">
<h3>📊 Phi Metrics</h3>
<div class="metric">
<span>Φ₀ (Stability):</span>
<span class="metric-value" id="phi0">0.000</span>
<span class="status-indicator status-fail" id="phi0-status"></span>
</div>
<div class="metric">
<span>Coherence:</span>
<span class="metric-value" id="coherence">0.000</span>
</div>
<div class="metric">
<span>Stability Check:</span>
<span class="metric-value" id="stability">FAIL</span>
<span class="status-indicator status-fail" id="stability-status"></span>
</div>
<div class="metric">
<span>Evolution Cycles:</span>
<span class="metric-value" id="cycles">0</span>
</div>
</div>
<div class="panel">
<h3>🧬 Ontology State</h3>
<div class="metric">
<span>Total Nodes:</span>
<span class="metric-value" id="total-nodes">0</span>
</div>
<div class="metric">
<span>Total Edges:</span>
<span class="metric-value" id="total-edges">0</span>
</div>
<div class="metric">
<span>Changed Nodes:</span>
<span class="metric-value" id="changed-nodes">0</span>
</div>
<div class="metric">
<span>Coverage Ratio:</span>
<span class="metric-value" id="coverage-ratio">0.00</span>
</div>
</div>
<div class="panel">
<h3>🤖 AI Advice</h3>
<div class="advice-content" id="advice-content">
Click "Get Advice" to receive AI recommendations...
</div>
</div>
<div class="panel">
<h3>🔍 Node Details</h3>
<div class="node-info" id="node-info">
Click on a node to see details...
</div>
</div>
<div class="panel">
<h3>⚡ Action Hub</h3>
<div class="metric">
<span>Pending Actions:</span>
<span class="metric-value" id="action-count">0</span>
</div>
<div class="advice-content" id="action-content">
<button class="btn" onclick="loadActions()" style="width: 100%; margin-bottom: 0.5rem;">Load Actions</button>
<div id="action-list">
Click "Load Actions" to see idempotent actions...
</div>
</div>
</div>
</div>
</div>
<script>
let network;
let nodes = new vis.DataSet();
let edges = new vis.DataSet();
let ws;
// Initialize WebSocket connection
function initWebSocket() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
ws = new WebSocket(`${protocol}//${window.location.host}/ws`);
ws.onopen = () => console.log('WebSocket connected');
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'graph_update') {
updateGraph(data.graph);
updateStatus(data.status);
}
};
ws.onclose = () => {
console.log('WebSocket disconnected, attempting reconnect...');
setTimeout(initWebSocket, 3000);
};
}
// Initialize graph visualization
function initGraph() {
const container = document.getElementById('psi-graph');
const data = { nodes: nodes, edges: edges };
const options = {
nodes: {
shape: 'dot',
size: 20,
font: { color: 'white', size: 12 },
borderWidth: 2,
shadow: true
},
edges: {
width: 2,
color: { color: 'rgba(255,255,255,0.4)' },
arrows: { to: { enabled: true, scaleFactor: 0.8 } },
smooth: { type: 'continuous' }
},
physics: {
stabilization: { iterations: 150 },
barnesHut: {
gravitationalConstant: -3000,
springLength: 200,
springConstant: 0.04,
damping: 0.09
},
maxVelocity: 50,
minVelocity: 0.1,
timestep: 0.5
},
interaction: {
hover: true,
tooltipDelay: 300
}
};
network = new vis.Network(container, data, options);
// Center PROJECT node after stabilization
network.on('stabilizationIterationsDone', () => {
centerProjectNode();
});
// Node selection handler
network.on('click', (params) => {
if (params.nodes.length > 0) {
const nodeId = params.nodes[0];
showNodeDetails(nodeId);
}
});
// Double-click handler for group expansion
network.on('doubleClick', (params) => {
if (params.nodes.length > 0) {
const nodeId = params.nodes[0];
expandGroup(nodeId);
}
});
}
// Center the PROJECT node in the visualization
function centerProjectNode() {
if (!network) return;
// Find PROJECT node
const projectNodeId = nodes.get().find(node =>
node.id === 'project:root' ||
(typeof node.type !== 'undefined' && node.type === 'PROJECT')
)?.id;
if (projectNodeId) {
// Position PROJECT node at center (0, 0)
network.moveNode(projectNodeId, 0, 0);
// Briefly focus on the project node to center the view
network.focus(projectNodeId, {
scale: 0.8,
animation: {
duration: 1000,
easingFunction: 'easeInOutQuad'
}
});
console.log('Centered PROJECT node:', projectNodeId);
}
}
// Expand a group to show individual files
async function expandGroup(nodeId) {
// Check if this is a group node that can be expanded
const node = nodes.get(nodeId);
if (!node || !nodeId.startsWith('GROUP_')) {
return;
}
console.log('Expanding group:', nodeId);