File size: 58,545 Bytes
0f336cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
import asyncio
from datetime import datetime, timezone
import json
import sqlite3
from typing import Any, Dict, List, Optional
import uuid

from schemas.enums import AgentState, DecisionStage, MissionStatus
from schemas.models import (
    AgentMessage,
    AgentReflectionDetail,
    AgentReputationModel,
    ApprovalRequestModel,
    BlackboardEntry,
    ConversationMessageModel,
    DebateSession,
    DiscussionEntry,
    EvidenceScore,
    KnowledgeEdge,
    KnowledgeNode,
    MissionContextModel,
    NotificationModel,
    TimelineEventModel,
)


class DatabaseManager:
    """SQLite Database Engine for Spark Colony System State, Memory & Logs."""

    def __init__(self, db_path: str = "spark_colony.db"):
        self.db_path = db_path
        self._init_db()

    def _get_connection(self) -> sqlite3.Connection:
        conn = sqlite3.connect(self.db_path, check_same_thread=False)
        conn.row_factory = sqlite3.Row
        conn.execute("PRAGMA journal_mode=WAL;")
        return conn

    def _init_db(self) -> None:
        with self._get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS missions (
                    id TEXT PRIMARY KEY,
                    topic TEXT NOT NULL,
                    status TEXT NOT NULL,
                    stage TEXT NOT NULL,
                    created_at TEXT NOT NULL,
                    updated_at TEXT NOT NULL,
                    summary TEXT,
                    total_cost REAL DEFAULT 0.0
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS agents (
                    id TEXT PRIMARY KEY,
                    name TEXT NOT NULL,
                    role TEXT NOT NULL,
                    state TEXT NOT NULL,
                    current_task TEXT,
                    confidence REAL NOT NULL,
                    last_active TEXT NOT NULL,
                    enabled INTEGER DEFAULT 1
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS memories (
                    id TEXT PRIMARY KEY,
                    agent_id TEXT NOT NULL,
                    mission_id TEXT NOT NULL,
                    content TEXT NOT NULL,
                    tags TEXT,
                    created_at TEXT NOT NULL
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS journals (
                    id TEXT PRIMARY KEY,
                    agent_id TEXT NOT NULL,
                    mission_id TEXT NOT NULL,
                    entry TEXT NOT NULL,
                    timestamp TEXT NOT NULL
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS messages (
                    id TEXT PRIMARY KEY,
                    sender TEXT NOT NULL,
                    recipient TEXT NOT NULL,
                    mission_id TEXT NOT NULL,
                    status TEXT NOT NULL,
                    summary TEXT NOT NULL,
                    next_request TEXT NOT NULL,
                    confidence REAL NOT NULL,
                    timestamp TEXT NOT NULL
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS evidence (
                    id TEXT PRIMARY KEY,
                    mission_id TEXT NOT NULL,
                    agent_id TEXT NOT NULL,
                    claim TEXT NOT NULL,
                    source TEXT NOT NULL,
                    credibility REAL NOT NULL,
                    freshness REAL NOT NULL,
                    authority REAL NOT NULL,
                    agreement REAL NOT NULL,
                    conflict REAL NOT NULL,
                    confidence REAL NOT NULL,
                    created_at TEXT NOT NULL
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS token_costs (
                    id TEXT PRIMARY KEY,
                    mission_id TEXT NOT NULL,
                    agent_id TEXT NOT NULL,
                    prompt_tokens INT DEFAULT 0,
                    completion_tokens INT DEFAULT 0,
                    reasoning_tokens INT DEFAULT 0,
                    vision_tokens INT DEFAULT 0,
                    cost_usd REAL DEFAULT 0.0,
                    timestamp TEXT NOT NULL
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS browser_cache (
                    id TEXT PRIMARY KEY,
                    url TEXT UNIQUE NOT NULL,
                    html TEXT NOT NULL,
                    title TEXT,
                    cached_at TEXT NOT NULL
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS plugins (
                    id TEXT PRIMARY KEY,
                    name TEXT UNIQUE NOT NULL,
                    version TEXT NOT NULL,
                    description TEXT NOT NULL,
                    entry_point TEXT NOT NULL,
                    permissions TEXT,
                    status TEXT NOT NULL,
                    registered_at TEXT NOT NULL
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS reflections (
                    id TEXT PRIMARY KEY,
                    mission_id TEXT NOT NULL,
                    agent_id TEXT NOT NULL,
                    lessons_learned TEXT NOT NULL,
                    mistakes_identified TEXT,
                    cost_usd REAL NOT NULL,
                    confidence_achieved REAL NOT NULL,
                    created_at TEXT NOT NULL,
                    FOREIGN KEY (mission_id) REFERENCES missions (id)
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS website_profiles (
                    domain TEXT PRIMARY KEY,
                    trust_score REAL NOT NULL,
                    authority REAL NOT NULL,
                    typical_layout TEXT NOT NULL,
                    has_captcha_history INTEGER DEFAULT 0,
                    interaction_success_rate REAL DEFAULT 100.0,
                    last_visited TEXT NOT NULL
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS screen_memories (
                    id TEXT PRIMARY KEY,
                    mission_id TEXT NOT NULL,
                    url TEXT NOT NULL,
                    screenshot_ref TEXT NOT NULL,
                    layout_summary TEXT NOT NULL,
                    timestamp TEXT NOT NULL
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS downloaded_files (
                    id TEXT PRIMARY KEY,
                    mission_id TEXT NOT NULL,
                    filename TEXT NOT NULL,
                    mime_type TEXT NOT NULL,
                    file_size INTEGER NOT NULL,
                    summary TEXT,
                    created_at TEXT NOT NULL
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS checkpoints (
                    id TEXT PRIMARY KEY,
                    mission_id TEXT NOT NULL,
                    stage TEXT NOT NULL,
                    data_json TEXT NOT NULL,
                    created_at TEXT NOT NULL,
                    FOREIGN KEY (mission_id) REFERENCES missions (id)
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS knowledge_nodes (
                    id TEXT PRIMARY KEY,
                    mission_id TEXT NOT NULL,
                    label TEXT NOT NULL,
                    entity_type TEXT NOT NULL,
                    confidence REAL NOT NULL
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS knowledge_edges (
                    id TEXT PRIMARY KEY,
                    mission_id TEXT NOT NULL,
                    source_node_id TEXT NOT NULL,
                    target_node_id TEXT NOT NULL,
                    relationship TEXT NOT NULL,
                    FOREIGN KEY (source_node_id) REFERENCES knowledge_nodes (id),
                    FOREIGN KEY (target_node_id) REFERENCES knowledge_nodes (id)
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS blackboard (
                    id TEXT PRIMARY KEY,
                    mission_id TEXT NOT NULL,
                    agent_id TEXT NOT NULL,
                    topic TEXT NOT NULL,
                    data_json TEXT NOT NULL,
                    timestamp TEXT NOT NULL
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS mission_contexts (
                    mission_id TEXT PRIMARY KEY,
                    topic TEXT NOT NULL,
                    priority INTEGER DEFAULT 5,
                    current_phase TEXT NOT NULL,
                    progress_percent REAL DEFAULT 0.0,
                    owner_agent TEXT NOT NULL,
                    resource_usage_json TEXT NOT NULL,
                    estimated_cost REAL DEFAULT 0.0,
                    health_status TEXT DEFAULT 'HEALTHY',
                    retry_count INTEGER DEFAULT 0,
                    checkpoint_state TEXT,
                    created_at TEXT NOT NULL
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS mission_timeline (
                    id TEXT PRIMARY KEY,
                    mission_id TEXT NOT NULL,
                    agent_id TEXT NOT NULL,
                    step_type TEXT NOT NULL,
                    description TEXT NOT NULL,
                    metadata_json TEXT NOT NULL,
                    timestamp TEXT NOT NULL
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS discussions (
                    id TEXT PRIMARY KEY,
                    mission_id TEXT NOT NULL,
                    agent_id TEXT NOT NULL,
                    agent_name TEXT NOT NULL,
                    discussion_type TEXT NOT NULL,
                    topic TEXT NOT NULL,
                    content TEXT NOT NULL,
                    evidence_ref TEXT,
                    tags_json TEXT,
                    confidence REAL NOT NULL,
                    timestamp TEXT NOT NULL
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS debates (
                    debate_id TEXT PRIMARY KEY,
                    mission_id TEXT NOT NULL,
                    topic TEXT NOT NULL,
                    status TEXT NOT NULL,
                    participants_json TEXT NOT NULL,
                    turns_json TEXT NOT NULL,
                    consensus_summary TEXT,
                    final_confidence REAL NOT NULL,
                    created_at TEXT NOT NULL
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS agent_reputations (
                    agent_id TEXT PRIMARY KEY,
                    name TEXT NOT NULL,
                    role TEXT NOT NULL,
                    experience_points INTEGER DEFAULT 100,
                    trust_score REAL DEFAULT 100.0,
                    accuracy_rate REAL DEFAULT 100.0,
                    reliability_score REAL DEFAULT 100.0,
                    speed_score REAL DEFAULT 100.0,
                    cost_efficiency REAL DEFAULT 100.0,
                    avg_confidence REAL DEFAULT 100.0,
                    success_rate REAL DEFAULT 100.0,
                    total_missions_participated INTEGER DEFAULT 0
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS agent_reflections_v2 (
                    reflection_id TEXT PRIMARY KEY,
                    mission_id TEXT NOT NULL,
                    agent_id TEXT NOT NULL,
                    agent_name TEXT NOT NULL,
                    what_worked TEXT NOT NULL,
                    what_failed TEXT NOT NULL,
                    what_surprised TEXT NOT NULL,
                    what_to_improve TEXT NOT NULL,
                    timestamp TEXT NOT NULL
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS approval_requests (
                    id TEXT PRIMARY KEY,
                    mission_id TEXT NOT NULL,
                    agent_id TEXT NOT NULL,
                    action_type TEXT NOT NULL,
                    prompt_message TEXT NOT NULL,
                    status TEXT NOT NULL,
                    input_data_json TEXT,
                    created_at TEXT NOT NULL
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS notifications (
                    id TEXT PRIMARY KEY,
                    level TEXT NOT NULL,
                    title TEXT NOT NULL,
                    message TEXT NOT NULL,
                    mission_id TEXT,
                    acknowledged INTEGER DEFAULT 0,
                    created_at TEXT NOT NULL
                )
            """)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS conversation_logs (
                    id TEXT PRIMARY KEY,
                    user_id TEXT NOT NULL,
                    sender TEXT NOT NULL,
                    message TEXT NOT NULL,
                    metadata_json TEXT,
                    timestamp TEXT NOT NULL
                )
            """)
            # Safe schema migration for blackboard
            try:
                cursor.execute("ALTER TABLE blackboard ADD COLUMN version INTEGER DEFAULT 1")
                cursor.execute("ALTER TABLE blackboard ADD COLUMN tags_json TEXT DEFAULT '[]'")
                cursor.execute("ALTER TABLE blackboard ADD COLUMN priority INTEGER DEFAULT 5")
                cursor.execute("ALTER TABLE blackboard ADD COLUMN confidence REAL DEFAULT 100.0")
            except sqlite3.OperationalError:
                pass  # Columns already exist
            conn.commit()

    async def save_mission(
        self,
        mission_id: str,
        topic: str,
        status: MissionStatus,
        stage: DecisionStage,
        summary: Optional[str] = None,
        total_cost: float = 0.0,
    ) -> None:
        def _exec():
            now = datetime.now(timezone.utc).isoformat()
            with self._get_connection() as conn:
                conn.execute(
                    """
                    INSERT INTO missions (id, topic, status, stage, created_at, updated_at, summary, total_cost)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                    ON CONFLICT(id) DO UPDATE SET
                        status=excluded.status,
                        stage=excluded.stage,
                        updated_at=excluded.updated_at,
                        summary=COALESCE(excluded.summary, missions.summary),
                        total_cost=missions.total_cost + excluded.total_cost
                    """,
                    (mission_id, topic, status.value, stage.value, now, now, summary, total_cost),
                )
                conn.commit()

        await asyncio.to_thread(_exec)

    async def update_mission_status(self, mission_id: str, status: MissionStatus, stage: Optional[DecisionStage] = None) -> None:
        def _exec():
            now = datetime.now(timezone.utc).isoformat()
            with self._get_connection() as conn:
                if stage:
                    conn.execute("UPDATE missions SET status=?, stage=?, updated_at=? WHERE id=?", (status.value, stage.value, now, mission_id))
                else:
                    conn.execute("UPDATE missions SET status=?, updated_at=? WHERE id=?", (status.value, now, mission_id))
                conn.commit()

        await asyncio.to_thread(_exec)

    async def delete_mission(self, mission_id: str) -> None:
        def _exec():
            with self._get_connection() as conn:
                conn.execute("DELETE FROM missions WHERE id=?", (mission_id,))
                conn.execute("DELETE FROM memories WHERE mission_id=?", (mission_id,))
                conn.execute("DELETE FROM journals WHERE mission_id=?", (mission_id,))
                conn.execute("DELETE FROM messages WHERE mission_id=?", (mission_id,))
                conn.execute("DELETE FROM evidence WHERE mission_id=?", (mission_id,))
                conn.execute("DELETE FROM reflections WHERE mission_id=?", (mission_id,))
                conn.execute("DELETE FROM screen_memories WHERE mission_id=?", (mission_id,))
                conn.execute("DELETE FROM downloaded_files WHERE mission_id=?", (mission_id,))
                conn.execute("DELETE FROM checkpoints WHERE mission_id=?", (mission_id,))
                conn.execute("DELETE FROM knowledge_nodes WHERE mission_id=?", (mission_id,))
                conn.execute("DELETE FROM knowledge_edges WHERE mission_id=?", (mission_id,))
                conn.execute("DELETE FROM blackboard WHERE mission_id=?", (mission_id,))
                conn.execute("DELETE FROM mission_contexts WHERE mission_id=?", (mission_id,))
                conn.execute("DELETE FROM mission_timeline WHERE mission_id=?", (mission_id,))
                conn.execute("DELETE FROM discussions WHERE mission_id=?", (mission_id,))
                conn.execute("DELETE FROM debates WHERE mission_id=?", (mission_id,))
                conn.execute("DELETE FROM agent_reflections_v2 WHERE mission_id=?", (mission_id,))
                conn.execute("DELETE FROM approval_requests WHERE mission_id=?", (mission_id,))
                conn.execute("DELETE FROM notifications WHERE mission_id=?", (mission_id,))
                conn.commit()

        await asyncio.to_thread(_exec)

    async def get_mission(self, mission_id: str) -> Optional[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM missions WHERE id = ?", (mission_id,))
                row = cursor.fetchone()
                return dict(row) if row else None

        return await asyncio.to_thread(_exec)

    async def get_all_missions(self) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM missions ORDER BY created_at DESC")
                return [dict(row) for row in cursor.fetchall()]

        return await asyncio.to_thread(_exec)

    async def count_missions(self) -> int:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT COUNT(*) FROM missions")
                return cursor.fetchone()[0]

        return await asyncio.to_thread(_exec)

    async def upsert_agent(
        self, agent_id: str, name: str, role: str, state: AgentState, current_task: Optional[str], confidence: float, enabled: bool = True
    ) -> None:
        def _exec():
            now = datetime.now(timezone.utc).isoformat()
            with self._get_connection() as conn:
                conn.execute(
                    """
                    INSERT INTO agents (id, name, role, state, current_task, confidence, last_active, enabled)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                    ON CONFLICT(id) DO UPDATE SET
                        name=excluded.name,
                        role=excluded.role,
                        state=excluded.state,
                        current_task=excluded.current_task,
                        confidence=excluded.confidence,
                        last_active=excluded.last_active,
                        enabled=excluded.enabled
                    """,
                    (agent_id, name, role, state.value, current_task, confidence, now, 1 if enabled else 0),
                )
                conn.commit()

        await asyncio.to_thread(_exec)

    async def get_all_agents(self) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM agents")
                return [dict(row) for row in cursor.fetchall()]

        return await asyncio.to_thread(_exec)

    async def get_agent(self, agent_id: str) -> Optional[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM agents WHERE id=?", (agent_id,))
                row = cursor.fetchone()
                return dict(row) if row else None

        return await asyncio.to_thread(_exec)

    async def save_memory(self, agent_id: str, mission_id: str, content: str, tags: List[str]) -> str:
        memory_id = str(uuid.uuid4())
        tags_str = json.dumps(tags)
        now = datetime.now(timezone.utc).isoformat()

        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    "INSERT INTO memories (id, agent_id, mission_id, content, tags, created_at) VALUES (?, ?, ?, ?, ?, ?)",
                    (memory_id, agent_id, mission_id, content, tags_str, now),
                )
                conn.commit()

        await asyncio.to_thread(_exec)
        return memory_id

    async def search_memories(self, query: str, tag: Optional[str] = None) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                if tag:
                    cursor.execute("SELECT * FROM memories WHERE content LIKE ? AND tags LIKE ?", (f"%{query}%", f"%{tag}%"))
                else:
                    cursor.execute("SELECT * FROM memories WHERE content LIKE ?", (f"%{query}%",))
                rows = cursor.fetchall()
                results = []
                for r in rows:
                    item = dict(r)
                    item["tags"] = json.loads(item["tags"]) if item["tags"] else []
                    results.append(item)
                return results

        return await asyncio.to_thread(_exec)

    async def delete_memory(self, memory_id: str) -> None:
        def _exec():
            with self._get_connection() as conn:
                conn.execute("DELETE FROM memories WHERE id=?", (memory_id,))
                conn.commit()

        await asyncio.to_thread(_exec)

    async def get_memories_for_mission(self, mission_id: str) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM memories WHERE mission_id = ? ORDER BY created_at ASC", (mission_id,))
                rows = cursor.fetchall()
                results = []
                for row in rows:
                    item = dict(row)
                    item["tags"] = json.loads(item["tags"]) if item["tags"] else []
                    results.append(item)
                return results

        return await asyncio.to_thread(_exec)

    async def count_memories(self) -> int:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT COUNT(*) FROM memories")
                return cursor.fetchone()[0]

        return await asyncio.to_thread(_exec)

    async def save_journal(self, agent_id: str, mission_id: str, entry: str) -> str:
        journal_id = str(uuid.uuid4())
        now = datetime.now(timezone.utc).isoformat()

        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    "INSERT INTO journals (id, agent_id, mission_id, entry, timestamp) VALUES (?, ?, ?, ?, ?)",
                    (journal_id, agent_id, mission_id, entry, now),
                )
                conn.commit()

        await asyncio.to_thread(_exec)
        return journal_id

    async def get_journals_for_mission(self, mission_id: str) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM journals WHERE mission_id = ? ORDER BY timestamp ASC", (mission_id,))
                return [dict(row) for row in cursor.fetchall()]

        return await asyncio.to_thread(_exec)

    async def save_message(self, message: AgentMessage) -> None:
        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    """
                    INSERT INTO messages (id, sender, recipient, mission_id, status, summary, next_request, confidence, timestamp)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                    """,
                    (
                        message.id,
                        message.sender,
                        message.recipient,
                        message.mission_id,
                        message.status,
                        message.summary,
                        message.next_request,
                        message.confidence,
                        message.timestamp,
                    ),
                )
                conn.commit()

        await asyncio.to_thread(_exec)

    async def get_messages_for_mission(self, mission_id: str) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM messages WHERE mission_id = ? ORDER BY timestamp ASC", (mission_id,))
                return [dict(row) for row in cursor.fetchall()]

        return await asyncio.to_thread(_exec)

    async def count_messages(self) -> int:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT COUNT(*) FROM messages")
                return cursor.fetchone()[0]

        return await asyncio.to_thread(_exec)

    async def save_evidence(
        self,
        mission_id: str,
        agent_id: str,
        claim: str,
        source: str,
        score: EvidenceScore,
    ) -> str:
        evidence_id = str(uuid.uuid4())
        now = datetime.now(timezone.utc).isoformat()

        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    """
                    INSERT INTO evidence (id, mission_id, agent_id, claim, source, credibility, freshness, authority, agreement, conflict, confidence, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    """,
                    (
                        evidence_id,
                        mission_id,
                        agent_id,
                        claim,
                        source,
                        score.credibility,
                        score.freshness,
                        score.authority,
                        score.agreement,
                        score.conflict,
                        score.overall_confidence,
                        now,
                    ),
                )
                conn.commit()

        await asyncio.to_thread(_exec)
        return evidence_id

    async def get_evidence_for_mission(self, mission_id: str) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM evidence WHERE mission_id = ? ORDER BY created_at ASC", (mission_id,))
                return [dict(row) for row in cursor.fetchall()]

        return await asyncio.to_thread(_exec)

    async def record_tokens(
        self,
        mission_id: str,
        agent_id: str,
        prompt_tokens: int,
        completion_tokens: int,
        reasoning_tokens: int,
        vision_tokens: int,
        cost_usd: float,
    ) -> None:
        token_id = str(uuid.uuid4())
        now = datetime.now(timezone.utc).isoformat()

        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    """
                    INSERT INTO token_costs (id, mission_id, agent_id, prompt_tokens, completion_tokens, reasoning_tokens, vision_tokens, cost_usd, timestamp)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                    """,
                    (token_id, mission_id, agent_id, prompt_tokens, completion_tokens, reasoning_tokens, vision_tokens, cost_usd, now),
                )
                conn.commit()

        await asyncio.to_thread(_exec)

    async def get_total_system_cost(self) -> float:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT SUM(cost_usd) FROM token_costs")
                res = cursor.fetchone()[0]
                return res if res else 0.0

        return await asyncio.to_thread(_exec)

    async def save_browser_cache(self, url: str, html: str, title: Optional[str]) -> str:
        cache_id = str(uuid.uuid4())
        now = datetime.now(timezone.utc).isoformat()

        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    """
                    INSERT INTO browser_cache (id, url, html, title, cached_at)
                    VALUES (?, ?, ?, ?, ?)
                    ON CONFLICT(url) DO UPDATE SET html=excluded.html, title=excluded.title, cached_at=excluded.cached_at
                    """,
                    (cache_id, url, html, title, now),
                )
                conn.commit()

        await asyncio.to_thread(_exec)
        return cache_id

    async def clear_browser_cache(self) -> None:
        def _exec():
            with self._get_connection() as conn:
                conn.execute("DELETE FROM browser_cache")
                conn.commit()

        await asyncio.to_thread(_exec)

    async def save_plugin(self, name: str, version: str, description: str, entry_point: str, permissions: List[str]) -> str:
        plugin_id = str(uuid.uuid4())
        now = datetime.now(timezone.utc).isoformat()
        perms_str = json.dumps(permissions)

        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    """
                    INSERT INTO plugins (id, name, version, description, entry_point, permissions, status, registered_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                    ON CONFLICT(name) DO UPDATE SET version=excluded.version, status=excluded.status
                    """,
                    (plugin_id, name, version, description, entry_point, perms_str, "ACTIVE", now),
                )
                conn.commit()

        await asyncio.to_thread(_exec)
        return plugin_id

    async def get_all_plugins(self) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM plugins")
                rows = cursor.fetchall()
                results = []
                for r in rows:
                    item = dict(r)
                    item["permissions"] = json.loads(item["permissions"]) if item["permissions"] else []
                    results.append(item)
                return results

        return await asyncio.to_thread(_exec)

    async def save_reflection(
        self,
        mission_id: str,
        agent_id: str,
        lessons_learned: str,
        mistakes_identified: Optional[str],
        cost_usd: float,
        confidence_achieved: float,
    ) -> str:
        ref_id = str(uuid.uuid4())
        now = datetime.now(timezone.utc).isoformat()

        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    """
                    INSERT INTO reflections (id, mission_id, agent_id, lessons_learned, mistakes_identified, cost_usd, confidence_achieved, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                    """,
                    (ref_id, mission_id, agent_id, lessons_learned, mistakes_identified, cost_usd, confidence_achieved, now),
                )
                conn.commit()

        await asyncio.to_thread(_exec)
        return ref_id

    async def get_reflections_for_mission(self, mission_id: str) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM reflections WHERE mission_id = ? ORDER BY created_at ASC", (mission_id,))
                return [dict(row) for row in cursor.fetchall()]

        return await asyncio.to_thread(_exec)

    async def get_all_reflections(self) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM reflections ORDER BY created_at DESC")
                return [dict(row) for row in cursor.fetchall()]

        return await asyncio.to_thread(_exec)

    async def upsert_website_profile(
        self,
        domain: str,
        trust_score: float,
        authority: float,
        typical_layout: str,
        has_captcha: bool = False,
        success_rate: float = 100.0,
    ) -> None:
        def _exec():
            now = datetime.now(timezone.utc).isoformat()
            with self._get_connection() as conn:
                conn.execute(
                    """
                    INSERT INTO website_profiles (domain, trust_score, authority, typical_layout, has_captcha_history, interaction_success_rate, last_visited)
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                    ON CONFLICT(domain) DO UPDATE SET
                        trust_score=excluded.trust_score,
                        authority=excluded.authority,
                        typical_layout=excluded.typical_layout,
                        has_captcha_history=excluded.has_captcha_history,
                        interaction_success_rate=excluded.interaction_success_rate,
                        last_visited=excluded.last_visited
                    """,
                    (domain, trust_score, authority, typical_layout, 1 if has_captcha else 0, success_rate, now),
                )
                conn.commit()

        await asyncio.to_thread(_exec)

    async def get_website_profiles(self) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM website_profiles ORDER BY trust_score DESC")
                return [dict(row) for row in cursor.fetchall()]

        return await asyncio.to_thread(_exec)

    async def save_screen_memory(self, mission_id: str, url: str, screenshot_ref: str, layout_summary: str) -> str:
        mem_id = str(uuid.uuid4())
        now = datetime.now(timezone.utc).isoformat()

        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    "INSERT INTO screen_memories (id, mission_id, url, screenshot_ref, layout_summary, timestamp) VALUES (?, ?, ?, ?, ?, ?)",
                    (mem_id, mission_id, url, screenshot_ref, layout_summary, now),
                )
                conn.commit()

        await asyncio.to_thread(_exec)
        return mem_id

    async def save_downloaded_file(self, mission_id: str, filename: str, mime_type: str, file_size: int, summary: str) -> str:
        file_id = str(uuid.uuid4())
        now = datetime.now(timezone.utc).isoformat()

        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    "INSERT INTO downloaded_files (id, mission_id, filename, mime_type, file_size, summary, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
                    (file_id, mission_id, filename, mime_type, file_size, summary, now),
                )
                conn.commit()

        await asyncio.to_thread(_exec)
        return file_id

    async def get_downloaded_files(self) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM downloaded_files ORDER BY created_at DESC")
                return [dict(row) for row in cursor.fetchall()]

        return await asyncio.to_thread(_exec)

    async def save_checkpoint(self, mission_id: str, stage: DecisionStage, data: Dict[str, Any]) -> str:
        cp_id = str(uuid.uuid4())
        now = datetime.now(timezone.utc).isoformat()
        data_str = json.dumps(data)

        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    "INSERT INTO checkpoints (id, mission_id, stage, data_json, created_at) VALUES (?, ?, ?, ?, ?)",
                    (cp_id, mission_id, stage.value, data_str, now),
                )
                conn.commit()

        await asyncio.to_thread(_exec)
        return cp_id

    async def get_latest_checkpoint(self, mission_id: str) -> Optional[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM checkpoints WHERE mission_id = ? ORDER BY created_at DESC LIMIT 1", (mission_id,))
                row = cursor.fetchone()
                if not row:
                    return None
                item = dict(row)
                item["data"] = json.loads(item["data_json"])
                return item

        return await asyncio.to_thread(_exec)

    async def get_checkpoints_for_mission(self, mission_id: str) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM checkpoints WHERE mission_id = ? ORDER BY created_at ASC", (mission_id,))
                rows = cursor.fetchall()
                results = []
                for r in rows:
                    item = dict(r)
                    item["data"] = json.loads(item["data_json"])
                    results.append(item)
                return results

        return await asyncio.to_thread(_exec)

    async def save_knowledge_node(self, node: KnowledgeNode) -> None:
        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    "INSERT INTO knowledge_nodes (id, mission_id, label, entity_type, confidence) VALUES (?, ?, ?, ?, ?)",
                    (node.id, node.mission_id, node.label, node.entity_type, node.confidence),
                )
                conn.commit()

        await asyncio.to_thread(_exec)

    async def save_knowledge_edge(self, edge: KnowledgeEdge) -> None:
        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    "INSERT INTO knowledge_edges (id, mission_id, source_node_id, target_node_id, relationship) VALUES (?, ?, ?, ?, ?)",
                    (edge.id, edge.mission_id, edge.source_node_id, edge.target_node_id, edge.relationship),
                )
                conn.commit()

        await asyncio.to_thread(_exec)

    async def get_knowledge_graph(self, mission_id: str) -> Dict[str, Any]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM knowledge_nodes WHERE mission_id=?", (mission_id,))
                nodes = [dict(r) for r in cursor.fetchall()]
                cursor.execute("SELECT * FROM knowledge_edges WHERE mission_id=?", (mission_id,))
                edges = [dict(r) for r in cursor.fetchall()]
                return {"mission_id": mission_id, "nodes": nodes, "edges": edges}

        return await asyncio.to_thread(_exec)

    async def save_blackboard_entry(self, entry: BlackboardEntry) -> None:
        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    "INSERT INTO blackboard (id, mission_id, agent_id, topic, data_json, timestamp) VALUES (?, ?, ?, ?, ?, ?)",
                    (entry.id, entry.mission_id, entry.agent_id, entry.topic, json.dumps(entry.data), entry.timestamp),
                )
                conn.commit()

        await asyncio.to_thread(_exec)

    async def get_blackboard_entries(self, mission_id: str, topic: Optional[str] = None) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                if topic:
                    cursor.execute("SELECT * FROM blackboard WHERE mission_id = ? AND topic = ? ORDER BY timestamp ASC", (mission_id, topic))
                else:
                    cursor.execute("SELECT * FROM blackboard WHERE mission_id = ? ORDER BY timestamp ASC", (mission_id,))
                rows = cursor.fetchall()
                results = []
                for r in rows:
                    item = dict(r)
                    item["data"] = json.loads(item["data_json"])
                    results.append(item)
                return results

        return await asyncio.to_thread(_exec)

    async def save_mission_context(self, ctx: MissionContextModel) -> None:
        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    """
                    INSERT INTO mission_contexts 
                    (mission_id, topic, priority, current_phase, progress_percent, owner_agent, resource_usage_json, estimated_cost, health_status, retry_count, checkpoint_state, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ON CONFLICT(mission_id) DO UPDATE SET
                        current_phase=excluded.current_phase,
                        progress_percent=excluded.progress_percent,
                        resource_usage_json=excluded.resource_usage_json,
                        estimated_cost=excluded.estimated_cost,
                        health_status=excluded.health_status,
                        retry_count=excluded.retry_count,
                        checkpoint_state=excluded.checkpoint_state
                    """,
                    (
                        ctx.mission_id,
                        ctx.topic,
                        ctx.priority,
                        ctx.current_phase.value,
                        ctx.progress_percent,
                        ctx.owner_agent,
                        json.dumps(ctx.resource_usage),
                        ctx.estimated_cost,
                        ctx.health_status,
                        ctx.retry_count,
                        ctx.checkpoint_state,
                        ctx.created_at,
                    ),
                )
                conn.commit()

        await asyncio.to_thread(_exec)

    async def get_all_mission_contexts(self) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM mission_contexts ORDER BY created_at DESC")
                rows = cursor.fetchall()
                results = []
                for r in rows:
                    item = dict(r)
                    item["resource_usage"] = json.loads(item["resource_usage_json"])
                    results.append(item)
                return results

        return await asyncio.to_thread(_exec)

    async def save_timeline_event(self, event: TimelineEventModel) -> None:
        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    "INSERT INTO mission_timeline (id, mission_id, agent_id, step_type, description, metadata_json, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?)",
                    (event.id, event.mission_id, event.agent_id, event.step_type.value, event.description, json.dumps(event.metadata), event.timestamp),
                )
                conn.commit()

        await asyncio.to_thread(_exec)

    async def get_mission_timeline(self, mission_id: str) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM mission_timeline WHERE mission_id = ? ORDER BY timestamp ASC", (mission_id,))
                rows = cursor.fetchall()
                results = []
                for r in rows:
                    item = dict(r)
                    item["metadata"] = json.loads(item["metadata_json"])
                    results.append(item)
                return results

        return await asyncio.to_thread(_exec)

    async def save_discussion_entry(self, entry: DiscussionEntry) -> None:
        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    """
                    INSERT INTO discussions (id, mission_id, agent_id, agent_name, discussion_type, topic, content, evidence_ref, tags_json, confidence, timestamp)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    """,
                    (
                        entry.id,
                        entry.mission_id,
                        entry.agent_id,
                        entry.agent_name,
                        entry.discussion_type.value,
                        entry.topic,
                        entry.content,
                        entry.evidence_ref,
                        json.dumps(entry.tags),
                        entry.confidence,
                        entry.timestamp,
                    ),
                )
                conn.commit()

        await asyncio.to_thread(_exec)

    async def get_discussions_for_mission(self, mission_id: str, tag: Optional[str] = None) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                if tag:
                    cursor.execute("SELECT * FROM discussions WHERE mission_id = ? AND tags_json LIKE ? ORDER BY timestamp ASC", (mission_id, f"%{tag}%"))
                else:
                    cursor.execute("SELECT * FROM discussions WHERE mission_id = ? ORDER BY timestamp ASC", (mission_id,))
                rows = cursor.fetchall()
                results = []
                for r in rows:
                    item = dict(r)
                    item["tags"] = json.loads(item["tags_json"]) if item.get("tags_json") else []
                    results.append(item)
                return results

        return await asyncio.to_thread(_exec)

    async def save_debate_session(self, debate: DebateSession) -> None:
        def _exec():
            with self._get_connection() as conn:
                turns_json = json.dumps([t.model_dump() for t in debate.turns])
                conn.execute(
                    """
                    INSERT INTO debates (debate_id, mission_id, topic, status, participants_json, turns_json, consensus_summary, final_confidence, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ON CONFLICT(debate_id) DO UPDATE SET
                        status=excluded.status,
                        turns_json=excluded.turns_json,
                        consensus_summary=excluded.consensus_summary,
                        final_confidence=excluded.final_confidence
                    """,
                    (
                        debate.debate_id,
                        debate.mission_id,
                        debate.topic,
                        debate.status,
                        json.dumps(debate.participants),
                        turns_json,
                        debate.consensus_summary,
                        debate.final_confidence,
                        debate.created_at,
                    ),
                )
                conn.commit()

        await asyncio.to_thread(_exec)

    async def get_debate_session(self, debate_id: str) -> Optional[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM debates WHERE debate_id = ?", (debate_id,))
                row = cursor.fetchone()
                if not row:
                    return None
                item = dict(row)
                item["participants"] = json.loads(item["participants_json"])
                item["turns"] = json.loads(item["turns_json"])
                return item

        return await asyncio.to_thread(_exec)

    async def get_debates_for_mission(self, mission_id: str) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM debates WHERE mission_id = ? ORDER BY created_at ASC", (mission_id,))
                rows = cursor.fetchall()
                results = []
                for r in rows:
                    item = dict(r)
                    item["participants"] = json.loads(item["participants_json"])
                    item["turns"] = json.loads(item["turns_json"])
                    results.append(item)
                return results

        return await asyncio.to_thread(_exec)

    async def save_agent_reputation(self, rep: AgentReputationModel) -> None:
        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    """
                    INSERT INTO agent_reputations 
                    (agent_id, name, role, experience_points, trust_score, accuracy_rate, reliability_score, speed_score, cost_efficiency, avg_confidence, success_rate, total_missions_participated)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ON CONFLICT(agent_id) DO UPDATE SET
                        experience_points=excluded.experience_points,
                        trust_score=excluded.trust_score,
                        accuracy_rate=excluded.accuracy_rate,
                        reliability_score=excluded.reliability_score,
                        speed_score=excluded.speed_score,
                        cost_efficiency=excluded.cost_efficiency,
                        avg_confidence=excluded.avg_confidence,
                        success_rate=excluded.success_rate,
                        total_missions_participated=excluded.total_missions_participated
                    """,
                    (
                        rep.agent_id,
                        rep.name,
                        rep.role,
                        rep.experience_points,
                        rep.trust_score,
                        rep.accuracy_rate,
                        rep.reliability_score,
                        rep.speed_score,
                        rep.cost_efficiency,
                        rep.avg_confidence,
                        rep.success_rate,
                        rep.total_missions_participated,
                    ),
                )
                conn.commit()

        await asyncio.to_thread(_exec)

    async def get_agent_reputation(self, agent_id: str) -> Optional[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM agent_reputations WHERE agent_id = ?", (agent_id,))
                row = cursor.fetchone()
                return dict(row) if row else None

        return await asyncio.to_thread(_exec)

    async def get_all_agent_reputations(self) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM agent_reputations ORDER BY trust_score DESC")
                return [dict(r) for r in cursor.fetchall()]

        return await asyncio.to_thread(_exec)

    async def save_agent_reflection_v2(self, refl: AgentReflectionDetail) -> None:
        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    """
                    INSERT INTO agent_reflections_v2 (reflection_id, mission_id, agent_id, agent_name, what_worked, what_failed, what_surprised, what_to_improve, timestamp)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                    """,
                    (
                        refl.reflection_id,
                        refl.mission_id,
                        refl.agent_id,
                        refl.agent_name,
                        refl.what_worked,
                        refl.what_failed,
                        refl.what_surprised,
                        refl.what_to_improve,
                        refl.timestamp,
                    ),
                )
                conn.commit()

        await asyncio.to_thread(_exec)

    async def get_agent_reflections_for_mission(self, mission_id: str) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM agent_reflections_v2 WHERE mission_id = ? ORDER BY timestamp ASC", (mission_id,))
                return [dict(r) for r in cursor.fetchall()]

        return await asyncio.to_thread(_exec)

    async def save_approval_request(self, req: ApprovalRequestModel) -> None:
        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    """
                    INSERT INTO approval_requests (id, mission_id, agent_id, action_type, prompt_message, status, input_data_json, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                    ON CONFLICT(id) DO UPDATE SET status=excluded.status, input_data_json=excluded.input_data_json
                    """,
                    (req.id, req.mission_id, req.agent_id, req.action_type.value, req.prompt_message, req.status.value, json.dumps(req.input_data), req.created_at),
                )
                conn.commit()

        await asyncio.to_thread(_exec)

    async def get_approval_request(self, approval_id: str) -> Optional[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM approval_requests WHERE id = ?", (approval_id,))
                row = cursor.fetchone()
                if not row:
                    return None
                item = dict(row)
                item["input_data"] = json.loads(item["input_data_json"]) if item.get("input_data_json") else {}
                return item

        return await asyncio.to_thread(_exec)

    async def get_pending_approvals(self) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM approval_requests WHERE status = 'PENDING' ORDER BY created_at ASC")
                rows = cursor.fetchall()
                results = []
                for r in rows:
                    item = dict(r)
                    item["input_data"] = json.loads(item["input_data_json"]) if item.get("input_data_json") else {}
                    results.append(item)
                return results

        return await asyncio.to_thread(_exec)

    async def save_notification(self, notif: NotificationModel) -> None:
        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    "INSERT INTO notifications (id, level, title, message, mission_id, acknowledged, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
                    (notif.id, notif.level.value, notif.title, notif.message, notif.mission_id, 1 if notif.acknowledged else 0, notif.created_at),
                )
                conn.commit()

        await asyncio.to_thread(_exec)

    async def get_unacknowledged_notifications(self) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM notifications WHERE acknowledged = 0 ORDER BY created_at DESC")
                return [dict(r) for r in cursor.fetchall()]

        return await asyncio.to_thread(_exec)

    async def acknowledge_notification(self, notif_id: str) -> None:
        def _exec():
            with self._get_connection() as conn:
                conn.execute("UPDATE notifications SET acknowledged = 1 WHERE id = ?", (notif_id,))
                conn.commit()

        await asyncio.to_thread(_exec)

    async def save_conversation_log(self, msg: ConversationMessageModel) -> None:
        def _exec():
            with self._get_connection() as conn:
                conn.execute(
                    "INSERT INTO conversation_logs (id, user_id, sender, message, metadata_json, timestamp) VALUES (?, ?, ?, ?, ?, ?)",
                    (msg.id, msg.user_id, msg.sender, msg.message, json.dumps(msg.metadata), msg.timestamp),
                )
                conn.commit()

        await asyncio.to_thread(_exec)

    async def get_conversation_history(self, user_id: str = "human-operator", limit: int = 50) -> List[Dict[str, Any]]:
        def _exec():
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM conversation_logs WHERE user_id = ? ORDER BY timestamp ASC LIMIT ?", (user_id, limit))
                rows = cursor.fetchall()
                results = []
                for r in rows:
                    item = dict(r)
                    item["metadata"] = json.loads(item["metadata_json"]) if item.get("metadata_json") else {}
                    results.append(item)
                return results

        return await asyncio.to_thread(_exec)