File size: 45,687 Bytes
b901883
 
ae35f49
 
 
 
 
 
 
b901883
 
51073dd
 
c5f052a
1a49277
4b8e764
 
c5f052a
94248da
ae35f49
51073dd
befca86
94248da
c5f052a
 
 
 
 
b901883
4b8e764
 
 
 
 
 
 
 
 
 
c5f052a
4b8e764
 
 
 
 
c5f052a
4b8e764
 
c5f052a
4b8e764
 
 
c5f052a
 
 
 
4b8e764
ced20ea
 
 
ae35f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ced20ea
 
ae35f49
c5f052a
 
 
 
ae35f49
 
 
 
ced20ea
c5f052a
ae35f49
ced20ea
4b8e764
 
ae35f49
ced20ea
4b8e764
 
 
ced20ea
ae35f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b8e764
ae35f49
51073dd
4b8e764
ae35f49
 
 
 
 
 
 
 
4b8e764
 
ae35f49
 
 
 
 
 
 
 
 
 
4b8e764
51073dd
ae35f49
 
 
 
 
4b8e764
ae35f49
 
 
 
 
 
 
 
 
 
 
 
94248da
4b8e764
ae35f49
4b8e764
 
 
 
ae35f49
 
4b8e764
 
ae35f49
4b8e764
 
b901883
 
ae35f49
4b8e764
 
ae35f49
4b8e764
 
 
ae35f49
 
 
 
 
 
 
 
 
 
4b8e764
c5f052a
51073dd
ae35f49
 
 
 
 
51073dd
 
 
 
 
ae35f49
 
51073dd
 
 
 
ae35f49
51073dd
ae35f49
 
51073dd
ae35f49
51073dd
4b8e764
ae35f49
 
 
 
0de7373
4b8e764
ae35f49
 
 
4b8e764
 
 
ae35f49
 
 
 
 
94248da
4b8e764
 
ae35f49
4b8e764
 
 
ae35f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a49277
ae35f49
 
 
 
 
 
 
1a49277
ae35f49
 
 
 
 
 
1a49277
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae35f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a49277
ae35f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a49277
ae35f49
 
 
 
 
 
 
 
51073dd
c5f052a
ae35f49
 
 
51073dd
ae35f49
 
 
 
51073dd
ae35f49
 
51073dd
 
ae35f49
 
 
 
 
 
 
 
51073dd
 
ae35f49
 
 
 
 
 
 
 
 
 
51073dd
ae35f49
 
 
 
51073dd
 
ae35f49
 
 
51073dd
 
ae35f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a49277
51073dd
ae35f49
 
 
 
51073dd
ae35f49
 
 
51073dd
 
 
c5f052a
ae35f49
c5f052a
 
 
ae35f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51073dd
 
ae35f49
 
51073dd
ae35f49
 
51073dd
ae35f49
51073dd
ae35f49
51073dd
 
ae35f49
 
 
 
 
51073dd
ae35f49
 
51073dd
1a49277
ae35f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51073dd
 
ae35f49
 
 
 
 
 
 
 
4b8e764
 
ae35f49
4b8e764
 
ae35f49
 
51073dd
ae35f49
 
 
 
 
51073dd
 
 
ae35f49
51073dd
4b8e764
 
 
ae35f49
 
 
 
 
 
 
 
 
 
 
51073dd
ae35f49
 
 
 
51073dd
 
 
ae35f49
 
 
 
 
 
 
 
 
1a49277
 
ae35f49
 
 
 
 
 
 
 
 
51073dd
ae35f49
 
51073dd
ae35f49
 
 
 
 
 
 
 
4b8e764
51073dd
ae35f49
 
 
 
4b8e764
 
ae35f49
4b8e764
befca86
ae35f49
4b8e764
 
 
ae35f49
 
 
51073dd
4b8e764
ae35f49
 
 
 
 
 
 
 
1a49277
ae35f49
 
 
 
 
 
4b8e764
ae35f49
4b8e764
 
 
1a49277
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b901883
c5f052a
ae35f49
 
4b8e764
ae35f49
 
1a49277
ae35f49
 
 
4b8e764
ae35f49
 
 
 
 
 
 
 
 
 
 
 
1a49277
ae35f49
 
4b8e764
ae35f49
 
 
 
 
 
4b8e764
b901883
ae35f49
4b8e764
 
ae35f49
c5f052a
ae35f49
 
4b8e764
ae35f49
 
 
 
 
4b8e764
 
ae35f49
4b8e764
 
 
ae35f49
 
 
 
4b8e764
ae35f49
 
 
 
 
 
 
4b8e764
 
ae35f49
4b8e764
ae35f49
4b8e764
ae35f49
4b8e764
 
ae35f49
 
4b8e764
ae35f49
4b8e764
 
ae35f49
4b8e764
 
 
ae35f49
 
 
 
 
4b8e764
ae35f49
94248da
4b8e764
ae35f49
4b8e764
 
 
ae35f49
 
94248da
4b8e764
ae35f49
 
1a49277
4b8e764
b901883
 
ae35f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b901883
 
ae35f49
 
 
 
b901883
ae35f49
b901883
ae35f49
 
 
 
 
 
 
 
 
 
 
b901883
ae35f49
 
 
b901883
ae35f49
 
b901883
ae35f49
 
 
 
 
b901883
ae35f49
 
b901883
ae35f49
 
 
 
 
 
b901883
ae35f49
b901883
ae35f49
b901883
ae35f49
4b8e764
ae35f49
 
 
 
 
 
 
 
 
 
 
 
 
4b8e764
ae35f49
 
 
94248da
 
 
 
 
 
 
 
 
 
 
 
ae35f49
4b8e764
ae35f49
 
 
 
94248da
4b8e764
ae35f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b8e764
ae35f49
 
 
 
 
 
 
4b8e764
b901883
ae35f49
 
 
4b8e764
 
ae35f49
4b8e764
 
ae35f49
 
 
4b8e764
ae35f49
4b8e764
ae35f49
 
 
 
 
4b8e764
 
ae35f49
 
 
4b8e764
ae35f49
 
 
 
 
 
 
 
 
 
 
 
 
 
4b8e764
ae35f49
 
 
4b8e764
ae35f49
 
 
 
 
 
4b8e764
ae35f49
4b8e764
ae35f49
 
4b8e764
ae35f49
 
 
 
 
 
 
 
 
 
4b8e764
 
 
b901883
ae35f49
 
 
 
 
 
 
 
 
4b8e764
ae35f49
4b8e764
ae35f49
 
 
 
 
 
4b8e764
ae35f49
 
4b8e764
ae35f49
 
 
 
 
 
 
 
 
 
 
94248da
 
ae35f49
 
 
 
b901883
 
 
ae35f49
 
 
b901883
4b8e764
ae35f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94248da
ae35f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94248da
ae35f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b8e764
ae35f49
 
 
b901883
c5f052a
ae35f49
 
 
c5f052a
ae35f49
4b8e764
b901883
4b8e764
 
 
ae35f49
 
 
 
94248da
 
 
b901883
ae35f49
 
 
 
 
4b8e764
 
 
ae35f49
 
 
 
 
 
4b8e764
 
 
ae35f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b8e764
ae35f49
4b8e764
 
 
 
ae35f49
 
4b8e764
ae35f49
94248da
1a49277
 
94248da
 
 
 
 
 
 
1a49277
 
 
 
 
 
 
 
 
 
 
 
 
94248da
 
 
 
 
 
 
 
 
1a49277
 
 
94248da
 
 
 
 
1a49277
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# core/agent_loop.py
"""
Оркестратор инженерных запросов.

Принцип маршрутизации:
1. QueryParser извлекает intent, параметры, город, код документа.
2. Полный числовой расчёт исполняется немедленно, без RAG.
3. Поиск используется для нормативных вопросов, определений,
   сравнений, свободного поиска и неполных city-зависимых расчётов.
"""

from __future__ import annotations

import re
from collections.abc import Mapping
from dataclasses import dataclass, field
from enum import Enum
from typing import Any
import logging
from core.query_parser import parse_query
from core.retrieval_memory import RetrievalMemory
from core.table_extractor import extract_tables, tables_to_dicts
logger = logging.getLogger(__name__)
try:
    from core.config import PROCESSED_DIR
except ImportError:
    from pathlib import Path
    PROCESSED_DIR = Path("data/processed")


class QueryType(Enum):
    CALCULATION = "calculation"
    DEFINITION = "definition"
    SEARCH = "search"
    COMPARISON = "comparison"
    REGULATORY = "regulatory"
    GENERAL = "general"


@dataclass(slots=True)
class ReasoningStep:
    step_id: int
    description: str
    result: Any = None
    confidence: float = 0.0
    next_steps: list[str] = field(default_factory=list)


@dataclass(slots=True)
class ContextInfo:
    query: str
    query_type: QueryType
    keywords: list[str]
    entities: dict[str, Any]
    parameters: dict[str, Any]
    chunks: list[dict[str, Any]]
    confidence: float = 0.0


class AgentLoop:
    """Маршрутизирует запросы между вычислительным и retrieval-слоями."""

    REGULATORY_MARKERS = (
        "должен",
        "должна",
        "должны",
        "требуется",
        "требуют",
        "следует",
        "необходимо",
        "не допускается",
        "допускается",
        "не менее",
        "не более",
        "принимается",
        "принимают",
        "устанавливается",
        "должно быть",
        "как правило",
        "в соответствии",
    )

    REGULATORY_QUERY_EXPANSIONS = {
        "вентиляция": [
            "системы вентиляции",
            "воздухообмен",
            "расход наружного воздуха",
            "требования к вентиляции",
        ],
        "микроклимат": [
            "параметры микроклимата",
            "температура воздуха",
            "относительная влажность",
            "скорость движения воздуха",
        ],
        "отопление": [
            "система отопления",
            "теплоснабжение",
            "отопительные приборы",
            "требования к отоплению",
        ],
        "изоляция": [
            "тепловая изоляция",
            "теплоизоляционные конструкции",
            "сопротивление теплопередаче",
        ],
        "тепловая защита": [
            "сопротивление теплопередаче",
            "ограждающие конструкции",
            "энергоэффективность здания",
        ],
    }

    def __init__(self, qa_system: Any, formula_engine: Any):
        self.qa_system = qa_system
        self.formula_engine = formula_engine

        self.messages: list[dict[str, Any]] = []
        self.reasoning_steps: list[ReasoningStep] = []
        self.context: ContextInfo | None = None
        self.last_error: str | None = None

        self.memory = RetrievalMemory(
            PROCESSED_DIR / "retrieval_memory.json"
        )

    async def run(self, user_content: str) -> dict[str, Any]:
        """Главная точка входа."""
        self.messages.append({"role": "user", "content": user_content})
        self.reasoning_steps = []
        self.context = None
        self.last_error = None

        try:
            step1 = self._analyze_query(user_content)
            self.reasoning_steps.append(step1)

            if step1.result is None:
                return self._create_error_response(
                    "Не удалось проанализировать запрос.",
                    step_id=1,
                )

            query_type: QueryType = step1.result["type"]
            keywords: list[str] = step1.result["keywords"]
            entities: dict[str, Any] = step1.result["entities"]
            parameters: dict[str, Any] = step1.result["parameters"]

            # Fast-path: прямой расчёт не должен зависеть от RAG.
            if (
                query_type == QueryType.CALCULATION
                and self.formula_engine.can_calculate_directly(
                    user_content,
                    parameters,
                )
            ):
                step2 = await self._handle_direct_calculation(
                    query=user_content,
                    parameters=parameters,
                    entities=entities,
                )
                self.reasoning_steps.append(step2)

                response = self._finalize_response(
                    result=step2.result,
                    query_type=query_type,
                    keywords=keywords,
                    original_query=user_content,
                )
                response["steps"] = len(self.reasoning_steps)
                return response

            # Retrieval нужен только если direct calculation невозможен
            # или вопрос по смыслу является нормативным/поисковым.
            step2 = self._search_chunks(
                query=user_content,
                query_type=query_type,
                entities=entities,
                keywords=keywords,
            )
            self.reasoning_steps.append(step2)

            chunks = step2.result.get("chunks", []) if step2.result else []

            step3 = self._build_context(
                query=user_content,
                query_type=query_type,
                keywords=keywords,
                entities=entities,
                parameters=parameters,
                chunks=chunks,
            )
            self.reasoning_steps.append(step3)

            if step3.result is None:
                return self._create_error_response(
                    "Не удалось сформировать контекст запроса.",
                    step_id=3,
                )

            context = step3.result
            self.context = context

            step4 = await self._dispatch(context)
            self.reasoning_steps.append(step4)

            if step4.result is None:
                return self._create_error_response(
                    "Не удалось сформировать ответ.",
                    step_id=4,
                )

            response = self._finalize_response(
                result=step4.result,
                query_type=query_type,
                keywords=keywords,
                original_query=user_content,
            )
            response["steps"] = len(self.reasoning_steps)

            return response

        except Exception as exc:
            self.last_error = str(exc)
            logger.exception("Непойманная ошибка AgentLoop.run для запроса %r", user_content[:200])
            return {
                "answer": f"❌ Внутренняя ошибка: {exc}",
                "sources": [],
                "tables": [],
                "formulas": [],
                "confidence": 0.0,
                "needs_clarification": True,
                "questions": ["Повторите запрос или уточните исходные данные."],
                "query_type": "error",
                "steps": len(self.reasoning_steps) or 1,
                "error": str(exc),
            }

    @staticmethod
    def _analyze_query(query: str) -> ReasoningStep:
        """Получает intent и сущности только через QueryParser."""
        step = ReasoningStep(
            step_id=1,
            description="Анализ запроса и извлечение сущностей",
        )

        try:
            parsed = parse_query(query)

            type_map = {
                "calculation": QueryType.CALCULATION,
                "definition": QueryType.DEFINITION,
                "search": QueryType.SEARCH,
                "comparison": QueryType.COMPARISON,
                "regulatory": QueryType.REGULATORY,
                "general": QueryType.GENERAL,
            }

            entities: dict[str, Any] = {}

            if getattr(parsed, "city", None):
                entities["city"] = parsed.city

            document_codes = list(
                getattr(parsed, "document_codes", []) or []
            )
            if document_codes:
                entities["document_codes"] = document_codes
                entities["documents"] = document_codes

            section_refs = list(
                getattr(parsed, "section_refs", []) or []
            )
            if section_refs:
                entities["section_refs"] = section_refs

            keywords = list(getattr(parsed, "keywords", []) or [])
            domain_terms = [
                word for word in keywords
                if len(word) > 2
            ]
            entities["domain_terms"] = domain_terms[:12]

            step.result = {
                "type": type_map.get(
                    getattr(parsed, "intent", "search"),
                    QueryType.SEARCH,
                ),
                "keywords": keywords,
                "entities": entities,
                "parameters": dict(
                    getattr(parsed, "parameters", {}) or {}
                ),
            }
            step.confidence = 0.9

        except (
            AttributeError,
            TypeError,
            ValueError,
        ) as exc:
            logger.warning("Не удалось разобрать запрос %r: %s", query[:200], exc)
            step.result = None
            step.confidence = 0.0
            step.description = f"Ошибка анализа запроса: {exc}"

        return step

    async def _handle_direct_calculation(
        self,
        query: str,
        parameters: dict[str, Any],
        entities: dict[str, Any],
    ) -> ReasoningStep:
        """Выполняет числовой расчёт без retrieval."""
        step = ReasoningStep(
            step_id=2,
            description="Прямой детерминированный расчёт без поиска",
        )

        result = await self.formula_engine.answer_calculation(
            query=query,
            parameters=parameters,
            entities=entities,
        )

        step.result = self._normalize_calculation_result(result)
        step.confidence = step.result["confidence"]

        return step

    async def _dispatch(
        self,
        context: ContextInfo,
    ) -> ReasoningStep:
        """Расчёты направляет в FormulaEngine, ответы — в общий RAG-путь."""
        if context.query_type == QueryType.CALCULATION:
            return await self._handle_calculation(context)

        if context.query_type == QueryType.DEFINITION:
            return self._handle_definition(context)

        if context.query_type == QueryType.COMPARISON:
            return self._handle_grounded(context, "Сравнение по найденным документам")

        if context.query_type == QueryType.REGULATORY:
            return self._handle_regulatory(context)

        return self._handle_search(context)

    def _handle_grounded(self, context: ContextInfo, description: str) -> ReasoningStep:
        """Передаёт уже найденные фрагменты QA без повторного поиска и потери источников."""
        step = ReasoningStep(step_id=4, description=description)
        try:
            answer_from_results = getattr(self.qa_system, "answer_from_results", None)
            if callable(answer_from_results):
                answer = answer_from_results(context.query, context.chunks)
            else:
                # Совместимость со старым пользовательским QA: только цитаты
                # найденного текста, без дополнений из памяти модели.
                answer = self._search_answer(context)
                answer.update(provider="none", used_llm=False, grounded=True)
            if not isinstance(answer, dict):
                raise TypeError("QA должен вернуть словарь с ответом и источниками")
            step.result = answer
            step.confidence = float(answer.get("confidence", 0.0) or 0.0)
        except (AttributeError, KeyError, TypeError, ValueError) as exc:
            logger.exception("Не удалось сформировать ответ по найденным фрагментам")
            step.result = self._create_error_response(f"Ошибка формирования ответа: {exc}", step_id=4)
            step.confidence = 0.0
        return step

    async def _handle_calculation(
        self,
        context: ContextInfo,
    ) -> ReasoningStep:
        """
        Неполный или city-зависимый расчёт.

        RAG уже выполнился только потому, что direct path оказался невозможен.
        FormulaEngine теперь может использовать TableCalculator и найденные
        климатические данные через qa_system.
        """
        step = ReasoningStep(
            step_id=4,
            description="Расчёт с проверкой табличных климатических данных",
        )

        try:
            result = await self.formula_engine.answer_calculation(
                query=context.query,
                parameters=context.parameters,
                entities=context.entities,
            )

            step.result = self._normalize_calculation_result(result)
            step.confidence = step.result["confidence"]

        except (
            ArithmeticError,
            AttributeError,
            KeyError,
            TypeError,
            ValueError,
        ) as exc:
            logger.exception("Ошибка инженерного расчёта")
            step.result = {
                "type": "calculation",
                "answer": f"❌ Ошибка расчёта: {exc}",
                "sources": [],
                "tables": [],
                "formulas": [],
                "confidence": 0.0,
                "needs_clarification": True,
                "questions": ["Проверьте введённые параметры."],
            }
            step.confidence = 0.0

        return step

    @staticmethod
    def _normalize_calculation_result(
        result: dict[str, Any],
    ) -> dict[str, Any]:
        return {
            "type": "calculation",
            "answer": result.get("answer", "Расчёт не выполнен."),
            "sources": result.get("sources", []),
            "tables": result.get("tables", []),
            "formulas": result.get("formulas", []),
            "formula": result.get("formula"),
            "parameters": result.get("params", {}),
            "result": result.get("result"),
            "reasoning": result.get("reasoning", ""),
            "grounded": bool(result.get("grounded", False)),
            "confidence": result.get("confidence", 0.0),
            "needs_clarification": result.get(
                "needs_clarification",
                False,
            ),
            "questions": result.get("questions", []),
        }

    @staticmethod
    def _unique_keep_order(items: list[str]) -> list[str]:
        seen: set[str] = set()
        result: list[str] = []

        for item in items:
            value = str(item).strip()
            key = value.lower()

            if value and key not in seen:
                seen.add(key)
                result.append(value)

        return result

    def _expand_query(
        self,
        query: str,
        query_type: QueryType,
        entities: dict[str, Any],
        keywords: list[str],
    ) -> list[str]:
        """Строит варианты запроса для retrieval."""
        variants = [query]

        document_codes = list(
            entities.get("document_codes")
            or entities.get("documents")
            or []
        )
        section_refs = list(entities.get("section_refs") or [])
        domain_terms = list(
            entities.get("domain_terms") or keywords[:8]
        )
        city = entities.get("city")

        if document_codes:
            variants.append(
                " ".join(document_codes[:2] + domain_terms[:6]).strip()
            )

        if section_refs:
            variants.append(
                " ".join(section_refs[:2] + domain_terms[:6]).strip()
            )

        if domain_terms:
            variants.append(" ".join(domain_terms[:10]).strip())

        if city:
            variants.extend([
                f"{city} климат температура отопительный период",
                f"{city} климатические параметры t от z от",
            ])

        if query_type == QueryType.REGULATORY:
            lower_query = query.lower()

            for trigger, expansions in self.REGULATORY_QUERY_EXPANSIONS.items():
                if trigger in lower_query:
                    variants.extend(expansions)

            variants.append(
                " ".join(
                    document_codes[:2]
                    + domain_terms[:8]
                    + ["требования", "следует", "не допускается"]
                ).strip()
            )

        memory_boosts = self.memory.get_boosts(
            query,
            query_type.value,
        )
        memory_terms = [str(term) for term in memory_boosts.get("terms", [])]

        if memory_terms:
            variants.append(
                " ".join(domain_terms[:6] + memory_terms[:4]).strip()
            )

        return self._unique_keep_order(
            [variant for variant in variants if variant.strip()]
        )

    @staticmethod
    def _rerank_chunks(
        chunks: list[dict[str, Any]],
        query_type: QueryType,
        entities: dict[str, Any],
        memory_boosts: dict[str, list[str]],
    ) -> list[dict[str, Any]]:
        """Повторно ранжирует найденные фрагменты."""
        preferred_sources = [
            source.lower()
            for source in memory_boosts.get("sources", [])
        ]
        document_codes = [
            code.lower()
            for code in entities.get("document_codes", [])
        ]
        section_refs = [
            ref.lower()
            for ref in entities.get("section_refs", [])
        ]
        domain_terms = [
            term.lower()
            for term in entities.get("domain_terms", [])[:12]
        ]
        city = str(entities.get("city", "")).lower().strip()

        reranked: list[dict[str, Any]] = []

        for chunk in chunks:
            doc_name = str(chunk.get("doc_name", ""))
            text = str(chunk.get("text", ""))

            lower_doc_name = doc_name.lower()
            lower_text = text.lower()

            score = float(chunk.get("score", 0.0) or 0.0)

            if any(source in lower_doc_name for source in preferred_sources):
                score += 0.20

            if any(
                code in lower_doc_name or code in lower_text
                for code in document_codes
            ):
                score += 0.45

            if any(ref in lower_text for ref in section_refs):
                score += 0.30

            if city and re.search(rf"\b{re.escape(city)}\b", lower_text):
                score += 0.25

            term_hits = sum(
                1 for term in domain_terms
                if term and term in lower_text
            )
            score += min(0.35, term_hits * 0.04)

            if query_type == QueryType.REGULATORY:
                marker_hits = sum(
                    1
                    for marker in AgentLoop.REGULATORY_MARKERS
                    if marker in lower_text
                )
                score += min(0.50, marker_hits * 0.08)

            reranked.append({
                **chunk,
                "score": score,
            })

        reranked.sort(
            key=lambda item: item.get("score", 0.0),
            reverse=True,
        )
        return reranked

    def _search_chunks(
        self,
        query: str,
        query_type: QueryType,
        entities: dict[str, Any] | None = None,
        keywords: list[str] | None = None,
    ) -> ReasoningStep:
        """Ищет, дедуплицирует и ранжирует фрагменты индекса."""
        step = ReasoningStep(
            step_id=2,
            description="Поиск и ранжирование фрагментов документов",
        )

        entities = dict(entities or {})
        keywords = list(keywords or [])

        try:
            if (
                self.qa_system is None
                or not getattr(self.qa_system, "is_ready", False)
            ):
                step.result = {
                    "chunks": [],
                    "count": 0,
                    "expanded_queries": [],
                }
                step.confidence = 0.2
                return step

            memory_boosts = self.memory.get_boosts(
                query,
                query_type.value,
            )

            expanded_queries = self._expand_query(
                query=query,
                query_type=query_type,
                entities=entities,
                keywords=keywords,
            )

            if query_type == QueryType.REGULATORY:
                top_k = 16
            elif query_type == QueryType.CALCULATION:
                top_k = 10
            else:
                top_k = 12

            collected: list[dict[str, Any]] = []
            seen: set[tuple[str, str]] = set()

            for search_query in expanded_queries[:6]:
                found = self.qa_system.search(
                    search_query,
                    top_k=top_k,
                )

                for raw_chunk in found or []:
                    chunk = self._search_result_to_dict(raw_chunk)
                    doc_name = str(chunk.get("doc_name", ""))
                    text = str(chunk.get("text", ""))
                    fingerprint = (
                        doc_name.lower().strip(),
                        re.sub(r"\s+", " ", text[:350]).lower(),
                    )

                    if not text.strip() or fingerprint in seen:
                        continue

                    seen.add(fingerprint)
                    collected.append(chunk)

            reranked = self._rerank_chunks(
                chunks=collected,
                query_type=query_type,
                entities=entities,
                memory_boosts=memory_boosts,
            )[:top_k]

            enriched: list[dict[str, Any]] = []

            for chunk in reranked:
                text = str(chunk.get("text", ""))
                doc_name = str(chunk.get("doc_name", ""))

                tables = extract_tables(text, doc_name=doc_name)
                formulas = self._extract_formulas(text)

                enriched.append({
                    **chunk,
                    "tables": tables_to_dicts(tables),
                    "formulas": formulas,
                })

            step.result = {
                "chunks": enriched,
                "count": len(enriched),
                "expanded_queries": expanded_queries,
                "memory_boosts": memory_boosts,
            }
            step.confidence = 0.85 if enriched else 0.3

        except (
            AttributeError,
            KeyError,
            TypeError,
            ValueError,
        ) as exc:
            logger.exception("Ошибка поиска фрагментов для запроса %r", query[:200])
            step.result = {
                "chunks": [],
                "count": 0,
                "expanded_queries": [],
                "error": str(exc),
            }
            step.confidence = 0.0
            step.description += f": {exc}"

        return step

    @staticmethod
    def _search_result_to_dict(value: Any) -> dict[str, Any]:
        """Принимает старый dict и текущий SearchResult с атрибутами."""
        if isinstance(value, Mapping):
            return dict(value)
        converter = getattr(value, "to_dict", None)
        if callable(converter):
            converted = converter()
            if isinstance(converted, Mapping):
                return dict(converted)
        if hasattr(value, "text"):
            return {
                "text": str(value.text),
                "doc_name": str(getattr(value, "doc_name", "")),
                "chunk_id": getattr(value, "chunk_id", 0),
                "score": float(getattr(value, "score", 0.0) or 0.0),
                "metadata": dict(getattr(value, "metadata", {}) or {}),
            }
        raise TypeError(f"Неподдерживаемый результат поиска: {type(value).__name__}")

    @staticmethod
    def _extract_formulas(text: str) -> list[dict[str, Any]]:
        """Извлекает короткие формулы из найденного текста."""
        raw_formulas: list[str] = []

        equation_pattern = (
            r"(?<!\w)"
            r"([A-Za-zА-Яа-яΔδλ]\w*\s*="
            r"\s*[^\n.;]{3,180})"
        )
        raw_formulas.extend(re.findall(equation_pattern, text))

        result: list[dict[str, Any]] = []
        seen: set[str] = set()

        for raw in raw_formulas:
            normalized = re.sub(r"\s+", " ", raw).strip()

            if normalized in seen:
                continue

            seen.add(normalized)

            variables = re.findall(
                r"[A-Za-zА-Яа-яΔδλ]\w*",
                normalized,
            )

            result.append({
                "raw": normalized,
                "variables": sorted(set(variables)),
            })

        return result[:5]

    @staticmethod
    def _build_context(
        query: str,
        query_type: QueryType,
        keywords: list[str],
        entities: dict[str, Any],
        parameters: dict[str, Any],
        chunks: list[dict[str, Any]],
    ) -> ReasoningStep:
        """
        Создаёт контекст, не извлекая числа повторно.

        Параметры остаются исключительно теми, которые вернул QueryParser.
        """
        step = ReasoningStep(
            step_id=3,
            description="Формирование контекста без повторного парсинга параметров",
        )

        try:
            high_score = [
                chunk for chunk in chunks
                if float(chunk.get("score", 0.0) or 0.0) >= 0.5
            ]

            confidence = (
                len(high_score) / len(chunks)
                if chunks
                else 0.2
            )

            context = ContextInfo(
                query=query,
                query_type=query_type,
                keywords=keywords,
                entities=entities,
                parameters=parameters,
                chunks=chunks,
                confidence=max(0.2, confidence),
            )

            step.result = context
            step.confidence = context.confidence

        except (AttributeError, TypeError, ValueError) as exc:
            step.result = None
            step.confidence = 0.0
            step.description += f": {exc}"

        return step

    def _handle_definition(
        self,
        context: ContextInfo,
    ) -> ReasoningStep:
        term = self._extract_definition_term(context.query)

        if not term:
            step = ReasoningStep(step_id=4, description="Уточнение термина")
            step.result = {
                "answer": "Уточните термин, для которого нужно дать определение.",
                "sources": [],
                "tables": [],
                "formulas": [],
                "confidence": 0.2,
                "needs_clarification": True,
                "questions": ["Какой термин нужно определить?"], "grounded": True,
            }
            step.confidence = 0.2
            return step
        return self._handle_grounded(context, f"Определение термина «{term}» по базе")


    @staticmethod
    def _extract_definition_term(query: str) -> str:
        value = query.strip().lower()

        prefixes = (
            "что такое ",
            "что значит ",
            "что означает ",
            "что это ",
            "дай определение ",
            "дайте определение ",
            "определение ",
            "определи ",
            "термин ",
            "понятие ",
            "расшифруй ",
            "расшифровка ",
            "аббревиатура ",
        )

        for prefix in prefixes:
            if value.startswith(prefix):
                value = value[len(prefix):]
                break

        return value.strip(" ?!.,:;\"'«»()[]")

    def _handle_regulatory(
        self,
        context: ContextInfo,
    ) -> ReasoningStep:
        """Собирает нормы по широкому набору нормативных формулировок."""
        step = ReasoningStep(
            step_id=4,
            description="Поиск нормативных требований",
        )

        candidates: list[tuple[float, dict[str, Any]]] = []

        for chunk in context.chunks:
            text = str(chunk.get("text", "")).strip()
            lower_text = text.lower()

            if not text:
                continue

            marker_hits = sum(
                1
                for marker in self.REGULATORY_MARKERS
                if marker in lower_text
            )

            score = float(chunk.get("score", 0.0) or 0.0)
            score += min(0.6, marker_hits * 0.1)

            document_codes = context.entities.get(
                "document_codes",
                [],
            )
            if any(code.lower() in lower_text for code in document_codes):
                score += 0.3

            candidates.append((score, chunk))

        candidates.sort(key=lambda item: item[0], reverse=True)

        if not candidates:
            step.result = {
                "answer": (
                    "⚠️ В текущем индексе не найдены релевантные нормативные "
                    "фрагменты. Проверьте, что нужный СП или ГОСТ загружен и "
                    "проиндексирован."
                ),
                "sources": [],
                "tables": [],
                "formulas": [],
                "confidence": 0.15,
                "needs_clarification": True,
                "questions": [
                    "Укажите номер документа, раздел или тему требования.",
                ],
            }
            step.confidence = 0.15
            return step

        selected_context = ContextInfo(
            query=context.query,
            query_type=context.query_type,
            keywords=context.keywords,
            entities=context.entities,
            parameters=context.parameters,
            chunks=[chunk for _, chunk in candidates[:4]],
            confidence=context.confidence,
        )
        return self._handle_grounded(
            selected_context,
            "Ответ по найденным нормативным фрагментам",
        )

    def _handle_search(
        self,
        context: ContextInfo,
    ) -> ReasoningStep:
        return self._handle_grounded(context, "Ответ по найденным документам")

    def _search_answer(
        self,
        context: ContextInfo,
        intro: str | None = None,
    ) -> dict[str, Any]:
        if not context.chunks:
            return {
                "answer": (
                    "⚠️ В проиндексированных документах ничего не найдено. "
                    "Проверьте наличие документа, тему запроса или формулировку."
                ),
                "sources": [],
                "tables": [],
                "formulas": [],
                "confidence": 0.15,
                "needs_clarification": True,
                "questions": ["Уточните документ, раздел или ключевой термин."],
            }

        result = self._build_evidence_answer(
            context.chunks[:4],
            title=intro or "Найденная информация",
            max_chars=750,
        )

        return result

    @staticmethod
    def _handle_comparison(
        context: ContextInfo,
    ) -> ReasoningStep:
        step = ReasoningStep(
            step_id=4,
            description="Подготовка сравнения",
        )

        query = context.query.lower()
        parts = re.split(r"\s+(?:и|vs|против)\s+", query)
        items = [part.strip() for part in parts if len(part.strip()) > 2]

        if len(items) < 2:
            step.result = {
                "answer": (
                    "⚠️ Не удалось определить объекты сравнения. "
                    "Напишите, например: «сравни минвату и пенополистирол»."
                ),
                "sources": [],
                "tables": [],
                "formulas": [],
                "confidence": 0.2,
                "needs_clarification": True,
                "questions": ["Что именно нужно сравнить?"],
            }
            step.confidence = 0.2
            return step

        rows: list[str] = []
        sources: list[dict[str, str]] = []

        for item in items[:3]:
            match = next(
                (
                    chunk for chunk in context.chunks
                    if item in str(chunk.get("text", "")).lower()
                ),
                None,
            )

            if match is None:
                rows.append(f"- **{item}**: данных в найденных фрагментах нет.")
                continue

            text = re.sub(
                r"\s+",
                " ",
                str(match.get("text", "")).strip(),
            )[:350]
            source = str(match.get("doc_name", ""))

            rows.append(f"- **{item}**: {text}")

            if source:
                sources.append({"doc_name": source})

        step.result = {
            "answer": "### Сравнение\n\n" + "\n\n".join(rows),
            "sources": AgentLoop._unique_sources(sources),
            "tables": [],
            "formulas": [],
            "confidence": 0.75,
            "needs_clarification": False,
            "questions": [],
        }
        step.confidence = 0.75

        return step

    @staticmethod
    def _build_evidence_answer(
        chunks: list[dict[str, Any]],
        title: str,
        max_chars: int,
    ) -> dict[str, Any]:
        parts: list[str] = []
        sources: list[dict[str, str]] = []
        tables: list[dict[str, Any]] = []
        formulas: list[dict[str, Any]] = []

        seen_text: set[str] = set()

        for chunk in chunks:
            text = re.sub(
                r"\s+",
                " ",
                str(chunk.get("text", "")).strip(),
            )

            if not text:
                continue

            fingerprint = text[:250].lower()
            if fingerprint in seen_text:
                continue

            seen_text.add(fingerprint)
            parts.append(text[:max_chars])

            doc_name = str(chunk.get("doc_name", "")).strip()
            if doc_name:
                sources.append({"doc_name": doc_name})

            tables.extend(chunk.get("tables", []))
            formulas.extend(chunk.get("formulas", []))

        if not parts:
            return {
                "answer": "⚠️ Найденные фрагменты не содержат текста для ответа.",
                "sources": [],
                "tables": [],
                "formulas": [],
                "confidence": 0.15,
                "needs_clarification": True,
                "questions": ["Уточните запрос."],
            }

        return {
            "answer": f"### {title}\n\n" + "\n\n".join(parts),
            "sources": AgentLoop._unique_sources(sources),
            "tables": AgentLoop._unique_tables(tables),
            "formulas": AgentLoop._unique_formulas(formulas),
            "confidence": min(0.9, 0.5 + len(parts) * 0.1),
            "needs_clarification": False,
            "questions": [],
        }

    @staticmethod
    def _unique_sources(
        sources: list[dict[str, str]],
    ) -> list[dict[str, str]]:
        seen: set[str] = set()
        result: list[dict[str, str]] = []

        for source in sources:
            name = str(source.get("doc_name") or "").strip()
            key = name.lower()

            if name and key not in seen:
                seen.add(key)
                result.append({"doc_name": name})

        return result

    @staticmethod
    def _unique_tables(
        tables: list[dict[str, Any]],
    ) -> list[dict[str, Any]]:
        seen: set[str] = set()
        result: list[dict[str, Any]] = []

        for table in tables:
            content = str(
                table.get("raw_text")
                or table.get("content")
                or ""
            ).strip()

            fingerprint = re.sub(
                r"\s+",
                " ",
                content[:300],
            ).lower()

            if not fingerprint or fingerprint in seen:
                continue

            seen.add(fingerprint)
            result.append(table)

        return result[:10]

    @staticmethod
    def _unique_formulas(
        formulas: list[dict[str, Any]],
    ) -> list[dict[str, Any]]:
        seen: set[str] = set()
        result: list[dict[str, Any]] = []

        for formula in formulas:
            raw = str(formula.get("raw", "")).strip()
            key = re.sub(r"\s+", " ", raw).lower()

            if raw and key not in seen:
                seen.add(key)
                result.append(formula)

        return result[:5]

    def _finalize_response(
        self,
        result: dict[str, Any],
        query_type: QueryType,
        keywords: list[str],
        original_query: str,
    ) -> dict[str, Any]:
        """Строит единый ответ и сохраняет удачный retrieval в память."""
        response = {
            "answer": result.get("answer", ""),
            "sources": result.get("sources", []),
            "tables": result.get("tables", []),
            "formulas": result.get("formulas", []),
            "formula": result.get("formula"),
            "params": result.get("parameters", result.get("params", {})),
            "result": result.get("result"),
            "reasoning": result.get("reasoning", ""),
            "provider": result.get("provider", "none"),
            "used_llm": bool(result.get("used_llm", False)),
            "grounded": bool(result.get("grounded", False)),
            "confidence": result.get("confidence", 0.0),
            "needs_clarification": result.get(
                "needs_clarification",
                False,
            ),
            "questions": result.get("questions", []),
            "query_type": query_type.value,
        }

        self._save_success_to_memory(
            original_query=original_query,
            query_type=query_type,
            keywords=keywords,
            response=response,
        )

        return response

    def _save_success_to_memory(
        self,
        original_query: str,
        query_type: QueryType,
        keywords: list[str],
        response: dict[str, Any],
    ) -> None:
        """
        В память отправляются только ответы с источниками и без
        необходимости уточнения; иначе память будет усиливать ошибки.
        """
        if response.get("needs_clarification"):
            return

        if response.get("confidence", 0.0) < 0.65:
            return

        source_names: list[str] = []

        for source in response.get("sources", []):
            if isinstance(source, dict):
                name = source.get("doc_name") or source.get("source")
            else:
                name = str(source)

            if name:
                source_names.append(str(name))

        source_names = self._unique_keep_order(source_names)

        if source_names:
            self.memory.save_success(
                query=original_query,
                query_type=query_type.value,
                keywords=keywords,
                sources=source_names,
            )

    @staticmethod
    def _create_error_response(
        message: str,
        step_id: int,
    ) -> dict[str, Any]:
        return {
            "answer": f"❌ {message}",
            "sources": [],
            "tables": [],
            "formulas": [],
            "confidence": 0.0,
            "needs_clarification": True,
            "questions": ["Уточните запрос."],
            "query_type": "error",
            "steps": step_id,
        }
def _run_self_tests() -> None:
    """Проверяет общий RAG-путь и совместимость с объектами SearchResult."""
    import asyncio
    from pathlib import Path
    from tempfile import TemporaryDirectory

    class _TestQA:
        is_ready = True

        @staticmethod
        def search(query: str, top_k: int = 5) -> list[Any]:
            from types import SimpleNamespace
            assert query and top_k > 0
            return [SimpleNamespace(
                doc_name="Тестовый СП", chunk_id=3,
                text="Вентиляция должна обеспечивать требуемый воздухообмен.",
                score=0.9, metadata={"page": 7},
            )]

        @staticmethod
        def answer_from_results(question: str, results: list[dict[str, Any]]) -> dict[str, Any]:
            assert question
            assert results and results[0]["doc_name"] == "Тестовый СП"
            return {
                "answer": "### Краткий ответ\n\nТребование найдено. [Источник 1]",
                "sources": [{"reference_id": 1, "doc_name": "Тестовый СП", "page": 7}],
                "tables": [], "formulas": [], "confidence": 0.9,
                "needs_clarification": False, "questions": [], "grounded": True,
            }

    class _TestFormula:
        @staticmethod
        def can_calculate_directly(query: str, parameters: dict[str, Any]) -> bool:
            assert query and isinstance(parameters, dict)
            return False

    with TemporaryDirectory() as directory:
        loop = AgentLoop(_TestQA(), _TestFormula())
        loop.memory = RetrievalMemory(Path(directory) / "memory.json")
        for question, expected_intent in (
            ("Какие требования к вентиляции?", "regulatory"),
            ("Что такое вентиляция?", "definition"),
            ("Сравни вентиляцию и отопление", "comparison"),
        ):
            test_response = asyncio.run(loop.run(question))
            assert test_response["sources"][0]["doc_name"] == "Тестовый СП"
            assert test_response["query_type"] == expected_intent
            assert test_response["grounded"]


if __name__ == "__main__":
    _run_self_tests()

# ИСПРАВЛЕНО: _handle_grounded; адаптер SearchResult; возврат определения; поиск/логирование; сравнение через QA; тесты.