File size: 44,941 Bytes
2c3dd0c
 
5782aa4
2c3dd0c
da97e0c
9eba3ee
7e63346
d778046
dd21a0d
 
 
2c3dd0c
dd21a0d
a4229a7
237532d
a4229a7
bb410e4
ff4bc35
 
da97e0c
2c3dd0c
 
dd21a0d
2c3dd0c
 
bb410e4
 
29da66b
5782aa4
2c3dd0c
 
 
a277afd
 
 
 
2c3dd0c
a277afd
2c3dd0c
 
 
22b34bc
2c3dd0c
bb410e4
2c3dd0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22b34bc
2c3dd0c
bb410e4
2c3dd0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22b34bc
2c3dd0c
 
 
 
 
 
 
bb410e4
2c3dd0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22b34bc
2c3dd0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22b34bc
2f9ca82
 
2c3dd0c
2f9ca82
2c3dd0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b2d4a3
22b34bc
c2435f0
 
 
 
 
 
 
 
 
 
 
2c3dd0c
2b2d4a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22b34bc
 
 
 
 
 
 
 
990be54
22b34bc
 
 
 
 
 
 
990be54
22b34bc
 
990be54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22b34bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffb58a3
 
0406dc5
ffb58a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
990be54
 
 
 
 
 
da97e0c
 
 
ffb58a3
 
da97e0c
 
 
 
 
 
 
 
 
 
 
 
 
ffb58a3
 
 
da97e0c
ffb58a3
 
da97e0c
 
990be54
da97e0c
 
990be54
da97e0c
 
 
 
 
 
 
 
 
ffb58a3
911c512
 
 
 
0406dc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1c1f0d
12ca3d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
990be54
12ca3d4
a1c1f0d
990be54
 
 
 
 
 
 
 
12ca3d4
 
a1c1f0d
990be54
12ca3d4
990be54
 
12ca3d4
 
990be54
 
12ca3d4
 
990be54
 
 
 
12ca3d4
 
a1c1f0d
990be54
 
 
 
12ca3d4
 
 
a1c1f0d
12ca3d4
 
 
 
 
 
 
 
bb410e4
12ca3d4
 
 
a1c1f0d
12ca3d4
a1c1f0d
12ca3d4
a1c1f0d
12ca3d4
a1c1f0d
12ca3d4
911c512
ffb58a3
 
 
 
 
 
 
 
 
 
0406dc5
ffb58a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1b70e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9eba3ee
d1b70e9
9eba3ee
 
d1b70e9
9eba3ee
d1b70e9
9eba3ee
 
d1b70e9
 
 
 
 
fcf26e6
d1b70e9
 
 
 
 
fcf26e6
1e81025
fcf26e6
1e81025
d1b70e9
fcf26e6
1e81025
fcf26e6
 
 
 
 
 
 
 
d1b70e9
 
fcf26e6
 
1e1ee41
ad45f9a
ab3306e
ad45f9a
1e1ee41
ab3306e
ad45f9a
1e1ee41
ad45f9a
4d4cac2
 
 
ad45f9a
4d4cac2
 
ad45f9a
4d4cac2
 
2f9ca82
 
bb410e4
2f9ca82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5085aa
 
 
 
 
 
bb410e4
c5085aa
 
 
 
eb83cd5
 
 
 
2e20681
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb83cd5
ff4bc35
 
 
 
 
 
 
 
2f9ca82
5782aa4
bb410e4
2f9ca82
5782aa4
 
 
2f9ca82
 
2e20681
d778046
 
2e20681
 
 
d778046
 
 
 
 
 
 
 
 
 
 
f2eb098
 
 
 
 
 
 
 
 
 
1353938
2f9ca82
5782aa4
1353938
2ccab46
5782aa4
f2eb098
2ccab46
 
 
 
5782aa4
 
1353938
5782aa4
1353938
 
f2eb098
2ccab46
 
 
75191db
2ccab46
1353938
 
 
5782aa4
f2eb098
2f9ca82
d778046
 
f2eb098
d778046
 
 
 
 
 
 
 
 
 
5782aa4
7e63346
 
237532d
5782aa4
 
7e63346
237532d
5782aa4
 
 
 
237532d
5782aa4
7e63346
 
5782aa4
 
7e63346
 
5782aa4
 
 
a4229a7
5782aa4
 
55c47f3
 
 
 
 
 
 
 
 
 
 
 
7e63346
 
 
 
 
 
 
 
 
 
 
 
4dba530
 
7e63346
1352d43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d4cac2
dd21a0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6c82a2
 
 
 
 
 
dd21a0d
 
 
 
 
 
 
 
 
 
 
 
 
 
5de0c3e
 
4d94786
 
 
 
 
 
 
5de0c3e
 
 
4d94786
5de0c3e
 
 
 
 
 
 
 
 
4d94786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab3306e
 
 
 
 
18163dc
1e1ee41
ab3306e
ad45f9a
ab3306e
ad45f9a
1e1ee41
ab3306e
ad45f9a
4d4cac2
 
 
f2f34e4
 
 
4d4cac2
4d94786
f2f34e4
18163dc
64dc4f8
4d94786
ab3306e
 
 
1e1ee41
 
 
 
 
 
 
 
 
 
 
ab3306e
 
 
 
ad45f9a
ab3306e
 
ad45f9a
 
 
 
1e1ee41
ad45f9a
ab3306e
4d94786
e0dbde1
 
 
4d4cac2
e0dbde1
f2f34e4
4d4cac2
f2f34e4
 
4d4cac2
f2f34e4
 
 
 
e0dbde1
f2f34e4
e0dbde1
 
4d4cac2
 
 
 
64dc4f8
e0dbde1
4d4cac2
 
4d94786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18163dc
ab3306e
 
18163dc
e0dbde1
18163dc
 
 
e0dbde1
4d4cac2
 
18163dc
f2f34e4
18163dc
e0dbde1
18163dc
 
1e1ee41
e0dbde1
4d4cac2
 
18163dc
 
 
dd21a0d
18163dc
 
 
 
 
ec44bd1
 
 
 
 
e6c82a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9a81ea
2c3dd0c
 
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
# agents/tools/storage.py

import hashlib
import sqlite3
import os
import json
import uuid
import time
import socket
import ipaddress
import netifaces

from datetime import datetime, timedelta, UTC, timezone, timezone as UTC
from werkzeug.security import generate_password_hash, check_password_hash
from tools.identity import generate_did
from tools.crypto import generate_keypair

UTC = timezone.utc

SCRIPTS_BASE_PATH = "scripts"

class Storage:
    _scope_cache = {}
    def __init__(self, config=None):
        self.config = config or {}
        db_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "agent_data.db"))
        self.db_path = db_path
        self.conn = sqlite3.connect(db_path, check_same_thread=False)
        self.conn.row_factory = sqlite3.Row
        self._init_db()

    def _init_db(self):
        # Загружаем и выполняем весь SQL из файла db_structure.sql
        sql_file = os.path.join(os.path.dirname(__file__), "db_structure.sql")
        with open(sql_file, "r", encoding="utf-8") as f:
            sql_script = f.read()
        c = self.conn.cursor()
        c.executescript(sql_script)  # Выполнит все команды сразу
        self.conn.commit()

    # Методы для работы с дневником

    def write_diary_entry(self, text, tags=None):
        timestamp = datetime.now(UTC).isoformat()
        tag_str = ",".join(tags) if tags else ""
        self.conn.execute(
            'INSERT INTO diary_entries (text, tags, timestamp) VALUES (?, ?, ?)',
            (text, tag_str, timestamp)
        )
        self.conn.commit()

    def read_diary_entries(self, limit=10, tag_filter=None):
        cursor = self.conn.cursor()
        if tag_filter:
            if isinstance(tag_filter, list):
                tag_filter = ",".join(tag_filter)
            like_expr = f"%{tag_filter}%"
            cursor.execute(
                'SELECT * FROM diary_entries WHERE tags LIKE ? ORDER BY id DESC LIMIT ?',
                (like_expr, limit)
            )
        else:
            cursor.execute('SELECT * FROM diary_entries ORDER BY id DESC LIMIT ?', (limit,))
        return cursor.fetchall()

    def search_diary_by_time_range(self, from_ts, to_ts):
        cursor = self.conn.cursor()
        cursor.execute(
            'SELECT * FROM diary_entries WHERE timestamp BETWEEN ? AND ? ORDER BY timestamp DESC',
            (from_ts, to_ts)
        )
        return cursor.fetchall()

    def delete_diary_entry_by_id(self, entry_id):
        self.conn.execute('DELETE FROM diary_entries WHERE id = ?', (entry_id,))
        self.conn.commit()

    def get_diary_tag_stats(self):
        cursor = self.conn.cursor()
        cursor.execute('SELECT tags FROM diary_entries')
        tag_counts = {}
        for row in cursor.fetchall():
            tags = row[0].split(",") if row[0] else []
            for tag in tags:
                tag = tag.strip()
                if tag:
                    tag_counts[tag] = tag_counts.get(tag, 0) + 1
        return tag_counts

    def export_diary_entries(self):
        cursor = self.conn.cursor()
        cursor.execute('SELECT id, text, tags, timestamp FROM diary_entries ORDER BY id ASC')
        return cursor.fetchall()
      
    # Методы для работы с концептами

    def add_concept(self, name, description=None):
        timestamp = datetime.now(UTC).isoformat()
        self.conn.execute(
            'INSERT INTO concepts (name, description, timestamp) VALUES (?, ?, ?)',
            (name, description, timestamp)
        )
        self.conn.commit()

    def get_concept_by_name(self, name):
        cursor = self.conn.cursor()
        cursor.execute('SELECT * FROM concepts WHERE name = ?', (name,))
        return cursor.fetchone()

    def list_concepts(self):
        cursor = self.conn.cursor()
        cursor.execute('SELECT * FROM concepts ORDER BY id ASC')
        return cursor.fetchall()

    # Методы для работы с связями

    def add_link(self, from_name, to_name, relation_type):
        from_concept = self.get_concept_by_name(from_name)
        to_concept = self.get_concept_by_name(to_name)
        if not from_concept or not to_concept:
            raise ValueError("Один или оба концепта не найдены")
        from_id = from_concept[0]
        to_id = to_concept[0]
        timestamp = datetime.now(UTC).isoformat()
        self.conn.execute(
            'INSERT INTO links (from_concept_id, to_concept_id, relation_type, timestamp) VALUES (?, ?, ?, ?)',
            (from_id, to_id, relation_type, timestamp)
        )
        self.conn.commit()

    def get_links_for_concept(self, concept_name):
        concept = self.get_concept_by_name(concept_name)
        if not concept:
            return []
        concept_id = concept[0]
        cursor = self.conn.cursor()
        cursor.execute(
            'SELECT * FROM links WHERE from_concept_id = ? OR to_concept_id = ?',
            (concept_id, concept_id)
        )
        return cursor.fetchall()

    # Сложные операции над графом

    def expand_concept_graph(self, start_id, depth):
        visited = set()
        results = []

        def dfs(node_id, level):
            if level > depth or node_id in visited:
                return
            visited.add(node_id)
            cursor = self.conn.execute(
                'SELECT from_concept_id, to_concept_id, relation_type FROM links WHERE from_concept_id=?',
                (node_id,)
            )
            for row in cursor.fetchall():
                results.append(row)
                dfs(row[1], level + 1)
        
        dfs(start_id, 0)
        return results

    def delete_concept_by_id(self, concept_id):
        self.conn.execute('DELETE FROM concepts WHERE id = ?', (concept_id,))
        self.conn.execute('DELETE FROM links WHERE from_concept_id = ? OR to_concept_id = ?', (concept_id, concept_id))
        self.conn.commit()

    def delete_link_by_id(self, link_id):
        self.conn.execute('DELETE FROM links WHERE id = ?', (link_id,))
        self.conn.commit()

    def export_semantic_graph(self):
        cursor = self.conn.cursor()
        cursor.execute('SELECT id, name, description FROM concepts ORDER BY id ASC')
        concepts = cursor.fetchall()

        cursor.execute('SELECT id, from_concept_id, to_concept_id, relation_type FROM links ORDER BY id ASC')
        links = cursor.fetchall()

        return {"concepts": concepts, "links": links}

    def update_concept_fields(self, concept_id, name=None, description=None):
        cursor = self.conn.cursor()
        if name is not None:
            cursor.execute('UPDATE concepts SET name = ? WHERE id = ?', (name, concept_id))
        if description is not None:
            cursor.execute('UPDATE concepts SET description = ? WHERE id = ?', (description, concept_id))
        self.conn.commit()

    def search_links_by_relation(self, relation):
        cursor = self.conn.cursor()
        cursor.execute(
            'SELECT id, from_concept_id, to_concept_id, relation_type FROM links WHERE relation LIKE ?',
            (f"%{relation}%",)
        )
        return cursor.fetchall()

    def search_concepts(self, query):
        cursor = self.conn.execute(
            '''SELECT id, name, description FROM concepts
               WHERE name LIKE ? OR description LIKE ?''',
            (f"%{query}%", f"%{query}%")
        )
        return cursor.fetchall()

    def merge_concepts(self, source_id, target_id):
        cursor = self.conn.cursor()
        cursor.execute('UPDATE links SET source_id = ? WHERE source_id = ?', (target_id, source_id))
        cursor.execute('UPDATE links SET target_id = ? WHERE target_id = ?', (target_id, source_id))
        self.delete_concept_by_id(source_id)
        self.conn.commit()

    def get_concept_id_by_name(self, name):
        cursor = self.conn.execute('SELECT id FROM concepts WHERE name = ?', (name,))
        row = cursor.fetchone()
        return row[0] if row else None
    
    # Методы для заметок

    #def write_note(self, text, tags=None):
    # переехал в Web-интерфейс и API

    def get_notes_by_tags(self, limit=10, tag_filter=None):
        cursor = self.conn.cursor()
        if tag_filter:
            if isinstance(tag_filter, list):
                tag_filter = ",".join(tag_filter)
            like_expr = f"%{tag_filter}%"
            cursor.execute(
                'SELECT * FROM notes WHERE tags LIKE ? ORDER BY id DESC LIMIT ?',
                (like_expr, limit)
            )
        else:
            cursor.execute('SELECT * FROM notes ORDER BY id DESC LIMIT ?', (limit,))
        return cursor.fetchall()

    def get_notes_after(self, since_ts):
        cursor = self.conn.cursor()
        cursor.execute(
            'SELECT id, text, source, timestamp FROM notes WHERE timestamp > ? ORDER BY timestamp',
            (since_ts,)
        )
        return cursor.fetchall()

    def get_first_unread_note(self):
        cursor = self.conn.cursor()
        cursor.execute(
            "SELECT id, text, source, timestamp, tags FROM notes WHERE read = 0 ORDER BY id ASC LIMIT 1"
        )
        return cursor.fetchone()

    def mark_note_as_read(self, note_id: int):
        self.conn.execute(
            "UPDATE notes SET read = 1 WHERE id = ?",
            (note_id,)
        )
        self.conn.commit()

    def set_tags(self, note_id: int, tags: list[str]):
        tag_str = ",".join(tags)
        self.conn.execute(
            "UPDATE notes SET tags = ? WHERE id = ?",
            (tag_str, note_id)
        )
        self.conn.commit()

    def get_random_note_by_tags(self, include_tags: list[str]):
        cursor = self.conn.cursor()
        like_clauses = " OR ".join(["tags LIKE ?"] * len(include_tags))
        values = [f"%{tag}%" for tag in include_tags]
        query = f"""
            SELECT id, text, source, timestamp, tags
            FROM notes
            WHERE ({like_clauses})
            ORDER BY RANDOM()
            LIMIT 1
        """
        cursor.execute(query, values)
        return cursor.fetchone()

    # Разное (LLM responses / memory)

    def get_llm_recent_responses(self, limit=20, llm_id=None):
        c = self.conn.cursor()
        query = "SELECT role, content FROM llm_recent_responses"
        if llm_id:
            query += " WHERE llm_id = ?"
            query += " ORDER BY timestamp DESC LIMIT ?"
            c.execute(query, (llm_id, limit))
        else:
            query += " ORDER BY timestamp DESC LIMIT ?"
            c.execute(query, (limit,))
        return c.fetchall()

    def add_llm_memory(self, content, title=None, tags=None, llm_id=None):
        c = self.conn.cursor()
        c.execute('''
            INSERT INTO llm_memory (title, content, tags, llm_id)
            VALUES (?, ?, ?, ?)
        ''', (title, content, tags, llm_id))
        self.conn.commit()

    def add_llm_recent_response(self, role, content, llm_id=None):
        c = self.conn.cursor()
        c.execute('''
            INSERT INTO llm_recent_responses (role, content, llm_id)
            VALUES (?, ?, ?)
        ''', (role, content, llm_id))
        self.conn.commit()

    # Скрипты агента

    def get_all_agent_scripts(self):
        c = self.conn.cursor()
        c.execute("SELECT id, name, version, language, description, tags, created_at, updated_at FROM agent_scripts")
        return c.fetchall()

    def get_agent_script_by_name(self, name, version=None):
        """Возвращает скрипт с подгруженным кодом из файла, если он был сохранён через @path"""
        c = self.conn.cursor()
        if version:
            c.execute("SELECT * FROM agent_scripts WHERE name = ? AND version = ?", (name, version))
        else:
            c.execute("""
                SELECT * FROM agent_scripts
                WHERE name = ?
                ORDER BY updated_at DESC
                LIMIT 1
            """, (name,))
        row = c.fetchone()
        if not row:
            return None

        row = list(row)
        code_entry = row[3]  # code

        if code_entry.strip().startswith("@path="):
            rel_path = code_entry.strip().split("=", 1)[1]
            full_path = os.path.join(SCRIPT_ROOT, rel_path)
            if os.path.isfile(full_path):
                with open(full_path, "r", encoding="utf-8") as f:
                    row[3] = f.read()
            else:
                row[3] = f"# Error: Script file not found at {full_path}"

        return tuple(row)

    def add_agent_script(self, name, version, code, description="", tags="", language="python", llm_id=None):
        c = self.conn.cursor()
        try:
            c.execute("""
                INSERT INTO agent_scripts (name, version, code, description, tags, language, llm_id)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            """, (name, version, code, description, tags, language, llm_id))
            self.conn.commit()
            return True
        except sqlite3.IntegrityError:
            return False  # Скрипт с таким name+version уже есть

    def update_agent_script(self, name, version, code=None, description=None, tags=None):
        c = self.conn.cursor()
        fields = []
        values = []

        if code is not None:
            fields.append("code = ?")
            values.append(code)
        if description is not None:
            fields.append("description = ?")
            values.append(description)
        if tags is not None:
            fields.append("tags = ?")
            values.append(tags)

        if not fields:
            return False

        fields.append("updated_at = CURRENT_TIMESTAMP")
        query = f"UPDATE agent_scripts SET {', '.join(fields)} WHERE name = ? AND version = ?"
        values.extend([name, version])

        c.execute(query, values)
        self.conn.commit()
        return c.rowcount > 0

    def delete_agent_script(self, name, version=None):
        c = self.conn.cursor()
        if version:
            c.execute("DELETE FROM agent_scripts WHERE name = ? AND version = ?", (name, version))
        else:
            c.execute("DELETE FROM agent_scripts WHERE name = ?", (name,))
        self.conn.commit()
        return c.rowcount > 0
    
    # process_log — лог задач, ошибок и событий

    def log_process_event(self, name, value=None, tags=None, status='ok', priority=0, llm_id=None):
        c = self.conn.cursor()
        c.execute('''
            INSERT INTO process_log (name, value, tags, status, priority, llm_id)
            VALUES (?, ?, ?, ?, ?, ?)
        ''', (name, value, tags, status, priority, llm_id))
        self.conn.commit()

    def get_recent_logs(self, limit=50, status_filter=None):
        c = self.conn.cursor()
        query = 'SELECT * FROM process_log'
        params = []

        if status_filter:
            query += ' WHERE status = ?'
            params.append(status_filter)

        query += ' ORDER BY timestamp DESC LIMIT ?'
        params.append(limit)

        c.execute(query, tuple(params))
        return c.fetchall()

    # agent_tables — декларации пользовательских таблиц

    def register_agent_table(self, table_name, schema, description=None, llm_id=None):
        c = self.conn.cursor()
        c.execute('''
            INSERT OR IGNORE INTO agent_tables (table_name, description, schema, llm_id)
            VALUES (?, ?, ?, ?)
        ''', (table_name, description, schema, llm_id))
        self.conn.commit()

    def get_agent_tables(self):
        c = self.conn.cursor()
        c.execute('SELECT * FROM agent_tables ORDER BY created_at DESC')
        return c.fetchall()

    # agent_scripts — код скриптов, которыми может пользоваться агент

    def delete_script_file(name, version):
        """Удаляет файл скрипта, если он существует"""
        path = os.path.join(SCRIPT_ROOT, name, f"v{version}", "script.py")
        if os.path.isfile(path):
            os.remove(path)
    
    def resolve_script_path(name, version):
        return os.path.join(SCRIPTS_BASE_PATH, name, f"v{version}", "script.py")

    def register_agent_script(self, name, version, code, language='python', description=None, tags=None, llm_id=None):
        c = self.conn.cursor()

        if code.strip().startswith("@path="):
            # сохраняем только путь как метку
            path = code.strip().split("=", 1)[1]
            code_entry = f"@path={path}"
        else:
            # сохраняем и файл
            path = resolve_script_path(name, version)
            os.makedirs(os.path.dirname(path), exist_ok=True)
            with open(path, "w", encoding="utf-8") as f:
                f.write(code)
            code_entry = f"@path={name}/v{version}/script.py"

        c.execute('''
            INSERT OR REPLACE INTO agent_scripts (name, version, code, language, description, tags, llm_id)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ''', (name, version, code_entry, language, description, tags, llm_id))
        self.conn.commit()

    def get_agent_script_code(self, name, version=None):
        """Возвращает только код (из БД или файла)"""
        row = self.get_agent_script_by_name(name, version)
        if not row:
            return None
        code_entry = row["code_or_path"]
        if code_entry.strip().startswith("@path="):
            rel_path = code_entry.strip().split("=", 1)[1]
            full_path = os.path.join(SCRIPTS_BASE_PATH, rel_path)
            if os.path.isfile(full_path):
                with open(full_path, "r", encoding="utf-8") as f:
                    return f.read()
            else:
                return f"# Error: File not found at path: {full_path}"
        return code_entry

    def list_agent_scripts(limit=50):
        c = self.conn.cursor()
        c.execute("SELECT * FROM agent_scripts ORDER BY updated_at DESC LIMIT ?", (limit,))
        return c.fetchall()    

    def get_latest_agent_script(self, name):
        c = self.conn.cursor()
        c.execute('''
            SELECT * FROM agent_scripts
            WHERE name = ?
            ORDER BY updated_at DESC
            LIMIT 1
        ''', (name,))
        return c.fetchone()

    def search_agent_scripts_by_tag(self, tag):
        c = self.conn.cursor()
        c.execute("SELECT * FROM agent_scripts WHERE tags LIKE ?", (f"%{tag}%",))
        return c.fetchall()

    def ensure_script_path(name, version):
        """Создаёт папку scripts/{name}/v{version}/ если не существует"""
        path = os.path.join(SCRIPT_ROOT, name, f"v{version}")
        os.makedirs(path, exist_ok=True)
        return os.path.join(path, "script.py")

    def save_script_to_file(code, name, version):
        """Сохраняет скрипт в файл и возвращает путь"""
        file_path = ensure_script_path(name, version)
        with open(file_path, "w", encoding="utf-8") as f:
            f.write(code)
        return file_path

    def update_agent_script(self, name, version, code=None, description=None, tags=None, mode="inline"):
        """
        mode: 'inline' (сохранять код в БД), 'file' (в файл, в БД — @path=...)
        """
        c = self.conn.cursor()

        # Получаем текущий code, чтобы понять, был ли путь к файлу
        c.execute("SELECT code FROM agent_scripts WHERE name = ? AND version = ?", (name, version))
        result = c.fetchone()
        if not result:
            return False
        old_code = result[0]

        fields = []
        values = []

        # Обработка поля code
        if code is not None:
            old_is_file = old_code.strip().startswith("@path=")

            if mode == "file":
                file_path = save_script_to_file(code, name, version)
                rel_path = os.path.relpath(file_path, SCRIPT_ROOT)
                code_ref = f"@path={rel_path}"
                fields.append("code = ?")
                values.append(code_ref)

                # если раньше был inline — ничего не делаем, если файл — перезаписываем

            else:  # inline
                fields.append("code = ?")
                values.append(code)

                # если раньше был файл — удалить его
                if old_is_file:
                    delete_script_file(name, version)

        if description is not None:
            fields.append("description = ?")
            values.append(description)

        if tags is not None:
            fields.append("tags = ?")
            values.append(tags)

        if not fields:
            return False

        fields.append("updated_at = ?")
        values.append(datetime.now(UTC).isoformat())

        values.extend([name, version])
        query = f"""
            UPDATE agent_scripts
            SET {', '.join(fields)}
            WHERE name = ? AND version = ?
        """

        c.execute(query, values)
        self.conn.commit()
        return c.rowcount > 0
    
    # llm_registry — реестр LLM-агентов

    def register_llm(self, llm_id, name=None, description=None):
        c = self.conn.cursor()
        c.execute('''
            INSERT OR REPLACE INTO llm_registry (id, name, description)
            VALUES (?, ?, ?)
        ''', (llm_id, name, description))
        self.conn.commit()

    def get_registered_llms(self):
        c = self.conn.cursor()
        c.execute('SELECT * FROM llm_registry ORDER BY registered_at DESC')
        return c.fetchall()

    # diary_graph_index — быстрые индексы по смысловой карте и дневнику

    def add_diary_relation(self, source_id, target_id, relation, strength=1.0, context=None):
        c = self.conn.cursor()
        c.execute('''
            INSERT INTO diary_graph_index (source_entry_id, target_entry_id, relation, strength, context)
            VALUES (?, ?, ?, ?, ?)
        ''', (source_id, target_id, relation, strength, context))
        self.conn.commit()

    def get_diary_relations(self, entry_id):
        c = self.conn.cursor()
        c.execute('''
            SELECT * FROM diary_graph_index
            WHERE source_entry_id = ? OR target_entry_id = ?
            ORDER BY timestamp DESC
        ''', (entry_id, entry_id))
        return c.fetchall()

    # Инициализация
    def set_config(self, key, value):
        cursor = self.conn.cursor()
        cursor.execute('''
            INSERT INTO config (key, value)
            VALUES (?, ?)
            ON CONFLICT(key) DO UPDATE SET value = excluded.value
        ''', (key, value))
        self.conn.commit()

    def add_identity(self, identity):
        cursor = self.conn.cursor()
        cursor.execute('''
            INSERT OR REPLACE INTO identity (id, name, pubkey, privkey, metadata, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ''', (
            identity['id'],
            identity['name'],
            identity['pubkey'],
            identity['privkey'],
            identity.get('metadata', ''),
            identity['created_at'],
            identity['updated_at']
        ))
        self.conn.commit()

    def add_llm(self, llm):
        cursor = self.conn.cursor()
        config_json = json.dumps(llm, ensure_ascii=False)
        cursor.execute('''
            INSERT OR REPLACE INTO llm_registry (id, name, description, config_json)
            VALUES (?, ?, ?, ?)
        ''', (
            llm['name'],  # используем name как id
            llm['name'],
            llm.get('description', ''),
            config_json
        ))
        self.conn.commit()

    def clear_llm_registry(self):
        cursor = self.conn.cursor()
        cursor.execute('DELETE FROM llm_registry')
        self.conn.commit()

    def add_user(self, user):
        cursor = self.conn.cursor()
        cursor.execute('''
            INSERT OR REPLACE INTO users (
                username, badges, did, mail, password_hash,
                info, contacts, language, operator, ban
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ''', (
            user.get('username'),
            user.get('badges'),
            user.get('did'),
            user.get('mail'),
            user.get('password_hash'),
            user.get('info'),
            user.get('contacts'),
            user.get('language'),
            int(user.get('operator', 0)),
            user.get('ban')
        ))
        self.conn.commit()
        return cursor.lastrowid

    # --- Генерация PoW ---
    def generate_pow(self, peer_id, pubkey, address, dt=None, difficulty=4):
        """
        Генерирует PoW для (peer_id + pubkey + address + datetime).
        Используется ISO 8601 без микросекунд, UTC.
        """
        if dt is None:
            dt = datetime.now(timezone.utc).replace(microsecond=0).isoformat()

        nonce = 0
        prefix = "0" * difficulty
        while True:
            base = f"{peer_id}{pubkey}{address}{dt}{nonce}".encode()
            h = hashlib.sha256(base).hexdigest()
            if h.startswith(prefix):
                return nonce, h, dt
            nonce += 1

    # Управление основными процессами
    def update_heartbeat(self, name: str):
        now = datetime.now(UTC).isoformat()
        self.conn.execute(
            "INSERT INTO main_process (name, heartbeat, stop) VALUES (?, ?, 0) "
            "ON CONFLICT(name) DO UPDATE SET heartbeat = excluded.heartbeat",
            (name, now)
        )
        self.conn.commit()

    def check_stop_flag(self, name: str) -> bool:
        cursor = self.conn.execute("SELECT stop FROM main_process WHERE name = ?", (name,))
        row = cursor.fetchone()
        if row and row[0] == 1:
            self.conn.execute("UPDATE main_process SET stop = 0 WHERE name = ?", (name,))
            self.conn.commit()
            return True
        return False

    def is_process_alive(self, name: str, max_delay=180):
        cursor = self.conn.execute("SELECT heartbeat FROM main_process WHERE name=?", (name,))
        row = cursor.fetchone()
        if row:
            try:
                last_beat = datetime.fromisoformat(row[0])
                return (datetime.now(UTC) - last_beat).total_seconds() < max_delay
            except:
                return False
        return False

    # Чтение параметра конфигурации из БД
    def get_config_value(self, key: str, default=None):
        cursor = self.conn.execute("SELECT value FROM config WHERE key = ?", (key,))
        row = cursor.fetchone()
        if not row:
            return default

        value = row[0]

        # Если это JSON-строка в кавычках — парсим
        try:
            parsed = json.loads(value)
            if isinstance(parsed, (str, int, float, bool, dict, list)):
                return parsed
        except (json.JSONDecodeError, TypeError):
            pass

        # На всякий случай убираем лишние кавычки
        if isinstance(value, str) and len(value) >= 2 and value[0] == '"' and value[-1] == '"':
            return value[1:-1]

        return value

    def set_config_value(self, key, value):
        c = self.conn.cursor()
        c.execute("""
            INSERT INTO config(key, value) VALUES (?, ?)
            ON CONFLICT(key) DO UPDATE SET value=excluded.value
        """, (key, value))
        self.conn.commit()

    # Web-интерфейс и API
    def write_note(self, content, user_did="anon", source="user", hidden=0):
        timestamp = datetime.now(UTC).isoformat()
        self.conn.execute("""
            INSERT INTO notes (text, user_did, source, timestamp, hidden)
            VALUES (?, ?, ?, ?, ?)
        """, (content, user_did, source, timestamp, hidden))
        self.conn.commit()

    def write_note_returning_id(self, content, user_did, agent_did, source="user", hidden=False, code=None, mentions="[]", hashtags="[]"):
        cursor = self.conn.cursor()
        cursor.execute("""
            INSERT INTO notes (timestamp, text, code, mentions, hashtags, user_did, agent_did, source, hidden)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        """, (time.time(), content, code, mentions, hashtags, user_did, agent_did, source, int(hidden)))
        self.conn.commit()
        return cursor.lastrowid

    def save_attachment(self, message_id, filename, mime_type, content):
        cursor = self.conn.cursor()
        cursor.execute("""
            INSERT INTO attachments (message_id, filename, mime_type, size, binary)
            VALUES (?, ?, ?, ?, ?)
        """, (message_id, filename, mime_type, len(content), content))
        self.conn.commit()

    def get_attachment_by_id(self, file_id):
        cursor = self.conn.cursor()
        cursor.execute("""
            SELECT id, filename, mime_type, size, binary
            FROM attachments
            WHERE id = ?
        """, (file_id,))
        row = cursor.fetchone()
        return dict(row) if row else None

    def get_notes(self, limit=50, user_did="anon", only_personal=False):
        cursor = self.conn.cursor()

        if only_personal:
            # Только личные (скрытые) сообщения пользователя
            query = """
                SELECT n.id, n.text, n.code, n.source, n.user_did, u.username, n.timestamp, n.hidden
                FROM notes n
                LEFT JOIN users u ON n.user_did = u.did
                WHERE n.user_did = ? AND n.hidden = 1
                ORDER BY n.timestamp DESC
                LIMIT ?
            """
            cursor.execute(query, (user_did, limit))
        else:
            # Личные сообщения + публичные от user/llm, которые не скрыты
            query = """
                SELECT n.id, n.text, n.code, n.source, n.user_did, u.username, u.badges, n.timestamp, n.hidden
                FROM notes n
                LEFT JOIN users u ON n.user_did = u.did
                WHERE n.user_did = ?
                   OR ((n.source = 'user' OR n.source = 'llm' OR n.source = 'cli') AND n.hidden = 0)
                ORDER BY n.timestamp DESC
                LIMIT ?
            """
            cursor.execute(query, (user_did, limit))

        result = [dict(row) for row in cursor.fetchall()]

        for note in result:
            note["attachments"] = self.get_attachments_for_note(note["id"])

        return result

    def get_attachments_for_note(self, message_id):
        cursor = self.conn.cursor()
        cursor.execute("""
            SELECT id, filename, mime_type, size FROM attachments
            WHERE message_id = ?
        """, (message_id,))
        return [dict(row) for row in cursor.fetchall()]

    # Пользователи
    def register_user(self, username: str, mail: str, password: str) -> bool:
        mail = mail.lower()
        did = generate_did()
        try:
            self.conn.execute(
                "INSERT INTO users (username, mail, password_hash, did) VALUES (?, ?, ?, ?)",
                (username, mail, generate_password_hash(password), did)
            )
            self.conn.commit()
            return True
        except sqlite3.IntegrityError:
            return False

    def authenticate_user(self, mail: str, password: str) -> bool:
        mail = mail.lower()
        cursor = self.conn.cursor()
        cursor.execute(
            "SELECT password_hash FROM users WHERE mail = ?",
            (mail,)
        )
        result = cursor.fetchone()
        if result:
            return check_password_hash(result["password_hash"], password)
        return False

    def is_banned(self, user_did):
        result = self.conn.execute("""
            SELECT ban
            FROM users
            WHERE did = ?
        """, (user_did,)).fetchone()

        if result and result["ban"]:
            return datetime.fromisoformat(result["ban"]) > datetime.now(UTC)

        return False

    def get_user_info(self, mail: str) -> dict | None:
        mail = mail.lower()
        cursor = self.conn.cursor()
        cursor.execute(
            "SELECT username, did FROM users WHERE mail = ?",
            (mail,)
        )
        result = cursor.fetchone()
        if result:
            return {
                "username": result["username"],
                "did": result["did"]
            }
        return None

    def get_user_info_by_did(self, did: str) -> dict | None:
        cursor = self.conn.cursor()
        cursor.execute(
            "SELECT username, mail, operator FROM users WHERE did = ?",
            (did,)
        )
        result = cursor.fetchone()
        if result:
            return {
                "username": result["username"],
                "mail": result["mail"],
                "operator": result["operator"]
            }
        return None

    # Нормализация адресов
    @staticmethod
    def parse_hostport(s: str):
        """
        Разбирает "IP:port" или "[IPv6]:port" и возвращает (host, port)
        """
        s = s.strip()
        if s.startswith("["):
            host, _, port = s[1:].partition("]:")
            try:
                port = int(port)
            except:
                port = None
            return host, port
        else:
            if ":" in s:
                host, port = s.rsplit(":", 1)
                try:
                    port = int(port)
                except:
                    port = None
                return host, port
            return s, None

    @staticmethod
    def is_ipv6(host: str):
        try:
            socket.inet_pton(socket.AF_INET6, host)
            return True
        except OSError:
            return False

    @staticmethod
    def is_private(ip: str) -> bool:
        try:
            return ipaddress.ip_address(ip).is_private
        except ValueError:
            return False

    @classmethod
    def get_ipv6_scope(cls, host):
        if host in cls._scope_cache:
            return cls._scope_cache[host]
        for iface in netifaces.interfaces():
            iface_addrs = netifaces.ifaddresses(iface).get(netifaces.AF_INET6, [])
            for addr_info in iface_addrs:
                if addr_info.get("addr") == host:
                    scope_id = socket.if_nametoindex(iface)
                    cls._scope_cache[host] = scope_id
                    return scope_id
        return None

    @classmethod
    def normalize_address(cls, addr) -> str:
        if isinstance(addr, dict) and "addr" in addr:
            addr = addr["addr"]
        if not isinstance(addr, str):
            return None

        addr = addr.strip()
        if not addr:
            return None
        if "://" not in addr:
            addr = f"any://{addr}"

        proto, hostport = addr.split("://", 1)
        host, port = cls.parse_hostport(hostport)

        if cls.is_ipv6(host) and not host.startswith("["):
            host = f"[{host}]"

        return f"{proto}://{host}:{port}" if port else f"{proto}://{host}"

    # Получаем уникальные локальные порты
    def get_local_ports(self):
        local_addrs = self.get_config_value("local_addresses", [])
        if not isinstance(local_addrs, list):
            try:
                local_addrs = json.loads(local_addrs)
            except Exception:
                print("[WARN] Не удалось разобрать local_addresses из БД")
                return []

        ports = []
        for entry in local_addrs:
            addr_str = entry.get("addr") or entry.get("address") if isinstance(entry, dict) else entry
            try:
                proto, hostport = addr_str.split("://", 1)
                _, port = self.parse_hostport(hostport)
                ports.append(port)
            except Exception as e:
                print(f"[WARN] Не удалось разобрать адрес {addr_str}: {e}")

        return ports

    # Получить локальные или глобальные адреса
    def get_addresses(self, which="local"):
        key = f"{which}_addresses"
        addrs = self.get_config_value(key, [])
        if not isinstance(addrs, list):
            try:
                addrs = json.loads(addrs)
            except Exception:
                print(f"[WARN] Не удалось разобрать {key} из БД")
                return []

        result = []
        for entry in addrs:
            if isinstance(entry, dict):
                result.append(entry.get("addr") or entry.get("address"))
            elif isinstance(entry, str):
                result.append(entry)
        return result

    # Нормализация DID
    @staticmethod
    def normalize_did(did: str) -> str:
        return did.strip().strip('"').strip("'")

    # Работа с пирам (agent_peers)
    # --- Проверка PoW ---
    @staticmethod
    def verify_pow(peer_id, pubkey, address, nonce, pow_hash, dt, difficulty=4):
        """
        Проверяет PoW (peer_id + pubkey + address + datetime).
        dt ожидается в формате ISO 8601 без микросекунд, UTC.
        """
        base = f"{peer_id}{pubkey}{address}{dt}{nonce}".encode()
        h = hashlib.sha256(base).hexdigest()
        return h == pow_hash and h.startswith("0" * difficulty)

    def add_or_update_peer(
        self, peer_id, name, addresses,
        source="discovery", status="unknown",
        pubkey=None, capabilities=None,
        heard_from=None, strict: bool = True
    ):
        c = self.conn.cursor()

        # --- нормализуем входные адреса ---
        norm_addresses = []
        for a in (addresses or []):
            if isinstance(a, dict) and "addr" in a:
                dt_raw = a.get("datetime")
                if dt_raw:
                    try:
                        dt_obj = datetime.fromisoformat(dt_raw)
                        dt_obj = dt_obj.astimezone(timezone.utc).replace(microsecond=0)
                        dt = dt_obj.isoformat()
                    except Exception:
                        dt = datetime.now(timezone.utc).replace(microsecond=0).isoformat()
                else:
                    dt = datetime.now(timezone.utc).replace(microsecond=0).isoformat()

                norm_addresses.append({
                    "addr": self.normalize_address(a["addr"]),
                    "nonce": a.get("nonce"),
                    "pow_hash": a.get("pow_hash"),
                    "datetime": dt
                })
            elif isinstance(a, str):
                norm_addresses.append({
                    "addr": self.normalize_address(a),
                    "nonce": None,
                    "pow_hash": None,
                    "datetime": datetime.now(timezone.utc).replace(microsecond=0).isoformat()
                })

        # --- получаем существующую запись ---
        existing_addresses = []
        existing_pubkey = None
        existing_capabilities = {}
        existing_heard_from = []

        if peer_id:
            c.execute("SELECT addresses, pubkey, capabilities, heard_from FROM agent_peers WHERE id=?", (peer_id,))
            row = c.fetchone()
            if row:
                db_addresses_json, existing_pubkey, db_caps_json, db_heard_from = row
                try:
                    existing_addresses = json.loads(db_addresses_json) or []
                except:
                    existing_addresses = []
                try:
                    existing_capabilities = json.loads(db_caps_json) if db_caps_json else {}
                except:
                    existing_capabilities = {}
                try:
                    existing_heard_from = json.loads(db_heard_from) if db_heard_from else []
                except:
                    existing_heard_from = []

        final_capabilities = capabilities or existing_capabilities
        combined_heard_from = list(set(existing_heard_from + (heard_from or [])))

        # --- строгий режим ---
        if strict:
            # Проверка pubkey
            if existing_pubkey and pubkey and existing_pubkey != pubkey:
                print(f"[WARN] Peer {peer_id} pubkey mismatch! Possible impersonation attempt.")
                return
            final_pubkey = existing_pubkey or pubkey

            # Объединяем адреса по addr, проверяем PoW и datetime
            addr_map = {a["addr"]: a for a in existing_addresses if isinstance(a, dict)}
            for a in norm_addresses:
                addr = a["addr"]
                nonce = a.get("nonce")
                pow_hash = a.get("pow_hash")
                dt = a.get("datetime")

                # проверка PoW
                if nonce is not None and pow_hash is not None:
                    if not self.verify_pow(peer_id, final_pubkey, addr, nonce, pow_hash, dt):
                        print(f"[WARN] Peer {peer_id} address {addr} failed PoW validation")
                        continue

                # проверка актуальности datetime
                if addr in addr_map:
                    old_dt = addr_map[addr].get("datetime")
                    if old_dt and dt <= old_dt:
                        continue

                addr_map[addr] = {"addr": addr, "nonce": nonce, "pow_hash": pow_hash, "datetime": dt}

            combined_addresses = list(addr_map.values())

        # --- упрощённый режим ---
        else:
            final_pubkey = existing_pubkey or pubkey
            addr_map = {a["addr"]: a for a in existing_addresses if isinstance(a, dict)}
            for a in norm_addresses:
                # просто перезаписываем адреса без PoW и datetime проверки
                addr_map[a["addr"]] = a
            combined_addresses = list(addr_map.values())

        # --- запись в БД ---
        c.execute("""
            INSERT INTO agent_peers (id, name, addresses, source, status, last_seen, pubkey, capabilities, heard_from)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ON CONFLICT(id) DO UPDATE SET
                name=excluded.name,
                addresses=excluded.addresses,
                source=excluded.source,
                status=excluded.status,
                last_seen=excluded.last_seen,
                capabilities=excluded.capabilities,
                heard_from=excluded.heard_from
        """, (
            peer_id,
            name,
            json.dumps(combined_addresses),
            source,
            status,
            datetime.now(timezone.utc).replace(microsecond=0).isoformat(),
            final_pubkey,
            json.dumps(final_capabilities),
            json.dumps(combined_heard_from)
        ))
        self.conn.commit()

    # Получение известных/онлайн пиров
    def get_online_peers(self, limit=50):
        c = self.conn.cursor()
        c.execute("SELECT id, addresses FROM agent_peers WHERE status='online' LIMIT ?", (limit,))
        return c.fetchall()

    def get_known_peers(self, my_id, limit=50):
        c = self.conn.cursor()
        c.execute("SELECT id, addresses FROM agent_peers WHERE id != ? LIMIT ?", (my_id, limit))
        return c.fetchall()

    def get_peer_address(self, peer_id: str, addr_str: str):
        """Возвращает запись адреса пира по peer_id и addr_str, или None если не найден"""
        peers = self.get_known_peers(my_id="", limit=1000)  # передаем "" чтобы не фильтровать по my_id
        for p in peers:
            pid = p["id"] if isinstance(p, dict) else p[0]
            addresses_json = p["addresses"] if isinstance(p, dict) else p[1]

            if pid != peer_id:
                continue

            try:
                addresses = json.loads(addresses_json)
            except Exception:
                continue

            for a in addresses:
                if a.get("addr") == addr_str:
                    return a
        return None

    # Утилиты
    def close(self):
        self.conn.close()